@devries-cameron20 / t3code-1 / commits / 629d5083b7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): a Claude session gone on resume starts fresh instead of failing every send (#37610)

Julius Marminge committed Nov 16, 2026 at 03:08 UTC 629d5083b7b0278edf0a5f587f25b8d40c3fdfb2
6 files changed +249 -5
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+44
@@ -14087,6 +14087,50 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14087 ),
14088 );
14089
14090 + it.effect("resumes in a fresh session after Claude Code reports its conversation gone", () =>
14091 + Effect.gen(function* () {
14092 + const harness = yield* openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame(
14093 + "claude-query-conversation-missing",
14094 + Stream.fail(
14095 + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
14096 + method: "fromAsyncIterable",
14097 + cause: new ClaudeAdapterV2.ClaudeConversationNotFoundError({
14098 + cause: new Error("Claude Code process exited with code 1"),
14099 + }),
14100 + }),
14101 + ),
14102 + );
14103 + const turnInput = harness.turnInput("a", 1);
14104 + const started = yield* harness.runtime.startTurn(turnInput).pipe(Effect.exit);
14105 + assert.isTrue(Exit.isFailure(started));
14106 + if (Exit.isFailure(started)) {
14107 + assert.include(
14108 + makeProviderFailure({ cause: started.cause, class: "transport_error" }).message,
14109 + "could not find this conversation",
14110 + );
14111 + }
14112 + // A failed resume is what sends the next turn to a fresh native session.
14113 + const resumed = yield* harness.runtime
14114 + .resumeThread({
14115 + providerThread: turnInput.providerThread,
14116 + threadId: turnInput.threadId,
14117 + modelSelection: CLAUDE_TEST_MODEL_SELECTION,
14118 + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
14119 + })
14120 + .pipe(Effect.exit);
14121 + assert.isTrue(Exit.isFailure(resumed));
14122 + }).pipe(
14123 + Effect.provide(
14124 + Layer.mergeAll(
14125 + IdAllocator.layer,
14126 + McpProviderSessions.layer,
14127 + NodeServices.layer,
14128 + NodeCrypto.layer,
14129 + ),
14130 + ),
14131 + ),
14132 + );
14133 +
14134 it.effect("fails a turn whose Claude query ends before its first frame", () =>
14135 Effect.gen(function* () {
14136 const harness = yield* openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame(
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+50 -3
@@ -383,6 +383,8 @@ const CLAUDE_DESCENDANT_POLL = "1 second";
383 // Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
384 const CLAUDE_ROOT_REFUSAL =
385 "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
386 +// Claude Code's answer to a --resume whose session store is gone, as a result error and on stderr.
387 +const CLAUDE_CONVERSATION_NOT_FOUND = "No conversation found with session ID:";
388
389 // fd 4 gates the launch until the server has recorded the process it is about to become.
390 // The shell enters the cwd itself: as a native cwd, a mount that hangs chdir freezes the server.
@@ -725,6 +727,17 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRoo
727 }
728 }
729
730 +export class ClaudeConversationNotFoundError extends Schema.TaggedError<ClaudeConversationNotFoundError>()(
731 + "ClaudeConversationNotFoundError",
732 + {
733 + cause: Schema.Defect(),
734 + },
735 +) {
736 + override get message(): string {
737 + return "Claude Code could not find this conversation to resume. Send the message again to continue in a new Claude session with this thread's history.";
738 + }
739 +}
740 +
741 class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
742 "ClaudeMcpRegistrationTimeoutError",
743 { phase: Schema.Literals(["initialize", "setMcpServers"]) },
@@ -821,6 +834,14 @@ export interface ClaudeAgentSdkSubagentLookupInput {
834 }
835
836 const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
837 +
838 +const isClaudeConversationNotFound = (cause: Cause.Cause<ClaudeAgentSdkQueryRunnerError>) => {
839 + const error = Cause.squash(cause);
840 + return (
841 + isClaudeAgentSdkQueryRunnerError(error) &&
842 + Predicate.isTagged(error.cause, "ClaudeConversationNotFoundError")
843 + );
844 +};
845 const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError);
846 const isProviderAdapterRuntimeRequestResponseError = Schema.is(
847 ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
@@ -1517,6 +1538,7 @@ export const layerQueryRunner: Layer.Layer<
1538 let stderrTail = "";
1539 let stderrClosed: Promise<void> = Promise.resolve();
1540 let answered = false;
1541 + let conversationMissing = false;
1542 const appendStderr = (text: string) => {
1543 if (answered) return;
1544 stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
@@ -1695,15 +1717,27 @@ export const layerQueryRunner: Layer.Layer<
1717 }
1718 const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
1719 return yield* queryRunnerError(
1698 - refusedRoot ? new ClaudeCodeRootRefusalError({ cause }) : cause,
1720 + refusedRoot
1721 + ? new ClaudeCodeRootRefusalError({ cause })
1722 + : conversationMissing ||
1723 + (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND))
1724 + ? new ClaudeConversationNotFoundError({ cause })
1725 + : cause,
1726 "fromAsyncIterable",
1727 );
1728 }),
1729 ),
1730 ),
1704 - Stream.tap(() =>
1731 + Stream.tap((message) =>
1732 Effect.sync(() => {
1733 answered = true;
1734 + if (
1735 + message.type === "result" &&
1736 + message.subtype !== "success" &&
1737 + message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND))
1738 + ) {
1739 + conversationMissing = true;
1740 + }
1741 }),
1742 ),
1743 Stream.tap((message) =>
@@ -5843,6 +5877,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5877 );
5878 });
5879 const openedNativeThreads = yield* Ref.make(new Set<string>());
5880 + // Sessions Claude Code reported gone on resume; resumeThread fails them into a fresh session.
5881 + const missingNativeThreads = new Set<string>();
5882 const pdfBudgets = new Map<string, ReturnType<typeof makeClaudeAttachmentBudget>>();
5883 const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
5884 // Claude 5 task tools edit one list per native session, across turns.
@@ -12910,7 +12946,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12946 Effect.exit,
12947 Effect.flatMap(
12948 Effect.fnUntraced(function* (exit: ClaudeQueryStreamExit) {
12913 - if (exit._tag === "Failure") context.exitCause = exit.cause;
12949 + if (exit._tag === "Failure") {
12950 + context.exitCause = exit.cause;
12951 + if (isClaudeConversationNotFound(exit.cause)) {
12952 + missingNativeThreads.add(context.nativeThreadId);
12953 + }
12954 + }
12955 const heldContext = yield* Ref.get(activeTurn);
12956 if (
12957 (yield* Ref.get(queryContext))?.query === querySession &&
@@ -13877,6 +13918,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13918 // A live process holds the conversation even before saving it.
13919 (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId
13920 ) {
13921 + if (missingNativeThreads.has(nativeThreadId)) {
13922 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
13923 + driver: CLAUDE_PROVIDER,
13924 + detail: `Claude Code has no conversation ${nativeThreadId} to resume.`,
13925 + });
13926 + }
13927 // An unreadable transcript leaves the resume to the CLI.
13928 const transcript = yield* claudeTranscriptState(nativeThreadId).pipe(
13929 Effect.orElseSucceed(() => "missing" as const),
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+43
@@ -710,6 +710,49 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
710
711 const unknown = yield* startupFailureMessage("token=sk-private-123");
712 assert.notInclude(unknown, "sk-private-123");
713 +
714 + const missingConversation = yield* startupFailureMessage(
715 + "No conversation found with session ID: sk-private-123",
716 + );
717 + assert.include(missingConversation, "could not find this conversation");
718 + assert.notInclude(missingConversation, "sk-private-123");
719 + }).pipe(Effect.provide(realQueryRunner)),
720 + );
721 +
722 + // What Claude Code writes when the session store behind --resume is gone.
723 + it.effect("names a resumed conversation Claude Code cannot find", () =>
724 + Effect.gen(function* () {
725 + const missing = "No conversation found with session ID: native-session-fake-cli";
726 + const result = JSON.stringify({
727 + type: "result",
728 + subtype: "error_during_execution",
729 + is_error: true,
730 + num_turns: 0,
731 + duration_ms: 0,
732 + duration_api_ms: 0,
733 + total_cost_usd: 0,
734 + usage: {},
735 + modelUsage: {},
736 + permission_denials: [],
737 + errors: [missing],
738 + session_id: "native-session-fake-cli",
739 + uuid: "00000000-0000-4000-8000-000000000000",
740 + });
741 + const cli = fakeClaudeCli(
742 + `printf '%s\\n' '${result}'\nprintf '%s\\n' '${missing}' >&2\nexit 1`,
743 + );
744 + yield* Effect.addFinalizer(() =>
745 + Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })),
746 + );
747 + const session = yield* openFakeCli(cli);
748 + const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit);
749 + assert.isTrue(Exit.isFailure(exit));
750 + if (Exit.isFailure(exit)) {
751 + assert.include(
752 + makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message,
753 + "could not find this conversation",
754 + );
755 + }
756 }).pipe(Effect.provide(realQueryRunner)),
757 );
758
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+82 -2
@@ -459,7 +459,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
459 readonly hasPendingBackgroundWorkForThread?: Effect.Effect<boolean>;
460 readonly backgroundTasksEndWithProcess?: boolean;
461 readonly hangSessionScopeClose?: boolean;
462 - readonly startTurn?: Effect.Effect<void>;
462 + readonly startTurn?: Effect.Effect<void, ProviderAdapter.ProviderAdapterProtocolError>;
463 readonly interruptTurn?: Effect.Effect<void>;
464 readonly beforeUnload?: Effect.Effect<void>;
465 readonly unloads?: Queue.Queue<string>;
@@ -641,7 +641,7 @@ function layerTest(input: {
641 readonly hasPendingBackgroundWorkForThread?: Effect.Effect<boolean>;
642 readonly backgroundTasksEndWithProcess?: boolean;
643 readonly hangSessionScopeClose?: boolean;
644 - readonly startTurn?: Effect.Effect<void>;
644 + readonly startTurn?: Effect.Effect<void, ProviderAdapter.ProviderAdapterProtocolError>;
645 readonly interruptTurn?: Effect.Effect<void>;
646 readonly beforeUnload?: Effect.Effect<void>;
647 readonly unloads?: Queue.Queue<string>;
@@ -1634,6 +1634,86 @@ it.effect("ProviderSessionManagerV2 gives up on a provider that never confirms a
1634 }),
1635 );
1636
1637 +// A failed start can leave its native thread gone, as when Claude rejects a resume.
1638 +it.effect("ProviderSessionManagerV2 resumes a thread natively again after its start failed", () =>
1639 + Effect.gen(function* () {
1640 + const state = yield* Ref.make(emptyState);
1641 + yield* Effect.gen(function* () {
1642 + const eventSink = yield* EventSink.EventSinkV2;
1643 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
1644 + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
1645 + const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1646 + const now = yield* DateTime.now;
1647 + const threadId = ThreadId.make("thread-provider-session-manager-failed-start-resume");
1648 + const providerSessionId = idAllocator.derive.providerSession({
1649 + providerInstanceId: modelSelection.instanceId,
1650 + });
1651 + yield* eventSink.write({
1652 + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
1653 + });
1654 + const runtime = yield* manager.open({
1655 + threadId,
1656 + providerSessionId,
1657 + modelSelection,
1658 + runtimePolicy,
1659 + });
1660 + const providerThread = makeProviderThread({
1661 + idAllocator,
1662 + threadId,
1663 + providerSessionId,
1664 + now,
1665 + nativeThreadId: `native-${threadId}`,
1666 + });
1667 + const resume = runtime.resumeThread({
1668 + providerThread,
1669 + threadId,
1670 + modelSelection,
1671 + runtimePolicy,
1672 + });
1673 + yield* resume;
1674 + yield* resume;
1675 + assert.equal((yield* Ref.get(state)).resumeCount, 1);
1676 + const runId = idAllocator.derive.run({ threadId, ordinal: 1 });
1677 + yield* runtime
1678 + .startTurn({
1679 + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread,
1680 + threadId,
1681 + runId,
1682 + runOrdinal: 1,
1683 + providerTurnOrdinal: 1,
1684 + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }),
1685 + rootNodeId: idAllocator.derive.rootNode({ runId }),
1686 + providerThread,
1687 + message: {
1688 + createdBy: "user",
1689 + creationSource: "web",
1690 + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }),
1691 + text: "turn",
1692 + attachments: [],
1693 + },
1694 + modelSelection,
1695 + runtimePolicy,
1696 + })
1697 + .pipe(Effect.flip);
1698 + yield* resume;
1699 + assert.equal((yield* Ref.get(state)).resumeCount, 2);
1700 + }).pipe(
1701 + Effect.provide(
1702 + layerTest({
1703 + state,
1704 + idleTimeoutMs: 60_000,
1705 + startTurn: Effect.fail(
1706 + new ProviderAdapter.ProviderAdapterProtocolError({
1707 + driver: CODEX_DRIVER,
1708 + detail: "query ended before the turn could start",
1709 + }),
1710 + ),
1711 + }),
1712 + ),
1713 + );
1714 + }),
1715 +);
1716 +
1717 it.effect("ProviderSessionManagerV2 still idles out a session releaseUnlessBusy kept", () =>
1718 Effect.gen(function* () {
1719 const state = yield* Ref.make(emptyState);
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+29
@@ -1683,6 +1683,25 @@ export const layerWithOptions = (
1683 ),
1684 );
1685
1686 + const forgetProviderThreadLoaded = (input: {
1687 + readonly providerSessionId: ProviderSessionId;
1688 + readonly threadId: ThreadId;
1689 + readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime;
1690 + }) =>
1691 + Ref.update(sessions, (current) => {
1692 + const key = sessionKey(input.providerSessionId);
1693 + const entry = current.get(key);
1694 + if (
1695 + entry?.runtime !== input.runtime ||
1696 + !entry.loadedProviderThreadKeyByThread.has(input.threadId)
1697 + ) {
1698 + return current;
1699 + }
1700 + const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread);
1701 + loadedProviderThreadKeyByThread.delete(input.threadId);
1702 + return new Map(current).set(key, { ...entry, loadedProviderThreadKeyByThread });
1703 + });
1704 +
1705 /** Pass the setting read before a native load; cache hits keep the earlier record. */
1706 const markProviderThreadLoaded = (input: {
1707 readonly providerSessionId: ProviderSessionId;
@@ -2494,6 +2513,16 @@ export const layerWithOptions = (
2513 ? observeActivity(
2514 providerSessionId,
2515 markIdle(providerSessionId, input.providerThread.id, input.runOrdinal),
2516 + ).pipe(
2517 + // A failed start can leave its native thread gone (Claude rejecting a
2518 + // resume), so the next start must ask the adapter to resume it again.
2519 + Effect.andThen(
2520 + forgetProviderThreadLoaded({
2521 + providerSessionId,
2522 + threadId: input.threadId,
2523 + runtime,
2524 + }),
2525 + ),
2526 )
2527 : Effect.void,
2528 ),
packages/provider-core/src/server/failure.ts
+1
@@ -122,6 +122,7 @@ function curatedCauseMessages(cause: unknown): {
122 case "ClaudeSettingsLaunchArgError":
123 case "ClaudeMcpRegistrationTimeoutError":
124 case "ClaudeCodeRootRefusalError":
125 + case "ClaudeConversationNotFoundError":
126 case "CursorModelUnavailableError":
127 case "CodexGoalObjectiveTooLongError":
128 case "ProviderSetupError":