Skip to content

Commit 9350032

Browse files
fix(server): a settled workflow member waits for its reply to reach the transcript
Claude Code flushes transcript writes every 100 ms, so a member's last reply can land after the progress frame that settles it. The settled read then found no text and showed the "Partial answer from workflow progress" excerpt; a later read added the real reply as a second answer, or, when the workflow had already ended, never ran. The excerpt now waits until a read started 500 ms after the member settled. When the coordinator has ended and nothing else will arrive, the adapter sleeps out the rest of that window and reads once more. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c05bed4 commit 9350032

2 files changed

Lines changed: 150 additions & 15 deletions

File tree

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

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14013,6 +14013,104 @@ describe("ClaudeAdapterV2 background wake turns", () => {
1401314013
),
1401414014
);
1401514015

14016+
it.effect("waits for a settled workflow member's reply to reach its transcript", () =>
14017+
Effect.scoped(
14018+
Effect.gen(function* () {
14019+
// Claude Code flushes transcript lines every 100 ms, so a member's reply
14020+
// can land after the frame that settles it (seen with CLI 2.1.301).
14021+
let appendLateReply: (() => void) | undefined;
14022+
const lateReplyWritten = yield* Deferred.make<void>();
14023+
yield* Effect.gen(function* () {
14024+
const harness = yield* makeWorkflowHarness;
14025+
const transcriptPath = (agentId: string) =>
14026+
NodePath.join(harness.transcriptDir, `agent-${agentId}.jsonl`);
14027+
const toolCall = (agentId: string) =>
14028+
memberAssistantLine(`line-${agentId}-bash`, `msg_${agentId}`, [
14029+
{ type: "tool_use", id: `toolu_${agentId}`, name: "Bash", input: { command: "ls" } },
14030+
]) + memberToolResultLine(`line-${agentId}-result`, `toolu_${agentId}`, "README.md");
14031+
const reply = (agentId: string) =>
14032+
memberAssistantLine(`line-${agentId}-reply`, `msg_${agentId}_reply`, [
14033+
{ type: "text", text: `${agentId} found README.md` },
14034+
]);
14035+
NodeFS.writeFileSync(transcriptPath("a1"), toolCall("a1"));
14036+
NodeFS.writeFileSync(transcriptPath("a2"), toolCall("a2"));
14037+
yield* harness.runtime.startTurn(
14038+
makeClaudeTestTurnInput({
14039+
threadId: harness.threadId,
14040+
providerThread: harness.providerThread,
14041+
now: yield* DateTime.now,
14042+
attemptId: RunAttemptId.make("attempt-claude-workflow-member-late-flush"),
14043+
text: "Run the alpha workflow.",
14044+
attachments: [],
14045+
}),
14046+
);
14047+
yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001395" });
14048+
const texts = (index: number) =>
14049+
threadMessages(
14050+
harness.events,
14051+
workflowMemberEvents(harness.events, index)[0]?.subagent.childThreadId,
14052+
).map((event) => event.message.text);
14053+
14054+
// The first member settles while the workflow runs on.
14055+
yield* harness.offerAndWait(
14056+
workflowSnapshot({
14057+
uuid: "00000000-0000-4000-8000-000000001396",
14058+
state: "done",
14059+
secondState: "start",
14060+
}),
14061+
);
14062+
assert.equal(
14063+
workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status,
14064+
"completed",
14065+
);
14066+
assert.deepEqual(texts(1), ["Reply with exactly: A1"], "no excerpt before the reply");
14067+
NodeFS.appendFileSync(transcriptPath("a1"), reply("a1"));
14068+
yield* harness.offerAndWait(
14069+
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001397", state: "done" }),
14070+
);
14071+
assert.deepEqual(texts(1), ["Reply with exactly: A1", "a1 found README.md"]);
14072+
assert.deepEqual(texts(2), ["Reply with exactly: A2"]);
14073+
14074+
// The workflow ends right after the second member, before its reply lands.
14075+
appendLateReply = () => NodeFS.appendFileSync(transcriptPath("a2"), reply("a2"));
14076+
const notified = yield* harness
14077+
.offerAndWait(
14078+
workflowNotification({
14079+
uuid: "00000000-0000-4000-8000-000000001398",
14080+
status: "completed",
14081+
}),
14082+
)
14083+
.pipe(Effect.forkScoped);
14084+
yield* Deferred.await(lateReplyWritten);
14085+
for (let tick = 0; tick < 20 && texts(2).length < 2; tick += 1) {
14086+
yield* TestClock.adjust("100 millis");
14087+
}
14088+
yield* Fiber.join(notified);
14089+
assert.deepEqual(texts(2), ["Reply with exactly: A2", "a2 found README.md"]);
14090+
assert.deepEqual(texts(1), ["Reply with exactly: A1", "a1 found README.md"]);
14091+
yield* Queue.offer(
14092+
harness.sdkMessages,
14093+
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001399", result: "Done." }),
14094+
);
14095+
yield* Queue.take(harness.terminalReceipts);
14096+
}).pipe(
14097+
Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => {
14098+
// Lands just after the read that would have settled the member.
14099+
if (read.agentId !== "a2" || appendLateReply === undefined) return Effect.void;
14100+
const append = appendLateReply;
14101+
appendLateReply = undefined;
14102+
append();
14103+
return Deferred.succeed(lateReplyWritten, undefined).pipe(Effect.asVoid);
14104+
}),
14105+
);
14106+
}).pipe(
14107+
Effect.provide(
14108+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14109+
),
14110+
),
14111+
),
14112+
);
14113+
1401614114
it.effect("re-reads a workflow member's transcript after a restart without new items", () =>
1401714115
Effect.scoped(
1401814116
Effect.gen(function* () {

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

Lines changed: 52 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,10 @@ const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
235235
// The SDK puts no deadline on control requests. The CLI answers
236236
// mcp_set_servers once each server connected or hit its own 30 s timeout.
237237
const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
238+
// Claude Code flushes transcript writes every 100 ms, so a workflow member's
239+
// reply can land after the progress frame that settles it. Its transcript
240+
// stays the source of its answer this long after it settles.
241+
const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
238242

239243
/**
240244
* When the CLI exits it stops the MCP servers it started, but not their children: a plugin's
@@ -4697,6 +4701,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
46974701
let textShown = !restarted && previous?.textShown === true;
46984702
let resultShown = !restarted && previous?.resultShown === true;
46994703
let transcriptRead = false;
4704+
let lastReadAt = now;
4705+
const awaitingReply = () => settled && transcriptRead && !textShown && !resultShown;
4706+
// Milliseconds until a read started at `at` sees every line the
4707+
// member wrote before it settled.
4708+
const flushWindowLeft = (at: DateTime.Utc) =>
4709+
completedAt === null
4710+
? 0
4711+
: WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS -
4712+
(DateTime.toEpochMillis(at) - DateTime.toEpochMillis(completedAt));
47004713
// Each read is capped, so keep reading until the transcript has no
47014714
// more complete lines; a settled member's answer may be past the cap.
47024715
let transcriptDrained = true;
@@ -4719,28 +4732,52 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
47194732
),
47204733
}),
47214734
}).pipe(Effect.option);
4722-
transcriptDrained = false;
4723-
while (!transcriptDrained) {
4724-
const read = yield* readNext(transcriptCursor);
4725-
if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
4726-
return;
4727-
if (Option.isNone(read)) break;
4728-
transcriptRead = true;
4729-
const advanced = read.value.cursor.offset !== transcriptCursor.offset;
4730-
transcriptCursor = read.value.cursor;
4731-
for (const line of read.value.lines) {
4732-
if (yield* projectSubagentTranscriptLine(target, line)) textShown = true;
4735+
// False once the coordinator was replaced mid-read.
4736+
const drain = Effect.fnUntraced(function* () {
4737+
lastReadAt = yield* DateTime.now;
4738+
transcriptDrained = false;
4739+
while (!transcriptDrained) {
4740+
const read = yield* readNext(transcriptCursor);
4741+
if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
4742+
return false;
4743+
if (Option.isNone(read)) break;
4744+
transcriptRead = true;
4745+
const advanced = read.value.cursor.offset !== transcriptCursor.offset;
4746+
transcriptCursor = read.value.cursor;
4747+
for (const line of read.value.lines) {
4748+
if (yield* projectSubagentTranscriptLine(target, line)) textShown = true;
4749+
}
4750+
// A line longer than the cap can't advance; stop rather than spin.
4751+
transcriptDrained = !read.value.truncated || !advanced;
47334752
}
4734-
// A line longer than the cap can't advance; stop rather than spin.
4735-
transcriptDrained = !read.value.truncated || !advanced;
4753+
return true;
4754+
});
4755+
if (!(yield* drain())) return;
4756+
// The coordinator sends nothing after its last frame, so wait out
4757+
// the flush window here rather than settle on the excerpt.
4758+
const waitLeft = flushWindowLeft(lastReadAt);
4759+
if (
4760+
input.coordinator.task.status !== "running" &&
4761+
awaitingReply() &&
4762+
member.result !== undefined &&
4763+
waitLeft > 0
4764+
) {
4765+
yield* Effect.sleep(waitLeft);
4766+
if (!(yield* drain())) return;
47364767
}
47374768
}
47384769
if (settled) {
47394770
// As for an ordinary subagent, a call still open once the member
47404771
// settles will never get its result.
47414772
yield* endOpenToolCalls();
4742-
// Only the progress excerpt is left when the transcript says nothing.
4743-
if (!textShown && !resultShown && member.result !== undefined) {
4773+
// Only the progress excerpt is left when the transcript says
4774+
// nothing, read after its last writes had time to land.
4775+
if (
4776+
!textShown &&
4777+
!resultShown &&
4778+
member.result !== undefined &&
4779+
(!transcriptRead || flushWindowLeft(lastReadAt) <= 0)
4780+
) {
47444781
yield* emitSubagentConversationMessage({
47454782
nativeItemId: `${memberKey}:result:${attempt}`,
47464783
threadId: childThreadId,

0 commit comments

Comments
 (0)