Skip to content

Commit 2090a54

Browse files
fix(server): a Claude Monitor line no longer wakes a delegated child's parent
Claude wakes a session for each Monitor line with a bare turn (init, assistant, task-notification result) and no task_notification frame, so the continuation carried no notification and fell back to background_task/updated, which starts a delegated follow-up and wakes the parent. The adapter now tags a wake turn that starts while a Monitor runs, with no recorded task report and no due ScheduleWakeup, as monitor/updated. A continuation carrying that tag replays only its own wake: a wake buffered behind it gets a continuation of its own, so its answer keeps its own tag. Fixes #36113 Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent cffa801 commit 2090a54

2 files changed

Lines changed: 127 additions & 6 deletions

File tree

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11587,6 +11587,61 @@ describe("ClaudeAdapterV2 background wake turns", () => {
1158711587
{ source: notification?.source, outcome: notification?.outcome },
1158811588
{ source: { kind: "monitor" }, outcome: "updated" },
1158911589
);
11590+
11591+
// A wake buffered behind the queued Monitor continuation must not run under its tag.
11592+
for (const frame of [
11593+
makeResultFrame({
11594+
uuid: "00000000-0000-4000-8000-000000000906",
11595+
result: "Covered. Waiting for the rest.",
11596+
origin: { kind: "task-notification" },
11597+
}),
11598+
claudeSdkFrame({
11599+
type: "system",
11600+
subtype: "init",
11601+
uuid: "00000000-0000-4000-8000-000000000907",
11602+
session_id: WAKE_NATIVE_SESSION,
11603+
}),
11604+
makeAssistantTextFrame({
11605+
uuid: "00000000-0000-4000-8000-000000000908",
11606+
text: "Scheduled answer.",
11607+
}),
11608+
makeResultFrame({
11609+
uuid: "00000000-0000-4000-8000-000000000909",
11610+
result: "Scheduled answer.",
11611+
}),
11612+
]) {
11613+
yield* harness.offerAndWait(frame);
11614+
}
11615+
const assistantTexts = () =>
11616+
harness.events.flatMap((event) =>
11617+
event.type === "message.updated" && event.message.role === "assistant"
11618+
? [event.message.text]
11619+
: [],
11620+
);
11621+
const startContinuation = (attempt: string, providerTurnOrdinal: number) =>
11622+
harness.runtime.startTurn(
11623+
makeClaudeTestTurnInput({
11624+
threadId: harness.threadId,
11625+
providerThread: harness.providerThread,
11626+
now,
11627+
attemptId: RunAttemptId.make(attempt),
11628+
text: "Background task completed.",
11629+
attachments: [],
11630+
providerTurnOrdinal,
11631+
messageCreatedBy: "agent",
11632+
messageCreationSource: "provider",
11633+
}),
11634+
);
11635+
yield* startContinuation("attempt-claude-monitor-event-2", 2);
11636+
yield* harness.awaitTerminal(2);
11637+
assert.notInclude(assistantTexts(), "Scheduled answer.");
11638+
yield* harness.awaitContinuation(2);
11639+
assert.isUndefined(harness.continuationRequests[1]?.notification);
11640+
11641+
yield* startContinuation("attempt-claude-monitor-event-3", 3);
11642+
yield* harness.awaitTerminal(3);
11643+
assert.include(assistantTexts(), "Scheduled answer.");
11644+
assert.lengthOf(harness.continuationRequests, 2);
1159011645
}).pipe(
1159111646
Effect.provide(
1159211647
Layer.mergeAll(

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

Lines changed: 72 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5775,6 +5775,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
57755775
const scheduledWakeupsByNativeThread = new Map<string, number>();
57765776
// Native threads whose current turn Claude started by itself inside the early-fire margin.
57775777
const possibleEarlyWakeNativeThreads = new Set<string>();
5778+
// Turn starts a due or nearly due ScheduleWakeup may have caused.
5779+
const possibleScheduledWakeStarts = new WeakSet<SDKMessage>();
5780+
// A Monitor event wakes Claude with a bare turn and no task_notification frame, so the
5781+
// only evidence is a turn start while a Monitor runs that no ScheduleWakeup explains.
5782+
const monitorEventWakeStarts = new WeakSet<SDKMessage>();
57785783
const trackClaudeScheduledWakeup = Effect.fnUntraced(function* (
57795784
nativeThreadId: string,
57805785
message: SDKMessage,
@@ -5783,6 +5788,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
57835788
const scheduledFor = scheduledWakeupsByNativeThread.get(nativeThreadId);
57845789
if (scheduledFor === undefined) return;
57855790
const now = DateTime.toEpochMillis(yield* DateTime.now);
5791+
if (now >= scheduledFor - CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS) {
5792+
possibleScheduledWakeStarts.add(message);
5793+
}
57865794
if (now >= scheduledFor) {
57875795
scheduledWakeupsByNativeThread.delete(nativeThreadId);
57885796
} else if (
@@ -5864,6 +5872,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
58645872
for (const [taskId] of endedIds) tasks.delete(taskId);
58655873
return [tasks, { ...current, tasks }] as const;
58665874
});
5875+
const hasRunningClaudeMonitor = (nativeThreadId: string) =>
5876+
Ref.get(claudeMonitors).pipe(
5877+
Effect.map((current) =>
5878+
[...current.tasks.values()].some((task) => task.nativeThreadId === nativeThreadId),
5879+
),
5880+
);
5881+
// The buffer's first wake is a Monitor event: its result, once known, is a task notification's.
5882+
const isClaudeMonitorEventWake = (messages: ReadonlyArray<SDKMessage>) => {
5883+
const startIndex = messages.findIndex(isClaudeTurnStartMessage);
5884+
const start = messages[startIndex];
5885+
if (start === undefined || !monitorEventWakeStarts.has(start)) return false;
5886+
const result = messages
5887+
.slice(startIndex + 1)
5888+
.find(
5889+
(entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
5890+
);
5891+
return result === undefined || isClaudeTaskNotificationOriginResult(result);
5892+
};
58675893
const claudeTaskOutcome = (status: "completed" | "failed" | "stopped") =>
58685894
status === "completed" ? "completed" : status === "stopped" ? "cancelled" : "failed";
58695895
// Reads the roster, so call it before the notification clears the task from it.
@@ -5905,6 +5931,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
59055931
readonly token: symbol;
59065932
readonly end: SDKMessage | undefined;
59075933
readonly retired: "unopened" | "opened" | null;
5934+
// Offered as Monitor progress, which starts no delegated follow-up.
5935+
readonly monitorEvent: boolean;
59085936
}
59095937
>(),
59105938
);
@@ -9379,6 +9407,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
93799407
if (isClaudeRootTurnFrame(message)) {
93809408
yield* forgetAbsorbedWake(wakeInput.nativeThreadId);
93819409
}
9410+
if (
9411+
isWakeTurnStart &&
9412+
!possibleScheduledWakeStarts.has(message) &&
9413+
(yield* hasRunningClaudeMonitor(wakeInput.nativeThreadId))
9414+
) {
9415+
monitorEventWakeStarts.add(message);
9416+
}
93829417
yield* Ref.update(wakeBuffers, (current) => {
93839418
const existing = current.get(wakeInput.nativeThreadId);
93849419
const updated = new Map(current);
@@ -9435,6 +9470,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
94359470
}
94369471
const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId);
94379472
const token = Symbol(nativeThreadId);
9473+
// A recorded report names finished work, which outranks Monitor progress.
9474+
const monitorEvent =
9475+
((yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId)?.size ?? 0) ===
9476+
0 && isClaudeMonitorEventWake(buffered?.messages ?? []);
94389477
const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => {
94399478
if (current.has(nativeThreadId)) {
94409479
return [false, current] as const;
@@ -9446,6 +9485,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
94469485
(entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
94479486
),
94489487
retired: null,
9488+
monitorEvent,
94499489
});
94509490
return [true, updated] as const;
94519491
});
@@ -9454,7 +9494,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
94549494
}
94559495
const reports = yield* takeWakeReports(nativeThreadId);
94569496
const notification = backgroundWorkNotification(
9457-
[...(reports?.values() ?? [])].map((entry) => entry.report),
9497+
monitorEvent
9498+
? [{ kind: "monitor", outcome: "updated" }]
9499+
: [...(reports?.values() ?? [])].map((entry) => entry.report),
94589500
);
94599501
yield* Effect.logInfo("orchestration-v2.claude-wake-turn-detected", {
94609502
providerSessionId: input.providerSessionId,
@@ -9610,9 +9652,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
96109652
// After a retired wake releases its latch, a wake buffered behind it has had no offer of its own.
96119653
const offerBufferedWake = Effect.fnUntraced(function* (nativeThreadId: string) {
96129654
const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
9655+
if (yield* holdsBufferedWake(nativeThreadId, messages))
9656+
yield* offerWakeContinuation(nativeThreadId);
9657+
});
9658+
9659+
const holdsBufferedWake = Effect.fnUntraced(function* (
9660+
nativeThreadId: string,
9661+
messages: ReadonlyArray<SDKMessage>,
9662+
) {
96139663
const reports = (yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId);
96149664
// A lifecycle result ends no turn, and closes the root frames before it.
9615-
const hasWake =
9665+
return (
96169666
messages
96179667
.slice(messages.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1)
96189668
.some(isClaudeRootTurnFrame) ||
@@ -9622,8 +9672,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
96229672
(entry.type === "system" &&
96239673
entry.subtype === "task_notification" &&
96249674
reports?.get(entry.task_id)?.report.kind === "subagent"),
9625-
);
9626-
if (hasWake) yield* offerWakeContinuation(nativeThreadId);
9675+
)
9676+
);
96279677
});
96289678

