Skip to content

Commit 63e18df

Browse files
authored
fix(server): replace Claude sessions that never saved a message (pingdotgg#19637)
1 parent 92224dd commit 63e18df

2 files changed

Lines changed: 157 additions & 0 deletions

File tree

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

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1284,6 +1284,96 @@ describe("ClaudeAdapterV2 executable path", () => {
12841284
);
12851285
});
12861286

1287+
describe("ClaudeAdapterV2 resumeThread", () => {
1288+
it.effect("fails for a transcript without messages so a fresh session replaces it", () =>
1289+
Effect.scoped(
1290+
Effect.gen(function* () {
1291+
const fileSystem = yield* FileSystem.FileSystem;
1292+
const path = yield* Path.Path;
1293+
const configDir = yield* fileSystem.makeTempDirectoryScoped({
1294+
prefix: "t3-claude-empty-session-",
1295+
});
1296+
const projectDir = path.join(configDir, "projects", "-workspace");
1297+
yield* fileSystem.makeDirectory(projectDir, { recursive: true });
1298+
// What a CLI stopped before it saved the first prompt leaves behind.
1299+
yield* fileSystem.writeFileString(
1300+
path.join(projectDir, "native-thread-empty.jsonl"),
1301+
[
1302+
`{"type":"last-prompt","lastPrompt":"hello","sessionId":"native-thread-empty"}`,
1303+
`{"type":"atis-latch","atis":"","sessionId":"native-thread-empty"}`,
1304+
`{"type":"cost-state","sessionId":"native-thread-empty","totalCostUSD":0}`,
1305+
"",
1306+
].join("\n"),
1307+
);
1308+
yield* fileSystem.writeFileString(
1309+
path.join(projectDir, "native-thread-saved.jsonl"),
1310+
`{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"native-thread-saved"}\n`,
1311+
);
1312+
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1313+
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1314+
settings: DEFAULT_CLAUDE_SETTINGS,
1315+
environment: { CLAUDE_CONFIG_DIR: configDir },
1316+
attachmentsDir: configDir,
1317+
fileSystem,
1318+
path,
1319+
crypto: yield* Crypto.Crypto,
1320+
idAllocator: yield* IdAllocator.IdAllocatorV2,
1321+
queryRunner: {
1322+
allocateSessionId: Effect.succeed("native-thread-empty"),
1323+
open: () => Effect.die("unused"),
1324+
forkSession: () => Effect.die("unused"),
1325+
subagentLaunchToolUseId: () => Effect.succeed(null),
1326+
assertComplete: Effect.void,
1327+
},
1328+
});
1329+
const threadId = ThreadId.make("thread-claude-empty-session");
1330+
const runtime = yield* adapter.openSession({
1331+
threadId,
1332+
providerSessionId: ProviderSessionId.make("provider-session-claude-empty-session"),
1333+
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1334+
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1335+
});
1336+
const providerThread = yield* runtime.ensureThread({
1337+
threadId,
1338+
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1339+
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1340+
});
1341+
1342+
const error = yield* Effect.flip(runtime.resumeThread({ providerThread }));
1343+
assert.equal(error._tag, "ProviderAdapterResumeThreadError");
1344+
1345+
const saved = yield* runtime.resumeThread({
1346+
providerThread: {
1347+
...providerThread,
1348+
nativeThreadRef: {
1349+
driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1350+
nativeId: "native-thread-saved",
1351+
strength: "strong",
1352+
},
1353+
},
1354+
});
1355+
assert.equal(saved.nativeThreadRef?.nativeId, "native-thread-saved");
1356+
1357+
const missing = yield* runtime.resumeThread({
1358+
providerThread: {
1359+
...providerThread,
1360+
nativeThreadRef: {
1361+
driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1362+
nativeId: "native-thread-missing",
1363+
strength: "strong",
1364+
},
1365+
},
1366+
});
1367+
assert.equal(missing.nativeThreadRef?.nativeId, "native-thread-missing");
1368+
}),
1369+
).pipe(
1370+
Effect.provide(
1371+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
1372+
),
1373+
),
1374+
);
1375+
});
1376+
12871377
describe("ClaudeAdapterV2 resume compaction", () => {
12881378
it.effect("resolves and cancels the SDK resume dialog through structured runtime input", () =>
12891379
Effect.scoped(

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

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1434,6 +1434,16 @@ function makeProviderThread(input: {
14341434
};
14351435
}
14361436

1437+
const decodeClaudeTranscriptLine = Schema.decodeUnknownOption(
1438+
Schema.fromJsonString(Schema.Struct({ type: Schema.String })),
1439+
);
1440+
1441+
const isClaudeConversationLine = (line: string): boolean =>
1442+
Option.match(decodeClaudeTranscriptLine(line), {
1443+
onNone: () => false,
1444+
onSome: (entry) => entry.type === "user" || entry.type === "assistant",
1445+
});
1446+
14371447
const getNativeThreadId = Effect.fnUntraced(function* (
14381448
providerThread: OrchestrationV2ProviderThread,
14391449
) {
@@ -9113,6 +9123,47 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
91139123
});
91149124
yield* Effect.addFinalizer(() => closeSession());
91159125

9126+
// A CLI stopped before it saved the first prompt can leave a transcript
9127+
// with only metadata lines. Claude can neither resume that id nor
9128+
// create it again, so resumeThread fails and the caller binds a fresh
9129+
// native session with a context handoff.
9130+
const hasEmptyClaudeTranscript = Effect.fn("ClaudeAdapterV2.hasEmptyClaudeTranscript")(
9131+
function* (nativeThreadId: string) {
9132+
const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
9133+
const projectsDir = path.join(
9134+
configuredDir.length > 0
9135+
? path.resolve(session.cwd, configuredDir)
9136+
: path.join(yield* HostProcess.HomeDirectory, ".claude"),
9137+
"projects",
9138+
);
9139+
// Empty only when every copy of the id is empty; any message means
9140+
// the CLI may still resume it.
9141+
let found = false;
9142+
for (const project of yield* fileSystem.readDirectory(projectsDir)) {
9143+
const transcriptPath = path.join(projectsDir, project, `${nativeThreadId}.jsonl`);
9144+
// Stray files beside the project dirs fail with ENOTDIR.
9145+
if (
9146+
!(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false)))
9147+
) {
9148+
continue;
9149+
}
9150+
const conversationLine = yield* fileSystem
9151+
.stream(transcriptPath)
9152+
.pipe(
9153+
Stream.decodeText,
9154+
Stream.splitLines,
9155+
Stream.filter(isClaudeConversationLine),
9156+
Stream.runHead,
9157+
);
9158+
if (Option.isSome(conversationLine)) {
9159+
return false;
9160+
}
9161+
found = true;
9162+
}
9163+
return found;
9164+
},
9165+
);
9166+
91169167
const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
91179168
instanceId: adapterOptions.instanceId,
91189169
driver: CLAUDE_PROVIDER,
@@ -9188,6 +9239,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
91889239
),
91899240
resumeThread: Effect.fn("ClaudeAdapterV2.resumeThread")(
91909241
function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
9242+
const nativeThreadId = threadInput.providerThread.nativeThreadRef?.nativeId;
9243+
if (
9244+
nativeThreadId !== undefined &&
9245+
nativeThreadId !== null &&
9246+
// A live process holds the conversation even before saving it.
9247+
(yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId &&
9248+
// An unreadable transcript leaves the resume to the CLI, as before.
9249+
(yield* hasEmptyClaudeTranscript(nativeThreadId).pipe(
9250+
Effect.orElseSucceed(() => false),
9251+
))
9252+
) {
9253+
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9254+
driver: CLAUDE_PROVIDER,
9255+
detail: `Claude session ${nativeThreadId} has no conversation to resume.`,
9256+
});
9257+
}
91919258
const updatedAt = yield* DateTime.now;
91929259
return {
91939260
...threadInput.providerThread,

0 commit comments

Comments
 (0)