diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 94315c9bb153f..b7b3797e38c75 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -2084,6 +2084,7 @@ function renderFeedEntry( toolSurface={entry.toolSurface} toolIcon={entry.toolIcon} summaryToolIcon={entry.summaryToolIcon} + notificationIcon={entry.notificationIcon} hasFailure={entry.hasFailure} shimmer={entry.shimmer} thought={entry.thought} diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 33b8613d99722..08ac9fbaa0386 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1343,6 +1343,7 @@ export function ThreadWorkGroupToggle(props: { readonly summary: string; readonly summaryKind: ToolGroupSummaryKind; readonly summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request" | "brain"; + readonly notificationIcon?: ThreadFeedActivity["icon"] | undefined; readonly themeAppearance: "light" | "dark"; readonly toolSurface?: import("@t3tools/contracts").ToolActivitySurface; readonly toolIcon?: ToolActivityIcon; @@ -1354,14 +1355,18 @@ export function ThreadWorkGroupToggle(props: { }) { const gt = useGT(); const statusLabel = props.hasFailure - ? gt("{preview}, tool call failed", { preview: props.summary }) + ? props.notificationIcon + ? gt("{preview}, notification failed", { preview: props.summary }) + : gt("{preview}, tool call failed", { preview: props.summary }) : props.summary; const accessibilityLabel = props.thought ? `${props.thought} ${statusLabel}` : statusLabel; const icon = props.summaryToolIcon ?? - (props.toolSurface - ? workRowSymbolName(props.toolSurface) - : toolGroupSummarySymbolName(props.summaryKind)); + (props.notificationIcon + ? workRowSymbolName(props.notificationIcon) + : props.toolSurface + ? workRowSymbolName(props.toolSurface) + : toolGroupSummarySymbolName(props.summaryKind)); return ( @@ -1391,15 +1396,25 @@ export function ThreadWorkGroupToggle(props: { accessibilityState={{ expanded: props.expanded }} accessibilityLabel={accessibilityLabel} accessibilityHint={ - props.expanded - ? gt( - "{count, plural, one {Double tap to hide {count} tool call.} other {Double tap to hide {count} tool calls.}}", - { count: props.hiddenCount }, - ) - : gt( - "{count, plural, one {Double tap to show {count} tool call.} other {Double tap to show {count} tool calls.}}", - { count: props.hiddenCount }, - ) + props.notificationIcon + ? props.expanded + ? gt( + "{count, plural, one {Double tap to hide {count} notification.} other {Double tap to hide {count} notifications.}}", + { count: props.hiddenCount }, + ) + : gt( + "{count, plural, one {Double tap to show {count} notification.} other {Double tap to show {count} notifications.}}", + { count: props.hiddenCount }, + ) + : props.expanded + ? gt( + "{count, plural, one {Double tap to hide {count} tool call.} other {Double tap to hide {count} tool calls.}}", + { count: props.hiddenCount }, + ) + : gt( + "{count, plural, one {Double tap to show {count} tool call.} other {Double tap to show {count} tool calls.}}", + { count: props.hiddenCount }, + ) } onPress={() => { void Haptics.selectionAsync(); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c9d43d96b3eb8..4b922962025cc 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4651,6 +4651,9 @@ "fd0d04d5a6627f70": "Öffnet den Thread dieses Agenten. Lange drücken zum Kopieren.", "7ba47e54094ba298": "Doppeltippen, um alle Details auszublenden. Lange drücken zum Kopieren.", "1862ffb47bf6736c": "Doppeltippen, um alle Details anzuzeigen. Lange drücken zum Kopieren.", + "16179c449afdc170": "{preview}, Benachrichtigung fehlgeschlagen", + "ed1e51a988f1b585": "{count, plural, one {Doppeltippen, um {count} Benachrichtigung auszublenden.} other {Doppeltippen, um {count} Benachrichtigungen auszublenden.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Doppeltippen, um {count} Benachrichtigung anzuzeigen.} other {Doppeltippen, um {count} Benachrichtigungen anzuzeigen.}}", "b2bb42d5ad881fd8": "{count, plural, one {Doppeltippen, um {count} Tool-Aufruf auszublenden.} other {Doppeltippen, um {count} Tool-Aufrufe auszublenden.}}", "f2338bdac15becc2": "{count, plural, one {Doppeltippen, um {count} Tool-Aufruf anzuzeigen.} other {Doppeltippen, um {count} Tool-Aufrufe anzuzeigen.}}", "e7588632064e0364": "Kopiert", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 7a89a1cf37c22..8e30e3ba5247e 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4652,6 +4652,9 @@ "fd0d04d5a6627f70": "Opens this agent's thread. Long press to copy.", "7ba47e54094ba298": "Double tap to hide full details. Long press to copy.", "1862ffb47bf6736c": "Double tap to show full details. Long press to copy.", + "16179c449afdc170": "{preview}, notification failed", + "ed1e51a988f1b585": "{count, plural, one {Double tap to hide {count} notification.} other {Double tap to hide {count} notifications.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Double tap to show {count} notification.} other {Double tap to show {count} notifications.}}", "b2bb42d5ad881fd8": "{count, plural, one {Double tap to hide {count} tool call.} other {Double tap to hide {count} tool calls.}}", "f2338bdac15becc2": "{count, plural, one {Double tap to show {count} tool call.} other {Double tap to show {count} tool calls.}}", "e7588632064e0364": "Copied", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 288dbfc7da2cf..19fc577a4b33e 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4644,6 +4644,9 @@ "fd0d04d5a6627f70": "Abre el hilo de este agente. Mantén pulsado para copiar.", "7ba47e54094ba298": "Toca dos veces para ocultar los detalles completos. Mantén pulsado para copiar.", "1862ffb47bf6736c": "Toca dos veces para mostrar los detalles completos. Mantén pulsado para copiar.", + "16179c449afdc170": "{preview}, notificación fallida", + "ed1e51a988f1b585": "{count, plural, one {Toca dos veces para ocultar {count} notificación.} other {Toca dos veces para ocultar {count} notificaciones.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Toca dos veces para mostrar {count} notificación.} other {Toca dos veces para mostrar {count} notificaciones.}}", "b2bb42d5ad881fd8": "{count, plural, one {Toca dos veces para ocultar {count} llamada a herramienta.} other {Toca dos veces para ocultar {count} llamadas a herramientas.}}", "f2338bdac15becc2": "{count, plural, one {Toca dos veces para mostrar {count} llamada a herramienta.} other {Toca dos veces para mostrar {count} llamadas a herramientas.}}", "e7588632064e0364": "Copiado", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 28ec2284fca74..717bc5b331c60 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4645,6 +4645,9 @@ "fd0d04d5a6627f70": "Ouvre le fil de cet agent. Appuyez longuement pour copier.", "7ba47e54094ba298": "Touchez deux fois pour masquer tous les détails. Appuyez longuement pour copier.", "1862ffb47bf6736c": "Touchez deux fois pour afficher tous les détails. Appuyez longuement pour copier.", + "16179c449afdc170": "{preview}, échec de la notification", + "ed1e51a988f1b585": "{count, plural, one {Touchez deux fois pour masquer {count} notification.} other {Touchez deux fois pour masquer {count} notifications.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Touchez deux fois pour afficher {count} notification.} other {Touchez deux fois pour afficher {count} notifications.}}", "b2bb42d5ad881fd8": "{count, plural, one {Touchez deux fois pour masquer {count} appel d’outil.} other {Touchez deux fois pour masquer {count} appels d’outils.}}", "f2338bdac15becc2": "{count, plural, one {Touchez deux fois pour afficher {count} appel d’outil.} other {Touchez deux fois pour afficher {count} appels d’outils.}}", "e7588632064e0364": "Copié", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f6741fdb8b775..174e0378a8c91 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4626,6 +4626,9 @@ "fd0d04d5a6627f70": "このエージェントのスレッドを開きます。長押しでコピーします。", "7ba47e54094ba298": "ダブルタップで詳細を非表示にします。長押しでコピーします。", "1862ffb47bf6736c": "ダブルタップで詳細を表示します。長押しでコピーします。", + "16179c449afdc170": "{preview}、通知が失敗しました", + "ed1e51a988f1b585": "{count, plural, other {ダブルタップで {count} 件の通知を非表示にします。}}", + "ec5ac7184ecd7ab9": "{count, plural, other {ダブルタップで {count} 件の通知を表示します。}}", "b2bb42d5ad881fd8": "{count, plural, other {ダブルタップで {count} 件のツール呼び出しを非表示にします。}}", "f2338bdac15becc2": "{count, plural, other {ダブルタップで {count} 件のツール呼び出しを表示します。}}", "e7588632064e0364": "コピーしました", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b1ef20ba0f347..3f6deec6ec88c 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4631,6 +4631,9 @@ "fd0d04d5a6627f70": "이 에이전트의 스레드를 엽니다. 길게 눌러 복사합니다.", "7ba47e54094ba298": "두 번 탭하여 전체 세부 정보를 숨깁니다. 길게 눌러 복사합니다.", "1862ffb47bf6736c": "두 번 탭하여 전체 세부 정보를 표시합니다. 길게 눌러 복사합니다.", + "16179c449afdc170": "{preview}, 알림 실패", + "ed1e51a988f1b585": "{count, plural, other {두 번 탭하여 알림 {count}개를 숨깁니다.}}", + "ec5ac7184ecd7ab9": "{count, plural, other {두 번 탭하여 알림 {count}개를 표시합니다.}}", "b2bb42d5ad881fd8": "{count, plural, other {두 번 탭하여 도구 호출 {count}개를 숨깁니다.}}", "f2338bdac15becc2": "{count, plural, other {두 번 탭하여 도구 호출 {count}개를 표시합니다.}}", "e7588632064e0364": "복사됨", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index b40494fca3885..534f338a91409 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4645,6 +4645,9 @@ "fd0d04d5a6627f70": "Abre a thread deste agente. Mantenha pressionado para copiar.", "7ba47e54094ba298": "Toque duas vezes para ocultar os detalhes completos. Mantenha pressionado para copiar.", "1862ffb47bf6736c": "Toque duas vezes para mostrar os detalhes completos. Mantenha pressionado para copiar.", + "16179c449afdc170": "{preview}, notificação falhou", + "ed1e51a988f1b585": "{count, plural, one {Toque duas vezes para ocultar {count} notificação.} other {Toque duas vezes para ocultar {count} notificações.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Toque duas vezes para mostrar {count} notificação.} other {Toque duas vezes para mostrar {count} notificações.}}", "b2bb42d5ad881fd8": "{count, plural, one {Toque duas vezes para ocultar {count} chamada de ferramenta.} other {Toque duas vezes para ocultar {count} chamadas de ferramentas.}}", "f2338bdac15becc2": "{count, plural, one {Toque duas vezes para mostrar {count} chamada de ferramenta.} other {Toque duas vezes para mostrar {count} chamadas de ferramentas.}}", "e7588632064e0364": "Copiado", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index cadf07e57eda9..3346339ba329d 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4723,6 +4723,9 @@ "fd0d04d5a6627f70": "Открывает тред этого агента. Нажмите и удерживайте, чтобы скопировать.", "7ba47e54094ba298": "Дважды нажмите, чтобы скрыть подробности. Нажмите и удерживайте, чтобы скопировать.", "1862ffb47bf6736c": "Дважды нажмите, чтобы показать подробности. Нажмите и удерживайте, чтобы скопировать.", + "16179c449afdc170": "{preview}, ошибка уведомления", + "ed1e51a988f1b585": "{count, plural, one {Дважды нажмите, чтобы скрыть {count} уведомление.} few {Дважды нажмите, чтобы скрыть {count} уведомления.} many {Дважды нажмите, чтобы скрыть {count} уведомлений.} other {Дважды нажмите, чтобы скрыть {count} уведомления.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Дважды нажмите, чтобы показать {count} уведомление.} few {Дважды нажмите, чтобы показать {count} уведомления.} many {Дважды нажмите, чтобы показать {count} уведомлений.} other {Дважды нажмите, чтобы показать {count} уведомления.}}", "b2bb42d5ad881fd8": "{count, plural, one {Дважды нажмите, чтобы скрыть {count} вызов инструмента.} few {Дважды нажмите, чтобы скрыть {count} вызова инструментов.} many {Дважды нажмите, чтобы скрыть {count} вызовов инструментов.} other {Дважды нажмите, чтобы скрыть {count} вызова инструментов.}}", "f2338bdac15becc2": "{count, plural, one {Дважды нажмите, чтобы показать {count} вызов инструмента.} few {Дважды нажмите, чтобы показать {count} вызова инструментов.} many {Дважды нажмите, чтобы показать {count} вызовов инструментов.} other {Дважды нажмите, чтобы показать {count} вызова инструментов.}}", "e7588632064e0364": "Скопировано", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 3a0273aef36fd..81b1ae3179ccf 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4651,6 +4651,9 @@ "fd0d04d5a6627f70": "Öppnar agentens tråd. Tryck länge för att kopiera.", "7ba47e54094ba298": "Dubbeltryck för att dölja alla detaljer. Tryck länge för att kopiera.", "1862ffb47bf6736c": "Dubbeltryck för att visa alla detaljer. Tryck länge för att kopiera.", + "16179c449afdc170": "{preview}, aviseringen misslyckades", + "ed1e51a988f1b585": "{count, plural, one {Dubbeltryck för att dölja {count} avisering.} other {Dubbeltryck för att dölja {count} aviseringar.}}", + "ec5ac7184ecd7ab9": "{count, plural, one {Dubbeltryck för att visa {count} avisering.} other {Dubbeltryck för att visa {count} aviseringar.}}", "b2bb42d5ad881fd8": "{count, plural, one {Dubbeltryck för att dölja {count} verktygsanrop.} other {Dubbeltryck för att dölja {count} verktygsanrop.}}", "f2338bdac15becc2": "{count, plural, one {Dubbeltryck för att visa {count} verktygsanrop.} other {Dubbeltryck för att visa {count} verktygsanrop.}}", "e7588632064e0364": "Kopierat", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f1c394c60c606..96b6ca00003eb 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4634,6 +4634,9 @@ "fd0d04d5a6627f70": "打开此智能体的会话。长按以复制。", "7ba47e54094ba298": "轻点两下以隐藏完整详情。长按以复制。", "1862ffb47bf6736c": "轻点两下以显示完整详情。长按以复制。", + "16179c449afdc170": "{preview},通知失败", + "ed1e51a988f1b585": "{count, plural, other {轻点两下以隐藏 {count} 条通知。}}", + "ec5ac7184ecd7ab9": "{count, plural, other {轻点两下以显示 {count} 条通知。}}", "b2bb42d5ad881fd8": "{count, plural, other {轻点两下以隐藏 {count} 个工具调用。}}", "f2338bdac15becc2": "{count, plural, other {轻点两下以显示 {count} 个工具调用。}}", "e7588632064e0364": "已复制", diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 175ef5b4bab3c..7c3bcaf762408 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -2209,6 +2209,195 @@ describe("streamed feed updates", () => { }); }); +describe("wake notification groups", () => { + const second = (value: number) => `2026-06-20T00:00:${String(value).padStart(2, "0")}.000Z`; + const wake = ( + id: string, + at: number, + outcome: "completed" | "failed" = "completed", + taskCount = 1, + ): Extract => ({ + ...base(id, second(at), at), + type: "notification", + source: { + kind: "delegated_task", + taskIds: Array.from({ length: taskCount }, (_, index) => NodeId.make(`task-${id}-${index}`)), + }, + outcome, + summary: `Delegated task "${id}" ${outcome === "failed" ? "failed" : "finished"}`, + }); + const work = (id: string, at: number): OrchestrationV2TurnItem => ({ + ...command(second(at)), + id: TurnItemId.make(id), + ordinal: at, + }); + const feed = () => + buildThreadFeed( + [ + userMessage(second(1)), + work("work-1", 2), + wake("a", 3), + work("work-2", 4), + wake("b", 5), + work("work-3", 6), + wake("c", 7, "failed"), + assistantMessage(second(8)), + ].map((item, position) => projected(item, position)), + ); + + it("folds back-to-back wakes of a settled run into one toggle", () => { + const cache = createThreadFeedCache(); + const rows = deriveThreadFeedPresentation( + feed(), + null, + new Set(), + new Set(), + null, + false, + cache, + ); + expect(rows.map((row) => row.type)).toEqual(["message", "run-fold", "work-toggle", "message"]); + expect(rows[2]).toMatchObject({ + groupId: "notifications:local:thread-1:a", + hiddenCount: 3, + expanded: false, + summary: "3 delegated tasks: 2 finished, 1 failed", + notificationIcon: "hammer", + hasFailure: true, + }); + + const expanded = deriveThreadFeedPresentation( + feed(), + null, + new Set(), + new Set(["notifications:local:thread-1:a"]), + ); + expect(expanded.map((row) => row.type)).toEqual([ + "message", + "run-fold", + "work-toggle", + "activity-group", + "message", + ]); + const details = expanded[3]; + expect( + details?.type === "activity-group" + ? details.activities.map((activity) => [activity.summary, activity.groupedToolDetail]) + : null, + ).toEqual([ + ['Delegated task "a" finished', true], + ['Delegated task "b" finished', true], + ['Delegated task "c" failed', true], + ]); + }); + + it.each([false, true])("counts batched wakes with mixed sources: %s", (mixed) => { + const rows = deriveThreadFeedPresentation( + buildThreadFeed( + [ + userMessage(second(1)), + work("work-1", 2), + mixed + ? { ...wake("a", 3), source: { kind: "system" as const } } + : wake("a", 3, "completed", 3), + work("work-2", 4), + mixed + ? { ...wake("b", 5, "failed"), source: { kind: "command" as const } } + : wake("b", 5, "failed", 2), + assistantMessage(second(6)), + ].map((item, position) => projected(item, position)), + ), + null, + new Set(), + ); + expect(rows[2]).toMatchObject({ + type: "work-toggle", + hiddenCount: 2, + summary: mixed + ? "2 notifications: 1 finished, 1 failed" + : "5 delegated tasks: 3 finished, 2 failed", + }); + }); + + it("keeps wakes separate where work runs between them", () => { + const rows = deriveThreadFeedPresentation(feed(), null, new Set([runId]), new Set()); + expect( + rows.flatMap((row) => + row.type === "activity-group" && + row.activities[0]?.projectedItem.item.type === "notification" + ? [row.activities[0].summary] + : [], + ), + ).toEqual([ + 'Delegated task "a" finished', + 'Delegated task "b" finished', + 'Delegated task "c" failed', + ]); + expect(rows.some((row) => row.type === "work-toggle" && row.notificationIcon)).toBe(false); + }); + + it("keeps cached rebuilds after a later prompt in step with a fresh build", () => { + const secondRun = RunId.make("run-2"); + const inSecondRun = (item: OrchestrationV2TurnItem, id: string): OrchestrationV2TurnItem => + ({ ...item, id: TurnItemId.make(id), runId: secondRun }) as OrchestrationV2TurnItem; + const rows = [ + userMessage(second(1)), + work("work-1", 2), + wake("a", 3), + work("work-2", 4), + wake("b", 5), + assistantMessage(second(6)), + { + ...inSecondRun(userMessage(second(20)), "second-prompt"), + messageId: MessageId.make("second-prompt"), + } as OrchestrationV2TurnItem, + inSecondRun(command(second(21)), "second-work"), + inSecondRun({ ...assistantMessage(second(22)), streaming: true }, "second-reply"), + ].map((item, position) => projected(item, position)); + const latestRun = { + runId: secondRun, + status: "running" as const, + startedAt: second(20), + completedAt: null, + }; + const present = (feed: ReadonlyArray, cache?: ThreadFeedCache) => + deriveThreadFeedPresentation( + feed, + latestRun, + new Set(), + new Set(), + second(20), + false, + cache, + ).map((row) => row.id); + + const cache = createThreadFeedCache(); + present(buildThreadFeed(rows.slice(0, -1), { cache }), cache); + const next = buildThreadFeed(rows, { cache }); + const fresh = present(next); + expect(fresh.filter((id) => id === "second-prompt")).toHaveLength(1); + expect(present(next, cache)).toEqual(fresh); + }); + + it("leaves a lone wake as its own row", () => { + const rows = deriveThreadFeedPresentation( + buildThreadFeed( + [userMessage(second(1)), work("work-1", 2), wake("a", 3), assistantMessage(second(4))].map( + (item, position) => projected(item, position), + ), + ), + null, + new Set(), + ); + expect(rows.map((row) => row.type)).toEqual([ + "message", + "run-fold", + "activity-group", + "message", + ]); + }); +}); + it.each([false, true])( "caps live approval headers while preserving the prompt (grouped: %s)", (grouped) => { diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 4254404a39a99..2f2540ce1c623 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -50,6 +50,7 @@ import type { OrchestrationV2CreationSource, OrchestrationV2ExecutionNode, OrchestrationMessageContext, + OrchestrationV2Notification, OrchestrationV2ProjectedTurnItem, OrchestrationV2RunAttempt, OrchestrationV2RunStatus, @@ -236,6 +237,8 @@ type ThreadFeedEntryContent = readonly toolSurface?: WorkLogPresentationEntry["toolSurface"]; readonly toolIcon?: WorkLogPresentationEntry["toolIcon"]; readonly summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request"; + /** Set when the toggle folds back-to-back wake notifications rather than tool calls. */ + readonly notificationIcon?: ThreadFeedActivity["icon"]; readonly hasFailure: boolean; readonly live: boolean; readonly shimmer: boolean; @@ -1810,6 +1813,7 @@ export function deriveThreadFeedPresentation( for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId); } } + let groupedFrom = tailStart; // The working run's fold row shows its live timer where "Worked for" lands once it settles. // Zen never folds, so it keeps only the Thinking row. // Runless work folds under its prompt's key once it settles, so the live row takes that key. @@ -1849,6 +1853,9 @@ export function deriveThreadFeedPresentation( } } if (isUserMessageEntry(entry)) { + // Group before recording where this message's rows start; a user message ends every run of wakes. + groupConsecutiveNotificationRows(result, groupedFrom, expandedWorkGroupIds); + groupedFrom = result.length; restarts.push({ entry: feedIndex, rowsLength: result.length }); } const isActiveTailGroup = @@ -1931,6 +1938,7 @@ export function deriveThreadFeedPresentation( } } if (liveFold !== null && !liveFoldPlaced) result.push(liveFold); + groupConsecutiveNotificationRows(result, groupedFrom, expandedWorkGroupIds); if ( isWorking && activeWorkStartedAt !== null && @@ -1971,7 +1979,8 @@ export function deriveThreadFeedPresentation( for (let index = tailStart; index < result.length; index += 1) { const row = result[index]!; if ( - (row.type === "run-fold" || row.type === "work-toggle") && + (row.type === "run-fold" || + (row.type === "work-toggle" && row.notificationIcon === undefined)) && row.runId !== null && checkpointByRunId.has(row.runId) && (row.type === "run-fold" || !workRowByRunId.has(row.runId)) @@ -2045,6 +2054,135 @@ export function deriveThreadFeedPresentation( const continuedWorkLogRows = new WeakMap(); +const NOTIFICATION_SOURCE_NOUNS = { + delegated_task: "delegated tasks", + subagent: "subagents", + command: "commands", + monitor: "monitors", + background_task: "background tasks", + system: "notifications", +} satisfies Record; + +const NOTIFICATION_OUTCOME_VERBS = { + completed: "finished", + failed: "failed", + cancelled: "cancelled", + updated: "updated", + unknown: "ended", +} satisfies Record; + +function notificationRowItem(row: ThreadFeedEntry | undefined) { + if (row?.type !== "activity-group" || row.activities.length !== 1) return null; + const activity = row.activities[0]!; + const item = activity.projectedItem.item; + return item.type === "notification" && !activity.groupedToolDetail ? item : null; +} + +function notificationGroupSummary(notifications: ReadonlyArray) { + const kinds = new Set(notifications.map((notification) => notification.source.kind)); + const noun = + kinds.size === 1 + ? NOTIFICATION_SOURCE_NOUNS[notifications[0]!.source.kind] + : NOTIFICATION_SOURCE_NOUNS.system; + // One delegated-task wake can report a batch of tasks. + const counts = new Map(); + let total = 0; + for (const notification of notifications) { + const count = + notification.source.kind === "delegated_task" + ? Math.max(1, notification.source.taskIds.length) + : 1; + total += count; + counts.set(notification.outcome, (counts.get(notification.outcome) ?? 0) + count); + } + const outcomes = ( + Object.keys(NOTIFICATION_OUTCOME_VERBS) as Array + ).filter((outcome) => counts.has(outcome)); + return outcomes.length === 1 + ? `${total} ${noun} ${NOTIFICATION_OUTCOME_VERBS[outcomes[0]!]}` + : `${total} ${noun}: ${outcomes + .map((outcome) => `${counts.get(outcome)} ${NOTIFICATION_OUTCOME_VERBS[outcome]}`) + .join(", ")}`; +} + +const notificationGroupRowsCache = new WeakMap< + ThreadFeedEntry, + { + readonly members: ReadonlyArray; + readonly expanded: boolean; + readonly rows: ReadonlyArray; + } +>(); + +/** + * Wake notifications stay visible when their run folds, so a long run of + * delegated work leaves one row per finished task. Back-to-back rows share + * one toggle instead. + */ +function groupConsecutiveNotificationRows( + rows: ThreadFeedEntry[], + start: number, + expandedWorkGroupIds: ReadonlySet, +): void { + for (let index = start; index < rows.length; index += 1) { + let end = index; + while (notificationRowItem(rows[end]) !== null) end += 1; + if (end - index < 2) continue; + const members = rows.slice(index, end) as ThreadFeedActivityGroup[]; + const first = members[0]!; + const groupId = `notifications:${first.id}`; + const expanded = expandedWorkGroupIds.has(groupId); + let cached = notificationGroupRowsCache.get(first); + if ( + !cached || + cached.expanded !== expanded || + cached.members.length !== members.length || + cached.members.some((member, memberIndex) => member !== members[memberIndex]) + ) { + const activities = members.map((member) => member.activities[0]!); + const icons = new Set(activities.map((activity) => activity.icon)); + const notifications = members.map((member) => notificationRowItem(member)!); + const toggle: ThreadFeedEntry = { + type: "work-toggle", + id: `work-toggle:${groupId}`, + createdAt: first.createdAt, + runId: first.runId, + groupId, + hiddenCount: activities.length, + expanded, + summary: notificationGroupSummary(notifications), + summaryKind: "other", + notificationIcon: icons.size === 1 ? activities[0]!.icon : "zap", + hasFailure: notifications.some((notification) => notification.outcome === "failed"), + live: false, + shimmer: false, + }; + cached = { + members, + expanded, + rows: expanded + ? [ + toggle, + { + type: "activity-group", + id: `work-details:${groupId}`, + createdAt: first.createdAt, + runId: first.runId, + activities: activities.map((activity) => ({ + ...activity, + groupedToolDetail: true, + })), + }, + ] + : [toggle], + }; + notificationGroupRowsCache.set(first, cached); + } + rows.splice(index, members.length, ...cached.rows); + index += cached.rows.length - 1; + } +} + function isWorkLogFeedRow(row: ThreadFeedEntry | undefined): boolean { return ( row !== undefined &&