Skip to content

Commit 175298a

Browse files
fix: monitor holds apply only to progress wakes and survive reconnects
Only a progress wake (notification outcome "updated", such as a Monitor line) counts as a background wake now. Terminal wakes like "Command … finished" or "Monitor … was stopped" alert at once, even while an unrelated monitor is pending. The in-memory shell builder and the SQL shell query apply the same rule. The notification gate waits out the grace for any settled background-wake completion, not only one whose hold was just released. A wake that completes after its monitor already left no longer alerts on top of the final wake. When the shell leaves live, the gate pauses its grace timers. The next live snapshot restarts the grace if the same completion is still latest, and drops it otherwise, so no completion fires while disconnected and then again after the reconnect. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e268b3e commit 175298a

8 files changed

Lines changed: 130 additions & 89 deletions

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -787,13 +787,15 @@ it.effect("shells flag a latest run triggered by a provider background wake", ()
787787
const initial = yield* store.getThreadProjection(threadId);
788788
const at = initial.updatedAt;
789789
let ordinal = 1;
790-
for (const [id, source, expected] of [
791-
["background-task", { kind: "background_task" }, true],
792-
["monitor", { kind: "monitor" }, true],
793-
["command", { kind: "command" }, true],
794-
["subagent", { kind: "subagent" }, false],
795-
["delegated", { kind: "delegated_task", taskIds: [] }, false],
796-
["steered", { kind: "background_task" }, false],
790+
for (const [id, source, outcome, expected] of [
791+
["background-task", { kind: "background_task" }, "updated", true],
792+
["monitor", { kind: "monitor" }, "updated", true],
793+
["command", { kind: "command" }, "updated", true],
794+
["command-finished", { kind: "command" }, "completed", false],
795+
["monitor-stopped", { kind: "monitor" }, "cancelled", false],
796+
["subagent", { kind: "subagent" }, "updated", false],
797+
["delegated", { kind: "delegated_task", taskIds: [] }, "updated", false],
798+
["steered", { kind: "background_task" }, "updated", false],
797799
] as const) {
798800
const messageId = MessageId.make(`message:background-wake:${id}`);
799801
yield* store.apply({
@@ -814,7 +816,7 @@ it.effect("shells flag a latest run triggered by a provider background wake", ()
814816
streaming: false,
815817
createdAt: at,
816818
updatedAt: at,
817-
notification: { source, outcome: "updated", summary: "Background activity updated" },
819+
notification: { source, outcome, summary: "Background activity updated" },
818820
...(id === "delegated"
819821
? {
820822
delegatedCompletion: {

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1765,7 +1765,9 @@ function isBackgroundWakeRunForShell(
17651765
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
17661766
return (
17671767
message?.delegatedCompletion === undefined &&
1768-
BACKGROUND_WAKE_SOURCE_KINDS.has(message?.notification?.source.kind ?? "") &&
1768+
// Only progress wakes; a terminal one ("Command … finished") is the work reporting its end.
1769+
message?.notification?.outcome === "updated" &&
1770+
BACKGROUND_WAKE_SOURCE_KINDS.has(message.notification.source.kind) &&
17691771
// A follow-up the user steered into the wake makes the run theirs.
17701772
!projection.messages.some(
17711773
(candidate) => candidate.runId === run.id && candidate.createdBy === "user",
@@ -6289,6 +6291,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
62896291
AND json_extract(wake.payload_json, '$.notification.source.kind')
62906292
IN ('background_task', 'background_command', 'command', 'monitor')
62916293
AND json_extract(wake.payload_json, '$.notification.source.work') IS NULL
6294+
AND json_extract(wake.payload_json, '$.notification.outcome') = 'updated'
62926295
AND json_extract(wake.payload_json, '$.delegatedCompletion') IS NULL
62936296
) AND NOT EXISTS (
62946297
SELECT 1 FROM orchestration_v2_projection_messages steer

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

Lines changed: 59 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -268,52 +268,68 @@ it("presents completion notifications and sound as soon as the shell completes",
268268
expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
269269
});
270270

271-
it("presents one completion when a monitor ends with a final wake", async () => {
272-
await using app = setup();
273-
using _timers = fakeTimers();
274-
state.mode = "notifications-and-sound";
275-
app.start();
276-
const watching = (
277-
turnId: string,
278-
turnState: string,
279-
completedAt: string | null,
280-
latestRunBackgroundWake: boolean,
281-
pendingBackgroundTasks: ReadonlyArray<{ taskId: string; kind: "monitor" }>,
282-
) => ({
283-
status: "live",
284-
snapshot: Option.some({
285-
threads: [
286-
{
287-
...toV2ThreadShell({ ...thread, latestTurn: { turnId, state: turnState, completedAt } }),
288-
latestRunBackgroundWake,
289-
pendingBackgroundTasks,
290-
},
291-
],
292-
}),
293-
});
294-
const monitor = [{ taskId: "watch", kind: "monitor" as const }];
295-
const titles = () => TestNotification.sent.map(({ title }) => title);
296-
state.shells.set(
297-
"one",
298-
watching("turn", "completed", "2026-09-13T07:00:01.000Z", false, monitor),
299-
);
300-
expect(titles()).toEqual(["Thread completed"]);
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"]);
301306

302-
state.shells.set("one", watching("wake", "running", null, true, monitor));
303-
state.shells.set("one", watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, monitor));
304-
expect(titles()).toEqual(["Thread completed"]);
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"]);
305313

306-
// The adapter drains the roster before the final wake starts.
307-
state.shells.set("one", watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, []));
308-
expect(titles()).toEqual(["Thread completed"]);
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+
}
309325

310-
state.shells.set("one", watching("final", "running", null, true, []));
311-
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
312-
state.shells.set("one", watching("final", "completed", "2026-09-13T07:00:11.000Z", true, []));
313-
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
314-
expect(titles()).toEqual(["Thread completed", "Thread completed"]);
315-
expect(state.sound).toHaveBeenCalledTimes(2);
316-
});
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+
);
317333

318334
it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
319335
"notifies for offline completion and %s once across reconnects",

‎apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts‎

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,20 @@ const working: ThreadNotificationObservation = {
1111
requestId: null,
1212
settled: false,
1313
completedAt: null,
14-
heldAt: null,
14+
backgroundWake: false,
1515
};
1616
const completed = (at: number): ThreadNotificationObservation => ({
1717
attention: null,
1818
requestId: null,
1919
settled: true,
2020
completedAt: at,
21-
heldAt: null,
21+
backgroundWake: false,
22+
});
23+
const waking: ThreadNotificationObservation = { ...working, backgroundWake: true };
24+
const woke = (at: number): ThreadNotificationObservation => ({
25+
...completed(at),
26+
backgroundWake: true,
2227
});
23-
const held = (at: number): ThreadNotificationObservation => ({ ...working, heldAt: at });
2428
const visible = { archived: false, quiet: false };
2529

2630
function fakeTimers(): Disposable {
@@ -137,14 +141,14 @@ describe("createThreadNotificationGate", () => {
137141
}
138142
});
139143

140-
it("waits out the grace before notifying a released hold, and a final wake replaces it", () => {
144+
it("waits out the grace before notifying a wake's completion, and a final wake replaces it", () => {
141145
using _timers = fakeTimers();
142146
const { notify, observe } = harness();
143147
observe(working);
144148
observe(completed(1));
145-
observe(working);
146-
observe(held(2));
147-
observe(completed(2));
149+
// Held until the monitor left, or completing after it already had: either way unheld here.
150+
observe(waking);
151+
observe(woke(2));
148152
expect(notify).toHaveBeenCalledTimes(1);
149153
observe(working);
150154
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
@@ -157,32 +161,34 @@ describe("createThreadNotificationGate", () => {
157161
]);
158162
});
159163

160-
it("notifies a released hold once after the grace when no run follows", () => {
164+
it("notifies a wake's completion once after the grace when no run follows, even across a pause", () => {
161165
using _timers = fakeTimers();
162-
const { notify, observe } = harness();
163-
observe(working);
164-
observe(held(1));
165-
observe(completed(1));
166+
const { gate, notify, observe } = harness();
167+
observe(waking);
168+
observe(woke(1));
169+
gate.pause();
170+
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
171+
expect(notify).not.toHaveBeenCalled();
172+
observe({ ...woke(1) });
166173
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS - 1);
167-
observe({ ...completed(1) });
174+
observe({ ...woke(1) });
168175
expect(notify).not.toHaveBeenCalled();
169176
vi.advanceTimersByTime(1);
170177
expect(notify.mock.calls).toEqual([["thread", "completion"]]);
171-
observe({ ...completed(1) });
178+
observe({ ...woke(1) });
172179
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
173180
expect(notify).toHaveBeenCalledTimes(1);
174181
});
175182

176-
it("drops a pending released hold when the thread is removed or the gate is cleared", () => {
183+
it("drops a pending wake completion when the thread is removed or the gate is cleared", () => {
177184
using _timers = fakeTimers();
178185
for (const reset of [
179186
(gate: ReturnType<typeof createThreadNotificationGate<string>>) => gate.retain(new Set()),
180187
(gate: ReturnType<typeof createThreadNotificationGate<string>>) => gate.clear(),
181188
]) {
182189
const { gate, notify, observe } = harness();
183-
observe(working);
184-
observe(held(1));
185-
observe(completed(1));
190+
observe(waking);
191+
observe(woke(1));
186192
reset(gate);
187193
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
188194
expect(notify).not.toHaveBeenCalled();

‎apps/web/src/components/ThreadNotificationCoordinator.logic.ts‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,31 @@ export interface ThreadNotificationObservation {
99
readonly settled: boolean;
1010
/** When the latest run completed, if it did. */
1111
readonly completedAt: number | null;
12-
/** When the latest run completed, while background work holds its alert back. */
13-
readonly heldAt: number | null;
12+
/** The latest run answers a background-work progress wake, like a Monitor line. */
13+
readonly backgroundWake: boolean;
1414
}
1515

16-
/** Matches the push relay's completion confirmation: a final wake can start right after a hold ends. */
16+
/** Matches the push relay's completion confirmation: a final wake can start right after a progress wake. */
1717
export const RELEASED_COMPLETION_GRACE_MS = 5_000;
1818

1919
export function createThreadNotificationGate<Key>(
2020
notify: (key: Key, kind: ThreadNotificationKind) => void,
2121
) {
2222
// The newest completion already notified, or deliberately skipped.
2323
const handled = new Map<Key, number>();
24-
// Released holds waiting out the grace, by completion time.
24+
// Wake completions waiting out the grace, by completion time; no timer while paused.
2525
const releases = new Map<
2626
Key,
27-
{ readonly at: number; readonly timer: ReturnType<typeof setTimeout> }
27+
{ readonly at: number; readonly timer: ReturnType<typeof setTimeout> | undefined }
2828
>();
29+
const release = (key: Key, at: number) => {
30+
const timer = setTimeout(() => {
31+
releases.delete(key);
32+
handled.set(key, at);
33+
notify(key, "completion");
34+
}, RELEASED_COMPLETION_GRACE_MS);
35+
releases.set(key, { at, timer });
36+
};
2937
const skip = (key: Key, at: number | null) => {
3038
if (at !== null && at > (handled.get(key) ?? -Infinity)) handled.set(key, at);
3139
};
@@ -58,8 +66,12 @@ export function createThreadNotificationGate<Key>(
5866
next: ThreadNotificationObservation,
5967
options: { readonly archived: boolean; readonly quiet: boolean },
6068
): void {
61-
// The grace survives updates that keep the released completion; anything else cancels it.
62-
if (releases.get(key)?.at === next.completedAt && !options.archived && !options.quiet) return;
69+
// The grace survives updates that keep the wake's completion; anything else cancels it.
70+
const pending = releases.get(key);
71+
if (pending?.at === next.completedAt && !options.archived && !options.quiet) {
72+
if (pending.timer === undefined) release(key, pending.at);
73+
return;
74+
}
6375
cancel(key);
6476
// The first sighting, archived threads, and stopped or silent runs never notify completion.
6577
if (!prior || options.archived || options.quiet) skip(key, next.completedAt);
@@ -71,18 +83,20 @@ export function createThreadNotificationGate<Key>(
7183
}
7284
const at = next.completedAt;
7385
if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return;
74-
if (prior.heldAt === at) {
75-
const timer = setTimeout(() => {
76-
releases.delete(key);
77-
handled.set(key, at);
78-
notify(key, "completion");
79-
}, RELEASED_COMPLETION_GRACE_MS);
80-
releases.set(key, { at, timer });
86+
if (next.backgroundWake) {
87+
release(key, at);
8188
return;
8289
}
8390
handled.set(key, at);
8491
notify(key, "completion");
8592
},
93+
/** Stops grace timers while the snapshot is stale; the next observation restarts or drops them. */
94+
pause(): void {
95+
for (const [key, { at, timer }] of releases) {
96+
clearTimeout(timer);
97+
releases.set(key, { at, timer: undefined });
98+
}
99+
},
86100
/** Forgets threads that left the snapshot. */
87101
retain(keys: ReadonlySet<Key>): void {
88102
for (const key of handled.keys()) if (!keys.has(key)) handled.delete(key);

‎apps/web/src/components/ThreadNotificationCoordinator.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,7 @@ export function startThreadNotifications(
265265
? `${thread.latestRun?.runId ?? ""}:${status}:${requestId ?? ""}`
266266
: null;
267267
const completed = status === "ready" && thread.latestRun?.status === "completed";
268-
const held = completed && monitorHoldsWakeCompletion(rawThread);
269-
const settled = completed && !held;
268+
const settled = completed && !monitorHoldsWakeCompletion(rawThread);
270269
const parsedCompletedAt = Date.parse(thread.latestRun?.completedAt ?? "");
271270
const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null;
272271
const state = {
@@ -278,7 +277,7 @@ export function startThreadNotifications(
278277
requestId,
279278
settled,
280279
completedAt: settled ? completedAt : null,
281-
heldAt: held ? completedAt : null,
280+
backgroundWake: rawThread.latestRunBackgroundWake === true,
282281
};
283282
next.set(thread.id, state);
284283
changed.push([prior, state]);
@@ -317,6 +316,7 @@ export function startThreadNotifications(
317316
return;
318317
}
319318
entry.reconnecting = true;
319+
entry.gate.pause();
320320
},
321321
{ immediate: true },
322322
);

‎packages/contracts/src/orchestrationV2.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2121,7 +2121,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
21212121
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
21222122
latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
21232123
latestRunStopRequested: Schema.optional(Schema.Boolean),
2124-
/** The latest run is a provider wake for background work, like a Monitor line. Absent from older servers. */
2124+
/** The latest run answers a background-work progress wake, like a Monitor line, not a terminal one. Absent from older servers. */
21252125
latestRunBackgroundWake: Schema.optional(Schema.Boolean),
21262126
activeRunId: Schema.NullOr(RunId),
21272127
activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),

‎packages/shared/src/orchestrationV2PendingBackgroundWork.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind
108108
}
109109
}
110110

111-
/** A monitor wakes the agent once per line, so a wake run's completion waits for the monitor to end. */
111+
/** A monitor wakes the agent once per line, so a progress wake run's completion waits for the monitor to end. */
112112
export function monitorHoldsWakeCompletion(
113113
thread: Pick<OrchestrationV2ThreadShell, "latestRunBackgroundWake" | "pendingBackgroundTasks">,
114114
): boolean {

0 commit comments

Comments
 (0)