Skip to content

Commit 59082a1

Browse files
committed
fix(server): isolate Claude workflow state between runs
1 parent 3b48b52 commit 59082a1

4 files changed

Lines changed: 164 additions & 15 deletions

File tree

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

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13698,6 +13698,123 @@ describe("ClaudeAdapterV2 background wake turns", () => {
1369813698
),
1369913699
);
1370013700

13701+
it.effect("isolates member threads and transcript state when a workflow run changes", () =>
13702+
Effect.scoped(
13703+
Effect.gen(function* () {
13704+
const harness = yield* makeWorkflowHarness;
13705+
yield* harness.runtime.startTurn(
13706+
makeClaudeTestTurnInput({
13707+
threadId: harness.threadId,
13708+
providerThread: harness.providerThread,
13709+
now: yield* DateTime.now,
13710+
attemptId: RunAttemptId.make("attempt-workflow-run-change"),
13711+
text: "Run the workflow twice.",
13712+
attachments: [],
13713+
}),
13714+
);
13715+
yield* harness.offerAndWait(workflowToolUse);
13716+
yield* harness.offerAndWait(workflowTaskStarted);
13717+
yield* harness.offerAndWait(
13718+
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000004001", state: "queued" }),
13719+
);
13720+
yield* harness.until(() => workflowMemberEvents(harness.events, 2).length === 1);
13721+
const beforeAck = workflowMemberEvents(harness.events, 1).at(-1)!.subagent;
13722+
yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
13723+
yield* harness.offerAndWait(
13724+
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000004002", state: "done" }),
13725+
);
13726+
yield* harness.until(
13727+
() => workflowMemberEvents(harness.events, 2).at(-1)?.subagent.status === "completed",
13728+
);
13729+
const first = workflowMemberEvents(harness.events, 1).at(-1)!.subagent;
13730+
assert.equal(first.childThreadId, beforeAck.childThreadId);
13731+
const firstMessages = threadMessages(harness.events, first.childThreadId);
13732+
assert.deepEqual(
13733+
firstMessages.map((event) => event.message.text),
13734+
["Reply with exactly: A1", "A1 from the transcript"],
13735+
);
13736+
const ack = workflowLaunchAck(harness.transcriptDir);
13737+
yield* harness.offerAndWait(
13738+
claudeSdkFrame({
13739+
...ack,
13740+
uuid: "00000000-0000-4000-8000-000000004003",
13741+
tool_use_result: { taskType: "local_workflow", runId: "wf_second" },
13742+
}),
13743+
);
13744+
yield* harness.until(
13745+
() =>
13746+
workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.runHandles
13747+
?.runId === "wf_second",
13748+
);
13749+
yield* harness.offerAndWait(
13750+
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000004004", state: "queued" }),
13751+
);
13752+
yield* harness.until(
13753+
() =>
13754+
workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] !==
13755+
undefined,
13756+
);
13757+
const secondThreadId = workflowCoordinatorEvents(harness.events).at(-1)!.subagent.workflow!
13758+
.agents[0]!.childThreadId;
13759+
assert.notEqual(secondThreadId, first.childThreadId);
13760+
yield* harness.until(
13761+
() =>
13762+
workflowMemberEvents(harness.events, 1).at(-1)?.subagent.childThreadId ===
13763+
secondThreadId,
13764+
);
13765+
const second = workflowMemberEvents(harness.events, 1).at(-1)!.subagent;
13766+
assert.notEqual(second.childThreadId, first.childThreadId);
13767+
assert.notEqual(second.id, first.id);
13768+
assert.equal(second.status, "pending");
13769+
assert.isNull(second.startedAt);
13770+
assert.isNull(second.completedAt);
13771+
assert.isNull(second.result);
13772+
const secondPrompt = threadMessages(harness.events, second.childThreadId);
13773+
assert.deepEqual(
13774+
secondPrompt.map((event) => event.message.text),
13775+
["Reply with exactly: A1"],
13776+
);
13777+
assert.notEqual(secondPrompt[0]!.message.id, firstMessages[0]!.message.id);
13778+
NodeFS.writeFileSync(
13779+
NodePath.join(harness.transcriptDir, "agent-a1.jsonl"),
13780+
'{"type":"assistant","uuid":"wf-second-run-line","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_second","content":[{"type":"text","text":"A1 from the second run transcript"}]}}\n',
13781+
);
13782+
yield* harness.offerAndWait(
13783+
claudeSdkFrame({
13784+
...ack,
13785+
uuid: "00000000-0000-4000-8000-000000004005",
13786+
tool_use_result: {
13787+
taskType: "local_workflow",
13788+
runId: "wf_second",
13789+
transcriptDir: harness.transcriptDir,
13790+
},
13791+
}),
13792+
);
13793+
yield* harness.offerAndWait(
13794+
workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000004006", state: "done" }),
13795+
);
13796+
yield* harness.until(
13797+
() =>
13798+
threadMessages(harness.events, second.childThreadId).at(-1)?.message.text ===
13799+
"A1 from the second run transcript",
13800+
);
13801+
assert.deepEqual(
13802+
threadMessages(harness.events, second.childThreadId).map((event) => event.message.text),
13803+
["Reply with exactly: A1", "A1 from the second run transcript"],
13804+
);
13805+
assert.deepEqual(threadMessages(harness.events, first.childThreadId), firstMessages);
13806+
yield* harness.offerAndWait(
13807+
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000004007", result: "Launched." }),
13808+
);
13809+
yield* Queue.take(harness.terminalReceipts);
13810+
}).pipe(
13811+
Effect.provide(
13812+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13813+
),
13814+
),
13815+
),
13816+
);
13817+
1370113818
it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () =>
1370213819
Effect.scoped(
1370313820
Effect.gen(function* () {

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

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5567,10 +5567,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
55675567
...workflow,
55685568
agents: workflow.agents.map((member) => ({
55695569
...member,
5570-
childThreadId: idAllocator.derive.threadFromProviderThread({
5571-
driver: CLAUDE_PROVIDER,
5572-
nativeThreadId: `${coordinatorChildThreadId}:agent:${member.index}`,
5573-
}),
5570+
childThreadId:
5571+
member.childThreadId ??
5572+
idAllocator.derive.threadFromProviderThread({
5573+
driver: CLAUDE_PROVIDER,
5574+
nativeThreadId: `${coordinatorChildThreadId}:run:${workflow.runHandles?.runId ?? "unknown"}:agent:${member.index}`,
5575+
}),
55745576
})),
55755577
});
55765578

@@ -5636,7 +5638,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
56365638
for (const member of input.workflow.agents) {
56375639
if ((yield* Ref.get(sessionSubagentsByTaskId)).get(taskId) !== input.coordinator)
56385640
return;
5639-
const memberKey = `${input.coordinator.childThreadId}:agent:${member.index}`;
5641+
const childThreadId = member.childThreadId;
5642+
if (childThreadId === undefined) continue;
5643+
const memberKey = `${childThreadId}:agent:${member.index}`;
56405644
const previous = seen.get(memberKey);
56415645
const status =
56425646
(member.state === "queued" || member.state === "running") &&
@@ -5692,9 +5696,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
56925696
driver: CLAUDE_PROVIDER,
56935697
nativeItemId: `${memberKey}:thread-root`,
56945698
});
5695-
const childThreadId = member.childThreadId;
5696-
if (childThreadId === undefined) continue;
5697-
56985699
if (
56995700
previous === undefined ||
57005701
previous.label !== member.label ||

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,26 @@ const agent = (overrides: Record<string, unknown>) => ({
2727
});
2828

2929
describe("mergeClaudeWorkflowProgress", () => {
30+
it("resets phases, members, handles and usage for a different run", () => {
31+
const previous = mergeClaudeWorkflowProgress({
32+
previous: undefined,
33+
name: "Review",
34+
runHandles: { runId: "old", transcriptDir: "/old", scriptPath: "/old.ts" },
35+
message: snapshotFrame([phase(1, "Old"), agent({ state: "done" })], {
36+
total_tokens: 100,
37+
tool_uses: 2,
38+
duration_ms: 50,
39+
}),
40+
});
41+
42+
expect(
43+
mergeClaudeWorkflowProgress({ previous, runHandles: { runId: "new" }, message: {} }),
44+
).toEqual({ name: "Review", runHandles: { runId: "new" }, phases: [], agents: [] });
45+
expect(
46+
mergeClaudeWorkflowProgress({ previous, runHandles: { runId: "old" }, message: {} }),
47+
).toEqual(previous);
48+
});
49+
3050
it("maps provider agent states and per-member metrics", () => {
3151
const workflow = mergeClaudeWorkflowProgress({
3252
previous: undefined,

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

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,18 @@ export function mergeClaudeWorkflowProgress(input: {
132132
) {
133133
return undefined;
134134
}
135+
const runChanged =
136+
input.runHandles?.runId !== undefined &&
137+
previous?.runHandles?.runId !== undefined &&
138+
input.runHandles.runId !== previous.runHandles.runId;
139+
const previousProgress = runChanged ? undefined : previous;
135140
const reported = field(input.message, "usage");
136141
const phasesByIndex = new Map(
137-
(previous?.phases ?? []).map((phase) => [phase.index, phase] as const),
142+
(previousProgress?.phases ?? []).map((phase) => [phase.index, phase] as const),
138143
);
139144
for (const phase of snapshot?.phases ?? []) phasesByIndex.set(phase.index, phase);
140145
const agentsByIndex = new Map(
141-
(previous?.agents ?? []).map((agent) => [agent.index, agent] as const),
146+
(previousProgress?.agents ?? []).map((agent) => [agent.index, agent] as const),
142147
);
143148
for (const agent of snapshot?.agents ?? []) {
144149
const prior = agentsByIndex.get(agent.index);
@@ -167,15 +172,21 @@ export function mergeClaudeWorkflowProgress(input: {
167172
}
168173
const runHandles =
169174
input.runHandles === undefined
170-
? previous?.runHandles
171-
: { ...previous?.runHandles, ...input.runHandles };
175+
? previousProgress?.runHandles
176+
: { ...previousProgress?.runHandles, ...input.runHandles };
172177
return {
173178
...optional("name", input.name ?? previous?.name),
174179
...optional("runHandles", runHandles),
175180
phases: Array.from(phasesByIndex.values()).sort((left, right) => left.index - right.index),
176181
agents: Array.from(agentsByIndex.values()).sort((left, right) => left.index - right.index),
177-
...optional("totalTokens", count(field(reported, "total_tokens")) ?? previous?.totalTokens),
178-
...optional("toolCalls", count(field(reported, "tool_uses")) ?? previous?.toolCalls),
179-
...optional("durationMs", count(field(reported, "duration_ms")) ?? previous?.durationMs),
182+
...optional(
183+
"totalTokens",
184+
count(field(reported, "total_tokens")) ?? previousProgress?.totalTokens,
185+
),
186+
...optional("toolCalls", count(field(reported, "tool_uses")) ?? previousProgress?.toolCalls),
187+
...optional(
188+
"durationMs",
189+
count(field(reported, "duration_ms")) ?? previousProgress?.durationMs,
190+
),
180191
};
181192
}

0 commit comments

Comments
 (0)