Skip to content

Commit 91ea0e1

Browse files
t3dotggLovelyCodeMonkeyclaude
authored
fix(threads): Working holds only background work the agent waits on (#24610)
Co-authored-by: lovelycodemonkey <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 27805ef commit 91ea0e1

28 files changed

Lines changed: 641 additions & 79 deletions

‎apps/mobile/src/features/threads/threadListV2.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,19 +101,20 @@ describe("resolveThreadListV2Status", () => {
101101
});
102102

103103
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" },
106107
] 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 }) => {
109110
const thread = presentThreadShell(
110111
environmentId,
111112
makeRawThreadShell({
112113
latestRunId: RunId.make("run-background-completion"),
113114
status: "completed",
114115
latestRunCompletedAt: DateTime.makeUnsafe(NOW),
115116
lastVisitedAt: DateTime.makeUnsafe("2026-06-01T23:59:00.000Z"),
116-
pendingBackgroundTasks: [{ taskId: "background-work", kind }],
117+
pendingBackgroundTasks: [{ taskId: "background-work", ...task }],
117118
}),
118119
);
119120

‎apps/server/src/mcp/toolkits/orchestrator/handlers.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,27 @@ const handlers = {
5757
);
5858
}),
5959
),
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+
),
6081
schedule_task: McpToolAccess.startsThreads(
6182
() => ({}),
6283
(input) =>

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
OrchestratorMcpThreadWaitResult,
3232
ThreadMetadataMcpUpdateInput,
3333
ThreadMetadataMcpUpdateResult,
34+
TrimmedNonEmptyString,
3435
} from "@t3tools/contracts";
3536
import { Tool, Toolkit } from "effect/ai";
3637
import * as Schema from "effect/Schema";
@@ -116,6 +117,25 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {
116117
.annotate(Tool.Title, "Stop a workflow")
117118
.annotate(Tool.Destructive, true);
118119

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+
119139
const ScheduleTaskTool = Tool.make("schedule_task", {
120140
description:
121141
"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(
279299
TaskStatusTool,
280300
TaskCancelTool,
281301
WorkflowStopTool,
302+
BackgroundWaitTool,
282303
ScheduleTaskTool,
283304
ListScheduledTasksTool,
284305
UpdateScheduledTaskTool,

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
type ModelSelection,
3636
NodeId,
3737
type OrchestrationV2AppThread,
38+
type OrchestrationV2PendingBackgroundTask,
3839
type OrchestrationV2ProviderThread,
3940
ProjectId,
4041
ProviderInstanceId,
@@ -565,6 +566,7 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
565566
assert.equal(systemPrompt.type, "preset");
566567
assert.equal(systemPrompt.preset, "claude_code");
567568
assert.include(systemPrompt.append ?? "", "Use `delegate_task`");
569+
assert.include(systemPrompt.append ?? "", "call `t3_background_wait`");
568570
const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
569571
assert.equal(logged.hasMcpServers, true);
570572
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
@@ -2202,6 +2204,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22022204
yield* Queue.unbounded<
22032205
Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "plan.updated" }>
22042206
>();
2207+
const providerThreadReceipts =
2208+
yield* Queue.unbounded<
2209+
Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "provider_thread.updated" }>
2210+
>();
22052211
let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
22062212
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
22072213
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
@@ -2329,6 +2335,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
23292335
if (event.type === "plan.updated") {
23302336
yield* Queue.offer(planReceipts, event);
23312337
}
2338+
if (event.type === "provider_thread.updated") {
2339+
yield* Queue.offer(providerThreadReceipts, event);
2340+
}
23322341
if (event.type === "turn_item.updated" && event.turnItem.type === "system_notice") {
23332342
yield* Queue.offer(systemNoticeReceipts, event);
23342343
}
@@ -2372,6 +2381,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
23722381
systemNoticeReceipts,
23732382
runtimeRequestReceipts,
23742383
planReceipts,
2384+
providerThreadReceipts,
23752385
getOpenedOptions: () => openedOptions,
23762386
terminalEvents,
23772387
hasPendingBackgroundWork,
@@ -6425,6 +6435,132 @@ describe("ClaudeAdapterV2 background wake turns", () => {
64256435
),
64266436
);
64276437

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+
64286564
it.effect("keeps a running Claude monitor typed after many newer monitors end", () =>
64296565
Effect.scoped(
64306566
Effect.gen(function* () {

0 commit comments

Comments
 (0)