fix(server): recover provider sessions when resume history is missing #5433
Closedchrisdeeming(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromrefs/pull/5433/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 2666Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2547,0 +2585,21 @@2585+ ? { resumeCursor: context.session.resumeCursor }2586+ : {}),2587+ }).pipe(2588+ Effect.catchCause((cause) =>2589+ emitRuntimeError(context, errorMessage, { cause }).pipe(Effect.as(undefined)),2590+ ),2591+ );2592+ if (restarted === undefined) {2593+ return;2594+ }2595+ const next = sessions.get(restarted.threadId);2596+ if (next === undefined) {2597+ yield* emitRuntimeError(context, errorMessage);2598+ return;2599+ }2600+ next.resumePathRetried = true;2601+ next.lastPrompt = prompt;2602+ if (next.sessionRecovery !== "missing") {2603+ yield* emitRuntimeWarning(next, SESSION_DIRECTORY_MISSING_MESSAGE);2604+ }2605+ yield* Queue.offer(next.promptQueue, { type: "message", message: prompt });apps/server/src/provider/Drivers/ClaudeSessionRecovery.ts line 113Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +70,21 @@70+ claudeProjectDirectoryName(path.resolve(input.cwd)),71+ );72+ const targetTranscript = path.join(targetDirectory, `${input.sessionId}.jsonl`);73+74+ if (yield* fileSystem.exists(targetTranscript)) {75+ return "available";76+ }77+ if (!(yield* fileSystem.exists(projectsDirectory))) {78+ return "missing";79+ }80+81+ const orphanedTranscripts: string[] = [];82+ for (const entry of yield* fileSystem.readDirectory(projectsDirectory)) {83+ const transcriptPath = path.join(projectsDirectory, entry, `${input.sessionId}.jsonl`);84+ if (!(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false)))) {85+ continue;86+ }87+ const transcriptCwd = latestTranscriptCwd(yield* readTranscriptTail(transcriptPath));88+ if (!transcriptCwd || (yield* fileSystem.exists(transcriptCwd))) {89+ return "available";90+ }apps/server/src/provider/Layers/ClaudeAdapter.ts line 3322Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3170,4 +3242,17 @@31703242 const startedAt = yield* nowIso;31713243 const resumeState = readClaudeResumeState(input.resumeCursor);31723244 const threadId = input.threadId;3173- const existingResumeSessionId = resumeState?.resume;3245+ const requestedResumeSessionId = resumeState?.resume;3246+ const sessionRecovery =3247+ requestedResumeSessionId && input.cwd3248+ ? yield* recoverClaudeSession({3249+ environment: claudeEnvironment,3250+ cwd: input.cwd,3251+ sessionId: requestedResumeSessionId,3252+ }).pipe(3253+ Effect.provideService(FileSystem.FileSystem, fileSystem),3254+ Effect.provideService(Path.Path, path),3255+ Effect.catchCause((cause) =>3256+ Effect.logWarning("claude.session.recovery.failed", { threadId, cause }).pipe(3257+ Effect.as("available" as const),3258+ ),
- apps/server/src/provider/Drivers/ClaudeSessionRecovery.ts line 88OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +68,21 @@68+ const targetDirectory = path.join(69+ projectsDirectory,70+ claudeProjectDirectoryName(path.resolve(input.cwd)),71+ );72+ const targetTranscript = path.join(targetDirectory, `${input.sessionId}.jsonl`);73+74+ if (yield* fileSystem.exists(targetTranscript)) {75+ return "available";76+ }77+ if (!(yield* fileSystem.exists(projectsDirectory))) {78+ return "missing";79+ }80+81+ const orphanedTranscripts: string[] = [];82+ for (const entry of yield* fileSystem.readDirectory(projectsDirectory)) {83+ const transcriptPath = path.join(projectsDirectory, entry, `${input.sessionId}.jsonl`);84+ if (!(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false)))) {85+ continue;86+ }87+ const transcriptCwd = latestTranscriptCwd(yield* readTranscriptTail(transcriptPath));88+ if (transcriptCwd !== undefined && (yield* fileSystem.exists(transcriptCwd))) {
- apps/server/src/provider/Drivers/ClaudeSessionRecovery.ts line 102OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ if (yield* fileSystem.exists(targetTranscript)) {83+ return "available";84+ }85+ if (!(yield* fileSystem.exists(projectsDirectory))) {86+ return "missing";87+ }88+89+ const orphanedTranscripts: string[] = [];90+ for (const entry of yield* fileSystem.readDirectory(projectsDirectory)) {91+ const transcriptPath = path.join(projectsDirectory, entry, `${input.sessionId}.jsonl`);92+ if (!(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false)))) {93+ continue;94+ }95+ const transcriptCwd = latestTranscriptCwd(yield* readTranscriptTail(transcriptPath));96+ if (transcriptCwd !== undefined && (yield* isDirectory(transcriptCwd))) {97+ return "available";98+ }99+ orphanedTranscripts.push(transcriptPath);100+ }101+102+ const sourceTranscript = orphanedTranscripts[0];
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 2642Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2547,0 +2587,21 @@2587+ context.turnState = undefined;2588+ yield* stopSessionInternal(context, { emitExitEvent: false });2589+ sessions.delete(threadId);2590+2591+ const restarted = yield* startSession({2592+ ...context.startInput,2593+ ...(context.session.resumeCursor !== undefined2594+ ? { resumeCursor: context.session.resumeCursor }2595+ : {}),2596+ }).pipe(2597+ Effect.catchCause((cause) =>2598+ emitRuntimeError(context, errorMessage, { cause }).pipe(Effect.as(undefined)),2599+ ),2600+ );2601+ if (restarted === undefined) {2602+ return;2603+ }2604+ const next = sessions.get(restarted.threadId);2605+ if (next === undefined) {2606+ yield* emitRuntimeError(context, errorMessage);2607+ return;apps/server/src/provider/Layers/ClaudeAdapter.ts line 2692Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2556,3 +2650,13 @@25562650 const status = turnStatusFromResult(message);25572651 const errorMessage = message.subtype === "success" ? undefined : message.errors[0];255826522653+ if (2654+ status === "failed" &&2655+ errorMessage !== undefined &&2656+ isMissingResumePathError(errorMessage) &&2657+ !context.resumePathRetried &&2658+ context.lastPrompt !== undefined2659+ ) {2660+ context.resumePathRetried = true;2661+ yield* restartAfterMissingPath(context, errorMessage).pipe(Effect.forkDetach);2662+ return;apps/server/src/provider/Layers/ClaudeAdapter.ts line 2692Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -2556,3 +2650,13 @@25562650 const status = turnStatusFromResult(message);25572651 const errorMessage = message.subtype === "success" ? undefined : message.errors[0];255826522653+ if (2654+ status === "failed" &&2655+ errorMessage !== undefined &&2656+ isMissingResumePathError(errorMessage) &&2657+ !context.resumePathRetried &&2658+ context.lastPrompt !== undefined2659+ ) {2660+ context.resumePathRetried = true;2661+ yield* restartAfterMissingPath(context, errorMessage).pipe(Effect.forkDetach);2662+ return;
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 2642Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2547,0 +2585,21 @@2585+ }2586+2587+ yield* stopSessionInternal(context, { emitExitEvent: false });2588+2589+ const restarted = yield* startSession({2590+ ...context.startInput,2591+ ...(context.session.resumeCursor !== undefined2592+ ? { resumeCursor: context.session.resumeCursor }2593+ : {}),2594+ }).pipe(2595+ Effect.catchCause((cause) =>2596+ emitRuntimeError(context, errorMessage, { cause }).pipe(Effect.as(undefined)),2597+ ),2598+ );2599+ if (restarted === undefined) {2600+ return;2601+ }2602+ const next = sessions.get(restarted.threadId);2603+ if (next === undefined) {2604+ yield* emitRuntimeError(context, errorMessage);2605+ return;
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 2622Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2547 +2587,21 @@254725872588+ const restartAfterMissingPath = Effect.fn("restartAfterMissingPath")(function* (2589+ context: ClaudeSessionContext,2590+ errorMessage: string,2591+ replayTurnId: TurnId | undefined,2592+ ) {2593+ const abandonReplayedTurn = Effect.fn("abandonReplayedTurn")(function* (2594+ failure: Cause.Cause<unknown> | undefined,2595+ ) {2596+ yield* emitRuntimeError(2597+ context,2598+ errorMessage,2599+ failure !== undefined ? { cause: failure } : undefined,2600+ );2601+ if (replayTurnId !== undefined) {2602+ context.turnState = restartTurnState(replayTurnId, yield* nowIso);2603+ yield* completeTurn(context, "failed", errorMessage);2604+ }2605+ context.restarting = false;2606+ yield* stopSessionInternal(context, { emitExitEvent: true });2607+ });
- apps/server/src/provider/Drivers/ClaudeSessionRecovery.ts line 125Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +102,21 @@102+ for (const entry of yield* fileSystem.readDirectory(projectsDirectory)) {103+ const transcriptPath = path.join(projectsDirectory, entry, `${input.sessionId}.jsonl`);104+ if (!(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false)))) {105+ continue;106+ }107+ const transcriptCwd = latestTranscriptCwd(yield* readTranscriptTail(transcriptPath));108+ if (transcriptCwd !== undefined && (yield* isDirectory(transcriptCwd))) {109+ return "available";110+ }111+ orphanedTranscripts.push({112+ path: transcriptPath,113+ modifiedAtMillis: yield* modifiedAtMillis(transcriptPath),114+ });115+ }116+117+ const sourceTranscript = orphanedTranscripts.sort(118+ (left, right) => right.modifiedAtMillis - left.modifiedAtMillis,119+ )[0]?.path;120+ if (!sourceTranscript) {121+ return "missing";122+ }
- apps/server/src/provider/Drivers/ClaudeSessionRecovery.ts line 75Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +55,21 @@55+});56+57+const readTranscriptTail = Effect.fn("readTranscriptTail")(function* (transcriptPath: string) {58+ const fileSystem = yield* FileSystem.FileSystem;59+ const size = (yield* fileSystem.stat(transcriptPath)).size;60+ const bytesToRead = size < FileSystem.MiB(8) ? size : FileSystem.MiB(8);61+ return yield* fileSystem62+ .stream(transcriptPath, {63+ offset: size - bytesToRead,64+ bytesToRead,65+ })66+ .pipe(67+ Stream.decodeText(),68+ Stream.runFold(69+ () => "",70+ (content, chunk) => content + chunk,71+ ),72+ );73+});74+75+export const recoverClaudeSession = Effect.fn("recoverClaudeSession")(function* (input: {
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 2631OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2547,0 +2611,21 @@2611+ eventId: exitStamp.eventId,2612+ provider: PROVIDER,2613+ createdAt: exitStamp.createdAt,2614+ threadId: context.session.threadId,2615+ payload: {2616+ reason: errorMessage,2617+ exitKind: "error",2618+ },2619+ providerRefs: {},2620+ });2621+ });2622+2623+ const prompt = context.lastPrompt;2624+ if (prompt === undefined || replayTurnId === undefined) {2625+ yield* abandonReplayedTurn(undefined);2626+ return;2627+ }2628+2629+ yield* stopSessionInternal(context, { emitExitEvent: false });2630+2631+ const restarted = yield* startSession(context.startInput).pipe(
- apps/server/src/provider/acp/AcpSessionRuntime.ts line 657OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -629,13 +653,5 @@629653 );630654631655 return loaded;632- }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));633- } else {634- const createPayload = {635- cwd: options.cwd,636- mcpServers: options.mcpServers ?? [],637- } satisfies EffectAcpSchema.NewSessionRequest;638- const created = yield* runLoggedRequest(639- "session/new",640- createPayload,641- acp.agent.createSession(createPayload),656+ }).pipe(657+ Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())),
- apps/server/src/provider/Drivers/ClaudeSessionRecovery.ts line 117Resolvedby chrisdeeming(GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+107+ const orphanedTranscripts: Array<{ readonly path: string; readonly modifiedAtMillis: number }> =108+ [];109+ for (const entry of yield* fileSystem.readDirectory(projectsDirectory)) {110+ const transcriptPath = path.join(projectsDirectory, entry, `${input.sessionId}.jsonl`);111+ if (!(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false)))) {112+ continue;113+ }114+ const { cwd: transcriptCwd, decodedAnyEntry } = latestTranscriptCwd(115+ yield* readTranscriptTail(transcriptPath),116+ );117+ if (!decodedAnyEntry) {118+ continue;119+ }120+ if (transcriptCwd !== undefined && (yield* isDirectory(transcriptCwd))) {121+ return "available";122+ }123+ orphanedTranscripts.push({124+ path: transcriptPath,125+ modifiedAtMillis: yield* modifiedAtMillis(transcriptPath),126+ });
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
47c6a9f5-fb2c-41b7-ab5e-0faba206c469You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share