Skip to content
TypeScript

fix(server): Claude prompts no longer hang on a uuid the session already holds (#16897)

Julius Marmingef570bd21663f
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index b57dffad2c1..595fe28b1b9 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -2229,6 +2229,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
processQueues,
offerAndWait,
offeredMessages,
+ // The uuid Claude echoes on the turn answering the nth offered prompt.
+ promptUuid: (index: number) => {
+ const uuid = offeredMessages[index]?.uuid;
+ if (uuid === undefined) throw new Error(`No prompt offered at index ${index}.`);
+ return uuid;
+ },
permissionModeChanges,
continuationRequests,
events,
@@ -4421,12 +4427,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const continuationAttempt = RunAttemptId.make("attempt-claude-wake-callback-3");
const planToolUseId = "toolu_01WakePlanExitPlanMode";
const planMarkdown = "# Wake plan\n\n1. Report the background result.";
- const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
- return claudeSdkFrame({
+ const stamp = (frame: SDKMessage, promptIndex: number) =>
+ claudeSdkFrame({
...frame,
- user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
+ user_message_uuid: harness.promptUuid(promptIndex),
});
- });
const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`);
const planToolUse = claudeSdkFrame({
type: "assistant",
@@ -4479,12 +4484,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
runtimePolicy,
}),
);
- yield* Queue.offer(harness.sdkMessages, yield* stamp(wakeTaskStarted, firstAttempt));
+ yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0));
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000740", result: "STARTED" }),
- firstAttempt,
+ 0,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
@@ -4541,22 +4546,22 @@ describe("ClaudeAdapterV2 background wake turns", () => {
// The prompt's own turn follows and echoes its uuid.
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeAssistantTextFrame({
uuid: "00000000-0000-4000-8000-000000000743",
text: "USER_REPLY",
}),
- userAttempt,
+ 1,
),
);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000744",
result: "USER_REPLY",
}),
- userAttempt,
+ 1,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal");
@@ -4721,12 +4726,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const firstAttempt = RunAttemptId.make("attempt-claude-wake-approval-1");
const userAttempt = RunAttemptId.make("attempt-claude-wake-approval-2");
const bashToolUseId = "toolu_01WakeApprovalBash";
- const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
- return claudeSdkFrame({
+ const stamp = (frame: SDKMessage, promptIndex: number) =>
+ claudeSdkFrame({
...frame,
- user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
+ user_message_uuid: harness.promptUuid(promptIndex),
});
- });
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
@@ -4741,16 +4745,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000780", text: "One." }),
- firstAttempt,
+ 0,
),
);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000781", result: "One." }),
- firstAttempt,
+ 0,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
@@ -4845,12 +4849,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const now = yield* DateTime.now;
const firstAttempt = RunAttemptId.make("attempt-claude-echo-debris-1");
const secondAttempt = RunAttemptId.make("attempt-claude-echo-debris-2");
- const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
- return claudeSdkFrame({
+ const stamp = (frame: SDKMessage, promptIndex: number) =>
+ claudeSdkFrame({
...frame,
- user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
+ user_message_uuid: harness.promptUuid(promptIndex),
});
- });
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
@@ -4865,16 +4868,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
// The first turn echoes on its first frame: this process echoes early.
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000760", text: "One." }),
- firstAttempt,
+ 0,
),
);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000761", result: "One." }),
- firstAttempt,
+ 0,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
@@ -4899,16 +4902,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000762", text: "Two." }),
- secondAttempt,
+ 1,
),
);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000763", result: "Two." }),
- secondAttempt,
+ 1,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal");
@@ -4944,12 +4947,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const now = yield* DateTime.now;
const firstAttempt = RunAttemptId.make("attempt-claude-echo-1");
const secondAttempt = RunAttemptId.make("attempt-claude-echo-2");
- const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
- return claudeSdkFrame({
+ const stamp = (frame: SDKMessage, promptIndex: number) =>
+ claudeSdkFrame({
...frame,
- user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
+ user_message_uuid: harness.promptUuid(promptIndex),
});
- });
const assistantTexts = () =>
harness.events.flatMap((event) =>
event.type === "message.updated" && event.message.role === "assistant"
@@ -4969,22 +4971,18 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachments: [],
}),
);
- assert.equal(
- harness.offeredMessages[0]?.uuid,
- yield* ClaudeAdapterV2.claudePromptUuid(firstAttempt),
- );
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000701", text: "One." }),
- firstAttempt,
+ 0,
),
);
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000702", result: "One." }),
- firstAttempt,
+ 0,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
@@ -5018,6 +5016,118 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect("gives the same run attempt a fresh prompt uuid on every offer", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ // Two servers sharing a database copy allocate identical run attempt
+ // ids and resume the same Claude session. Claude acks a prompt whose
+ // uuid its transcript already holds without ever running a turn.
+ const original = yield* makeWakeHarness;
+ const copy = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ for (const harness of [original, copy]) {
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-shared-copy"),
+ text: "Continue where you left off.",
+ attachments: [],
+ }),
+ );
+ }
+ assert.notEqual(original.promptUuid(0), copy.promptUuid(0));
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
+ ),
+ );
+
+ it.effect("fails a prompt Claude completes without starting a turn for it", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ // Claude answers a prompt whose uuid its transcript already holds with
+ // a lone completed lifecycle frame and never runs a turn for it.
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-duplicate-prompt"),
+ text: "Bump this PR to the latest main.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(
+ harness.sdkMessages,
+ claudeSdkFrame({
+ type: "command_lifecycle",
+ command_uuid: harness.promptUuid(0),
+ state: "completed",
+ uuid: "00000000-0000-4000-8000-000000000790",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
+ const [terminal] = harness.terminalEvents();
+ assert.equal(terminal?.status, "failed");
+ if (terminal?.status !== "failed") return;
+ assert.equal(terminal.threadDisposition, "reusable");
+ assert.include(terminal.failure.message, "never started a turn");
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
+ ),
+ );
+
+ it.effect("keeps a started prompt running until its result", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-started-prompt"),
+ text: "Bump this PR to the latest main.",
+ attachments: [],
+ }),
+ );
+ const lifecycle = (state: string, uuid: string) =>
+ claudeSdkFrame({
+ type: "command_lifecycle",
+ command_uuid: harness.promptUuid(0),
+ state,
+ uuid,
+ session_id: WAKE_NATIVE_SESSION,
+ });
+ yield* Queue.offer(
+ harness.sdkMessages,
+ lifecycle("queued", "00000000-0000-4000-8000-000000000791"),
+ );
+ yield* Queue.offer(
+ harness.sdkMessages,
+ lifecycle("started", "00000000-0000-4000-8000-000000000792"),
+ );
+ // The CLI can report the prompt completed before its turn's result.
+ yield* Queue.offer(
+ harness.sdkMessages,
+ lifecycle("completed", "00000000-0000-4000-8000-000000000793"),
+ );
+ yield* Queue.offer(
+ harness.sdkMessages,
+ claudeSdkFrame({
+ ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000794", result: "Done." }),
+ user_message_uuid: harness.promptUuid(0),
+ }),
+ );
+ yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
+ assert.equal(harness.terminalEvents()[0]?.status, "completed");
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
+ ),
+ );
+
it.effect("buffers wake output and requests a single continuation run", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -6031,12 +6141,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const userAttempt = RunAttemptId.make("attempt-claude-wake-subagent-2");
const continuationAttempt = RunAttemptId.make("attempt-claude-wake-subagent-3");
const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`);
- const stamp = Effect.fnUntraced(function* (frame: SDKMessage, attemptId: RunAttemptId) {
- return claudeSdkFrame({
+ const stamp = (frame: SDKMessage, promptIndex: number) =>
+ claudeSdkFrame({
...frame,
- user_message_uuid: yield* ClaudeAdapterV2.claudePromptUuid(attemptId),
+ user_message_uuid: harness.promptUuid(promptIndex),
});
- });
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
@@ -6048,12 +6157,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
attachments: [],
}),
);
- yield* Queue.offer(harness.sdkMessages, yield* stamp(wakeTaskStarted, firstAttempt));
+ yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0));
yield* Queue.offer(
harness.sdkMessages,
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000770", result: "STARTED" }),
- firstAttempt,
+ 0,
),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
@@ -6120,16 +6229,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
}),
wakeResult,
- yield* stamp(
+ stamp(
makeAssistantTextFrame({
uuid: "00000000-0000-4000-8000-000000000776",
text: "USER_REPLY",
}),
- userAttempt,
+ 1,
),
- yield* stamp(
+ stamp(
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000777", result: "USER_REPLY" }),
- userAttempt,
+ 1,
),
];
for (const frame of wakeFrames) {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
index 2f73c0db11e..3e70e3d9a8f 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts
@@ -18,6 +18,7 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
+import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
@@ -1577,11 +1578,13 @@ async function recordClaudeStreamingQuery(input: {
};
try {
for (const [index, prompt] of input.prompts.entries()) {
- // Like the adapter, give each prompt a uuid Claude echoes on its turn.
+ // Like the adapter, give each prompt a fresh uuid Claude echoes on its turn.
const message = ClaudeAdapterV2.makeClaudeUserMessage({
text: prompt,
uuid: await Effect.runPromise(
- ClaudeAdapterV2.claudePromptUuid(`${input.sessionId}:prompt:${index + 1}`).pipe(
+ Crypto.Crypto.pipe(
+ Effect.flatMap((crypto) => crypto.randomUUIDv4),
+ Effect.filterOrFail(ClaudeAdapterV2.isClaudePromptUuid),
Effect.provide(NodeServices.layer),
),
),
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 6cedbb153d8..26246b2038b 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -71,7 +71,6 @@ import {
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
-import * as Hex from "effect/encoding/Hex";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -1417,19 +1416,9 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
} satisfies SDKUserMessage;
});
-// Stable per run attempt, so a replayed prompt offer matches its recording.
-// Claude echoes it back as user_message_uuid on the turn that answers it.
-export const claudePromptUuid = Effect.fn("claudePromptUuid")(function* (attemptId: string) {
- const crypto = yield* Crypto.Crypto;
- const digest = yield* crypto
- .digest("SHA-256", new TextEncoder().encode(`t3-claude-prompt:${attemptId}`))
- .pipe(Effect.orDie);
- const hex = Hex.encode(digest);
- const variant = ((Number.parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);
- const uuid: NonNullable<SDKUserMessage["uuid"]> =
- `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
- return uuid;
-});
+export function isClaudePromptUuid(value: string): value is NonNullable<SDKUserMessage["uuid"]> {
+ return /^[^-]+-[^-]+-[^-]+-[^-]+-[^-]+$/.test(value);
+}
type ClaudeAssistantContentBlock = SDKAssistantMessage["message"]["content"][number];
type ClaudeToolUseContentBlock = Extract<
@@ -2477,14 +2466,17 @@ function claudeEchoedPromptUuids(message: SDKMessage): ReadonlyArray<string> {
return typeof uuid === "string" ? [uuid] : [];
}
-// The prompt uuid a command_lifecycle frame (queued, started, completed)
+// The prompt a command_lifecycle frame (queued, started, completed)
// acknowledges. A CLI that sends them also echoes that uuid on the result of
// the turn answering the prompt; one that does not keeps the old path.
-function claudeAcknowledgedPromptUuid(message: SDKMessage): string | null {
+function claudePromptLifecycle(
+ message: SDKMessage,
+): { readonly uuid: string; readonly state: string } | null {
const type: unknown = Reflect.get(message, "type");
if (type !== "command_lifecycle") return null;
const uuid: unknown = Reflect.get(message, "command_uuid");
- return typeof uuid === "string" ? uuid : null;
+ const state: unknown = Reflect.get(message, "state");
+ return typeof uuid === "string" && typeof state === "string" ? { uuid, state } : null;
}
// A result that answers a turn other than the pending prompt's. An echo
@@ -2750,6 +2742,8 @@ interface ActiveClaudeTurnContext {
// prompt's turn echoes this uuid (see handleSdkMessage).
readonly promptUuid: string | null;
promptEcho: "pending" | "confirmed";
+ // Claude acknowledged starting the prompt (command_lifecycle "started").
+ promptStarted: boolean;
// Root frames seen before the echo; held only when the CLI echoes early.
gatedFramesBeforeEcho: number;
readonly heldRootFrames: Array<SDKMessage>;
@@ -6801,11 +6795,32 @@ export function makeClaudeAdapterV2(
yield* handleRoutedSdkMessage(input);
return;
}
- if (
- liveQuery.promptEchoMode === "unknown" &&
- claudeAcknowledgedPromptUuid(message) === context.promptUuid
- ) {
- liveQuery.promptEchoMode = "acknowledged";
+ const lifecycle = claudePromptLifecycle(message);
+ if (lifecycle?.uuid === context.promptUuid) {
+ if (liveQuery.promptEchoMode === "unknown") {
+ liveQuery.promptEchoMode = "acknowledged";
+ }
+ if (lifecycle.state === "started") {
+ context.promptStarted = true;
+ }
+ // Claude finishes a prompt whose uuid its transcript already
+ // holds without starting it, and no turn will ever answer it.
+ if (lifecycle.state === "completed" && !context.promptStarted) {
+ yield* Effect.logWarning("orchestration-v2.claude-prompt-completed-without-turn", {
+ providerTurnId: context.providerTurnId,
+ promptUuid: context.promptUuid,
+ });
+ yield* finalizeActiveTurn({
+ context,
+ status: "failed",
+ completedAt: yield* DateTime.now,
+ failure: makeProviderFailure({
+ class: "provider_error",
+ message: "Claude acknowledged the message but never started a turn for it.",
+ }),
+ });
+ return;
+ }
}
if (!isClaudePromptEchoGatedFrame(message)) {
// Frames the held turn produced through its own tool uses (a
@@ -7442,10 +7457,22 @@ export function makeClaudeAdapterV2(
const startedAt = yield* DateTime.now;
const nativeThreadId = yield* getNativeThreadId(turnInput.providerThread);
const nativeTurnId = `turn:${turnInput.attemptId}`;
+ // Fresh for every offer: Claude acks a prompt whose uuid its
+ // transcript already holds without running a turn, and a session
+ // can outlive this database (or be resumed from a copy of it), so
+ // a uuid derived from run ids can repeat.
const promptUuid = isClaudeProviderContinuationTurn(turnInput)
? null
- : yield* claudePromptUuid(turnInput.attemptId).pipe(
- Effect.provideService(Crypto.Crypto, crypto),
+ : yield* crypto.randomUUIDv4.pipe(
+ Effect.filterOrFail(isClaudePromptUuid),
+ Effect.mapError(
+ (cause) =>
+ new ProviderAdapter.ProviderAdapterProtocolError({
+ driver: CLAUDE_PROVIDER,
+ detail: "Failed to allocate a Claude prompt uuid.",
+ payload: cause,
+ }),
+ ),
);
const providerTurnId = idAllocator.derive.providerTurn({
driver: CLAUDE_PROVIDER,
@@ -7505,6 +7532,7 @@ export function makeClaudeAdapterV2(
subagentNodesByTaskId: new Map(),
promptUuid,
promptEcho: isClaudeProviderContinuationTurn(turnInput) ? "confirmed" : "pending",
+ promptStarted: false,
gatedFramesBeforeEcho: 0,
heldRootFrames: [],
};