The best way to control Claude Code, Codex and more from any computer or phone
fix: Claude monitor wakes no longer fire a completion alert per line (#32520)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 10, 2026 at 09:46 UTC
20723d6d9bd23adddc4c1a92eea496c0af32c3dc
10 files changed
+407
-16
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+99
@@ -827,6 +827,105 @@ it.effect("record reads filter notification sources without dropping matching me
827
}).pipe(Effect.provide(layerTest)),
828
);
829
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
+
929
it.effect("SQL queue readiness skips held runs without bypassing active work", () =>
930
Effect.gen(function* () {
931
const store = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+50
@@ -1032,6 +1032,7 @@ type ShellThreadRow = {
1032
readonly latest_run_started_at: string | null;
1033
readonly latest_run_completed_at: string | null;
1034
readonly latest_run_stop_requested: number;
1035
+ readonly latest_run_background_wake: number;
1036
readonly active_run_id: string | null;
1037
readonly active_run_status: string | null;
1038
readonly activity_run_status: string | null;
@@ -1043,6 +1044,7 @@ type ShellThreadRow = {
1044
readonly blocking_run_started_at: string | null;
1045
readonly blocking_run_completed_at: string | null;
1046
readonly blocking_run_stop_requested: number;
1047
+ readonly blocking_run_background_wake: number;
1048
readonly blocking_failure_payload_json: string | null;
1049
readonly pending_request_payload_json: string | null;
1050
readonly pending_secret_request_payload_json: string | null;
@@ -1658,6 +1660,8 @@ export function threadShellFromProjection(
1660
projection.turnItems.some(
1661
(item) => item.runId === latestRun.id && item.type === "run_interrupt_request",
1662
),
1663
+ latestRunBackgroundWake:
1664
+ latestRun != null && isBackgroundWakeRunForShell(latestRun, projection),
1665
activeRunId: activeRun?.id ?? null,
1666
blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
1667
activityRunStatus: activityRun?.status ?? null,
@@ -1753,6 +1757,25 @@ function isSilentRunForShell(
1757
);
1758
}
1759
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
+
1779
function isInterruptibleRunForShell(run: OrchestrationV2ThreadProjection["runs"][number]): boolean {
1780
return run.status === "preparing" || run.status === "starting" || run.status === "running";
1781
}
@@ -1775,6 +1798,7 @@ type ShellThreadState = {
1798
readonly latestRunStartedAt: DateTime.Utc | null;
1799
readonly latestRunCompletedAt: DateTime.Utc | null;
1800
readonly latestRunStopRequested: boolean;
1801
+ readonly latestRunBackgroundWake: boolean;
1802
readonly activeRunId: RunId | null;
1803
readonly blockedOnThreadWait: boolean;
1804
readonly activityRunStatus: ShellActivityRunStatus | null;
@@ -1935,6 +1959,7 @@ function shellFromState(input: {
1959
latestRunStartedAt: input.state.latestRunStartedAt,
1960
latestRunCompletedAt: input.state.latestRunCompletedAt,
1961
latestRunStopRequested: input.state.latestRunStopRequested,
1962
+ latestRunBackgroundWake: input.state.latestRunBackgroundWake,
1963
activeRunId: input.state.activeRunId,
1964
blockedOnThreadWait: input.state.blockedOnThreadWait,
1965
activityRunStatus: input.state.activityRunStatus,
@@ -6267,6 +6292,25 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6292
LIMIT 1
6293
)`;
6294
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
+
6314
const selectShellThreadRows = (
6315
threadId?: ThreadId,
6316
{
@@ -6299,6 +6343,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6343
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = presented.run_id
6344
AND stop_request.type = 'run_interrupt_request'
6345
) AS latest_run_stop_requested,
6346
+ ${isBackgroundWakeShellRun("presented")} AS latest_run_background_wake,
6347
active.run_id AS active_run_id,
6348
active.status AS active_run_status,
6349
(
@@ -6356,6 +6401,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6401
WHERE stop_request.thread_id = t.thread_id AND stop_request.run_id = blocked.run_id
6402
AND stop_request.type = 'run_interrupt_request'
6403
) AS blocking_run_stop_requested,
6404
+ ${isBackgroundWakeShellRun("blocked")} AS blocking_run_background_wake,
6405
(
6406
SELECT item.payload_json
6407
FROM orchestration_v2_projection_turn_items item
@@ -6928,6 +6974,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6974
? null
6975
: DateTime.makeUnsafe(row.latest_run_completed_at);
6976
let latestRunStopRequested = row.latest_run_stop_requested === 1;
6977
+ let latestRunBackgroundWake = row.latest_run_background_wake === 1;
6978
if (row.blocking_run_id !== null && row.blocking_failure_payload_json !== null) {
6979
const blockingFailure = yield* decodeTurnItemPayload(
6980
row.blocking_failure_payload_json,
@@ -6941,6 +6988,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6988
terminalFailureItem = blockingFailure;
6989
latestRunId = RunId.make(row.blocking_run_id);
6990
latestRunStopRequested = row.blocking_run_stop_requested === 1;
6991
+ latestRunBackgroundWake = row.blocking_run_background_wake === 1;
6992
latestRunStatus = "failed";
6993
latestRunRequestedAt =
6994
row.blocking_run_requested_at === null
@@ -6981,6 +7029,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7029
latestRunStartedAt,
7030
latestRunCompletedAt,
7031
latestRunStopRequested,
7032
+ latestRunBackgroundWake,
7033
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
7034
blockedOnThreadWait: deriveBlockedOnThreadWait({
7035
activeRun:
@@ -7251,6 +7300,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
7300
activityRunStatus: state.activityRunStatus,
7301
latestRunCompletedAt: state.latestRunCompletedAt,
7302
latestRunStopRequested: state.latestRunStopRequested,
7303
+ latestRunBackgroundWake: state.latestRunBackgroundWake,
7304
pendingRuntimeRequest: state.pendingRuntimeRequest,
7305
pendingBackgroundTasks: state.pendingBackgroundTasks,
7306
})),
apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts
+65
-1
@@ -5,7 +5,8 @@ import * as Option from "effect/Option";
5
import { Atom, AtomRegistry } from "effect/reactivity";
6
import { expect, it, vi } from "vite-plus/test";
7
8
-import { stubGlobal } from "../../test/render";
8
+import { fakeTimers, stubGlobal } from "../../test/render";
9
+import { RELEASED_COMPLETION_GRACE_MS } from "./ThreadNotificationCoordinator.logic";
10
11
const state = vi.hoisted(() => ({
12
mode: "notifications",
@@ -267,6 +268,69 @@ it("presents completion notifications and sound as soon as the shell completes",
268
expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
269
});
270
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
+
334
it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
335
"notifies for offline completion and %s once across reconnects",
336
async (flag) => {
apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts
+69
-7
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
2
3
import {
4
createThreadNotificationGate,
5
+ RELEASED_COMPLETION_GRACE_MS,
6
type ThreadNotificationObservation,
7
} from "./ThreadNotificationCoordinator.logic";
8
@@ -10,15 +11,27 @@ const working: ThreadNotificationObservation = {
11
requestId: null,
12
settled: false,
13
completedAt: null,
14
+ backgroundWake: false,
15
};
16
const completed = (at: number): ThreadNotificationObservation => ({
17
attention: null,
18
requestId: null,
19
settled: true,
20
completedAt: at,
21
+ backgroundWake: false,
22
+});
23
+const waking: ThreadNotificationObservation = { ...working, backgroundWake: true };
24
+const woke = (at: number): ThreadNotificationObservation => ({
25
+ ...completed(at),
26
+ backgroundWake: true,
27
});
28
const visible = { archived: false, quiet: false };
29
30
+function fakeTimers(): Disposable {
31
+ vi.useFakeTimers();
32
+ return { [Symbol.dispose]: () => void vi.useRealTimers() };
33
+}
34
+
35
function harness() {
36
const notify = vi.fn();
37
const gate = createThreadNotificationGate<string>(notify);
@@ -59,12 +72,7 @@ describe("createThreadNotificationGate", () => {
72
it("notifies each attention once per stretch and still notifies the subsequent completion", () => {
73
const { notify, observe } = harness();
74
observe(working);
62
- const attention = {
63
- attention: "run-1:approval:a",
64
- requestId: "a",
65
- settled: false,
66
- completedAt: null,
67
- };
75
+ const attention = { ...working, attention: "run-1:approval:a", requestId: "a" };
76
observe(attention);
77
expect(notify.mock.calls).toEqual([["thread", "input"]]);
78
observe({ ...attention });
@@ -96,7 +104,7 @@ describe("createThreadNotificationGate", () => {
104
const { notify, observe } = harness();
105
observe(working);
106
observe(completed(1));
99
- observe({ attention: "run-1:limited", requestId: null, settled: false, completedAt: null });
107
+ observe({ ...working, attention: "run-1:limited" });
108
observe(completed(1));
109
expect(notify.mock.calls).toEqual([
110
["thread", "completion"],
@@ -132,4 +140,58 @@ describe("createThreadNotificationGate", () => {
140
expect(notify.mock.calls).toEqual([["thread", "completion"]]);
141
}
142
});
143
+
144
+ it("waits out the grace before notifying a wake's completion, and a final wake replaces it", () => {
145
+ using _timers = fakeTimers();
146
+ const { notify, observe } = harness();
147
+ observe(working);
148
+ observe(completed(1));
149
+ // Held until the monitor left, or completing after it already had: either way unheld here.
150
+ observe(waking);
151
+ observe(woke(2));
152
+ expect(notify).toHaveBeenCalledTimes(1);
153
+ observe(working);
154
+ vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
155
+ expect(notify).toHaveBeenCalledTimes(1);
156
+ observe(completed(3));
157
+ vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
158
+ expect(notify.mock.calls).toEqual([
159
+ ["thread", "completion"],
160
+ ["thread", "completion"],
161
+ ]);
162
+ });
163
+
164
+ it("notifies a wake's completion once after the grace when no run follows, even across a pause", () => {
165
+ using _timers = fakeTimers();
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) });
173
+ vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS - 1);
174
+ observe({ ...woke(1) });
175
+ expect(notify).not.toHaveBeenCalled();
176
+ vi.advanceTimersByTime(1);
177
+ expect(notify.mock.calls).toEqual([["thread", "completion"]]);
178
+ observe({ ...woke(1) });
179
+ vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
180
+ expect(notify).toHaveBeenCalledTimes(1);
181
+ });
182
+
183
+ it("drops a pending wake completion when the thread is removed or the gate is cleared", () => {
184
+ using _timers = fakeTimers();
185
+ for (const reset of [
186
+ (gate: ReturnType<typeof createThreadNotificationGate<string>>) => gate.retain(new Set()),
187
+ (gate: ReturnType<typeof createThreadNotificationGate<string>>) => gate.clear(),
188
+ ]) {
189
+ const { gate, notify, observe } = harness();
190
+ observe(waking);
191
+ observe(woke(1));
192
+ reset(gate);
193
+ vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
194
+ expect(notify).not.toHaveBeenCalled();
195
+ }
196
+ });
197
});
apps/web/src/components/ThreadNotificationCoordinator.logic.ts
+42
@@ -9,16 +9,38 @@ export interface ThreadNotificationObservation {
9
readonly settled: boolean;
10
/** When the latest run completed, if it did. */
11
readonly completedAt: number | null;
12
+ /** The latest run answers a background-work progress wake, like a Monitor line. */
13
+ readonly backgroundWake: boolean;
14
}
15
16
+/** Matches the push relay's completion confirmation: a final wake can start right after a progress wake. */
17
+export const RELEASED_COMPLETION_GRACE_MS = 5_000;
18
+
19
export function createThreadNotificationGate<Key>(
20
notify: (key: Key, kind: ThreadNotificationKind) => void,
21
) {
22
// The newest completion already notified, or deliberately skipped.
23
const handled = new Map<Key, number>();
24
+ // Wake completions waiting out the grace, by completion time; no timer while paused.
25
+ const releases = new Map<
26
+ Key,
27
+ { readonly at: number; readonly timer: ReturnType<typeof setTimeout> | undefined }
28
+ >();
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
+ };
37
const skip = (key: Key, at: number | null) => {
38
if (at !== null && at > (handled.get(key) ?? -Infinity)) handled.set(key, at);
39
};
40
+ const cancel = (key: Key) => {
41
+ clearTimeout(releases.get(key)?.timer);
42
+ releases.delete(key);
43
+ };
44
// Attention keys with a request id seen since the thread last stopped needing attention.
45
const attended = new Map<Key, Set<string>>();
46
const attend = (
@@ -44,6 +66,13 @@ export function createThreadNotificationGate<Key>(
66
next: ThreadNotificationObservation,
67
options: { readonly archived: boolean; readonly quiet: boolean },
68
): void {
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
+ }
75
+ cancel(key);
76
// The first sighting, archived threads, and stopped or silent runs never notify completion.
77
if (!prior || options.archived || options.quiet) skip(key, next.completedAt);
78
const fresh = attend(key, prior, next);
@@ -54,15 +83,28 @@ export function createThreadNotificationGate<Key>(
83
}
84
const at = next.completedAt;
85
if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return;
86
+ if (next.backgroundWake) {
87
+ release(key, at);
88
+ return;
89
+ }
90
handled.set(key, at);
91
notify(key, "completion");
92
},
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
+ },
100
/** Forgets threads that left the snapshot. */
101
retain(keys: ReadonlySet<Key>): void {
102
for (const key of handled.keys()) if (!keys.has(key)) handled.delete(key);
103
+ for (const key of releases.keys()) if (!keys.has(key)) cancel(key);
104
for (const key of attended.keys()) if (!keys.has(key)) attended.delete(key);
105
},
106
clear(): void {
107
+ for (const key of releases.keys()) cancel(key);
108
handled.clear();
109
attended.clear();
110
},
apps/web/src/components/ThreadNotificationCoordinator.tsx
+8
-3
@@ -7,6 +7,7 @@ import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
7
import type { AnyRouter } from "@tanstack/react-router";
8
import { threadKey } from "@t3tools/client-runtime/state/entities";
9
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
10
+import { monitorHoldsWakeCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
11
import type { ClientSettings } from "@t3tools/contracts/settings";
12
import * as Option from "effect/Option";
13
import type { AtomRegistry } from "effect/reactivity";
@@ -263,8 +264,10 @@ export function startThreadNotifications(
264
const attention = needsAttention
265
? `${thread.latestRun?.runId ?? ""}:${status}:${requestId ?? ""}`
266
: null;
266
- const completedAt = Date.parse(thread.latestRun?.completedAt ?? "");
267
- const settled = status === "ready" && thread.latestRun?.status === "completed";
267
+ const completed = status === "ready" && thread.latestRun?.status === "completed";
268
+ const settled = completed && !monitorHoldsWakeCompletion(rawThread);
269
+ const parsedCompletedAt = Date.parse(thread.latestRun?.completedAt ?? "");
270
+ const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null;
271
const state = {
272
raw: rawThread,
273
subagentRequest,
@@ -273,7 +276,8 @@ export function startThreadNotifications(
276
attention,
277
requestId,
278
settled,
276
- completedAt: settled && Number.isFinite(completedAt) ? completedAt : null,
279
+ completedAt: settled ? completedAt : null,
280
+ backgroundWake: rawThread.latestRunBackgroundWake === true,
281
};
282
next.set(thread.id, state);
283
changed.push([prior, state]);
@@ -312,6 +316,7 @@ export function startThreadNotifications(
316
return;
317
}
318
entry.reconnecting = true;
319
+ entry.gate.pause();
320
},
321
{ immediate: true },
322
);
packages/contracts/src/orchestrationV2.ts
+2
@@ -2122,6 +2122,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
2122
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2123
latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2124
latestRunStopRequested: Schema.optional(Schema.Boolean),
2125
+ /** The latest run answers a background-work progress wake, like a Monitor line, not a terminal one. Absent from older servers. */
2126
+ latestRunBackgroundWake: Schema.optional(Schema.Boolean),
2127
activeRunId: Schema.NullOr(RunId),
2128
activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
2129
activityRunStatus: Schema.optional(
packages/shared/src/agentAwareness.test.ts
+50
-2
@@ -24,6 +24,7 @@ describe("projectThreadAwarenessV2", () => {
24
Pick<
25
OrchestrationV2ThreadShell,
26
| "activityRunStatus"
27
+ | "latestRunBackgroundWake"
28
| "latestRunStopRequested"
29
| "status"
30
| "pendingBackgroundTasks"
@@ -63,6 +64,44 @@ describe("projectThreadAwarenessV2", () => {
64
).toBeNull();
65
});
66
67
+ it.each([
68
+ ["holds a wake run", true, [{ taskId: "watch", kind: "monitor" as const }], "running"],
69
+ ["completes a wake run once its monitor ends", true, [], "completed"],
70
+ [
71
+ "holds a wake run while a monitor remains beside other work",
72
+ true,
73
+ [
74
+ { taskId: "build", kind: "command" as const },
75
+ { taskId: "watch", kind: "monitor" as const },
76
+ ],
77
+ "running",
78
+ ],
79
+ [
80
+ "completes a wake run with only a command pending",
81
+ true,
82
+ [{ taskId: "build", kind: "command" as const }],
83
+ "completed",
84
+ ],
85
+ [
86
+ "completes a run the user started",
87
+ false,
88
+ [{ taskId: "watch", kind: "monitor" as const }],
89
+ "completed",
90
+ ],
91
+ ] as const)("%s while a monitor wakes the thread", (_, latestRunBackgroundWake, tasks, phase) => {
92
+ expect(
93
+ projectThreadAwarenessV2({
94
+ environmentId: "env-1" as EnvironmentId,
95
+ project,
96
+ thread: v2Thread({
97
+ status: "completed",
98
+ latestRunBackgroundWake,
99
+ pendingBackgroundTasks: [...tasks],
100
+ }),
101
+ })?.phase,
102
+ ).toBe(phase);
103
+ });
104
+
105
it.each([
106
["running", "subagent"],
107
["completed", "subagent"],
@@ -97,12 +136,21 @@ describe("projectThreadAwarenessV2", () => {
136
).toMatchObject({ phase: "running", headline: "Agent is working" });
137
});
138
100
- it.each(["completed", "failed"] as const)("removes settled %s work", (status) => {
139
+ it.each([
140
+ ["completed", "completed", false],
141
+ ["failed", "failed", false],
142
+ ["monitor-held", "completed", true],
143
+ ] as const)("removes settled %s work", (_, status, latestRunBackgroundWake) => {
144
expect(
145
projectThreadAwarenessV2({
146
environmentId: "env-1" as EnvironmentId,
147
project,
105
- thread: v2Thread({ status, settledOverride: "settled" }),
148
+ thread: v2Thread({
149
+ status,
150
+ settledOverride: "settled",
151
+ latestRunBackgroundWake,
152
+ pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],
153
+ }),
154
}),
155
).toBeNull();
156
});
packages/shared/src/agentAwareness.ts
+11
-3
@@ -9,7 +9,10 @@ import {
9
} from "@t3tools/contracts";
10
import * as DateTime from "effect/DateTime";
11
12
-import { backgroundWorkHoldsCompletion } from "./orchestrationV2PendingBackgroundWork.ts";
12
+import {
13
+ backgroundWorkHoldsCompletion,
14
+ monitorHoldsWakeCompletion,
15
+} from "./orchestrationV2PendingBackgroundWork.ts";
16
17
export type AgentAwarenessPhase =
18
| "starting"
@@ -73,6 +76,7 @@ export interface ProjectThreadAwarenessV2Input {
76
| "activityRunStatus"
77
| "id"
78
| "lineage"
79
+ | "latestRunBackgroundWake"
80
| "latestRunStopRequested"
81
| "modelSelection"
82
| "pendingBackgroundTasks"
@@ -98,9 +102,12 @@ export function projectThreadAwarenessV2(
102
}
103
if (phase === "completed" && thread.latestRunStopRequested === true) return null;
104
// Resolve the phase first so live or waiting work stays visible after settlement.
105
+ const runStatus = thread.activityRunStatus ?? thread.status;
106
if (
107
thread.settledOverride === "settled" &&
103
- (phase === "completed" || phase === "failed") &&
108
+ (phase === "completed" ||
109
+ phase === "failed" ||
110
+ (phase === "running" && runStatus === "completed")) &&
111
!backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
112
) {
113
return null;
@@ -153,7 +160,8 @@ function resolveThreadAwarenessPhaseV2(
160
case "waiting":
161
return "running";
162
case "completed":
156
- return backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
163
+ return backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) ||
164
+ monitorHoldsWakeCompletion(thread)
165
? "running"
166
: "completed";
167
case "failed":
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+11
@@ -2,6 +2,7 @@ import type {
2
OrchestrationV2PendingBackgroundTask,
3
OrchestrationV2ProviderThread,
4
OrchestrationV2Run,
5
+ OrchestrationV2ThreadShell,
6
OrchestrationV2TurnItem,
7
ThreadId,
8
ThreadPullRequestLink,
@@ -107,6 +108,16 @@ function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind
108
}
109
}
110
111
+/** A monitor wakes the agent once per line, so a progress wake run's completion waits for the monitor to end. */
112
+export function monitorHoldsWakeCompletion(
113
+ thread: Pick<OrchestrationV2ThreadShell, "latestRunBackgroundWake" | "pendingBackgroundTasks">,
114
+): boolean {
115
+ return (
116
+ thread.latestRunBackgroundWake === true &&
117
+ (thread.pendingBackgroundTasks ?? []).some((task) => task.kind === "monitor")
118
+ );
119
+}
120
+
121
type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
122
123
type PendingBackgroundWorkPullRequest = Pick<