Skip to content
Open
62 changes: 62 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12505,6 +12505,57 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
}),
);
// A sleep is a timer the agent ends its turn on, so a restart must wake it.
const sleeps = [
["timer", "sleep 1740; date", true],
["computed_timer", "sleep $((29 * 60)); date", true],
["quoted_timer", 'sleep "60" && date', true],
["single_quoted_timer", "sleep '60'; date", true],
["quoted_computed_timer", 'sleep "$((29 * 60))"; date', true],
["expanded_timer", 'sleep "${DELAY:-60}"; date', true],
["unit_timer", 'sleep 5m && echo "Time to check the build"', true],
["quoted_note_timer", 'sleep 60 && echo "Timer finished; check build"', true],
["endless_sleep", "sleep infinity", false],
["delayed_server", "sleep 5 && npm run dev", false],
["substituted_server", 'sleep 60; echo "$(npm run dev)"', false],
] as const;
yield* Queue.offer(
harness.sdkMessages,
claudeSdkFrame({
type: "assistant",
message: {
model: "claude-sonnet-4-6",
id: "msg_background_timer",
type: "message",
role: "assistant",
content: sleeps.map(([taskId, command]) => ({
type: "tool_use",
id: `toolu_${taskId}`,
name: "Bash",
input: { command, run_in_background: true },
})),
},
parent_tool_use_id: null,
uuid: "background-timer-launch",
session_id: WAKE_NATIVE_SESSION,
}),
);
for (const [index, [taskId]] of sleeps.entries()) {
yield* Queue.offer(
harness.sdkMessages,
claudeSdkFrame({
type: "system",
subtype: "task_started",
task_id: taskId,
tool_use_id: `toolu_${taskId}`,
description: "Wait before the next check",
is_backgrounded: true,
task_type: "local_bash",
uuid: `00000000-0000-4000-8000-00000000021${index}`,
session_id: WAKE_NATIVE_SESSION,
}),
);
}
yield* Queue.offer(harness.sdkMessages, turnOneResult);
yield* harness.awaitTerminal(1);

Expand All @@ -12515,6 +12566,17 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0];
assert.equal(started?.taskId, WAKE_TASK_ID);
assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID);
assert.deepEqual(
(afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? []).map((task) => [
task.taskId,
task.awaited === true,
]),
[
[WAKE_TASK_ID, false],
["moved-build", false],
...sleeps.map(([taskId, , awaited]) => [taskId, awaited]),
],
);

