From df183b3e69f91f4ed5b9000733705c9233d7ede5 Mon Sep 17 00:00:00 2001 From: MarconLP <13001502+MarconLP@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:11:00 +0000 Subject: [PATCH 1/7] fix(server): Claude's push notifications reach the desktop and web apps Claude Code counts an Agent SDK session as an open terminal, so its PushNotification tool answers user_present from every T3 thread and sends nothing. A PostToolUse hook now takes over that refusal: the server hands the message to connected clients over a new subscribeAgentAlerts stream, the web and desktop apps show it with the existing toast and notification code, and the model is told whether a client took it. Refs #25645 --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/notifications/AgentAlerts.test.ts | 50 +++++ apps/server/src/notifications/AgentAlerts.ts | 42 ++++ .../src/observability/RpcInstrumentation.ts | 1 + .../Adapters/ClaudeAdapterV2.ts | 25 ++- .../Adapters/claudePushNotification.test.ts | 112 +++++++++++ .../Adapters/claudePushNotification.ts | 74 +++++++ apps/server/src/server.ts | 4 + apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 3 + ...ificationCoordinator.badge.browser.test.ts | 87 ++++++++- .../ThreadNotificationCoordinator.tsx | 181 ++++++++++++------ packages/client-runtime/src/rpc/client.ts | 1 + packages/client-runtime/src/state/server.ts | 6 + packages/contracts/src/agentAlert.ts | 12 ++ packages/contracts/src/environment.ts | 2 + packages/contracts/src/index.ts | 1 + packages/contracts/src/rpc.ts | 10 + 19 files changed, 559 insertions(+), 56 deletions(-) create mode 100644 apps/server/src/notifications/AgentAlerts.test.ts create mode 100644 apps/server/src/notifications/AgentAlerts.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts create mode 100644 packages/contracts/src/agentAlert.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index a765c28476322..7777a1c2191b7 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -225,6 +225,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.subscribeDeviceState]: AuthOrchestrationReadScope, [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope, [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope, + [WS_METHODS.subscribeAgentAlerts]: AuthOrchestrationReadScope, [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope, } as const satisfies Readonly>; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 1760623071efb..4012ef82e0fd7 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -263,6 +263,7 @@ export const make = Effect.gen(function* () { threadProjectFromScratch: true, threadTitleRegeneration: true, commandOutputStreaming: true, + agentAlerts: true, threadVisitedTracking: true, threadPullRequests: true, threadPullRequestWatch: true, diff --git a/apps/server/src/notifications/AgentAlerts.test.ts b/apps/server/src/notifications/AgentAlerts.test.ts new file mode 100644 index 0000000000000..79fb49b56ebbc --- /dev/null +++ b/apps/server/src/notifications/AgentAlerts.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "@effect/vitest"; +import { type AgentAlert, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; + +import * as AgentAlerts from "./AgentAlerts.ts"; + +const alert = { + id: "tool-1", + threadId: ThreadId.make("thread-1"), + body: "fleet.lock stuck", +} satisfies AgentAlert; + +describe("AgentAlerts", () => { + it.effect("reports no delivery when no client is subscribed", () => + Effect.gen(function* () { + const alerts = yield* AgentAlerts.AgentAlerts; + expect(yield* alerts.offer(alert)).toBe(false); + }).pipe(Effect.provide(AgentAlerts.layer)), + ); + + it.effect("delivers to every subscribed client until it disconnects", () => + Effect.gen(function* () { + const alerts = yield* AgentAlerts.AgentAlerts; + const first = yield* Queue.unbounded(); + const second = yield* Queue.unbounded(); + const firstClient = yield* alerts.stream.pipe( + Stream.runForEach((item) => Queue.offer(first, item)), + Effect.forkScoped({ startImmediately: true }), + ); + const secondClient = yield* alerts.stream.pipe( + Stream.runForEach((item) => Queue.offer(second, item)), + Effect.forkScoped({ startImmediately: true }), + ); + + expect(yield* alerts.offer(alert)).toBe(true); + expect(yield* Queue.take(first)).toEqual(alert); + expect(yield* Queue.take(second)).toEqual(alert); + + yield* Fiber.interrupt(firstClient); + expect(yield* alerts.offer(alert)).toBe(true); + expect(yield* Queue.take(second)).toEqual(alert); + + yield* Fiber.interrupt(secondClient); + expect(yield* alerts.offer(alert)).toBe(false); + }).pipe(Effect.provide(AgentAlerts.layer), Effect.scoped), + ); +}); diff --git a/apps/server/src/notifications/AgentAlerts.ts b/apps/server/src/notifications/AgentAlerts.ts new file mode 100644 index 0000000000000..02f63731b85fe --- /dev/null +++ b/apps/server/src/notifications/AgentAlerts.ts @@ -0,0 +1,42 @@ +import type { AgentAlert } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; + +export class AgentAlerts extends Context.Service< + AgentAlerts, + { + /** Hands the alert to every subscribed client. False when none is subscribed. */ + readonly offer: (alert: AgentAlert) => Effect.Effect; + readonly stream: Stream.Stream; + } +>()("t3/notifications/AgentAlerts") {} + +const make = Effect.gen(function* () { + const subscribers = yield* Ref.make(0); + const alerts = yield* PubSub.unbounded(); + + const stream = Stream.unwrap( + Effect.gen(function* () { + // Subscribe before counting: counted first, an offer in between reports a + // delivery that the subscription never receives. + const subscription = yield* PubSub.subscribe(alerts); + yield* Ref.update(subscribers, (count) => count + 1); + yield* Effect.addFinalizer(() => Ref.update(subscribers, (count) => count - 1)); + return Stream.fromSubscription(subscription); + }), + ); + + const offer: AgentAlerts["Service"]["offer"] = Effect.fn("AgentAlerts.offer")(function* (alert) { + if ((yield* Ref.get(subscribers)) === 0) return false; + yield* PubSub.publish(alerts, alert); + return true; + }); + + return AgentAlerts.of({ offer, stream }); +}); + +export const layer = Layer.effect(AgentAlerts, make); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a103dc14e3678..ad5799cf9a9f8 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -245,6 +245,7 @@ const RPC_AGGREGATES = { [WS_METHODS.subscribeDeviceState]: "device", [WS_METHODS.subscribeServerConfig]: "server", [WS_METHODS.subscribeServerLifecycle]: "server", + [WS_METHODS.subscribeAgentAlerts]: "server", [WS_METHODS.subscribeAuthAccess]: "auth", } as const satisfies Readonly>; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 35db7f169159c..29c17c42190fb 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -6,6 +6,10 @@ import { } from "@t3tools/shared/toolOutput"; import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts"; import { claudeTaskOutputRoot, tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts"; +import { + CLAUDE_PUSH_NOTIFICATION_TOOL, + makeClaudePushNotificationHook, +} from "./claudePushNotification.ts"; import { dynamicToolTitle, formatReadToolLabel, @@ -163,6 +167,7 @@ import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; +import * as AgentAlerts from "../../notifications/AgentAlerts.ts"; import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts"; import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; @@ -2189,6 +2194,7 @@ export function makeClaudeQueryOptions(input: { readonly onUserDialog?: ClaudeQueryOptions["onUserDialog"]; readonly onElicitation?: ClaudeQueryOptions["onElicitation"]; readonly onStop?: HookCallback; + readonly onPushNotification?: HookCallback; readonly supportedDialogKinds?: ClaudeQueryOptions["supportedDialogKinds"]; readonly allowDangerouslySkipPermissions?: boolean; readonly appendSystemPromptFileText?: string; @@ -2343,13 +2349,20 @@ export function makeClaudeQueryOptions(input: { ...launchAppendSystemPrompt, ].join("\n\n"), }, - ...(deviceInstructions || input.onStop !== undefined + ...(deviceInstructions || input.onStop !== undefined || input.onPushNotification !== undefined ? { hooks: { ...(deviceInstructions ? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } : {}), ...(input.onStop === undefined ? {} : { Stop: [{ hooks: [input.onStop] }] }), + ...(input.onPushNotification === undefined + ? {} + : { + PostToolUse: [ + { matcher: CLAUDE_PUSH_NOTIFICATION_TOOL, hooks: [input.onPushNotification] }, + ], + }), }, } : {}), @@ -5545,6 +5558,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService); + const agentAlerts = yield* Effect.serviceOption(AgentAlerts.AgentAlerts); const { attachmentsDir, fileSystem, path, random, idAllocator, queryRunner } = adapterOptions; const loadModelCatalog = ( adapterOptions.modelCatalog ?? Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG) @@ -12694,6 +12708,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return pendingWake !== undefined && (yield* pendingWake) ? { continue: false } : {}; }), ); + const onPushNotification = makeClaudePushNotificationHook((alert) => + runPromise( + Option.match(agentAlerts, { + onNone: () => Effect.succeed(false), + onSome: (alerts) => alerts.offer({ ...alert, threadId: turnInput.threadId }), + }), + ), + ); const mcpOverrides = claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: @@ -12869,6 +12891,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( onUserDialog, onElicitation, onStop, + onPushNotification, supportedDialogKinds: ["resume_return"], ...(appendSystemPromptFileText === undefined ? {} : { appendSystemPromptFileText }), ...(toolSearchOverride === undefined ? {} : { toolSearchOverride }), diff --git a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts new file mode 100644 index 0000000000000..7b509221d86f9 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts @@ -0,0 +1,112 @@ +import { describe, it } from "@effect/vitest"; +import * as NodeAssert from "node:assert/strict"; + +import { makeClaudePushNotificationHook } from "./claudePushNotification.ts"; + +const USER_PRESENT = { + message: "Not sent — this terminal is active.", + pushSent: false, + localSent: false, + disabledReason: "user_present", + sentAt: "2026-11-17T12:00:00.000Z", +}; + +function run( + hook: ReturnType, + input: { readonly message?: unknown; readonly response?: unknown; readonly tool?: string }, +) { + return hook( + { + hook_event_name: "PostToolUse", + tool_name: input.tool ?? "PushNotification", + tool_input: { message: input.message ?? "fleet.lock stuck", status: "proactive" }, + tool_response: input.response ?? USER_PRESENT, + tool_use_id: "tool-1", + session_id: "session-1", + transcript_path: "", + cwd: "/workspace", + }, + "tool-1", + { signal: new AbortController().signal }, + ); +} + +describe("claudePushNotification", () => { + it("delivers a push Claude refused as user_present and reports a local send", async () => { + const delivered: Array<{ readonly id: string; readonly body: string }> = []; + const hook = makeClaudePushNotificationHook(async (alert) => { + delivered.push(alert); + return true; + }); + + NodeAssert.deepEqual(await run(hook, {}), { + hookSpecificOutput: { + hookEventName: "PostToolUse", + updatedToolOutput: { + message: "Sent through T3 Code.", + pushSent: false, + localSent: true, + disabledReason: "no_transport", + sentAt: "2026-11-17T12:00:00.000Z", + }, + additionalContext: + "T3 Code showed this notification on the user's connected T3 Code client.", + }, + }); + NodeAssert.deepEqual(delivered, [{ id: "tool-1", body: "fleet.lock stuck" }]); + }); + + it("does not tell the model the user is present when no client took the alert", async () => { + const hook = makeClaudePushNotificationHook(async () => false); + + NodeAssert.deepEqual(await run(hook, {}), { + hookSpecificOutput: { + hookEventName: "PostToolUse", + updatedToolOutput: { + message: "Not sent. No T3 Code client with notifications on is connected.", + pushSent: false, + localSent: false, + disabledReason: "no_transport", + sentAt: "2026-11-17T12:00:00.000Z", + }, + additionalContext: + "This notification reached nobody: no T3 Code client with notifications on is connected.", + }, + }); + }); + + it("sends one line of at most 200 characters", async () => { + const bodies: Array = []; + const hook = makeClaudePushNotificationHook(async (alert) => { + bodies.push(alert.body); + return true; + }); + + await run(hook, { message: " line\n\nbreak " }); + await run(hook, { message: "x".repeat(240) }); + + NodeAssert.equal(bodies[0], "line break"); + NodeAssert.equal(bodies[1]?.length, 200); + NodeAssert.equal(bodies[1]?.endsWith("…"), true); + }); + + it("leaves every other result as Claude wrote it", async () => { + const delivered: Array = []; + const hook = makeClaudePushNotificationHook(async (alert) => { + delivered.push(alert.body); + return true; + }); + + for (const response of [ + { message: "Sent", pushSent: true, localSent: true }, + { message: "Notifications are off.", pushSent: false, disabledReason: "config_off" }, + { message: "No push transport.", pushSent: false, disabledReason: "no_transport" }, + ]) { + NodeAssert.deepEqual(await run(hook, { response }), {}); + } + NodeAssert.deepEqual(await run(hook, { tool: "Bash" }), {}); + NodeAssert.deepEqual(await run(hook, { message: " " }), {}); + NodeAssert.deepEqual(await run(hook, { message: 42 }), {}); + NodeAssert.deepEqual(delivered, []); + }); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts new file mode 100644 index 0000000000000..aa336321eedb8 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts @@ -0,0 +1,74 @@ +import type { HookCallback, SyncHookJSONOutput } from "@anthropic-ai/claude-agent-sdk"; + +export const CLAUDE_PUSH_NOTIFICATION_TOOL = "PushNotification"; +// The tool asks the model for under 200 characters; phones cut longer text. +const MAX_MESSAGE_LENGTH = 200; + +function readMessage(toolInput: unknown): string | null { + if (typeof toolInput !== "object" || toolInput === null || !("message" in toolInput)) { + return null; + } + if (typeof toolInput.message !== "string") return null; + const oneLine = toolInput.message.trim().replace(/\s+/g, " "); + if (oneLine.length === 0) return null; + return oneLine.length > MAX_MESSAGE_LENGTH + ? `${oneLine.slice(0, MAX_MESSAGE_LENGTH - 1)}…` + : oneLine; +} + +type ToolResponse = Readonly>; + +function refusedAsUserPresent(toolResponse: unknown): toolResponse is ToolResponse { + return ( + typeof toolResponse === "object" && + toolResponse !== null && + "disabledReason" in toolResponse && + toolResponse.disabledReason === "user_present" + ); +} + +function toolOutput(toolResponse: ToolResponse, delivered: boolean): SyncHookJSONOutput { + return { + hookSpecificOutput: { + hookEventName: "PostToolUse", + // Claude Code writes the model's result text from these fields and ignores `message`. + // `no_transport` is its closest wording: a local notification was or was not sent, and + // no mobile push was. `additionalContext` tells the model what T3 did. + updatedToolOutput: { + ...toolResponse, + message: delivered + ? "Sent through T3 Code." + : "Not sent. No T3 Code client with notifications on is connected.", + pushSent: false, + localSent: delivered, + disabledReason: "no_transport", + }, + additionalContext: delivered + ? "T3 Code showed this notification on the user's connected T3 Code client." + : "This notification reached nobody: no T3 Code client with notifications on is connected.", + }, + }; +} + +/** + * Claude Code decides delivery inside the CLI and counts an Agent SDK session as an open + * terminal, so from a T3 thread the tool always answers `user_present` and sends nothing. + * This takes over that one refusal: T3 delivers the message and the model hears what happened. + */ +export function makeClaudePushNotificationHook( + deliver: (alert: { readonly id: string; readonly body: string }) => Promise, +): HookCallback { + return async (input) => { + if ( + input.hook_event_name !== "PostToolUse" || + input.tool_name !== CLAUDE_PUSH_NOTIFICATION_TOOL || + // A real send, or a refusal for another reason, reaches the model unchanged. + !refusedAsUserPresent(input.tool_response) + ) { + return {}; + } + const body = readMessage(input.tool_input); + if (body === null) return {}; + return toolOutput(input.tool_response, await deliver({ id: input.tool_use_id, body })); + }; +} diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 29e3143cbc638..5cbdb8f7b88ab 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -112,6 +112,7 @@ import * as Keybindings from "./keybindings.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as ServerOwnership from "./serverOwnership.ts"; import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; +import * as AgentAlerts from "./notifications/AgentAlerts.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; import * as ServerSettings from "./serverSettings.ts"; import * as ManagedLimits from "./policy/managedLimits.ts"; @@ -751,6 +752,9 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( // One gate for the server, below hydration so the Claude adapter sees it: layers memoize by // reference, so the runtime layer shares it. Layer.provideMerge(ProviderInstallationGate.layer), + // Below hydration for the same reason: the Claude adapter offers alerts to the instance the + // WebSocket streams from. + Layer.provideMerge(AgentAlerts.layer), // Provider hydration builds the Claude runner, which reports agents to the same scanner the // terminal and preview layers share. Layer.provideMerge(layerPortScanner), diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 4583ca2209277..e59863a62a7c1 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -128,6 +128,7 @@ import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; +import * as AgentAlerts from "./notifications/AgentAlerts.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; import * as NpmRelease from "./cloud/npmRelease.ts"; @@ -872,6 +873,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(SecretResolver.SecretResolver)({}), Layer.mock(GuestShareService.GuestShareService)({}), Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}), + Layer.mock(AgentAlerts.AgentAlerts)({}), Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}), Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}), Layer.mock(NpmRelease.NpmRelease)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index bbe80f28e9681..6b74d8033a066 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -186,6 +186,7 @@ import * as ProviderInstallation from "./provider/providerInstallation.ts"; import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; import * as NpmRelease from "./cloud/npmRelease.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; +import * as AgentAlerts from "./notifications/AgentAlerts.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as ServerSettings from "./serverSettings.ts"; @@ -1549,6 +1550,7 @@ export const layerWsRpc = ( const npmRelease = yield* NpmRelease.NpmRelease; const config = yield* ServerConfig.ServerConfig; const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; + const agentAlerts = yield* AgentAlerts.AgentAlerts; const storageCleanup = yield* StorageCleanup.StorageCleanup; const databaseStorage = yield* DatabaseStorage.DatabaseStorage; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -3493,6 +3495,7 @@ export const layerWsRpc = ( ); }), ), + [WS_METHODS.subscribeAgentAlerts]: (_input) => agentAlerts.stream, [WS_METHODS.subscribeServerLifecycle]: (_input) => Stream.unwrap( Effect.gen(function* () { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 7da8504990fe6..3119114c33141 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -2,7 +2,7 @@ import type { AnyRouter } from "@tanstack/react-router"; import { EnvironmentId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; -import { Atom, AtomRegistry } from "effect/reactivity"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { expect, it, vi } from "vite-plus/test"; import { fakeTimers, stubGlobal } from "../../test/render"; @@ -40,6 +40,18 @@ vi.mock(import("../state/shell"), async (original) => { }, }; }); +vi.mock(import("../state/server"), async (original) => { + const actual = await original(); + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + agentAlerts: ((target: { environmentId: string }) => + alertAtom(target.environmentId)) as never, + configValueAtom: ((id: string) => configAtom(id)) as never, + }, + }; +}); vi.mock(import("../state/presentation"), async (original) => { const actual = await original(); return { @@ -88,6 +100,11 @@ import { startThreadNotifications } from "./ThreadNotificationCoordinator"; let registry: AtomRegistry.AtomRegistry; const shellAtom = Atom.family((_id: string) => Atom.make(null)); +const alertAtom = Atom.family((_id: string) => Atom.make(AsyncResult.initial())); +// Only "one" runs a server that serves agent alerts. +const configAtom = Atom.family((id: string) => + Atom.make({ environment: { capabilities: id === "one" ? { agentAlerts: true } : {} } }), +); const environmentIdsAtom = Atom.make>([]); const noRequestsAtom = Atom.make(new Map()); const noDelegatedAtom = Atom.make>(new Set()); @@ -229,6 +246,9 @@ function setup() { stack.defer(startThreadNotifications(testRegistry, router)); }, setEnvironmentIds: (ids: ReadonlyArray) => testRegistry.set(environmentIdsAtom, ids), + // The stream never ends, so its atom marks every alert as waiting for more. + alert: (environmentId: string, alert: { id: string; threadId: string; body: string }) => + testRegistry.set(alertAtom(environmentId), AsyncResult.success(alert, { waiting: true })), openThread: (environmentId: string, threadId: string) => { route.params = { environmentId, threadId }; for (const listener of routeListeners) listener(); @@ -453,3 +473,68 @@ it("opening a thread or removing its environment closes only its in-app toasts, app.changeSettings(); expect(state.closeToast.mock.calls.slice(3)).toEqual([["one-other"]]); }); + +it("shows an agent's alert once as a desktop notification that opens its thread", async () => { + await using app = setup(); + // Left in the atom by an earlier subscription. + app.alert("one", { id: "tool-0", threadId: "thread", body: "already shown" }); + app.start(); + const alert = { id: "tool-1", threadId: "thread", body: "fleet.lock stuck" }; + app.alert("one", alert); + // A reconnect replays the last alert the stream held. + app.alert("one", { ...alert }); + app.alert("one", { ...alert, id: "tool-2", threadId: "gone" }); + app.alert("two", { ...alert, id: "tool-3" }); + state.shells.set("one", shell({ archivedAt: "2026-09-13T07:00:00.000Z" })); + app.alert("one", { ...alert, id: "tool-4" }); + + expect(TestNotification.sent.map(({ title, options }) => [title, options.body])).toEqual([ + ["Test thread", "fleet.lock stuck"], + ["T3 Code", "fleet.lock stuck"], + ]); + expect(state.badge).toHaveBeenLastCalledWith(2); + TestNotification.sent[0]!.dispatchEvent(new Event("click")); + expect(state.navigate).toHaveBeenCalledWith({ + to: "/$environmentId/$threadId", + params: { environmentId: EnvironmentId.make("one"), threadId: "thread" }, + }); +}); + +it("keeps an agent's alert on screen when its thread then completes", async () => { + await using app = setup(); + app.start(); + app.alert("one", { id: "tool-1", threadId: "thread", body: "fleet.lock stuck" }); + state.shells.set( + "one", + shell({ + latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:00:01.000Z" }, + }), + ); + + expect(TestNotification.sent.map(({ title }) => title)).toEqual([ + "Test thread", + "Thread completed", + ]); + expect(TestNotification.sent[0]!.close).not.toHaveBeenCalled(); +}); + +it("toasts an agent's alert in the focused app unless its thread is the open one", async () => { + await using app = setup(); + state.inApp = true; + focused = true; + state.shells.set("one", shell({}, { id: "other", title: "Other thread" })); + app.start(); + app.openThread("one", "thread"); + app.alert("one", { id: "tool-1", threadId: "thread", body: "fleet.lock stuck" }); + expect(state.toast).not.toHaveBeenCalled(); + + app.alert("one", { id: "tool-2", threadId: "other", body: "needs a push guard" }); + expect(state.toast).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + type: "info", + title: "Other thread", + description: "needs a push guard", + }), + ); + expect(TestNotification.sent).toEqual([]); +}); diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 0268da23dd2e1..79e88481178b2 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -6,21 +6,29 @@ import { import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; import type { AnyRouter } from "@tanstack/react-router"; import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities"; -import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; +import type { + AgentAlert, + EnvironmentId, + OrchestrationV2ThreadShell, + ThreadId, +} from "@t3tools/contracts"; import { monitorHoldsWakeCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import type { ClientSettings } from "@t3tools/contracts/settings"; import * as Option from "effect/Option"; -import type { AtomRegistry } from "effect/reactivity"; +import { AsyncResult, type AtomRegistry } from "effect/reactivity"; import { + BellIcon, CircleAlertIcon, CircleCheckIcon, MessageCircleQuestionIcon, ShieldQuestionIcon, } from "lucide-react"; +import type { ReactNode } from "react"; import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings"; import { isWindowsPlatform } from "../lib/utils"; import { environmentSummaries } from "../state/presentation"; +import { serverEnvironment } from "../state/server"; import { environmentShell } from "../state/shell"; import { environmentThreadShells } from "../state/threads"; import { @@ -128,72 +136,55 @@ export function startThreadNotifications( setNotificationBadge(0); }; - const present = ( + const show = ( environmentId: EnvironmentId, - state: NotificationState, - kind: ThreadNotificationKind, + threadId: ThreadId, + presentation: { + readonly title: string; + readonly body: string; + readonly sound: ThreadNotificationKind; + readonly toastType: "success" | "error" | "warning" | "info"; + readonly icon: ReactNode; + readonly tag: string; + readonly requireInteraction: boolean; + }, ) => { - const { thread, status } = state; if ( registry .get(environmentThreadShells.hiddenThreadKeysAtom) - .has(threadKey({ environmentId, threadId: thread.id })) + .has(threadKey({ environmentId, threadId })) ) return; const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings(); const active = activeThread(); - const title = - kind === "completion" - ? "Thread completed" - : status === "approval" - ? "Approval needed" - : status === "limited" - ? "Usage limit reached" - : status === "failed" - ? "Thread failed" - : status === "request" - ? "Guest request" - : "Input needed"; if (hasNotificationSound(mode)) { - void playNotificationSound(kind, () => + void playNotificationSound(presentation.sound, () => hasNotificationSound(getClientSettings().notificationMode), ); } + const openThread = () => + void router.navigate({ + to: "/$environmentId/$threadId", + params: { environmentId, threadId }, + }); if ( inAppNotificationsEnabled && document.visibilityState === "visible" && document.hasFocus() && - (active.environmentId !== environmentId || active.threadId !== thread.id) + (active.environmentId !== environmentId || active.threadId !== threadId) ) { - const toastKey = threadKey({ environmentId, threadId: thread.id }); + const toastKey = threadKey({ environmentId, threadId }); const toastId: ToastId = toastManager.add({ onRemove: (): void => forgetToast(toastKey, toastId), - type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning", - title, - description: thread.title, - data: { - hideCopyButton: true, - leadingIcon: - kind === "completion" ? ( - - ) : status === "approval" ? ( - - ) : status === "limited" ? ( - - ) : status === "failed" ? ( - - ) : ( - - ), - }, + type: presentation.toastType, + title: presentation.title, + description: presentation.body, + data: { hideCopyButton: true, leadingIcon: presentation.icon }, actionProps: { children: "Open thread", onClick: () => { toastManager.close(toastId); - void router.navigate({ - to: "/$environmentId/$threadId", - params: { environmentId, threadId: thread.id }, - }); + openThread(); }, }, }); @@ -208,28 +199,77 @@ export function startThreadNotifications( ) return; try { - const notification = new Notification(title, { - body: thread.title, - tag: threadNotificationTag(environmentId, thread.id), + const notification = new Notification(presentation.title, { + body: presentation.body, + tag: presentation.tag, silent: true, - // Windows drops clicks after a toast moves into Notification Center. - requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform), + requireInteraction: presentation.requireInteraction, }); - trackNotification(environmentId, thread.id, notification); + trackNotification(environmentId, threadId, notification); notification.addEventListener("click", () => { notification.close(); window.focus(); void window.desktopBridge?.revealWindow().catch(() => undefined); - void router.navigate({ - to: "/$environmentId/$threadId", - params: { environmentId, threadId: thread.id }, - }); + openThread(); }); } catch { // Some browsers expose Notification but reject desktop presentation. } }; + const present = ( + environmentId: EnvironmentId, + state: NotificationState, + kind: ThreadNotificationKind, + ) => { + const { thread, status } = state; + show(environmentId, thread.id, { + title: + kind === "completion" + ? "Thread completed" + : status === "approval" + ? "Approval needed" + : status === "limited" + ? "Usage limit reached" + : status === "failed" + ? "Thread failed" + : status === "request" + ? "Guest request" + : "Input needed", + body: thread.title, + sound: kind, + toastType: kind === "completion" ? "success" : status === "failed" ? "error" : "warning", + icon: + kind === "completion" ? ( + + ) : status === "approval" ? ( + + ) : status === "limited" ? ( + + ) : status === "failed" ? ( + + ) : ( + + ), + tag: threadNotificationTag(environmentId, thread.id), + // Windows drops clicks after a toast moves into Notification Center. + requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform), + }); + }; + + // An agent's own message, sent while its thread is still running, so no status change announces it. + const presentAgentAlert = (environmentId: EnvironmentId, alert: AgentAlert, title: string) => + show(environmentId, alert.threadId, { + title, + body: alert.body, + sound: "input", + toastType: "info", + icon: , + // Its own tag, so the thread's next status notification does not replace the message. + tag: `${threadNotificationTag(environmentId, alert.threadId)}:alert`, + requireInteraction: false, + }); + const observeThreads = ( environmentId: EnvironmentId, entry: WatchedEnvironment, @@ -349,10 +389,43 @@ export function startThreadNotifications( environmentThreadShells.delegatedUnderParentAtom, reobserve, ); + const subscribeAlerts = () => { + // The atom keeps its last alert, so the one it holds on subscribing is old, and each id + // is shown once. + let shownAlertId: string | null | undefined; + return registry.subscribe( + serverEnvironment.agentAlerts({ environmentId, input: {} }), + (result) => { + // Every value of a stream that is still open is `waiting`, so that flag says nothing here. + const alert = AsyncResult.isSuccess(result) ? result.value : null; + const seen = shownAlertId; + shownAlertId = alert?.id ?? null; + if (seen === undefined || alert === null || alert.id === seen) return; + const thread = threads?.find((candidate) => candidate.id === alert.threadId); + if (thread?.archivedAt != null) return; + presentAgentAlert(environmentId, alert, thread?.title || "T3 Code"); + }, + { immediate: true }, + ); + }; + // Older servers do not serve the stream, so follow it only where it is advertised. + let unsubscribeAlerts: (() => void) | null = null; + const unsubscribeConfig = registry.subscribe( + serverEnvironment.configValueAtom(environmentId), + (config) => { + const advertised = config?.environment.capabilities.agentAlerts === true; + if (advertised === (unsubscribeAlerts !== null)) return; + unsubscribeAlerts?.(); + unsubscribeAlerts = advertised ? subscribeAlerts() : null; + }, + { immediate: true }, + ); entry.unsubscribe = () => { unsubscribeShell(); unsubscribeRequests(); unsubscribeDelegated(); + unsubscribeConfig(); + unsubscribeAlerts?.(); entry.gate.clear(); }; return entry; diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index ee70400ca47a5..4490b70e36058 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -67,6 +67,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribeDiscoveredLocalServers | typeof WS_METHODS.subscribeDeviceState | typeof WS_METHODS.subscribeResourceTelemetry + | typeof WS_METHODS.subscribeAgentAlerts | typeof WS_METHODS.pullRequestsSubscribeRefreshes | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes | typeof WS_METHODS.subscribeVcsStatus diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index cbc4de0beac72..a7bb3fd1aa83f 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1546,6 +1546,12 @@ export function createServerEnvironmentAtoms( tag: WS_METHODS.subscribeResourceTelemetry, idleTtlMs: 0, }), + agentAlerts: createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:server:agent-alerts", + tag: WS_METHODS.subscribeAgentAlerts, + // Stream atoms publish only the last value per chunk; every alert must arrive. + transform: (stream) => stream.pipe(Stream.rechunk(1)), + }), resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:server:resource-telemetry-history", tag: WS_METHODS.serverGetResourceTelemetryHistory, diff --git a/packages/contracts/src/agentAlert.ts b/packages/contracts/src/agentAlert.ts new file mode 100644 index 0000000000000..c732fd1020794 --- /dev/null +++ b/packages/contracts/src/agentAlert.ts @@ -0,0 +1,12 @@ +import * as Schema from "effect/Schema"; + +import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** A message an agent asked to have shown to the user while its thread is still running. */ +export const AgentAlert = Schema.Struct({ + // Two alerts with the same text are still two alerts. + id: TrimmedNonEmptyString, + threadId: ThreadId, + body: TrimmedNonEmptyString, +}); +export type AgentAlert = typeof AgentAlert.Type; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index b1b014cbc1312..f833967f4aeda 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -170,6 +170,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ desktopAppChannelSwitch: Schema.optionalKey(Schema.Boolean), /** Subscribe to command output only when advertised; older servers never send it. */ commandOutputStreaming: Schema.optionalKey(Schema.Boolean), + /** Serves `subscribeAgentAlerts`; subscribe only when advertised. */ + agentAlerts: Schema.optionalKey(Schema.Boolean), /** Hosts headless Chromium tabs streamed over /api/preview-stream for clients without a local runtime. */ serverBrowser: Schema.optionalKey(Schema.Boolean), /** Server links to other environments (`PeerLink`) and its agents can work diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index c005fdd03900d..5cb1a60629348 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -54,6 +54,7 @@ export * from "./t3ProjectFile.ts"; export * from "./editor.ts"; export * from "./project.ts"; export * from "./filesystem.ts"; +export * from "./agentAlert.ts"; export * from "./agentSessions.ts"; export * from "./assets.ts"; export * from "./review.ts"; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index d4206b74f2f57..d8ebf69fd010e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -37,6 +37,7 @@ import * as Schema from "effect/Schema"; import * as Rpc from "effect/rpc/Rpc"; import * as RpcGroup from "effect/rpc/RpcGroup"; import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; +import { AgentAlert } from "./agentAlert.ts"; import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { SecretSourceCheckResult } from "./settingsSecretValue.ts"; import { SecretReference } from "./secretReference.ts"; @@ -668,6 +669,7 @@ export const WS_METHODS = { subscribeServerLifecycle: "subscribeServerLifecycle", subscribeAuthAccess: "subscribeAuthAccess", subscribeResourceTelemetry: "subscribeResourceTelemetry", + subscribeAgentAlerts: "subscribeAgentAlerts", } as const; const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, { @@ -2240,6 +2242,13 @@ const WsSubscribeResourceTelemetryRpc = Rpc.make(WS_METHODS.subscribeResourceTel stream: true, }); +const WsSubscribeAgentAlertsRpc = Rpc.make(WS_METHODS.subscribeAgentAlerts, { + payload: Schema.Struct({}), + success: AgentAlert, + error: EnvironmentAuthorizationError, + stream: true, +}); + export class RpcScopeAuthorization extends RpcMiddleware.Service()( "t3/contracts/RpcScopeAuthorization", { error: EnvironmentAuthorizationError }, @@ -2457,6 +2466,7 @@ export const WsRpcGroup = RpcGroup.make( WsSubscribeServerLifecycleRpc, WsSubscribeAuthAccessRpc, WsSubscribeResourceTelemetryRpc, + WsSubscribeAgentAlertsRpc, WsOrchestrationV2DispatchCommandRpc, WsOrchestrationV2GetWorkflowScriptRpc, WsOrchestrationV2GetNativeChildWorkRpc, From 7538a4cd4e198c4eed5d4a4e04e90844c13d997d Mon Sep 17 00:00:00 2001 From: MarconLP <13001502+MarconLP@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:19:34 +0000 Subject: [PATCH 2/7] fix(web): agent alerts stop when notifications are off or the thread is archived The alert stream now closes as soon as the client stops following it, so the server no longer tells the agent an alert was shown during the five-minute idle window. An alert for a thread that is not on the live list (archived or deleted) is not shown. --- .../ThreadNotificationCoordinator.badge.browser.test.ts | 3 +-- apps/web/src/components/ThreadNotificationCoordinator.tsx | 5 +++-- packages/client-runtime/src/state/server.ts | 3 +++ 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 3119114c33141..25dc35648da4e 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -490,9 +490,8 @@ it("shows an agent's alert once as a desktop notification that opens its thread" expect(TestNotification.sent.map(({ title, options }) => [title, options.body])).toEqual([ ["Test thread", "fleet.lock stuck"], - ["T3 Code", "fleet.lock stuck"], ]); - expect(state.badge).toHaveBeenLastCalledWith(2); + expect(state.badge).toHaveBeenLastCalledWith(1); TestNotification.sent[0]!.dispatchEvent(new Event("click")); expect(state.navigate).toHaveBeenCalledWith({ to: "/$environmentId/$threadId", diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 79e88481178b2..67f537ab8b6df 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -402,8 +402,9 @@ export function startThreadNotifications( shownAlertId = alert?.id ?? null; if (seen === undefined || alert === null || alert.id === seen) return; const thread = threads?.find((candidate) => candidate.id === alert.threadId); - if (thread?.archivedAt != null) return; - presentAgentAlert(environmentId, alert, thread?.title || "T3 Code"); + // An archived thread never notifies, and archiving takes it off the live list. + if (thread === undefined || thread.archivedAt !== null) return; + presentAgentAlert(environmentId, alert, thread.title || "T3 Code"); }, { immediate: true }, ); diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index a7bb3fd1aa83f..3d81776f3a78f 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1549,6 +1549,9 @@ export function createServerEnvironmentAtoms( agentAlerts: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:server:agent-alerts", tag: WS_METHODS.subscribeAgentAlerts, + // The server tells the agent an alert was shown while this stream is open, so it must + // close as soon as nothing follows it. + idleTtlMs: 0, // Stream atoms publish only the last value per chunk; every alert must arrive. transform: (stream) => stream.pipe(Stream.rechunk(1)), }), From 9ffe79a51382f33ebd9445941aec971d90efd634 Mon Sep 17 00:00:00 2001 From: MarconLP <13001502+MarconLP@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:31:23 +0000 Subject: [PATCH 3/7] fix(server): tell Claude its alert was passed to a client, not shown The server knows a client is following the alert stream, not that the client put the alert on screen: the client stays quiet when the thread is open, hidden or archived. --- apps/server/src/notifications/AgentAlerts.ts | 5 ++++- .../orchestration-v2/Adapters/claudePushNotification.test.ts | 2 +- .../src/orchestration-v2/Adapters/claudePushNotification.ts | 5 +++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/server/src/notifications/AgentAlerts.ts b/apps/server/src/notifications/AgentAlerts.ts index 02f63731b85fe..26083ad561ac8 100644 --- a/apps/server/src/notifications/AgentAlerts.ts +++ b/apps/server/src/notifications/AgentAlerts.ts @@ -9,7 +9,10 @@ import * as Stream from "effect/Stream"; export class AgentAlerts extends Context.Service< AgentAlerts, { - /** Hands the alert to every subscribed client. False when none is subscribed. */ + /** + * Hands the alert to every subscribed client. False when none is subscribed. True means a + * client took it, not that it put it on screen. + */ readonly offer: (alert: AgentAlert) => Effect.Effect; readonly stream: Stream.Stream; } diff --git a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts index 7b509221d86f9..a59046129bfd1 100644 --- a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts @@ -50,7 +50,7 @@ describe("claudePushNotification", () => { sentAt: "2026-11-17T12:00:00.000Z", }, additionalContext: - "T3 Code showed this notification on the user's connected T3 Code client.", + "T3 Code passed this notification to a connected T3 Code client with notifications on. That client shows it unless the user already has this thread open.", }, }); NodeAssert.deepEqual(delivered, [{ id: "tool-1", body: "fleet.lock stuck" }]); diff --git a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts index aa336321eedb8..c75710c37144d 100644 --- a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts @@ -33,7 +33,8 @@ function toolOutput(toolResponse: ToolResponse, delivered: boolean): SyncHookJSO hookEventName: "PostToolUse", // Claude Code writes the model's result text from these fields and ignores `message`. // `no_transport` is its closest wording: a local notification was or was not sent, and - // no mobile push was. `additionalContext` tells the model what T3 did. + // no mobile push was. `additionalContext` tells the model what T3 did: it knows a client + // took the alert, not that the client put it on screen. updatedToolOutput: { ...toolResponse, message: delivered @@ -44,7 +45,7 @@ function toolOutput(toolResponse: ToolResponse, delivered: boolean): SyncHookJSO disabledReason: "no_transport", }, additionalContext: delivered - ? "T3 Code showed this notification on the user's connected T3 Code client." + ? "T3 Code passed this notification to a connected T3 Code client with notifications on. That client shows it unless the user already has this thread open." : "This notification reached nobody: no T3 Code client with notifications on is connected.", }, }; From e92eb8921bae04b154dd89a1bc45c7ac3662dcf1 Mon Sep 17 00:00:00 2001 From: MarconLP <13001502+MarconLP@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:35:13 +0000 Subject: [PATCH 4/7] fix(server): say an alert's presentation is not confirmed --- .../orchestration-v2/Adapters/claudePushNotification.test.ts | 2 +- .../src/orchestration-v2/Adapters/claudePushNotification.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts index a59046129bfd1..fd709232eaa2e 100644 --- a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.test.ts @@ -50,7 +50,7 @@ describe("claudePushNotification", () => { sentAt: "2026-11-17T12:00:00.000Z", }, additionalContext: - "T3 Code passed this notification to a connected T3 Code client with notifications on. That client shows it unless the user already has this thread open.", + "T3 Code passed this notification to a connected T3 Code client with notifications on. Whether that client put it on screen is not confirmed.", }, }); NodeAssert.deepEqual(delivered, [{ id: "tool-1", body: "fleet.lock stuck" }]); diff --git a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts index c75710c37144d..c8808c0c6eacd 100644 --- a/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts @@ -45,7 +45,7 @@ function toolOutput(toolResponse: ToolResponse, delivered: boolean): SyncHookJSO disabledReason: "no_transport", }, additionalContext: delivered - ? "T3 Code passed this notification to a connected T3 Code client with notifications on. That client shows it unless the user already has this thread open." + ? "T3 Code passed this notification to a connected T3 Code client with notifications on. Whether that client put it on screen is not confirmed." : "This notification reached nobody: no T3 Code client with notifications on is connected.", }, }; From 3eba2f3052751dbd7f36af64737846ae24ef730a Mon Sep 17 00:00:00 2001 From: MarconLP <13001502+MarconLP@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:49:21 +0000 Subject: [PATCH 5/7] fix(server): count an alert subscriber and register its cleanup in one step --- apps/server/src/notifications/AgentAlerts.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/server/src/notifications/AgentAlerts.ts b/apps/server/src/notifications/AgentAlerts.ts index 26083ad561ac8..3914e81aaeac5 100644 --- a/apps/server/src/notifications/AgentAlerts.ts +++ b/apps/server/src/notifications/AgentAlerts.ts @@ -27,8 +27,11 @@ const make = Effect.gen(function* () { // Subscribe before counting: counted first, an offer in between reports a // delivery that the subscription never receives. const subscription = yield* PubSub.subscribe(alerts); - yield* Ref.update(subscribers, (count) => count + 1); - yield* Effect.addFinalizer(() => Ref.update(subscribers, (count) => count - 1)); + // One step, so an interrupt cannot leave the count raised with no cleanup registered. + yield* Effect.acquireRelease( + Ref.update(subscribers, (count) => count + 1), + () => Ref.update(subscribers, (count) => count - 1), + ); return Stream.fromSubscription(subscription); }), ); From edf8eb69e70ddf086987946d8e1fabd71079ea05 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 18 Nov 2026 12:08:02 +0000 Subject: [PATCH 6/7] fix(web): silence agent alerts for the focused thread --- ...hreadNotificationCoordinator.badge.browser.test.ts | 2 ++ .../src/components/ThreadNotificationCoordinator.tsx | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 25dc35648da4e..315b0dab75f8d 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -519,6 +519,7 @@ it("keeps an agent's alert on screen when its thread then completes", async () = it("toasts an agent's alert in the focused app unless its thread is the open one", async () => { await using app = setup(); + state.mode = "notifications-and-sound"; state.inApp = true; focused = true; state.shells.set("one", shell({}, { id: "other", title: "Other thread" })); @@ -526,6 +527,7 @@ it("toasts an agent's alert in the focused app unless its thread is the open one app.openThread("one", "thread"); app.alert("one", { id: "tool-1", threadId: "thread", body: "fleet.lock stuck" }); expect(state.toast).not.toHaveBeenCalled(); + expect(state.sound).not.toHaveBeenCalled(); app.alert("one", { id: "tool-2", threadId: "other", body: "needs a push guard" }); expect(state.toast).toHaveBeenCalledExactlyOnceWith( diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index bc77790a52da1..a72d353cbd0c9 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -260,7 +260,15 @@ export function startThreadNotifications( }; // An agent's own message, sent while its thread is still running, so no status change announces it. - const presentAgentAlert = (environmentId: EnvironmentId, alert: AgentAlert, title: string) => + const presentAgentAlert = (environmentId: EnvironmentId, alert: AgentAlert, title: string) => { + const active = activeThread(); + if ( + document.visibilityState === "visible" && + document.hasFocus() && + active.environmentId === environmentId && + active.threadId === alert.threadId + ) + return; show(environmentId, alert.threadId, { title, body: alert.body, @@ -271,6 +279,7 @@ export function startThreadNotifications( tag: `${threadNotificationTag(environmentId, alert.threadId)}:alert`, requireInteraction: false, }); + }; const observeThreads = ( environmentId: EnvironmentId, From e83b4f19b4f6f93510929e3faa34827def0c781c Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 18 Nov 2026 12:28:26 +0000 Subject: [PATCH 7/7] fix(web): retain agent alerts during shell synchronization --- ...ificationCoordinator.badge.browser.test.ts | 8 +++++++- .../ThreadNotificationCoordinator.tsx | 20 ++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 315b0dab75f8d..1c2ad5bf90103 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -478,11 +478,15 @@ it("shows an agent's alert once as a desktop notification that opens its thread" await using app = setup(); // Left in the atom by an earlier subscription. app.alert("one", { id: "tool-0", threadId: "thread", body: "already shown" }); + state.shells.set("one", { ...shell(), status: "synchronizing" }); app.start(); const alert = { id: "tool-1", threadId: "thread", body: "fleet.lock stuck" }; app.alert("one", alert); + expect(TestNotification.sent).toEqual([]); + state.shells.set("one", shell()); // A reconnect replays the last alert the stream held. app.alert("one", { ...alert }); + app.alert("one", { ...alert, id: "tool-1b", body: "another alert" }); app.alert("one", { ...alert, id: "tool-2", threadId: "gone" }); app.alert("two", { ...alert, id: "tool-3" }); state.shells.set("one", shell({ archivedAt: "2026-09-13T07:00:00.000Z" })); @@ -490,8 +494,10 @@ it("shows an agent's alert once as a desktop notification that opens its thread" expect(TestNotification.sent.map(({ title, options }) => [title, options.body])).toEqual([ ["Test thread", "fleet.lock stuck"], + ["Test thread", "another alert"], ]); - expect(state.badge).toHaveBeenLastCalledWith(1); + expect(state.badge).toHaveBeenLastCalledWith(2); + expect(TestNotification.sent[0]!.close).not.toHaveBeenCalled(); TestNotification.sent[0]!.dispatchEvent(new Event("click")); expect(state.navigate).toHaveBeenCalledWith({ to: "/$environmentId/$threadId", diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index a72d353cbd0c9..cbe9f22e611eb 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -276,7 +276,7 @@ export function startThreadNotifications( toastType: "info", icon: , // Its own tag, so the thread's next status notification does not replace the message. - tag: `${threadNotificationTag(environmentId, alert.threadId)}:alert`, + tag: `${threadNotificationTag(environmentId, alert.threadId)}:alert:${alert.id}`, requireInteraction: false, }); }; @@ -373,6 +373,17 @@ export function startThreadNotifications( }), }; let threads: ReadonlyArray | null = null; + const pendingAlerts: Array = []; + const receiveAlert = (alert: AgentAlert) => { + if (threads === null) { + if (pendingAlerts.length === 32) pendingAlerts.shift(); + pendingAlerts.push(alert); + return; + } + const thread = threads.find((candidate) => candidate.id === alert.threadId); + if (thread === undefined || thread.archivedAt !== null) return; + presentAgentAlert(environmentId, alert, thread.title || "T3 Code"); + }; const unsubscribeShell = registry.subscribe( environmentShell.stateValueAtom(environmentId), (shell) => { @@ -382,6 +393,7 @@ export function startThreadNotifications( : null; if (threads !== null) { observeThreads(environmentId, entry, threads); + pendingAlerts.splice(0).forEach(receiveAlert); return; } entry.reconnecting = true; @@ -412,10 +424,7 @@ export function startThreadNotifications( const seen = shownAlertId; shownAlertId = alert?.id ?? null; if (seen === undefined || alert === null || alert.id === seen) return; - const thread = threads?.find((candidate) => candidate.id === alert.threadId); - // An archived thread never notifies, and archiving takes it off the live list. - if (thread === undefined || thread.archivedAt !== null) return; - presentAgentAlert(environmentId, alert, thread.title || "T3 Code"); + receiveAlert(alert); }, { immediate: true }, ); @@ -438,6 +447,7 @@ export function startThreadNotifications( unsubscribeDelegated(); unsubscribeConfig(); unsubscribeAlerts?.(); + pendingAlerts.length = 0; entry.gate.clear(); }; return entry;