GeezerVison is showing github.com — Merge pull request 'fix(server): Claude threads recover when their se… · yasinuslu/t3code@b7ebb25
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +59Lines changed: 59 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -46,6 +46,7 @@ import * as Stream from "effect/Stream"; | 46 | 46 | import { Tool } from "effect/unstable/ai"; | 47 | 47 | import { formatClaudeResumeCompactionQuestion } from "@t3tools/shared/claudeCompaction"; | 48 | 48 | import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; | | 49 | +import { PROMPT_NOT_RUN_FAILURE_CODE } from "@t3tools/shared/orchestrationV2ThreadError"; | 49 | 50 | import { SpawnExecutableResolution } from "@t3tools/shared/shell"; | 50 | 51 |
| 51 | 52 | import { attachmentRelativePath } from "../../attachmentStore.ts"; | @@ -4082,6 +4083,64 @@ describe("ClaudeAdapterV2 background wake turns", () => { | 4082 | 4083 | ), | 4083 | 4084 | ); | 4084 | 4085 |
| | 4086 | + it.effect("turns a lost Claude session into an unrun prompt that will not be resumed again", () => | | 4087 | + Effect.scoped( | | 4088 | + Effect.gen(function* () { | | 4089 | + const harness = yield* makeWakeHarness; | | 4090 | + const now = yield* DateTime.now; | | 4091 | + yield* harness.runtime.startTurn( | | 4092 | + makeClaudeTestTurnInput({ | | 4093 | + threadId: harness.threadId, | | 4094 | + providerThread: harness.providerThread, | | 4095 | + now, | | 4096 | + attemptId: RunAttemptId.make("attempt-claude-lost-session"), | | 4097 | + text: "Continue.", | | 4098 | + attachments: [], | | 4099 | + }), | | 4100 | + ); | | 4101 | + yield* Queue.offer( | | 4102 | + harness.sdkMessages, | | 4103 | + claudeSdkFrame({ | | 4104 | + type: "result", | | 4105 | + subtype: "error_during_execution", | | 4106 | + duration_ms: 0, | | 4107 | + duration_api_ms: 0, | | 4108 | + is_error: true, | | 4109 | + num_turns: 0, | | 4110 | + stop_reason: null, | | 4111 | + total_cost_usd: 0, | | 4112 | + usage: { | | 4113 | + input_tokens: 0, | | 4114 | + output_tokens: 0, | | 4115 | + cache_creation_input_tokens: 0, | | 4116 | + cache_read_input_tokens: 0, | | 4117 | + }, | | 4118 | + modelUsage: {}, | | 4119 | + permission_denials: [], | | 4120 | + errors: [`No conversation found with session ID: ${WAKE_NATIVE_SESSION}`], | | 4121 | + uuid: "00000000-0000-4000-8000-000000000301", | | 4122 | + session_id: WAKE_NATIVE_SESSION, | | 4123 | + }), | | 4124 | + ); | | 4125 | + yield* awaitUntil(() => harness.terminalEvents().length === 1, "lost-session terminal"); | | 4126 | + const terminal = harness.terminalEvents()[0]; | | 4127 | + assert.equal(terminal?.status, "failed"); | | 4128 | + assert.equal(terminal?.failure?.code, PROMPT_NOT_RUN_FAILURE_CODE); | | 4129 | + | | 4130 | + // The resend must start a fresh session instead of resuming this one. | | 4131 | + const resumed = yield* Effect.exit( | | 4132 | + harness.runtime.resumeThread({ | | 4133 | + providerThread: { ...harness.providerThread, lastRunOrdinal: 1 }, | | 4134 | + threadId: harness.threadId, | | 4135 | + modelSelection: CLAUDE_TEST_MODEL_SELECTION, | | 4136 | + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, | | 4137 | + }), | | 4138 | + ); | | 4139 | + assert.isTrue(Exit.isFailure(resumed)); | | 4140 | + }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))), | | 4141 | + ), | | 4142 | + ); | | 4143 | + | 4085 | 4144 | it.effect( | 4086 | 4145 | "clears the replaced sibling native thread roster when openQuery switches processes", | 4087 | 4146 | () => | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +103-6Lines changed: 103 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -133,6 +133,7 @@ import * as IdAllocator from "../IdAllocator.ts"; | 133 | 133 | import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts"; | 134 | 134 | import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts"; | 135 | 135 | import { providerMessageTextWithAttachmentPaths } from "../AttachmentPrompt.ts"; | | 136 | +import { ensureClaudeResumeTranscript } from "./ClaudeResumeTranscript.ts"; | 136 | 137 | import * as ProviderAdapter from "../ProviderAdapter.ts"; | 137 | 138 | import { | 138 | 139 | ProviderAdapterDriverCreateError, | @@ -2382,6 +2383,17 @@ function terminalResultError( | 2382 | 2383 | } | 2383 | 2384 | } | 2384 | 2385 |
| | 2386 | +/** The CLI could not load the session it was asked to resume, so it ran nothing. */ | | 2387 | +export function isClaudeSessionNotFoundResult(result: SDKResultMessage): boolean { | | 2388 | + return ( | | 2389 | + result.subtype !== "success" && | | 2390 | + result.num_turns === 0 && | | 2391 | + result.errors.some( | | 2392 | + (error) => typeof error === "string" && error.startsWith("No conversation found"), | | 2393 | + ) | | 2394 | + ); | | 2395 | +} | | 2396 | + | 2385 | 2397 | function isOverloadedResult(result: SDKResultMessage): boolean { | 2386 | 2398 | return result.subtype === "success" && result.api_error_status === 529; | 2387 | 2399 | } | @@ -3013,6 +3025,8 @@ export interface ClaudeAdapterV2Options { | 3013 | 3025 | readonly onUsageLimits?: ServerProviderShape["applyUsageLimits"]; | 3014 | 3026 | /** Resolves CLAUDE_CONFIG_DIR per project from code profiles or `homePathCommand`. */ | 3015 | 3027 | readonly configDirResolver?: ClaudeConfigDirResolver; | | 3028 | + /** Other Claude config dirs a session's transcript may have been written to. */ | | 3029 | + readonly transcriptSearchConfigDirs?: Effect.Effect<ReadonlyArray<string>>; | 3016 | 3030 | /** | 3017 | 3031 | * Receives the full command list whenever a session reloads it | 3018 | 3032 | * (`/reload-skills`, `/reload-plugins`, skills found mid-session), so the | @@ -3104,16 +3118,21 @@ export function makeClaudeAdapterV2( | 3104 | 3118 | // process, skill scan and sign-in hint of the session uses one dir. | 3105 | 3119 | const projectConfigDir = | 3106 | 3120 | adapterOptions.configDirResolver !== undefined && input.runtimePolicy.cwd !== null | 3107 | | - ? yield* adapterOptions.configDirResolver.resolveForWorkspace(input.runtimePolicy.cwd) | | 3121 | + ? yield* adapterOptions.configDirResolver.resolveForWorkspace( | | 3122 | + input.runtimePolicy.cwd, | | 3123 | + input.runtimePolicy.projectRoot, | | 3124 | + ) | 3108 | 3125 | : undefined; | 3109 | 3126 | const sessionEnvironment: NodeJS.ProcessEnv = | 3110 | 3127 | projectConfigDir === undefined | 3111 | 3128 | ? adapterOptions.environment | 3112 | 3129 | : { ...adapterOptions.environment, CLAUDE_CONFIG_DIR: projectConfigDir.path }; | | 3130 | + const sessionConfigDir = yield* resolveClaudeHomePath( | | 3131 | + { homePath: "" }, | | 3132 | + sessionEnvironment, | | 3133 | + ).pipe(Effect.provideService(Path.Path, path)); | 3113 | 3134 | const configuredConfigDir = describeClaudeConfigDir( | 3114 | | - yield* resolveClaudeHomePath({ homePath: "" }, sessionEnvironment).pipe( | 3115 | | - Effect.provideService(Path.Path, path), | 3116 | | - ), | | 3135 | + sessionConfigDir, | 3117 | 3136 | projectConfigDir?.profile, | 3118 | 3137 | ); | 3119 | 3138 | // Holds the latest session record: the CLI reports the dir it actually | @@ -3141,6 +3160,10 @@ export function makeClaudeAdapterV2( | 3141 | 3160 | // created, never resumed, even on a provider thread with earlier | 3142 | 3161 | // turns (a fresh native session after a failed resume). | 3143 | 3162 | const unpromptedNativeThreads = yield* Ref.make(new Set<string>()); | | 3163 | + // Sessions the CLI said it could not find ("No conversation found"). | | 3164 | + // Resuming them again fails the same way, so resumeThread refuses | | 3165 | + // them and T3 starts a fresh session instead. | | 3166 | + const lostNativeThreads = yield* Ref.make(new Set<string>()); | 3144 | 3167 | const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>()); | 3145 | 3168 | const planIdsByNativeItem = yield* Ref.make( | 3146 | 3169 | new Map<string, OrchestrationV2PlanArtifact["id"]>(), | @@ -6533,9 +6556,22 @@ export function makeClaudeAdapterV2( | 6533 | 6556 | resetTimes.length > 0 && resetTimes.every((time) => time !== null) | 6534 | 6557 | ? resetTimes.reduce((latest, time) => (time! > latest ? time! : latest), "") | 6535 | 6558 | : null; | | 6559 | + const sessionLost = !interrupted && isClaudeSessionNotFoundResult(message); | | 6560 | + if (sessionLost) { | | 6561 | + yield* Ref.update(lostNativeThreads, (current) => | | 6562 | + new Set(current).add(message.session_id), | | 6563 | + ); | | 6564 | + } | 6536 | 6565 | const resultFailure = interrupted | 6537 | 6566 | ? null | 6538 | | - : providerFailureFromResult(message, failureHint, usageLimited); | | 6567 | + : sessionLost | | 6568 | + ? // The prompt never ran; the resend starts a fresh session. | | 6569 | + makeProviderFailure({ | | 6570 | + message: resultUserFacingError(message), | | 6571 | + code: PROMPT_NOT_RUN_FAILURE_CODE, | | 6572 | + class: "provider_error", | | 6573 | + }) | | 6574 | + : providerFailureFromResult(message, failureHint, usageLimited); | 6539 | 6575 | const terminalFailure = | 6540 | 6576 | resultFailure?.class === "usage_limit" | 6541 | 6577 | ? { ...resultFailure, resetAt } | @@ -7348,6 +7384,58 @@ export function makeClaudeAdapterV2( | 7348 | 7384 | return context; | 7349 | 7385 | }); | 7350 | 7386 |
| | 7387 | + // Fails when the CLI could not resume this provider thread's session, | | 7388 | + // so T3 starts a fresh one seeded with the thread's history instead of | | 7389 | + // failing the turn with "No conversation found". A transcript written | | 7390 | + // under another cwd or config dir is copied to where the CLI looks. | | 7391 | + const assertResumableNativeThread = Effect.fnUntraced(function* ( | | 7392 | + providerThread: OrchestrationV2ProviderThread, | | 7393 | + ) { | | 7394 | + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; | | 7395 | + const cwd = input.runtimePolicy.cwd; | | 7396 | + if (nativeThreadId == null) return; | | 7397 | + const lost = (yield* Ref.get(lostNativeThreads)).has(nativeThreadId); | | 7398 | + if ( | | 7399 | + !lost && | | 7400 | + (cwd === null || | | 7401 | + providerThread.lastRunOrdinal === null || | | 7402 | + (yield* Ref.get(unpromptedNativeThreads)).has(nativeThreadId) || | | 7403 | + (yield* Ref.get(queryContext))?.nativeThreadId === nativeThreadId) | | 7404 | + ) { | | 7405 | + return; | | 7406 | + } | | 7407 | + const transcript = | | 7408 | + lost || cwd === null | | 7409 | + ? ({ _tag: "missing" } as const) | | 7410 | + : yield* ensureClaudeResumeTranscript({ | | 7411 | + configDir: sessionConfigDir, | | 7412 | + cwd, | | 7413 | + sessionId: nativeThreadId, | | 7414 | + ...(adapterOptions.transcriptSearchConfigDirs | | 7415 | + ? { searchConfigDirs: adapterOptions.transcriptSearchConfigDirs } | | 7416 | + : {}), | | 7417 | + }).pipe( | | 7418 | + Effect.provideService(FileSystem.FileSystem, fileSystem), | | 7419 | + Effect.provideService(Path.Path, path), | | 7420 | + ); | | 7421 | + if (transcript._tag === "copied") { | | 7422 | + yield* Effect.logInfo("Copied a Claude transcript so its session can resume", { | | 7423 | + nativeThreadId, | | 7424 | + from: transcript.from, | | 7425 | + configDir: sessionConfigDir, | | 7426 | + cwd, | | 7427 | + }); | | 7428 | + } | | 7429 | + if (transcript._tag === "missing") { | | 7430 | + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ | | 7431 | + driver: CLAUDE_PROVIDER, | | 7432 | + detail: lost | | 7433 | + ? `Claude could not find session ${nativeThreadId}.` | | 7434 | + : `Claude session ${nativeThreadId} has no transcript under ${sessionConfigDir}.`, | | 7435 | + }); | | 7436 | + } | | 7437 | + }); | | 7438 | + | 7351 | 7439 | const startTurn = Effect.fn("ClaudeAdapterV2.startTurn")( | 7352 | 7440 | function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) { | 7353 | 7441 | const startedAt = yield* DateTime.now; | @@ -7756,6 +7844,10 @@ export function makeClaudeAdapterV2( | 7756 | 7844 | } | 7757 | 7845 | return false; | 7758 | 7846 | }), | | 7847 | + needsResume: (providerThread) => | | 7848 | + Ref.get(lostNativeThreads).pipe( | | 7849 | + Effect.map((lost) => lost.has(providerThread.nativeThreadRef?.nativeId ?? "")), | | 7850 | + ), | 7759 | 7851 | hasPendingBackgroundWorkForThread: (providerThread) => | 7760 | 7852 | Effect.gen(function* () { | 7761 | 7853 | const nativeThreadId = providerThread.nativeThreadRef?.nativeId; | @@ -7801,6 +7893,7 @@ export function makeClaudeAdapterV2( | 7801 | 7893 | ), | 7802 | 7894 | resumeThread: Effect.fn("ClaudeAdapterV2.resumeThread")( | 7803 | 7895 | function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { | | 7896 | + yield* assertResumableNativeThread(threadInput.providerThread); | 7804 | 7897 | const updatedAt = yield* DateTime.now; | 7805 | 7898 | return { | 7806 | 7899 | ...threadInput.providerThread, | @@ -8048,7 +8141,11 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")( | 8048 | 8141 | input: ProviderAdapterDriverCreateInput<ClaudeSettings>, | 8049 | 8142 | hooks: Pick< | 8050 | 8143 | ClaudeAdapterV2Options, | 8051 | | - "scopedLimitNames" | "onUsageLimits" | "configDirResolver" | "onCommandsChanged" | | 8144 | + | "scopedLimitNames" | | 8145 | + | "onUsageLimits" | | 8146 | + | "configDirResolver" | | 8147 | + | "transcriptSearchConfigDirs" | | 8148 | + | "onCommandsChanged" | 8052 | 8149 | > = {}, | 8053 | 8150 | ) { | 8054 | 8151 | const { instanceId, environment, enabled, config } = input; | |
Collapse file Copy file name to clipboard +139Lines changed: 139 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import * as NodeServices from "@effect/platform-node/NodeServices"; | | 2 | +import { describe, expect, it } from "@effect/vitest"; | | 3 | +import * as Effect from "effect/Effect"; | | 4 | +import * as FileSystem from "effect/FileSystem"; | | 5 | +import * as Path from "effect/Path"; | | 6 | + | | 7 | +import { claudeProjectDirName, ensureClaudeResumeTranscript } from "./ClaudeResumeTranscript.ts"; | | 8 | + | | 9 | +const SESSION = "0c907d22-4291-42fa-8316-2d2a1ccdf5be"; | | 10 | + | | 11 | +const writeTranscript = Effect.fn(function* (configDir: string, cwd: string) { | | 12 | + const fs = yield* FileSystem.FileSystem; | | 13 | + const path = yield* Path.Path; | | 14 | + const dir = path.join(configDir, "projects", claudeProjectDirName(cwd)); | | 15 | + yield* fs.makeDirectory(path.join(dir, SESSION, "tool-results"), { recursive: true }); | | 16 | + yield* fs.writeFileString(path.join(dir, `${SESSION}.jsonl`), '{"type":"user"}\n'); | | 17 | + yield* fs.writeFileString(path.join(dir, SESSION, "tool-results", "a.txt"), "out"); | | 18 | +}); | | 19 | + | | 20 | +describe("ensureClaudeResumeTranscript", () => { | | 21 | + it("maps a cwd to Claude's project dir name", () => { | | 22 | + expect(claudeProjectDirName("/home/u/.t3/worktrees/t3code/feat-x")).toBe( | | 23 | + "-home-u--t3-worktrees-t3code-feat-x", | | 24 | + ); | | 25 | + }); | | 26 | + | | 27 | + it.effect("finds the transcript where the CLI looks", () => | | 28 | + Effect.gen(function* () { | | 29 | + const fs = yield* FileSystem.FileSystem; | | 30 | + const home = yield* fs.makeTempDirectoryScoped(); | | 31 | + yield* writeTranscript(home, "/work/repo"); | | 32 | + const status = yield* ensureClaudeResumeTranscript({ | | 33 | + configDir: home, | | 34 | + cwd: "/work/repo", | | 35 | + sessionId: SESSION, | | 36 | + }); | | 37 | + expect(status._tag).toBe("present"); | | 38 | + }).pipe(Effect.provide(NodeServices.layer)), | | 39 | + ); | | 40 | + | | 41 | + it.effect("copies the transcript after the thread moved to another cwd", () => | | 42 | + Effect.gen(function* () { | | 43 | + const fs = yield* FileSystem.FileSystem; | | 44 | + const path = yield* Path.Path; | | 45 | + const home = yield* fs.makeTempDirectoryScoped(); | | 46 | + yield* writeTranscript(home, "/work/worktrees/feat-x"); | | 47 | + const status = yield* ensureClaudeResumeTranscript({ | | 48 | + configDir: home, | | 49 | + cwd: "/work/repo", | | 50 | + sessionId: SESSION, | | 51 | + }); | | 52 | + expect(status._tag).toBe("copied"); | | 53 | + const target = path.join(home, "projects", claudeProjectDirName("/work/repo")); | | 54 | + expect(yield* fs.readFileString(path.join(target, `${SESSION}.jsonl`))).toBe( | | 55 | + '{"type":"user"}\n', | | 56 | + ); | | 57 | + expect(yield* fs.exists(path.join(target, SESSION, "tool-results", "a.txt"))).toBe(true); | | 58 | + }).pipe(Effect.provide(NodeServices.layer)), | | 59 | + ); | | 60 | + | | 61 | + it.effect("copies the transcript from the config dir that wrote it", () => | | 62 | + Effect.gen(function* () { | | 63 | + const fs = yield* FileSystem.FileSystem; | | 64 | + const path = yield* Path.Path; | | 65 | + const writer = yield* fs.makeTempDirectoryScoped(); | | 66 | + const other = yield* fs.makeTempDirectoryScoped(); | | 67 | + yield* writeTranscript(writer, "/work/repo"); | | 68 | + const status = yield* ensureClaudeResumeTranscript({ | | 69 | + configDir: other, | | 70 | + cwd: "/work/repo", | | 71 | + sessionId: SESSION, | | 72 | + searchConfigDirs: Effect.succeed([writer]), | | 73 | + }); | | 74 | + expect(status).toEqual({ | | 75 | + _tag: "copied", | | 76 | + from: path.join(writer, "projects", claudeProjectDirName("/work/repo"), `${SESSION}.jsonl`), | | 77 | + }); | | 78 | + }).pipe(Effect.provide(NodeServices.layer)), | | 79 | + ); | | 80 | + | | 81 | + it.effect("reports a transcript that is gone everywhere", () => | | 82 | + Effect.gen(function* () { | | 83 | + const fs = yield* FileSystem.FileSystem; | | 84 | + const home = yield* fs.makeTempDirectoryScoped(); | | 85 | + const status = yield* ensureClaudeResumeTranscript({ | | 86 | + configDir: home, | | 87 | + cwd: "/work/repo", | | 88 | + sessionId: SESSION, | | 89 | + searchConfigDirs: Effect.succeed(["/nonexistent/claude"]), | | 90 | + }); | | 91 | + expect(status._tag).toBe("missing"); | | 92 | + }).pipe(Effect.provide(NodeServices.layer)), | | 93 | + ); | | 94 | + it.effect("copies the most recently written transcript when several exist", () => | | 95 | + Effect.gen(function* () { | | 96 | + const fs = yield* FileSystem.FileSystem; | | 97 | + const path = yield* Path.Path; | | 98 | + const home = yield* fs.makeTempDirectoryScoped(); | | 99 | + yield* writeTranscript(home, "/work/old"); | | 100 | + yield* writeTranscript(home, "/work/new"); | | 101 | + const newer = path.join( | | 102 | + home, | | 103 | + "projects", | | 104 | + claudeProjectDirName("/work/new"), | | 105 | + `${SESSION}.jsonl`, | | 106 | + ); | | 107 | + yield* fs.writeFileString(newer, '{"type":"user"}\n{"type":"assistant"}\n'); | | 108 | + yield* fs.utimes( | | 109 | + path.join(home, "projects", claudeProjectDirName("/work/old"), `${SESSION}.jsonl`), | | 110 | + 1, | | 111 | + 1, | | 112 | + ); | | 113 | + const status = yield* ensureClaudeResumeTranscript({ | | 114 | + configDir: home, | | 115 | + cwd: "/work/repo", | | 116 | + sessionId: SESSION, | | 117 | + }); | | 118 | + expect(status).toEqual({ _tag: "copied", from: newer }); | | 119 | + }).pipe(Effect.provide(NodeServices.layer)), | | 120 | + ); | | 121 | + | | 122 | + it.effect("looks under the real path of a symlinked cwd, like the CLI", () => | | 123 | + Effect.gen(function* () { | | 124 | + const fs = yield* FileSystem.FileSystem; | | 125 | + const path = yield* Path.Path; | | 126 | + const home = yield* fs.makeTempDirectoryScoped(); | | 127 | + const real = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); | | 128 | + const link = path.join(home, "link"); | | 129 | + yield* fs.symlink(real, link); | | 130 | + yield* writeTranscript(home, real); | | 131 | + const status = yield* ensureClaudeResumeTranscript({ | | 132 | + configDir: home, | | 133 | + cwd: link, | | 134 | + sessionId: SESSION, | | 135 | + }); | | 136 | + expect(status._tag).toBe("present"); | | 137 | + }).pipe(Effect.provide(NodeServices.layer)), | | 138 | + ); | | 139 | +}); |
|