@devries-cameron20 / t3code Mirror · read-only / commits / 931cd3afab
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, 16:00 UTC

fix(server): a Claude Monitor line no longer wakes a delegated child's parent (#36339)

Julius Marminge committed Nov 13, 2026 at 13:24 UTC 931cd3afab30d8f381ce13b87e4a97d01e6737c8
4 files changed +286 -13
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+195
@@ -11498,6 +11498,201 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11498 ),
11499 );
11500
11501 + // Claude 2.1.323 wakes a session per Monitor event with only init, assistant and a
11502 + // task-notification result; just the Monitor's end sends a task_notification frame.
11503 + it.effect.each([
11504 + { monitorWake: "ends with its own result", laterWake: "ends with its own result" },
11505 + { monitorWake: "ends with its own result", laterWake: "is absorbed by a user turn" },
11506 + { monitorWake: "is absorbed by a user turn", laterWake: "is absorbed by a user turn" },
11507 + ] as const)(
11508 + "tags a Claude Monitor event wake as a monitor update (it $monitorWake, later wake $laterWake)",
11509 + ({ monitorWake, laterWake }) =>
11510 + Effect.gen(function* () {
11511 + const absorbed = laterWake === "is absorbed by a user turn";
11512 + const monitorWakeAbsorbed = monitorWake === "is absorbed by a user turn";
11513 + const harness = yield* makeWakeHarness;
11514 + const now = yield* DateTime.now;
11515 + const taskId = "bi5kfx7xp";
11516 + const toolUseId = "toolu_monitor_events";
11517 +
11518 + yield* harness.runtime.startTurn(
11519 + makeClaudeTestTurnInput({
11520 + threadId: harness.threadId,
11521 + providerThread: harness.providerThread,
11522 + now,
11523 + attemptId: RunAttemptId.make("attempt-claude-monitor-event"),
11524 + text: "Watch the mutation run and report each survivor.",
11525 + attachments: [],
11526 + }),
11527 + );
11528 + for (const frame of [
11529 + claudeSdkFrame({
11530 + type: "assistant",
11531 + message: {
11532 + model: "claude-sonnet-4-6",
11533 + id: "msg_monitor_events",
11534 + type: "message",
11535 + role: "assistant",
11536 + content: [
11537 + {
11538 + type: "tool_use",
11539 + id: toolUseId,
11540 + name: "Monitor",
11541 + input: { description: "line monitor", command: "./mutate.sh" },
11542 + },
11543 + ],
11544 + stop_reason: null,
11545 + stop_sequence: null,
11546 + usage: { input_tokens: 1, output_tokens: 1 },
11547 + },
11548 + parent_tool_use_id: null,
11549 + uuid: "00000000-0000-4000-8000-000000000901",
11550 + session_id: WAKE_NATIVE_SESSION,
11551 + }),
11552 + claudeSdkFrame({
11553 + type: "system",
11554 + subtype: "task_started",
11555 + task_id: taskId,
11556 + tool_use_id: toolUseId,
11557 + description: "line monitor",
11558 + is_backgrounded: true,
11559 + task_type: "local_bash",
11560 + uuid: "00000000-0000-4000-8000-000000000902",
11561 + session_id: WAKE_NATIVE_SESSION,
11562 + }),
11563 + claudeSdkFrame({
11564 + type: "user",
11565 + message: {
11566 + role: "user",
11567 + content: [
11568 + {
11569 + type: "tool_result",
11570 + tool_use_id: toolUseId,
11571 + content: `Monitor started (task ${taskId}). You will be notified on each event.`,
11572 + },
11573 + ],
11574 + },
11575 + parent_tool_use_id: null,
11576 + uuid: "00000000-0000-4000-8000-000000000903",
11577 + session_id: WAKE_NATIVE_SESSION,
11578 + tool_use_result: { taskId, persistent: false },
11579 + }),
11580 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000904", result: "STARTED" }),
11581 + ]) {
11582 + yield* Queue.offer(harness.sdkMessages, frame);
11583 + }
11584 + yield* harness.awaitTerminal(1);
11585 +
11586 + yield* harness.offerAndWait(wakeTurnInit);
11587 + yield* harness.offerAndWait(
11588 + makeAssistantTextFrame({
11589 + uuid: "00000000-0000-4000-8000-000000000905",
11590 + text: "Covered. Waiting for the rest.",
11591 + }),
11592 + );
11593 + yield* harness.awaitContinuation(1);
11594 +
11595 + const notification = harness.continuationRequests[0]?.notification;
11596 + assert.deepEqual(
11597 + { source: notification?.source, outcome: notification?.outcome },
11598 + { source: { kind: "monitor" }, outcome: "updated" },
11599 + );
11600 +
11601 + let settled = 1;
11602 + // Claude folds a prompt into the wake turn it already opened, so one result ends both.
11603 + const absorbWithUserTurn = Effect.fnUntraced(function* (result: SDKMessage) {
11604 + settled += 1;
11605 + yield* harness.runtime.startTurn(
11606 + makeClaudeTestTurnInput({
11607 + threadId: harness.threadId,
11608 + providerThread: harness.providerThread,
11609 + now,
11610 + attemptId: RunAttemptId.make(`attempt-claude-monitor-event-user-${settled}`),
11611 + text: "Any survivors yet?",
11612 + attachments: [],
11613 + providerTurnOrdinal: settled,
11614 + }),
11615 + );
11616 + yield* harness.until(() => harness.offeredMessages.length === settled);
11617 + yield* Queue.offer(harness.sdkMessages, result);
11618 + yield* harness.awaitTerminal(settled);
11619 + });
11620 + const monitorWakeResult = makeResultFrame({
11621 + uuid: "00000000-0000-4000-8000-000000000906",
11622 + result: "Covered. Waiting for the rest.",
11623 + ...(monitorWakeAbsorbed ? {} : { origin: { kind: "task-notification" } as const }),
11624 + });
11625 + if (monitorWakeAbsorbed) yield* absorbWithUserTurn(monitorWakeResult);
11626 + else yield* harness.offerAndWait(monitorWakeResult);
11627 +
11628 + // A wake buffered behind the queued Monitor continuation must not run under its tag.
11629 + for (const frame of [
11630 + claudeSdkFrame({
11631 + type: "system",
11632 + subtype: "init",
11633 + uuid: "00000000-0000-4000-8000-000000000907",
11634 + session_id: WAKE_NATIVE_SESSION,
11635 + }),
11636 + makeAssistantTextFrame({
11637 + uuid: "00000000-0000-4000-8000-000000000908",
11638 + text: "Scheduled answer.",
11639 + }),
11640 + ]) {
11641 + yield* harness.offerAndWait(frame);
11642 + }
11643 + const laterResult = makeResultFrame({
11644 + uuid: "00000000-0000-4000-8000-000000000909",
11645 + result: absorbed ? "No survivors yet." : "Scheduled answer.",
11646 + });
11647 + if (absorbed) yield* absorbWithUserTurn(laterResult);
11648 + else yield* harness.offerAndWait(laterResult);
11649 + const assistantTexts = () =>
11650 + harness.events.flatMap((event) =>
11651 + event.type === "message.updated" && event.message.role === "assistant"
11652 + ? [event.message.text]
11653 + : [],
11654 + );
11655 + const startContinuation = (attempt: string, providerTurnOrdinal: number) =>
11656 + harness.runtime.startTurn(
11657 + makeClaudeTestTurnInput({
11658 + threadId: harness.threadId,
11659 + providerThread: harness.providerThread,
11660 + now,
11661 + attemptId: RunAttemptId.make(attempt),
11662 + text: "Background task completed.",
11663 + attachments: [],
11664 + providerTurnOrdinal,
11665 + messageCreatedBy: "agent",
11666 + messageCreationSource: "provider",
11667 + }),
11668 + );
11669 + yield* startContinuation("attempt-claude-monitor-event-2", settled + 1);
11670 + yield* harness.awaitTerminal(settled + 1);
11671 + assert.notInclude(assistantTexts(), "Scheduled answer.");
11672 + yield* harness.awaitContinuation(2);
11673 + // With no result of its own in the buffer, the later wake reads as another Monitor event.
11674 + assert.equal(
11675 + harness.continuationRequests[1]?.notification?.source.kind,
11676 + absorbed ? "monitor" : undefined,
11677 + );
11678 +
11679 + yield* startContinuation("attempt-claude-monitor-event-3", settled + 2);
11680 + yield* harness.awaitTerminal(settled + 2);
11681 + assert.equal(harness.terminalEvents()[settled + 1]?.status, "completed");
11682 + assert.include(assistantTexts(), "Scheduled answer.");
11683 + assert.lengthOf(harness.continuationRequests, 2);
11684 + }).pipe(
11685 + Effect.provide(
11686 + Layer.mergeAll(
11687 + IdAllocator.layer,
11688 + McpProviderSessions.layer,
11689 + NodeServices.layer,
11690 + NodeCrypto.layer,
11691 + ),
11692 + ),
11693 + ),
11694 + );
11695 +
11696 const scheduleWakeupFrames = (input: {
11697 readonly toolUseId: string;
11698 readonly uuids: readonly [string, string];
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+74 -7
@@ -5796,6 +5796,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5796 const scheduledWakeupsByNativeThread = new Map<string, number>();
5797 // Native threads whose current turn Claude started by itself inside the early-fire margin.
5798 const possibleEarlyWakeNativeThreads = new Set<string>();
5799 + // Turn starts a due or nearly due ScheduleWakeup may have caused.
5800 + const possibleScheduledWakeStarts = new WeakSet<SDKMessage>();
5801 + // A Monitor event wakes Claude with a bare turn and no task_notification frame, so the
5802 + // only evidence is a turn start while a Monitor runs that no ScheduleWakeup explains.
5803 + const monitorEventWakeStarts = new WeakSet<SDKMessage>();
5804 const trackClaudeScheduledWakeup = Effect.fnUntraced(function* (
5805 nativeThreadId: string,
5806 message: SDKMessage,
@@ -5804,6 +5809,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5809 const scheduledFor = scheduledWakeupsByNativeThread.get(nativeThreadId);
5810 if (scheduledFor === undefined) return;
5811 const now = DateTime.toEpochMillis(yield* DateTime.now);
5812 + if (now >= scheduledFor - CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS) {
5813 + possibleScheduledWakeStarts.add(message);
5814 + }
5815 if (now >= scheduledFor) {
5816 scheduledWakeupsByNativeThread.delete(nativeThreadId);
5817 } else if (
@@ -5885,6 +5893,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5893 for (const [taskId] of endedIds) tasks.delete(taskId);
5894 return [tasks, { ...current, tasks }] as const;
5895 });
5896 + const hasRunningClaudeMonitor = (nativeThreadId: string) =>
5897 + Ref.get(claudeMonitors).pipe(
5898 + Effect.map((current) =>
5899 + [...current.tasks.values()].some((task) => task.nativeThreadId === nativeThreadId),
5900 + ),
5901 + );
5902 + // The buffer's first wake is a Monitor event: its result, once known, is a task notification's.
5903 + const isClaudeMonitorEventWake = (messages: ReadonlyArray<SDKMessage>) => {
5904 + const startIndex = messages.findIndex(isClaudeTurnStartMessage);
5905 + const start = messages[startIndex];
5906 + if (start === undefined || !monitorEventWakeStarts.has(start)) return false;
5907 + const result = messages
5908 + .slice(startIndex + 1)
5909 + .find(
5910 + (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
5911 + );
5912 + return result === undefined || isClaudeTaskNotificationOriginResult(result);
5913 + };
5914 const claudeTaskOutcome = (status: "completed" | "failed" | "stopped") =>
5915 status === "completed" ? "completed" : status === "stopped" ? "cancelled" : "failed";
5916 // Reads the roster, so call it before the notification clears the task from it.
@@ -5926,6 +5952,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5952 readonly token: symbol;
5953 readonly end: SDKMessage | undefined;
5954 readonly retired: "unopened" | "opened" | null;
5955 + // Offered as Monitor progress, which starts no delegated follow-up.
5956 + readonly monitorEvent: boolean;
5957 }
5958 >(),
5959 );
@@ -9400,6 +9428,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9428 if (isClaudeRootTurnFrame(message)) {
9429 yield* forgetAbsorbedWake(wakeInput.nativeThreadId);
9430 }
9431 + if (
9432 + isWakeTurnStart &&
9433 + !possibleScheduledWakeStarts.has(message) &&
9434 + (yield* hasRunningClaudeMonitor(wakeInput.nativeThreadId))
9435 + ) {
9436 + monitorEventWakeStarts.add(message);
9437 + }
9438 yield* Ref.update(wakeBuffers, (current) => {
9439 const existing = current.get(wakeInput.nativeThreadId);
9440 const updated = new Map(current);
@@ -9456,6 +9491,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9491 }
9492 const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId);
9493 const token = Symbol(nativeThreadId);
9494 + // A recorded report names finished work, which outranks Monitor progress.
9495 + const monitorEvent =
9496 + ((yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId)?.size ?? 0) ===
9497 + 0 && isClaudeMonitorEventWake(buffered?.messages ?? []);
9498 const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => {
9499 if (current.has(nativeThreadId)) {
9500 return [false, current] as const;
@@ -9467,6 +9506,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9506 (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
9507 ),
9508 retired: null,
9509 + monitorEvent,
9510 });
9511 return [true, updated] as const;
9512 });
@@ -9475,7 +9515,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9515 }
9516 const reports = yield* takeWakeReports(nativeThreadId);
9517 const notification = backgroundWorkNotification(
9478 - [...(reports?.values() ?? [])].map((entry) => entry.report),
9518 + monitorEvent
9519 + ? [{ kind: "monitor", outcome: "updated" }]
9520 + : [...(reports?.values() ?? [])].map((entry) => entry.report),
9521 );
9522 yield* Effect.logInfo("orchestration-v2.claude-wake-turn-detected", {
9523 providerSessionId: input.providerSessionId,
@@ -9631,9 +9673,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9673 // After a retired wake releases its latch, a wake buffered behind it has had no offer of its own.
9674 const offerBufferedWake = Effect.fnUntraced(function* (nativeThreadId: string) {
9675 const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
9676 + if (yield* holdsBufferedWake(nativeThreadId, messages))
9677 + yield* offerWakeContinuation(nativeThreadId);
9678 + });
9679 +
9680 + const holdsBufferedWake = Effect.fnUntraced(function* (
9681 + nativeThreadId: string,
9682 + messages: ReadonlyArray<SDKMessage>,
9683 + ) {
9684 const reports = (yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId);
9685 // A lifecycle result ends no turn, and closes the root frames before it.
9636 - const hasWake =
9686 + return (
9687 messages
9688 .slice(messages.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1)
9689 .some(isClaudeRootTurnFrame) ||
@@ -9643,8 +9693,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9693 (entry.type === "system" &&
9694 entry.subtype === "task_notification" &&
9695 reports?.get(entry.task_id)?.report.kind === "subagent"),
9646 - );
9647 - if (hasWake) yield* offerWakeContinuation(nativeThreadId);
9696 + )
9697 + );
9698 });
9699
9700 // Untraced like the roster message handling: it runs for every streamed roster change.
@@ -12636,14 +12686,29 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12686 yield* sdkMessageLock.withPermits(1)(
12687 Effect.gen(function* () {
12688 yield* attachTurn;
12639 - const drained = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
12689 + const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
12690 + const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId);
12691 + // This run carries the Monitor tag, which starts no delegated follow-up, so a wake
12692 + // buffered behind the Monitor event is left for a continuation of its own.
12693 + const ownEndIndex =
12694 + latch?.monitorEvent === true && latch.end !== undefined
12695 + ? buffered.indexOf(latch.end)
12696 + : -1;
12697 + const leavesLaterWake =
12698 + ownEndIndex !== -1 &&
12699 + (yield* holdsBufferedWake(nativeThreadId, buffered.slice(ownEndIndex + 1)));
12700 + const drained = leavesLaterWake ? buffered.slice(0, ownEndIndex + 1) : buffered;
12701 yield* Ref.update(requestedContinuations, (current) => {
12702 const updated = new Map(current);
12703 updated.delete(nativeThreadId);
12704 return updated;
12705 });
12645 - const wakeAbsorbed = (yield* Ref.get(absorbedWakes)).has(nativeThreadId);
12646 - yield* forgetAbsorbedWake(nativeThreadId);
12706 + // A root frame clears the absorbed marker, so behind a split it is the later wake's
12707 + // and stays; the split wake was absorbed when its end is not a result.
12708 + const wakeAbsorbed = leavesLaterWake
12709 + ? latch?.end?.type !== "result"
12710 + : (yield* Ref.get(absorbedWakes)).has(nativeThreadId);
12711 + if (!leavesLaterWake) yield* forgetAbsorbedWake(nativeThreadId);
12712 if (drained.length === 0) {
12713 const completedAt = yield* DateTime.now;
12714 yield* finalizeActiveTurn({ context, status: "completed", completedAt });
@@ -12704,11 +12769,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12769 }
12770 if (lastResult !== undefined && !emptyTurnBeforeNextTurn) {
12771 yield* handleSdkMessage({ query: querySession.query, message: lastResult });
12772 + if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
12773 return;
12774 }
12775 if (wakeAbsorbed || (hasOpaqueTaskNotification && !context.nativeWakeStarted)) {
12776 const completedAt = yield* DateTime.now;
12777 yield* finalizeActiveTurn({ context, status: "completed", completedAt });
12778 + if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
12779 } else if (!context.nativeWakeStarted) {
12780 yield* Effect.sleep(CLAUDE_WAKE_TURN_START_DEADLINE).pipe(
12781 Effect.andThen(
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+13 -5
@@ -2635,11 +2635,19 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
2635 threadId: child.childThreadId,
2636 messageId: wakeMessageId,
2637 text: "Background activity updated",
2638 - notification: {
2639 - source: { kind: "command" },
2640 - outcome: "completed",
2641 - summary: 'Command "sleep 60" finished',
2642 - },
2638 + // A monitor that ends is finished work too; only its per-line updates are progress.
2639 + notification:
2640 + delivery === "live"
2641 + ? {
2642 + source: { kind: "monitor" },
2643 + outcome: "completed",
2644 + summary: 'Monitor "sleep 60" finished',
2645 + }
2646 + : {
2647 + source: { kind: "command" },
2648 + outcome: "completed",
2649 + summary: 'Command "sleep 60" finished',
2650 + },
2651 attachments: [],
2652 dispatchMode: { type: "queue_after_active" },
2653 });
apps/server/src/orchestration-v2/Orchestrator.ts
+4 -1
@@ -785,7 +785,10 @@ function mayStartSubagentFollowup(
785 ): boolean {
786 if (command.scheduledTaskId !== undefined || command.restartContinuationOfRunId !== undefined)
787 return false;
788 - if (command.notification !== undefined) return command.notification.source.kind !== "monitor";
788 + if (command.notification !== undefined)
789 + return (
790 + command.notification.source.kind !== "monitor" || command.notification.outcome !== "updated"
791 + );
792 return (
793 command.createdBy === "user" ||
794 command.creationSource === "mcp" ||