Skip to content

Commit 3456c3f

Browse files
fix(server): Claude threads recover after you log in again
The Claude CLI reads its login once per process, and a thread keeps one process alive between turns. After a turn fails to authenticate, mark that process signed out so the next turn replaces it with a fresh one that resumes the same conversation. The sign-in error tells the user to send the message again instead of starting a new thread. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5fe7568 commit 3456c3f

5 files changed

Lines changed: 77 additions & 4 deletions

File tree

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3198,6 +3198,68 @@ describe("ClaudeAdapterV2 background wake turns", () => {
31983198
),
31993199
);
32003200

3201+
it.effect.each([
3202+
{ failure: "authentication_failed", opensFreshProcess: true },
3203+
{ failure: "server_error", opensFreshProcess: false },
3204+
] as const)(
3205+
"after a turn fails with $failure, the next turn opens a fresh process: $opensFreshProcess",
3206+
({ failure, opensFreshProcess }) =>
3207+
Effect.gen(function* () {
3208+
let closeCount = 0;
3209+
const harness = yield* makeWakeHarnessWithOptions({
3210+
freshQueueOnReopen: true,
3211+
close: () =>
3212+
Effect.sync(() => {
3213+
closeCount += 1;
3214+
}),
3215+
});
3216+
const now = yield* DateTime.now;
3217+
const startTurn = (attempt: string, text: string) =>
3218+
harness.runtime.startTurn(
3219+
makeClaudeTestTurnInput({
3220+
threadId: harness.threadId,
3221+
providerThread: harness.providerThread,
3222+
now,
3223+
attemptId: RunAttemptId.make(attempt),
3224+
text,
3225+
attachments: [],
3226+
}),
3227+
);
3228+
3229+
yield* startTurn("attempt-claude-relogin-1", "Continue.");
3230+
yield* Queue.offerAll(harness.sdkMessages, [
3231+
makeAssistantErrorFrame({ uuid: "00000000-0000-4000-8000-000000000611", error: failure }),
3232+
makeResultFrame({
3233+
uuid: "00000000-0000-4000-8000-000000000612",
3234+
result: "API Error",
3235+
terminalReason: "api_error",
3236+
isError: true,
3237+
}),
3238+
]);
3239+
const failed = yield* Queue.take(harness.terminalReceipts);
3240+
assert.equal(failed.status, "failed");
3241+
3242+
yield* startTurn("attempt-claude-relogin-2", "Try again.");
3243+
assert.equal(harness.processQueues.length, opensFreshProcess ? 2 : 1);
3244+
assert.equal(closeCount, opensFreshProcess ? 1 : 0);
3245+
if (opensFreshProcess) {
3246+
// The fresh process resumes the same Claude conversation.
3247+
assert.equal(harness.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION);
3248+
assert.isUndefined(harness.getOpenedOptions()?.sessionId);
3249+
}
3250+
yield* Queue.offer(
3251+
harness.processQueues.at(-1)!,
3252+
makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000613", result: "Done." }),
3253+
);
3254+
const completed = yield* Queue.take(harness.terminalReceipts);
3255+
assert.equal(completed.status, "completed");
3256+
}).pipe(
3257+
Effect.provide(
3258+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3259+
),
3260+
),
3261+
);
3262+
32013263
it.effect.each([
32023264
{ recovered: false, expected: "Claude usage limit reached" },
32033265
{ recovered: true, expected: "Claude gave up after repeated API errors" },

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3006,6 +3006,9 @@ interface ClaudeLiveQueryContext {
30063006
permissionMode: PermissionMode;
30073007
// Stop, rollback or fork is closing this process; its work is ending.
30083008
stopping: boolean;
3009+
// A turn failed to authenticate. The CLI reads its login once per process,
3010+
// so the next turn replaces this process to pick up a new login.
3011+
signedOut: boolean;
30093012
// Registry entries still running when this process opened. Their process
30103013
// is gone and never reports their end; any later task_started replaces the
30113014
// entry, so an entry still in this set runs nowhere.
@@ -7615,9 +7618,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
76157618
resultFailure?.class === "usage_limit"
76167619
? { ...resultFailure, resetAt: resetAt ?? resultFailure.resetAt ?? null }
76177620
: resultFailure;
7621+
const status = interrupted
7622+
? "interrupted"
7623+
: terminalStatusFromResult(message, failureHint);
7624+
if (status === "failed" && context.authenticationFailureMessage !== undefined) {
7625+
liveQuery.signedOut = true;
7626+
}
76187627
yield* finalizeActiveTurn({
76197628
context,
7620-
status: interrupted ? "interrupted" : terminalStatusFromResult(message, failureHint),
7629+
status,
76217630
completedAt,
76227631
result: message,
76237632
...(terminalFailure === null ? {} : { failure: terminalFailure }),
@@ -8218,6 +8227,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
82188227
if (
82198228
existing !== null &&
82208229
existing.nativeThreadId === nativeThreadId &&
8230+
!existing.signedOut &&
82218231
existing.queryPolicyKey === queryPolicyKey &&
82228232
existing.selectionKey === compiledSelection.queryIdentity
82238233
) {
@@ -8353,6 +8363,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
83538363
openedPermissionMode: queryOptions.permissionMode,
83548364
permissionMode: queryOptions.permissionMode,
83558365
stopping: false,
8366+
signedOut: false,
83568367
subagentsFromEarlierProcesses: new Set(
83578368
[...(yield* Ref.get(sessionSubagentsByTaskId)).values()].filter(
83588369
(subagent) => subagent.task.status === "running",

‎apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313

1414
const AUTH_ERROR_TEXT = "Failed to authenticate. API Error: 401 Invalid authentication credentials";
1515
const AUTH_FAILURE_TEXT =
16-
"Claude could not authenticate. For subscription login, run `claude auth login` on this environment's machine, then start a new thread. For API-key authentication, check this instance's configured credentials.";
16+
"Claude could not authenticate. For subscription login, run `claude auth login` on this environment's machine, then send the message again. For API-key authentication, check this instance's configured credentials.";
1717

1818
export function assertClaudeResultIsErrorOutput(
1919
result: OrchestratorV2ScenarioResult,

‎apps/server/src/provider/Drivers/ClaudeHome.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
7373
const message = claudeSignedOutMessage({ configDir, cwd: "/synthetic/project" });
7474
expect(message).toContain(`CLAUDE_CONFIG_DIR set to "${configDir}"`);
7575
expect(message).not.toContain("CLAUDE_CONFIG_DIR=");
76-
expect(message).toContain("then start a new thread");
76+
expect(message).toContain("then send the message again");
7777
});
7878

7979
it.effect("separates capability probes by cwd", () =>

‎apps/server/src/provider/Drivers/ClaudeHome.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,5 +86,5 @@ export const claudeSignedOutMessage = (input: {
8686
input.configDir !== undefined
8787
? ` from ${quotePath(input.cwd)}, with CLAUDE_CONFIG_DIR set to ${quotePath(input.configDir)}`
8888
: "";
89-
return `Claude could not authenticate. For subscription login, run \`claude auth login\` on this environment's machine${configuration}, then start a new thread. For API-key authentication, check this instance's configured credentials.`;
89+
return `Claude could not authenticate. For subscription login, run \`claude auth login\` on this environment's machine${configuration}, then send the message again. For API-key authentication, check this instance's configured credentials.`;
9090
};

0 commit comments

Comments
 (0)