Skip to content

Commit ea6af59

Browse files
SunkenInTimeclaudejuliusmarminge
authored
feat(mobile): redesign the Android agent activity card (pingdotgg#11645)
Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 3be02ae commit ea6af59

13 files changed

Lines changed: 570 additions & 62 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
package expo.modules.t3agentnotifications
2+
3+
import android.content.Context
4+
import android.graphics.Typeface
5+
import android.text.SpannableStringBuilder
6+
import android.text.Spanned
7+
import android.text.style.ForegroundColorSpan
8+
import android.text.style.StyleSpan
9+
import androidx.core.app.NotificationCompat
10+
import androidx.core.content.ContextCompat
11+
12+
internal data class ActivityRow(val status: String, val title: String, val project: String)
13+
14+
/**
15+
* One entry per relay phase. The status label matches the relay's row wording and the
16+
* tint matches the web sidebar pills and the iOS Live Activity so a thread reads the
17+
* same on every surface. The icon is always the T3 mark; the chip verb carries the state.
18+
*/
19+
internal enum class ActivityPhase(
20+
val status: String,
21+
val heading: String,
22+
val chip: String,
23+
val action: String,
24+
val color: Int
25+
) {
26+
STARTING("Connecting", "Starting", "Working", "Open", R.color.agent_activity_working),
27+
RUNNING("Working", "Working", "Working", "Open", R.color.agent_activity_working),
28+
APPROVAL(
29+
"Approval",
30+
"Approval needed",
31+
"Approve",
32+
"Approve",
33+
R.color.agent_activity_attention
34+
),
35+
INPUT(
36+
"Input",
37+
"Question for you",
38+
"Answer",
39+
"Answer",
40+
R.color.agent_activity_input
41+
),
42+
STALE(
43+
"Waiting",
44+
"Waiting for an update",
45+
"Waiting",
46+
"Open",
47+
R.color.agent_activity_waiting
48+
),
49+
COMPLETED(
50+
"Done",
51+
"Finished",
52+
"Done",
53+
"Open",
54+
R.color.agent_activity_done
55+
),
56+
FAILED(
57+
"Failed",
58+
"Failed",
59+
"Failed",
60+
"Open",
61+
R.color.agent_activity_failed
62+
);
63+
64+
val needsUser get() = this == APPROVAL || this == INPUT
65+
val finished get() = this == COMPLETED || this == FAILED
66+
67+
companion object {
68+
fun forStatus(status: String) = entries.firstOrNull { it.status == status }
69+
}
70+
}
71+
72+
/** The relay orders rows and their deep link together; never reorder them in the client. */
73+
internal fun activityRows(data: Map<String, String>) = (0..4).mapNotNull {
74+
val parts = data["activity_line_$it"]?.split('\t', limit = 3) ?: return@mapNotNull null
75+
if (parts.size != 3 || parts[1].isBlank()) {
76+
null
77+
} else {
78+
ActivityRow(parts[0].take(40), parts[1].take(120), parts[2].take(120))
79+
}
80+
}
81+
82+
internal fun activityPhase(data: Map<String, String>, rows: List<ActivityRow>): ActivityPhase? =
83+
when (data["activity_phase"]?.takeIf { it.isNotBlank() }) {
84+
"starting" -> ActivityPhase.STARTING
85+
"running" -> ActivityPhase.RUNNING
86+
"waiting_for_approval" -> ActivityPhase.APPROVAL
87+
"waiting_for_input" -> ActivityPhase.INPUT
88+
"stale" -> ActivityPhase.STALE
89+
"completed" -> ActivityPhase.COMPLETED
90+
"failed" -> ActivityPhase.FAILED
91+
else -> rows.firstOrNull()?.let { ActivityPhase.forStatus(it.status) }
92+
}
93+
94+
/**
95+
* Header carries the state, the title says what needs you (or which thread, when
96+
* there is only one), and the body lists every thread with its status in front.
97+
* System UI renders all of it, so the same builder serves the shade, the lock
98+
* screen and the status bar chip.
99+
*/
100+
internal class ActivityPresentation(data: Map<String, String>, private val active: Boolean) {
101+
private val rows = activityRows(data)
102+
private val hero = rows.firstOrNull()
103+
val phase = activityPhase(data, rows)
104+
private val activeCount = data["activity_active_count"]?.toIntOrNull()?.coerceAtLeast(0)
105+
?: rows.count { ActivityPhase.forStatus(it.status)?.finished != true }
106+
private val attentionCount = data["activity_attention_count"]?.toIntOrNull()?.coerceAtLeast(0)
107+
?: rows.count { ActivityPhase.forStatus(it.status)?.needsUser == true }
108+
private val failedCount = rows.count { it.status == ActivityPhase.FAILED.status }
109+
val threadCount =
110+
activeCount + rows.count { ActivityPhase.forStatus(it.status)?.finished == true }
111+
private val singleProject = rows.map { it.project }.distinct().size == 1
112+
private val legacyBody = (0..4).mapNotNull { data["activity_line_$it"]?.take(300) }
113+
.takeIf { it.isNotEmpty() }?.joinToString("\n")
114+
?: data["activity_body"].orEmpty().take(240)
115+
116+
val summary = when {
117+
hero == null -> data["activity_title"]?.takeIf { it.isNotBlank() }?.take(120)
118+
?: "Agent activity"
119+
rows.size == 1 -> hero.title
120+
attentionCount == 1 -> "1 needs you"
121+
attentionCount > 1 -> "$attentionCount need you"
122+
activeCount > 0 && failedCount > 0 -> "$failedCount failed"
123+
activeCount > 0 -> "$activeCount working"
124+
failedCount > 0 -> "Finished, $failedCount failed"
125+
else -> "All finished"
126+
}
127+
128+
val chip = when {
129+
!active -> null
130+
phase == null -> data["activity_chip"]?.takeIf { it.isNotBlank() }?.take(7) ?: "Active"
131+
phase == ActivityPhase.RUNNING && activeCount > 1 ->
132+
"${if (activeCount > 9) "9+" else activeCount} live"
133+
else -> phase.chip
134+
}
135+
136+
val action = if (active) phase?.action ?: "Open" else null
137+
138+
fun applyTo(builder: NotificationCompat.Builder, context: Context) {
139+
val tint = phase?.let { ContextCompat.getColor(context, it.color) }
140+
builder.setSmallIcon(R.drawable.agent_activity_mark)
141+
if (tint != null) builder.setColor(tint)
142+
// Tint the summary only when it names an outcome or a request; a plain
143+
// "3 working" stays neutral so the accent keeps meaning something.
144+
val tintedSummary = tint != null && rows.size > 1 && phase != ActivityPhase.RUNNING &&
145+
phase != ActivityPhase.STARTING
146+
builder.setContentTitle(if (tintedSummary) tinted(summary, tint!!) else summary)
147+
if (rows.size > 1) {
148+
builder.setSubText(
149+
listOfNotNull(
150+
hero!!.project.takeIf { singleProject && it.isNotBlank() },
151+
if (activeCount > 0) "$activeCount active" else "$threadCount threads"
152+
).joinToString(" · ")
153+
)
154+
}
155+
val body = body(context)
156+
// The collapsed card gets the priority row; the expanded card gets them all.
157+
val lineBreak = body.indexOf('\n')
158+
val firstLine = if (lineBreak >= 0) body.subSequence(0, lineBreak) else body
159+
builder.setContentText(firstLine).setStyle(NotificationCompat.BigTextStyle().bigText(body))
160+
// Thread update timestamps can change while an approval remains pending.
161+
// Leave the timer hidden until the payload has a stable phase-entry timestamp.
162+
builder.setShowWhen(false).setUsesChronometer(false)
163+
}
164+
165+
private fun body(context: Context): CharSequence = when {
166+
hero == null -> legacyBody
167+
// The title already names the thread; the body only needs its status and project.
168+
rows.size == 1 -> statusLine(context, hero.copy(title = hero.project), "")
169+
else -> SpannableStringBuilder().apply {
170+
rows.forEachIndexed { index, row ->
171+
if (index > 0) append("\n")
172+
append(statusLine(context, row, row.project.takeUnless { singleProject }.orEmpty()))
173+
}
174+
}
175+
}
176+
177+
private fun statusLine(context: Context, row: ActivityRow, trailing: String): CharSequence =
178+
SpannableStringBuilder().apply {
179+
val status = ActivityPhase.forStatus(row.status)
180+
val color = ContextCompat.getColor(context, status?.color ?: R.color.agent_activity_waiting)
181+
append(tinted(row.status, color, bold = true))
182+
append(" ").append(row.title)
183+
// Promoted cards drop text color, so the separator has to do the work of the dimming.
184+
if (trailing.isNotBlank()) {
185+
val start = length
186+
append(" · ").append(trailing)
187+
setSpan(
188+
ForegroundColorSpan(ContextCompat.getColor(context, R.color.agent_activity_waiting)),
189+
start,
190+
length,
191+
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
192+
)
193+
}
194+
}
195+
196+
private fun tinted(text: String, color: Int, bold: Boolean = false) =
197+
SpannableStringBuilder(text).apply {
198+
setSpan(ForegroundColorSpan(color), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
199+
if (bold) setSpan(StyleSpan(Typeface.BOLD), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
200+
}
201+
}

‎apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt‎

Lines changed: 14 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ import android.content.Intent
1111
import android.content.SharedPreferences
1212
import android.net.Uri
1313
import android.os.Build
14-
import android.text.TextPaint
15-
import android.text.TextUtils
1614
import androidx.core.app.NotificationCompat
1715
import androidx.core.app.NotificationManagerCompat
1816
import androidx.lifecycle.Lifecycle
@@ -197,34 +195,32 @@ object AgentNotifications {
197195
active: Boolean,
198196
remainingMs: Long
199197
) {
200-
val body = data["activity_body"].orEmpty().take(240)
201198
val dismissIntent = PendingIntent.getBroadcast(
202199
context,
203200
ACTIVITY_ID,
204201
Intent(context, AgentActivityDismissReceiver::class.java),
205202
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
206203
)
207-
val lines = (0..4).mapNotNull {
208-
data["activity_line_$it"]?.let { line -> activityLine(context, line) }
209-
}
210-
// BigTextStyle remains eligible for Android Live Update promotion.
211-
val style = NotificationCompat.BigTextStyle().bigText(
212-
if (lines.isEmpty()) body else lines.joinToString("\n")
213-
)
214-
val notification = base(context, ACTIVITY_CHANNEL)
215-
.setContentTitle(data["activity_title"].orEmpty().take(120))
216-
.setContentText(body)
217-
.setStyle(style)
204+
val presentation = ActivityPresentation(data, active)
205+
val openThread = contentIntent(context, scheme, data["activity_path"], ACTIVITY_ID)
206+
val builder = base(context, ACTIVITY_CHANNEL)
218207
.setOngoing(active).setOnlyAlertOnce(true).setSilent(true)
219208
.setTimeoutAfter(remainingMs)
220209
// Live Updates must remain uncolorized to qualify for promotion.
221210
.setColorized(false)
222211
.setRequestPromotedOngoing(active)
223-
.setContentIntent(contentIntent(context, scheme, data["activity_path"], ACTIVITY_ID))
212+
.setShortCriticalText(presentation.chip)
213+
.setContentIntent(openThread)
224214
.setDeleteIntent(dismissIntent)
225-
.addAction(0, "Dismiss", dismissIntent)
226-
.build()
227-
manager(context).notify(ACTIVITY_TAG, ACTIVITY_ID, notification)
215+
presentation.applyTo(builder, context)
216+
// A finished card is no longer ongoing, so it swipes away and a tap opens
217+
// the thread; buttons would only repeat that.
218+
val action = presentation.action
219+
if (action != null) {
220+
if (openThread != null) builder.addAction(0, action, openThread)
221+
builder.addAction(0, "Dismiss", dismissIntent)
222+
}
223+
manager(context).notify(ACTIVITY_TAG, ACTIVITY_ID, builder.build())
228224
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
229225
// Notification timeouts were added in API 26. One inexact alarm also
230226
// expires cards on Android 7, including when the app process has exited.
@@ -253,32 +249,6 @@ object AgentNotifications {
253249
}
254250
}
255251

256-
private fun activityLine(context: Context, value: String): String {
257-
val parts = value.split('\t', limit = 3)
258-
if (parts.size != 3) return value.take(300)
259-
val metrics = context.resources.displayMetrics
260-
val paint = TextPaint().apply { textSize = 14 * metrics.scaledDensity }
261-
val prefix = "${parts[0]}: "
262-
val separator = " · "
263-
// Reserve the system notification's icon and margins. Fit the two titles
264-
// independently so large fonts/long names never hide the project or status.
265-
// The shade uses a narrow column even when a headless service sees a
266-
// foldable's wider display metrics. Keep rows inside that column too.
267-
val width = (metrics.widthPixels - 152 * metrics.density)
268-
.coerceIn(120 * metrics.density, 280 * metrics.density)
269-
val available = (width - paint.measureText(prefix + separator)).coerceAtLeast(0f)
270-
val projectWidth = paint.measureText(parts[2]).coerceAtMost(available * 0.4f)
271-
val titleWidth = paint.measureText(parts[1]).coerceAtMost(available - projectWidth)
272-
val title = TextUtils.ellipsize(parts[1], paint, titleWidth, TextUtils.TruncateAt.END)
273-
val project = TextUtils.ellipsize(
274-
parts[2],
275-
paint,
276-
available - titleWidth,
277-
TextUtils.TruncateAt.END
278-
)
279-
return "$prefix$title$separator$project"
280-
}
281-
282252
private fun manager(context: Context) = context.getSystemService(NotificationManager::class.java)
283253

284254
private fun channels(context: Context) {

‎apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/T3AgentNotificationsModule.kt‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package expo.modules.t3agentnotifications
22

3+
import android.content.ActivityNotFoundException
4+
import android.content.Intent
5+
import android.os.Build
6+
import android.provider.Settings
37
import expo.modules.kotlin.modules.Module
48
import expo.modules.kotlin.modules.ModuleDefinition
59

@@ -21,5 +25,23 @@ class T3AgentNotificationsModule : Module() {
2125
Function("clear") {
2226
appContext.reactContext?.let { AgentNotifications.clear(it) }
2327
}
28+
29+
Function("openLiveUpdateSettings") {
30+
val context = appContext.reactContext
31+
if (context == null || Build.VERSION.SDK_INT < 36) {
32+
false
33+
} else {
34+
try {
35+
context.startActivity(
36+
Intent(Settings.ACTION_APP_NOTIFICATION_PROMOTION_SETTINGS)
37+
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
38+
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
39+
)
40+
true
41+
} catch (_: ActivityNotFoundException) {
42+
false
43+
}
44+
}
45+
}
2446
}
2547
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<!-- The T3 mark, full bleed, so it renders as large as other apps' status bar icons. -->
2+
<vector xmlns:android="http://schemas.android.com/apk/res/android"
3+
android:width="24dp" android:height="24dp"
4+
android:viewportWidth="120" android:viewportHeight="120">
5+
<group android:translateX="-2.5" android:translateY="-6">
6+
<path android:fillColor="#FFFFFFFF"
7+
android:pathData="M33.4509,93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253,93.96C82.832,93.96 78.9653,93.4533 75.1253,92.44C71.2853,91.3733 68.032,89.88 65.3653,87.96L70.4053,78.04C72.5386,79.5867 75.0186,80.8133 77.8453,81.72C80.672,82.6267 83.5253,83.08 86.4053,83.08C89.6586,83.08 92.2186,82.44 94.0853,81.16C95.952,79.88 96.8853,78.12 96.8853,75.88C96.8853,73.7467 96.0586,72.0667 94.4053,70.84C92.752,69.6133 90.0853,69 86.4053,69H80.4853V60.44L96.0853,42.76L97.5253,47.4H68.1653V37H107.365V45.4L91.8453,63.08L85.2853,59.32H89.0453C95.9253,59.32 101.125,60.8667 104.645,63.96C108.165,67.0533 109.925,71.0267 109.925,75.88C109.925,79.0267 109.099,81.9867 107.445,84.76C105.792,87.48 103.259,89.6933 99.8453,91.4C96.432,93.1067 92.0586,93.96 86.7253,93.96Z" />
8+
</group>
9+
</vector>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<!-- Dark shade uses the 300 stops, matching the iOS banner on its dark material. -->
2+
<resources>
3+
<color name="agent_activity_working">#7DD3FC</color>
4+
<color name="agent_activity_attention">#FCD34D</color>
5+
<color name="agent_activity_input">#A5B4FC</color>
6+
<color name="agent_activity_waiting">#94A3B8</color>
7+
<color name="agent_activity_done">#6EE7B7</color>
8+
<color name="agent_activity_failed">#FCA5A5</color>
9+
</resources>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<!-- Phase tints shared with the web sidebar pills and the iOS Live Activity (600 stops). -->
2+
<resources>
3+
<color name="agent_activity_working">#0284C7</color>
4+
<color name="agent_activity_attention">#D97706</color>
5+
<color name="agent_activity_input">#4F46E5</color>
6+
<color name="agent_activity_waiting">#64748B</color>
7+
<color name="agent_activity_done">#059669</color>
8+
<color name="agent_activity_failed">#DC2626</color>
9+
</resources>

0 commit comments

Comments
 (0)