@devries-cameron20 / t3code Mirror · read-only / commits / 458a792087
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 22:15 UTC

fix(server): a Claude thread waiting on a ScheduleWakeup stays in Working (#23648)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 11:59 UTC 458a79208752696b8ccbb7031a2e8e5d10ffbcd1
2 files changed +568 -2
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+469
@@ -76,6 +76,7 @@ import * as Stream from "effect/Stream";
76 import * as TestClock from "effect/testing/TestClock";
77 import { Tool } from "effect/ai";
78 import { formatClaudeResumeCompactionQuestion } from "@t3tools/shared/claudeCompaction";
79 +import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
80 import * as HostProcess from "@t3tools/shared/HostProcess";
81 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
82 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
@@ -10840,6 +10841,474 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10841 ),
10842 );
10843
10844 + const scheduleWakeupFrames = (input: {
10845 + readonly toolUseId: string;
10846 + readonly uuids: readonly [string, string];
10847 + readonly toolInput: Record<string, unknown>;
10848 + readonly scheduledFor: number;
10849 + }) => [
10850 + claudeSdkFrame({
10851 + type: "assistant",
10852 + message: {
10853 + model: "claude-sonnet-4-6",
10854 + id: `msg_${input.toolUseId}`,
10855 + type: "message",
10856 + role: "assistant",
10857 + content: [
10858 + { type: "tool_use", id: input.toolUseId, name: "ScheduleWakeup", input: input.toolInput },
10859 + ],
10860 + stop_reason: null,
10861 + stop_sequence: null,
10862 + usage: { input_tokens: 1, output_tokens: 1 },
10863 + },
10864 + parent_tool_use_id: null,
10865 + uuid: input.uuids[0],
10866 + session_id: WAKE_NATIVE_SESSION,
10867 + }),
10868 + claudeSdkFrame({
10869 + type: "user",
10870 + message: {
10871 + role: "user",
10872 + content: [{ type: "tool_result", tool_use_id: input.toolUseId, content: "Scheduled." }],
10873 + },
10874 + parent_tool_use_id: null,
10875 + uuid: input.uuids[1],
10876 + session_id: WAKE_NATIVE_SESSION,
10877 + tool_use_result: {
10878 + scheduledFor: input.scheduledFor,
10879 + clampedDelaySeconds: 60,
10880 + wasClamped: false,
10881 + },
10882 + }),
10883 + ];
10884 +
10885 + const startScheduleWakeupTurn = Effect.fnUntraced(function* (
10886 + harness: Effect.Success<typeof makeWakeHarness>,
10887 + result = makeResultFrame({
10888 + uuid: "00000000-0000-4000-8000-000000002103",
10889 + result: "Scheduled.",
10890 + }),
10891 + ) {
10892 + const now = yield* DateTime.now;
10893 + yield* harness.runtime.startTurn(
10894 + makeClaudeTestTurnInput({
10895 + threadId: harness.threadId,
10896 + providerThread: harness.providerThread,
10897 + now,
10898 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-1"),
10899 + text: "Wake up in a minute.",
10900 + attachments: [],
10901 + }),
10902 + );
10903 + for (const frame of scheduleWakeupFrames({
10904 + toolUseId: "toolu_schedule_wakeup_1",
10905 + uuids: ["00000000-0000-4000-8000-000000002101", "00000000-0000-4000-8000-000000002102"],
10906 + toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "wake", noop: false },
10907 + scheduledFor: DateTime.toEpochMillis(now) + 60_000,
10908 + })) {
10909 + yield* Queue.offer(harness.sdkMessages, frame);
10910 + }
10911 + yield* Queue.offer(harness.sdkMessages, result);
10912 + yield* harness.awaitTerminal(1);
10913 + });
10914 +
10915 + const publishedRoster = (harness: Effect.Success<typeof makeWakeHarness>) =>
10916 + providerThreadRosterEvents(harness.events).at(-1)?.providerThread.pendingBackgroundTasks ?? [];
10917 +
10918 + it.effect.each([
10919 + { rescheduled: false, firedAfter: "60 seconds" },
10920 + { rescheduled: true, firedAfter: "60 seconds" },
10921 + // Claude fires one-shot wakeups early, so the wake init can precede scheduledFor.
10922 + { rescheduled: false, firedAfter: "30 seconds" },
10923 + ] as const)(
10924 + "a fired ScheduleWakeup holds completion only while its wake turn reschedules (rescheduled=$rescheduled, fired after $firedAfter)",
10925 + ({ rescheduled, firedAfter }) =>
10926 + Effect.scoped(
10927 + Effect.gen(function* () {
10928 + const harness = yield* makeWakeHarness;
10929 + yield* startScheduleWakeupTurn(harness);
10930 + assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness)));
10931 + assert.isTrue(
10932 + yield* harness.hasPendingBackgroundWork,
10933 + "a wakeup past the idle timeout must keep the session from being released",
10934 + );
10935 +
10936 + yield* TestClock.adjust(firedAfter);
10937 + yield* harness.offerAndWait(wakeTurnInit);
10938 + yield* harness.awaitContinuation(1);
10939 + const now = yield* DateTime.now;
10940 + yield* harness.runtime.startTurn(
10941 + makeClaudeTestTurnInput({
10942 + threadId: harness.threadId,
10943 + providerThread: harness.providerThread,
10944 + now,
10945 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-2"),
10946 + text: "say WOKE",
10947 + attachments: [],
10948 + providerTurnOrdinal: 2,
10949 + messageCreatedBy: "agent",
10950 + messageCreationSource: "provider",
10951 + }),
10952 + );
10953 + if (rescheduled) {
10954 + for (const frame of scheduleWakeupFrames({
10955 + toolUseId: "toolu_schedule_wakeup_2",
10956 + uuids: [
10957 + "00000000-0000-4000-8000-000000002201",
10958 + "00000000-0000-4000-8000-000000002202",
10959 + ],
10960 + toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "loop", noop: false },
10961 + scheduledFor: DateTime.toEpochMillis(now) + 60_000,
10962 + })) {
10963 + yield* harness.offerAndWait(frame);
10964 + }
10965 + }
10966 + yield* harness.offerAndWait(
10967 + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000002203", text: "WOKE" }),
10968 + );
10969 + yield* harness.offerAndWait(
10970 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002204", result: "WOKE" }),
10971 + );
10972 + yield* harness.awaitTerminal(2);
10973 + assert.equal(harness.terminalEvents()[1]?.status, "completed");
10974 + assert.equal(backgroundWorkHoldsCompletion(publishedRoster(harness)), rescheduled);
10975 + assert.equal(yield* harness.hasPendingBackgroundWork, rescheduled);
10976 + }).pipe(
10977 + Effect.provide(
10978 + Layer.mergeAll(
10979 + IdAllocator.layer,
10980 + McpProviderSessions.layer,
10981 + NodeServices.layer,
10982 + NodeCrypto.layer,
10983 + ),
10984 + ),
10985 + ),
10986 + ),
10987 + );
10988 +
10989 + it.effect("a user turn before the wakeup fires keeps the pending wakeup's hold", () =>
10990 + Effect.scoped(
10991 + Effect.gen(function* () {
10992 + const harness = yield* makeWakeHarness;
10993 + yield* startScheduleWakeupTurn(harness);
10994 + yield* TestClock.adjust("10 seconds");
10995 + yield* harness.runtime.startTurn(
10996 + makeClaudeTestTurnInput({
10997 + threadId: harness.threadId,
10998 + providerThread: harness.providerThread,
10999 + now: yield* DateTime.now,
11000 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-user"),
11001 + text: "What time is it?",
11002 + attachments: [],
11003 + providerTurnOrdinal: 2,
11004 + }),
11005 + );
11006 + yield* harness.offerAndWait(wakeTurnInit);
11007 + yield* harness.offerAndWait(
11008 + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000002401", text: "Noon." }),
11009 + );
11010 + yield* harness.offerAndWait(
11011 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002402", result: "Noon." }),
11012 + );
11013 + yield* harness.awaitTerminal(2);
11014 + assert.equal(harness.terminalEvents()[1]?.status, "completed");
11015 + assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness)));
11016 + assert.isTrue(yield* harness.hasPendingBackgroundWork);
11017 + }).pipe(
11018 + Effect.provide(
11019 + Layer.mergeAll(
11020 + IdAllocator.layer,
11021 + McpProviderSessions.layer,
11022 + NodeServices.layer,
11023 + NodeCrypto.layer,
11024 + ),
11025 + ),
11026 + ),
11027 + ),
11028 + );
11029 +
11030 + it.effect("a task notification waking Claude just before the wakeup keeps its hold", () =>
11031 + Effect.scoped(
11032 + Effect.gen(function* () {
11033 + const harness = yield* makeWakeHarness;
11034 + const now = yield* DateTime.now;
11035 + yield* harness.runtime.startTurn(
11036 + makeClaudeTestTurnInput({
11037 + threadId: harness.threadId,
11038 + providerThread: harness.providerThread,
11039 + now,
11040 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-task"),
11041 + text: "Run the build in the background and check back in two minutes.",
11042 + attachments: [],
11043 + }),
11044 + );
11045 + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
11046 + for (const frame of scheduleWakeupFrames({
11047 + toolUseId: "toolu_schedule_wakeup_fallback",
11048 + uuids: ["00000000-0000-4000-8000-000000002501", "00000000-0000-4000-8000-000000002502"],
11049 + toolInput: { delaySeconds: 120, prompt: "check the build", reason: "fallback" },
11050 + scheduledFor: DateTime.toEpochMillis(now) + 120_000,
11051 + })) {
11052 + yield* Queue.offer(harness.sdkMessages, frame);
11053 + }
11054 + yield* Queue.offer(harness.sdkMessages, turnOneResult);
11055 + yield* harness.awaitTerminal(1);
11056 +
11057 + yield* TestClock.adjust("60 seconds");
11058 + // Claude runs an empty turn for the notification and opens the real one right after,
11059 + // both before the wake run attaches.
11060 + yield* harness.offerAndWait(wakeNotification);
11061 + yield* Queue.offer(harness.sdkMessages, wakeTurnInit);
11062 + yield* Queue.offer(
11063 + harness.sdkMessages,
11064 + makeResultFrame({
11065 + uuid: "00000000-0000-4000-8000-000000002503",
11066 + result: "",
11067 + numTurns: 0,
11068 + origin: { kind: "task-notification" },
11069 + terminalReason: null,
11070 + }),
11071 + );
11072 + yield* harness.offerAndWait(
11073 + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000002504" }),
11074 + );
11075 + yield* harness.awaitContinuation(1);
11076 + yield* harness.runtime.startTurn(
11077 + makeClaudeTestTurnInput({
11078 + threadId: harness.threadId,
11079 + providerThread: harness.providerThread,
11080 + now: yield* DateTime.now,
11081 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-task-2"),
11082 + text: "Background task completed.",
11083 + attachments: [],
11084 + providerTurnOrdinal: 2,
11085 + messageCreatedBy: "agent",
11086 + messageCreationSource: "provider",
11087 + }),
11088 + );
11089 + yield* harness.offerAndWait(wakeAssistant);
11090 + yield* harness.offerAndWait(wakeResult);
11091 + yield* harness.awaitTerminal(2);
11092 + assert.equal(harness.terminalEvents()[1]?.status, "completed");
11093 + assert.isTrue(
11094 + backgroundWorkHoldsCompletion(publishedRoster(harness)),
11095 + "the wakeup is still pending after the task notification's wake turn",
11096 + );
11097 + assert.isTrue(yield* harness.hasPendingBackgroundWork);
11098 + }).pipe(
11099 + Effect.provide(
11100 + Layer.mergeAll(
11101 + IdAllocator.layer,
11102 + McpProviderSessions.layer,
11103 + NodeServices.layer,
11104 + NodeCrypto.layer,
11105 + ),
11106 + ),
11107 + ),
11108 + ),
11109 + );
11110 +
11111 + it.effect.each([{ emptyResult: true }, { emptyResult: false }])(
11112 + "an early wakeup after an idle task notification releases its hold (empty result: $emptyResult)",
11113 + ({ emptyResult }) =>
11114 + Effect.scoped(
11115 + Effect.gen(function* () {
11116 + const harness = yield* makeWakeHarness;
11117 + const now = yield* DateTime.now;
11118 + yield* harness.runtime.startTurn(
11119 + makeClaudeTestTurnInput({
11120 + threadId: harness.threadId,
11121 + providerThread: harness.providerThread,
11122 + now,
11123 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-notified"),
11124 + text: "Run the build in the background and check back in two minutes.",
11125 + attachments: [],
11126 + }),
11127 + );
11128 + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
11129 + for (const frame of scheduleWakeupFrames({
11130 + toolUseId: "toolu_schedule_wakeup_notified",
11131 + uuids: ["00000000-0000-4000-8000-000000002601", "00000000-0000-4000-8000-000000002602"],
11132 + toolInput: { delaySeconds: 120, prompt: "check the build", reason: "fallback" },
11133 + scheduledFor: DateTime.toEpochMillis(now) + 120_000,
11134 + })) {
11135 + yield* Queue.offer(harness.sdkMessages, frame);
11136 + }
11137 + yield* Queue.offer(harness.sdkMessages, turnOneResult);
11138 + yield* harness.awaitTerminal(1);
11139 +
11140 + yield* TestClock.adjust("10 seconds");
11141 + yield* harness.offerAndWait(wakeNotification);
11142 + if (emptyResult) {
11143 + yield* harness.offerAndWait(
11144 + makeResultFrame({
11145 + uuid: "00000000-0000-4000-8000-000000002603",
11146 + result: "",
11147 + numTurns: 0,
11148 + origin: { kind: "task-notification" },
11149 + terminalReason: null,
11150 + }),
11151 + );
11152 + }
11153 +
11154 + yield* TestClock.adjust("80 seconds");
11155 + yield* harness.offerAndWait(wakeTurnInit);
11156 + yield* harness.awaitContinuation(1);
11157 + yield* harness.runtime.startTurn(
11158 + makeClaudeTestTurnInput({
11159 + threadId: harness.threadId,
11160 + providerThread: harness.providerThread,
11161 + now: yield* DateTime.now,
11162 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-notified-2"),
11163 + text: "check the build",
11164 + attachments: [],
11165 + providerTurnOrdinal: 2,
11166 + messageCreatedBy: "agent",
11167 + messageCreationSource: "provider",
11168 + }),
11169 + );
11170 + yield* harness.offerAndWait(
11171 + makeAssistantTextFrame({
11172 + uuid: "00000000-0000-4000-8000-000000002604",
11173 + text: "Built.",
11174 + }),
11175 + );
11176 + yield* harness.offerAndWait(
11177 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002605", result: "Built." }),
11178 + );
11179 + yield* harness.awaitTerminal(2);
11180 + assert.equal(harness.terminalEvents()[1]?.status, "completed");
11181 + assert.isFalse(backgroundWorkHoldsCompletion(publishedRoster(harness)));
11182 + assert.isFalse(yield* harness.hasPendingBackgroundWork);
11183 + }).pipe(
11184 + Effect.provide(
11185 + Layer.mergeAll(
11186 + IdAllocator.layer,
11187 + McpProviderSessions.layer,
11188 + NodeServices.layer,
11189 + NodeCrypto.layer,
11190 + ),
11191 + ),
11192 + ),
11193 + ),
11194 + );
11195 +
11196 + it.effect("a failed turn on a live Claude process keeps the pending wakeup's hold", () =>
11197 + Effect.scoped(
11198 + Effect.gen(function* () {
11199 + const harness = yield* makeWakeHarness;
11200 + yield* startScheduleWakeupTurn(
11201 + harness,
11202 + makeResultFrame({
11203 + uuid: "00000000-0000-4000-8000-000000002103",
11204 + result: "API Error: 529 overloaded",
11205 + subtype: "error_during_execution",
11206 + isError: true,
11207 + errors: ["API Error: 529 overloaded"],
11208 + terminalReason: "model_error",
11209 + }),
11210 + );
11211 + assert.equal(harness.terminalEvents()[0]?.status, "failed");
11212 + assert.isTrue(backgroundWorkHoldsCompletion(publishedRoster(harness)));
11213 + assert.isTrue(yield* harness.hasPendingBackgroundWork);
11214 + }).pipe(
11215 + Effect.provide(
11216 + Layer.mergeAll(
11217 + IdAllocator.layer,
11218 + McpProviderSessions.layer,
11219 + NodeServices.layer,
11220 + NodeCrypto.layer,
11221 + ),
11222 + ),
11223 + ),
11224 + ),
11225 + );
11226 +
11227 + it.effect("ScheduleWakeup stop:true releases the pending wakeup's hold", () =>
11228 + Effect.scoped(
11229 + Effect.gen(function* () {
11230 + const harness = yield* makeWakeHarness;
11231 + const now = yield* DateTime.now;
11232 + yield* harness.runtime.startTurn(
11233 + makeClaudeTestTurnInput({
11234 + threadId: harness.threadId,
11235 + providerThread: harness.providerThread,
11236 + now,
11237 + attemptId: RunAttemptId.make("attempt-claude-schedule-wakeup-stop"),
11238 + text: "Schedule a wakeup, then cancel it.",
11239 + attachments: [],
11240 + }),
11241 + );
11242 + const frames = [
11243 + ...scheduleWakeupFrames({
11244 + toolUseId: "toolu_schedule_wakeup_set",
11245 + uuids: ["00000000-0000-4000-8000-000000002301", "00000000-0000-4000-8000-000000002302"],
11246 + toolInput: { delaySeconds: 60, prompt: "say WOKE", reason: "wake", noop: false },
11247 + scheduledFor: DateTime.toEpochMillis(now) + 60_000,
11248 + }),
11249 + ...scheduleWakeupFrames({
11250 + toolUseId: "toolu_schedule_wakeup_stop",
11251 + uuids: ["00000000-0000-4000-8000-000000002303", "00000000-0000-4000-8000-000000002304"],
11252 + toolInput: { stop: true },
11253 + scheduledFor: 0,
11254 + }),
11255 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002305", result: "Cancelled." }),
11256 + ];
11257 + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame);
11258 + yield* harness.awaitTerminal(1);
11259 + assert.isFalse(backgroundWorkHoldsCompletion(publishedRoster(harness)));
11260 + assert.isFalse(yield* harness.hasPendingBackgroundWork);
11261 + }).pipe(
11262 + Effect.provide(
11263 + Layer.mergeAll(
11264 + IdAllocator.layer,
11265 + McpProviderSessions.layer,
11266 + NodeServices.layer,
11267 + NodeCrypto.layer,
11268 + ),
11269 + ),
11270 + ),
11271 + ),
11272 + );
11273 +
11274 + it.effect("Stop on a thread waiting for a ScheduleWakeup closes Claude and drops the hold", () =>
11275 + Effect.scoped(
11276 + Effect.gen(function* () {
11277 + let closes = 0;
11278 + const harness = yield* makeWakeHarnessWithOptions({
11279 + close: (sdkMessages) =>
11280 + Effect.sync(() => {
11281 + closes++;
11282 + }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))),
11283 + });
11284 + yield* startScheduleWakeupTurn(harness);
11285 + const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread;
11286 + assert.isTrue(backgroundWorkHoldsCompletion(settledThread?.pendingBackgroundTasks ?? []));
11287 + // The wakeup alone must not refuse a model or mode change.
11288 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWorkForThread!(settledThread!));
11289 +
11290 + yield* harness.runtime.interruptTurn({
11291 + providerThread: settledThread ?? harness.providerThread,
11292 + providerTurnId: harness.terminalEvents()[0]!.providerTurnId,
11293 + requestRuntimeRestart: true,
11294 + });
11295 +
11296 + assert.equal(closes, 1, "the wakeup lives in the CLI process, so Stop must close it");
11297 + yield* harness.until(() => publishedRoster(harness).length === 0);
11298 + assert.isFalse(yield* harness.hasPendingBackgroundWork);
11299 + }).pipe(
11300 + Effect.provide(
11301 + Layer.mergeAll(
11302 + IdAllocator.layer,
11303 + McpProviderSessions.layer,
11304 + NodeServices.layer,
11305 + NodeCrypto.layer,
11306 + ),
11307 + ),
11308 + ),
11309 + ),
11310 + );
11311 +
11312 it.effect.skipIf(process.getuid === undefined)(
11313 "tails foreground Bash output under the physical cwd the query launched in",
11314 () =>
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+99 -2
@@ -3279,6 +3279,17 @@ function isClaudeRootTurnFrame(message: SDKMessage): boolean {
3279 );
3280 }
3281
3282 +// One stable id per native thread: a new ScheduleWakeup replaces the pending one.
3283 +const CLAUDE_SCHEDULED_WAKEUP_TASK: OrchestrationV2PendingBackgroundTask = {
3284 + taskId: "claude-scheduled-wakeup",
3285 + kind: "background_task",
3286 + description: "Scheduled wakeup",
3287 +};
3288 +
3289 +// Claude Code jitters one-shot wakeups early but never before the requested time, which is at
3290 +// most 60 s before the minute-rounded scheduledFor it reports; the rest is slack.
3291 +const CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS = 120_000;
3292 +
3293 function claudePendingBackgroundTasksFromRoster(
3294 roster: ReadonlyMap<string, OrchestrationV2PendingBackgroundTask>,
3295 awaitedTaskIds: ReadonlySet<string>,
@@ -5409,6 +5420,75 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5420 return { ...current, calls };
5421 });
5422 };
5423 + // ScheduleWakeup reports no background task: its tool result is the only sign that Claude
5424 + // will start a turn by itself, and Claude keeps one pending wakeup per session. It stays
5425 + // out of pendingBackgroundTasksByNativeThread because a wakeup must not refuse a model or
5426 + // mode change; replacing the process cancels it, and that clears this record too.
5427 + const scheduleWakeupCalls = new Set<string>();
5428 + const scheduledWakeupsByNativeThread = new Map<string, number>();
5429 + // Native threads whose current turn Claude started by itself inside the early-fire margin.
5430 + const possibleEarlyWakeNativeThreads = new Set<string>();
5431 + const trackClaudeScheduledWakeup = Effect.fnUntraced(function* (
5432 + nativeThreadId: string,
5433 + message: SDKMessage,
5434 + ) {
5435 + if (isClaudeTurnStartMessage(message)) {
5436 + const scheduledFor = scheduledWakeupsByNativeThread.get(nativeThreadId);
5437 + if (scheduledFor === undefined) return;
5438 + const now = DateTime.toEpochMillis(yield* DateTime.now);
5439 + if (now >= scheduledFor) {
5440 + scheduledWakeupsByNativeThread.delete(nativeThreadId);
5441 + } else if (
5442 + (yield* Ref.get(activeTurn)) === null &&
5443 + now >= scheduledFor - CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS
5444 + ) {
5445 + possibleEarlyWakeNativeThreads.add(nativeThreadId);
5446 + }
5447 + return;
5448 + }
5449 + // A task notification also starts a turn by itself, so an early turn is the wake only
5450 + // when its result is not a task notification's.
5451 + if (message.type === "result") {
5452 + if (
5453 + possibleEarlyWakeNativeThreads.delete(nativeThreadId) &&
5454 + !isClaudeTaskNotificationOriginResult(message)
5455 + ) {
5456 + scheduledWakeupsByNativeThread.delete(nativeThreadId);
5457 + }
5458 + return;
5459 + }
5460 + for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) {
5461 + if (toolUse.name === "ScheduleWakeup") scheduleWakeupCalls.add(toolUse.id);
5462 + }
5463 + if (message.type !== "user") return;
5464 + const returned = claudeToolResultBlocksFromUserMessage(message).filter((toolResult) =>
5465 + scheduleWakeupCalls.delete(toolResult.tool_use_id),
5466 + );
5467 + if (returned.length === 0) return;
5468 + const result = message.tool_use_result;
5469 + const scheduledFor =
5470 + returned.length === 1 && typeof result === "object" && result !== null
5471 + ? Reflect.get(result, "scheduledFor")
5472 + : undefined;
5473 + // stop:true reports scheduledFor 0. A failed call also clears: losing the hold early
5474 + // is recoverable, a hold that outlives its wakeup is not.
5475 + possibleEarlyWakeNativeThreads.delete(nativeThreadId);
5476 + if (typeof scheduledFor === "number" && scheduledFor > 0) {
5477 + scheduledWakeupsByNativeThread.set(nativeThreadId, scheduledFor);
5478 + } else {
5479 + scheduledWakeupsByNativeThread.delete(nativeThreadId);
5480 + }
5481 + });
5482 + const publishedPendingBackgroundTasks = (
5483 + nativeThreadId: string | null,
5484 + roster: ReadonlyMap<string, OrchestrationV2PendingBackgroundTask>,
5485 + awaitedTaskIds: ReadonlySet<string>,
5486 + ): ReadonlyArray<OrchestrationV2PendingBackgroundTask> => {
5487 + const tasks = claudePendingBackgroundTasksFromRoster(roster, awaitedTaskIds);
5488 + return nativeThreadId !== null && scheduledWakeupsByNativeThread.has(nativeThreadId)
5489 + ? [...tasks, CLAUDE_SCHEDULED_WAKEUP_TASK]
5490 + : tasks;
5491 + };
5492 const isClaudeMonitorTask = (input: {
5493 readonly nativeThreadId: string;
5494 readonly taskId: string;
@@ -5768,7 +5848,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5848 ...input.providerThread,
5849 providerSessionId: session.id,
5850 ...(input.status === undefined ? {} : { status: input.status }),
5771 - pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster, awaitedTaskIds),
5851 + pendingBackgroundTasks: publishedPendingBackgroundTasks(
5852 + input.nativeThreadId,
5853 + roster,
5854 + awaitedTaskIds,
5855 + ),
5856 ...(goalsByNativeThread.has(input.nativeThreadId)
5857 ? { goal: goalsByNativeThread.get(input.nativeThreadId) ?? null }
5858 : {}),
@@ -5993,6 +6077,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6077 const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) =>
6078 bufferedTaskNotificationIds.has(taskId),
6079 );
6080 + scheduledWakeupsByNativeThread.delete(nativeThreadId);
6081 + possibleEarlyWakeNativeThreads.delete(nativeThreadId);
6082 yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId);
6083 yield* clearNativeThreadTaskIdSet(
6084 wakeEligibleBackgroundTasksByNativeThread,
@@ -8273,6 +8359,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8359 input.context.input.providerThread.nativeThreadRef?.nativeId ?? null;
8360 if (nativeThreadId !== null) {
8361 if (input.status !== "completed") {
8362 + // Stop cancels Claude's wakeup and an exited process loses it; a failed
8363 + // turn on a live process leaves it pending. Process exits null the query first.
8364 + if (input.status !== "failed" || (yield* Ref.get(queryContext)) === null) {
8365 + scheduledWakeupsByNativeThread.delete(nativeThreadId);
8366 + }
8367 yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId);
8368 yield* clearNativeThreadTaskIdSet(
8369 wakeEligibleBackgroundTasksByNativeThread,
@@ -8336,7 +8427,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8427 input.context.input.providerThread.firstRunOrdinal ??
8428 input.context.input.runOrdinal,
8429 lastRunOrdinal: input.context.input.runOrdinal,
8339 - pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(
8430 + pendingBackgroundTasks: publishedPendingBackgroundTasks(
8431 + nativeThreadId,
8432 roster,
8433 awaitedTaskIds,
8434 ),
@@ -8978,6 +9070,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9070 }
9071 // Track before routing: idle-wake Monitors report tasks before replaying their tool calls.
9072 yield* trackClaudeMonitorCalls(message);
9073 + yield* trackClaudeScheduledWakeup(liveQuery.nativeThreadId, message);
9074 // Update before routing because the idle wake gate reads this.
9075 if (
9076 message.type === "system" &&
@@ -12027,6 +12120,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12120 events: Stream.fromEffectRepeat(Queue.take(events)),
12121 backgroundTasksEndWithProcess: true,
12122 hasPendingBackgroundWork: Effect.gen(function* () {
12123 + // A wakeup can be up to an hour out, past the idle timeout, and dies with the process.
12124 + if (scheduledWakeupsByNativeThread.size > 0) {
12125 + return true;
12126 + }
12127 for (const roster of (yield* Ref.get(pendingBackgroundTasksByNativeThread)).values()) {
12128 if (roster.size > 0) {
12129 return true;