96299679
// Untraced like the roster message handling: it runs for every streamed roster change.
@@ -12615,13 +12665,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1261512665
yield* sdkMessageLock.withPermits(1)(
1261612666
Effect.gen(function* () {
1261712667
yield* attachTurn;
12618-
const drained = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
12668+
const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
12669+
const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId);
12670+
// This run carries the Monitor tag, which starts no delegated follow-up, so a wake
12671+
// buffered behind the Monitor event is left for a continuation of its own.
12672+
const ownEndIndex =
12673+
latch?.monitorEvent === true && latch.end !== undefined
12674+
? buffered.indexOf(latch.end)
12675+
: -1;
12676+
const leavesLaterWake =
12677+
ownEndIndex !== -1 &&
12678+
(yield* holdsBufferedWake(nativeThreadId, buffered.slice(ownEndIndex + 1)));
12679+
const drained = leavesLaterWake ? buffered.slice(0, ownEndIndex + 1) : buffered;
1261912680
yield* Ref.update(requestedContinuations, (current) => {
1262012681
const updated = new Map(current);
1262112682
updated.delete(nativeThreadId);
1262212683
return updated;
1262312684
});
12624-
const wakeAbsorbed = (yield* Ref.get(absorbedWakes)).has(nativeThreadId);
12685+
// A split wake that a user turn ended gets no result of its own.
12686+
const wakeAbsorbed =
12687+
(yield* Ref.get(absorbedWakes)).has(nativeThreadId) ||
12688+
(leavesLaterWake && latch?.end?.type !== "result");
1262512689
yield* forgetAbsorbedWake(nativeThreadId);
1262612690
if (drained.length === 0) {
1262712691
const completedAt = yield* DateTime.now;
@@ -12683,11 +12747,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1268312747
}
1268412748
if (lastResult !== undefined && !emptyTurnBeforeNextTurn) {
1268512749
yield* handleSdkMessage({ query: querySession.query, message: lastResult });
12750+
if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
1268612751
return;
1268712752
}
1268812753
if (wakeAbsorbed || (hasOpaqueTaskNotification && !context.nativeWakeStarted)) {
1268912754
const completedAt = yield* DateTime.now;
1269012755
yield* finalizeActiveTurn({ context, status: "completed", completedAt });
12756+
if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
1269112757
} else if (!context.nativeWakeStarted) {
1269212758
yield* Effect.sleep(CLAUDE_WAKE_TURN_START_DEADLINE).pipe(
1269312759
Effect.andThen(

0 commit comments

Comments
 (0)