const command = harness.events.find(
(event) =>
Expand Down
76 changes: 71 additions & 5 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2139,6 +2139,67 @@ function parseClaudeInteger(text: string): number {
return Number.parseInt(value, 10);
}

const CLAUDE_SLEEP_DURATION = String.raw`(?:\d[\w.]*|\$\(\([\d\s+*/%-]+\)\)|\$\{\w+(?::?[-=]\d[\w.]*)?\}|\$\w+)`;
const CLAUDE_SLEEP_TIMER_START = new RegExp(
String.raw`^[ \t\n]*sleep[ \t]+(?:${CLAUDE_SLEEP_DURATION}|"${CLAUDE_SLEEP_DURATION}"|'\d[\w.]*')[ \t]*(?:$|;|&&|\n)`,
);
// Bash separates words only with spaces and tabs, so `\s` would read `true\rnpm` as `true`.
const CLAUDE_SLEEP_TIMER_REPORT = /^[ \t]*(?:$|(?:date|echo|printf|true|:)(?:[ \t]|$))/;

// A background command that only sleeps for a finite time, then at most prints the time or a
// note, is a timer the agent set to check back, which Claude wakes it for when it ends. Any other
// step (`sleep 5 && npm run dev`) may never end, so that command is not a timer.
function isClaudeSleepTimer(command: string | undefined): boolean {
const start = command === undefined ? null : CLAUDE_SLEEP_TIMER_START.exec(command);
if (command === undefined || start === null) return false;
const steps = splitClaudeSleepTimerSteps(command.slice(start[0].length));
return steps !== undefined && steps.every((step) => CLAUDE_SLEEP_TIMER_REPORT.test(step));
}

// Splits at unquoted `;`, `&&` and newlines. Gives up on anything a report never needs that could
// run or hide another command: pipes, `||`, a lone `&`, subshells, heredocs, substitutions, `${…}`,
// `$'…'`, comments, and unbalanced quotes or escapes.
function splitClaudeSleepTimerSteps(tail: string): string[] | undefined {
const steps: string[] = [];
let step = "";
let quote: string | undefined;
for (let index = 0; index < tail.length; index++) {
const char = tail[index] ?? "";
const next = tail[index + 1] ?? "";
if (quote === "'") {
if (char === "'") quote = undefined;
step += char;
continue;
}
if (char === "\\") {
if (next === "") return undefined;
step += char + next;
index++;
continue;
}
if (char === "`" || (char === "$" && "({'\"".includes(next) && next !== "")) return undefined;
if (quote === '"') {
if (char === '"') quote = undefined;
step += char;
continue;
}
if (char === "'" || char === '"') {
quote = char;
} else if (char === ";" || char === "\n" || (char === "&" && next === "&")) {
steps.push(step);
step = "";
if (char === "&") index++;
continue;
} else if (char === "&" ? next !== ">" && tail[index - 1] !== ">" : "|()<#".includes(char)) {
return undefined;
}
step += char;
}
if (quote !== undefined) return undefined;
steps.push(step);
return steps;
}

// Claude Code defers MCP tools behind ToolSearch, so the agent only finds
// t3_background_wait when the system prompt says when to reach for it.
const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = `
Expand Down Expand Up @@ -6821,17 +6882,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
nativeThreadId: string,
task: OrchestrationV2PendingBackgroundTask,
) {
const startedMonitor = yield* Ref.modify(
const startedWait = yield* Ref.modify(
pendingBackgroundTasksByNativeThread,
(current) => {
const roster = new Map(rosterForNativeThread(current, nativeThreadId));
const startedMonitor =
task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor";
const previous = roster.get(task.taskId);
const startedWait =
task.kind === "monitor"
? previous?.kind !== "monitor"
: task.kind === "command" &&
previous?.command === undefined &&
isClaudeSleepTimer(task.command);
roster.set(task.taskId, task);
return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const;
return [startedWait, new Map(current).set(nativeThreadId, roster)] as const;
},
);
if (startedMonitor) {
if (startedWait) {
yield* addTaskIdsToNativeThreadSet(
awaitedBackgroundTasksByNativeThread,
nativeThreadId,
Expand Down
4 changes: 2 additions & 2 deletions docs/user/thread-sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ open.

Threads that are working or waiting on work they will resume from move into a collapsed
**Working** section below the active list.
That includes subagents, watched pull requests with checks still running, Claude monitors,
and background commands or other monitors the agent says it is waiting on. A dev server or other process an agent leaves running does not keep a thread
That includes subagents, watched pull requests with checks still running, Claude monitors and
`sleep` timers, and background commands or other monitors the agent says it is waiting on. A dev server or other process an agent leaves running does not keep a thread
there. A thread returns to the top of the active list when it finishes, fails, or needs an approval or
answer. The Working section lists the thread you last sent work to first. Pinned threads stay in
the pinned section.
Expand Down
2 changes: 1 addition & 1 deletion docs/user/updating.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ T3 Code must start again on that machine;
the setting does not enable automatic startup. Terminal commands may still be
interrupted, and threads without saved provider resume state need a new message.
A thread that finished its turn to wait on a subagent, a background task, a Claude
monitor, or a command or other monitor the agent said it was waiting on is woken and told that this work
monitor or `sleep` timer, or a command or other monitor the agent said it was waiting on is woken and told that this work
stopped. Other background shells and monitors, such as a dev server and its
watchdog, do not wake it; the thread learns about them with your next message.
A thread is not resumed while it waits for your approval, answer, or secret, or
Expand Down
Loading