From a68290870cb642127597512f3dc02aefa355154a Mon Sep 17 00:00:00 2001 From: Grant Reaber Date: Thu, 19 Nov 2026 10:24:34 +0100 Subject: [PATCH] fix(web): notify when delegated work settles, and name the asking subagent A coordinator that hands work to delegated tasks got "Thread completed" each time a task finished: the task's result commits before the parent's wake run exists, and in that gap the parent reads as done. When a completion was held by background work and that work ends, the notification gate now waits out the same grace a monitor wake gets (5 s, matching the push relay's completion confirmation). The wake run cancels it; if no wake follows, it notifies. A subagent's approval request now names the subagent and opens it, in web and desktop notifications and toasts and in mobile push. Co-Authored-By: Claude Opus 5.5 --- .../src/relay/AgentAwarenessRelay.test.ts | 2 + apps/server/src/relay/AgentAwarenessRelay.ts | 2 +- ...ificationCoordinator.badge.browser.test.ts | 31 ++++++++++++++- ...hreadNotificationCoordinator.logic.test.ts | 23 +++++++++++ .../ThreadNotificationCoordinator.logic.ts | 7 +++- .../ThreadNotificationCoordinator.tsx | 39 +++++++++++++------ docs/user/mobile-notifications.md | 2 +- docs/user/thread-sidebar.md | 4 +- packages/shared/src/agentAwareness.ts | 24 +++++++++--- 9 files changed, 109 insertions(+), 25 deletions(-) diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 85b9b44f4daf7..25eb2a3aecaaa 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -354,6 +354,8 @@ describe("AgentAwarenessRelay", () => { assert.equal(publications.length, 2); assert.isTrue(publications[1]?.url.includes(`/threads/${THREAD_ID}/`) ?? false); assert.equal(publications[1]?.state?.phase, "waiting_for_approval"); + assert.equal(publications[1]?.state?.detail, "Child needs approval."); + assert.isTrue(publications[1]?.state?.deepLink.endsWith(`/${CHILD_THREAD_ID}`) ?? false); // A rename keeps the same request's alert time, so the phone doesn't re-alert. yield* setShell( diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index c14558762183a..52d760ade19bb 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -758,7 +758,7 @@ export const make = Effect.gen(function* () { if (requestId !== entry.requestId) subagentRequests.set(childId, { ...entry, requestId }); // The newest wait is the one to announce. if (pending === null || DateTime.isGreaterThan(child.updatedAt, pending.updatedAt)) { - pending = { requestId, updatedAt: child.updatedAt }; + pending = { threadId: childId, title: child.title, requestId, updatedAt: child.updatedAt }; } } return pending; diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index aab1de3db6726..07cf02f80622f 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -51,7 +51,8 @@ vi.mock(import("../state/threads"), async (original) => { ...actual, environmentThreadShells: { ...actual.environmentThreadShells, - pendingSubagentRequestsAtom: (() => noRequestsAtom) as never, + pendingSubagentRequestsAtom: (() => requestsAtom) as never, + childThreadInputsAtom: (() => childInputsAtom) as never, get delegatedUnderParentAtom() { return noDelegatedAtom as never; }, @@ -81,7 +82,8 @@ import { startThreadNotifications } from "./ThreadNotificationCoordinator"; let registry: AtomRegistry.AtomRegistry; const shellAtom = Atom.family((_id: string) => Atom.make(null)); const environmentIdsAtom = Atom.make>([]); -const noRequestsAtom = Atom.make(new Map()); +const requestsAtom = Atom.make>(new Map()); +const childInputsAtom = Atom.make>([]); const noDelegatedAtom = Atom.make>(new Set()); state.shells = { set: (id, value) => registry.set(shellAtom(id), value) }; @@ -254,6 +256,31 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)( }, ); +it("names a subagent asking for approval through its parent and opens it", async () => { + await using app = setup(); + app.start(); + registry.set(childInputsAtom, [ + { + environmentId: "two", + id: "child", + title: "Fix flaky test", + hasPendingApprovals: true, + lineage: { sideChat: false }, + }, + ]); + registry.set(requestsAtom, new Map([["thread", "approval"]])); + const [notification] = TestNotification.sent; + expect([notification?.title, notification?.options.body]).toEqual([ + "Approval needed", + "Fix flaky test (in Test thread)", + ]); + notification!.dispatchEvent(new Event("click")); + expect(state.navigate).toHaveBeenCalledWith({ + to: "/$environmentId/$threadId", + params: { environmentId: "two", threadId: "child" }, + }); +}); + it("presents completion notifications and sound as soon as the shell completes", async () => { await using app = setup(); state.mode = "notifications-and-sound"; diff --git a/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts index 965dba45ce8a2..581cc146e44f6 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts @@ -12,6 +12,7 @@ const working: ThreadNotificationObservation = { settled: false, completedAt: null, backgroundWake: false, + heldCompletedAt: null, }; const completed = (at: number): ThreadNotificationObservation => ({ attention: null, @@ -19,12 +20,14 @@ const completed = (at: number): ThreadNotificationObservation => ({ settled: true, completedAt: at, backgroundWake: false, + heldCompletedAt: null, }); const waking: ThreadNotificationObservation = { ...working, backgroundWake: true }; const woke = (at: number): ThreadNotificationObservation => ({ ...completed(at), backgroundWake: true, }); +const held = (at: number): ThreadNotificationObservation => ({ ...working, heldCompletedAt: at }); const visible = { archived: false, quiet: false }; function fakeTimers(): Disposable { @@ -161,6 +164,26 @@ describe("createThreadNotificationGate", () => { ]); }); + it("waits out the grace when held work ends, so the wake it starts replaces the completion", () => { + using _timers = fakeTimers(); + const { notify, observe } = harness(); + observe(working); + // The run ended while a delegated task still ran, then the task finished before its wake. + observe(held(1)); + observe(completed(1)); + expect(notify).not.toHaveBeenCalled(); + observe(working); + vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS); + expect(notify).not.toHaveBeenCalled(); + observe(held(2)); + observe(completed(2)); + vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS - 1); + observe({ ...completed(2) }); + expect(notify).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(notify.mock.calls).toEqual([["thread", "completion"]]); + }); + it("notifies a wake's completion once after the grace when no run follows, even across a pause", () => { using _timers = fakeTimers(); const { gate, notify, observe } = harness(); diff --git a/apps/web/src/components/ThreadNotificationCoordinator.logic.ts b/apps/web/src/components/ThreadNotificationCoordinator.logic.ts index c8f0ca7df7a9a..4016ecdd1b47a 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.logic.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.logic.ts @@ -11,9 +11,11 @@ export interface ThreadNotificationObservation { readonly completedAt: number | null; /** The latest run answers a background-work progress wake, like a Monitor line. */ readonly backgroundWake: boolean; + /** When the latest run completed, while background work such as a delegated task holds it. */ + readonly heldCompletedAt: number | null; } -/** Matches the push relay's completion confirmation: a final wake can start right after a progress wake. */ +/** Matches the push relay's completion confirmation: a wake can start right after held work ends. */ export const RELEASED_COMPLETION_GRACE_MS = 5_000; export function createThreadNotificationGate( @@ -83,7 +85,8 @@ export function createThreadNotificationGate( } const at = next.completedAt; if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return; - if (next.backgroundWake) { + // Held work that ends wakes the agent, and its result commits before that wake run exists. + if (next.backgroundWake || prior.heldCompletedAt === at) { release(key, at); return; } diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 2051d4ad633a8..3b2b96b763218 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -142,6 +142,26 @@ export function startThreadNotifications( : status === "request" ? "Guest request" : "Input needed"; + // A subagent or side chat asking through its parent is named and opened directly. + const requester = + kind === "input" && + state.subagentRequest !== null && + !thread.hasPendingApprovals && + !thread.hasPendingUserInput + ? (registry + .get( + environmentThreadShells.childThreadInputsAtom({ environmentId, threadId: thread.id }), + ) + .find((child) => + state.subagentRequest === "approval" + ? child.hasPendingApprovals + : child.lineage.sideChat === true, + ) ?? null) + : null; + const body = requester ? `${requester.title} (in ${thread.title})` : thread.title; + const target = requester + ? { environmentId: requester.environmentId, threadId: requester.id } + : { environmentId, threadId: thread.id }; if (hasNotificationSound(mode)) { void playNotificationSound(kind, () => hasNotificationSound(getClientSettings().notificationMode), @@ -158,7 +178,7 @@ export function startThreadNotifications( onRemove: (): void => forgetToast(toastKey, toastId), type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning", title, - description: thread.title, + description: body, data: { hideCopyButton: true, leadingIcon: @@ -178,10 +198,7 @@ export function startThreadNotifications( children: "Open thread", onClick: () => { toastManager.close(toastId); - void router.navigate({ - to: "/$environmentId/$threadId", - params: { environmentId, threadId: thread.id }, - }); + void router.navigate({ to: "/$environmentId/$threadId", params: target }); }, }, }); @@ -197,7 +214,7 @@ export function startThreadNotifications( return; try { const notification = new Notification(title, { - body: thread.title, + body, tag: threadNotificationTag(environmentId, thread.id), silent: true, // Windows drops clicks after a toast moves into Notification Center. @@ -208,10 +225,7 @@ export function startThreadNotifications( notification.close(); window.focus(); void window.desktopBridge?.revealWindow().catch(() => undefined); - void router.navigate({ - to: "/$environmentId/$threadId", - params: { environmentId, threadId: thread.id }, - }); + void router.navigate({ to: "/$environmentId/$threadId", params: target }); }); } catch { // Some browsers expose Notification but reject desktop presentation. @@ -264,8 +278,8 @@ export function startThreadNotifications( const attention = needsAttention ? `${thread.latestRun?.runId ?? ""}:${status}:${requestId ?? ""}` : null; - const completed = status === "ready" && thread.latestRun?.status === "completed"; - const settled = completed && !monitorHoldsWakeCompletion(rawThread); + const runCompleted = thread.latestRun?.status === "completed"; + const settled = status === "ready" && runCompleted && !monitorHoldsWakeCompletion(rawThread); const parsedCompletedAt = Date.parse(thread.latestRun?.completedAt ?? ""); const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null; const state = { @@ -278,6 +292,7 @@ export function startThreadNotifications( settled, completedAt: settled ? completedAt : null, backgroundWake: rawThread.latestRunBackgroundWake === true, + heldCompletedAt: runCompleted && !settled ? completedAt : null, }; next.set(thread.id, state); changed.push([prior, state]); diff --git a/docs/user/mobile-notifications.md b/docs/user/mobile-notifications.md index 992efd5b7b29a..4c9cb52996a8b 100644 --- a/docs/user/mobile-notifications.md +++ b/docs/user/mobile-notifications.md @@ -1,6 +1,6 @@ # Mobile notifications -Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled. +Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread, or the subagent whose approval it asks for. Your environment must have agent activity publishing enabled. Enable **Live Activity Updates** on iOS, **Agent Live Updates** on Android 16 and newer, or **Ongoing Agent Activity** on older Android versions to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off the same switch to stop future cards. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index e8a06a0d5feb3..1a5ac0c72ba29 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -287,7 +287,9 @@ Stop on a thread also stops the subagents it delegated to. Subagent threads started by the agent can't take messages; message the parent thread instead. When such a subagent needs an approval or an answer, the parent -thread asks for it. +thread asks for it, and an approval notification names the subagent and opens it. +Subagents don't notify you when they finish. The parent notifies you once it +finishes with no delegated work left running. Expand a tool call in the conversation to see its full command and output. Summaries shorten shell wrappers and can still describe the latest call after it diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts index 55ad807957d64..9cd95a568cbab 100644 --- a/packages/shared/src/agentAwareness.ts +++ b/packages/shared/src/agentAwareness.ts @@ -24,6 +24,9 @@ export type AgentAwarenessPhase = | "stale"; export interface SubagentRequestAwareness { + /** The asking subagent, which the alert names and opens. */ + readonly threadId: ThreadId; + readonly title: string; readonly requestId: RuntimeRequestId; /** The child's own update time, which moves whenever its request changes. */ readonly updatedAt: DateTime.Utc; @@ -112,12 +115,18 @@ export function projectThreadAwarenessV2( ) { return null; } + const asking = + subagentRequest !== null && resolveThreadAwarenessPhaseV2(thread, false) !== phase + ? subagentRequest + : null; const detail = - phase === "completed" - ? "Review the completed task." - : phase === "failed" - ? "The agent run failed." - : undefined; + asking !== null + ? `${asking.title} needs approval.` + : phase === "completed" + ? "Review the completed task." + : phase === "failed" + ? "The agent run failed." + : undefined; return { environmentId, threadId: thread.id, @@ -134,7 +143,10 @@ export function projectThreadAwarenessV2( ? thread.updatedAt : DateTime.max(thread.updatedAt, subagentRequest.updatedAt), ), - deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }), + deepLink: buildAgentAwarenessDeepLink({ + environmentId, + threadId: asking?.threadId ?? thread.id, + }), }; }