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..3914e81aaeac5 --- /dev/null +++ b/apps/server/src/notifications/AgentAlerts.ts @@ -0,0 +1,48 @@ +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. True means a + * client took it, not that it put it on screen. + */ + 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); + // 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); + }), + ); + + 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 2974c1a81ab2b..8ad01e9372aa3 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] }, + ], + }), }, } : {}), @@ -5588,6 +5601,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) @@ -12758,6 +12772,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: @@ -12933,6 +12955,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..fd709232eaa2e --- /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 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" }]); + }); + + 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..c8808c0c6eacd --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/claudePushNotification.ts @@ -0,0 +1,75 @@ +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: it knows a client + // took the alert, not that the client put it on screen. + 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 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.", + }, + }; +} + +/** + * 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..1c2ad5bf90103 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,75 @@ 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" }); + 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" })); + app.alert("one", { ...alert, id: "tool-4" }); + + expect(TestNotification.sent.map(({ title, options }) => [title, options.body])).toEqual([ + ["Test thread", "fleet.lock stuck"], + ["Test thread", "another alert"], + ]); + 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", + 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.mode = "notifications-and-sound"; + 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(); + expect(state.sound).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 e2801c97d6e8d..cbe9f22e611eb 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -8,21 +8,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 { @@ -130,72 +138,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" - ? m(msg("Thread completed")) - : status === "approval" - ? m(msg("Approval needed")) - : status === "limited" - ? m(msg("Usage limit reached")) - : status === "failed" - ? m(msg("Thread failed")) - : status === "request" - ? m(msg("Guest request")) - : m(msg("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: m(msg("Open thread")), onClick: () => { toastManager.close(toastId); - void router.navigate({ - to: "/$environmentId/$threadId", - params: { environmentId, threadId: thread.id }, - }); + openThread(); }, }, }); @@ -210,28 +201,86 @@ 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" + ? m(msg("Thread completed")) + : status === "approval" + ? m(msg("Approval needed")) + : status === "limited" + ? m(msg("Usage limit reached")) + : status === "failed" + ? m(msg("Thread failed")) + : status === "request" + ? m(msg("Guest request")) + : m(msg("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) => { + 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, + 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:${alert.id}`, + requireInteraction: false, + }); + }; + const observeThreads = ( environmentId: EnvironmentId, entry: WatchedEnvironment, @@ -324,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) => { @@ -333,6 +393,7 @@ export function startThreadNotifications( : null; if (threads !== null) { observeThreads(environmentId, entry, threads); + pendingAlerts.splice(0).forEach(receiveAlert); return; } entry.reconnecting = true; @@ -351,10 +412,42 @@ 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; + receiveAlert(alert); + }, + { 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?.(); + pendingAlerts.length = 0; entry.gate.clear(); }; return entry; diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 7c8f06cb1f083..f4a98e2bf99e4 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -77,6 +77,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 cb02405722fe0..3afecea38a623 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1621,6 +1621,15 @@ export function createServerEnvironmentAtoms( tag: WS_METHODS.subscribeResourceTelemetry, idleTtlMs: 0, }), + 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)), + }), 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,