Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentActivity.tsx

381 lines14.9 KB

1import { HStack, Image, Spacer, Text, VStack, ZStack } from "@expo/ui/swift-ui";
2import type { ComponentProps } from "react";
3import {
4 font,
5 foregroundStyle,
6 frame,
7 layoutPriority,
8 lineLimit,
9 padding,
10 resizable,
11 widgetURL,
12} from "@expo/ui/swift-ui/modifiers";
13import {
14 createLiveActivity,
15 type LiveActivityComponent,
16 type LiveActivityLayout,
17} from "expo-widgets";
18​
19type LiveActivityEnvironment = Parameters<LiveActivityComponent<AgentActivityProps>>[1];
20​
21export type AgentActivityPhase =
22 | "starting"
23 | "running"
24 | "waiting_for_approval"
25 | "waiting_for_input"
26 | "completed"
27 | "failed"
28 | "stale";
29​
30export interface AgentActivityRowProps {
31 readonly environmentId: string;
32 readonly threadId: string;
33 readonly projectTitle: string;
34 readonly threadTitle: string;
35 readonly modelTitle: string;
36 readonly phase: AgentActivityPhase;
37 readonly status: string;
38 readonly updatedAt: string;
39 readonly deepLink: string;
41​
42export interface AgentActivityProps {
43 readonly title: string;
44 readonly subtitle: string;
45 readonly activeCount: number;
46 readonly updatedAt: string;
47 readonly activities: ReadonlyArray<AgentActivityRowProps>;
49​
50// This function is serialized into the widget extension's JS bundle, so it
51// must stay self-contained: no references to module-scope helpers, only the
52// imported view/modifier factories.
53export function AgentActivity(
54 props: AgentActivityProps,
55 environment: LiveActivityEnvironment,
56): LiveActivityLayout {
57 "widget";
58​
59 // Use SwiftUI's semantic label colors rather than fixed hex keyed off the
60 // device color scheme. A Live Activity banner always renders over a dark
61 // system material regardless of the device's light/dark setting, so
62 // scheme-derived dark text read as unreadable dark-on-dark on the lock
63 // screen. Semantic colors adapt to whatever material the OS places them on:
64 // the dark LA banner and the (light or dark) home-screen widget alike.
65 const primaryForeground = "primary";
66 const secondaryForeground = "secondary";
67​
68 // Status tints mirror the web sidebar's pills
69 // (apps/web/src/components/Sidebar.logic.ts resolveThreadStatusPill): amber
70 // for approval, indigo for input, sky for working, emerald for completed.
71 // On iPhone the LA sits on a dark material, but macOS (iPhone Mirroring /
72 // Mac notification center) renders it on a light one — so pick the web
73 // palette's light (-600) or dark (-300) variant off the color scheme.
74 const isLightScheme = environment.colorScheme === "light";
75 const phaseTint = (phase: AgentActivityPhase | undefined): string => {
76 if (environment.isLuminanceReduced) {
77 return secondaryForeground;
78 }
79 switch (phase) {
80 case "waiting_for_approval":
81 return isLightScheme ? "#d97706" : "#fcd34d"; // amber-600 / amber-300
82 case "waiting_for_input":
83 return isLightScheme ? "#4f46e5" : "#a5b4fc"; // indigo-600 / indigo-300
84 case "failed":
85 return isLightScheme ? "#dc2626" : "#fca5a5"; // red-600 / red-300
86 case "completed":
87 return isLightScheme ? "#059669" : "#6ee7b7"; // emerald-600 / emerald-300
88 case "starting":
89 case "running":
90 default:
91 return isLightScheme ? "#0284c7" : "#7dd3fc"; // sky-600 / sky-300
92 }
93 };
94​
95 // Order attention-first so whatever needs the user floats to the top of every
96 // presentation, then failures, then in-flight work, then finished/stale.
97 const phasePriority = (phase: AgentActivityPhase): number => {
98 if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0;
99 if (phase === "failed") return 1;
100 if (phase === "running" || phase === "starting") return 2;
101 return 3;
102 };
103 const ordered = [...props.activities].sort(
104 (a, b) => phasePriority(a.phase) - phasePriority(b.phase),
105 );
106 const row0 = ordered[0];
107 const row1 = ordered[1];
108 const row2 = ordered[2];
109 const row3 = ordered[3];
110 const row4 = ordered[4];
111​
112 const attentionRows = props.activities.filter(
113 (row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input",
114 );
115 const attentionRow = attentionRows[0];
116 const failedRow = props.activities.find((row) => row.phase === "failed");
117 const heroRow = attentionRow ?? failedRow ?? row0;
118 const tint = phaseTint(heroRow?.phase);
119 // Headline count leans on the accent when a human is actually blocked.
120 const headerTint = attentionRow
121 ? phaseTint(attentionRow.phase)
122 : failedRow
123 ? phaseTint(failedRow.phase)
124 : tint;
125​
126 // With nothing active the aggregate only carries recently finished work, so
127 // "0 active agents" (and a lone "0" in the expanded island) read as broken.
128 // Lead with the outcome instead. The outcome is derived here from the rows
129 // rather than taken from the server subtitle (which keys off the newest
130 // terminal row): every presentation — header text, tint, count slots,
131 // minimal glyph — must agree, and a failure anywhere should dominate a
132 // newer success.
133 const allDone = props.activeCount === 0;
134 const doneLabel = failedRow ? "Failed" : "Done";
135 const outcomeLabel = failedRow ? "Agent work failed" : "Agent work completed";
136​
137 // Header copy: "5 active agents" + (", 1 needs attention"). The banner renders
138 // the two parts in-line so the attention half can carry the accent color;
139 // `summary` is the short form for tight spots (expanded center, watch card).
140 const agentWord = props.activeCount === 1 ? "agent" : "agents";
141 const agentsLabel = allDone ? outcomeLabel : `${props.activeCount} active ${agentWord}`;
142 const attentionSuffix =
143 attentionRows.length > 0
144 ? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention`
145 : "";
146 const activeLabel = allDone ? doneLabel : `${props.activeCount} active`;
147 const summary = attentionSuffix || activeLabel;
148​
149 // Any registered scheme variant routes back to this app; taps are delivered
150 // to the widget's containing app, so the prod scheme is safe for all builds.
151 const deepLinkRow = attentionRow ?? row0;
152 const deepLink =
153 deepLinkRow && deepLinkRow.deepLink.startsWith("/") && !deepLinkRow.deepLink.startsWith("//")
154 ? `t3code://${deepLinkRow.deepLink.slice(1)}`
155 : null;
156​
157 // A scannable status glyph per phase — reads faster than colored words and
158 // ties the compact / expanded / banner / watch presentations together.
159 type SFName = NonNullable<ComponentProps<typeof Image>["systemName"]>;
160 const phaseSymbol = (phase: AgentActivityPhase): SFName => {
161 switch (phase) {
162 case "waiting_for_approval":
163 return "exclamationmark.circle.fill";
164 case "waiting_for_input":
165 return "questionmark.circle.fill";
166 case "failed":
167 return "xmark.octagon.fill";
168 case "completed":
169 return "checkmark.circle.fill";
170 case "starting":
171 return "circle.dotted";
172 case "stale":
173 return "clock.arrow.circlepath";
174 case "running":
175 default:
176 return "arrow.triangle.2.circlepath";
177 }
178 };
179​
180 // SF Symbols, like the logo, ignore frame/foregroundStyle applied directly to
181 // the image; size + tint them through a container the resizable symbol fills.
182 const renderGlyph = (systemName: SFName, size: number, color: string) => (
183 <HStack modifiers={[frame({ width: size, height: size }), foregroundStyle(color)]}>
184 <Image systemName={systemName} modifiers={[resizable()]} />
185 </HStack>
186 );
187​
188 // Single-line row used by every presentation: glyph, title, inline project,
189 // status. The project and status carry layoutPriority(1) so when space runs
190 // out it's the title that truncates, never the (short) project name or the
191 // status label. Single-line keeps rows inside the expanded island's hard
192 // height budget (~160pt) and lets the banner fit more agents.
193 const renderCompactRow = (row: AgentActivityRowProps) => (
194 <HStack spacing={7} alignment="center">
195 <Text
196 modifiers={[
197 font({ weight: "semibold", size: 13 }),
198 foregroundStyle(primaryForeground),
199 lineLimit(1),
200 ]}
201 >
202 {row.threadTitle}
203 </Text>
204 {/* No layoutPriority and no frame on the project: two bare texts take
205 their ideal width when it fits and shrink proportionally only when it
206 doesn't — so short rows never truncate, and long title + long project
207 truncate together. (A maxWidth frame is greedy and reserved its full
208 width even for short names; layoutPriority let the project starve the
209 title.) */}
210 <Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}>
211 {row.projectTitle}
212 </Text>
213 <Spacer minLength={8} />
214 <Text
215 modifiers={[
216 font({ weight: "semibold", size: 11 }),
217 foregroundStyle(phaseTint(row.phase)),
218 layoutPriority(1),
219 ]}
220 >
221 {row.status}
222 </Text>
223 </HStack>
224 );
225​
226 // The branded T3 mark. `assetName` resolves the template image set bundled in
227 // the widget extension's asset catalog. Image views only honor `resizable`
228 // directly (frame/foregroundStyle are dropped), so we size it via a container
229 // frame the resizable image fills and tint it through the container's
230 // foreground style, which the template image inherits. The 3:2 frame matches
231 // the glyph's aspect ratio so it never distorts.
232 const renderLogo = (height: number, color: string) => (
233 <HStack modifiers={[frame({ width: height * 1.5, height }), foregroundStyle(color)]}>
234 <Image assetName="T3Mark" modifiers={[resizable()]} />
235 </HStack>
236 );
237​
238 return {
239 banner: (
240 <VStack
241 alignment="leading"
242 spacing={6}
243 modifiers={deepLink ? [padding({ all: 14 }), widgetURL(deepLink)] : [padding({ all: 14 })]}
244 >
245 {/* Logo pinned to the leading edge; the status texts centered across the
246 full width (ZStack so the logo doesn't skew the centering). No footer —
247 overflow beyond the visible rows is inferable from the count. */}
248 <ZStack>
249 <HStack spacing={0} alignment="center">
250 {renderLogo(13, primaryForeground)}
251 <Spacer minLength={0} />
252 </HStack>
253 <HStack spacing={6} alignment="center">
254 <Spacer minLength={0} />
255 <Text
256 modifiers={[
257 font({ weight: "semibold", size: 13 }),
258 // The all-done header carries the outcome tint (emerald /
259 // red) the way the Done/Failed status labels do.
260 foregroundStyle(allDone ? headerTint : primaryForeground),
261 lineLimit(1),
262 ]}
263 >
264 {agentsLabel}
265 </Text>
266 {attentionSuffix ? (
267 <Text modifiers={[font({ size: 13 }), foregroundStyle(secondaryForeground)]}>·</Text>
268 ) : null}
269 {attentionSuffix ? (
270 <Text
271 modifiers={[
272 font({ weight: "semibold", size: 13 }),
273 foregroundStyle(headerTint),
274 lineLimit(1),
275 ]}
276 >
277 {attentionSuffix}
278 </Text>
279 ) : null}
280 <Spacer minLength={0} />
281 </HStack>
282 </ZStack>
283 {row0 ? renderCompactRow(row0) : null}
284 {row1 ? renderCompactRow(row1) : null}
285 {row2 ? renderCompactRow(row2) : null}
286 {row3 ? renderCompactRow(row3) : null}
287 {row4 ? renderCompactRow(row4) : null}
288 </VStack>
289 ),
290 // Compact card for the watchOS Smart Stack + CarPlay (the `.small` family):
291 // brand + count, then the single most important agent with its status glyph.
292 bannerSmall: (
293 <VStack alignment="leading" spacing={5} modifiers={[padding({ all: 10 })]}>
294 <HStack spacing={7} alignment="center">
295 {renderLogo(14, primaryForeground)}
296 <Text
297 modifiers={[
298 font({ weight: "bold", size: 13 }),
299 foregroundStyle(headerTint),
300 lineLimit(1),
301 ]}
302 >
303 {attentionRows.length > 0 ? summary : activeLabel}
304 </Text>
305 <Spacer minLength={6} />
306 </HStack>
307 {row0 ? (
308 <HStack spacing={7} alignment="center">
309 <Text
310 modifiers={[
311 font({ weight: "semibold", size: 12 }),
312 foregroundStyle(primaryForeground),
313 lineLimit(1),
314 ]}
315 >
316 {row0.threadTitle}
317 </Text>
318 <Spacer minLength={6} />
319 <Text modifiers={[font({ size: 11 }), foregroundStyle(phaseTint(row0.phase))]}>
320 {row0.status}
321 </Text>
322 </HStack>
323 ) : null}
324 </VStack>
325 ),
326 compactLeading: renderLogo(14, tint),
327 compactTrailing: (
328 <Text modifiers={[font({ weight: "semibold", size: 11 }), foregroundStyle(tint)]}>
329 {attentionRow
330 ? attentionRow.phase === "waiting_for_approval"
331 ? "Approval"
332 : "Input"
333 : activeLabel}
334 </Text>
335 ),
336 // The shared/minimal form is a ~22pt circle — a single signal reads there,
337 // the wordmark does not. Show the blocking/outcome phase glyph, else the
338 // mark (all-done shows the hero row's checkmark/cross).
339 minimal:
340 (attentionRow || failedRow || allDone) && heroRow
341 ? renderGlyph(phaseSymbol(heroRow.phase), 13, phaseTint(heroRow.phase))
342 : renderLogo(11, tint),
343 expandedLeading: (
344 <HStack spacing={5} alignment="center" modifiers={[padding({ leading: 4, vertical: 4 })]}>
345 {renderLogo(15, tint)}
346 <Text modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(tint)]}>
347 {allDone ? doneLabel : `${props.activeCount}`}
348 </Text>
349 </HStack>
350 ),
351 // No center content: the phase glyphs + statuses in expandedBottom already
352 // carry the attention signal, and the expanded island's height budget is
353 // tight enough that a summary line there pushed the third row off.
354 expandedCenter: null,
355 // No trailing content: a timestamp is glanceable-lock-screen info, not
356 // useful in a view the user is actively holding open — and the trailing
357 // region hugs the island's corner radius, which clipped it anyway.
358 expandedTrailing: null,
359 expandedBottom: (
360 // Vertical padding only: the expanded region provides its own horizontal
361 // content margins, so `all` padding double-indented the rows.
362 // Horizontal padding keeps both edges clear of the island's corner
363 // curvature (right edge clipped status labels; titles hugged the left).
364 <VStack
365 alignment="leading"
366 spacing={5}
367 modifiers={
368 deepLink
369 ? [padding({ vertical: 2, horizontal: 8 }), widgetURL(deepLink)]
370 : [padding({ vertical: 2, horizontal: 8 })]
371 }
372 >
373 {row0 ? renderCompactRow(row0) : null}
374 {row1 ? renderCompactRow(row1) : null}
375 {row2 ? renderCompactRow(row2) : null}
376 </VStack>
377 ),
378 };
380​
381export default createLiveActivity<AgentActivityProps>("AgentActivity", AgentActivity);