Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(hetero): resurrect GC-ed Claude Code sessions by rebuilding transcripts for --resume (#17437)

Arvin Xu79419f922de3
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index ef7ee18def4..0b5086da546 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -41,12 +41,14 @@ import {
buildAgentInput,
ClaudeAgentSdkSession,
createFileStoreImageUploader,
+ ensureClaudeCodeResumeTranscript,
readCodexSessionModel,
resolveCliSpawnPlan,
resolveCodexInitialModel,
} from '@lobechat/heterogeneous-agents/spawn';
import type {
HeterogeneousAgentModelCatalog,
+ HeteroSessionImportMessage,
ListHeterogeneousAgentModelsParams,
} from '@lobechat/types';
import { app as electronApp, BrowserWindow } from 'electron';
@@ -185,6 +187,14 @@ interface SendPromptParams {
*/
operationId: string;
prompt: string;
+ /**
+ * Prior conversation turns used to rebuild a Claude Code transcript that the
+ * CLI garbage-collected (`cleanupPeriodDays`, default 30 days). Only consumed
+ * when resuming and the on-disk transcript is missing β€” see
+ * `ensureClaudeCodeResumeTranscript`. Without it, `--resume <staleId>` fails
+ * with "No conversation found with session ID".
+ */
+ resumeReplayMessages?: HeteroSessionImportMessage[];
sessionId: string;
/** Extra context injected before the user prompt without mutating the prompt text. */
systemContext?: string;
@@ -1106,6 +1116,36 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
throw new Error(preflightError.message);
}
+ // Revive a Claude Code session whose local transcript the CLI already
+ // garbage-collected (`cleanupPeriodDays`, default 30 days). Rebuilding it
+ // from the turns LobeHub still holds turns a hard
+ // "No conversation found with session ID" into a normal `--resume` that
+ // hydrates the native history. No-ops when the transcript still exists.
+ // MUST run before the Claude SDK early return β€” both transports read the
+ // same on-disk transcript for resume.
+ if (
+ session.agentType === 'claude-code' &&
+ session.agentSessionId &&
+ session.cwd &&
+ params.resumeReplayMessages?.length
+ ) {
+ try {
+ const ensured = await ensureClaudeCodeResumeTranscript({
+ cwd: session.cwd,
+ messages: params.resumeReplayMessages,
+ sessionId: session.agentSessionId,
+ });
+ if (ensured.written)
+ logger.info('Rebuilt GC-ed Claude Code transcript for resume:', {
+ path: ensured.path,
+ turns: params.resumeReplayMessages.length,
+ });
+ } catch (error) {
+ // Never block the run on this β€” worst case CC starts a fresh session.
+ logger.warn('Failed to rebuild Claude Code resume transcript:', error);
+ }
+ }
+
if (
session.agentType === 'claude-code' &&
(session.useClaudeCodeSdk || this.isClaudeCodeSdkLabEnabled)
diff --git a/packages/heterogeneous-agents/src/spawn/ensureResumeTranscript.test.ts b/packages/heterogeneous-agents/src/spawn/ensureResumeTranscript.test.ts
new file mode 100644
index 00000000000..0f12c02d888
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/ensureResumeTranscript.test.ts
@@ -0,0 +1,143 @@
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import type { HeteroSessionImportMessage } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ ensureClaudeCodeResumeTranscript,
+ resolveClaudeCodeTranscriptPath,
+} from './ensureResumeTranscript';
+
+const SESSION_ID = '72f65fa9-0355-45d3-b903-8f41027ed5f2';
+
+const messages: HeteroSessionImportMessage[] = [
+ {
+ clientId: 'u1',
+ content: 'Remember the token MAGIC-4247.',
+ createdAt: '2026-07-01T00:00:00.000Z',
+ role: 'user',
+ },
+ { clientId: 'a1', content: 'stored', createdAt: '2026-07-01T00:00:01.000Z', role: 'assistant' },
+];
+
+let home: string;
+let cwd: string;
+
+beforeEach(async () => {
+ home = await mkdtemp(path.join(tmpdir(), 'cc-home-'));
+ cwd = await mkdtemp(path.join(tmpdir(), 'cc-cwd-'));
+});
+
+afterEach(async () => {
+ await rm(home, { force: true, recursive: true });
+ await rm(cwd, { force: true, recursive: true });
+});
+
+describe('resolveClaudeCodeTranscriptPath', () => {
+ it('builds <home>/.claude/projects/<encoded-realpath-cwd>/<id>.jsonl', async () => {
+ const p = await resolveClaudeCodeTranscriptPath({ cwd, home, sessionId: SESSION_ID });
+ expect(p).not.toBeNull();
+ // cwd is realpath-resolved (macOS tmp symlinks), so assert on the shape
+ expect(p!.startsWith(path.join(home, '.claude', 'projects'))).toBe(true);
+ expect(p!.endsWith(`${SESSION_ID}.jsonl`)).toBe(true);
+ // the dir segment is a dash-slug with no slashes/dots
+ const dir = path.basename(path.dirname(p!));
+ expect(dir).toMatch(/^[\dA-Z-]+$/i);
+ });
+});
+
+describe('ensureClaudeCodeResumeTranscript', () => {
+ it('writes a rebuilt transcript when the file is missing', async () => {
+ const res = await ensureClaudeCodeResumeTranscript({
+ cwd,
+ home,
+ messages,
+ sessionId: SESSION_ID,
+ });
+ expect(res.written).toBe(true);
+ expect(res.reason).toBe('written');
+ const content = await readFile(res.path!, 'utf8');
+ expect(content).toContain('MAGIC-4247');
+ expect(content).toContain(`"sessionId":"${SESSION_ID}"`);
+ // at least one line the CLI's existence gate accepts
+ expect(content).toMatch(/"type":"(user|assistant)"/);
+ });
+
+ it('never clobbers an existing (live) transcript', async () => {
+ const p = (await resolveClaudeCodeTranscriptPath({ cwd, home, sessionId: SESSION_ID }))!;
+ await mkdir(path.dirname(p), { recursive: true });
+ await writeFile(p, '{"type":"user","original":true}\n', 'utf8');
+
+ const res = await ensureClaudeCodeResumeTranscript({
+ cwd,
+ home,
+ messages,
+ sessionId: SESSION_ID,
+ });
+ expect(res.written).toBe(false);
+ expect(res.reason).toBe('exists');
+ expect(await readFile(p, 'utf8')).toContain('"original":true');
+ });
+
+ it('no-ops (does not write) when there are no messages', async () => {
+ const res = await ensureClaudeCodeResumeTranscript({
+ cwd,
+ home,
+ messages: [],
+ sessionId: SESSION_ID,
+ });
+ expect(res.written).toBe(false);
+ expect(res.reason).toBe('no-messages');
+ });
+});
+
+describe('session-id validation (path traversal)', () => {
+ // heteroSessionId is an unconstrained string on topic metadata, so on a shared
+ // topic a collaborator controls it β€” and it lands in a filesystem path.
+ const TRAVERSAL_IDS = [
+ '../../../../../../tmp/pwned',
+ '..',
+ '../72f65fa9-0355-45d3-b903-8f41027ed5f2',
+ 'a/b',
+ String.raw`..\..\windows`,
+ '',
+ 'not-a-uuid',
+ // a UUID with a traversal suffix must not slip through a loose match
+ '72f65fa9-0355-45d3-b903-8f41027ed5f2/../../escape',
+ ];
+
+ it.each(TRAVERSAL_IDS)('rejects %j instead of resolving a path', async (sessionId) => {
+ expect(await resolveClaudeCodeTranscriptPath({ cwd, home, sessionId })).toBeNull();
+ });
+
+ it('writes nothing to disk for a traversal id', async () => {
+ const escapeTarget = path.join(tmpdir(), `cc-escape-${process.pid}`);
+ await rm(escapeTarget, { force: true, recursive: true }).catch(() => {});
+
+ const res = await ensureClaudeCodeResumeTranscript({
+ cwd,
+ home,
+ messages,
+ // path.join would collapse this to <tmpdir>/cc-escape-<pid>.jsonl
+ sessionId: path.relative(path.join(home, '.claude', 'projects', 'x'), escapeTarget),
+ });
+
+ expect(res.written).toBe(false);
+ expect(res.reason).toBe('invalid-session-id');
+ expect(res.path).toBeNull();
+ await expect(stat(`${escapeTarget}.jsonl`)).rejects.toThrow();
+ });
+
+ it('still accepts a well-formed uppercase-hex UUID', async () => {
+ const p = await resolveClaudeCodeTranscriptPath({
+ cwd,
+ home,
+ sessionId: SESSION_ID.toUpperCase(),
+ });
+ expect(p).not.toBeNull();
+ const lower = await resolveClaudeCodeTranscriptPath({ cwd, home, sessionId: SESSION_ID });
+ expect(path.dirname(p!)).toBe(path.dirname(lower!));
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/ensureResumeTranscript.ts b/packages/heterogeneous-agents/src/spawn/ensureResumeTranscript.ts
new file mode 100644
index 00000000000..248afeb3cc4
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/ensureResumeTranscript.ts
@@ -0,0 +1,123 @@
+import { mkdir, realpath, stat, writeFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import type { HeteroSessionImportMessage } from '@lobechat/types';
+
+import {
+ buildClaudeCodeTranscript,
+ type BuildClaudeCodeTranscriptOptions,
+ encodeClaudeProjectDir,
+} from '../transcript/rebuildClaudeCode';
+
+/**
+ * The CLI's own session-id gate: a lowercase-hex UUID. Anything else resolves to
+ * `invalid-resume-id.jsonl` there and can never be resumed, so rejecting it
+ * early costs nothing.
+ *
+ * This is also a SECURITY boundary. `heteroSessionId` is stored on topic
+ * metadata as an unconstrained string (`chatTopicMetadataUpdateSchema`), so on a
+ * shared topic any collaborator who can patch metadata controls this value. It
+ * is interpolated into a filesystem path, and `path.join` happily collapses
+ * `..` segments β€” `../../../../tmp/x` escapes the projects directory entirely.
+ */
+const CLAUDE_SESSION_ID_RE = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
+
+export const isValidClaudeSessionId = (sessionId: string): boolean =>
+ CLAUDE_SESSION_ID_RE.test(sessionId);
+
+/**
+ * Resolve the on-disk transcript path the CC CLI reads for `--resume`:
+ * `<home>/.claude/projects/<encode(realpath(cwd))>/<sessionId>.jsonl`.
+ *
+ * `cwd` is realpath-resolved (symlinks + macOS `/tmp` β†’ `/private/tmp`) to
+ * match the directory the CLI itself computes; a missing/invalid cwd falls back
+ * to the literal path. The cwd segment is sanitized by `encodeClaudeProjectDir`
+ * (every non-alphanumeric char becomes `-`), so only `sessionId` can carry
+ * traversal β€” it is rejected unless it matches the CLI's UUID format.
+ *
+ * Returns `null` for a session id that could not be a real CC session.
+ */
+export const resolveClaudeCodeTranscriptPath = async (params: {
+ cwd: string;
+ home?: string;
+ sessionId: string;
+}): Promise<string | null> => {
+ const { cwd, sessionId } = params;
+ if (!isValidClaudeSessionId(sessionId)) return null;
+
+ const home = params.home ?? homedir();
+ let realCwd = cwd;
+ try {
+ realCwd = await realpath(cwd);
+ } catch {
+ // cwd may not exist yet β€” fall back to the literal path, same as the CLI
+ }
+ const projectDir = path.join(home, '.claude', 'projects', encodeClaudeProjectDir(realCwd));
+ const filePath = path.join(projectDir, `${sessionId}.jsonl`);
+
+ // Belt-and-braces: the regex already forbids separators, but assert the
+ // resolved destination really is a direct child of the project directory so a
+ // future change to either helper can't silently reopen the traversal.
+ if (path.dirname(path.resolve(filePath)) !== path.resolve(projectDir)) return null;
+
+ return filePath;
+};
+
+const fileExists = async (p: string): Promise<boolean> => {
+ try {
+ return (await stat(p)).isFile();
+ } catch {
+ return false;
+ }
+};
+
+export type EnsureResumeTranscriptReason =
+ 'exists' | 'invalid-session-id' | 'no-messages' | 'empty-transcript' | 'written';
+
+export interface EnsureResumeTranscriptResult {
+ /** Null when the session id was rejected β€” nothing was touched on disk. */
+ path: string | null;
+ reason: EnsureResumeTranscriptReason;
+ written: boolean;
+}
+
+/**
+ * Ensure a resumable transcript exists before spawning CC with `--resume`.
+ *
+ * When the local transcript was GC'd (CC's `cleanupPeriodDays`, default 30),
+ * rebuild it from the messages LobeHub still holds and write it to the path the
+ * CLI expects, so `--resume <sessionId>` hydrates the native history again
+ * instead of failing with "No conversation found with session ID".
+ *
+ * No-ops when the transcript already exists (never clobbers a live session), and
+ * refuses a session id that isn't the CLI's UUID format β€” that value comes from
+ * topic metadata a shared-topic collaborator can set, and it lands in a
+ * filesystem path.
+ */
+export const ensureClaudeCodeResumeTranscript = async (params: {
+ cwd: string;
+ home?: string;
+ messages: HeteroSessionImportMessage[];
+ sessionId: string;
+ transcriptOptions?: Partial<Omit<BuildClaudeCodeTranscriptOptions, 'cwd' | 'sessionId'>>;
+}): Promise<EnsureResumeTranscriptResult> => {
+ const { cwd, messages, sessionId } = params;
+ const filePath = await resolveClaudeCodeTranscriptPath({ cwd, home: params.home, sessionId });
+ if (!filePath) return { path: null, reason: 'invalid-session-id', written: false };
+
+ if (await fileExists(filePath)) return { path: filePath, reason: 'exists', written: false };
+ if (!messages || messages.length === 0)
+ return { path: filePath, reason: 'no-messages', written: false };
+
+ const transcript = buildClaudeCodeTranscript(messages, {
+ cwd,
+ sessionId,
+ ...params.transcriptOptions,
+ });
+ if (!transcript) return { path: filePath, reason: 'empty-transcript', written: false };
+
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, transcript, 'utf8');
+ return { path: filePath, reason: 'written', written: true };
+};
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index cb71c0a2547..93a15814047 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -71,6 +71,12 @@ export { JsonlStreamProcessor } from './jsonlProcessor';
// `resolveCliSpawnPlan`), so pulling it in would break unrelated suites at
// import time. Import it from the dedicated `@lobechat/heterogeneous-agents/
// resolveCliCommand` subpath instead.
+export {
+ ensureClaudeCodeResumeTranscript,
+ type EnsureResumeTranscriptReason,
+ type EnsureResumeTranscriptResult,
+ resolveClaudeCodeTranscriptPath,
+} from './ensureResumeTranscript';
export {
AMP_BASE_ARGS,
CLAUDE_CODE_BASE_ARGS,
diff --git a/packages/heterogeneous-agents/src/transcript/index.ts b/packages/heterogeneous-agents/src/transcript/index.ts
index 3480812fcf8..2047712f3ec 100644
--- a/packages/heterogeneous-agents/src/transcript/index.ts
+++ b/packages/heterogeneous-agents/src/transcript/index.ts
@@ -12,4 +12,6 @@ export {
parseCodexSession,
parseCodexSessionDigest,
} from './codex';
+export type { BuildClaudeCodeTranscriptOptions } from './rebuildClaudeCode';
+export { buildClaudeCodeTranscript, encodeClaudeProjectDir } from './rebuildClaudeCode';
export { parseJsonlRecords, stripNulDeep, truncateTitle } from './utils';
diff --git a/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts b/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts
new file mode 100644
index 00000000000..1713f9348dc
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.test.ts
@@ -0,0 +1,179 @@
+import type { HeteroSessionImportMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { parseClaudeCodeSession } from './claudeCode';
+import { buildClaudeCodeTranscript, encodeClaudeProjectDir } from './rebuildClaudeCode';
+
+const SESSION_ID = '72f65fa9-0355-45d3-b903-8f41027ed5f2';
+const CWD = '/Users/arvinxx/CodeProjects/LobeHub/lobehub-cloud-cc';
+
+const parseLines = (jsonl: string) =>
+ jsonl
+ .trim()
+ .split('\n')
+ .map((l) => JSON.parse(l));
+
+const userMsg = (content: string): HeteroSessionImportMessage => ({
+ clientId: `u-${content.slice(0, 6)}`,
+ content,
+ createdAt: '2026-07-01T00:00:00.000Z',
+ role: 'user',
+});
+
+const assistantMsg = (
+ content: string,
+ tools?: HeteroSessionImportMessage['tools'],
+): HeteroSessionImportMessage => ({
+ clientId: `a-${content.slice(0, 6)}`,
+ content,
+ createdAt: '2026-07-01T00:00:01.000Z',
+ role: 'assistant',
+ ...(tools ? { tools } : {}),
+});
+
+const toolMsg = (toolCallId: string, content: string): HeteroSessionImportMessage => ({
+ clientId: `t-${toolCallId}`,
+ content,
+ createdAt: '2026-07-01T00:00:02.000Z',
+ role: 'tool',
+ toolCallId,
+});
+
+describe('buildClaudeCodeTranscript', () => {
+ it('emits a parentUuid chain the CLI can hydrate (first user parentUuid=null)', () => {
+ const jsonl = buildClaudeCodeTranscript([userMsg('hi'), assistantMsg('hello')], {
+ cwd: CWD,
+ sessionId: SESSION_ID,
+ });
+ const recs = parseLines(jsonl);
+ expect(recs).toHaveLength(2);
+ expect(recs[0]).toMatchObject({ type: 'user', parentUuid: null, sessionId: SESSION_ID });
+ expect(recs[1]).toMatchObject({ type: 'assistant', parentUuid: recs[0].uuid });
+ // every record stamps the same session + cwd so the file is self-consistent
+ for (const r of recs) {
+ expect(r.sessionId).toBe(SESSION_ID);
+ expect(r.cwd).toBe(CWD);
+ expect(r.uuid).toMatch(/^[\da-f-]{36}$/);
+ }
+ });
+
+ it('round-trips through the parser back to the same normalized messages', () => {
+ const original: HeteroSessionImportMessage[] = [
+ userMsg('Check the deploy region.'),
+ assistantMsg('Reading config.', [
+ {
+ apiName: 'Read',
+ arguments: '{"file_path":"/repo/deploy.json"}',
+ id: 'toolu_1',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ]),
+ toolMsg('toolu_1', '{ "region": "ap-osaka-3" }'),
+ assistantMsg('The region is ap-osaka-3.'),
+ ];
+ const jsonl = buildClaudeCodeTranscript(original, { cwd: CWD, sessionId: SESSION_ID });
+ const parsed = parseClaudeCodeSession(jsonl);
+ expect(parsed).not.toBeNull();
+ const roles = parsed!.messages.map((m) => m.role);
+ expect(roles).toEqual(['user', 'assistant', 'tool', 'assistant']);
+ expect(parsed!.messages[0].content).toBe('Check the deploy region.');
+ expect(parsed!.messages[1].tools?.[0]).toMatchObject({ apiName: 'Read', id: 'toolu_1' });
+ expect(parsed!.messages[2].content).toBe('{ "region": "ap-osaka-3" }');
+ expect(parsed!.messages[2].toolCallId).toBe('toolu_1');
+ expect(parsed!.messages[3].content).toBe('The region is ap-osaka-3.');
+ expect(parsed!.sessionId).toBe(SESSION_ID);
+ expect(parsed!.workingDirectory).toBe(CWD);
+ });
+
+ it('drops thinking/reasoning β€” no signature to replay, would 400 the API', () => {
+ const msg: HeteroSessionImportMessage = {
+ ...assistantMsg('visible answer'),
+ reasoning: { content: 'secret chain of thought' },
+ };
+ const jsonl = buildClaudeCodeTranscript([userMsg('q'), msg], {
+ cwd: CWD,
+ sessionId: SESSION_ID,
+ });
+ expect(jsonl).not.toContain('thinking');
+ expect(jsonl).not.toContain('secret chain of thought');
+ const asst = parseLines(jsonl)[1];
+ expect(asst.message.content).toEqual([{ type: 'text', text: 'visible answer' }]);
+ });
+
+ it('trims a trailing unanswered tool_use (would 400 the next turn)', () => {
+ const jsonl = buildClaudeCodeTranscript(
+ [
+ userMsg('go'),
+ assistantMsg('running', [
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'toolu_dangling',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ]),
+ ],
+ { cwd: CWD, sessionId: SESSION_ID },
+ );
+ // the assistant tool_use has no matching tool_result β†’ trimmed away,
+ // leaving just the user turn (still a valid, resumable transcript)
+ const recs = parseLines(jsonl);
+ expect(recs).toHaveLength(1);
+ expect(recs[0].type).toBe('user');
+ expect(jsonl).not.toContain('toolu_dangling');
+ });
+
+ it('keeps a resolved tool_use but trims a later dangling one', () => {
+ const jsonl = buildClaudeCodeTranscript(
+ [
+ userMsg('go'),
+ assistantMsg('a', [
+ {
+ apiName: 'Read',
+ arguments: '{}',
+ id: 'toolu_ok',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ]),
+ toolMsg('toolu_ok', 'result'),
+ assistantMsg('b', [
+ {
+ apiName: 'Bash',
+ arguments: '{}',
+ id: 'toolu_bad',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ]),
+ ],
+ { cwd: CWD, sessionId: SESSION_ID },
+ );
+ expect(jsonl).toContain('toolu_ok');
+ expect(jsonl).not.toContain('toolu_bad');
+ const recs = parseLines(jsonl);
+ // user, assistant(tool_ok), tool_result β€” the dangling assistant is gone
+ expect(recs.map((r: any) => r.type)).toEqual(['user', 'assistant', 'user']);
+ });
+
+ it('returns empty string when there is nothing replay-worthy', () => {
+ expect(buildClaudeCodeTranscript([], { cwd: CWD, sessionId: SESSION_ID })).toBe('');
+ });
+});
+
+describe('encodeClaudeProjectDir', () => {
+ it('replaces every non-alphanumeric char with a dash (matches the CLI)', () => {
+ expect(encodeClaudeProjectDir('/Users/arvinxx/CodeProjects/LobeHub/lobehub-cloud-cc')).toBe(
+ '-Users-arvinxx-CodeProjects-LobeHub-lobehub-cloud-cc',
+ );
+ expect(encodeClaudeProjectDir('/private/tmp/cc-resurrect-lab')).toBe(
+ '-private-tmp-cc-resurrect-lab',
+ );
+ });
+
+ it('collapses dots and underscores to dashes too', () => {
+ expect(encodeClaudeProjectDir('/a/b.c_d')).toBe('-a-b-c-d');
+ });
+});
diff --git a/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.ts b/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.ts
new file mode 100644
index 00000000000..9ac8ed62c62
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/rebuildClaudeCode.ts
@@ -0,0 +1,214 @@
+import type { HeteroSessionImportMessage } from '@lobechat/types';
+
+/**
+ * Rebuild a Claude Code transcript JSONL from normalized messages β€” the inverse
+ * of {@link parseClaudeCodeSession} (transcript β†’ messages).
+ *
+ * Why this exists: the Claude Code CLI garbage-collects local transcripts
+ * (`~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl`) after `cleanupPeriodDays`
+ * (default 30). Once the file is gone, `--resume <sessionId>` fails with
+ * "No conversation found with session ID". Rebuilding the transcript from the
+ * messages LobeHub still holds lets `--resume` hydrate the full native history
+ * (text + tool cycles) again, and CC appends new turns in place under the same
+ * sessionId β€” so the stored `heteroSessionId` stays valid.
+ *
+ * Fidelity rules (verified against the bundled CLI + a live `--resume` round-trip):
+ * - Emit only replay-safe content: user text, assistant text + `tool_use`,
+ * and `tool_result` (as a `type:"user"` record).
+ * - DROP `thinking` blocks: their `signature` can't be reconstructed from the
+ * DB, and the Anthropic API rejects thinking blocks with invalid signatures
+ * when the history is replayed. Text + tool cycles rebuild a faithful,
+ * replayable conversation without them.
+ * - Every `tool_use` must be answered by a `tool_result`, and the transcript
+ * must NOT end on an unanswered `tool_use`, or the next-turn API call 400s.
+ * Trailing unanswered tool calls are trimmed.
+ */
+
+export interface BuildClaudeCodeTranscriptOptions {
+ /** cwd stamped into every record (the un-encoded real path). */
+ cwd: string;
+ /** git branch stamped into every record (optional, cosmetic). */
+ gitBranch?: string;
+ /** model stamped onto assistant records (cosmetic; defaults to a placeholder). */
+ model?: string;
+ /** the sessionId β€” MUST equal the transcript filename stem. */
+ sessionId: string;
+ /** CLI version string stamped into every record (cosmetic). */
+ version?: string;
+}
+
+const DEFAULT_VERSION = '2.1.215';
+const DEFAULT_MODEL = 'claude-opus-4-8';
+
+const uuid = (): string => globalThis.crypto.randomUUID();
+
+const safeParse = (s: string): any => {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return {};
+ }
+};
+
+/**
+ * A single reconstructed transcript record plus the tool-call ids it introduces
+ * (assistant) or answers (tool), so we can trim trailing unanswered tool calls.
+ */
+interface StagedRecord {
+ /** tool_use ids this assistant record opens (empty otherwise). */
+ opensToolIds: string[];
+ record: Record<string, any>;
+ /** tool_use id this record answers (tool records only). */
+ resolvesToolId?: string;
+ role: 'assistant' | 'tool' | 'user';
+}
+
+/**
+ * Build the transcript JSONL text (newline-joined, trailing newline) for the
+ * given messages. Returns an empty string when there's nothing replay-worthy.
+ */
+export const buildClaudeCodeTranscript = (
+ messages: HeteroSessionImportMessage[],
+ options: BuildClaudeCodeTranscriptOptions,
+): string => {
+ const { cwd, sessionId } = options;
+ const gitBranch = options.gitBranch ?? '';
+ const version = options.version ?? DEFAULT_VERSION;
+ const model = options.model ?? DEFAULT_MODEL;
+
+ const envelope = (extra: Record<string, any>): Record<string, any> => ({
+ isSidechain: false,
+ userType: 'external',
+ entrypoint: 'sdk-cli',
+ cwd,
+ sessionId,
+ version,
+ gitBranch,
+ ...extra,
+ });
+
+ const staged: StagedRecord[] = [];
+
+ for (const m of messages) {
+ const timestamp = m.createdAt ?? new Date().toISOString();
+
+ if (m.role === 'user') {
+ staged.push({
+ opensToolIds: [],
+ role: 'user',
+ record: envelope({
+ type: 'user',
+ message: { role: 'user', content: [{ type: 'text', text: m.content ?? '' }] },
+ timestamp,
+ }),
+ });
+ continue;
+ }
+
+ if (m.role === 'assistant') {
+ const content: any[] = [];
+ if (m.content && m.content.trim()) content.push({ type: 'text', text: m.content });
+ const opensToolIds: string[] = [];
+ for (const t of m.tools ?? []) {
+ content.push({
+ type: 'tool_use',
+ id: t.id,
+ name: t.apiName,
+ input: safeParse(t.arguments),
+ caller: { type: 'direct' },
+ });
+ opensToolIds.push(t.id);
+ }
+ // never emit an empty assistant turn β€” it carries no history and can
+ // confuse the deserializer; skip it entirely
+ if (content.length === 0) continue;
+ staged.push({
+ opensToolIds,
+ role: 'assistant',
+ record: envelope({
+ type: 'assistant',
+ requestId: `req_rebuilt_${staged.length}`,
+ message: {
+ model: m.model ?? model,
+ id: `msg_rebuilt_${staged.length}`,
+ type: 'message',
+ role: 'assistant',
+ content,
+ stop_reason: opensToolIds.length > 0 ? 'tool_use' : 'end_turn',
+ stop_sequence: null,
+ },
+ timestamp,
+ }),
+ });
+ continue;
+ }
+
+ // role: 'tool' β€” a tool_result carried on a user record
+ if (!m.toolCallId) continue;
+ staged.push({
+ opensToolIds: [],
+ resolvesToolId: m.toolCallId,
+ role: 'tool',
+ record: envelope({
+ type: 'user',
+ message: {
+ role: 'user',
+ content: [{ type: 'tool_result', tool_use_id: m.toolCallId, content: m.content ?? '' }],
+ },
+ timestamp,
+ toolUseResult: { rebuilt: true },
+ }),
+ });
+ }
+
+ // Trim trailing records until every opened tool_use is answered by a later
+ // tool_result. An unanswered trailing tool_use makes the next API turn 400.
+ const answered = new Set<string>();
+ for (const s of staged) if (s.resolvesToolId) answered.add(s.resolvesToolId);
+ while (staged.length > 0) {
+ const last = staged.at(-1)!;
+ const unanswered = last.opensToolIds.some((id) => !answered.has(id));
+ if (!unanswered) break;
+ staged.pop();
+ if (last.resolvesToolId) answered.delete(last.resolvesToolId);
+ }
+
+ if (staged.length === 0) return '';
+
+ // Stamp the parentUuid chain + uuids now that trimming is settled.
+ let parentUuid: string | null = null;
+ const lines: string[] = [];
+ for (const s of staged) {
+ const recUuid = uuid();
+ const rec: Record<string, any> = { ...s.record, uuid: recUuid, parentUuid };
+ if (s.role === 'tool') rec.sourceToolAssistantUUID = parentUuid;
+ lines.push(JSON.stringify(rec));
+ parentUuid = recUuid;
+ }
+
+ return lines.join('\n') + '\n';
+};
+
+const MAX_DIR_SLUG = 200;
+
+/**
+ * Encode an already-resolved (realpath'd) cwd into the `~/.claude/projects/`
+ * directory name, mirroring the CLI's own encoding:
+ * `realpath(cwd).replace(/[^a-zA-Z0-9]/g,'-')`, NFC-normalized, with a base-36
+ * hash suffix when the slug exceeds the CLI's max length.
+ *
+ * Pass an ALREADY realpath-resolved path β€” resolving symlinks needs fs and is
+ * the caller's job (see `ensureClaudeCodeResumeTranscript`).
+ */
+export const encodeClaudeProjectDir = (realCwd: string): string => {
+ const normalized = realCwd.normalize('NFC');
+ const slug = normalized.replaceAll(/[^a-z0-9]/gi, '-');
+ if (slug.length <= MAX_DIR_SLUG) return slug;
+ // djb2-ish hash matching the CLI's "truncate + base36 hash" shape; the exact
+ // hash doesn't need to match the CLI because callers only hit this branch for
+ // pathologically long cwds, which LobeHub doesn't produce.
+ let h = 0;
+ for (let i = 0; i < normalized.length; i += 1)
+ h = (Math.imul(31, h) + normalized.charCodeAt(i)) | 0;
+ return `${slug.slice(0, MAX_DIR_SLUG)}-${Math.abs(h).toString(36)}`;
+};
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index fd4ed21097a..a31ef793a49 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -5,6 +5,7 @@ import type {
} from '@lobechat/electron-client-ipc';
import type {
HeterogeneousAgentModelCatalog,
+ HeteroSessionImportMessage,
ListHeterogeneousAgentModelsParams,
} from '@lobechat/types';
@@ -35,6 +36,8 @@ class HeterogeneousAgentService {
imageList?: Array<{ id: string; url: string }>;
operationId: string;
prompt: string;
+ /** Prior turns used to rebuild a GC-ed Claude Code transcript before `--resume`. */
+ resumeReplayMessages?: HeteroSessionImportMessage[];
sessionId: string;
systemContext?: string;
topicId?: string;
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 9793869999e..2b9076d4318 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -99,6 +99,15 @@ export class TopicService {
return lambdaClient.topic.getMaxTaskDuration.query();
};
+ /**
+ * Fetch a single topic row by id, bypassing the paginated list store.
+ * Used when a deep-linked topic is not on the loaded page but its metadata
+ * (workingDirectory / heteroSessionId bindings) must drive a run.
+ */
+ getTopicDetail = async (id: string): Promise<ChatTopic | null> => {
+ return lambdaClient.topic.getTopicDetail.query({ id }) as Promise<ChatTopic | null>;
+ };
+
getRecentTopics = async (limit?: number): Promise<RecentTopic[]> => {
return lambdaClient.topic.recentTopics.query({ limit });
};
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index ea9a0557ee3..edffd3c603c 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -43,6 +43,7 @@ import { chatService } from '@/services/chat';
import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';
import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';
import { messageService } from '@/services/message';
+import { topicService } from '@/services/topic';
import { getAgentStoreState, useAgentStore } from '@/store/agent';
import {
agentByIdSelectors,
@@ -99,6 +100,8 @@ import {
parseSingleAgentMentionDirectRoute,
processCommands,
} from './commandBus';
+import { resolveExistingTopicForRun } from './resolveExistingTopic';
+
/**
* Extended params for sendMessage with context
*/
@@ -594,9 +597,19 @@ export class ConversationLifecycleActionImpl {
this.#get().associateMessageWithOperation(tempId, operationId);
this.#get().associateMessageWithOperation(tempAssistantId, operationId);
- const existingTopic = operationContext.topicId
- ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
- : undefined;
+ // The topic list store is paginated β€” a deep-linked older topic can be the
+ // ACTIVE topic yet miss `getTopicById`. For hetero runs that miss used to
+ // silently resolve the agent/device default cwd instead of the topic's
+ // bound workingDirectory and drop `--resume` (fresh CLI session, context
+ // lost, no error) β€” fall back to the server row.
+ const existingTopic = await resolveExistingTopicForRun({
+ fetchTopicDetail: (id) => topicService.getTopicDetail(id),
+ isHetero: !!heterogeneousProvider,
+ storeTopic: operationContext.topicId
+ ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
+ : undefined,
+ topicId: operationContext.topicId,
+ });
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
// Resolve the cwd for every hetero-provider run that lands on a MACHINE
// (in-process `hetero` runtime, or a gateway dispatch whose effective
@@ -981,9 +994,14 @@ export class ConversationLifecycleActionImpl {
// resume. `resolveHeteroResume` drops the sessionId when the saved cwd
// doesn't match the current one, so CC doesn't emit
// "No conversation found with session ID".
- const topic = heteroContext.topicId
- ? topicSelectors.getTopicById(heteroContext.topicId)(this.#get())
- : undefined;
+ // Store lookup first (freshest optimistic edits), but fall back to the
+ // server row resolved above β€” the paginated store misses deep-linked
+ // older topics, and a miss here silently dropped `--resume` even when
+ // the cwd resolution already used the topic's bound workingDirectory.
+ const topic =
+ (heteroContext.topicId
+ ? topicSelectors.getTopicById(heteroContext.topicId)(this.#get())
+ : undefined) ?? existingTopic;
const { cwdChanged, resumeSessionId } = resolveHeteroResume(
topic?.metadata,
workingDirectory,
diff --git a/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.test.ts b/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.test.ts
new file mode 100644
index 00000000000..20be75793f5
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ChatTopic } from '@/types/topic';
+
+import { resolveExistingTopicForRun } from './resolveExistingTopic';
+
+const topic = (over?: Partial<ChatTopic>): ChatTopic =>
+ ({
+ createdAt: 0,
+ favorite: false,
+ id: 'tpc_x',
+ metadata: { workingDirectory: '/repo/bound-dir' },
+ title: 't',
+ updatedAt: 0,
+ ...over,
+ }) as ChatTopic;
+
+describe('resolveExistingTopicForRun', () => {
+ it('returns the store row without fetching when present', async () => {
+ const fetchTopicDetail = vi.fn();
+ const storeTopic = topic();
+ const out = await resolveExistingTopicForRun({
+ fetchTopicDetail,
+ isHetero: true,
+ storeTopic,
+ topicId: 'tpc_x',
+ });
+ expect(out).toBe(storeTopic);
+ expect(fetchTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the server row when the paginated store misses a hetero topic', async () => {
+ // the exact production failure: deep-linked old topic beyond the loaded
+ // page β†’ store miss β†’ cwd/resume metadata must come from the server row
+ const serverTopic = topic({ id: 'tpc_deep' });
+ const fetchTopicDetail = vi.fn().mockResolvedValue(serverTopic);
+ const out = await resolveExistingTopicForRun({
+ fetchTopicDetail,
+ isHetero: true,
+ storeTopic: undefined,
+ topicId: 'tpc_deep',
+ });
+ expect(out).toBe(serverTopic);
+ expect(fetchTopicDetail).toHaveBeenCalledWith('tpc_deep');
+ expect(out?.metadata?.workingDirectory).toBe('/repo/bound-dir');
+ });
+
+ it('skips the round-trip for non-hetero runs', async () => {
+ const fetchTopicDetail = vi.fn();
+ const out = await resolveExistingTopicForRun({
+ fetchTopicDetail,
+ isHetero: false,
+ storeTopic: undefined,
+ topicId: 'tpc_x',
+ });
+ expect(out).toBeUndefined();
+ expect(fetchTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('skips when there is no topicId (new-topic send)', async () => {
+ const fetchTopicDetail = vi.fn();
+ const out = await resolveExistingTopicForRun({
+ fetchTopicDetail,
+ isHetero: true,
+ storeTopic: undefined,
+ topicId: undefined,
+ });
+ expect(out).toBeUndefined();
+ expect(fetchTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('degrades to undefined (old behavior) when the fetch fails', async () => {
+ const fetchTopicDetail = vi.fn().mockRejectedValue(new Error('network down'));
+ const out = await resolveExistingTopicForRun({
+ fetchTopicDetail,
+ isHetero: true,
+ storeTopic: undefined,
+ topicId: 'tpc_x',
+ });
+ expect(out).toBeUndefined();
+ });
+
+ it('maps a server null (topic deleted) to undefined', async () => {
+ const fetchTopicDetail = vi.fn().mockResolvedValue(null);
+ const out = await resolveExistingTopicForRun({
+ fetchTopicDetail,
+ isHetero: true,
+ storeTopic: undefined,
+ topicId: 'tpc_gone',
+ });
+ expect(out).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts b/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts
new file mode 100644
index 00000000000..be5e869a521
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts
@@ -0,0 +1,34 @@
+import type { ChatTopic } from '@/types/topic';
+
+/**
+ * Resolve the topic row a run should read its metadata from.
+ *
+ * The topic list store is PAGINATED (`topicDataMap[key].items` holds only the
+ * loaded pages), so a deep-linked older topic misses `getTopicById` even while
+ * it is the ACTIVE topic. For heterogeneous CLI runs that miss used to cascade
+ * silently: the cwd resolution fell back to the agent/device default directory
+ * instead of the topic's bound `workingDirectory`, `resolveHeteroResume` then
+ * saw no metadata and dropped `--resume`, and every turn started a brand-new
+ * CLI session with no history β€” no error anywhere.
+ *
+ * Store row wins when present (it may carry fresher optimistic edits). On a
+ * miss for a hetero run, fall back to the server row. Fetch failures degrade
+ * to the old behavior rather than blocking the turn.
+ */
+export const resolveExistingTopicForRun = async (params: {
+ fetchTopicDetail: (id: string) => Promise<ChatTopic | null>;
+ /** Only hetero runs consume topic-bound cwd/session metadata β€” skip the round-trip otherwise. */
+ isHetero: boolean;
+ storeTopic: ChatTopic | undefined;
+ topicId: string | null | undefined;
+}): Promise<ChatTopic | undefined> => {
+ const { fetchTopicDetail, isHetero, storeTopic, topicId } = params;
+ if (storeTopic) return storeTopic;
+ if (!topicId || !isHetero) return undefined;
+ try {
+ return (await fetchTopicDetail(topicId)) ?? undefined;
+ } catch (error) {
+ console.error('[resolveExistingTopicForRun] Failed to fetch topic detail:', error);
+ return undefined;
+ }
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 098e06a241d..ac072374308 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -75,6 +75,7 @@ import type { RunScope } from '../../lifecycle/types';
import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';
import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';
import { createPendingCreateLedger } from './pendingCreateLedger';
+import { buildResumeReplayMessages } from './resumeReplay';
import { buildLobeHubSessionEnv } from './sessionEnv';
/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */
@@ -2328,12 +2329,26 @@ export const executeHeterogeneousAgent = async (
workingDirectory,
});
+ // When resuming, hand main the prior turns so it can rebuild a Claude Code
+ // transcript the CLI already garbage-collected (default 30 days) β€” without
+ // it, `--resume <staleId>` dies with "No conversation found with session ID".
+ // Raw rows first: the display map collapses history into virtual
+ // `assistantGroup` rows, which carry no replayable turn.
+ const resumeReplayMessages = resumeSessionId
+ ? buildResumeReplayMessages(
+ (get().dbMessagesMap?.[messageMapKey(context)] ??
+ get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined,
+ message,
+ )
+ : undefined;
+
// Send the prompt β€” blocks until process exits
await heterogeneousAgentService.sendPrompt({
agentId: context.agentId,
imageList,
operationId,
prompt: message,
+ ...(resumeReplayMessages?.length ? { resumeReplayMessages } : {}),
sessionId: agentSessionId,
systemContext: systemContext || undefined,
topicId: context.topicId ?? undefined,
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.ts
new file mode 100644
index 00000000000..606b209a10d
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.test.ts
@@ -0,0 +1,72 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildResumeReplayMessages } from './resumeReplay';
+
+const msg = (over: Partial<UIChatMessage>): UIChatMessage =>
+ ({ content: '', createdAt: 1_780_000_000_000, id: 'm', role: 'user', ...over }) as UIChatMessage;
+
+describe('buildResumeReplayMessages', () => {
+ it('maps user / assistant / tool turns into the transcript-rebuild shape', () => {
+ const out = buildResumeReplayMessages([
+ msg({ content: 'hi', id: 'u1', role: 'user' }),
+ msg({
+ content: 'reading',
+ id: 'a1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'Read',
+ arguments: '{"p":1}',
+ id: 'toolu_1',
+ identifier: 'claude-code',
+ type: 'default',
+ },
+ ],
+ } as Partial<UIChatMessage>),
+ msg({ content: 'file body', id: 't1', role: 'tool', tool_call_id: 'toolu_1' }),
+ ]);
+
+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant', 'tool']);
+ expect(out[1].tools?.[0]).toMatchObject({ apiName: 'Read', id: 'toolu_1' });
+ expect(out[2].toolCallId).toBe('toolu_1');
+ expect(out[0].createdAt).toBe(new Date(1_780_000_000_000).toISOString());
+ });
+
+ it('skips virtual/grouping roles that carry no replayable turn', () => {
+ const out = buildResumeReplayMessages([
+ msg({ content: 'real', id: 'u1', role: 'user' }),
+ msg({ content: 'grouped', id: 'g1', role: 'assistantGroup' as any }),
+ msg({ content: 'sys', id: 's1', role: 'system' as any }),
+ ]);
+ expect(out).toHaveLength(1);
+ expect(out[0].content).toBe('real');
+ });
+
+ it('drops a tool turn with no tool_call_id (nothing to answer)', () => {
+ const out = buildResumeReplayMessages([
+ msg({ content: 'q', id: 'u1', role: 'user' }),
+ msg({ content: 'orphan', id: 't1', role: 'tool' }),
+ ]);
+ expect(out.map((m) => m.role)).toEqual(['user']);
+ });
+
+ it('drops the in-flight prompt echo and the empty assistant placeholder', () => {
+ const out = buildResumeReplayMessages(
+ [
+ msg({ content: 'older turn', id: 'u1', role: 'user' }),
+ msg({ content: 'older reply', id: 'a1', role: 'assistant' }),
+ msg({ content: 'new question', id: 'u2', role: 'user' }),
+ msg({ content: '', id: 'a2', role: 'assistant' }),
+ ],
+ 'new question',
+ );
+ // only the PREVIOUS turns survive β€” the new prompt is sent separately
+ expect(out.map((m) => m.content)).toEqual(['older turn', 'older reply']);
+ });
+
+ it('returns an empty array for empty/undefined input', () => {
+ expect(buildResumeReplayMessages(undefined)).toEqual([]);
+ expect(buildResumeReplayMessages([])).toEqual([]);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts
new file mode 100644
index 00000000000..2cae804721f
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts
@@ -0,0 +1,65 @@
+import type { HeteroSessionImportMessage, UIChatMessage } from '@lobechat/types';
+
+/**
+ * Map the topic's chat messages into the normalized shape
+ * `buildClaudeCodeTranscript` consumes, so a GC'd Claude Code session can be
+ * rebuilt on disk before `--resume`.
+ *
+ * Only real conversation roles survive β€” virtual/grouping roles
+ * (`assistantGroup`, `tasks`, `compressedGroup`, `system`, …) carry no
+ * replayable turn and would corrupt the rebuilt chain.
+ *
+ * `promptInFlight` is the prompt about to be sent this turn; it (and any empty
+ * placeholder trailing it) is dropped so the rebuilt history holds only
+ * PREVIOUS turns β€” the new prompt is delivered separately by the spawn.
+ */
+export const buildResumeReplayMessages = (
+ messages: UIChatMessage[] | undefined,
+ promptInFlight?: string,
+): HeteroSessionImportMessage[] => {
+ if (!messages || messages.length === 0) return [];
+
+ const mapped: HeteroSessionImportMessage[] = [];
+
+ for (const m of messages) {
+ const createdAt = m.createdAt ? new Date(m.createdAt).toISOString() : undefined;
+ const base = { clientId: m.id, content: m.content ?? '', ...(createdAt ? { createdAt } : {}) };
+
+ if (m.role === 'user') {
+ mapped.push({ ...base, role: 'user' });
+ continue;
+ }
+
+ if (m.role === 'assistant') {
+ const tools = (m.tools ?? []).map((t) => ({
+ apiName: t.apiName,
+ arguments: t.arguments,
+ id: t.id,
+ identifier: t.identifier,
+ // the transcript only replays the call itself; the render type is a UI
+ // concern and the import shape pins it to 'default' (same as the parser)
+ type: 'default' as const,
+ }));
+ mapped.push({ ...base, role: 'assistant', ...(tools.length > 0 ? { tools } : {}) });
+ continue;
+ }
+
+ if (m.role === 'tool' && m.tool_call_id) {
+ mapped.push({ ...base, role: 'tool', toolCallId: m.tool_call_id });
+ }
+ }
+
+ // Drop trailing in-flight turns: the empty assistant placeholder created for
+ // this run, and the user message carrying the prompt we're about to send.
+ while (mapped.length > 0) {
+ const last = mapped.at(-1)!;
+ const isEmptyAssistant =
+ last.role === 'assistant' && !last.content.trim() && (last.tools?.length ?? 0) === 0;
+ const isPromptEcho =
+ last.role === 'user' && !!promptInFlight && last.content.trim() === promptInFlight.trim();
+ if (!isEmptyAssistant && !isPromptEcho) break;
+ mapped.pop();
+ }
+
+ return mapped;
+};