Skip to content
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<WsRpcMethod, AuthEnvironmentScope>>;

Expand Down
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ export const make = Effect.gen(function* () {
threadProjectFromScratch: true,
threadTitleRegeneration: true,
commandOutputStreaming: true,
agentAlerts: true,
threadVisitedTracking: true,
threadPullRequests: true,
threadPullRequestWatch: true,
Expand Down
50 changes: 50 additions & 0 deletions apps/server/src/notifications/AgentAlerts.test.ts
Original file line number Diff line number Diff line change
@@ -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<AgentAlert>();
const second = yield* Queue.unbounded<AgentAlert>();
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),
);
});
48 changes: 48 additions & 0 deletions apps/server/src/notifications/AgentAlerts.ts
Original file line number Diff line number Diff line change
@@ -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<boolean>;
readonly stream: Stream.Stream<AgentAlert>;
}
>()("t3/notifications/AgentAlerts") {}

const make = Effect.gen(function* () {
const subscribers = yield* Ref.make(0);
const alerts = yield* PubSub.unbounded<AgentAlert>();

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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});

return AgentAlerts.of({ offer, stream });
});

export const layer = Layer.effect(AgentAlerts, make);
1 change: 1 addition & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Record<WsRpcMethod, string>>;

Expand Down
25 changes: 24 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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] },
],
}),
},
}
: {}),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -12933,6 +12955,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
onUserDialog,
onElicitation,
onStop,
onPushNotification,
supportedDialogKinds: ["resume_return"],
...(appendSystemPromptFileText === undefined ? {} : { appendSystemPromptFileText }),
...(toolSearchOverride === undefined ? {} : { toolSearchOverride }),
Expand Down
Original file line number Diff line number Diff line change
@@ -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<typeof makeClaudePushNotificationHook>,
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<string> = [];
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<string> = [];
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, []);
});
});
Original file line number Diff line number Diff line change
@@ -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<Record<string, unknown>>;

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<boolean>,
): 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 }));
};
}
Loading
Loading