The best way to control Claude Code, Codex and more from any computer or phone
fix(threads): Working holds only background work the agent waits on (#24610)
Co-authored-by: lovelycodemonkey <ghassemimahyad@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 24, 2026 at 17:36 UTC
91ea0e18ebe2db81752bad7f0d4fa70a66d7562b
28 files changed
+641
-79
apps/mobile/src/features/threads/threadListV2.test.ts
+6
-5
@@ -101,11 +101,12 @@ describe("resolveThreadListV2Status", () => {
101
});
102
103
it.each([
104
- { kind: "command", status: "ready" },
105
- { kind: "monitor", status: "waiting" },
104
+ { roster: "dev server", task: { kind: "command" }, status: "ready" },
105
+ { roster: "dev server watchdog", task: { kind: "monitor" }, status: "ready" },
106
+ { roster: "awaited command", task: { kind: "command", awaited: true }, status: "waiting" },
107
] as const)(
107
- "presents an unseen completion with a $kind roster as $status",
108
- ({ kind, status }) => {
108
+ "presents an unseen completion with a $roster roster as $status",
109
+ ({ task, status }) => {
110
const thread = presentThreadShell(
111
environmentId,
112
makeRawThreadShell({
@@ -113,7 +114,7 @@ describe("resolveThreadListV2Status", () => {
114
status: "completed",
115
latestRunCompletedAt: DateTime.makeUnsafe(NOW),
116
lastVisitedAt: DateTime.makeUnsafe("2026-06-01T23:59:00.000Z"),
116
- pendingBackgroundTasks: [{ taskId: "background-work", kind }],
117
+ pendingBackgroundTasks: [{ taskId: "background-work", ...task }],
118
}),
119
);
120
apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+21
@@ -57,6 +57,27 @@ const handlers = {
57
);
58
}),
59
),
60
+ t3_background_wait: McpToolAccess.actsAsCaller((input) =>
61
+ Effect.gen(function* () {
62
+ const { scope, threads } = yield* readCaller();
63
+ const caller = yield* McpInvocationContext.requireThreadScope(scope, "t3_background_wait");
64
+ return yield* threads
65
+ .awaitBackgroundTasks({
66
+ threadId: caller.thread.threadId,
67
+ taskIds: input.taskIds,
68
+ awaited: input.waiting ?? true,
69
+ })
70
+ .pipe(
71
+ Effect.mapError(
72
+ (cause) =>
73
+ new OrchestratorMcpFailure({
74
+ code: cause.reason === "unsupported" ? "invalid_request" : "orchestration_error",
75
+ message: cause.message,
76
+ }),
77
+ ),
78
+ );
79
+ }),
80
+ ),
81
schedule_task: McpToolAccess.startsThreads(
82
() => ({}),
83
(input) =>
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+21
@@ -31,6 +31,7 @@ import {
31
OrchestratorMcpThreadWaitResult,
32
ThreadMetadataMcpUpdateInput,
33
ThreadMetadataMcpUpdateResult,
34
+ TrimmedNonEmptyString,
35
} from "@t3tools/contracts";
36
import { Tool, Toolkit } from "effect/ai";
37
import * as Schema from "effect/Schema";
@@ -116,6 +117,25 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {
117
.annotate(Tool.Title, "Stop a workflow")
118
.annotate(Tool.Destructive, true);
119
120
+const BackgroundWaitTool = Tool.make("t3_background_wait", {
121
+ description:
122
+ "Keep this thread in the user's Working list and out of their inbox while you wait for background work. Start a background command or Monitor first. Call this before you end your turn if you will act on its result when it wakes you. In taskIds, give the ID shown when the task started. The thread stays in Working until the task ends. The user is not told the work is done. Do not mark work you leave running, such as a dev server or watcher. Unmarked commands and monitors never keep the thread in Working. Pass waiting=false to remove the mark. This does not stop the task. IDs that are not running return in unmatched and change nothing. Only Claude threads support this tool. Other providers return an error.",
123
+ parameters: Schema.Struct({
124
+ taskIds: Schema.Array(TrimmedNonEmptyString).check(
125
+ Schema.isMinLength(1),
126
+ Schema.isMaxLength(20),
127
+ ),
128
+ waiting: Schema.optional(Schema.Boolean),
129
+ }),
130
+ success: Schema.Struct({
131
+ matched: Schema.Array(Schema.String),
132
+ unmatched: Schema.Array(Schema.String),
133
+ }),
134
+ failure: OrchestratorMcpFailure,
135
+ failureMode: "return",
136
+ dependencies,
137
+}).annotate(Tool.Title, "Wait on background work");
138
+
139
const ScheduleTaskTool = Tool.make("schedule_task", {
140
description:
141
"Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhook dedupe accepts replayKey and coalesceKey templates with coalesceWindowSeconds (10–3600, default 120); replay keys expire after 7 days and coalescing keeps the latest payload in a window measured from its first delivery. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. To run only for some requests, add filters, all of which must match, e.g. filters:[{path:'headers.x-github-event', op:'equals', value:'pull_request'}, {path:'body.action', op:'in', value:['opened','reopened']}]; ops are equals, notEquals, in, startsWith and exists. A path segment ending in [] fans out over an array: {path:'body.issue.labels[].name', op:'equals', value:'needs more info'} matches when any label has that name, and notEquals only when none does. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",
@@ -279,6 +299,7 @@ export const OrchestratorToolkit = Toolkit.make(
299
TaskStatusTool,
300
TaskCancelTool,
301
WorkflowStopTool,
302
+ BackgroundWaitTool,
303
ScheduleTaskTool,
304
ListScheduledTasksTool,
305
UpdateScheduledTaskTool,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+136
@@ -35,6 +35,7 @@ import {
35
type ModelSelection,
36
NodeId,
37
type OrchestrationV2AppThread,
38
+ type OrchestrationV2PendingBackgroundTask,
39
type OrchestrationV2ProviderThread,
40
ProjectId,
41
ProviderInstanceId,
@@ -565,6 +566,7 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
566
assert.equal(systemPrompt.type, "preset");
567
assert.equal(systemPrompt.preset, "claude_code");
568
assert.include(systemPrompt.append ?? "", "Use `delegate_task`");
569
+ assert.include(systemPrompt.append ?? "", "call `t3_background_wait`");
570
const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
571
assert.equal(logged.hasMcpServers, true);
572
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
@@ -2202,6 +2204,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2204
yield* Queue.unbounded<
2205
Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "plan.updated" }>
2206
>();
2207
+ const providerThreadReceipts =
2208
+ yield* Queue.unbounded<
2209
+ Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "provider_thread.updated" }>
2210
+ >();
2211
let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
2212
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2213
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
@@ -2329,6 +2335,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2335
if (event.type === "plan.updated") {
2336
yield* Queue.offer(planReceipts, event);
2337
}
2338
+ if (event.type === "provider_thread.updated") {
2339
+ yield* Queue.offer(providerThreadReceipts, event);
2340
+ }
2341
if (event.type === "turn_item.updated" && event.turnItem.type === "system_notice") {
2342
yield* Queue.offer(systemNoticeReceipts, event);
2343
}
@@ -2372,6 +2381,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2381
systemNoticeReceipts,
2382
runtimeRequestReceipts,
2383
planReceipts,
2384
+ providerThreadReceipts,
2385
getOpenedOptions: () => openedOptions,
2386
terminalEvents,
2387
hasPendingBackgroundWork,
@@ -6425,6 +6435,132 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6435
),
6436
);
6437
6438
+ it.effect("holds only the background tasks the agent marks awaited, until they end", () =>
6439
+ Effect.scoped(
6440
+ Effect.gen(function* () {
6441
+ const harness = yield* makeWakeHarness;
6442
+ const now = yield* DateTime.now;
6443
+ const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks;
6444
+ if (awaitBackgroundTasks === undefined) {
6445
+ throw new Error("Claude adapter runtime must expose awaitBackgroundTasks.");
6446
+ }
6447
+ const roster = (tasks: ReadonlyArray<string>, uuid: string) =>
6448
+ claudeSdkFrame({
6449
+ type: "system",
6450
+ subtype: "background_tasks_changed",
6451
+ tasks: tasks.map((taskId) => ({
6452
+ task_id: taskId,
6453
+ task_type: "local_bash",
6454
+ description: taskId,
6455
+ })),
6456
+ uuid,
6457
+ session_id: WAKE_NATIVE_SESSION,
6458
+ });
6459
+ const nextRoster = Effect.fn("nextRoster")(function* (
6460
+ matches: (tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>) => boolean,
6461
+ ) {
6462
+ while (true) {
6463
+ const { providerThread } = yield* Queue.take(harness.providerThreadReceipts);
6464
+ const tasks = providerThread.pendingBackgroundTasks ?? [];
6465
+ if (matches(tasks)) return tasks;
6466
+ }
6467
+ });
6468
+ const marks = (tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>) =>
6469
+ tasks.map((task) => [task.taskId, task.awaited === true]);
6470
+
6471
+ yield* harness.runtime.startTurn(
6472
+ makeClaudeTestTurnInput({
6473
+ threadId: harness.threadId,
6474
+ providerThread: harness.providerThread,
6475
+ now,
6476
+ attemptId: RunAttemptId.make("attempt-claude-awaited-roster"),
6477
+ text: "Run the tests in the background and the dev server.",
6478
+ attachments: [],
6479
+ }),
6480
+ );
6481
+ yield* Queue.offer(
6482
+ harness.sdkMessages,
6483
+ roster([WAKE_TASK_ID, "dev-server"], "00000000-0000-4000-8000-000000000301"),
6484
+ );
6485
+ yield* nextRoster((tasks) => tasks.length === 2);
6486
+
6487
+ const marked = yield* awaitBackgroundTasks({
6488
+ providerThread: harness.providerThread,
6489
+ taskIds: [WAKE_TASK_ID, "already-finished"],
6490
+ awaited: true,
6491
+ });
6492
+ assert.deepStrictEqual(marked.matched, [WAKE_TASK_ID]);
6493
+ assert.deepStrictEqual(
6494
+ marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))),
6495
+ [
6496
+ [WAKE_TASK_ID, true],
6497
+ ["dev-server", false],
6498
+ ],
6499
+ );
6500
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
6501
+ yield* Queue.take(harness.terminalReceipts);
6502
+
6503
+ // A replacing level rebuilds every entry; the mark must survive it.
6504
+ yield* Queue.offer(
6505
+ harness.sdkMessages,
6506
+ roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000302"),
6507
+ );
6508
+ assert.deepStrictEqual(
6509
+ marks(yield* nextRoster((tasks) => tasks[0]?.taskId === "dev-server")),
6510
+ [
6511
+ ["dev-server", false],
6512
+ [WAKE_TASK_ID, true],
6513
+ ],
6514
+ );
6515
+
6516
+ // Once the task leaves the roster, a reused id starts unmarked.
6517
+ yield* Queue.offer(
6518
+ harness.sdkMessages,
6519
+ roster(["dev-server"], "00000000-0000-4000-8000-000000000303"),
6520
+ );
6521
+ yield* nextRoster((tasks) => tasks.length === 1);
6522
+ yield* Queue.offer(
6523
+ harness.sdkMessages,
6524
+ roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000304"),
6525
+ );
6526
+ assert.deepStrictEqual(marks(yield* nextRoster((tasks) => tasks.length === 2)), [
6527
+ ["dev-server", false],
6528
+ [WAKE_TASK_ID, false],
6529
+ ]);
6530
+
6531
+ yield* awaitBackgroundTasks({
6532
+ providerThread: harness.providerThread,
6533
+ taskIds: ["dev-server"],
6534
+ awaited: true,
6535
+ });
6536
+ assert.deepStrictEqual(
6537
+ marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))),
6538
+ [
6539
+ ["dev-server", true],
6540
+ [WAKE_TASK_ID, false],
6541
+ ],
6542
+ );
6543
+ const released = yield* awaitBackgroundTasks({
6544
+ providerThread: harness.providerThread,
6545
+ taskIds: ["dev-server"],
6546
+ awaited: false,
6547
+ });
6548
+ assert.deepStrictEqual(released.matched, ["dev-server"]);
6549
+ assert.deepStrictEqual(
6550
+ marks(yield* nextRoster((tasks) => !tasks.some((task) => task.awaited === true))),
6551
+ [
6552
+ ["dev-server", false],
6553
+ [WAKE_TASK_ID, false],
6554
+ ],
6555
+ );
6556
+ }).pipe(
6557
+ Effect.provide(
6558
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6559
+ ),
6560
+ ),
6561
+ ),
6562
+ );
6563
+
6564
it.effect("keeps a running Claude monitor typed after many newer monitors end", () =>
6565
Effect.scoped(
6566
Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+112
-23
@@ -1296,6 +1296,15 @@ export function claudeQueryEnvironment(
1296
return { ...environment, CLAUDE_CODE_PROMPT_CACHE_TTL: subagentPromptCacheTtl };
1297
}
1298
1299
+// Claude Code defers MCP tools behind ToolSearch, so the agent only finds
1300
+// t3_background_wait when the system prompt says when to reach for it.
1301
+const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = `
1302
+
1303
+### Background work you wait on
1304
+
1305
+Before you end your turn to wait for a background command or Monitor you started, such as tests, a build, or a CI wait, call \`t3_background_wait\` with its task ID. The thread then stays in the user's Working list until that task ends, instead of returning to them early. Do not mark a dev server, a watcher, or anything else you leave running.
1306
+`;
1307
+
1308
export function makeClaudeQueryOptions(input: {
1309
readonly modelSelection: ModelSelection;
1310
readonly nativeThreadId: string;
@@ -1409,7 +1418,9 @@ export function makeClaudeQueryOptions(input: {
1418
preset: "claude_code" as const,
1419
append: [
1420
buildRuntimeInstructions({ harness: "Claude Code" }) +
1412
- (input.mcpServers === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS),
1421
+ (input.mcpServers === undefined
1422
+ ? ""
1423
+ : T3_CODE_ORCHESTRATION_INSTRUCTIONS + CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS),
1424
...launchAppendSystemPrompt,
1425
].join("\n\n"),
1426
},
@@ -2453,8 +2464,11 @@ function isClaudeRootTurnFrame(message: SDKMessage): boolean {
2464
2465
function claudePendingBackgroundTasksFromRoster(
2466
roster: ReadonlyMap<string, OrchestrationV2PendingBackgroundTask>,
2467
+ awaitedTaskIds: ReadonlySet<string>,
2468
): ReadonlyArray<OrchestrationV2PendingBackgroundTask> {
2457
- return Array.from(roster.values());
2469
+ return Array.from(roster.values(), (task) =>
2470
+ awaitedTaskIds.has(task.taskId) ? { ...task, awaited: true as const } : task,
2471
+ );
2472
}
2473
2474
function parseClaudeBackgroundTaskEntry(
@@ -4137,6 +4151,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4151
const pendingBackgroundTasksByNativeThread = yield* Ref.make(
4152
new Map<string, Map<string, OrchestrationV2PendingBackgroundTask>>(),
4153
);
4154
+ // Survives roster REPLACE levels, which rebuild every entry without the agent's mark.
4155
+ const awaitedBackgroundTasksByNativeThread = yield* Ref.make(
4156
+ new Map<string, Set<string>>(),
4157
+ );
4158
// Wake eligibility is separate from the Waiting roster. It survives empty
4159
// background_tasks_changed levels (SDK: empty level can precede task_notification) and
4160
// is consumed when the first idle notification is buffered/offered so duplicates cannot
@@ -4570,12 +4588,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4588
yield* Ref.get(pendingBackgroundTasksByNativeThread),
4589
input.nativeThreadId,
4590
);
4591
+ const awaitedTaskIds = taskIdSetForNativeThread(
4592
+ yield* Ref.get(awaitedBackgroundTasksByNativeThread),
4593
+ input.nativeThreadId,
4594
+ );
4595
const now = yield* DateTime.now;
4596
const providerThread: OrchestrationV2ProviderThread = {
4597
...input.providerThread,
4598
providerSessionId: session.id,
4599
...(input.status === undefined ? {} : { status: input.status }),
4578
- pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster),
4600
+ pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster, awaitedTaskIds),
4601
...(goalsByNativeThread.has(input.nativeThreadId)
4602
? { goal: goalsByNativeThread.get(input.nativeThreadId) ?? null }
4603
: {}),
@@ -4657,6 +4679,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4679
tasks.map((task) => task.taskId),
4680
);
4681
}
4682
+ const listed = new Set(tasks.map((task) => task.taskId));
4683
+ yield* Ref.update(awaitedBackgroundTasksByNativeThread, (current) => {
4684
+ const awaited = current.get(nativeThreadId);
4685
+ if (awaited === undefined) return current;
4686
+ const kept = new Set([...awaited].filter((taskId) => listed.has(taskId)));
4687
+ if (kept.size === awaited.size) return current;
4688
+ const updated = new Map(current);
4689
+ if (kept.size === 0) updated.delete(nativeThreadId);
4690
+ else updated.set(nativeThreadId, kept);
4691
+ return updated;
4692
+ });
4693
});
4694
4695
const upsertPendingBackgroundTask =
@@ -4689,7 +4722,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4722
updated.set(nativeThreadId, nextRoster);
4723
}
4724
return [true, updated] as const;
4692
- });
4725
+ }).pipe(
4726
+ Effect.tap(() =>
4727
+ clearTaskIdFromNativeThreadSet(
4728
+ awaitedBackgroundTasksByNativeThread,
4729
+ nativeThreadId,
4730
+ taskId,
4731
+ ),
4732
+ ),
4733
+ );
4734
4735
const clearPendingBackgroundTasksForNativeThread =
4736
/* Provider events include streaming deltas; avoid a span for each update. */
@@ -4702,6 +4743,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4743
updated.delete(nativeThreadId);
4744
return updated;
4745
});
4746
+ yield* clearNativeThreadTaskIdSet(awaitedBackgroundTasksByNativeThread, nativeThreadId);
4747
yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId);
4748
});
4749
@@ -6858,6 +6900,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6900
yield* Ref.get(pendingBackgroundTasksByNativeThread),
6901
nativeThreadId,
6902
);
6903
+ const awaitedTaskIds =
6904
+ nativeThreadId === null
6905
+ ? new Set<string>()
6906
+ : taskIdSetForNativeThread(
6907
+ yield* Ref.get(awaitedBackgroundTasksByNativeThread),
6908
+ nativeThreadId,
6909
+ );
6910
const clearConversationHead =
6911
input.status === "completed" &&
6912
input.context.input.providerThread.nativeConversationHeadRef !== null;
@@ -6895,7 +6944,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6944
input.context.input.providerThread.firstRunOrdinal ??
6945
input.context.input.runOrdinal,
6946
lastRunOrdinal: input.context.input.runOrdinal,
6898
- pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster),
6947
+ pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(
6948
+ roster,
6949
+ awaitedTaskIds,
6950
+ ),
6951
status: input.status === "completed" ? "active" : "idle",
6952
updatedAt: input.completedAt,
6953
};
@@ -7282,6 +7334,26 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7334
});
7335
});
7336
7337
+ // Untraced like the roster message handling: it runs for every streamed roster change.
7338
+ const emitRosterUpdate = Effect.fnUntraced(function* (
7339
+ nativeThreadId: string,
7340
+ activeContext: ActiveClaudeTurnContext | null,
7341
+ ) {
7342
+ const baseThread =
7343
+ activeContext?.input.providerThread ??
7344
+ (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId);
7345
+ if (baseThread === undefined) {
7346
+ return;
7347
+ }
7348
+ const status =
7349
+ activeContext === null
7350
+ ? ("idle" as const)
7351
+ : baseThread.status === "idle"
7352
+ ? ("active" as const)
7353
+ : baseThread.status;
7354
+ yield* emitProviderThreadRoster({ nativeThreadId, providerThread: baseThread, status });
7355
+ });
7356
+
7357
const applyBackgroundTaskRosterMessage = Effect.fnUntraced(function* (input: {
7358
readonly nativeThreadId: string;
7359
readonly message: SDKMessage;
@@ -7355,24 +7427,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
7427
return false;
7428
}
7429
7358
- const baseThread =
7359
- input.activeContext?.input.providerThread ??
7360
- (yield* Ref.get(lastProviderThreadByNativeThread)).get(input.nativeThreadId);
7361
- if (baseThread === undefined) {
7362
- return true;
7363
- }
7364
-
7365
- const status =
7366
- input.activeContext === null
7367
- ? ("idle" as const)
7368
- : baseThread.status === "idle"
7369
- ? ("active" as const)
7370
- : baseThread.status;
7371
- yield* emitProviderThreadRoster({
7372
- nativeThreadId: input.nativeThreadId,
7373
- providerThread: baseThread,
7374
- status,
7375
- });
7430
+ yield* emitRosterUpdate(input.nativeThreadId, input.activeContext);
7431
return true;
7432
});
7433
@@ -10231,6 +10286,40 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10286
),
10287
);
10288
}),
10289
+ awaitBackgroundTasks: Effect.fn("ClaudeAdapterV2.awaitBackgroundTasks")(
10290
+ function* ({ providerThread, taskIds, awaited }) {
10291
+ const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
10292
+ if (nativeThreadId == null) return { matched: [] };
10293
+ const roster = rosterForNativeThread(
10294
+ yield* Ref.get(pendingBackgroundTasksByNativeThread),
10295
+ nativeThreadId,
10296
+ );
10297
+ const matched = [...new Set(taskIds)].filter((taskId) => roster.has(taskId));
10298
+ if (matched.length === 0) return { matched };
10299
+ if (awaited) {
10300
+ yield* addTaskIdsToNativeThreadSet(
10301
+ awaitedBackgroundTasksByNativeThread,
10302
+ nativeThreadId,
10303
+ matched,
10304
+ );
10305
+ } else {
10306
+ for (const taskId of matched) {
10307
+ yield* clearTaskIdFromNativeThreadSet(
10308
+ awaitedBackgroundTasksByNativeThread,
10309
+ nativeThreadId,
10310
+ taskId,
10311
+ );
10312
+ }
10313
+ }
10314
+ const active = yield* Ref.get(activeTurn);
10315
+ yield* emitRosterUpdate(
10316
+ nativeThreadId,
10317
+ active?.nativeThreadId === nativeThreadId ? active : null,
10318
+ );
10319
+ return { matched };
10320
+ },
10321
+ (effect) => sdkMessageLock.withPermits(1)(effect),
10322
+ ),
10323
interruptTurn,
10324
stopSubagent: Effect.fn("ClaudeAdapterV2.stopSubagent")(function* (input) {
10325
const existing = yield* Ref.get(queryContext);
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+1
-1
@@ -2035,7 +2035,7 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
2035
completionWake: "always",
2036
continuationPending: true,
2037
runStatus: "completed",
2038
- lostWork: [{ kind: "monitor", label: "Gate attempt 9" }],
2038
+ lostWork: [{ kind: "monitor", label: "Gate attempt 9", awaited: true }],
2039
now,
2040
});
2041
yield* orchestrator.recoverDelegatedTasks;
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+4
-1
@@ -5954,6 +5954,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
5954
taskId: "pull-request-watch:github.com/pingdotgg/t3code#7",
5955
description: "Watching pull request #7",
5956
kind: "monitor",
5957
+ awaited: true,
5958
},
5959
]);
5960
assert.equal(yield* phase, "running");
@@ -5986,7 +5987,9 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
5987
lastRunOrdinal: 1,
5988
handoffIds: [],
5989
forkedFrom: null,
5989
- pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" as const }],
5990
+ pendingBackgroundTasks: [
5991
+ { taskId: "watch", kind: "monitor" as const, awaited: true as const },
5992
+ ],
5993
createdAt: completedAt,
5994
updatedAt: completedAt,
5995
};
apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts
+7
@@ -115,6 +115,13 @@ it("names a lost subagent by the id the agent resumes it with", () => {
115
}).label;
116
assert.lengthOf(longId, 160);
117
assert.isFalse(isAwaitedWork(cancelledRosterTaskWork({ kind: "command", taskId: "shell-2" })));
118
+ assert.isTrue(
119
+ isAwaitedWork(cancelledRosterTaskWork({ kind: "command", taskId: "tests", awaited: true })),
120
+ );
121
+ assert.isFalse(isAwaitedWork(cancelledRosterTaskWork({ kind: "monitor", taskId: "watchdog" })));
122
+ assert.isTrue(
123
+ isAwaitedWork(cancelledRosterTaskWork({ kind: "monitor", taskId: "ci", awaited: true })),
124
+ );
125
assert.equal(
126
cancelledTurnItemWork({
127
id: "item-1",
apps/server/src/orchestration-v2/RestartBackgroundNote.ts
+6
-4
@@ -118,6 +118,7 @@ export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTa
118
description === undefined ? task.taskId : `${description} (id ${task.taskId})`,
119
) ?? "background task",
120
id: task.taskId,
121
+ ...(task.awaited === true ? { awaited: true as const } : {}),
122
};
123
}
124
@@ -158,11 +159,12 @@ export function isRestartNoteSource(
159
}
160
161
/**
161
- * A shell does not wake it: most are dev servers that nobody waits on, so their
162
- * note waits for the next user message.
162
+ * Matches the Working-section hold: a shell or monitor wakes it only when the agent said it
163
+ * waits on it. Most are dev servers and their watchdogs, so their note waits for the next
164
+ * user message.
165
*/
164
-export function isAwaitedWork(work: Pick<Work, "kind">): boolean {
165
- return work.kind !== "shell";
166
+export function isAwaitedWork(work: Pick<Work, "kind" | "awaited">): boolean {
167
+ return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor");
168
}
169
170
export function runOutcome(
apps/server/src/orchestration-v2/RestartContinuation.test.ts
+2
-2
@@ -191,12 +191,12 @@ it("does not continue settled root runs with restart-cancelled background work",
191
});
192
193
it.effect.each(["completed", "waiting", "cancelled"] as const)(
194
- "wakes a %s run whose monitor the restart cancelled, with the note as its prompt",
194
+ "wakes a %s run whose awaited monitor the restart cancelled, with the note as its prompt",
195
(status) =>
196
Effect.gen(function* () {
197
const base = makeProjection();
198
const work = [
199
- { kind: "monitor" as const, label: "Watch CI run 42" },
199
+ { kind: "monitor" as const, label: "Watch CI run 42", awaited: true as const },
200
{ kind: "shell" as const, label: "vp run dev" },
201
];
202
const projection = {
apps/server/src/orchestration-v2/ThreadManagementService.test.ts
+104
@@ -3,6 +3,10 @@ import {
3
CommandId,
4
MessageId,
5
type OrchestrationV2Run,
6
+ type OrchestrationV2ProviderThread,
7
+ ProviderThreadId,
8
+ ProviderDriverKind,
9
+ ProviderSessionId,
10
type OrchestrationV2StoredEvent,
11
type OrchestrationV2ThreadProjection,
12
ProjectId,
@@ -12,6 +16,7 @@ import {
16
} from "@t3tools/contracts";
17
import * as Deferred from "effect/Deferred";
18
import * as DateTime from "effect/DateTime";
19
+import * as Option from "effect/Option";
20
import * as Effect from "effect/Effect";
21
import * as Fiber from "effect/Fiber";
22
import * as Layer from "effect/Layer";
@@ -23,7 +28,9 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
28
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
29
import * as Orchestrator from "./Orchestrator.ts";
30
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
31
+import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
32
import * as ThreadManagementService from "./ThreadManagementService.ts";
33
+import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
34
35
const layerReceiptsTest = CommandReceiptStore.layer.pipe(
36
Layer.provide(SqlitePersistence.layerMemory),
@@ -297,6 +304,103 @@ it.effect("waitForThread returns the cut run once its continuation is declined",
304
}),
305
);
306
307
+it.effect.each(["live", "no-session", "unsupported-runtime"] as const)(
308
+ "marks background work awaited on the thread's active provider thread with state %s",
309
+ (state) =>
310
+ Effect.gen(function* () {
311
+ const threadId = ThreadId.make("thread:background-wait");
312
+ const providerThreadId = ProviderThreadId.make("provider-thread:background-wait");
313
+ const providerSessionId = ProviderSessionId.make("provider-session:background-wait");
314
+ const driver = ProviderDriverKind.make("claudeAgent");
315
+ const now = yield* DateTime.now;
316
+ const providerThread: OrchestrationV2ProviderThread = {
317
+ id: providerThreadId,
318
+ driver,
319
+ providerInstanceId: ProviderInstanceId.make("claudeAgent"),
320
+ providerSessionId,
321
+ appThreadId: threadId,
322
+ ownerNodeId: null,
323
+ nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
324
+ nativeConversationHeadRef: null,
325
+ status: "idle",
326
+ firstRunOrdinal: 1,
327
+ lastRunOrdinal: 1,
328
+ handoffIds: [],
329
+ forkedFrom: null,
330
+ pendingBackgroundTasks: [{ taskId: "tests", kind: "command" }],
331
+ contextUsage: null,
332
+ nativeMetadata: null,
333
+ createdAt: now,
334
+ updatedAt: now,
335
+ };
336
+ const calls: Array<{ providerThreadId: ProviderThreadId; awaited: boolean }> = [];
337
+ const runtime = {
338
+ driver,
339
+ providerSessionId,
340
+ ...(state === "unsupported-runtime"
341
+ ? {}
342
+ : {
343
+ awaitBackgroundTasks: (input: {
344
+ readonly providerThread: OrchestrationV2ProviderThread;
345
+ readonly taskIds: ReadonlyArray<string>;
346
+ readonly awaited: boolean;
347
+ }) =>
348
+ Effect.sync(() => {
349
+ calls.push({
350
+ providerThreadId: input.providerThread.id,
351
+ awaited: input.awaited,
352
+ });
353
+ return { matched: input.taskIds.filter((taskId) => taskId === "tests") };
354
+ }),
355
+ }),
356
+ } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
357
+ const layerTest = ThreadManagementService.layer.pipe(
358
+ Layer.provide(
359
+ Layer.mergeAll(
360
+ Layer.mock(Orchestrator.OrchestratorV2)({
361
+ getThreadRecords: () =>
362
+ Effect.succeed({
363
+ thread: {
364
+ id: threadId,
365
+ deletedAt: null,
366
+ activeProviderThreadId: providerThreadId,
367
+ },
368
+ providerThreads: [providerThread],
369
+ } as unknown as OrchestrationV2ThreadProjection),
370
+ }),
371
+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
372
+ get: () =>
373
+ Effect.succeed(state === "no-session" ? Option.none() : Option.some(runtime)),
374
+ }),
375
+ ),
376
+ ),
377
+ Layer.provide(ServerSettings.layerTest()),
378
+ Layer.provide(layerReceiptsTest),
379
+ );
380
+ const result = yield* Effect.gen(function* () {
381
+ const service = yield* ThreadManagementService.ThreadManagementService;
382
+ return yield* service
383
+ .awaitBackgroundTasks({ threadId, taskIds: ["tests", "finished"], awaited: true })
384
+ .pipe(Effect.result);
385
+ }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer)));
386
+
387
+ if (state === "live") {
388
+ expect(result).toMatchObject({
389
+ success: { matched: ["tests"], unmatched: ["finished"] },
390
+ });
391
+ expect(calls).toEqual([{ providerThreadId, awaited: true }]);
392
+ } else {
393
+ expect(result).toMatchObject({
394
+ failure: {
395
+ _tag: "ThreadManagementBackgroundWaitError",
396
+ reason: state === "no-session" ? "unavailable" : "unsupported",
397
+ },
398
+ });
399
+ expect(calls).toEqual([]);
400
+ }
401
+ }),
402
+);
403
+
404
it.effect.each([
405
{ status: "completed" as const, settles: true },
406
{ status: "failed" as const, settles: false },
apps/server/src/orchestration-v2/ThreadManagementService.ts
+78
@@ -295,6 +295,26 @@ export class ThreadManagementProviderInstanceDisabledError extends Schema.Tagged
295
}
296
}
297
298
+export class ThreadManagementBackgroundWaitError extends Schema.TaggedError<ThreadManagementBackgroundWaitError>()(
299
+ "ThreadManagementBackgroundWaitError",
300
+ {
301
+ threadId: ThreadId,
302
+ reason: Schema.Literals(["unsupported", "unavailable", "failed"]),
303
+ cause: Schema.optional(Schema.Defect()),
304
+ },
305
+) {
306
+ override get message(): string {
307
+ switch (this.reason) {
308
+ case "unsupported":
309
+ return "This provider cannot mark background work as awaited.";
310
+ case "unavailable":
311
+ return "This thread has no live provider session.";
312
+ case "failed":
313
+ return "Failed to update the awaited background work.";
314
+ }
315
+ }
316
+}
317
+
318
export const ThreadManagementError = Schema.Union([
319
ThreadManagementThreadNotFoundError,
320
ThreadManagementRunNotFoundError,
@@ -421,6 +441,14 @@ export interface ThreadManagementServiceShape {
441
readonly stopWorkflow: (
442
input: OrchestrationV2StopWorkflowInput,
443
) => Effect.Effect<void, OrchestrationV2StopWorkflowError>;
444
+ readonly awaitBackgroundTasks: (input: {
445
+ readonly threadId: ThreadId;
446
+ readonly taskIds: ReadonlyArray<string>;
447
+ readonly awaited: boolean;
448
+ }) => Effect.Effect<
449
+ { readonly matched: ReadonlyArray<string>; readonly unmatched: ReadonlyArray<string> },
450
+ ThreadManagementBackgroundWaitError
451
+ >;
452
readonly stopDelegatedTasks: (input: {
453
readonly threadId: ThreadId;
454
readonly commandId: CommandId;
@@ -1097,6 +1125,55 @@ const make = Effect.gen(function* () {
1125
(effect, input) => effect.pipe((effect) => threadDispatch.withLock(input.threadId, effect)),
1126
);
1127
1128
+ const awaitBackgroundTasks: ThreadManagementServiceShape["awaitBackgroundTasks"] = Effect.fn(
1129
+ "ThreadManagementService.awaitBackgroundTasks",
1130
+ )(function* (input) {
1131
+ const unavailable = (cause?: unknown) =>
1132
+ new ThreadManagementBackgroundWaitError({
1133
+ threadId: input.threadId,
1134
+ reason: "unavailable",
1135
+ ...(cause === undefined ? {} : { cause }),
1136
+ });
1137
+ const records = yield* orchestrator
1138
+ .getThreadRecords(input.threadId, ["providerThreads"])
1139
+ .pipe(Effect.mapError(unavailable));
1140
+ const providerThread = records.providerThreads.find(
1141
+ (candidate) =>
1142
+ candidate.id === records.thread.activeProviderThreadId &&
1143
+ candidate.appThreadId === input.threadId,
1144
+ );
1145
+ if (records.thread.deletedAt !== null || providerThread?.providerSessionId == null) {
1146
+ return yield* unavailable();
1147
+ }
1148
+ const runtime = yield* sessions
1149
+ .get(providerThread.providerSessionId)
1150
+ .pipe(Effect.mapError(unavailable));
1151
+ if (Option.isNone(runtime)) {
1152
+ return yield* unavailable();
1153
+ }
1154
+ if (runtime.value.awaitBackgroundTasks === undefined) {
1155
+ return yield* new ThreadManagementBackgroundWaitError({
1156
+ threadId: input.threadId,
1157
+ reason: "unsupported",
1158
+ });
1159
+ }
1160
+ const { matched } = yield* runtime.value
1161
+ .awaitBackgroundTasks({ providerThread, taskIds: input.taskIds, awaited: input.awaited })
1162
+ .pipe(
1163
+ Effect.timeout("15 seconds"),
1164
+ Effect.mapError(
1165
+ (cause) =>
1166
+ new ThreadManagementBackgroundWaitError({
1167
+ threadId: input.threadId,
1168
+ reason: "failed",
1169
+ cause,
1170
+ }),
1171
+ ),
1172
+ );
1173
+ const matchedIds = new Set(matched);
1174
+ return { matched, unmatched: input.taskIds.filter((taskId) => !matchedIds.has(taskId)) };
1175
+ });
1176
+
1177
const stopDelegatedTasks: ThreadManagementServiceShape["stopDelegatedTasks"] = Effect.fn(
1178
"ThreadManagementService.stopDelegatedTasks",
1179
)(function* (input) {
@@ -1189,6 +1266,7 @@ const make = Effect.gen(function* () {
1266
interruptThread,
1267
stopDelegatedTasks,
1268
stopWorkflow,
1269
+ awaitBackgroundTasks,
1270
getThreadEventSequence: orchestrator.getThreadEventSequence,
1271
recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1272
delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+14
-5
@@ -3478,10 +3478,11 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3478
["completed", "shell", false],
3479
["waiting", "shell", false],
3480
["cancelled", "shell", false],
3481
- ["failed", "monitor", false],
3482
- ["completed", "monitor", true],
3483
- ["waiting", "monitor", true],
3484
- ["cancelled", "monitor", true],
3481
+ ["completed", "watchdog-monitor", false],
3482
+ ["failed", "awaited-monitor", false],
3483
+ ["completed", "awaited-monitor", true],
3484
+ ["waiting", "awaited-monitor", true],
3485
+ ["cancelled", "awaited-monitor", true],
3486
] as const)(
3487
"admits a restart continuation of a %s run that lost a %s: %s",
3488
([status, kind, admitted]) =>
@@ -3539,7 +3540,15 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3540
occurredAt: now,
3541
payload: {
3542
runId: original.id,
3542
- restartCancelledBackgroundWork: [{ kind, label: "sleep 25" }],
3543
+ restartCancelledBackgroundWork: [
3544
+ kind === "shell"
3545
+ ? { kind, label: "sleep 25" }
3546
+ : {
3547
+ kind: "monitor",
3548
+ label: "sleep 25",
3549
+ ...(kind === "awaited-monitor" ? { awaited: true as const } : {}),
3550
+ },
3551
+ ],
3552
},
3553
},
3554
],
apps/server/src/relay/AgentAwarenessRelay.test.ts
+3
-2
@@ -215,6 +215,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
215
settleThread: unused,
216
interruptThread: unused,
217
stopWorkflow: () => Effect.die("unused stopWorkflow"),
218
+ awaitBackgroundTasks: unused,
219
stopDelegatedTasks: unused,
220
getThreadEventSequence: unused,
221
recoverDelegatedTask: unused,
@@ -418,14 +419,14 @@ describe("AgentAwarenessRelay", () => {
419
}).pipe(Effect.scoped),
420
);
421
421
- it.effect("keeps settled live work until its monitor finishes", () =>
422
+ it.effect("keeps settled live work until its awaited monitor finishes", () =>
423
Effect.gen(function* () {
424
const { relay, currentShell, publications } = yield* makeTestRelay();
425
yield* relay.publishThread(THREAD_ID);
426
const held = shell({
427
status: "completed",
428
settledOverride: "settled",
428
- pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],
429
+ pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
430
});
431
yield* Ref.set(currentShell, held);
432
yield* relay.publishThread(THREAD_ID);
apps/web/src/components/Sidebar.logic.test.ts
+35
-6
@@ -446,7 +446,9 @@ describe("resolveThreadStatusPill", () => {
446
resolveThreadStatusPill({
447
thread: {
448
...baseThread,
449
- pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],
449
+ pendingBackgroundTasks: [
450
+ { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
451
+ ],
452
runtime: {
453
...baseThread.runtime,
454
status: "idle",
@@ -961,16 +963,38 @@ describe("navigation after parking a thread", () => {
963
964
describe("unseen completion with background work", () => {
965
it.each([
964
- { kind: "command", status: "ready", topStatus: "done", receded: false, pill: "Completed" },
965
- { kind: "monitor", status: "waiting", topStatus: "waiting", receded: true, pill: "Waiting" },
966
- ] as const)("presents a completed thread with a $kind roster", (expected) => {
966
+ {
967
+ roster: "dev server",
968
+ task: { kind: "command" },
969
+ status: "ready",
970
+ topStatus: "done",
971
+ receded: false,
972
+ pill: "Completed",
973
+ },
974
+ {
975
+ roster: "dev server watchdog",
976
+ task: { kind: "monitor" },
977
+ status: "ready",
978
+ topStatus: "done",
979
+ receded: false,
980
+ pill: "Completed",
981
+ },
982
+ {
983
+ roster: "awaited command",
984
+ task: { kind: "command", awaited: true },
985
+ status: "waiting",
986
+ topStatus: "waiting",
987
+ receded: true,
988
+ pill: "Waiting",
989
+ },
990
+ ] as const)("presents a completed thread with a $roster roster", (expected) => {
991
const thread = presentThreadShell(localEnvironmentId, {
992
...makeThreadFixture().source,
993
latestRunId: RunId.make("run-background-completion"),
994
status: "completed",
995
latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
996
lastVisitedAt: DateTime.makeUnsafe("2026-06-20T00:59:00.000Z"),
973
- pendingBackgroundTasks: [{ taskId: "background-work", kind: expected.kind }],
997
+ pendingBackgroundTasks: [{ taskId: "background-work", ...expected.task }],
998
});
999
const status = resolveSidebarThreadStatus(thread);
1000
const isUnread = hasUnseenCompletion(thread);
@@ -1001,7 +1025,12 @@ describe("Working shelf (beta)", () => {
1025
lastError: null,
1026
updatedAt: "2026-03-09T10:00:00.000Z",
1027
};
1004
- const backgroundTask = { taskId: "bg-1", description: "Watch build", kind: "monitor" as const };
1028
+ const backgroundTask = {
1029
+ taskId: "bg-1",
1030
+ description: "Watch build",
1031
+ kind: "monitor" as const,
1032
+ awaited: true as const,
1033
+ };
1034
const idle = {
1035
hasActionableProposedPlan: false,
1036
hasPendingApprovals: false,
docs/internals/server-updates.md
+5
-4
@@ -72,10 +72,11 @@ opt-out. The
72
requires matching durable run, provider thread, session, and native resume identity.
73
Queued runs never started, so recovery holds them and continues the run they wait
74
behind. A settled run qualifies only when the restart cancels work the agent waits on
75
-(a monitor, subagent, or background task) and its session was live, so stale records
76
-from an older crash never wake it. Its continuation prompt is the note of what will not
77
-report back. A shell alone does not wake a settled run: most are dev servers nobody
78
-waits on, so that note waits for the next user message.
75
+(a subagent, a background task, or a shell or monitor the agent marked with
76
+`t3_background_wait`) and its session was live, so stale records from an older crash
77
+never wake it. Its continuation prompt is the note of what will not report back. An
78
+unmarked shell or monitor does not wake a settled run: most are dev servers and their
79
+watchdogs that nobody waits on, so that note waits for the next user message.
80
81
Recovery retires effects tied to the lost process and records continuation intent
82
in the durable outbox. That intent survives another restart before provider startup.
docs/user/thread-sidebar.md
+8
-6
@@ -120,10 +120,12 @@ open.
120
121
Turn on **Settings → General → Working section (beta)** on web and desktop, or **Settings →
122
Thread behavior → Working section** on iOS and Android, to move threads that are working or
123
-monitoring into a collapsed **Working** section below the active list. A thread returns to the top
124
-of the active list when it finishes, fails, or needs an approval or answer. The Working section
125
-lists the thread you last sent work to first. Pinned threads stay in the pinned section. Each
126
-device keeps its own choice.
123
+waiting on work they will resume from into a collapsed **Working** section below the active list.
124
+That includes subagents, watched pull requests, and background commands or monitors the agent
125
+says it is waiting on. A dev server or other process an agent leaves running does not keep a thread
126
+there. A thread returns to the top of the active list when it finishes, fails, or needs an approval or
127
+answer. The Working section lists the thread you last sent work to first. Pinned threads stay in
128
+the pinned section. Each device keeps its own choice.
129
130
While this is on, the active list is ordered by when each thread last came back to you, so you
131
cannot drag or move threads within it. Your saved order returns when you turn it off.
@@ -153,8 +155,8 @@ Press `Escape` while dragging to cancel.
155
By default, environments settle inactive threads after three days and settle
156
threads whose pull request merged. A closed pull request can also settle an idle
157
thread. An empty thread's inactivity counts from when it was created.
156
-Work in progress, pending questions or approvals, and live background work
157
-prevent automatic settlement. An open pull request does not prevent inactivity
158
+Work in progress, pending questions or approvals, and background work the agent
159
+is waiting on prevent automatic settlement. An open pull request does not prevent inactivity
160
settlement unless you turn on **Keep threads with a PR** in **Settings → General**,
161
but an old closed or merged pull request does not settle work you
162
resumed after it closed. Only your own messages count as resuming. A turn that
docs/user/updating.md
+4
-3
@@ -49,9 +49,10 @@ different value, use **Apply to all** in Settings after it connects.
49
T3 Code must start again on that machine;
50
the setting does not enable automatic startup. Terminal commands may still be
51
interrupted, and threads without saved provider resume state need a new message.
52
-A thread that finished its turn to wait on a monitor, subagent, or background task
53
-is woken and told that this work stopped. A background shell, such as a dev server,
54
-does not wake it; the thread learns about it with your next message.
52
+A thread that finished its turn to wait on a subagent, a background task, or a
53
+command or monitor the agent said it was waiting on is woken and told that this work
54
+stopped. Other background shells and monitors, such as a dev server and its
55
+watchdog, do not wake it; the thread learns about them with your next message.
56
A thread is not resumed while it waits for your approval, answer, or secret, or
57
while it is archived, snoozed, or settled. After three automatic resumes in a row,
58
the thread waits for your next message.
packages/client-runtime/src/state/entities.test.ts
+14
-6
@@ -73,7 +73,11 @@ describe("V2 client presentation", () => {
73
});
74
75
it("parks a thread that never ran at idle while a pull request watch holds it", () => {
76
- const watch = { taskId: "pull-request-watch:github.com/acme/app#1", kind: "monitor" as const };
76
+ const watch = {
77
+ taskId: "pull-request-watch:github.com/acme/app#1",
78
+ kind: "monitor" as const,
79
+ awaited: true as const,
80
+ };
81
const watched = presentThreadShell(environmentId, {
82
...v2ThreadShell,
83
latestRunId: null,
@@ -141,7 +145,9 @@ describe("V2 client presentation", () => {
145
activeRunId: null,
146
status: "failed",
147
lastError: "Provider turn failed",
144
- pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],
148
+ pendingBackgroundTasks: [
149
+ { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
150
+ ],
151
});
152
153
expect(shell.runtime).toMatchObject({ status: "failed", lastError: "Provider turn failed" });
@@ -192,7 +198,9 @@ describe("V2 client presentation", () => {
198
latestRunId: runId,
199
activeRunId: runId,
200
status: "running",
195
- pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],
201
+ pendingBackgroundTasks: [
202
+ { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
203
+ ],
204
});
205
206
expect(shell.latestRun).toMatchObject({ runId, status: "running" });
@@ -201,7 +209,7 @@ describe("V2 client presentation", () => {
209
activeRunId: runId,
210
});
211
expect(shell.pendingBackgroundTasks).toEqual([
204
- { taskId: "bg-1", description: "Watch build", kind: "monitor" },
212
+ { taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
213
]);
214
});
215
@@ -403,7 +411,7 @@ describe("V2 client presentation", () => {
411
).toMatchObject({ status, activeRunId: null });
412
}
413
406
- for (const kind of ["monitor", "background_task"] as const) {
414
+ for (const held of [{ kind: "monitor", awaited: true }, { kind: "background_task" }] as const) {
415
const providerThread = {
416
id: ProviderThreadId.make("provider-thread-background"),
417
driver: ProviderDriverKind.make("claudeCode"),
@@ -418,7 +426,7 @@ describe("V2 client presentation", () => {
426
lastRunOrdinal: 1,
427
handoffIds: [],
428
forkedFrom: null,
421
- pendingBackgroundTasks: [{ taskId: "background-task", kind }],
429
+ pendingBackgroundTasks: [{ taskId: "background-task", ...held }],
430
createdAt: now,
431
updatedAt: now,
432
};
packages/client-runtime/src/state/models.ts
+4
-4
@@ -211,10 +211,10 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
211
);
212
}
213
214
-// Only work that wakes the agent holds it: commands it left running, such as a
215
-// dev server, present the run's own status (#14872). The server suppresses the
216
-// roster while an interruptible activity run exists, so a remaining roster is
217
-// stronger than checkpoint-oriented waiting.
214
+// Only work the agent waits on holds it: commands and monitors it left running
215
+// unmarked, such as a dev server, present the run's own status (#14872). The
216
+// server suppresses the roster while an interruptible activity run exists, so a
217
+// remaining roster is stronger than checkpoint-oriented waiting.
218
function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
219
const parkAtIdle =
220
backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []) &&
packages/client-runtime/src/t3ToolSummary.ts
+3
@@ -176,6 +176,9 @@ export function summarizeT3ToolCalls(
176
case "task-status":
177
label = phrase("Checked", "check", `task status ${times}`);
178
break;
179
+ case "background-wait":
180
+ label = phrase("Updated", "update", `background waits ${times}`);
181
+ break;
182
case "task-cancel":
183
label = phrase(
184
"Requested cancellation of",
packages/client-runtime/src/work-log/presentation.ts
+1
@@ -490,6 +490,7 @@ function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction)
490
case "thread-send":
491
case "thread-interrupt":
492
case "workflow-stop":
493
+ case "background-wait":
494
case "schedule-create":
495
case "schedule-update":
496
case "schedule-delete":
packages/contracts/src/orchestrationV2.ts
+7
@@ -556,6 +556,8 @@ export const OrchestrationV2RestartCancelledBackgroundWork = Schema.Struct({
556
kind: Schema.Literals(["subagent", "shell", "monitor", "task"]),
557
label: TrimmedNonEmptyString,
558
id: Schema.optional(TrimmedNonEmptyString),
559
+ /** The agent was waiting on this work, so its restart note wakes the agent even for a shell. */
560
+ awaited: Schema.optional(Schema.Literal(true)),
561
});
562
export type OrchestrationV2RestartCancelledBackgroundWork =
563
typeof OrchestrationV2RestartCancelledBackgroundWork.Type;
@@ -874,6 +876,11 @@ const PendingBackgroundTaskFields = {
876
description: Schema.optional(TrimmedNonEmptyString),
877
/** The subagent task that started this work and waits on it. */
878
parentTaskId: Schema.optional(TrimmedNonEmptyString),
879
+ /**
880
+ * The agent declared it resumes when this work ends, so the thread holds like it does for a
881
+ * subagent. Only the agent knows whether a command is a wait or a dev server it left running.
882
+ */
883
+ awaited: Schema.optional(Schema.Literal(true)),
884
};
885
886
export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
packages/provider-core/src/server/ProviderAdapter.ts
+9
@@ -609,6 +609,15 @@ export interface ProviderAdapterV2SessionRuntime {
609
readonly providerThread: OrchestrationV2ProviderThread;
610
readonly taskId: string;
611
}) => Effect.Effect<void, ProviderAdapterV2Error>;
612
+ /**
613
+ * Marks or unmarks background tasks the agent will resume from, using the ids the agent saw.
614
+ * Ids not running on this provider thread come back unmatched and change nothing.
615
+ */
616
+ readonly awaitBackgroundTasks?: (input: {
617
+ readonly providerThread: OrchestrationV2ProviderThread;
618
+ readonly taskIds: ReadonlyArray<string>;
619
+ readonly awaited: boolean;
620
+ }) => Effect.Effect<{ readonly matched: ReadonlyArray<string> }, ProviderAdapterV2Error>;
621
readonly interruptTurn: (
622
input: ProviderAdapterV2InterruptInput,
623
) => Effect.Effect<void, ProviderAdapterV2Error>;
packages/shared/src/agentAwareness.test.ts
+8
-3
@@ -153,7 +153,7 @@ describe("projectThreadAwarenessV2", () => {
153
},
154
);
155
156
- it("keeps settled work held open by a monitor", () => {
156
+ it("keeps settled work held open by an awaited monitor", () => {
157
expect(
158
projectThreadAwarenessV2({
159
environmentId: "env-1" as EnvironmentId,
@@ -161,7 +161,7 @@ describe("projectThreadAwarenessV2", () => {
161
thread: v2Thread({
162
status: "completed",
163
settledOverride: "settled",
164
- pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],
164
+ pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }],
165
}),
166
}),
167
).toMatchObject({ phase: "running" });
@@ -169,7 +169,12 @@ describe("projectThreadAwarenessV2", () => {
169
170
it.each([
171
["only a dev server", "completed", [{ taskId: "dev", kind: "command" }]],
172
- ["a monitor", "running", [{ taskId: "watch", kind: "monitor" }]],
172
+ ["a dev server's watchdog monitor", "completed", [{ taskId: "watch", kind: "monitor" }]],
173
+ [
174
+ "a command the agent waits on",
175
+ "running",
176
+ [{ taskId: "tests", kind: "command", awaited: true }],
177
+ ],
178
[
179
"a dev server and a subagent",
180
"running",
packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts
+15
-1
@@ -5,6 +5,17 @@ import {
5
derivePendingBackgroundWork,
6
} from "./orchestrationV2PendingBackgroundWork.ts";
7
8
+describe("backgroundWorkHoldsCompletion", () => {
9
+ it.each([
10
+ ["a dev server", false, [{ taskId: "dev", kind: "command" }]],
11
+ ["a dev server's watchdog monitor", false, [{ taskId: "watch", kind: "monitor" }]],
12
+ ["a command the agent waits on", true, [{ taskId: "tests", kind: "command", awaited: true }]],
13
+ ["a subagent", true, [{ taskId: "review", kind: "subagent" }]],
14
+ ] as const)("with %s pending, holds completion: %s", (_case, holds, tasks) => {
15
+ expect(backgroundWorkHoldsCompletion(tasks)).toBe(holds);
16
+ });
17
+});
18
+
19
describe("derivePendingBackgroundWork", () => {
20
it("takes each subagent item's instance from its joined owner", () => {
21
const owner = ProviderInstanceId.make("claude-owner");
@@ -309,6 +320,7 @@ describe("derivePendingBackgroundWork kinds", () => {
320
id: "pt-1" as never,
321
pendingBackgroundTasks: [
322
{ taskId: "bash", kind: "command" },
323
+ { taskId: "tests", kind: "command", awaited: true },
324
{ taskId: "watch", kind: "monitor" },
325
{ taskId: "workflow", kind: "background_task" },
326
],
@@ -335,6 +347,7 @@ describe("derivePendingBackgroundWork kinds", () => {
347
});
348
expect(tasks).toEqual([
349
{ taskId: "bash", kind: "command" },
350
+ { taskId: "tests", kind: "command", awaited: true },
351
{ taskId: "watch", kind: "monitor" },
352
{ taskId: "workflow", kind: "background_task" },
353
{
@@ -376,7 +389,7 @@ describe("derivePendingBackgroundWork kinds", () => {
389
link(3, { source: "stack-dismissed" }),
390
];
391
379
- it("keeps a settled run waiting on each visible watch, as a monitor", () => {
392
+ it("keeps a settled run waiting on each visible watch, as an awaited monitor", () => {
393
const tasks = derivePendingBackgroundWork({
394
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
395
providerThreads: [],
@@ -388,6 +401,7 @@ describe("derivePendingBackgroundWork kinds", () => {
401
taskId: "pull-request-watch:github.com/acme/app#1",
402
description: "Watching pull request #1",
403
kind: "monitor",
404
+ awaited: true,
405
},
406
]);
407
expect(backgroundWorkHoldsCompletion(tasks)).toBe(true);
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+8
-3
@@ -92,17 +92,21 @@ export function deriveBlockedOnThreadWait(input: {
92
}
93
94
export function backgroundWorkHoldsCompletion(
95
- tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
95
+ tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind" | "awaited">>,
96
): boolean {
97
- return tasks.some((task) => backgroundWorkKindHoldsCompletion(task.kind));
97
+ return tasks.some(
98
+ (task) => task.awaited === true || backgroundWorkKindHoldsCompletion(task.kind),
99
+ );
100
}
101
102
+// Commands and monitors are as often a dev server or its watchdog as a wait, so they hold
103
+// only when the agent marks them awaited.
104
function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind"]): boolean {
105
switch (kind) {
106
case "command":
107
+ case "monitor":
108
return false;
109
case "subagent":
105
- case "monitor":
110
case "background_task":
111
return true;
112
}
@@ -308,6 +312,7 @@ function pullRequestWatchTasks(
312
taskId: `pull-request-watch:${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
313
description: `Watching pull request #${link.number}`,
314
kind: "monitor" as const,
315
+ awaited: true as const,
316
},
317
],
318
);
packages/shared/src/t3McpToolPresentation.ts
+5
@@ -22,6 +22,7 @@ export type T3McpToolSummaryAction =
22
| "thread-wait"
23
| "thread-interrupt"
24
| "workflow-stop"
25
+ | "background-wait"
26
| "thread-configuration"
27
| "thread-configure"
28
| "thread-fork"
@@ -154,6 +155,10 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
155
["Stop", "Stopping", "Requested a stop for", "a workflow"],
156
"workflow-stop",
157
),
158
+ t3_background_wait: tool(
159
+ ["Update", "Updating", "Updated", "background waits"],
160
+ "background-wait",
161
+ ),
162
t3_thread_interrupt: tool(
163
["Interrupt", "Interrupting", "Requested an interrupt of", "a T3 thread"],
164
"thread-interrupt",