Skip to content

Commit 7a67dfe

Browse files
fix: monitor wakes no longer fire a completion alert per line
Claude wakes the agent once per Monitor output line, and each wake is a new run that completes while the monitor is still pending. Every one fired a desktop "Thread completed" notification with sound and a push completion, so a chatty monitor produced one alert per line. The thread shell now carries latestRunBackgroundWake, derived from the latest run's trigger message: true only for a provider background wake (background task, command or monitor notification, not a delegated completion, and no follow-up the user steered into the run). While such a run has a monitor pending, the web notification gate holds its completion and push awareness reports the thread as running. When the monitor leaves, the newest completion alerts once; a completion released this way waits the same 5 s grace the push relay uses, so a terminal wake that starts right after the roster drains does not alert twice. Runs started any other way alert as before. Fixes #32497
1 parent e455200 commit 7a67dfe

10 files changed

Lines changed: 336 additions & 8 deletions

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,103 @@ it.effect("record reads filter notification sources without dropping matching me
771771
}).pipe(Effect.provide(layerTest)),
772772
);
773773

774+
it.effect("shells flag a latest run triggered by a provider background wake", () =>
775+
Effect.gen(function* () {
776+
const store = yield* ProjectionStore.ProjectionStoreV2;
777+
const threadId = yield* addRolledBackRecoveryCandidate("background-wake");
778+
const initial = yield* store.getThreadProjection(threadId);
779+
const at = initial.updatedAt;
780+
let ordinal = 1;
781+
for (const [id, source, expected] of [
782+
["background-task", { kind: "background_task" }, true],
783+
["monitor", { kind: "monitor" }, true],
784+
["command", { kind: "command" }, true],
785+
["subagent", { kind: "subagent" }, false],
786+
["delegated", { kind: "delegated_task", taskIds: [] }, false],
787+
["steered", { kind: "background_task" }, false],
788+
] as const) {
789+
const messageId = MessageId.make(`message:background-wake:${id}`);
790+
yield* store.apply({
791+
id: EventId.make(`event:background-wake:${id}:message`),
792+
type: "message.updated",
793+
threadId,
794+
occurredAt: at,
795+
payload: {
796+
id: messageId,
797+
threadId,
798+
runId: null,
799+
nodeId: null,
800+
createdBy: "agent",
801+
creationSource: "server",
802+
role: "user",
803+
text: id,
804+
attachments: [],
805+
streaming: false,
806+
createdAt: at,
807+
updatedAt: at,
808+
notification: { source, outcome: "updated", summary: "Background activity updated" },
809+
...(id === "delegated"
810+
? {
811+
delegatedCompletion: {
812+
parentRunId: initial.runs[0]!.id,
813+
generation: 1,
814+
taskIds: [],
815+
},
816+
}
817+
: {}),
818+
},
819+
});
820+
ordinal += 1;
821+
yield* store.apply({
822+
id: EventId.make(`event:background-wake:${id}:run`),
823+
type: "run.created",
824+
threadId,
825+
occurredAt: at,
826+
payload: {
827+
...initial.runs[0]!,
828+
id: RunId.make(`run:background-wake:${id}`),
829+
ordinal,
830+
userMessageId: messageId,
831+
status: "completed",
832+
completedAt: at,
833+
},
834+
});
835+
if (id === "steered") {
836+
yield* store.apply({
837+
id: EventId.make("event:background-wake:steered:follow-up"),
838+
type: "message.updated",
839+
threadId,
840+
occurredAt: at,
841+
payload: {
842+
id: MessageId.make("message:background-wake:steered:follow-up"),
843+
threadId,
844+
runId: RunId.make("run:background-wake:steered"),
845+
nodeId: null,
846+
createdBy: "user",
847+
creationSource: "web",
848+
role: "user",
849+
text: "also fix X",
850+
attachments: [],
851+
streaming: false,
852+
createdAt: at,
853+
updatedAt: at,
854+
},
855+
});
856+
}
857+
const shells = [
858+
yield* store.getThreadShell(threadId),
859+
ProjectionStore.threadShellFromProjection(yield* store.getThreadProjection(threadId)),
860+
];
861+
assert.deepEqual(
862+
shells.map((shell) => shell?.latestRunBackgroundWake),
863+
[expected, expected],
864+
id,
865+
);
866+
yield* assertShellIndexCoversShells();
867+
}
868+
}).pipe(Effect.provide(layerTest)),
869+
);
870+
774871
it.effect("SQL queue readiness skips held runs without bypassing active work", () =>
775872
Effect.gen(function* () {
776873
const store = yield* ProjectionStore.ProjectionStoreV2;

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1025,6 +1025,7 @@ type ShellThreadRow = {
10251025
readonly latest_run_started_at: string | null;
10261026
readonly latest_run_completed_at: string | null;
10271027
readonly latest_run_stop_requested: number;
1028+
readonly latest_run_background_wake: number;
10281029
readonly active_run_id: string | null;
10291030
readonly active_run_status: string | null;
10301031
readonly activity_run_status: string | null;
@@ -1036,6 +1037,7 @@ type ShellThreadRow = {
10361037
readonly blocking_run_started_at: string | null;
10371038
readonly blocking_run_completed_at: string | null;
10381039
readonly blocking_run_stop_requested: number;
1040+
readonly blocking_run_background_wake: number;
10391041
readonly blocking_failure_payload_json: string | null;
10401042
readonly pending_request_payload_json: string | null;
10411043
readonly pending_secret_request_payload_json: string | null;
@@ -1651,6 +1653,8 @@ export function threadShellFromProjection(
16511653
projection.turnItems.some(
16521654
(item) => item.runId === latestRun.id && item.type === "run_interrupt_request",
16531655
),
1656+
latestRunBackgroundWake:
1657+
latestRun != null && isBackgroundWakeRunForShell(latestRun, projection),
16541658
activeRunId: activeRun?.id ?? null,
16551659
blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
16561660
activityRunStatus: activityRun?.status ?? null,
@@ -1746,6 +1750,23 @@ function isSilentRunForShell(
17461750
);
17471751
}
17481752

1753+
const BACKGROUND_WAKE_SOURCE_KINDS = new Set(["background_task", "command", "monitor"]);
1754+
1755+
function isBackgroundWakeRunForShell(
1756+
run: OrchestrationV2ThreadProjection["runs"][number],
1757+
projection: Pick<OrchestrationV2ThreadProjection, "messages">,
1758+
): boolean {
1759+
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1760+
return (
1761+
message?.delegatedCompletion === undefined &&
1762+
BACKGROUND_WAKE_SOURCE_KINDS.has(message?.notification?.source.kind ?? "") &&
1763+
// A follow-up the user steered into the wake makes the run theirs.
1764+
!projection.messages.some(
1765+
(candidate) => candidate.runId === run.id && candidate.createdBy === "user",
1766+
)
1767+
);
1768+
}
1769+
17491770
function isInterruptibleRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
17501771
return run.status === "preparing" || run.status === "starting" || run.status === "running";
17511772
}
@@ -1768,6 +1789,7 @@ type ShellThreadState = {
17681789
readonly latestRunStartedAt: DateTime.Utc | null;
17691790
readonly latestRunCompletedAt: DateTime.Utc | null;
17701791
readonly latestRunStopRequested: boolean;
1792+
readonly latestRunBackgroundWake: boolean;
17711793
readonly activeRunId: RunId | null;
17721794
readonly blockedOnThreadWait: boolean;
17731795
readonly activityRunStatus: ShellActivityRunStatus | null;
@@ -1928,6 +1950,7 @@ function shellFromState(input: {
19281950
latestRunStartedAt: input.state.latestRunStartedAt,
19291951
latestRunCompletedAt: input.state.latestRunCompletedAt,
19301952
latestRunStopRequested: input.state.latestRunStopRequested,
1953+
latestRunBackgroundWake: input.state.latestRunBackgroundWake,
19311954
activeRunId: input.state.activeRunId,
19321955
blockedOnThreadWait: input.state.blockedOnThreadWait,
19331956
activityRunStatus: input.state.activityRunStatus,
@@ -6188,6 +6211,24 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
61886211
)`;
61896212
};
61906213

6214+
// Mirrors isBackgroundWakeRunForShell. Stored sources keep the legacy encoding, where a
6215+
// command is background_command and a subagent is background_task with work "subagent".
6216+
const isBackgroundWakeShellRun = (alias: string) => {
6217+
const run = sql.literal(alias);
6218+
return sql`EXISTS (
6219+
SELECT 1 FROM orchestration_v2_projection_messages wake
6220+
WHERE wake.message_id = json_extract(${run}.payload_json, '$.userMessageId')
6221+
AND json_extract(wake.payload_json, '$.notification.source.kind')
6222+
IN ('background_task', 'background_command', 'command', 'monitor')
6223+
AND json_extract(wake.payload_json, '$.notification.source.work') IS NULL
6224+
AND json_extract(wake.payload_json, '$.delegatedCompletion') IS NULL
6225+
) AND NOT EXISTS (
6226+
SELECT 1 FROM orchestration_v2_projection_messages steer
6227+
WHERE steer.run_id = ${run}.run_id
6228+
AND json_extract(steer.payload_json, '$.createdBy') = 'user'
6229+
)`;
6230+
};
6231+
61916232
const selectShellThreadRows = (
61926233
threadId?: ThreadId,
61936234
{
@@ -6220,6 +6261,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
62206261
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = presented.run_id
62216262
AND stop_request.type = 'run_interrupt_request'
62226263
) AS latest_run_stop_requested,
6264+
${isBackgroundWakeShellRun("presented")} AS latest_run_background_wake,
62236265
active.run_id AS active_run_id,
62246266
active.status AS active_run_status,
62256267
(
@@ -6277,6 +6319,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
62776319
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = blocked.run_id
62786320
AND stop_request.type = 'run_interrupt_request'
62796321
) AS blocking_run_stop_requested,
6322+
${isBackgroundWakeShellRun("blocked")} AS blocking_run_background_wake,
62806323
(
62816324
SELECT item.payload_json
62826325
FROM orchestration_v2_projection_turn_items item
@@ -6860,6 +6903,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
68606903
? null
68616904
: DateTime.makeUnsafe(row.latest_run_completed_at);
68626905
let latestRunStopRequested = row.latest_run_stop_requested === 1;
6906+
let latestRunBackgroundWake = row.latest_run_background_wake === 1;
68636907
if (row.blocking_run_id !== null && row.blocking_failure_payload_json !== null) {
68646908
const blockingFailure = yield* decodeTurnItemPayload(
68656909
row.blocking_failure_payload_json,
@@ -6873,6 +6917,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
68736917
terminalFailureItem = blockingFailure;
68746918
latestRunId = RunId.make(row.blocking_run_id);
68756919
latestRunStopRequested = row.blocking_run_stop_requested === 1;
6920+
latestRunBackgroundWake = row.blocking_run_background_wake === 1;
68766921
latestRunStatus = "failed";
68776922
latestRunRequestedAt =
68786923
row.blocking_run_requested_at === null
@@ -6913,6 +6958,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
69136958
latestRunStartedAt,
69146959
latestRunCompletedAt,
69156960
latestRunStopRequested,
6961+
latestRunBackgroundWake,
69166962
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
69176963
blockedOnThreadWait: deriveBlockedOnThreadWait({
69186964
activeRun:
@@ -7182,6 +7228,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
71827228
activityRunStatus: state.activityRunStatus,
71837229
latestRunCompletedAt: state.latestRunCompletedAt,
71847230
latestRunStopRequested: state.latestRunStopRequested,
7231+
latestRunBackgroundWake: state.latestRunBackgroundWake,
71857232
pendingRuntimeRequest: state.pendingRuntimeRequest,
71867233
pendingBackgroundTasks: state.pendingBackgroundTasks,
71877234
})),

‎apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import * as Option from "effect/Option";
55
import { Atom, AtomRegistry } from "effect/reactivity";
66
import { expect, it, vi } from "vite-plus/test";
77

8-
import { stubGlobal } from "../../test/render";
8+
import { fakeTimers, stubGlobal } from "../../test/render";
9+
import { RELEASED_COMPLETION_GRACE_MS } from "./ThreadNotificationCoordinator.logic";
910

1011
const state = vi.hoisted(() => ({
1112
mode: "notifications",
@@ -254,6 +255,53 @@ it("presents completion notifications and sound as soon as the shell completes",
254255
expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
255256
});
256257

258+
it("presents one completion when a monitor ends with a final wake", async () => {
259+
await using app = setup();
260+
using _timers = fakeTimers();
261+
state.mode = "notifications-and-sound";
262+
app.start();
263+
const watching = (
264+
turnId: string,
265+
turnState: string,
266+
completedAt: string | null,
267+
latestRunBackgroundWake: boolean,
268+
pendingBackgroundTasks: ReadonlyArray<{ taskId: string; kind: "monitor" }>,
269+
) => ({
270+
status: "live",
271+
snapshot: Option.some({
272+
threads: [
273+
{
274+
...toV2ThreadShell({ ...thread, latestTurn: { turnId, state: turnState, completedAt } }),
275+
latestRunBackgroundWake,
276+
pendingBackgroundTasks,
277+
},
278+
],
279+
}),
280+
});
281+
const monitor = [{ taskId: "watch", kind: "monitor" as const }];
282+
const titles = () => TestNotification.sent.map(({ title }) => title);
283+
state.shells.set(
284+
"one",
285+
watching("turn", "completed", "2026-09-13T07:00:01.000Z", false, monitor),
286+
);
287+
expect(titles()).toEqual(["Thread completed"]);
288+
289+
state.shells.set("one", watching("wake", "running", null, true, monitor));
290+
state.shells.set("one", watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, monitor));
291+
expect(titles()).toEqual(["Thread completed"]);
292+
293+
// The adapter drains the roster before the final wake starts.
294+
state.shells.set("one", watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, []));
295+
expect(titles()).toEqual(["Thread completed"]);
296+
297+
state.shells.set("one", watching("final", "running", null, true, []));
298+
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
299+
state.shells.set("one", watching("final", "completed", "2026-09-13T07:00:11.000Z", true, []));
300+
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
301+
expect(titles()).toEqual(["Thread completed", "Thread completed"]);
302+
expect(state.sound).toHaveBeenCalledTimes(2);
303+
});
304+
257305
it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
258306
"notifies for offline completion and %s once across reconnects",
259307
async (flag) => {

0 commit comments

Comments
 (0)