Skip to content

Commit 20723d6

Browse files
fix: Claude monitor wakes no longer fire a completion alert per line (pingdotgg#32520)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 524a531 commit 20723d6

10 files changed

Lines changed: 407 additions & 16 deletions

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

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -827,6 +827,105 @@ it.effect("record reads filter notification sources without dropping matching me
827827
}).pipe(Effect.provide(layerTest)),
828828
);
829829

830+
it.effect("shells flag a latest run triggered by a provider background wake", () =>
831+
Effect.gen(function* () {
832+
const store = yield* ProjectionStore.ProjectionStoreV2;
833+
const threadId = yield* addRolledBackRecoveryCandidate("background-wake");
834+
const initial = yield* store.getThreadProjection(threadId);
835+
const at = initial.updatedAt;
836+
let ordinal = 1;
837+
for (const [id, source, outcome, expected] of [
838+
["background-task", { kind: "background_task" }, "updated", true],
839+
["monitor", { kind: "monitor" }, "updated", true],
840+
["command", { kind: "command" }, "updated", true],
841+
["command-finished", { kind: "command" }, "completed", false],
842+
["monitor-stopped", { kind: "monitor" }, "cancelled", false],
843+
["subagent", { kind: "subagent" }, "updated", false],
844+
["delegated", { kind: "delegated_task", taskIds: [] }, "updated", false],
845+
["steered", { kind: "background_task" }, "updated", false],
846+
] as const) {
847+
const messageId = MessageId.make(`message:background-wake:${id}`);
848+
yield* store.apply({
849+
id: EventId.make(`event:background-wake:${id}:message`),
850+
type: "message.updated",
851+
threadId,
852+
occurredAt: at,
853+
payload: {
854+
id: messageId,
855+
threadId,
856+
runId: null,
857+
nodeId: null,
858+
createdBy: "agent",
859+
creationSource: "server",
860+
role: "user",
861+
text: id,
862+
attachments: [],
863+
streaming: false,
864+
createdAt: at,
865+
updatedAt: at,
866+
notification: { source, outcome, summary: "Background activity updated" },
867+
...(id === "delegated"
868+
? {
869+
delegatedCompletion: {
870+
parentRunId: initial.runs[0]!.id,
871+
generation: 1,
872+
taskIds: [],
873+
},
874+
}
875+
: {}),
876+
},
877+
});
878+
ordinal += 1;
879+
yield* store.apply({
880+
id: EventId.make(`event:background-wake:${id}:run`),
881+
type: "run.created",
882+
threadId,
883+
occurredAt: at,
884+
payload: {
885+
...initial.runs[0]!,
886+
id: RunId.make(`run:background-wake:${id}`),
887+
ordinal,
888+
userMessageId: messageId,
889+
status: "completed",
890+
completedAt: at,
891+
},
892+
});
893+
if (id === "steered") {
894+
yield* store.apply({
895+
id: EventId.make("event:background-wake:steered:follow-up"),
896+
type: "message.updated",
897+
threadId,
898+
occurredAt: at,
899+
payload: {
900+
id: MessageId.make("message:background-wake:steered:follow-up"),
901+
threadId,
902+
runId: RunId.make("run:background-wake:steered"),
903+
nodeId: null,
904+
createdBy: "user",
905+
creationSource: "web",
906+
role: "user",
907+
text: "also fix X",
908+
attachments: [],
909+
streaming: false,
910+
createdAt: at,
911+
updatedAt: at,
912+
},
913+
});
914+
}
915+
const shells = [
916+
yield* store.getThreadShell(threadId),
917+
ProjectionStore.threadShellFromProjection(yield* store.getThreadProjection(threadId)),
918+
];
919+
assert.deepEqual(
920+
shells.map((shell) => shell?.latestRunBackgroundWake),
921+
[expected, expected],
922+
id,
923+
);
924+
yield* assertShellIndexCoversShells();
925+
}
926+
}).pipe(Effect.provide(layerTest)),
927+
);
928+
830929
it.effect("SQL queue readiness skips held runs without bypassing active work", () =>
831930
Effect.gen(function* () {
832931
const store = yield* ProjectionStore.ProjectionStoreV2;

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1032,6 +1032,7 @@ type ShellThreadRow = {
10321032
readonly latest_run_started_at: string | null;
10331033
readonly latest_run_completed_at: string | null;
10341034
readonly latest_run_stop_requested: number;
1035+
readonly latest_run_background_wake: number;
10351036
readonly active_run_id: string | null;
10361037
readonly active_run_status: string | null;
10371038
readonly activity_run_status: string | null;
@@ -1043,6 +1044,7 @@ type ShellThreadRow = {
10431044
readonly blocking_run_started_at: string | null;
10441045
readonly blocking_run_completed_at: string | null;
10451046
readonly blocking_run_stop_requested: number;
1047+
readonly blocking_run_background_wake: number;
10461048
readonly blocking_failure_payload_json: string | null;
10471049
readonly pending_request_payload_json: string | null;
10481050
readonly pending_secret_request_payload_json: string | null;
@@ -1658,6 +1660,8 @@ export function threadShellFromProjection(
16581660
projection.turnItems.some(
16591661
(item) => item.runId === latestRun.id && item.type === "run_interrupt_request",
16601662
),
1663+
latestRunBackgroundWake:
1664+
latestRun != null && isBackgroundWakeRunForShell(latestRun, projection),
16611665
activeRunId: activeRun?.id ?? null,
16621666
blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
16631667
activityRunStatus: activityRun?.status ?? null,
@@ -1753,6 +1757,25 @@ function isSilentRunForShell(
17531757
);
17541758
}
17551759

1760+
const BACKGROUND_WAKE_SOURCE_KINDS = new Set(["background_task", "command", "monitor"]);
1761+
1762+
function isBackgroundWakeRunForShell(
1763+
run: OrchestrationV2ThreadProjection["runs"][number],
1764+
projection: Pick<OrchestrationV2ThreadProjection, "messages">,
1765+
): boolean {
1766+
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1767+
return (
1768+
message?.delegatedCompletion === undefined &&
1769+
// Only progress wakes; a terminal one ("Command … finished") is the work reporting its end.
1770+
message?.notification?.outcome === "updated" &&
1771+
BACKGROUND_WAKE_SOURCE_KINDS.has(message.notification.source.kind) &&
1772+
// A follow-up the user steered into the wake makes the run theirs.
1773+
!projection.messages.some(
1774+
(candidate) => candidate.runId === run.id && candidate.createdBy === "user",
1775+
)
1776+
);
1777+
}
1778+
17561779
function isInterruptibleRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
17571780
return run.status === "preparing" || run.status === "starting" || run.status === "running";
17581781
}
@@ -1775,6 +1798,7 @@ type ShellThreadState = {
17751798
readonly latestRunStartedAt: DateTime.Utc | null;
17761799
readonly latestRunCompletedAt: DateTime.Utc | null;
17771800
readonly latestRunStopRequested: boolean;
1801+
readonly latestRunBackgroundWake: boolean;
17781802
readonly activeRunId: RunId | null;
17791803
readonly blockedOnThreadWait: boolean;
17801804
readonly activityRunStatus: ShellActivityRunStatus | null;
@@ -1935,6 +1959,7 @@ function shellFromState(input: {
19351959
latestRunStartedAt: input.state.latestRunStartedAt,
19361960
latestRunCompletedAt: input.state.latestRunCompletedAt,
19371961
latestRunStopRequested: input.state.latestRunStopRequested,
1962+
latestRunBackgroundWake: input.state.latestRunBackgroundWake,
19381963
activeRunId: input.state.activeRunId,
19391964
blockedOnThreadWait: input.state.blockedOnThreadWait,
19401965
activityRunStatus: input.state.activityRunStatus,
@@ -6267,6 +6292,25 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
62676292
LIMIT 1
62686293
)`;
62696294

6295+
// Mirrors isBackgroundWakeRunForShell. Stored sources keep the legacy encoding, where a
6296+
// command is background_command and a subagent is background_task with work "subagent".
6297+
const isBackgroundWakeShellRun = (alias: string) => {
6298+
const run = sql.literal(alias);
6299+
return sql`EXISTS (
6300+
SELECT 1 FROM orchestration_v2_projection_messages wake
6301+
WHERE wake.message_id = json_extract(${run}.payload_json, '$.userMessageId')
6302+
AND json_extract(wake.payload_json, '$.notification.source.kind')
6303+
IN ('background_task', 'background_command', 'command', 'monitor')
6304+
AND json_extract(wake.payload_json, '$.notification.source.work') IS NULL
6305+
AND json_extract(wake.payload_json, '$.notification.outcome') = 'updated'
6306+
AND json_extract(wake.payload_json, '$.delegatedCompletion') IS NULL
6307+
) AND NOT EXISTS (
6308+
SELECT 1 FROM orchestration_v2_projection_messages steer
6309+
WHERE steer.run_id = ${run}.run_id
6310+
AND json_extract(steer.payload_json, '$.createdBy') = 'user'
6311+
)`;
6312+
};
6313+
62706314
const selectShellThreadRows = (
62716315
threadId?: ThreadId,
62726316
{
@@ -6299,6 +6343,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
62996343
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = presented.run_id
63006344
AND stop_request.type = 'run_interrupt_request'
63016345
) AS latest_run_stop_requested,
6346+
${isBackgroundWakeShellRun("presented")} AS latest_run_background_wake,
63026347
active.run_id AS active_run_id,
63036348
active.status AS active_run_status,
63046349
(
@@ -6356,6 +6401,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
63566401
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = blocked.run_id
63576402
AND stop_request.type = 'run_interrupt_request'
63586403
) AS blocking_run_stop_requested,
6404+
${isBackgroundWakeShellRun("blocked")} AS blocking_run_background_wake,
63596405
(
63606406
SELECT item.payload_json
63616407
FROM orchestration_v2_projection_turn_items item
@@ -6928,6 +6974,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
69286974
? null
69296975
: DateTime.makeUnsafe(row.latest_run_completed_at);
69306976
let latestRunStopRequested = row.latest_run_stop_requested === 1;
6977+
let latestRunBackgroundWake = row.latest_run_background_wake === 1;
69316978
if (row.blocking_run_id !== null && row.blocking_failure_payload_json !== null) {
69326979
const blockingFailure = yield* decodeTurnItemPayload(
69336980
row.blocking_failure_payload_json,
@@ -6941,6 +6988,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
69416988
terminalFailureItem = blockingFailure;
69426989
latestRunId = RunId.make(row.blocking_run_id);
69436990
latestRunStopRequested = row.blocking_run_stop_requested === 1;
6991+
latestRunBackgroundWake = row.blocking_run_background_wake === 1;
69446992
latestRunStatus = "failed";
69456993
latestRunRequestedAt =
69466994
row.blocking_run_requested_at === null
@@ -6981,6 +7029,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
69817029
latestRunStartedAt,
69827030
latestRunCompletedAt,
69837031
latestRunStopRequested,
7032+
latestRunBackgroundWake,
69847033
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
69857034
blockedOnThreadWait: deriveBlockedOnThreadWait({
69867035
activeRun:
@@ -7251,6 +7300,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
72517300
activityRunStatus: state.activityRunStatus,
72527301
latestRunCompletedAt: state.latestRunCompletedAt,
72537302
latestRunStopRequested: state.latestRunStopRequested,
7303+
latestRunBackgroundWake: state.latestRunBackgroundWake,
72547304
pendingRuntimeRequest: state.pendingRuntimeRequest,
72557305
pendingBackgroundTasks: state.pendingBackgroundTasks,
72567306
})),

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

Lines changed: 65 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",
@@ -267,6 +268,69 @@ it("presents completion notifications and sound as soon as the shell completes",
267268
expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
268269
});
269270

271+
it.each([false, true])(
272+
"presents one completion when a monitor ends with a final wake (disconnected: %s)",
273+
async (disconnect) => {
274+
await using app = setup();
275+
using _timers = fakeTimers();
276+
state.mode = "notifications-and-sound";
277+
app.start();
278+
const watching = (
279+
turnId: string,
280+
turnState: string,
281+
completedAt: string | null,
282+
latestRunBackgroundWake: boolean,
283+
pendingBackgroundTasks: ReadonlyArray<{ taskId: string; kind: "monitor" }>,
284+
) => ({
285+
status: "live",
286+
snapshot: Option.some({
287+
threads: [
288+
{
289+
...toV2ThreadShell({
290+
...thread,
291+
latestTurn: { turnId, state: turnState, completedAt },
292+
}),
293+
latestRunBackgroundWake,
294+
pendingBackgroundTasks,
295+
},
296+
],
297+
}),
298+
});
299+
const monitor = [{ taskId: "watch", kind: "monitor" as const }];
300+
const titles = () => TestNotification.sent.map(({ title }) => title);
301+
state.shells.set(
302+
"one",
303+
watching("turn", "completed", "2026-09-13T07:00:01.000Z", false, monitor),
304+
);
305+
expect(titles()).toEqual(["Thread completed"]);
306+
307+
state.shells.set("one", watching("wake", "running", null, true, monitor));
308+
state.shells.set(
309+
"one",
310+
watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, monitor),
311+
);
312+
expect(titles()).toEqual(["Thread completed"]);
313+
314+
// The adapter drains the roster before the final wake starts.
315+
state.shells.set("one", watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, []));
316+
expect(titles()).toEqual(["Thread completed"]);
317+
if (disconnect) {
318+
state.shells.set("one", {
319+
...watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, []),
320+
status: "cached",
321+
});
322+
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
323+
expect(titles()).toEqual(["Thread completed"]);
324+
}
325+
326+
state.shells.set("one", watching("final", "running", null, false, []));
327+
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
328+
state.shells.set("one", watching("final", "completed", "2026-09-13T07:00:11.000Z", false, []));
329+
expect(titles()).toEqual(["Thread completed", "Thread completed"]);
330+
expect(state.sound).toHaveBeenCalledTimes(2);
331+
},
332+
);
333+
270334
it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
271335
"notifies for offline completion and %s once across reconnects",
272336
async (flag) => {

0 commit comments

Comments
 (0)