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(desktop): resume local Claude Code runs after an app restart (#19775)

Arvin Xu878cc0bd52fc
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index 13bb54e2ec4..fd92cefd823 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -846,7 +846,7 @@ importers:
version: 5.0.0
vitest:
specifier: 5.0.0
stubs/business-const: {}
@@ -5267,9 +5267,6 @@ packages:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==}
-
resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}
@@ -9313,7 +9310,7 @@ snapshots:
dependencies:
package-manager-detector: 1.8.0
- tinyexec: 1.3.0
+ tinyexec: 1.3.1
'@anthropic-ai/[email protected]':
optional: true
@@ -13683,8 +13680,6 @@ snapshots:
-
@@ -18067,8 +18062,8 @@ snapshots:
dependencies:
cac: 7.0.0
- es-module-lexer: 2.3.0
- obug: 2.1.3
+ es-module-lexer: 2.3.2
+ obug: 2.2.1
pathe: 2.0.3
transitivePeerDependencies:
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index 48b6513f590..fab6916d80a 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -64,6 +64,21 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
return (await this.getImplementation()).getSessionInfo(...args);
}
+ @IpcMethod()
+ async listInterruptedRuns(...args: Parameters<Implementation['listInterruptedRuns']>) {
+ return (await this.getImplementation()).listInterruptedRuns(...args);
+ }
+
+ @IpcMethod()
+ async releaseInterruptedRun(...args: Parameters<Implementation['releaseInterruptedRun']>) {
+ return (await this.getImplementation()).releaseInterruptedRun(...args);
+ }
+
+ @IpcMethod()
+ async probeTranscriptReplay(...args: Parameters<Implementation['probeTranscriptReplay']>) {
+ return (await this.getImplementation()).probeTranscriptReplay(...args);
+ }
+
@IpcMethod()
async listModels(...args: Parameters<Implementation['listModels']>) {
return (await this.getImplementation()).listModels(...args);
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 8c659fe2807..b18619c747f 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -2,7 +2,7 @@ import type { ChildProcess } from 'node:child_process';
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { existsSync, unlinkSync } from 'node:fs';
-import { access, appendFile, mkdir, unlink, writeFile } from 'node:fs/promises';
+import { access, appendFile, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import type { Readable, Writable } from 'node:stream';
@@ -93,11 +93,16 @@ import {
isDroidAcpSessionNotFoundError,
normalizeImage,
readCodexSessionModel,
+ resolveClaudeCodeTranscriptPath,
resolveCliSpawnPlan,
resolveCodexInitialModel,
TraeAcpSession,
} from '@lobechat/heterogeneous-agents/spawn';
-import { truncateTitle } from '@lobechat/heterogeneous-agents/transcript';
+import {
+ buildClaudeCodeReplayTurn,
+ claudeCodeReplayTurnMatchesPrompt,
+ truncateTitle,
+} from '@lobechat/heterogeneous-agents/transcript';
import {
describeUnusableWorkingDirectory,
isSpawnableDirectory,
@@ -127,6 +132,10 @@ import {
createLambdaFileStorePort,
type RemoteServerAuth,
} from '@/modules/heterogeneousAgent/fileStorePort';
+import {
+ type HeteroInflightRun,
+ HeteroInflightRunRegistry,
+} from '@/modules/heterogeneousAgent/inflightRunRegistry';
import { fetchKimiCodeQuota } from '@/modules/heterogeneousAgent/kimiCodeQuota';
import { PiRpcPool } from '@/modules/heterogeneousAgent/piRpcPool';
import type { HostedProviderBinding } from '@/modules/heterogeneousAgent/providerBindingHost';
@@ -147,6 +156,15 @@ import type {
HeterogeneousAgentImageAttachment,
} from '@/modules/heterogeneousAgent/types';
import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
+import {
+ commandLineLooksLikeHeteroCli,
+ describeHeteroCliProcess,
+ isPidAlive,
+ isProcessAlive,
+ killProcessTreeByPid,
+ readProcessIdentity,
+ waitForProcessExit,
+} from '@/utils/heteroCliProcess';
import { createLogger } from '@/utils/logger';
import BrowserControlCtr from './BrowserControlCtr';
@@ -286,6 +304,23 @@ export interface StartSessionResult {
sessionId: string;
}
+/** Whether a transcript exists for a run and what its last turn looks like — see `probeTranscriptReplay`. */
+export interface HeteroTranscriptReplayProbe {
+ available: boolean;
+ /** Present when available: false means the turn was cut off. */
+ complete?: boolean;
+ reason?: string;
+}
+
+/** Result of a `replayTranscript` prompt — see `SendPromptParams.replayTranscript`. */
+export interface HeteroTranscriptReplayOutcome {
+ replay: {
+ /** False when the replayed turn was cut off and still needs a continuation. */
+ complete: boolean;
+ recordCount: number;
+ };
+}
+
/** Run identity the browser MCP tools need to reach the right in-app page. */
interface BrowserRunBinding {
agentId?: string;
@@ -299,6 +334,8 @@ interface SendPromptParams {
* they aren't watching.
*/
agentId?: string;
+ /** Assistant row this run streams into — recorded so recovery can scope to its branch. */
+ assistantMessageId?: string;
/** Image attachments to include in the prompt (downloaded from url, cached by id) */
imageList?: HeterogeneousAgentImageAttachment[];
/**
@@ -308,6 +345,28 @@ interface SendPromptParams {
*/
operationId: string;
prompt: string;
+ /**
+ * Do not spawn the CLI. Instead, read the last turn of the session's on-disk
+ * transcript (Claude Code only) and stream it through the same pipeline a
+ * live process feeds, so a turn that finished or died while the app was
+ * down lands in the topic exactly as it would have live. Resolves with the
+ * replay outcome so the caller knows whether a `--resume` continuation is
+ * still owed.
+ */
+ replayTranscript?: boolean;
+ /**
+ * Claude profile root the transcript was written under. Passed by restart
+ * recovery from its ledger: this turn's own account routing may resolve a
+ * different profile, but the file to read is the one the interrupted run
+ * actually produced.
+ */
+ replayTranscriptConfigDir?: string;
+ /**
+ * ISO spawn time of the interrupted run whose transcript is being replayed.
+ * Pins the replay to that run's own turn — see
+ * `claudeCodeReplayTurnMatchesPrompt`.
+ */
+ replayTranscriptStartedAt?: string;
/**
* Prior conversation turns used to rebuild a Claude Code transcript that the
* CLI garbage-collected (`cleanupPeriodDays`, default 30 days). Only consumed
@@ -327,6 +386,10 @@ interface SendPromptParams {
* a different namespace entirely.
*/
topicId?: string;
+ /** User the run belongs to; recovery only releases runs of the signed-in one. */
+ userId?: string;
+ /** Workspace the run belongs to; recovery only releases runs of the active one. */
+ workspaceId?: string;
}
interface CancelSessionParams {
@@ -532,6 +595,69 @@ export default class HeterogeneousAgentCtr {
private sessions = new Map<string, AgentSession>();
+ private inflightRunRegistry?: HeteroInflightRunRegistry;
+
+ /**
+ * Enter a started run in the recovery ledger. Every transport that can carry
+ * a Claude Code turn has to go through here, or a restart during that run
+ * leaves its topic stranded with no entry for `listInterruptedRuns`.
+ */
+ private recordInflightRun(args: {
+ command?: string;
+ configDir?: string;
+ cwd: string;
+ params: SendPromptParams;
+ pid?: number;
+ scriptPath?: string;
+ session: AgentSession;
+ /**
+ * ISO time the run began, taken BEFORE the CLI could exist. A replay is
+ * only accepted for a transcript turn recorded at or after this, so a
+ * timestamp taken once the child is already running (and, in stdin mode,
+ * already holding the prompt) could fall on the wrong side of the turn it
+ * is meant to admit.
+ */
+ startedAt?: string;
+ }): void {
+ const { command, configDir, cwd, params, pid, scriptPath, session, startedAt } = args;
+ this.getInflightRuns()?.upsert({
+ agentId: params.agentId,
+ agentSessionId: session.agentSessionId,
+ agentType: session.agentType,
+ assistantMessageId: params.assistantMessageId,
+ bindingKey: session.hostedProviderBinding?.bindingKey,
+ command,
+ configDir,
+ cwd,
+ ipcSessionId: session.sessionId,
+ operationId: params.operationId,
+ pid,
+ scriptPath,
+ startedAt: startedAt ?? new Date().toISOString(),
+ topicId: params.topicId,
+ userId: params.userId,
+ workspaceId: params.workspaceId,
+ });
+ }
+
+ /**
+ * Crash-safe ledger of the CLI runs this process has spawned and not seen
+ * exit. Read back by `listInterruptedRuns` after a restart. Lazy: the
+ * storage path is not available until the app store is ready, and a
+ * missing path must never break a run — the ledger is best-effort.
+ */
+ private getInflightRuns(): HeteroInflightRunRegistry | undefined {
+ if (this.inflightRunRegistry) return this.inflightRunRegistry;
+ try {
+ this.inflightRunRegistry = new HeteroInflightRunRegistry(
+ path.join(this.app.appStoragePath, 'heteroAgent', 'inflight-runs.json'),
+ );
+ } catch (error) {
+ logger.warn('Inflight-run registry unavailable:', error);
+ }
+ return this.inflightRunRegistry;
+ }
+
/**
* Runtime selection registry — the heterogeneous-agent counterpart of the
* adapter registry. Each entry decides whether it handles a prompt for its
@@ -1619,9 +1745,14 @@ export default class HeterogeneousAgentCtr {
* the shared `AgentStreamPipeline` (JSONL → adapter → toStreamEvent) and
* broadcasts the resulting `AgentStreamEvent`s on `heteroAgentEvent`.
*/
- async sendPrompt(params: SendPromptParams): Promise<ServerDefaultOperationSettlement | void> {
+ async sendPrompt(
+ params: SendPromptParams,
+ ): Promise<ServerDefaultOperationSettlement | HeteroTranscriptReplayOutcome | void> {
const session = this.sessions.get(params.sessionId);
if (session) session.cancelledByUs = false;
+ // A replay reads a file and calls no model, so it bypasses server-default
+ // operation accounting entirely.
+ if (params.replayTranscript) return this.replayTranscript(params);
const serverDefaultApiConfig = session?.serverDefaultApiConfig;
if (!session || !serverDefaultApiConfig) return this.sendPromptImpl(params);
if (!params.topicId) throw new Error('Server-default execution requires a topic');
@@ -1863,6 +1994,10 @@ export default class HeterogeneousAgentCtr {
try {
await new Promise<void>((resolve, reject) => {
+ // Stamped before the child exists: it is the floor a transcript replay
+ // is matched against, and the CLI may append this turn's prompt record
+ // the moment it starts.
+ const startedAt = new Date().toISOString();
const proc = spawn(resolvedCliSpawnPlan.command, resolvedCliSpawnPlan.args, spawnOptions);
this.handleSpawnedAgentProcess({
cwd,
@@ -1874,6 +2009,7 @@ export default class HeterogeneousAgentCtr {
session,
initialCumulativeUsage,
spawnEnv,
+ startedAt,
traceSession,
useStdin,
spawnPlan,
@@ -1924,6 +2060,9 @@ export default class HeterogeneousAgentCtr {
return;
}
+ // Same floor as the spawned-CLI path: taken before the transport (and the
+ // executable it launches) exists.
+ const startedAt = new Date().toISOString();
const sdkSession = new ClaudeAgentSdkSession({
args: session.args,
commandPath,
@@ -1937,12 +2076,24 @@ export default class HeterogeneousAgentCtr {
});
}
},
+ onProcessSpawn: ({ args, command, pid }) => {
+ // The SDK launches a real Claude executable, so this run has an orphan
+ // to reap after a hard crash exactly like a spawned CLI does. Patched
+ // rather than recorded up front: the ledger entry is written before
+ // `run()` even starts the transport.
+ this.getInflightRuns()?.patch(session.sessionId, {
+ ...describeHeteroCliProcess(command, args),
+ pid,
+ });
+ },
onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),
onRuntimeStatus: (status) => {
this.broadcast('heteroAgentRuntimeStatus', status);
},
onSessionId: (agentSessionId) => {
- if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
+ if (agentSessionId === session.agentSessionId) return;
+ session.agentSessionId = agentSessionId;
+ this.getInflightRuns()?.patch(session.sessionId, { agentSessionId });
},
onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),
operationId: params.operationId,
@@ -1953,6 +2104,17 @@ export default class HeterogeneousAgentCtr {
});
session.sdkSession = sdkSession;
+ // The SDK is a Claude Code transport like any other, so a restart mid-run
+ // has to find this turn on the ledger. The CLI child it spawns is entered
+ // through `onProcessSpawn` once it exists.
+ this.recordInflightRun({
+ command: path.basename(commandPath),
+ configDir: spawnEnv.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir,
+ cwd,
+ params,
+ session,
+ startedAt,
+ });
logger.info('Starting Claude Code SDK session:', {
commandPath,
@@ -2972,6 +3134,7 @@ export default class HeterogeneousAgentCtr {
session,
spawnEnv,
spawnPlan,
+ startedAt,
traceSession,
useStdin,
}: {
@@ -2985,6 +3148,8 @@ export default class HeterogeneousAgentCtr {
initialCumulativeUsage?: UsageData | undefined;
spawnEnv: NodeJS.ProcessEnv;
spawnPlan: HeterogeneousAgentBuildPlan;
+ /** ISO time taken before the spawn — see `recordInflightRun`. */
+ startedAt?: string;
traceSession: CliTraceSession | undefined;
useStdin: boolean;
}) {
@@ -3014,6 +3179,18 @@ export default class HeterogeneousAgentCtr {
}
session.process = proc;
+ this.recordInflightRun({
+ // The interpreter alone is not an identity — see describeHeteroCliProcess.
+ ...describeHeteroCliProcess(proc.spawnfile || session.command, proc.spawnargs),
+ // The EFFECTIVE profile: quota-account routing and agent env also set
+ // CLAUDE_CONFIG_DIR, and the transcript is written under whichever won.
+ configDir: spawnEnv.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir,
+ cwd,
+ params,
+ pid: proc.pid,
+ session,
+ startedAt,
+ });
// Producer-side conversion (V3 contract): JSONL framing + adapter +
// toStreamEvent all run inside the shared pipeline, so renderer + future
@@ -3049,6 +3226,9 @@ export default class HeterogeneousAgentCtr {
// IPC by mirroring the freshest value onto the session record.
if (pipeline.sessionId && pipeline.sessionId !== session.agentSessionId) {
session.agentSessionId = pipeline.sessionId;
+ this.getInflightRuns()?.patch(session.sessionId, {
+ agentSessionId: pipeline.sessionId,
+ });
}
events.push(
...(await this.verifyCodexSessionModel({
@@ -3143,6 +3323,12 @@ export default class HeterogeneousAgentCtr {
logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });
session.process = undefined;
+ // The ledger entry deliberately OUTLIVES the process. The CLI exiting
+ // says nothing about whether the renderer stored the turn — it may be
+ // reloading, or gone — and dropping the entry here would leave a
+ // reloading renderer with no recovery token at all. `stopSession`,
+ // which the executor calls once its terminal handling and persistence
+ // have settled, is the acknowledgement that releases it.
// If *we* killed it (cancel / stop / before-quit), treat the non-zero
// exit as a clean shutdown — surfacing it as an error would make a
@@ -3150,6 +3336,13 @@ export default class HeterogeneousAgentCtr {
// shutdown affecting OTHER running CC sessions would pollute their
// topics with a misleading "Agent exited with code 143" message.
if (session.cancelledByUs) {
+ // Quit-driven kill: say nothing to the renderer. A `complete`
+ // broadcast (or a settled `sendPrompt`) reaching a renderer that
+ // is still tearing down would let its executor mark the topic
+ // finished and drop the ledger entry — erasing exactly the state
+ // the next launch resumes from. The IPC promise is left pending;
+ // the process is exiting anyway.
+ if (this.shuttingDown) return;
this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
resolve();
return;
@@ -3175,6 +3368,291 @@ export default class HeterogeneousAgentCtr {
});
}
+ /**
+ * Runs this machine had in flight when the previous desktop process went
+ * away — only those belonging to the caller's user and workspace. Each is
+ * reaped first: a session that is still in memory (renderer reload, main
+ * survived) is stopped like a cancel, and a CLI left over from a crashed
+ * main (spawned detached, so it outlives its parent) is signalled after its
+ * command line is checked, so a recycled pid never gets an unrelated
+ * process killed. The caller replays the on-disk transcript, resumes from
+ * there, and calls {@link releaseInterruptedRun} when it is done.
+ *
+ * Entries are CLAIMED, not consumed: recovery spans several renderer steps
+ * and a crash in the middle would otherwise strand the topic with no token
+ * left to retry it. The claim count bounds the retries.
+ */
+ async listInterruptedRuns(params?: {
+ userId?: string;
+ workspaceId?: string;
+ }): Promise<HeteroInflightRun[]> {
+ const registry = this.getInflightRuns();
+ if (!registry) return [];
+ const recoverable: HeteroInflightRun[] = [];
+ for (const entry of registry.list()) {
+ // Topic lookups run through the caller's user and workspace scope, so a
+ // run recorded under either a different account (same Electron profile,
+ // someone signed in after) or a different workspace would resolve as a
+ // missing topic. Leave it for the launch that owns it — the workspace is
+ // undefined for personal space, which is why the user is compared too.
+ const sameOwner =
+ (entry.userId ?? undefined) === (params?.userId ?? undefined) &&
+ (entry.workspaceId ?? undefined) === (params?.workspaceId ?? undefined);
+ if (!sameOwner) continue;
+
+ const run = registry.claim(entry);
+ let safe = false;
+ try {
+ safe = await this.reapInterruptedRun(run);
+ } catch (error) {
+ logger.warn('Failed to reap interrupted run:', { error, ipcSessionId: run.ipcSessionId });
+ }
+
+ // An expired run is handed over for a status-only cleanup, but age only
+ // makes its transcript stale — it says nothing about the process. An
+ // orphan hung in a long-running tool is still reaped above; when even
+ // that cannot be confirmed, the topic is released anyway rather than
+ // left spinning, since the entry itself is already spent.
+ if (run.expired) {
+ if (!safe) {
+ logger.warn('Expired run may still be alive; settling its topic anyway:', {
+ ipcSessionId: run.ipcSessionId,
+ pid: run.pid,
+ });
+ }
+ recoverable.push(run);
+ continue;
+ }
+
+ // Safety could not be established (identity unreadable, the tree outlived
+ // SIGKILL, the reap threw). Withhold the run: replaying or resuming next
+ // to a live writer is worse than waiting — and put the entry back, since
+ // reaping an in-memory session goes through `stopSession`, which releases
+ // the claim as part of stopping it.
+ if (!safe) {
+ registry.upsert(run);
+ continue;
+ }
+ recoverable.push(run);
+ }
+ return recoverable;
+ }
+
+ /**
+ * Drop a claimed run from the ledger. The renderer owns this call: recovery
+ * is only over once the topic has been replayed, resumed or settled, and
+ * until then the entry has to survive another crash.
+ */
+ async releaseInterruptedRun(params: { ipcSessionId: string }): Promise<void> {
+ this.getInflightRuns()?.release(params.ipcSessionId);
+ }
+
+ /**
+ * Make sure nothing from the previous run is still writing before the
+ * renderer reads its transcript and resumes the session: a still-running
+ * orphan would keep flushing records under the replay's feet and then be a
+ * second writer on the same session id. Same TERM → wait → KILL ladder as
+ * `stopSession`.
+ *
+ * Returns false when a process matching this run is STILL alive afterwards.
+ * The caller then withholds the run: replaying or resuming next to a live
+ * writer is worse than leaving the topic for the stale-run watchdog.
+ */
+ private async reapInterruptedRun(run: HeteroInflightRun): Promise<boolean> {
+ if (this.sessions.has(run.ipcSessionId)) {
+ await this.stopSession({ sessionId: run.ipcSessionId });
+ if (!run.pid) return true;
+ if (await waitForProcessExit(run.pid, 5000)) return true;
+ logger.warn('Stopped session is still alive; withholding recovery:', { pid: run.pid });
+ return false;
+ }
+ // Unix liveness deliberately tests the whole process GROUP, so this stays
+ // true when the CLI leader has exited but one of its tool children is
+ // still running.
+ if (!run.pid || !isProcessAlive(run.pid)) return true;
+
+ const identity = await readProcessIdentity(run.pid);
+
+ if (identity.status === 'found') {
+ // A pid that no longer looks like our CLI was recycled, so the original
+ // process is gone and the run is safe to recover.
+ if (!commandLineLooksLikeHeteroCli(identity.commandLine, run)) {
+ logger.info('Skipping pid reuse for interrupted run:', {
+ commandLine: identity.commandLine,
+ pid: run.pid,
+ });
+ return true;
+ }
+ } else if (isPidAlive(run.pid)) {
+ // No command line while the pid itself is still there: the lookup failed
+ // operationally, so the identity is unknown and the leader may well be
+ // writing. Withhold rather than guess in either direction.
+ logger.warn('Could not read process identity; withholding recovery:', { pid: run.pid });
+ return false;
+ }
+
+ // Either the identity matched, or the leader is independently confirmed
+ // gone while its group lives on through a tool child. The group id is
+ // still ours — it is only released once empty — so reaping it cannot
+ // reach an unrelated tree.
+ logger.info('Reaping orphaned CLI from previous desktop process:', {
+ agentType: run.agentType,
+ leaderExited: identity.status !== 'found',
+ pid: run.pid,
+ });
+ killProcessTreeByPid(run.pid, 'SIGTERM');
+ if (await waitForProcessExit(run.pid, 3000)) return true;
+ killProcessTreeByPid(run.pid, 'SIGKILL');
+ if (await waitForProcessExit(run.pid, 2000)) return true;
+ logger.warn('Orphaned CLI survived SIGKILL; withholding recovery:', { pid: run.pid });
+ return false;
+ }
+
+ /**
+ * Read the replayable last turn of a Claude Code session's transcript.
+ * Shared by the probe (renderer decides whether recovery is possible before
+ * touching any rows) and the replay itself.
+ */
+ private async readClaudeCodeReplayTurn(params: {
+ configDir?: string;
+ cwd: string;
+ /** Prompt the interrupted run was given — see claudeCodeReplayTurnMatchesPrompt. */
+ expectedPrompt?: string;
+ /** ISO spawn time of the interrupted run; an older turn on disk is not it. */
+ notBefore?: string;
+ sessionId: string;
+ }): Promise<ReturnType<typeof buildClaudeCodeReplayTurn>> {
+ const filePath = await resolveClaudeCodeTranscriptPath(params);
+ if (!filePath) throw new Error(`Transcript replay rejected session id ${params.sessionId}`);
+
+ let content: string;
+ try {
+ content = await readFile(filePath, 'utf8');
+ } catch {
+ throw new Error(`No Claude Code transcript on disk for session ${params.sessionId}`);
+ }
+ const turn = buildClaudeCodeReplayTurn(content);
+ if (!turn) throw new Error(`Claude Code transcript ${params.sessionId} has no turn to replay`);
+
+ // A resumed session shares one transcript across turns, so a restart that
+ // lands before the CLI recorded the new prompt leaves the PREVIOUS turn as
+ // the last one. Replaying that under the new prompt would rewrite the
+ // conversation and report success. The spawn time settles it: the CLI
+ // cannot have written this run's prompt before the run existed.
+ if (!claudeCodeReplayTurnMatchesPrompt(turn, params.expectedPrompt, params.notBefore)) {
+ throw new Error(
+ `Claude Code transcript ${params.sessionId} last turn does not match the interrupted prompt`,
+ );
+ }
+ return turn;
+ }
+
+ /**
+ * Can this run's transcript be replayed? Answered without spawning
+ * anything, so restart recovery can keep the rows it already has when the
+ * answer is no.
+ */
+ async probeTranscriptReplay(params: {
+ agentType: string;
+ configDir?: string;
+ cwd?: string;
+ /** Prompt of the interrupted run; a transcript whose last turn is a different one is rejected. */
+ expectedPrompt?: string;
+ /** ISO spawn time of the interrupted run; a turn recorded before it is not this run's. */
+ notBefore?: string;
+ sessionId?: string;
+ }): Promise<HeteroTranscriptReplayProbe> {
+ if (params.agentType !== 'claude-code') {
+ return { available: false, reason: `unsupported agent type ${params.agentType}` };
+ }
+ if (!params.sessionId || !params.cwd) {
+ return { available: false, reason: 'missing session id or working directory' };
+ }
+ try {
+ const turn = await this.readClaudeCodeReplayTurn({
+ configDir: params.configDir,
+ cwd: params.cwd,
+ expectedPrompt: params.expectedPrompt,
+ notBefore: params.notBefore,
+ sessionId: params.sessionId,
+ });
+ return { available: true, complete: turn!.complete };
+ } catch (error) {
+ return { available: false, reason: error instanceof Error ? error.message : String(error) };
+ }
+ }
+
+ /**
+ * Stream the last turn of a Claude Code transcript as if the CLI were
+ * printing it live. Same pipeline as `handleSpawnedAgentProcess`, so the
+ * renderer's executor cannot tell the difference; a cut-off turn ends as
+ * interrupted (its dangling tool marked unsuccessful by the flush) instead
+ * of clean, so nothing downstream treats it as a finished run.
+ */
+ private async replayTranscript(params: SendPromptParams): Promise<HeteroTranscriptReplayOutcome> {
+ const session = this.sessions.get(params.sessionId);
+ if (!session) throw new Error(`Session not found: ${params.sessionId}`);
+ if (session.agentType !== 'claude-code') {
+ throw new Error(
+ `Transcript replay is only supported for Claude Code, got ${session.agentType}`,
+ );
+ }
+ if (!session.agentSessionId || !session.cwd) {
+ throw new Error('Transcript replay needs a resumable session id and a working directory');
+ }
+
+ const turn = (await this.readClaudeCodeReplayTurn({
+ configDir:
+ params.replayTranscriptConfigDir ??
+ session.env?.CLAUDE_CONFIG_DIR ??
+ session.hostedProviderBinding?.profileDir,
+ cwd: session.cwd,
+ // The prompt this run was given — re-checked here, not just at probe time.
+ expectedPrompt: params.prompt,
+ notBefore: params.replayTranscriptStartedAt,
+ sessionId: session.agentSessionId,
+ }))!;
+
+ const pipeline = new AgentStreamPipeline({
+ agentType: session.agentType,
+ cwd: session.cwd,
+ operationId: params.operationId,
+ uploadImage: this.uploadResultImage,
+ });
+ const emit = (events: AgentStreamEvent[]) => {
+ for (const event of events) {
+ this.broadcast('heteroAgentEvent', { event, sessionId: session.sessionId });
+ }
+ };
+
+ try {
+ for (const line of turn.lines) emit(await pipeline.push(`${line}\n`));
+ emit(await pipeline.flush());
+ if (turn.complete) {
+ emit(pipeline.validateCompletion());
+ } else {
+ emit(
+ pipeline.completeRuntime({
+ kind: 'aborted',
+ reason: 'interrupted',
+ subtype: 'app_restart',
+ }),
+ );
+ }
+ if (pipeline.sessionId) session.agentSessionId = pipeline.sessionId;
+ } finally {
+ await session.hostedProviderBinding?.cleanup();
+ }
+
+ logger.info('Replayed Claude Code transcript turn:', {
+ complete: turn.complete,
+ recordCount: turn.recordCount,
+ sessionId: session.sessionId,
+ });
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return { replay: { complete: turn.complete, recordCount: turn.recordCount } };
+ }
+
/**
* Get session info (agent's internal session ID for multi-turn resume).
*/
@@ -3499,6 +3977,12 @@ export default class HeterogeneousAgentCtr {
* Stop and clean up a session.
*/
async stopSession(params: StopSessionParams): Promise<void> {
+ // The renderer reaching its own cleanup IS the acknowledgement that the run
+ // was stored, so release the ledger entry before anything can return early.
+ // A stop racing app shutdown is the exception: that entry is what the next
+ // launch resumes from.
+ if (!this.shuttingDown) this.getInflightRuns()?.remove(params.sessionId);
+
const session = this.sessions.get(params.sessionId);
if (!session) return;
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 47fb8e01616..b249e427d10 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -1,6 +1,6 @@
import { EventEmitter } from 'node:events';
import { existsSync, statSync } from 'node:fs';
-import { access, mkdtemp, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';
+import { access, mkdir, mkdtemp, readdir, readFile, rm, unlink, writeFile } from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
import { PassThrough } from 'node:stream';
@@ -17,6 +17,7 @@ import { AcpRpcResponseError } from '@lobechat/heterogeneous-agents/spawn';
import { app as electronAppMock } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as heteroCliProcessModule from '../../utils/heteroCliProcess';
import HeterogeneousAgentCtr, { redactPromptArgs } from '../HeterogeneousAgentImpl';
/**
@@ -25,6 +26,34 @@ import HeterogeneousAgentCtr, { redactPromptArgs } from '../HeterogeneousAgentIm
*/
const cliGuideBlock = { text: lobeHubCliGuide, type: 'text' };
+/**
+ * Process-table access used by interrupted-run reaping. Real by default; a
+ * test that needs a specific liveness answer sets an override.
+ */
+const heteroProcessOverrides: {
+ isProcessAlive?: (pid: number) => boolean;
+ killProcessTreeByPid?: (pid: number, signal: NodeJS.Signals) => void;
+ readProcessIdentity?: (pid: number) => Promise<{ commandLine?: string; status: string }>;
+ waitForProcessExit?: (pid: number, timeoutMs: number) => Promise<boolean>;
+} = {};
+
+vi.mock('@/utils/heteroCliProcess', async (importOriginal) => {
+ const actual = await importOriginal<typeof heteroCliProcessModule>();
+ return {
+ ...actual,
+ isProcessAlive: (...args: Parameters<typeof actual.isProcessAlive>) =>
+ (heteroProcessOverrides.isProcessAlive ?? actual.isProcessAlive)(...args),
+ killProcessTreeByPid: (...args: Parameters<typeof actual.killProcessTreeByPid>) =>
+ (heteroProcessOverrides.killProcessTreeByPid ?? actual.killProcessTreeByPid)(...args),
+ readProcessIdentity: (...args: Parameters<typeof actual.readProcessIdentity>) =>
+ (heteroProcessOverrides.readProcessIdentity ?? actual.readProcessIdentity)(
+ ...(args as [number]),
+ ),
+ waitForProcessExit: (...args: Parameters<typeof actual.waitForProcessExit>) =>
+ (heteroProcessOverrides.waitForProcessExit ?? actual.waitForProcessExit)(...args),
+ };
+});
+
vi.mock('node:os', async () => {
const actual = await vi.importActual<typeof os>('node:os');
return { ...actual, platform: vi.fn(() => 'linux') };
@@ -136,6 +165,7 @@ vi.mock('@/utils/logger', () => ({
}));
const {
+ claudeSdkSessionAfterSpawnMock,
claudeSdkSessionCloseMock,
claudeSdkSessionConstructMock,
codexAppServerCanReuse,
@@ -175,6 +205,7 @@ const {
piRpcSessionRebindMock,
piRpcSessionRunMock,
} = vi.hoisted(() => ({
+ claudeSdkSessionAfterSpawnMock: vi.fn(async () => {}),
claudeSdkSessionCloseMock: vi.fn(),
claudeSdkSessionConstructMock: vi.fn(),
codexAppServerCanReuse: { value: true },
@@ -233,6 +264,13 @@ vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => {
async run() {
const now = Date.now();
+ // The real session hands the CLI child it spawns to its host here.
+ this.options.onProcessSpawn?.({
+ args: ['/usr/local/bin/claude', '-p', '--output-format', 'stream-json'],
+ command: '/usr/local/bin/claude',
+ pid: 99_001,
+ });
+ await claudeSdkSessionAfterSpawnMock();
this.options.onRuntimeStatus({
activeTasks: [
{
@@ -631,8 +669,10 @@ vi.mock('@/modules/heterogeneousAgent/kimiCodeQuota', () => ({
// Captures the most recent spawn() call so sendPrompt tests can assert on argv.
const spawnCalls: Array<{ args: string[]; command: string; options: any }> = [];
let nextFakeProc: any = null;
-const { execFileMock } = vi.hoisted(() => ({
+const { execFileMock, onSpawnMock } = vi.hoisted(() => ({
execFileMock: vi.fn(),
+ /** Runs inside the spawn mock, so a test can move the clock across a spawn. */
+ onSpawnMock: vi.fn(),
}));
vi.mock('node:child_process', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
@@ -642,6 +682,7 @@ vi.mock('node:child_process', async (importOriginal) => {
execFile: execFileMock,
spawn: (command: string, args: string[], options: any) => {
spawnCalls.push({ args, command, options });
+ onSpawnMock();
nextFakeProc?.__start?.();
return nextFakeProc;
},
@@ -712,6 +753,9 @@ describe('HeterogeneousAgentCtr', () => {
consumeCodexRateLimitResetCreditMock.mockReset();
fetchCodexQuotaMock.mockReset();
fetchKimiCodeQuotaMock.mockReset();
+ onSpawnMock.mockReset();
+ claudeSdkSessionAfterSpawnMock.mockReset();
+ claudeSdkSessionAfterSpawnMock.mockImplementation(async () => {});
claudeSdkSessionCloseMock.mockReset();
claudeSdkSessionConstructMock.mockReset();
codexAppServerCanReuse.value = true;
@@ -1475,6 +1519,83 @@ describe('HeterogeneousAgentCtr', () => {
expect(send).toHaveBeenCalledWith('heteroAgentSessionComplete', { sessionId });
});
+ it('stamps the replay floor before the CLI can record its prompt', async () => {
+ // `startedAt` is the floor a transcript replay is matched against. Taken
+ // after the spawn, the CLI could append this turn's prompt record first
+ // and recovery would then reject its own turn.
+ const start = new Date('2026-09-22T10:00:00.000Z');
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ vi.setSystemTime(start);
+ onSpawnMock.mockImplementation(() => {
+ vi.setSystemTime(new Date(start.getTime() + 5000));
+ });
+ nextFakeProc = createFakeProc().proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'claude-code',
+ command: 'claude',
+ });
+
+ await ctr.sendPrompt({
+ operationId: 'op-floor',
+ prompt: 'do the thing',
+ sessionId,
+ topicId: 'topic-floor',
+ });
+
+ const ledger = JSON.parse(
+ await readFile(path.join(appStoragePath, 'heteroAgent', 'inflight-runs.json'), 'utf8'),
+ ).runs;
+ expect(ledger).toHaveLength(1);
+ // The spawn jumped the clock 5s; a floor taken after it would land there.
+ expect(Date.parse(ledger[0].startedAt)).toBeLessThan(start.getTime() + 5000);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('records the SDK-spawned CLI child on the recovery ledger', async () => {
+ // The SDK launches a real Claude executable: a hard crash leaves an
+ // orphan that keeps writing the transcript a replay would read, and a
+ // PID-less ledger entry looks safe to recover next to it.
+ process.env.LOBE_CLAUDE_CODE_SDK = '1';
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const { sessionId } = await ctr.startSession({
+ agentType: 'claude-code',
+ command: 'claude',
+ });
+
+ let ledgerDuringRun: any[] = [];
+ claudeSdkSessionAfterSpawnMock.mockImplementation(async () => {
+ ledgerDuringRun = JSON.parse(
+ await readFile(path.join(appStoragePath, 'heteroAgent', 'inflight-runs.json'), 'utf8'),
+ ).runs;
+ });
+
+ await ctr.sendPrompt({
+ operationId: 'op-sdk-ledger',
+ prompt: 'watch ci',
+ sessionId,
+ topicId: 'topic-sdk',
+ });
+
+ expect(ledgerDuringRun).toEqual([
+ expect.objectContaining({
+ agentType: 'claude-code',
+ command: 'claude',
+ pid: 99_001,
+ topicId: 'topic-sdk',
+ }),
+ ]);
+ });
+
it('does not start the Claude SDK when server-default execution is cancelled during preparation', async () => {
process.env.LOBE_CLAUDE_CODE_SDK = '1';
const ctr = new HeterogeneousAgentCtr({
@@ -5442,4 +5563,123 @@ describe('HeterogeneousAgentCtr', () => {
expect(() => beforeQuit({ preventDefault: vi.fn() })).not.toThrow();
});
});
+
+ describe('listInterruptedRuns', () => {
+ const DEAD_PID = 2_147_483_000;
+
+ const ledgerPath = () => path.join(appStoragePath, 'heteroAgent', 'inflight-runs.json');
+
+ const seedLedger = async (runs: Record<string, unknown>[]) => {
+ await mkdir(path.dirname(ledgerPath()), { recursive: true });
+ await writeFile(ledgerPath(), JSON.stringify({ runs, version: 1 }), 'utf8');
+ };
+
+ const readLedger = async () =>
+ JSON.parse(await readFile(ledgerPath(), 'utf8')).runs as Record<string, any>[];
+
+ const entry = (extra?: Record<string, unknown>) => ({
+ agentType: 'claude-code',
+ ipcSessionId: 'ipc-1',
+ operationId: 'op-1',
+ pid: DEAD_PID,
+ startedAt: new Date().toISOString(),
+ topicId: 'topic-1',
+ ...extra,
+ });
+
+ const createCtr = () =>
+ new HeterogeneousAgentCtr({ appStoragePath, storeManager: { get: vi.fn() } } as any);
+
+ beforeEach(() => {
+ for (const key of Object.keys(heteroProcessOverrides)) {
+ delete (heteroProcessOverrides as Record<string, unknown>)[key];
+ }
+ });
+
+ it('keeps a claimed run on the ledger until the renderer releases it', async () => {
+ // Recovery spans several renderer steps (reap, probe, replay, settle).
+ // Consuming the entry here would leave the topic stranded if the app
+ // died again half way through, with no token left to retry it.
+ await seedLedger([entry()]);
+ const ctr = createCtr();
+
+ expect(await ctr.listInterruptedRuns({})).toEqual([
+ expect.objectContaining({ claimCount: 1, ipcSessionId: 'ipc-1' }),
+ ]);
+ expect(await readLedger()).toEqual([expect.objectContaining({ claimCount: 1 })]);
+
+ await ctr.releaseInterruptedRun({ ipcSessionId: 'ipc-1' });
+ expect(await readLedger()).toEqual([]);
+ });
+
+ it('reaps an expired run before handing its topic over for cleanup', async () => {
+ // Age only makes the transcript stale; it says nothing about the
+ // process. An orphan hung in a long-running tool is still out there.
+ const killed: [number, NodeJS.Signals][] = [];
+ heteroProcessOverrides.isProcessAlive = () => true;
+ heteroProcessOverrides.readProcessIdentity = async () => ({
+ commandLine: '/usr/local/bin/claude -p --output-format stream-json',
+ status: 'found',
+ });
+ heteroProcessOverrides.killProcessTreeByPid = (pid, signal) => killed.push([pid, signal]);
+ heteroProcessOverrides.waitForProcessExit = async () => true;
+
+ await seedLedger([
+ entry({
+ command: 'claude',
+ pid: 4321,
+ startedAt: new Date(Date.now() - 72 * 60 * 60 * 1000).toISOString(),
+ }),
+ ]);
+
+ const runs = await createCtr().listInterruptedRuns({});
+
+ expect(runs).toEqual([expect.objectContaining({ expired: true, ipcSessionId: 'ipc-1' })]);
+ expect(killed).toEqual([[4321, 'SIGTERM']]);
+ // Spent: nothing is left to claim a second time.
+ expect(await readLedger()).toEqual([]);
+ });
+
+ it('withholds a run whose process survived, leaving the entry for the next launch', async () => {
+ heteroProcessOverrides.isProcessAlive = () => true;
+ heteroProcessOverrides.readProcessIdentity = async () => ({
+ commandLine: '/usr/local/bin/claude -p --output-format stream-json',
+ status: 'found',
+ });
+ heteroProcessOverrides.killProcessTreeByPid = () => {};
+ heteroProcessOverrides.waitForProcessExit = async () => false;
+
+ await seedLedger([entry({ command: 'claude', pid: 4321 })]);
+
+ expect(await createCtr().listInterruptedRuns({})).toEqual([]);
+ expect(await readLedger()).toEqual([expect.objectContaining({ claimCount: 1 })]);
+ });
+
+ it('puts a withheld run back when stopping its live session released the claim', async () => {
+ // Reaping a session this process still holds goes through `stopSession`,
+ // which releases the ledger entry as part of stopping it. A stop that
+ // cannot confirm the child died would otherwise leave the topic stranded
+ // with nothing to retry.
+ heteroProcessOverrides.waitForProcessExit = async () => false;
+ await seedLedger([entry({ command: 'claude', pid: 4321 })]);
+ const ctr = createCtr();
+ (ctr as any).sessions.set('ipc-1', {
+ agentType: 'claude-code',
+ command: 'claude',
+ sessionId: 'ipc-1',
+ });
+
+ expect(await ctr.listInterruptedRuns({})).toEqual([]);
+ expect(await readLedger()).toEqual([expect.objectContaining({ ipcSessionId: 'ipc-1' })]);
+ });
+
+ it('leaves a run recorded by another account on the ledger, unclaimed', async () => {
+ await seedLedger([entry({ userId: 'someone-else' })]);
+
+ expect(await createCtr().listInterruptedRuns({ userId: 'me' })).toEqual([]);
+ const ledger = await readLedger();
+ expect(ledger).toHaveLength(1);
+ expect(ledger[0].claimCount).toBeUndefined();
+ });
+ });
});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.ts
new file mode 100644
index 00000000000..a78b61c73e0
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.test.ts
@@ -0,0 +1,131 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ HETERO_INFLIGHT_RUN_MAX_AGE_MS,
+ HETERO_INFLIGHT_RUN_MAX_CLAIMS,
+ type HeteroInflightRun,
+ HeteroInflightRunRegistry,
+} from './inflightRunRegistry';
+
+const run = (ipcSessionId: string, extra?: Partial<HeteroInflightRun>): HeteroInflightRun => ({
+ agentType: 'claude-code',
+ ipcSessionId,
+ operationId: `op-${ipcSessionId}`,
+ startedAt: new Date('2026-09-21T02:00:00.000Z').toISOString(),
+ topicId: 'topic-1',
+ ...extra,
+});
+
+describe('HeteroInflightRunRegistry', () => {
+ let dir: string;
+ let filePath: string;
+ let registry: HeteroInflightRunRegistry;
+
+ beforeEach(() => {
+ dir = mkdtempSync(path.join(tmpdir(), 'hetero-inflight-'));
+ filePath = path.join(dir, 'nested', 'inflight-runs.json');
+ registry = new HeteroInflightRunRegistry(filePath);
+ });
+
+ afterEach(() => {
+ rmSync(dir, { force: true, recursive: true });
+ });
+
+ it('starts empty when the file does not exist', () => {
+ expect(registry.list()).toEqual([]);
+ });
+
+ it('persists upserts across instances and creates parent directories', () => {
+ registry.upsert(run('s1', { pid: 123 }));
+ registry.upsert(run('s2'));
+
+ const reloaded = new HeteroInflightRunRegistry(filePath);
+ expect(reloaded.list().map((r) => r.ipcSessionId)).toEqual(['s1', 's2']);
+ expect(JSON.parse(readFileSync(filePath, 'utf8'))).toMatchObject({ version: 1 });
+ });
+
+ it('replaces an existing entry on upsert and merges on patch', () => {
+ registry.upsert(run('s1'));
+ registry.upsert(run('s1', { pid: 9 }));
+ registry.patch('s1', { agentSessionId: 'cc-session' });
+ registry.patch('missing', { agentSessionId: 'ignored' });
+
+ expect(registry.list()).toEqual([
+ expect.objectContaining({ agentSessionId: 'cc-session', ipcSessionId: 's1', pid: 9 }),
+ ]);
+ });
+
+ it('removes only the named entry', () => {
+ registry.upsert(run('s1'));
+ registry.upsert(run('s2'));
+ registry.remove('s1');
+ registry.remove('s1');
+
+ expect(registry.list().map((r) => r.ipcSessionId)).toEqual(['s2']);
+ });
+
+ it('keeps a claimed run on the ledger until it is released', () => {
+ registry.upsert(run('s1'));
+
+ // The renderer still has to reap, replay and settle; a crash before that
+ // would otherwise leave the topic with no token to retry it.
+ const claimed = registry.claim(run('s1'));
+ expect(claimed.claimCount).toBe(1);
+ expect(claimed.expired).toBeUndefined();
+ expect(registry.list()).toEqual([
+ expect.objectContaining({ claimCount: 1, ipcSessionId: 's1' }),
+ ]);
+
+ registry.release('s1');
+ expect(registry.list()).toEqual([]);
+ });
+
+ it('spends a run that keeps being claimed without ever being released', () => {
+ registry.upsert(run('s1'));
+
+ let entry = registry.list()[0];
+ for (let index = 1; index < HETERO_INFLIGHT_RUN_MAX_CLAIMS; index++) {
+ entry = registry.claim(entry);
+ expect(entry.expired).toBeUndefined();
+ entry = registry.list()[0];
+ }
+
+ // The last handover is status-only cleanup, and the entry goes with it.
+ expect(registry.claim(entry)).toMatchObject({ expired: true });
+ expect(registry.list()).toEqual([]);
+ });
+
+ it('claim flags stale runs and drops them, leaving fresh ones in place', () => {
+ const now = Date.parse('2026-09-21T10:00:00.000Z');
+ registry.upsert(run('fresh'));
+ registry.upsert(
+ run('stale', {
+ startedAt: new Date(now - HETERO_INFLIGHT_RUN_MAX_AGE_MS - 1000).toISOString(),
+ }),
+ );
+ registry.upsert(run('broken', { startedAt: 'not-a-date' }));
+
+ // An expired entry still comes back: its topic may be parked mid-run and
+ // the stale-topic watchdog only ever looks at `running`.
+ const claimed = registry.list().map((entry) => registry.claim(entry, now));
+ expect(claimed.map((r) => [r.ipcSessionId, r.expired ?? false])).toEqual([
+ ['fresh', false],
+ ['stale', true],
+ ['broken', true],
+ ]);
+ expect(registry.list().map((r) => r.ipcSessionId)).toEqual(['fresh']);
+ });
+
+ it('treats an unreadable file as empty instead of throwing', () => {
+ writeFileSync(path.join(dir, 'corrupt.json'), '{not json');
+ const corrupt = new HeteroInflightRunRegistry(path.join(dir, 'corrupt.json'));
+
+ expect(corrupt.list()).toEqual([]);
+ corrupt.upsert(run('s1'));
+ expect(corrupt.list()).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.ts b/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.ts
new file mode 100644
index 00000000000..3da4a3888a2
--- /dev/null
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/inflightRunRegistry.ts
@@ -0,0 +1,188 @@
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { createLogger } from '@/utils/logger';
+
+const logger = createLogger('modules:heterogeneousAgent:inflightRunRegistry');
+
+/**
+ * One local heterogeneous-agent CLI run this desktop process spawned and has
+ * not seen exit yet. Everything a restart needs to pick the run back up: the
+ * topic it belongs to (which owns the persisted rows and the `--resume` id),
+ * the cwd the CLI session is keyed under, and the pid so an orphan left by a
+ * crash can be reaped instead of burning quota headless.
+ */
+export interface HeteroInflightRun {
+ agentId?: string;
+ /** CLI-native session id (Claude Code `session_id`), known once the stream starts. */
+ agentSessionId?: string;
+ agentType: string;
+ /**
+ * Assistant row this run streams into. The only precise handle on the run's
+ * own branch: a regenerated turn hangs several assistant branches off one
+ * user row, and recovery must not touch the others.
+ */
+ assistantMessageId?: string;
+ /**
+ * Hosted provider binding the CLI session belongs to, when the run had one.
+ * A resume is dropped when its key does not match the binding this machine
+ * resolves, so recovery has to restore it alongside the session id.
+ */
+ bindingKey?: string;
+ /**
+ * How many launches have taken this entry for recovery. The entry survives
+ * a handover (see {@link HeteroInflightRunRegistry.claim}), so this is what
+ * stops a recovery that keeps dying from being retried forever.
+ */
+ claimCount?: number;
+ /** Basename of the spawned executable (e.g. `claude`), used to verify a pid before signalling it. */
+ command?: string;
+ /**
+ * Effective Claude profile root (`CLAUDE_CONFIG_DIR`) the run spawned with —
+ * a hosted binding profile, a quota-routed account, or an agent env override.
+ * The transcript lives under it, so probing and replay must both use it.
+ */
+ configDir?: string;
+ cwd?: string;
+ /**
+ * Set on {@link HeteroInflightRunRegistry.claim} when the entry is past
+ * {@link HETERO_INFLIGHT_RUN_MAX_AGE_MS} or out of claims. Not replayable
+ * any more, but its topic may still be parked mid-run, so the entry is
+ * handed over for a status-only cleanup instead of being dropped silently.
+ */
+ expired?: boolean;
+ /** Desktop IPC session id (`AgentSession.sessionId`). */
+ ipcSessionId: string;
+ operationId: string;
+ pid?: number;
+ /**
+ * Path of the CLI script when the executable is a shared interpreter (an npm
+ * `.cmd` shim unwraps to `node <cli-script>`). Pins the pid identity: `node`
+ * on its own matches half the machine.
+ */
+ scriptPath?: string;
+ /** ISO timestamp of the spawn. */
+ startedAt: string;
+ topicId?: string;
+ /**
+ * User the run belongs to. A personal-space run has no workspace, so the
+ * account is the only thing separating two people sharing one install.
+ */
+ userId?: string;
+ /**
+ * Workspace the run belongs to. Topic lookups are workspace-scoped, so a
+ * relaunch under a different workspace must leave this entry alone rather
+ * than consume it and resolve the topic as missing.
+ */
+ workspaceId?: string;
+}
+
+/** Runs older than this are no longer replayed — their transcript is stale. */
+export const HETERO_INFLIGHT_RUN_MAX_AGE_MS = 48 * 60 * 60 * 1000;
+
+/**
+ * Handovers one entry gets before it is spent. A recovery that dies mid-way
+ * has to be retryable, but an entry that kills every launch it is handed to
+ * must not come back a fourth time.
+ */
+export const HETERO_INFLIGHT_RUN_MAX_CLAIMS = 3;
+
+/**
+ * Crash-safe ledger of in-flight local CLI runs, kept as a small JSON file
+ * under the app storage path.
+ *
+ * The desktop main process holds every session in memory only, and a clean
+ * quit SIGTERMs each CLI child. Neither survives a restart, so without this
+ * file the next launch has no way to know which topics were mid-run on THIS
+ * machine (topic status alone cannot tell a run killed here from one still
+ * running on another device). Writes are synchronous: entries are removed in
+ * process-exit handlers that may race app shutdown, and the file is a few
+ * hundred bytes.
+ */
+export class HeteroInflightRunRegistry {
+ constructor(private readonly filePath: string) {}
+
+ list(): HeteroInflightRun[] {
+ let raw: string;
+ try {
+ raw = readFileSync(this.filePath, 'utf8');
+ } catch {
+ return [];
+ }
+ try {
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed?.runs) ? (parsed.runs as HeteroInflightRun[]) : [];
+ } catch (error) {
+ logger.warn('Discarding unreadable inflight-run registry:', error);
+ return [];
+ }
+ }
+
+ upsert(run: HeteroInflightRun): void {
+ const runs = this.list().filter((item) => item.ipcSessionId !== run.ipcSessionId);
+ runs.push(run);
+ this.write(runs);
+ }
+
+ patch(ipcSessionId: string, update: Partial<HeteroInflightRun>): void {
+ const runs = this.list();
+ const index = runs.findIndex((item) => item.ipcSessionId === ipcSessionId);
+ if (index < 0) return;
+ runs[index] = { ...runs[index], ...update };
+ this.write(runs);
+ }
+
+ remove(ipcSessionId: string): void {
+ const runs = this.list();
+ const next = runs.filter((item) => item.ipcSessionId !== ipcSessionId);
+ if (next.length === runs.length) return;
+ this.write(next);
+ }
+
+ /**
+ * Hand one run to a recovery attempt.
+ *
+ * The entry STAYS in the file: the renderer still has to reap, probe,
+ * replay and settle, and if it dies (or the whole app crashes again) part
+ * way through, this entry is the only token that can pick the topic back
+ * up. {@link release} removes it once recovery has reached an outcome.
+ *
+ * The returned view is flagged `expired` when the entry is past
+ * {@link HETERO_INFLIGHT_RUN_MAX_AGE_MS} or has used up its claims: too old
+ * (or too dangerous) to replay, but the topic it left parked still needs a
+ * status-only cleanup, and that last handover removes it right away so it
+ * cannot be retried again.
+ */
+ claim(run: HeteroInflightRun, now: number = Date.now()): HeteroInflightRun {
+ const claimCount = (run.claimCount ?? 0) + 1;
+ const startedAt = Date.parse(run.startedAt);
+ const tooOld = !Number.isFinite(startedAt) || now - startedAt > HETERO_INFLIGHT_RUN_MAX_AGE_MS;
+ const spent = claimCount >= HETERO_INFLIGHT_RUN_MAX_CLAIMS;
+
+ if (tooOld || spent) {
+ this.remove(run.ipcSessionId);
+ return { ...run, claimCount, expired: true };
+ }
+ this.patch(run.ipcSessionId, { claimCount });
+ return { ...run, claimCount };
+ }
+
+ /**
+ * Drop an entry whose recovery has reached an outcome. Called by the
+ * renderer, which is the only side that knows the topic was settled.
+ */
+ release(ipcSessionId: string): void {
+ this.remove(ipcSessionId);
+ }
+
+ private write(runs: HeteroInflightRun[]): void {
+ try {
+ mkdirSync(path.dirname(this.filePath), { recursive: true });
+ const tmp = `${this.filePath}.${process.pid}.tmp`;
+ writeFileSync(tmp, JSON.stringify({ runs, version: 1 }), 'utf8');
+ renameSync(tmp, this.filePath);
+ } catch (error) {
+ logger.warn('Failed to write inflight-run registry:', error);
+ }
+ }
+}
diff --git a/apps/desktop/src/main/utils/heteroCliProcess.test.ts b/apps/desktop/src/main/utils/heteroCliProcess.test.ts
new file mode 100644
index 00000000000..eae12fca5a2
--- /dev/null
+++ b/apps/desktop/src/main/utils/heteroCliProcess.test.ts
@@ -0,0 +1,215 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ commandLineLooksLikeHeteroCli,
+ describeHeteroCliProcess,
+ isPidAlive,
+ isProcessAlive,
+ readProcessIdentity,
+ tokenizeCommandLine,
+ waitForProcessExit,
+} from './heteroCliProcess';
+
+describe('commandLineLooksLikeHeteroCli', () => {
+ it('matches the recorded command basename anywhere on the command line', () => {
+ expect(
+ commandLineLooksLikeHeteroCli(
+ 'node /Users/me/.npm/bin/claude -p --output-format stream-json',
+ { agentType: 'claude-code', command: 'claude' },
+ ),
+ ).toBe(true);
+ });
+
+ it('falls back to the agent type when no command was recorded', () => {
+ expect(commandLineLooksLikeHeteroCli('/opt/codex exec --json', { agentType: 'codex' })).toBe(
+ true,
+ );
+ });
+
+ it('matches a Windows executable token regardless of case and suffix', () => {
+ expect(
+ commandLineLooksLikeHeteroCli(
+ 'C:\\Users\\me\\bin\\Claude.exe -p --output-format stream-json',
+ {
+ agentType: 'claude-code',
+ command: 'claude',
+ },
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects an unrelated process that merely mentions the CLI name', () => {
+ // Substring matching would have killed this process tree.
+ expect(
+ commandLineLooksLikeHeteroCli('python /tmp/claude-cleanup.py --force', {
+ agentType: 'claude-code',
+ command: 'claude',
+ }),
+ ).toBe(false);
+ expect(
+ commandLineLooksLikeHeteroCli('/usr/bin/grep -r claude /var/log', {
+ agentType: 'claude-code',
+ command: 'claude',
+ }),
+ ).toBe(false);
+ });
+
+ it('rejects an unrelated process that recycled the pid', () => {
+ expect(
+ commandLineLooksLikeHeteroCli('/Applications/Safari.app/Contents/MacOS/Safari', {
+ agentType: 'claude-code',
+ command: 'claude',
+ }),
+ ).toBe(false);
+ expect(commandLineLooksLikeHeteroCli(undefined, { agentType: 'claude-code' })).toBe(false);
+ });
+});
+
+describe('tokenizeCommandLine', () => {
+ it('keeps a quoted path with spaces as one token', () => {
+ expect(
+ tokenizeCommandLine('"C:\\Program Files\\nodejs\\node.exe" "C:\\app\\cli.js" -p'),
+ ).toEqual(['C:\\Program Files\\nodejs\\node.exe', 'C:\\app\\cli.js', '-p']);
+ });
+
+ it('splits an unquoted line on whitespace', () => {
+ expect(tokenizeCommandLine(' /usr/bin/node /opt/cli.js -p ')).toEqual([
+ '/usr/bin/node',
+ '/opt/cli.js',
+ '-p',
+ ]);
+ });
+});
+
+describe('commandLineLooksLikeHeteroCli with quoted Windows paths', () => {
+ const run = {
+ agentType: 'claude-code',
+ command: 'node',
+ scriptPath: 'C:\\app\\node_modules\\@anthropic-ai\\claude-code\\cli.js',
+ };
+
+ it('matches the real orphan whose executable path is quoted', () => {
+ // Splitting on whitespace yielded `"C:\Program` and `Files\nodejs\node.exe"`,
+ // so the genuine orphan failed its own check and was left running.
+ expect(
+ commandLineLooksLikeHeteroCli(
+ '"C:\\Program Files\\nodejs\\node.exe" "C:\\app\\node_modules\\@anthropic-ai\\claude-code\\cli.js" -p',
+ run,
+ ),
+ ).toBe(true);
+ });
+
+ it('still rejects a quoted node process running something else', () => {
+ expect(
+ commandLineLooksLikeHeteroCli(
+ '"C:\\Program Files\\nodejs\\node.exe" "C:\\other\\server.js"',
+ run,
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('describeHeteroCliProcess', () => {
+ it('records the CLI script when the executable is an interpreter', () => {
+ // A Windows npm shim is unwrapped into `node <cli-script>`.
+ expect(
+ describeHeteroCliProcess('C:\\Program Files\\nodejs\\node.exe', [
+ 'C:\\Program Files\\nodejs\\node.exe',
+ 'C:\\app\\node_modules\\@anthropic-ai\\claude-code\\cli.js',
+ '-p',
+ ]),
+ ).toEqual({
+ command: 'node',
+ scriptPath: 'C:\\app\\node_modules\\@anthropic-ai\\claude-code\\cli.js',
+ });
+ });
+
+ it('skips interpreter flags when looking for the script', () => {
+ expect(
+ describeHeteroCliProcess('/usr/bin/node', [
+ '/usr/bin/node',
+ '--enable-source-maps',
+ '/opt/cli.js',
+ ]).scriptPath,
+ ).toBe('/opt/cli.js');
+ });
+
+ it('records no script when the executable IS the CLI', () => {
+ expect(
+ describeHeteroCliProcess('/Users/me/.local/bin/claude', [
+ '/Users/me/.local/bin/claude',
+ '-p',
+ '--output-format',
+ 'stream-json',
+ ]),
+ ).toEqual({ command: 'claude', scriptPath: undefined });
+ });
+});
+
+describe('commandLineLooksLikeHeteroCli with an interpreter identity', () => {
+ const run = {
+ agentType: 'claude-code',
+ command: 'node',
+ scriptPath: 'C:\\app\\node_modules\\@anthropic-ai\\claude-code\\cli.js',
+ };
+
+ it('accepts the same interpreter running the recorded script', () => {
+ expect(
+ commandLineLooksLikeHeteroCli(
+ 'node.exe C:\\app\\node_modules\\@anthropic-ai\\claude-code\\cli.js -p',
+ run,
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects an unrelated node process that recycled the pid', () => {
+ // `node` alone matches half the machine; the script path is what pins it.
+ expect(commandLineLooksLikeHeteroCli('node.exe C:\\other\\server.js', run)).toBe(false);
+ });
+});
+
+describe('readProcessIdentity', () => {
+ it('reports the current process as found with its command line', async () => {
+ const identity = await readProcessIdentity(process.pid, 'darwin');
+
+ expect(identity.status).toBe('found');
+ expect(identity.commandLine).toBeTruthy();
+ });
+
+ it('reports no output as unknown rather than proof of absence', async () => {
+ // `ps` exits non-zero both for "no such process" and for an operational
+ // failure, so absence is established by isPidAlive instead.
+ expect((await readProcessIdentity(2_147_483_000, 'darwin')).status).toBe('unknown');
+ });
+});
+
+describe('isPidAlive', () => {
+ it('confirms the current process and a dead pid independently of any tool', () => {
+ expect(isPidAlive(process.pid)).toBe(true);
+ expect(isPidAlive(2_147_483_000)).toBe(false);
+ });
+});
+
+describe('isProcessAlive', () => {
+ it('reports the current process alive and a dead pid gone', () => {
+ // Own pid is not a group leader; use the platform-specific target of its own group.
+ expect(isProcessAlive(process.pid, 'win32')).toBe(true);
+ expect(isProcessAlive(2_147_483_000, 'win32')).toBe(false);
+ });
+});
+
+describe('waitForProcessExit', () => {
+ it('resolves true as soon as the process is gone', async () => {
+ let polls = 0;
+ const isAlive = vi.fn(() => ++polls < 3);
+
+ await expect(waitForProcessExit(1, 1000, { isAlive, pollMs: 1 })).resolves.toBe(true);
+ expect(isAlive).toHaveBeenCalledTimes(3);
+ });
+
+ it('resolves false when the process outlives the timeout', async () => {
+ await expect(waitForProcessExit(1, 20, { isAlive: () => true, pollMs: 1 })).resolves.toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/desktop/src/main/utils/heteroCliProcess.ts b/apps/desktop/src/main/utils/heteroCliProcess.ts
new file mode 100644
index 00000000000..923c7b0897e
--- /dev/null
+++ b/apps/desktop/src/main/utils/heteroCliProcess.ts
@@ -0,0 +1,220 @@
+import { execFile } from 'node:child_process';
+
+/**
+ * Basename of an argv token, lowercased and without a Windows executable
+ * suffix: `/usr/local/bin/claude` and `C:\\bin\\Claude.exe` both yield `claude`.
+ */
+const tokenIdentity = (token: string): string => {
+ const name = token.split(/[/\\]/).pop() ?? token;
+ return name.toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '');
+};
+
+/**
+ * Split a command line into argv tokens, honouring quotes. Windows'
+ * `Win32_Process.CommandLine` quotes any executable installed under a path
+ * with spaces (`"C:\\Program Files\\nodejs\\node.exe" …`); splitting on
+ * whitespace would yield `"C:\\Program` and `Files\\nodejs\\node.exe"`, and the
+ * real orphan would then fail its own identity check.
+ */
+export const tokenizeCommandLine = (commandLine: string): string[] => {
+ const tokens: string[] = [];
+ let current = '';
+ let quote: string | undefined;
+
+ for (const char of commandLine) {
+ if (quote) {
+ if (char === quote) quote = undefined;
+ else current += char;
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (/\s/.test(char)) {
+ if (current) tokens.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ if (current) tokens.push(current);
+
+ return tokens;
+};
+
+/**
+ * Spawn-time identity of a CLI run, recorded so a later launch can tell the
+ * original process from whatever inherited its pid.
+ */
+export interface HeteroCliProcessIdentity {
+ /** Basename identity of the spawned executable, e.g. `claude` or `node`. */
+ command?: string;
+ /** Path of the script the executable runs, when it is an interpreter. */
+ scriptPath?: string;
+}
+
+/**
+ * Derive the identity to persist from a spawned child. `spawnfile` alone is not
+ * enough: an npm `.cmd` shim is unwrapped into `node <cli-script>`, so the
+ * executable is the generic interpreter and only the script says which CLI it
+ * is (`proc.spawnargs[0]` is the program, so the script is searched after it).
+ */
+export const describeHeteroCliProcess = (
+ spawnfile: string | undefined,
+ spawnargs: readonly string[] | undefined,
+): HeteroCliProcessIdentity => {
+ const command = spawnfile ? tokenIdentity(spawnfile) : undefined;
+ const scriptPath = (spawnargs ?? [])
+ .slice(1)
+ .find((arg) => !arg.startsWith('-') && /[/\\]/.test(arg));
+ return { command, scriptPath };
+};
+
+/**
+ * Whether a live process's command line plausibly belongs to a recorded
+ * heterogeneous-agent CLI run. Pids are recycled, so an orphan is only
+ * signalled when its command line still carries the CLI that was spawned.
+ *
+ * Two independent gates:
+ * - the recorded executable has to appear where a PROGRAM can appear — the
+ * first token, or a token spelled as a path. A plain substring (or any argv
+ * token) would accept processes that merely name it (`grep -r claude`,
+ * `python /tmp/claude-cleanup.py`) and kill their whole tree.
+ * - when a CLI script was recorded, that exact path must be on the line. The
+ * executable is then a shared interpreter, and `node` alone matches half the
+ * machine.
+ */
+export const commandLineLooksLikeHeteroCli = (
+ commandLine: string | undefined,
+ run: { agentType: string } & HeteroCliProcessIdentity,
+): boolean => {
+ if (!commandLine) return false;
+
+ const tokens = tokenizeCommandLine(commandLine);
+ if (tokens.length === 0) return false;
+
+ if (run.scriptPath) {
+ const script = run.scriptPath.toLowerCase();
+ if (!tokens.some((token) => token.toLowerCase() === script)) return false;
+ }
+
+ const needles = new Set(
+ [run.command, run.agentType]
+ .filter((value): value is string => !!value)
+ .map((value) => tokenIdentity(value)),
+ );
+ if (needles.size === 0) return false;
+
+ return tokens.some((token, index) => {
+ const isProgramPosition = index === 0 || /[/\\]/.test(token);
+ return isProgramPosition && needles.has(tokenIdentity(token));
+ });
+};
+
+/**
+ * Outcome of a process identity lookup. No output means only `unknown`: a
+ * non-zero exit from `ps` / PowerShell is indistinguishable between "no such
+ * process" and the tool failing operationally, so absence has to be
+ * established independently — see {@link isPidAlive}.
+ */
+export type ProcessIdentityStatus = 'found' | 'unknown';
+
+export interface ProcessIdentity {
+ commandLine?: string;
+ status: ProcessIdentityStatus;
+}
+
+const run = (file: string, args: string[]): Promise<ProcessIdentity> =>
+ new Promise((resolve) => {
+ execFile(file, args, { timeout: 5000, windowsHide: true }, (_error, stdout) => {
+ const line = stdout.trim();
+ resolve(line ? { commandLine: line, status: 'found' } : { status: 'unknown' });
+ });
+ });
+
+/** Identity of `pid` from the OS process table — see {@link ProcessIdentity}. */
+export const readProcessIdentity = (
+ pid: number,
+ platform: NodeJS.Platform = process.platform,
+): Promise<ProcessIdentity> =>
+ platform === 'win32'
+ ? run('powershell.exe', [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`,
+ ])
+ : run('ps', ['-o', 'command=', '-p', String(pid)]);
+
+/**
+ * Whether the process `pid` ITSELF still exists, independent of its group and
+ * of any external tool. Signal 0 to a live pid succeeds; ESRCH means the
+ * process is genuinely gone, and EPERM means it exists but belongs elsewhere.
+ */
+export const isPidAlive = (pid: number): boolean => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+};
+
+/**
+ * Whether `pid` still exists. On Unix the check targets the process GROUP
+ * (the CLI is spawned detached as a group leader, and its tool children share
+ * the group), so a `claude` that already exited but left a `bash` behind
+ * still counts as alive. Windows has no groups; the pid itself is checked.
+ */
+export const isProcessAlive = (
+ pid: number,
+ platform: NodeJS.Platform = process.platform,
+): boolean => {
+ try {
+ process.kill(platform === 'win32' ? pid : -pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';
+ }
+};
+
+/**
+ * Signal the whole tree rooted at `pid`. Unix: the process group (negated
+ * pid). Windows: `taskkill /T /F` walks the tree; there is no graceful step.
+ */
+export const killProcessTreeByPid = (
+ pid: number,
+ signal: NodeJS.Signals,
+ platform: NodeJS.Platform = process.platform,
+): void => {
+ if (platform === 'win32') {
+ void run('taskkill', ['/pid', String(pid), '/T', '/F']);
+ return;
+ }
+ try {
+ process.kill(-pid, signal);
+ } catch {
+ try {
+ process.kill(pid, signal);
+ } catch {
+ /* already gone */
+ }
+ }
+};
+
+/** Resolves true once `pid` (its group on Unix) is gone, false on timeout. */
+export const waitForProcessExit = async (
+ pid: number,
+ timeoutMs: number,
+ options?: { isAlive?: (pid: number) => boolean; pollMs?: number },
+): Promise<boolean> => {
+ const isAlive = options?.isAlive ?? isProcessAlive;
+ const pollMs = options?.pollMs ?? 100;
+ const deadline = Date.now() + timeoutMs;
+ while (isAlive(pid)) {
+ if (Date.now() >= deadline) return false;
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
+ }
+ return true;
+};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index acf8515c3d5..2ccf8996ce1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1054,6 +1054,8 @@
"heteroAgent.quota.updatedAgo": "Updated {{duration}} ago",
"heteroAgent.quota.updatedJustNow": "Updated just now",
"heteroAgent.quota.weekly": "Weekly",
+ "heteroAgent.restartRecovery.resumed_one": "Picked up {{count}} local agent run that the app restart interrupted.",
+ "heteroAgent.restartRecovery.resumed_other": "Picked up {{count}} local agent runs that the app restart interrupted.",
"heteroAgent.resumeReset.bindingChanged": "Authentication binding changed. The previous local agent session could not be resumed safely, so a new conversation has started.",
"heteroAgent.resumeReset.cursorAcpIncompatible": "The previous Cursor session could not be restored through ACP, so a new conversation has started with fresh context.",
"heteroAgent.resumeReset.cwdChanged": "Working directory changed. Previous Claude Code session can only be resumed from its original directory, so a new conversation has started.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index b80e46d9fcc..273142a51e6 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1054,6 +1054,8 @@
"heteroAgent.quota.updatedAgo": "{{duration}}前更新",
"heteroAgent.quota.updatedJustNow": "刚刚更新",
"heteroAgent.quota.weekly": "每周",
+ "heteroAgent.restartRecovery.resumed_one": "已自动接续 {{count}} 个因应用重启而中断的本地 Agent 运行。",
+ "heteroAgent.restartRecovery.resumed_other": "已自动接续 {{count}} 个因应用重启而中断的本地 Agent 运行。",
"heteroAgent.resumeReset.bindingChanged": "认证绑定已更改,之前的本地 Agent 会话无法安全恢复,已开始新会话。",
"heteroAgent.resumeReset.cursorAcpIncompatible": "之前的 Cursor 会话无法通过 ACP 恢复,已使用全新上下文开始新对话。",
"heteroAgent.resumeReset.cwdChanged": "工作目录已切换,之前的 Claude Code 会话只能在原目录下继续,已开始新对话。",
diff --git a/packages/const/src/heterogeneousAgent.ts b/packages/const/src/heterogeneousAgent.ts
index e427a57042e..ff7b49b2fa5 100644
--- a/packages/const/src/heterogeneousAgent.ts
+++ b/packages/const/src/heterogeneousAgent.ts
@@ -2,6 +2,15 @@
export const HETERO_CONTINUE_PROMPT =
'Continue the task from where it stopped. The transcript above shows the work already completed — do not redo it.';
+/**
+ * Model instruction for a run cut off by a desktop restart. The transcript on
+ * disk already holds every step up to the cut, and the interrupted tool call
+ * is answered with the CLI's own "[Request interrupted]" marker, so the model
+ * only needs to be told why it stopped and to pick up rather than start over.
+ */
+export const HETERO_RESTART_CONTINUE_PROMPT =
+ 'The LobeHub desktop app hosting this session was restarted while you were working, which interrupted your previous turn. Continue the task from where it stopped — the transcript above shows the work already completed, do not redo it. If the task was already finished, briefly report the final result instead.';
+
/**
* Legacy heterogeneous-agent model IDs. Before `agencyConfig.heterogeneousProvider`
* existed, an agent was routed to the external-CLI / device execution path purely
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts
index 8575d8b4b44..0496aa4d434 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts
@@ -1,10 +1,14 @@
+import { EventEmitter } from 'node:events';
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolveClaudeSdkExecutablePath } from './claudeAgentSdkSession';
+import { resolveClaudeSdkExecutablePath, spawnClaudeCodeCliProcess } from './claudeAgentSdkSession';
const resolveCliSpawnPlanMock = vi.hoisted(() => vi.fn());
+const spawnMock = vi.hoisted(() => vi.fn());
vi.mock('./cliSpawn', () => ({ resolveCliSpawnPlan: resolveCliSpawnPlanMock }));
+vi.mock('node:child_process', () => ({ spawn: spawnMock }));
describe('resolveClaudeSdkExecutablePath', () => {
beforeEach(() => {
@@ -65,3 +69,63 @@ describe('resolveClaudeSdkExecutablePath', () => {
expect(resolveCliSpawnPlanMock).not.toHaveBeenCalled();
});
});
+
+describe('spawnClaudeCodeCliProcess', () => {
+ const spawnOptions = {
+ args: ['--output-format', 'stream-json'],
+ command: '/usr/local/bin/claude',
+ cwd: '/repo',
+ env: { PATH: '/usr/bin' },
+ signal: new AbortController().signal,
+ };
+
+ const fakeChild = () => {
+ const child = new EventEmitter() as any;
+ child.pid = 4321;
+ child.stderr = new EventEmitter();
+ return child;
+ };
+
+ beforeEach(() => {
+ spawnMock.mockReset();
+ });
+
+ it('reports the CLI child so a crashed host can reap it', () => {
+ // The SDK runs a real Claude executable; without its identity, an orphan
+ // left by a hard crash is still writing the transcript recovery replays.
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const onProcessSpawn = vi.fn();
+
+ spawnClaudeCodeCliProcess(spawnOptions as any, { onProcessSpawn, onStderr: vi.fn() }, 'darwin');
+
+ expect(onProcessSpawn).toHaveBeenCalledWith({
+ args: ['/usr/local/bin/claude', '--output-format', 'stream-json'],
+ command: '/usr/local/bin/claude',
+ pid: 4321,
+ });
+ // Its own Unix process group, so reaping takes the tool children with it.
+ expect(spawnMock.mock.calls[0][2]).toMatchObject({ cwd: '/repo', detached: true });
+ });
+
+ it('keeps the child out of a process group on Windows', () => {
+ spawnMock.mockReturnValue(fakeChild());
+
+ spawnClaudeCodeCliProcess(spawnOptions as any, { onStderr: vi.fn() }, 'win32');
+
+ expect(spawnMock.mock.calls[0][2]).toMatchObject({ detached: false });
+ });
+
+ it('drains stderr the SDK no longer reads', () => {
+ // The SDK only wires its own stderr option on the spawn it owns; an
+ // unread pipe fills up and blocks the CLI.
+ const child = fakeChild();
+ spawnMock.mockReturnValue(child);
+ const onStderr = vi.fn();
+
+ spawnClaudeCodeCliProcess(spawnOptions as any, { onStderr }, 'darwin');
+ child.stderr.emit('data', Buffer.from('boom'));
+
+ expect(onStderr).toHaveBeenCalledWith('boom');
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
index 0bb45dfcdbe..166c4a4b281 100644
--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts
@@ -1,8 +1,12 @@
+import { type ChildProcess, spawn } from 'node:child_process';
+
import type {
Options as ClaudeAgentSdkOptions,
Query as ClaudeAgentSdkQuery,
SDKMessage,
SDKUserMessage,
+ SpawnedProcess as SdkSpawnedProcess,
+ SpawnOptions as SdkSpawnOptions,
} from '@anthropic-ai/claude-agent-sdk';
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
@@ -154,6 +158,12 @@ export interface ClaudeAgentSdkSessionOptions {
cwd: string;
env: NodeJS.ProcessEnv;
onEvents: (events: AgentStreamEvent[]) => Promise<void> | void;
+ /**
+ * The CLI child this session spawned. The SDK runs an actual Claude
+ * executable, so a host crash can leave that process orphaned — the host
+ * needs its identity to reap it on the next launch.
+ */
+ onProcessSpawn?: (process: { args: string[]; command: string; pid?: number }) => void;
onRawMessage: (line: string) => Promise<void> | void;
onRuntimeStatus: (status: HeterogeneousAgentRuntimeStatus) => void;
onSessionId: (sessionId: string) => void;
@@ -166,6 +176,48 @@ export interface ClaudeAgentSdkSessionOptions {
uploadImage?: UploadHeterogeneousImage;
}
+/**
+ * Spawn the CLI the SDK would otherwise own privately.
+ *
+ * Two reasons to take it over: the pid has to reach the host's recovery ledger
+ * (an SDK run orphaned by a main-process crash is a real Claude process, still
+ * writing the transcript a replay is about to read), and the child belongs in
+ * its own Unix process group like every other CLI run here, so reaping it takes
+ * its tool children with it. `signal` is the SDK's forwarded one — it fires
+ * only after the graceful stdin-EOF window.
+ */
+export const spawnClaudeCodeCliProcess = (
+ options: SdkSpawnOptions,
+ hooks: {
+ onProcessSpawn?: (process: { args: string[]; command: string; pid?: number }) => void;
+ onStderr: (data: string) => void;
+ },
+ platform: NodeJS.Platform = process.platform,
+): SdkSpawnedProcess => {
+ const child: ChildProcess = spawn(options.command, options.args, {
+ cwd: options.cwd,
+ detached: platform !== 'win32',
+ // The SDK types env as a plain string map; this repo augments ProcessEnv
+ // with required keys, which no spawn caller carries.
+ env: options.env as NodeJS.ProcessEnv,
+ signal: options.signal,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+
+ // The SDK only wires its own `stderr` option on the spawn it owns, so this
+ // pipe has nobody reading it — and a full stderr pipe blocks the CLI.
+ child.stderr?.on('data', (chunk: Buffer | string) => hooks.onStderr(chunk.toString()));
+
+ hooks.onProcessSpawn?.({
+ args: [options.command, ...options.args],
+ command: options.command,
+ pid: child.pid,
+ });
+
+ return child as unknown as SdkSpawnedProcess;
+};
+
export class ClaudeAgentSdkSession {
private readonly abortController = new AbortController();
private activeTasks = new Map<string, TrackedTask>();
@@ -260,6 +312,11 @@ export class ClaudeAgentSdkSession {
includePartialMessages: true,
pathToClaudeCodeExecutable: executablePath,
permissionMode: 'bypassPermissions',
+ spawnClaudeCodeProcess: (spawnOptions) =>
+ spawnClaudeCodeCliProcess(spawnOptions, {
+ onProcessSpawn: this.options.onProcessSpawn,
+ onStderr: (data) => void this.options.onStderr(data),
+ }),
...(this.options.resumeSessionId ? { resume: this.options.resumeSessionId } : {}),
...argOptions,
stderr: (data) => {
diff --git a/packages/heterogeneous-agents/src/transcript/index.ts b/packages/heterogeneous-agents/src/transcript/index.ts
index 2047712f3ec..092e8bb803b 100644
--- a/packages/heterogeneous-agents/src/transcript/index.ts
+++ b/packages/heterogeneous-agents/src/transcript/index.ts
@@ -14,4 +14,6 @@ export {
} from './codex';
export type { BuildClaudeCodeTranscriptOptions } from './rebuildClaudeCode';
export { buildClaudeCodeTranscript, encodeClaudeProjectDir } from './rebuildClaudeCode';
+export type { ClaudeCodeReplayTurn } from './replayClaudeCode';
+export { buildClaudeCodeReplayTurn, claudeCodeReplayTurnMatchesPrompt } from './replayClaudeCode';
export { parseJsonlRecords, stripNulDeep, truncateTitle } from './utils';
diff --git a/packages/heterogeneous-agents/src/transcript/replayClaudeCode.test.ts b/packages/heterogeneous-agents/src/transcript/replayClaudeCode.test.ts
new file mode 100644
index 00000000000..e4808d4952c
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/replayClaudeCode.test.ts
@@ -0,0 +1,388 @@
+import { describe, expect, it } from 'vitest';
+
+import { AgentStreamPipeline } from '../spawn/agentStreamPipeline';
+import { buildClaudeCodeReplayTurn, claudeCodeReplayTurnMatchesPrompt } from './replayClaudeCode';
+
+const SESSION_ID = '03003604-e4aa-4c7c-ac24-86e4adcfca35';
+
+const line = (record: Record<string, any>) => JSON.stringify(record);
+
+const base = { cwd: '/repo', isSidechain: false, sessionId: SESSION_ID, version: '2.1.266' };
+
+const userPrompt = (uuid: string, parentUuid: string | null, text: string) =>
+ line({
+ ...base,
+ message: { content: text, role: 'user' },
+ parentUuid,
+ timestamp: '2026-09-21T02:00:00.000Z',
+ type: 'user',
+ uuid,
+ });
+
+const attachment = (uuid: string, parentUuid: string) =>
+ line({ ...base, attachment: { type: 'environment' }, parentUuid, type: 'attachment', uuid });
+
+const assistant = (
+ uuid: string,
+ parentUuid: string,
+ msgId: string,
+ block: Record<string, any>,
+ stopReason: string,
+ extra?: Record<string, any>,
+) =>
+ line({
+ ...base,
+ message: {
+ content: [block],
+ id: msgId,
+ model: 'claude-opus-5',
+ role: 'assistant',
+ stop_reason: stopReason,
+ type: 'message',
+ usage: { input_tokens: 12, output_tokens: 34 },
+ },
+ parentUuid,
+ timestamp: '2026-09-21T02:00:01.000Z',
+ type: 'assistant',
+ uuid,
+ ...extra,
+ });
+
+const toolResult = (uuid: string, parentUuid: string, toolUseId: string, text: string) =>
+ line({
+ ...base,
+ message: {
+ content: [{ content: text, tool_use_id: toolUseId, type: 'tool_result' }],
+ role: 'user',
+ },
+ parentUuid,
+ timestamp: '2026-09-21T02:00:02.000Z',
+ toolUseResult: { stdout: text },
+ type: 'user',
+ uuid,
+ });
+
+const bash = (id: string, command: string) => ({
+ id,
+ input: { command },
+ name: 'Bash',
+ type: 'tool_use',
+});
+
+/** Turn 1 finished normally; turn 2 is the one under test. */
+const FIRST_TURN = [
+ userPrompt('u1', null, 'first request'),
+ attachment('a1', 'u1'),
+ assistant('m1', 'a1', 'msg_1', { text: 'done with first', type: 'text' }, 'end_turn'),
+];
+
+const completedTranscript = [
+ ...FIRST_TURN,
+ userPrompt('u2', 'm1', 'second request'),
+ attachment('a2', 'u2'),
+ assistant(
+ 'm2a',
+ 'a2',
+ 'msg_2',
+ { signature: 'sig', thinking: 'plan', type: 'thinking' },
+ 'tool_use',
+ ),
+ assistant('m2b', 'm2a', 'msg_2', bash('toolu_1', 'ls'), 'tool_use'),
+ toolResult('r1', 'm2b', 'toolu_1', 'file-a\nfile-b'),
+ attachment('a3', 'r1'),
+ assistant('m3', 'a3', 'msg_3', { text: 'STEP1_OK', type: 'text' }, 'end_turn'),
+ line({ leafUuid: 'm3', type: 'last-prompt' }),
+].join('\n');
+
+const interruptedTranscript = [
+ ...FIRST_TURN,
+ userPrompt('u2', 'm1', 'second request'),
+ assistant('m2a', 'u2', 'msg_2', bash('toolu_1', 'ls'), 'tool_use'),
+ toolResult('r1', 'm2a', 'toolu_1', 'file-a'),
+ assistant('m3', 'r1', 'msg_3', bash('toolu_2', 'sleep 40'), 'tool_use'),
+ line({ leafUuid: 'm3', type: 'last-prompt' }),
+].join('\n');
+
+describe('buildClaudeCodeReplayTurn', () => {
+ it('replays only the last turn and reports it complete', () => {
+ const turn = buildClaudeCodeReplayTurn(completedTranscript);
+
+ expect(turn).not.toBeNull();
+ expect(turn!.sessionId).toBe(SESSION_ID);
+ expect(turn!.promptUuid).toBe('u2');
+ expect(turn!.promptText).toBe('second request');
+ expect(turn!.complete).toBe(true);
+ // thinking + tool_use + tool_result + final text
+ expect(turn!.recordCount).toBe(4);
+
+ const parsed = turn!.lines.map((l) => JSON.parse(l));
+ expect(parsed.map((p) => p.type)).toEqual([
+ 'system',
+ 'assistant',
+ 'assistant',
+ 'user',
+ 'assistant',
+ 'result',
+ ]);
+ expect(parsed[0]).toMatchObject({
+ model: 'claude-opus-5',
+ session_id: SESSION_ID,
+ subtype: 'init',
+ });
+ // Nothing from the first turn leaks in.
+ expect(turn!.lines.join('\n')).not.toContain('done with first');
+ // Envelope fields are spelled the stream-json way.
+ expect(parsed[3]).toMatchObject({
+ session_id: SESSION_ID,
+ tool_use_result: { stdout: 'file-a\nfile-b' },
+ type: 'user',
+ });
+ expect(parsed[3].toolUseResult).toBeUndefined();
+ expect(parsed.at(-1)).toMatchObject({
+ is_error: false,
+ result: 'STEP1_OK',
+ subtype: 'success',
+ usage: { input_tokens: 12, output_tokens: 34 },
+ });
+ });
+
+ it('flags a turn cut off on a dangling tool_use as incomplete and emits no result', () => {
+ const turn = buildClaudeCodeReplayTurn(interruptedTranscript);
+
+ expect(turn!.complete).toBe(false);
+ const parsed = turn!.lines.map((l) => JSON.parse(l));
+ expect(parsed.map((p) => p.type)).toEqual(['system', 'assistant', 'user', 'assistant']);
+ expect(parsed.some((p) => p.type === 'result')).toBe(false);
+ });
+
+ it('treats a turn that ended on an API error message as incomplete', () => {
+ const transcript = [
+ ...FIRST_TURN,
+ userPrompt('u2', 'm1', 'second request'),
+ assistant(
+ 'm2',
+ 'u2',
+ 'msg_2',
+ { text: 'API Error: overloaded', type: 'text' },
+ 'stop_sequence',
+ { isApiErrorMessage: true },
+ ),
+ line({ leafUuid: 'm2', type: 'last-prompt' }),
+ ].join('\n');
+
+ expect(buildClaudeCodeReplayTurn(transcript)!.complete).toBe(false);
+ });
+
+ it('pulls parallel tool results from sibling branches, in tool order', () => {
+ const transcript = [
+ ...FIRST_TURN,
+ userPrompt('u2', 'm1', 'second request'),
+ assistant('m2a', 'u2', 'msg_2', bash('toolu_a', 'ls a'), 'tool_use'),
+ assistant('m2b', 'm2a', 'msg_2', bash('toolu_b', 'ls b'), 'tool_use'),
+ // result B lands on the trunk, result A on a sibling branch
+ toolResult('rb', 'm2b', 'toolu_b', 'out-b'),
+ toolResult('ra', 'm2b', 'toolu_a', 'out-a'),
+ assistant('m3', 'rb', 'msg_3', { text: 'both done', type: 'text' }, 'end_turn'),
+ line({ leafUuid: 'm3', type: 'last-prompt' }),
+ ].join('\n');
+
+ const turn = buildClaudeCodeReplayTurn(transcript);
+ const parsed = turn!.lines.map((l) => JSON.parse(l));
+ const toolResultIds = parsed
+ .filter((p) => p.type === 'user')
+ .map((p) => p.message.content[0].tool_use_id);
+
+ expect(turn!.complete).toBe(true);
+ expect(toolResultIds).toEqual(['toolu_a', 'toolu_b']);
+ expect(parsed.filter((p) => p.uuid === 'ra')).toHaveLength(1);
+ });
+
+ it('holds a bundled parallel result until every call it answers is registered', async () => {
+ // The API returns parallel tool results as ONE user record answering both
+ // calls; emitting it on the first call would deliver b's result before b
+ // was registered.
+ const bundled = line({
+ ...base,
+ message: {
+ content: [
+ { content: 'out-a', tool_use_id: 'toolu_a', type: 'tool_result' },
+ { content: 'out-b', tool_use_id: 'toolu_b', type: 'tool_result' },
+ ],
+ role: 'user',
+ },
+ parentUuid: 'm2b',
+ timestamp: '2026-09-21T02:00:02.000Z',
+ type: 'user',
+ uuid: 'rboth',
+ });
+ const transcript = [
+ ...FIRST_TURN,
+ userPrompt('u2', 'm1', 'second request'),
+ assistant('m2a', 'u2', 'msg_2', bash('toolu_a', 'ls a'), 'tool_use'),
+ assistant('m2b', 'm2a', 'msg_2', bash('toolu_b', 'ls b'), 'tool_use'),
+ bundled,
+ assistant('m3', 'rboth', 'msg_3', { text: 'both done', type: 'text' }, 'end_turn'),
+ line({ leafUuid: 'm3', type: 'last-prompt' }),
+ ].join('\n');
+
+ const turn = buildClaudeCodeReplayTurn(transcript)!;
+ const parsed = turn.lines.map((l) => JSON.parse(l));
+
+ // The bundled record lands only after BOTH tool_use lines.
+ expect(parsed.map((p) => p.type)).toEqual([
+ 'system',
+ 'assistant',
+ 'assistant',
+ 'user',
+ 'assistant',
+ 'result',
+ ]);
+ expect(parsed[3].uuid).toBe('rboth');
+ // It is written once, not once per answered call.
+ expect(parsed.filter((p) => p.uuid === 'rboth')).toHaveLength(1);
+ expect(turn.complete).toBe(true);
+
+ // The real adapter resolves both calls successfully.
+ const pipeline = new AgentStreamPipeline({ agentType: 'claude-code', operationId: 'op-1' });
+ const events = [];
+ for (const l of turn.lines) events.push(...(await pipeline.push(`${l}\n`)));
+ events.push(...(await pipeline.flush()));
+
+ const toolEnds = events.filter((e) => e.type === 'tool_end') as any[];
+ expect(toolEnds.map((e) => [e.data.toolCallId, e.data.isSuccess])).toEqual([
+ ['toolu_a', true],
+ ['toolu_b', true],
+ ]);
+ });
+
+ it('does not anchor on the meta follow-up the CLI injects after an interrupt', () => {
+ const transcript = [
+ ...FIRST_TURN,
+ userPrompt('u2', 'm1', 'second request'),
+ assistant('m2', 'u2', 'msg_2', bash('toolu_1', 'sleep 40'), 'tool_use'),
+ line({
+ ...base,
+ message: {
+ content: [
+ {
+ content: '[Request interrupted by user for tool use]',
+ tool_use_id: 'toolu_1',
+ type: 'tool_result',
+ },
+ ],
+ role: 'user',
+ },
+ parentUuid: 'm2',
+ toolDenialKind: 'interrupt',
+ type: 'user',
+ uuid: 'r1',
+ }),
+ line({
+ ...base,
+ isMeta: true,
+ message: {
+ content: [{ text: '[Request interrupted by user]', type: 'text' }],
+ role: 'user',
+ },
+ parentUuid: 'r1',
+ type: 'user',
+ uuid: 'meta1',
+ }),
+ line({ leafUuid: 'meta1', type: 'last-prompt' }),
+ ].join('\n');
+
+ const turn = buildClaudeCodeReplayTurn(transcript);
+
+ expect(turn!.promptUuid).toBe('u2');
+ expect(turn!.complete).toBe(false);
+ });
+
+ it('returns null without a user prompt or session id', () => {
+ expect(buildClaudeCodeReplayTurn('')).toBeNull();
+ expect(buildClaudeCodeReplayTurn(line({ type: 'ai-title', aiTitle: 'x' }))).toBeNull();
+ expect(
+ buildClaudeCodeReplayTurn(
+ assistant('m1', 'x', 'msg_1', { text: 'orphan', type: 'text' }, 'end_turn'),
+ ),
+ ).toBeNull();
+ });
+
+ it('drives the real Claude Code adapter like a live process would', async () => {
+ const turn = buildClaudeCodeReplayTurn(completedTranscript)!;
+ const pipeline = new AgentStreamPipeline({ agentType: 'claude-code', operationId: 'op-1' });
+
+ const events = [];
+ for (const l of turn.lines) events.push(...(await pipeline.push(`${l}\n`)));
+ events.push(...(await pipeline.flush()));
+
+ const types = events.map((e) => e.type);
+ expect(pipeline.sessionId).toBe(SESSION_ID);
+ expect(types[0]).toBe('stream_start');
+ expect(types).toContain('tool_start');
+ expect(types).toContain('tool_end');
+ expect(types).toContain('stream_chunk');
+ expect(types.at(-1)).toBe('agent_runtime_end');
+
+ const toolEnd = events.find((e) => e.type === 'tool_end') as any;
+ expect(toolEnd.data.toolCallId).toBe('toolu_1');
+ expect(toolEnd.data.isSuccess).toBe(true);
+ });
+
+ it('leaves the dangling tool unsuccessful and no runtime end for a cut-off turn', async () => {
+ const turn = buildClaudeCodeReplayTurn(interruptedTranscript)!;
+ const pipeline = new AgentStreamPipeline({ agentType: 'claude-code', operationId: 'op-1' });
+
+ const events = [];
+ for (const l of turn.lines) events.push(...(await pipeline.push(`${l}\n`)));
+ events.push(...(await pipeline.flush()));
+
+ const types = events.map((e) => e.type);
+ expect(types).not.toContain('agent_runtime_end');
+ const toolEnds = events.filter((e) => e.type === 'tool_end') as any[];
+ expect(toolEnds.map((e) => [e.data.toolCallId, e.data.isSuccess])).toEqual([
+ ['toolu_1', true],
+ ['toolu_2', false],
+ ]);
+ });
+});
+
+describe('claudeCodeReplayTurnMatchesPrompt', () => {
+ const turn = buildClaudeCodeReplayTurn(completedTranscript)!;
+
+ it('matches the prompt the interrupted run was given', () => {
+ expect(claudeCodeReplayTurnMatchesPrompt(turn, 'second request')).toBe(true);
+ // The CLI may record a preamble around what we sent, and vice versa.
+ expect(claudeCodeReplayTurnMatchesPrompt(turn, ' second request ')).toBe(true);
+ expect(claudeCodeReplayTurnMatchesPrompt(turn, 'please: second request now')).toBe(true);
+ });
+
+ it('rejects a transcript still ending on the previous turn', () => {
+ // The restart beat the CLI to recording the follow-up, so the last turn on
+ // disk answers an older prompt — replaying it would rewrite the topic.
+ expect(claudeCodeReplayTurnMatchesPrompt(turn, 'a completely different ask')).toBe(false);
+ });
+
+ it('does not gate when the caller pinned no prompt', () => {
+ expect(claudeCodeReplayTurnMatchesPrompt(turn, undefined)).toBe(true);
+ });
+
+ it('surfaces the time the CLI recorded the prompt', () => {
+ expect(turn.promptTimestamp).toBe('2026-09-21T02:00:00.000Z');
+ });
+
+ it('rejects an older turn whose text merely contains the new prompt', () => {
+ // The dangerous case text matching cannot see: a follow-up (`second`) the
+ // CLI never got to record, next to a finished turn (`second request`) that
+ // contains it. The run was spawned after that turn was written, so it
+ // cannot be the one it answers.
+ expect(claudeCodeReplayTurnMatchesPrompt(turn, 'second', '2026-09-21T02:00:30.000Z')).toBe(
+ false,
+ );
+ });
+
+ it('accepts the turn the CLI recorded after the run was spawned', () => {
+ expect(
+ claudeCodeReplayTurnMatchesPrompt(turn, 'second request', '2026-09-21T01:59:59.000Z'),
+ ).toBe(true);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/transcript/replayClaudeCode.ts b/packages/heterogeneous-agents/src/transcript/replayClaudeCode.ts
new file mode 100644
index 00000000000..5198e4183bd
--- /dev/null
+++ b/packages/heterogeneous-agents/src/transcript/replayClaudeCode.ts
@@ -0,0 +1,314 @@
+import { parseJsonlRecords } from './utils';
+
+/**
+ * Turn the tail of a Claude Code local transcript
+ * (`~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl`) back into the
+ * `--output-format stream-json` lines the CLI would have printed for that turn.
+ *
+ * Why: when the desktop app restarts (or its renderer reloads) mid-run, the
+ * CLI process dies or keeps running headless, and everything it produced after
+ * the last flushed chunk never reached LobeHub. The transcript on disk still
+ * has it. Feeding these synthesized lines through the same
+ * `AgentStreamPipeline` a live process uses persists that work exactly as if
+ * the app had been watching — same adapter, same reducer, same rows.
+ *
+ * Shape notes (verified against real transcripts):
+ * - `assistant` / `user` records already carry the Anthropic `message` the
+ * stream-json events wrap; the event shape differs only in envelope fields
+ * (`session_id` vs `sessionId`, `tool_use_result` vs `toolUseResult`).
+ * - One transcript line per assistant content block, sharing `message.id` —
+ * exactly how stream-json emits them, so no merging is needed here.
+ * - Parallel tool results live on sibling branches of the trunk; they are
+ * indexed globally by `tool_use_id` and emitted right after their
+ * `tool_use`, in tool order.
+ * - Sidechain (subagent) records live in separate files and are not replayed.
+ */
+
+export interface ClaudeCodeReplayTurn {
+ /**
+ * True when the turn ended on its own: the last main-chain record is an
+ * assistant message, every `tool_use` has a `tool_result`, and the model did
+ * not stop to call another tool. False means the run was cut off and needs
+ * a `--resume` continuation after the replay.
+ */
+ complete: boolean;
+ /** stream-json lines, in emission order (system init first, result last when complete). */
+ lines: string[];
+ /** Text of the user prompt that opened the turn (for diagnostics / matching). */
+ promptText: string;
+ /**
+ * ISO time the CLI appended that prompt record. Written by the CLI on this
+ * machine, so it shares a clock with the ledger's `startedAt` — the durable
+ * half of {@link claudeCodeReplayTurnMatchesPrompt}.
+ */
+ promptTimestamp?: string;
+ /** Transcript record uuid of that prompt. */
+ promptUuid: string;
+ /** Number of assistant / tool_result records replayed. */
+ recordCount: number;
+ sessionId: string;
+}
+
+const isConversational = (record: any): boolean =>
+ !record?.isSidechain && (record?.type === 'user' || record?.type === 'assistant');
+
+const textOfContent = (content: any): string => {
+ if (typeof content === 'string') return content;
+ if (!Array.isArray(content)) return '';
+ return content
+ .map((block: any) => (block?.type === 'text' ? block.text : ''))
+ .filter(Boolean)
+ .join('\n\n');
+};
+
+/**
+ * A user record that opens a turn: real input, not a `tool_result` carrier and
+ * not one of the CLI's own meta injections (`isMeta`, e.g. the synthesized
+ * "[Request interrupted by user for tool use]" follow-up on resume).
+ */
+const isUserPrompt = (record: any): boolean => {
+ if (record?.type !== 'user' || record.isMeta) return false;
+ const content = record.message?.content;
+ if (typeof content === 'string') return content.length > 0;
+ if (!Array.isArray(content)) return false;
+ return content.some((block: any) => block?.type !== 'tool_result');
+};
+
+const walkTrunk = (records: any[]): any[] => {
+ const byUuid = new Map<string, any>();
+ for (const record of records) if (record?.uuid) byUuid.set(record.uuid, record);
+
+ const lastPrompt = records.findLast((r) => r?.type === 'last-prompt');
+ const leafUuid: string | undefined =
+ lastPrompt?.leafUuid ?? records.findLast((r) => r?.uuid && isConversational(r))?.uuid;
+ if (!leafUuid) return [];
+
+ const chain: any[] = [];
+ const visited = new Set<string>();
+ let cursor = byUuid.get(leafUuid);
+ while (cursor && cursor.uuid && !visited.has(cursor.uuid)) {
+ visited.add(cursor.uuid);
+ chain.unshift(cursor);
+ cursor = cursor.parentUuid ? byUuid.get(cursor.parentUuid) : undefined;
+ }
+ return chain;
+};
+
+const toAssistantLine = (record: any, sessionId: string): string =>
+ JSON.stringify({
+ message: record.message,
+ parent_tool_use_id: null,
+ session_id: sessionId,
+ type: 'assistant',
+ uuid: record.uuid,
+ });
+
+const toUserLine = (record: any, sessionId: string): string =>
+ JSON.stringify({
+ message: record.message,
+ parent_tool_use_id: null,
+ session_id: sessionId,
+ // The live event spells this in snake_case; the transcript in camelCase.
+ ...(record.toolUseResult === undefined ? {} : { tool_use_result: record.toolUseResult }),
+ type: 'user',
+ uuid: record.uuid,
+ });
+
+const normalizePrompt = (value: string): string => value.replaceAll(/\s+/g, ' ').trim();
+
+/**
+ * Whether a replayable turn really is the one LobeHub was running.
+ *
+ * A resumed session keeps one transcript across turns, so a restart that lands
+ * before the CLI appended the new prompt leaves the PREVIOUS completed turn as
+ * the last one on disk. Replaying that under the new prompt would silently
+ * rewrite the conversation, so the turn has to be pinned to the run.
+ *
+ * Two gates, and the first is the one that holds:
+ * - `notBefore`: the CLI cannot have recorded this run's prompt before the run
+ * was spawned, so a turn older than the spawn is somebody else's. Both times
+ * are written on this machine (the ledger by Electron main, the record by the
+ * CLI), so the comparison stays inside one clock.
+ * - text: containment rather than equality, because what the CLI recorded may
+ * carry an injected preamble or drop a slash command. On its own it accepts
+ * an adjacent prompt (`continue` against a recorded `continue fixing tests`),
+ * which is exactly what the timestamp gate rules out.
+ */
+export const claudeCodeReplayTurnMatchesPrompt = (
+ turn: ClaudeCodeReplayTurn,
+ expectedPrompt: string | undefined,
+ notBefore?: string,
+): boolean => {
+ const floor = notBefore ? Date.parse(notBefore) : Number.NaN;
+ const recordedAt = turn.promptTimestamp ? Date.parse(turn.promptTimestamp) : Number.NaN;
+ if (Number.isFinite(floor) && Number.isFinite(recordedAt) && recordedAt < floor) return false;
+
+ const expected = normalizePrompt(expectedPrompt ?? '');
+ const recorded = normalizePrompt(turn.promptText);
+ // Nothing to compare against — the caller did not pin a prompt.
+ if (!expected) return true;
+ if (!recorded) return false;
+ return recorded.includes(expected) || expected.includes(recorded);
+};
+
+/**
+ * Build the replay for the LAST turn of a transcript. Returns null when the
+ * transcript has no session id or no user prompt to anchor on.
+ */
+export const buildClaudeCodeReplayTurn = (content: string): ClaudeCodeReplayTurn | null => {
+ const records = parseJsonlRecords(content);
+ if (records.length === 0) return null;
+
+ const sessionId: string | undefined = records.find((r) => r?.sessionId)?.sessionId;
+ if (!sessionId) return null;
+
+ const trunk = walkTrunk(records).filter((r) => isConversational(r));
+ const promptIndex = trunk.findLastIndex((r) => isUserPrompt(r));
+ if (promptIndex < 0) return null;
+
+ const prompt = trunk[promptIndex];
+ const turn = trunk.slice(promptIndex + 1);
+
+ // Every tool_result in the file, by the tool_use it answers. Parallel tool
+ // calls park their results on sibling branches the trunk walk never visits.
+ // A single record can answer SEVERAL calls (the API bundles parallel results
+ // into one user message), so the reverse index is kept too.
+ const toolResultByUseId = new Map<string, any>();
+ const answeredIdsByRecord = new Map<string, string[]>();
+ for (const record of records) {
+ if (record?.type !== 'user' || record.isSidechain) continue;
+ const blocks = record.message?.content;
+ if (!Array.isArray(blocks)) continue;
+ for (const block of blocks) {
+ if (block?.type === 'tool_result' && block.tool_use_id) {
+ toolResultByUseId.set(block.tool_use_id, record);
+ const answered = answeredIdsByRecord.get(record.uuid) ?? [];
+ answered.push(block.tool_use_id);
+ answeredIdsByRecord.set(record.uuid, answered);
+ }
+ }
+ }
+
+ // Every tool_use this turn issues. A bundled result may also answer calls
+ // from an earlier turn; those must not hold the record back forever.
+ const turnToolUseIds = new Set<string>();
+ for (const record of turn) {
+ if (record.type !== 'assistant') continue;
+ const blocks = Array.isArray(record.message?.content) ? record.message.content : [];
+ for (const block of blocks) {
+ if (block?.type === 'tool_use' && block.id) turnToolUseIds.add(block.id);
+ }
+ }
+
+ const lines: string[] = [];
+ const emitted = new Set<string>();
+ let model: string | undefined;
+ let lastAssistant: any;
+ let lastUsage: any;
+ let dangling = false;
+ let recordCount = 0;
+
+ /** tool_use ids already written to the stream — see `emitToolResult`. */
+ const openedToolUseIds = new Set<string>();
+
+ const emitToolResult = (toolUseId: string) => {
+ const record = toolResultByUseId.get(toolUseId);
+ if (!record) {
+ dangling = true;
+ return;
+ }
+ if (emitted.has(record.uuid)) return;
+
+ // Hold a bundled record until every call it answers has been written.
+ // Emitting it on the first call would hand the consumer a result for a
+ // tool it has not registered yet — dropped as unknown, and never retried
+ // because the record is then marked emitted.
+ const pending = (answeredIdsByRecord.get(record.uuid) ?? []).filter(
+ (id) => turnToolUseIds.has(id) && !openedToolUseIds.has(id),
+ );
+ if (pending.length > 0) return;
+
+ emitted.add(record.uuid);
+ lines.push(toUserLine(record, sessionId));
+ recordCount++;
+ };
+
+ for (const record of turn) {
+ if (emitted.has(record.uuid)) continue;
+
+ if (record.type === 'assistant') {
+ emitted.add(record.uuid);
+ model ??= record.message?.model;
+ lastAssistant = record;
+ if (record.message?.usage) lastUsage = record.message.usage;
+ lines.push(toAssistantLine(record, sessionId));
+ recordCount++;
+
+ const blocks = Array.isArray(record.message?.content) ? record.message.content : [];
+ // Register every call this record opens BEFORE resolving any of them, so
+ // a record bundling this message's own parallel results is not held back.
+ for (const block of blocks) {
+ if (block?.type === 'tool_use' && block.id) openedToolUseIds.add(block.id);
+ }
+ for (const block of blocks) {
+ if (block?.type === 'tool_use' && block.id) emitToolResult(block.id);
+ }
+ continue;
+ }
+
+ // A trunk user record here is a tool_result carrier the loop above did not
+ // reach through its tool_use (or a meta injection) — emit tool results only.
+ const blocks = record.message?.content;
+ const hasToolResult =
+ Array.isArray(blocks) && blocks.some((block: any) => block?.type === 'tool_result');
+ if (!hasToolResult) continue;
+ emitted.add(record.uuid);
+ lines.push(toUserLine(record, sessionId));
+ recordCount++;
+ }
+
+ const endedOnAssistant = turn.at(-1)?.type === 'assistant' && !!lastAssistant;
+ const stoppedForTool = lastAssistant?.message?.stop_reason === 'tool_use';
+ const complete =
+ endedOnAssistant && !dangling && !stoppedForTool && !lastAssistant?.isApiErrorMessage;
+
+ lines.unshift(
+ JSON.stringify({
+ cwd: records.find((r) => r?.cwd)?.cwd,
+ mcp_servers: [],
+ model,
+ session_id: sessionId,
+ subtype: 'init',
+ tools: [],
+ type: 'system',
+ }),
+ );
+
+ if (complete) {
+ lines.push(
+ JSON.stringify({
+ duration_ms: 0,
+ is_error: false,
+ result: textOfContent(lastAssistant?.message?.content),
+ session_id: sessionId,
+ subtype: 'success',
+ type: 'result',
+ ...(lastUsage ? { usage: lastUsage } : {}),
+ }),
+ );
+ }
+ // A cut-off turn gets NO `result` line, mirroring a CLI killed mid-turn: the
+ // pipeline flush marks the dangling tool unsuccessful and the caller closes
+ // the runtime as interrupted, so the replay never drains queued messages or
+ // fires a "run finished" notification — the continuation owns the ending.
+
+ return {
+ complete,
+ lines,
+ promptText: textOfContent(prompt.message?.content),
+ promptTimestamp: typeof prompt.timestamp === 'string' ? prompt.timestamp : undefined,
+ promptUuid: prompt.uuid,
+ recordCount,
+ sessionId,
+ };
+};
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 181bb14146e..73934762020 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -594,6 +594,10 @@ export default {
'The previous Cursor session could not be restored through ACP, so a new conversation has started with fresh context.',
'heteroAgent.resumeReset.resumeFailed':
'The saved Codex thread could not be resumed safely, so a new conversation has started for this topic.',
+ 'heteroAgent.restartRecovery.resumed_one':
+ 'Picked up {{count}} local agent run that the app restart interrupted.',
+ 'heteroAgent.restartRecovery.resumed_other':
+ 'Picked up {{count}} local agent runs that the app restart interrupted.',
'heteroAgent.switchCwd.cancel': 'Cancel',
'heteroAgent.switchCwd.content':
'Agent sessions are pinned to a working directory. Switching will start a new session for this topic — chat messages stay, but the previous session context cannot be resumed.',
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
index a81b82d44ac..4bbf0b8efca 100644
--- a/src/features/Conversation/store/slices/generation/action.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -1805,8 +1805,12 @@ describe('Generation Actions', () => {
}),
);
- // Store is refreshed so the loading bubble shows while the CLI streams.
- expect(mockRefreshMessages).toHaveBeenCalled();
+ // Store is refreshed so the loading bubble shows while the CLI streams —
+ // scoped to the run's own context, not whatever topic happens to be
+ // active (restart recovery runs this for background topics).
+ expect(mockRefreshMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'session-1', topicId: 'topic-1' }),
+ );
// The executor receives the new assistant row id, the original user
// message's images, the original prompt, and the child hetero op id.
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index dddee59d19a..18d84aed9c8 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -3,6 +3,7 @@ import { HETERO_CONTINUE_PROMPT, LOADING_FLAT } from '@lobechat/const';
import { shouldDropUnsupportedClaudeAssistantPrefill } from '@lobechat/model-runtime/providers/anthropic/modelId';
import type {
ChatImageItem,
+ ChatTopic,
ConversationContext,
HeterogeneousProviderConfig,
} from '@lobechat/types';
@@ -40,6 +41,7 @@ import {
} from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';
import {
mergeAgentRuntimeInitialContexts,
resolveActiveTopicDocumentInitialContext,
@@ -110,7 +112,7 @@ const settleGenerationEntry = (
* mounted. No-ops for authors, members-with-resolved-answers, and non-workspace
* agents; a failed fetch falls back to authorship for this run.
*/
-const ensureEffectiveAgencyAccess = async (agentId: string) => {
+export const ensureEffectiveAgencyAccess = async (agentId: string) => {
const agentState = getAgentStoreState();
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
await ensureAgentManagementAccess({
@@ -122,7 +124,7 @@ const ensureEffectiveAgencyAccess = async (agentId: string) => {
});
};
-const getEffectiveAgencyConfig = (agentId: string) => {
+export const getEffectiveAgencyConfig = (agentId: string) => {
const agentState = getAgentStoreState();
const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;
const agent = agentByIdSelectors.getAgentById(agentId)(agentState);
@@ -174,14 +176,16 @@ const getEffectiveAgencyConfig = (agentId: string) => {
* over the agent-level default, so regenerate/continue stay on the same project
* as the original turn.
*/
-const resolveHeteroRunContext = (
+export const resolveHeteroRunContext = (
chatStore: ReturnType<typeof useChatStore.getState>,
context: ConversationContext,
agentId: string,
+ /** Topic row when the caller already holds it (the paginated store may not). */
+ topicOverride?: ChatTopic,
) => {
- const topic = context.topicId
- ? topicSelectors.getTopicById(context.topicId)(chatStore)
- : undefined;
+ const topic =
+ topicOverride ??
+ (context.topicId ? topicSelectors.getTopicById(context.topicId)(chatStore) : undefined);
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
const agentState = getAgentStoreState();
const desktopContext = globalAgentContextManager.getContext();
@@ -224,7 +228,7 @@ const resolveHeteroRunContext = (
* `execHeterogeneousAgent` op as a child of the caller's parent op so Stop
* cancels the executor without killing the parent op early.
*/
-const runHeterogeneousFromExistingMessage = async (
+export const runHeterogeneousFromExistingMessage = async (
chatStore: ReturnType<typeof useChatStore.getState>,
params: {
context: ConversationContext;
@@ -234,23 +238,55 @@ const runHeterogeneousFromExistingMessage = async (
parentMessageId: string;
parentOperationId: string;
prompt: string;
+ /**
+ * Replay the topic's on-disk CLI transcript into this row instead of
+ * spawning the CLI (desktop restart recovery). The saved session id must
+ * resolve, or there is nothing to read.
+ */
+ replayTranscript?: boolean;
+ /** Claude profile root the interrupted run's transcript was written under. */
+ replayTranscriptConfigDir?: string;
+ /** ISO spawn time of the interrupted run; pins the replay to that run's own turn. */
+ replayTranscriptStartedAt?: string;
+ /** Topic row when the caller already holds it (not necessarily in the paginated store). */
+ topic?: ChatTopic;
},
-): Promise<string> => {
- const { context, heterogeneousProvider, imageList, parentMessageId, parentOperationId, prompt } =
- params;
+): Promise<{
+ assistantMessageId: string;
+ replayComplete?: boolean;
+ /** The executor persisted a terminal error instead of throwing. */
+ terminalError?: boolean;
+}> => {
+ const {
+ context,
+ heterogeneousProvider,
+ imageList,
+ parentMessageId,
+ parentOperationId,
+ prompt,
+ replayTranscript,
+ replayTranscriptConfigDir,
+ replayTranscriptStartedAt,
+ topic: topicOverride,
+ } = params;
const agentId = context.agentId;
if (!agentId) throw new Error('agentId is required for heterogeneous agent');
await ensureEffectiveAgencyAccess(agentId);
const { cwdChanged, reason, resumeBindingKey, resumeSessionId, workingDirectory } =
- resolveHeteroRunContext(chatStore, context, agentId);
+ resolveHeteroRunContext(chatStore, context, agentId, topicOverride);
+ if (replayTranscript && !resumeSessionId) {
+ throw new Error('Transcript replay needs a resumable CLI session on the topic');
+ }
if (cwdChanged) toast.info(t('heteroAgent.resumeReset.cwdChanged', { ns: 'chat' }));
else if (reason === 'binding_changed')
toast.info(t('heteroAgent.resumeReset.bindingChanged', { ns: 'chat' }));
- const topicPin = context.topicId
- ? topicSelectors.getTopicHeteroPinById(context.topicId)(chatStore)
- : undefined;
+ const topicPin =
+ (topicOverride ? resolveTopicHeteroPin(topicOverride) : undefined) ??
+ (context.topicId
+ ? topicSelectors.getTopicHeteroPinById(context.topicId)(chatStore)
+ : undefined);
const effectiveHeterogeneousProvider = applyTopicModelToHeterogeneousProvider(
heterogeneousProvider,
topicPin,
@@ -270,7 +306,11 @@ const runHeterogeneousFromExistingMessage = async (
// Pull the new row into the store so the loading bubble is visible while
// the executor runs (the executor only dispatches updates, not creates).
- await chatStore.refreshMessages();
+ // Scoped to THIS context: restart recovery runs this for a topic the user
+ // may not be looking at, and an unscoped refresh would hit the active topic
+ // instead — leaving the new row out of the store, so every step the executor
+ // chains under it renders as an orphan group.
+ await chatStore.refreshMessages(context);
const { operationId: heteroOpId } = chatStore.startOperation({
context,
@@ -283,19 +323,26 @@ const runHeterogeneousFromExistingMessage = async (
const { executeHeterogeneousAgent } =
await import('@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor');
- await executeHeterogeneousAgent(() => useChatStore.getState(), {
+ const outcome = await executeHeterogeneousAgent(() => useChatStore.getState(), {
assistantMessageId: assistantMsg.id,
context,
heterogeneousProvider: effectiveHeterogeneousProvider,
imageList: imageList?.length ? imageList : undefined,
message: prompt,
operationId: heteroOpId,
+ ...(replayTranscript
+ ? { replayTranscript: true, replayTranscriptConfigDir, replayTranscriptStartedAt }
+ : {}),
resumeBindingKey,
resumeSessionId,
workingDirectory,
});
- return assistantMsg.id;
+ return {
+ assistantMessageId: assistantMsg.id,
+ replayComplete: outcome?.replay?.complete,
+ terminalError: outcome?.terminalError,
+ };
};
export interface HeteroContinuationScheduleParams {
diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/index.tsx b/src/features/Electron/HeterogeneousAgent/RestartRecovery/index.tsx
new file mode 100644
index 00000000000..d90087ac6ae
--- /dev/null
+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/index.tsx
@@ -0,0 +1,44 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { memo, useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserStore } from '@/store/user';
+
+import { recoverInterruptedHeteroRuns } from './recoverInterruptedRuns';
+
+/**
+ * Render-less. Once the signed-in user state is ready, asks desktop main for
+ * the local CLI runs the previous process left in flight and picks them up
+ * (transcript replay, then `--resume` when the turn was cut off). Runs once
+ * per renderer boot: main hands the ledger over exactly once, so a second
+ * call would find nothing anyway.
+ */
+const RestartRecovery = memo(() => {
+ const { t } = useTranslation('chat');
+ const isReady = useUserStore((s) => s.isUserStateInit && !!s.isSignedIn);
+ const startedRef = useRef(false);
+
+ useEffect(() => {
+ if (!isReady || startedRef.current) return;
+ startedRef.current = true;
+
+ void recoverInterruptedHeteroRuns()
+ .then((results) => {
+ const recovered = results.filter(
+ (result) => result.outcome === 'replayed' || result.outcome === 'resumed',
+ ).length;
+ if (recovered > 0) {
+ toast.info(t('heteroAgent.restartRecovery.resumed', { count: recovered }));
+ }
+ })
+ .catch((error) => {
+ console.error('[restartRecovery] failed:', error);
+ });
+ }, [isReady, t]);
+
+ return null;
+});
+
+RestartRecovery.displayName = 'HeteroRestartRecovery';
+
+export default RestartRecovery;
diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts
new file mode 100644
index 00000000000..6ae1231542a
--- /dev/null
+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts
@@ -0,0 +1,688 @@
+import { HETERO_RESTART_CONTINUE_PROMPT } from '@lobechat/const';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { recoverInterruptedHeteroRuns } from './recoverInterruptedRuns';
+
+const mockListInterruptedRuns = vi.fn();
+const mockProbeTranscriptReplay = vi.fn();
+const mockReleaseInterruptedRun = vi.fn(async (..._args: unknown[]) => {});
+vi.mock('@/services/electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: {
+ listInterruptedRuns: (...args: unknown[]) => mockListInterruptedRuns(...args),
+ probeTranscriptReplay: (...args: unknown[]) => mockProbeTranscriptReplay(...args),
+ releaseInterruptedRun: (...args: unknown[]) => mockReleaseInterruptedRun(...args),
+ },
+}));
+
+const mockGetTopicDetail = vi.fn();
+vi.mock('@/services/topic', () => ({
+ topicService: { getTopicDetail: (...args: unknown[]) => mockGetTopicDetail(...args) },
+}));
+
+const mockGetMessages = vi.fn();
+const mockRemoveMessages = vi.fn();
+vi.mock('@/services/message', () => ({
+ messageService: {
+ getMessages: (...args: unknown[]) => mockGetMessages(...args),
+ removeMessages: (...args: unknown[]) => mockRemoveMessages(...args),
+ },
+}));
+
+const mockGetAgentConfigById = vi.fn();
+vi.mock('@/services/agent', () => ({
+ agentService: { getAgentConfigById: (...args: unknown[]) => mockGetAgentConfigById(...args) },
+}));
+
+const mockRunHetero = vi.fn();
+const mockEnsureAccess = vi.fn(async (..._args: unknown[]) => {});
+const mockGetAgencyConfig = vi.fn();
+const mockResolveRunContext = vi.fn();
+vi.mock('@/features/Conversation/store/slices/generation/action', () => ({
+ ensureEffectiveAgencyAccess: (...args: unknown[]) => mockEnsureAccess(...args),
+ getEffectiveAgencyConfig: (...args: unknown[]) => mockGetAgencyConfig(...args),
+ resolveHeteroRunContext: (...args: unknown[]) => mockResolveRunContext(...args),
+ runHeterogeneousFromExistingMessage: (...args: unknown[]) => mockRunHetero(...args),
+}));
+
+const agentState = { agentMap: {} as Record<string, any> };
+const mockAgentSetState = vi.fn((...args: any[]) => {
+ const updater = args[0];
+ Object.assign(agentState, typeof updater === 'function' ? updater(agentState) : updater);
+});
+vi.mock('@/store/agent', () => ({
+ useAgentStore: {
+ getState: () => agentState,
+ setState: (...args: unknown[]) => mockAgentSetState(...args),
+ },
+}));
+
+const chatStore = {
+ completeOperation: vi.fn(),
+ failOperation: vi.fn(),
+ refreshMessages: vi.fn(async (..._args: unknown[]) => {}),
+ replaceMessages: vi.fn(),
+ startOperation: vi.fn(() => ({ operationId: 'wrap-op' })),
+ updateTopicMetadata: vi.fn(async (..._args: unknown[]) => {}),
+ updateTopicStatus: vi.fn(async () => {}),
+};
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => chatStore },
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ getActiveWorkspaceId: () => 'ws-1',
+}));
+
+vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: { userId: () => 'user-1' },
+}));
+
+const provider = { command: 'claude', type: 'claude-code' as const };
+const run = {
+ agentId: 'agent-1',
+ agentType: 'claude-code',
+ ipcSessionId: 'ipc-1',
+ operationId: 'op-1',
+ startedAt: '2026-09-21T02:00:00.000Z',
+ topicId: 'topic-1',
+};
+const topic = {
+ id: 'topic-1',
+ metadata: { heteroSessionIdByWorkingDirectory: { '/repo': 'cc-1' }, workingDirectory: '/repo' },
+ status: 'running',
+};
+const messages = [
+ { content: 'earlier', createdAt: 100, id: 'u0', role: 'user' },
+ { content: 'earlier answer', createdAt: 110, id: 'a0', parentId: 'u0', role: 'assistant' },
+ { content: 'do the thing', createdAt: 200, id: 'u1', role: 'user' },
+ { content: 'partial', createdAt: 210, id: 'a1', parentId: 'u1', role: 'assistant' },
+ { content: '', createdAt: 220, id: 't1', parentId: 'a1', role: 'tool' },
+ // subagent thread rows are not touched
+ { content: 'sub', createdAt: 230, id: 's1', role: 'assistant', threadId: 'thread-1' },
+];
+
+describe('recoverInterruptedHeteroRuns', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ agentState.agentMap = {};
+ mockListInterruptedRuns.mockResolvedValue([run]);
+ mockGetTopicDetail.mockResolvedValue(topic);
+ mockProbeTranscriptReplay.mockResolvedValue({ available: true, complete: true });
+ mockGetMessages.mockResolvedValue(messages);
+ mockGetAgentConfigById.mockResolvedValue({
+ agencyConfig: { heterogeneousProvider: provider },
+ id: 'agent-1',
+ });
+ mockGetAgencyConfig.mockReturnValue({
+ agencyConfig: { heterogeneousProvider: provider },
+ });
+ // Mirror the real resolver: it reads the (possibly just-patched) topic.
+ mockResolveRunContext.mockImplementation((...args: any[]) => {
+ const topicArg = args[3];
+ const cwd = topicArg?.metadata?.workingDirectory ?? '/repo';
+ return {
+ cwdChanged: false,
+ resumeSessionId: topicArg?.metadata?.heteroSessionIdByWorkingDirectory?.[cwd],
+ workingDirectory: cwd,
+ };
+ });
+ });
+
+ it('asks main only for runs of the user and workspace it is in', async () => {
+ // Topic reads are scoped to both, so a run recorded elsewhere must stay on
+ // the ledger rather than resolve as a missing topic and be consumed.
+ mockListInterruptedRuns.mockResolvedValue([]);
+
+ await recoverInterruptedHeteroRuns();
+
+ expect(mockListInterruptedRuns).toHaveBeenCalledWith({
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('does nothing when the ledger is empty', async () => {
+ mockListInterruptedRuns.mockResolvedValue([]);
+
+ expect(await recoverInterruptedHeteroRuns()).toEqual([]);
+ expect(mockGetTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('replaces the interrupted turn with a transcript replay and stops when the turn finished', async () => {
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
+ // Cold agent store: the config is fetched and seeded before reading agency config.
+ expect(mockGetAgentConfigById).toHaveBeenCalledWith('agent-1');
+ expect(agentState.agentMap['agent-1']).toBeDefined();
+ expect(mockEnsureAccess).toHaveBeenCalledWith('agent-1');
+ // The transcript is probed with the topic's own resume identity first.
+ expect(mockProbeTranscriptReplay).toHaveBeenCalledWith({
+ agentType: 'claude-code',
+ configDir: undefined,
+ cwd: '/repo',
+ // Pins the transcript's last turn to the prompt this run was given.
+ expectedPrompt: 'do the thing',
+ notBefore: run.startedAt,
+ sessionId: 'cc-1',
+ });
+ // The probe identity comes from the resolver the run itself uses.
+ expect(mockResolveRunContext).toHaveBeenCalled();
+ expect(chatStore.updateTopicMetadata).not.toHaveBeenCalled();
+ // Only the interrupted turn's own rows go; earlier turns and thread rows stay.
+ expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ });
+ // The surviving rows are seeded into the store before the run, so the user
+ // turn renders while the topic's own fetch is gated off by the running op.
+ expect(chatStore.replaceMessages).toHaveBeenCalledWith(
+ messages.filter((m) => m.id !== 'a1' && m.id !== 't1'),
+ { action: 'restartRecovery', context: { agentId: 'agent-1', topicId: 'topic-1' } },
+ );
+ expect(chatStore.refreshMessages).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ });
+ expect(mockRunHetero).toHaveBeenCalledTimes(1);
+ expect(mockRunHetero).toHaveBeenCalledWith(
+ chatStore,
+ expect.objectContaining({
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ heterogeneousProvider: provider,
+ parentMessageId: 'u1',
+ parentOperationId: 'wrap-op',
+ prompt: 'do the thing',
+ replayTranscript: true,
+ // The probe and the replay must read the SAME profile the run used.
+ replayTranscriptConfigDir: undefined,
+ topic,
+ }),
+ );
+ expect(chatStore.completeOperation).toHaveBeenCalledWith('wrap-op');
+ });
+
+ it('chains a --resume continuation onto the replayed tail when the turn was cut off', async () => {
+ mockRunHetero
+ .mockResolvedValueOnce({ assistantMessageId: 'a-new', replayComplete: false })
+ .mockResolvedValueOnce({ assistantMessageId: 'a-cont' });
+ mockGetMessages
+ .mockResolvedValueOnce(messages)
+ .mockResolvedValueOnce([
+ ...messages.slice(0, 3),
+ { content: 'replayed', createdAt: 300, id: 'a-new', parentId: 'u1', role: 'assistant' },
+ { content: '', createdAt: 310, id: 't-new', parentId: 'a-new', role: 'tool' },
+ ]);
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'resumed', topicId: 'topic-1' }]);
+ expect(mockRunHetero).toHaveBeenCalledTimes(2);
+ expect(mockRunHetero.mock.calls[1][1]).toMatchObject({
+ parentMessageId: 'a-new',
+ prompt: HETERO_RESTART_CONTINUE_PROMPT,
+ topic,
+ });
+ expect(mockRunHetero.mock.calls[1][1].replayTranscript).toBeUndefined();
+ expect(chatStore.completeOperation).toHaveBeenCalledWith('wrap-op');
+ });
+
+ it('leaves a topic alone that is no longer running', async () => {
+ mockGetTopicDetail.mockResolvedValue({ ...topic, status: 'active' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'skipped', reason: 'not-running', topicId: 'topic-1' }]);
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ expect(mockRunHetero).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ it('settles an unsupported run back to active without touching its rows', async () => {
+ mockListInterruptedRuns.mockResolvedValue([{ ...run, agentType: 'codex' }]);
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'unsupported-run', topicId: 'topic-1' },
+ ]);
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ });
+
+ it('fails the wrapper operation and keeps going when a replay throws', async () => {
+ mockListInterruptedRuns.mockResolvedValue([
+ run,
+ { ...run, ipcSessionId: 'ipc-2', topicId: 'topic-2' },
+ ]);
+ mockGetTopicDetail.mockImplementation(async (id: string) => ({ ...topic, id }));
+ mockRunHetero
+ .mockRejectedValueOnce(new Error('no transcript'))
+ .mockResolvedValueOnce({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'failed', reason: 'no transcript', topicId: 'topic-1' },
+ { outcome: 'replayed', topicId: 'topic-2' },
+ ]);
+ expect(chatStore.failOperation).toHaveBeenCalledWith('wrap-op', {
+ message: 'no transcript',
+ type: 'RestartRecoveryError',
+ });
+ });
+
+ it('keeps the persisted rows and settles the topic when no transcript can be replayed', async () => {
+ mockProbeTranscriptReplay.mockResolvedValue({ available: false, reason: 'gone' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'no-transcript: gone', topicId: 'topic-1' },
+ ]);
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ expect(mockRunHetero).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('restores the resume metadata from the ledger when the topic write was lost', async () => {
+ mockListInterruptedRuns.mockResolvedValue([
+ {
+ ...run,
+ agentSessionId: 'cc-from-ledger',
+ bindingKey: 'provider:openai-compatible#1',
+ configDir: '/profile',
+ cwd: '/repo',
+ },
+ ]);
+ mockGetTopicDetail.mockResolvedValue({ ...topic, metadata: { workingDirectory: '/repo' } });
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
+ // The binding key travels with the session id: main drops a provider-bound
+ // resume whose key does not match the binding it resolves, and the replay
+ // then has no session to read.
+ expect(chatStore.updateTopicMetadata).toHaveBeenCalledWith('topic-1', {
+ heteroSessionBindingKey: 'provider:openai-compatible#1',
+ heteroSessionBindingKeyByWorkingDirectory: { '/repo': 'provider:openai-compatible#1' },
+ heteroSessionId: 'cc-from-ledger',
+ heteroSessionIdByWorkingDirectory: { '/repo': 'cc-from-ledger' },
+ workingDirectory: '/repo',
+ });
+ expect(mockProbeTranscriptReplay).toHaveBeenCalledWith({
+ agentType: 'claude-code',
+ configDir: '/profile',
+ cwd: '/repo',
+ expectedPrompt: 'do the thing',
+ notBefore: run.startedAt,
+ sessionId: 'cc-from-ledger',
+ });
+ // The run itself sees the patched topic so resume resolves from it, and the
+ // replay reads the profile the interrupted run actually wrote under.
+ expect(mockRunHetero.mock.calls[0][1].topic.metadata).toMatchObject({
+ heteroSessionIdByWorkingDirectory: { '/repo': 'cc-from-ledger' },
+ });
+ expect(mockRunHetero.mock.calls[0][1].replayTranscriptConfigDir).toBe('/profile');
+ });
+
+ it('settles a topic still marked running when the replay throws before the executor owns it', async () => {
+ mockRunHetero.mockRejectedValueOnce(new Error('createMessage failed'));
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'failed', reason: 'createMessage failed', topicId: 'topic-1' },
+ ]);
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('leaves the status alone when the executor already wrote its own terminal state', async () => {
+ mockRunHetero.mockRejectedValueOnce(new Error('cli exit 1'));
+ mockGetTopicDetail
+ .mockResolvedValueOnce(topic)
+ .mockResolvedValueOnce({ ...topic, status: 'failed' });
+
+ await recoverInterruptedHeteroRuns();
+
+ expect(chatStore.updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ it('recovers a topic left awaiting human input', async () => {
+ // AskUserQuestion parks the topic as waitingForHuman; the restart killed
+ // the CLI and its intervention bridge, and the stale-topic watchdog only
+ // looks at `running`, so nothing else would ever reset it.
+ mockGetTopicDetail.mockResolvedValue({ ...topic, status: 'waitingForHuman' });
+ mockProbeTranscriptReplay.mockResolvedValue({ available: true, complete: false });
+ mockRunHetero
+ .mockResolvedValueOnce({ assistantMessageId: 'a-new', replayComplete: false })
+ .mockResolvedValueOnce({ assistantMessageId: 'a-cont' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'resumed', topicId: 'topic-1' }]);
+ expect(mockRunHetero).toHaveBeenCalledTimes(2);
+ });
+
+ it('settles a stranded waitingForHuman topic when the replay cannot run', async () => {
+ mockGetTopicDetail.mockResolvedValue({ ...topic, status: 'waitingForHuman' });
+ mockProbeTranscriptReplay.mockResolvedValue({ available: false, reason: 'gone' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'no-transcript: gone', topicId: 'topic-1' },
+ ]);
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it("deletes only the interrupted run's own branch, keeping earlier answers", async () => {
+ // A regenerated turn hangs several assistant branches off one user row.
+ const withBranches = [
+ ...messages.slice(0, 3),
+ // an earlier, completed answer to the same user turn
+ { content: 'first answer', createdAt: 205, id: 'a-old', parentId: 'u1', role: 'assistant' },
+ { content: 'old tool', createdAt: 206, id: 't-old', parentId: 'a-old', role: 'tool' },
+ // the interrupted run's own branch
+ { content: 'partial', createdAt: 210, id: 'a1', parentId: 'u1', role: 'assistant' },
+ { content: '', createdAt: 220, id: 't1', parentId: 'a1', role: 'tool' },
+ ];
+ mockListInterruptedRuns.mockResolvedValue([{ ...run, assistantMessageId: 'a1' }]);
+ mockGetMessages.mockResolvedValue(withBranches);
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
+ expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('leaves the topic alone when another device added a newer assistant branch', async () => {
+ // Regeneration elsewhere does not move the user row's timestamp, so only
+ // the recorded assistant identity catches this takeover.
+ mockListInterruptedRuns.mockResolvedValue([{ ...run, assistantMessageId: 'a1' }]);
+ mockGetMessages.mockResolvedValue([
+ ...messages,
+ { content: 'newer run', createdAt: 900, id: 'a-newer', parentId: 'u1', role: 'assistant' },
+ ]);
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'topic-taken-over', topicId: 'topic-1' },
+ ]);
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ it('does not report a failed continuation as resumed', async () => {
+ // The executor persists a terminal error instead of throwing, so the call
+ // resolving is not success — a toast saying the run was picked up would be
+ // a lie when the CLI never started.
+ mockRunHetero
+ .mockResolvedValueOnce({ assistantMessageId: 'a-new', replayComplete: false })
+ .mockResolvedValueOnce({ assistantMessageId: 'a-cont', terminalError: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ {
+ outcome: 'failed',
+ reason: 'Restart continuation ended on a terminal error',
+ topicId: 'topic-1',
+ },
+ ]);
+ expect(chatStore.completeOperation).not.toHaveBeenCalled();
+ });
+
+ it('does not resume when the replay reported no outcome', async () => {
+ // The executor swallows a replay failure and returns nothing; resuming
+ // would spend a real turn on top of a replay that never happened.
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ {
+ outcome: 'failed',
+ reason: 'Transcript replay reported no outcome',
+ topicId: 'topic-1',
+ },
+ ]);
+ expect(mockRunHetero).toHaveBeenCalledTimes(1);
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('still recovers a topic the stale-run watchdog already flipped to active', async () => {
+ // The watchdog's two-hour sweep only means nobody claimed the run; the
+ // ledger entry proves it never settled, so the partial turn is still owed
+ // a replay.
+ mockListInterruptedRuns.mockResolvedValue([{ ...run, assistantMessageId: 'a1' }]);
+ mockGetTopicDetail.mockResolvedValue({ ...topic, status: 'active' });
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
+ expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('does not settle a topic another device took over, even when the probe fails', async () => {
+ // Ownership is decided before any write: probing the other device's newer
+ // session against our old profile fails, and settling on that would
+ // clobber its live status.
+ mockListInterruptedRuns.mockResolvedValue([{ ...run, assistantMessageId: 'a1' }]);
+ mockGetMessages.mockResolvedValue([
+ ...messages,
+ { content: 'newer run', createdAt: 900, id: 'a-newer', parentId: 'u1', role: 'assistant' },
+ ]);
+ mockProbeTranscriptReplay.mockResolvedValue({ available: false, reason: 'gone' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'topic-taken-over', topicId: 'topic-1' },
+ ]);
+ expect(chatStore.updateTopicStatus).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(mockProbeTranscriptReplay).not.toHaveBeenCalled();
+ });
+
+ it('settles an expired run instead of replaying it', async () => {
+ // Past the replay window the transcript is unusable, but a waitingForHuman
+ // topic would otherwise stay parked forever — the watchdog only sees
+ // `running`.
+ mockListInterruptedRuns.mockResolvedValue([{ ...run, expired: true }]);
+ mockGetTopicDetail.mockResolvedValue({ ...topic, status: 'waitingForHuman' });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'skipped', reason: 'expired', topicId: 'topic-1' }]);
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ expect(mockRunHetero).not.toHaveBeenCalled();
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ });
+
+ it('leaves a topic alone when a newer turn took it over while the app was down', async () => {
+ // Another device started a turn after our run was spawned: its user row is
+ // newer than the ledger entry. Touching it would delete that live run's
+ // output, and settling would clobber its status.
+ mockGetMessages.mockResolvedValue([
+ ...messages,
+ {
+ content: 'newer turn',
+ createdAt: Date.parse(run.startedAt) + 1000,
+ id: 'u2',
+ role: 'user',
+ },
+ ]);
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'topic-taken-over', topicId: 'topic-1' },
+ ]);
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ expect(mockRunHetero).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ it('keeps the rows when the saved session cannot be resumed under the current binding', async () => {
+ // The shared resolver rejects the session (auth binding changed while the
+ // app was down); deleting rows first would lose the output for nothing.
+ mockResolveRunContext.mockReturnValue({
+ cwdChanged: false,
+ reason: 'binding_changed',
+ resumeSessionId: undefined,
+ workingDirectory: '/repo',
+ });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'skipped', reason: 'resume-unavailable', topicId: 'topic-1' },
+ ]);
+ expect(mockProbeTranscriptReplay).not.toHaveBeenCalled();
+ expect(mockRemoveMessages).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('settles the topic when the pre-flight agent load fails', async () => {
+ // The ledger entry is already consumed, so a throw here would otherwise
+ // leave the topic spinning until the stale-topic watchdog runs.
+ mockGetAgentConfigById.mockRejectedValue(new Error('network down'));
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'failed', reason: 'network down', topicId: 'topic-1' }]);
+ expect(chatStore.failOperation).not.toHaveBeenCalled();
+ expect(chatStore.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('recovers each topic once even when the ledger holds duplicate entries', async () => {
+ mockListInterruptedRuns.mockResolvedValue([run, { ...run, ipcSessionId: 'ipc-later' }]);
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toHaveLength(1);
+ expect(mockRunHetero).toHaveBeenCalledTimes(1);
+ // The superseded entry is spent too, or it would be retried every launch.
+ expect(mockReleaseInterruptedRun).toHaveBeenCalledWith('ipc-1');
+ expect(mockReleaseInterruptedRun).toHaveBeenCalledWith('ipc-later');
+ });
+
+ it('restores a native binding key when the run had no hosted binding', async () => {
+ mockListInterruptedRuns.mockResolvedValue([
+ { ...run, agentSessionId: 'cc-from-ledger', cwd: '/repo' },
+ ]);
+ mockGetTopicDetail.mockResolvedValue({ ...topic, metadata: { workingDirectory: '/repo' } });
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ await recoverInterruptedHeteroRuns();
+
+ expect(chatStore.updateTopicMetadata).toHaveBeenCalledWith(
+ 'topic-1',
+ expect.objectContaining({ heteroSessionBindingKey: 'native:v1:claude-code' }),
+ );
+ });
+
+ it('probes with the prompt the CLI was actually given', async () => {
+ // The executor strips the `/goal` command before sending, so the
+ // transcript never holds the raw row content — probing with it would
+ // reject the run's own turn as a different one.
+ mockGetMessages.mockResolvedValue([
+ ...messages.slice(0, 2),
+ { content: '/goal ship the report', createdAt: 200, id: 'u1', role: 'user' },
+ ...messages.slice(3),
+ ]);
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ await recoverInterruptedHeteroRuns();
+
+ expect(mockProbeTranscriptReplay).toHaveBeenCalledWith(
+ expect.objectContaining({ expectedPrompt: 'ship the report' }),
+ );
+ });
+
+ it('releases the ledger entry once recovery has an outcome', async () => {
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ await recoverInterruptedHeteroRuns();
+
+ expect(mockReleaseInterruptedRun).toHaveBeenCalledWith('ipc-1');
+ });
+
+ it('keeps the ledger entry when recovery dies before reaching an outcome', async () => {
+ // Main hands entries over as claims precisely for this: the topic is still
+ // mid-run, and the entry is the only thing that can pick it up next launch.
+ mockGetTopicDetail.mockRejectedValue(new Error('renderer went away'));
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([
+ { outcome: 'failed', reason: 'renderer went away', topicId: 'topic-1' },
+ ]);
+ expect(mockReleaseInterruptedRun).not.toHaveBeenCalled();
+ });
+
+ it('recovers its own turn when the desktop clock runs behind the database', async () => {
+ // `startedAt` is stamped by Electron main, message rows by the server. A
+ // desktop a few minutes behind would read this topic's OWN user turn as a
+ // newer takeover; the recorded assistant row settles it without a clock.
+ mockListInterruptedRuns.mockResolvedValue([
+ { ...run, assistantMessageId: 'a1', startedAt: new Date(150).toISOString() },
+ ]);
+ mockRunHetero.mockResolvedValue({ assistantMessageId: 'a-new', replayComplete: true });
+
+ const results = await recoverInterruptedHeteroRuns();
+
+ expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
+ expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ });
+ });
+});
diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts
new file mode 100644
index 00000000000..919db50042a
--- /dev/null
+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts
@@ -0,0 +1,456 @@
+import { stripGoalCommand } from '@lobechat/builtin-tool-goal';
+import { HETERO_RESTART_CONTINUE_PROMPT } from '@lobechat/const';
+import type { ChatTopic, ConversationContext, UIChatMessage } from '@lobechat/types';
+
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import {
+ ensureEffectiveAgencyAccess,
+ getEffectiveAgencyConfig,
+ resolveHeteroRunContext,
+ runHeterogeneousFromExistingMessage,
+} from '@/features/Conversation/store/slices/generation/action';
+import {
+ getHeteroSessionIdForWorkingDirectory,
+ setHeteroSessionBindingKeyForWorkingDirectory,
+ setHeteroSessionIdForWorkingDirectory,
+} from '@/helpers/heteroSessionByWorkingDirectory';
+import { agentService } from '@/services/agent';
+import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';
+import { messageService } from '@/services/message';
+import { topicService } from '@/services/topic';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { getNativeHeteroSessionBindingKey } from '@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume';
+import { getUserStoreState } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+/**
+ * Pick local Claude Code runs back up after the desktop app restarted.
+ *
+ * What a restart leaves behind: the topic still `running`, whatever rows the
+ * renderer flushed before it died, and — on disk — the CLI's own transcript
+ * holding everything the run produced, possibly including a finished answer
+ * the app never saw. Desktop main also keeps a ledger of the runs it spawned
+ * (`listInterruptedRuns`), which is how a run killed HERE is told apart from
+ * one still running on another device.
+ *
+ * Per run: drop the half-persisted assistant rows of the interrupted turn,
+ * replay that turn from the transcript into a fresh row (same pipeline as a
+ * live run, so tools / thinking / usage land as if the app had been watching),
+ * then — only if the transcript shows the turn was cut off — `--resume` the
+ * session with a continuation prompt so the agent finishes the job.
+ */
+
+export type RestartRecoveryOutcome = 'replayed' | 'resumed' | 'skipped' | 'failed';
+
+export interface RestartRecoveryResult {
+ outcome: RestartRecoveryOutcome;
+ reason?: string;
+ topicId?: string;
+}
+
+interface InterruptedRun {
+ agentId?: string;
+ /** CLI-native session id main saw on the stream — the ledger's own copy. */
+ agentSessionId?: string;
+ agentType: string;
+ /** Assistant row the interrupted run streamed into — its branch root. */
+ assistantMessageId?: string;
+ /** Hosted provider binding the run's CLI session belongs to, when it had one. */
+ bindingKey?: string;
+ configDir?: string;
+ cwd?: string;
+ /** Too old to replay; hand the topic a status-only cleanup and stop there. */
+ expired?: boolean;
+ ipcSessionId: string;
+ /** ISO timestamp of the spawn — the ownership token for the topic's latest turn. */
+ startedAt?: string;
+ topicId?: string;
+}
+
+/**
+ * Topic states a restart can leave stranded. `running` is the ordinary one;
+ * `waitingForHuman` is written when the CLI raised an AskUserQuestion, and a
+ * restart kills both the CLI and its intervention bridge — nothing else ever
+ * resets it, because the stale-topic watchdog only looks at `running`.
+ */
+const isInterruptedTopicStatus = (status: string | null | undefined): boolean =>
+ status === 'running' || status === 'waitingForHuman';
+
+const toTime = (value: UIChatMessage['createdAt']): number => {
+ const time = typeof value === 'number' ? value : new Date(value as any).getTime();
+ return Number.isFinite(time) ? time : 0;
+};
+
+/**
+ * The run's own branch: its assistant row plus everything hanging off it. A
+ * regenerated turn keeps several assistant branches under one user row, and
+ * only this one belongs to the interrupted run.
+ */
+const collectBranch = (messages: UIChatMessage[], rootId: string): string[] => {
+ const childrenByParent = new Map<string, UIChatMessage[]>();
+ for (const message of messages) {
+ if (!message.parentId) continue;
+ const siblings = childrenByParent.get(message.parentId) ?? [];
+ siblings.push(message);
+ childrenByParent.set(message.parentId, siblings);
+ }
+
+ const ids: string[] = [];
+ const queue = [rootId];
+ const seen = new Set<string>();
+ while (queue.length > 0) {
+ const id = queue.shift()!;
+ if (seen.has(id)) continue;
+ seen.add(id);
+ ids.push(id);
+ for (const child of childrenByParent.get(id) ?? []) queue.push(child.id);
+ }
+ return ids;
+};
+
+/** Rows on the topic's main chain, oldest first. Subagent threads are left alone. */
+const mainChainOf = (messages: UIChatMessage[]): UIChatMessage[] =>
+ messages
+ .filter((message) => !message.threadId)
+ .sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt));
+
+/**
+ * The agent store is filled by SWR hooks as screens mount; at boot the agent
+ * of a background topic is usually not there yet, and the agency config
+ * (which CLI, which auth) lives on it.
+ */
+const ensureAgentLoaded = async (agentId: string): Promise<void> => {
+ if (useAgentStore.getState().agentMap[agentId]?.agencyConfig) return;
+ const config = await agentService.getAgentConfigById(agentId);
+ if (!config) throw new Error(`Agent ${agentId} not found`);
+ useAgentStore.setState(
+ (state) => ({ agentMap: { ...state.agentMap, [agentId]: config } }),
+ false,
+ 'restartRecovery/ensureAgentLoaded',
+ );
+};
+
+const recoverRun = async (run: InterruptedRun): Promise<RestartRecoveryResult> => {
+ const { agentId, topicId } = run;
+ if (!agentId || !topicId) return { outcome: 'skipped', reason: 'missing-context', topicId };
+
+ const topic = await topicService.getTopicDetail(topicId);
+ if (!topic) return { outcome: 'skipped', reason: 'topic-missing', topicId };
+
+ // `active` counts too, but only with a recorded assistant row to verify
+ // ownership against: the stale-run watchdog flips an unclaimed topic there
+ // after two hours, and its sweep means nobody picked the run up — not that it
+ // finished. Every other status is somebody's decision (archived, failed,
+ // scheduled, read) and is left alone.
+ const claimable =
+ isInterruptedTopicStatus(topic.status) ||
+ (topic.status === 'active' && !!run.assistantMessageId);
+ if (!claimable) return { outcome: 'skipped', reason: 'not-running', topicId };
+
+ const chatStore = useChatStore.getState();
+ const settle = () => chatStore.updateTopicStatus({ agentId, status: 'active', topicId });
+ const context: ConversationContext = { agentId, topicId };
+
+ // Ownership comes before ANY write or settling exit. Another device may be
+ // running this topic right now, and settling it — or patching its metadata —
+ // would clobber a live run even though no rows get deleted.
+ const allMessages = await messageService.getMessages(context);
+ const mainChain = mainChainOf(allMessages);
+
+ // The run's own assistant row, when it lived long enough to persist one.
+ // Ownership is then decided between rows that all carry the SAME clock (the
+ // database's): comparing a server timestamp against the local spawn time
+ // would read this topic's own user turn as a takeover on a desktop whose
+ // clock runs behind the server.
+ const ownRoot = run.assistantMessageId
+ ? mainChain.find((message) => message.id === run.assistantMessageId)
+ : undefined;
+ const ownBranch = ownRoot ? new Set(collectBranch(mainChain, ownRoot.id)) : undefined;
+
+ // Prefer the user row our own branch hangs off; only a run that never got a
+ // row of its own has to guess at the topic's last turn.
+ const ownUserTurn = ownRoot
+ ? mainChain.find((message) => message.id === ownRoot.parentId && message.role === 'user')
+ : undefined;
+ const userTurn = ownUserTurn ?? mainChain.findLast((message) => message.role === 'user');
+
+ if (ownBranch) {
+ // Rows are ordered by one clock, so the newest row on the main chain says
+ // it all: anything outside our branch means the topic moved on without us.
+ const newest = mainChain.at(-1);
+ if (newest && !ownBranch.has(newest.id)) {
+ return { outcome: 'skipped', reason: 'topic-taken-over', topicId };
+ }
+ } else {
+ // Nothing of ours on the topic to anchor against. The spawn time is all
+ // that is left — a cross-clock comparison, so it is only trusted to spot a
+ // user turn that clearly postdates the run.
+ const startedAt = run.startedAt ? Date.parse(run.startedAt) : Number.NaN;
+ if (userTurn && Number.isFinite(startedAt) && toTime(userTurn.createdAt) > startedAt) {
+ return { outcome: 'skipped', reason: 'topic-taken-over', topicId };
+ }
+ }
+
+ // A regeneration hangs a NEW assistant branch off the SAME user row. When the
+ // row we recorded is gone but another branch stands in its place, that branch
+ // is somebody else's answer.
+ const branchRoots = userTurn
+ ? mainChain
+ .filter((message) => message.parentId === userTurn.id && message.role !== 'user')
+ .sort((a, b) => toTime(a.createdAt) - toTime(b.createdAt))
+ : [];
+ const newestRoot = branchRoots.at(-1);
+ if (run.assistantMessageId && !ownRoot && newestRoot) {
+ return { outcome: 'skipped', reason: 'topic-taken-over', topicId };
+ }
+
+ // Past the replay window. The transcript is too stale to reproduce, but the
+ // topic is still parked mid-run with nobody left to release it — and the
+ // stale-run watchdog only ever looks at `running`.
+ if (run.expired) {
+ await settle();
+ return { outcome: 'skipped', reason: 'expired', topicId };
+ }
+
+ if (run.agentType !== 'claude-code') {
+ await settle();
+ return { outcome: 'skipped', reason: 'unsupported-run', topicId };
+ }
+
+ // Every failure from here on has to put the topic down: returning a result
+ // releases the ledger entry, so nothing will retry this run and the topic
+ // would otherwise spin until the two-hour stale watchdog notices.
+ let operationId: string | undefined;
+ try {
+ await ensureAgentLoaded(agentId);
+ await ensureEffectiveAgencyAccess(agentId);
+ const heterogeneousProvider =
+ getEffectiveAgencyConfig(agentId).agencyConfig?.heterogeneousProvider;
+ if (heterogeneousProvider?.type !== 'claude-code') {
+ await settle();
+ return { outcome: 'skipped', reason: 'provider-mismatch', topicId };
+ }
+
+ // The topic's resume metadata is written by the renderer as the stream
+ // starts; a quit that lands between main patching the ledger and that write
+ // settling leaves the topic without a session id even though the ledger
+ // knows it. Restore the write from the ledger so the run stays resumable.
+ const ledgerCwd = topic.metadata?.workingDirectory ?? run.cwd;
+ if (
+ run.agentSessionId &&
+ ledgerCwd &&
+ !getHeteroSessionIdForWorkingDirectory(topic.metadata, ledgerCwd)
+ ) {
+ // The binding key travels WITH the session id: a provider-bound resume
+ // whose key does not match the binding main resolves is dropped there,
+ // and the replay then has no session to read. Both were written by the
+ // same lost update, so both are restored.
+ const bindingKey = run.bindingKey ?? getNativeHeteroSessionBindingKey(run.agentType);
+ const patch = {
+ heteroSessionBindingKey: bindingKey,
+ heteroSessionBindingKeyByWorkingDirectory: setHeteroSessionBindingKeyForWorkingDirectory(
+ topic.metadata,
+ ledgerCwd,
+ bindingKey,
+ ),
+ heteroSessionId: run.agentSessionId,
+ heteroSessionIdByWorkingDirectory: setHeteroSessionIdForWorkingDirectory(
+ topic.metadata,
+ ledgerCwd,
+ run.agentSessionId,
+ ),
+ workingDirectory: ledgerCwd,
+ };
+ await chatStore.updateTopicMetadata(topicId, patch);
+ topic.metadata = { ...topic.metadata, ...patch };
+ }
+
+ // Ask the SAME resolver the run itself will use. Comparing adapter types is
+ // not enough: an auth binding the user changed while the app was down makes
+ // the saved session unresumable, and finding that out after the rows are
+ // gone would lose the output for nothing.
+ const { resumeSessionId, workingDirectory } = resolveHeteroRunContext(
+ chatStore,
+ context,
+ agentId,
+ topic as ChatTopic,
+ );
+ if (!resumeSessionId) {
+ await settle();
+ return { outcome: 'skipped', reason: 'resume-unavailable', topicId };
+ }
+
+ if (!userTurn) {
+ await settle();
+ return { outcome: 'skipped', reason: 'no-user-turn', topicId };
+ }
+
+ // Nothing is touched until the transcript is known to be readable: the
+ // rows already persisted are the only record of the run when it is not.
+ const probe = await heterogeneousAgentService.probeTranscriptReplay({
+ agentType: run.agentType,
+ configDir: run.configDir,
+ cwd: workingDirectory,
+ // A resumed session shares one transcript, so the last turn on disk may
+ // still be the PREVIOUS one when the restart beat the CLI to recording
+ // this prompt. Replaying that would rewrite the conversation.
+ //
+ // Stripped exactly like the executor strips it before sending: a `/goal`
+ // turn reaches the CLI without its command word, so the raw row content
+ // is not what the transcript recorded.
+ expectedPrompt: stripGoalCommand(userTurn.content),
+ // The CLI cannot have recorded this run's prompt before the run existed,
+ // which is what tells two adjacent prompts apart when their text does not.
+ notBefore: run.startedAt,
+ sessionId: resumeSessionId,
+ });
+ if (!probe.available) {
+ await settle();
+ return { outcome: 'skipped', reason: `no-transcript: ${probe.reason ?? 'unknown'}`, topicId };
+ }
+
+ // Everything the interrupted turn persisted is a partial view of what the
+ // transcript holds in full — replace it rather than try to stitch. Scoped
+ // to the run's own branch: earlier completed answers under the same user
+ // row are somebody's history, not this run's leftovers.
+ const branchRootId = ownRoot?.id ?? newestRoot?.id;
+ const staleIds = branchRootId ? collectBranch(mainChain, branchRootId) : [];
+ if (staleIds.length > 0) await messageService.removeMessages(staleIds, context);
+
+ // Seed the in-memory list ourselves: while the recovery op is running, the
+ // topic's own fetch is gated off (a mid-run snapshot would clobber streamed
+ // rows), so without this the surviving user turn never reaches the view
+ // and only the rows the executor dispatches would render.
+ const staleIdSet = new Set(staleIds);
+ chatStore.replaceMessages(
+ allMessages.filter((message) => !staleIdSet.has(message.id)),
+ { action: 'restartRecovery', context },
+ );
+
+ operationId = chatStore.startOperation({
+ context: { ...context, messageId: userTurn.id },
+ type: 'regenerate',
+ }).operationId;
+
+ const { replayComplete } = await runHeterogeneousFromExistingMessage(chatStore, {
+ context,
+ heterogeneousProvider,
+ parentMessageId: userTurn.id,
+ parentOperationId: operationId,
+ prompt: userTurn.content,
+ replayTranscript: true,
+ // The transcript sits under the profile the interrupted run used, which
+ // this turn's own account routing may no longer resolve to.
+ replayTranscriptConfigDir: run.configDir,
+ replayTranscriptStartedAt: run.startedAt,
+ topic: topic as ChatTopic,
+ });
+
+ if (replayComplete === true) {
+ chatStore.completeOperation(operationId);
+ return { outcome: 'replayed', topicId };
+ }
+
+ // No outcome at all means the replay never ran: the executor swallowed the
+ // failure and persisted a terminal error. Resuming here would spend a real
+ // turn — and touch the workspace — on top of a replay that did not happen.
+ if (replayComplete !== false) {
+ throw new Error('Transcript replay reported no outcome');
+ }
+
+ // Chain the continuation onto the replayed tail so it grows the same
+ // assistant group instead of opening a new bubble.
+ const tail = mainChainOf(await messageService.getMessages(context)).findLast(
+ (message) => message.role === 'assistant',
+ );
+ const continuation = await runHeterogeneousFromExistingMessage(chatStore, {
+ context,
+ heterogeneousProvider,
+ parentMessageId: tail?.id ?? userTurn.id,
+ parentOperationId: operationId,
+ prompt: HETERO_RESTART_CONTINUE_PROMPT,
+ topic: topic as ChatTopic,
+ });
+ // The executor persists a terminal error rather than throwing, so the call
+ // resolving is not success. Reporting `resumed` here would tell the user a
+ // run was picked up when the CLI never started.
+ if (continuation.terminalError) {
+ throw new Error('Restart continuation ended on a terminal error');
+ }
+ chatStore.completeOperation(operationId);
+ return { outcome: 'resumed', topicId };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (operationId) {
+ chatStore.failOperation(operationId, { message, type: 'RestartRecoveryError' });
+ }
+ // The executor writes its own terminal status once it owns the run, so
+ // only a topic still stuck in flight is put down here.
+ const current = await topicService.getTopicDetail(topicId).catch(() => null);
+ if (isInterruptedTopicStatus(current?.status)) await settle().catch(() => {});
+ return { outcome: 'failed', reason: message, topicId };
+ } finally {
+ // Reconcile with the server snapshot now that nothing is streaming. Only
+ // meaningful once a run actually started; the early exits above never
+ // touched the in-memory list.
+ if (operationId) {
+ await chatStore.refreshMessages({ agentId, topicId }).catch(() => {});
+ }
+ }
+};
+
+/**
+ * Recover every run the previous desktop process left in flight. Runs are
+ * handled one after another: each replay + resume is a full CLI turn, and the
+ * ledger rarely holds more than one or two.
+ */
+export const recoverInterruptedHeteroRuns = async (): Promise<RestartRecoveryResult[]> => {
+ // Scoped to the user AND workspace this renderer is in: topic reads go
+ // through both, so a run recorded elsewhere stays on the ledger until the
+ // launch that owns it. Personal space has no workspace, which is why the
+ // account has to be part of the key.
+ const runs = (await heterogeneousAgentService.listInterruptedRuns({
+ userId: userProfileSelectors.userId(getUserStoreState()),
+ workspaceId: getActiveWorkspaceId() ?? undefined,
+ })) as InterruptedRun[];
+ if (!runs?.length) return [];
+
+ // One recovery per topic; a later entry supersedes an earlier one.
+ const byTopic = new Map<string, InterruptedRun>();
+ const unkeyed: InterruptedRun[] = [];
+ for (const run of runs) {
+ if (!run.topicId) {
+ unkeyed.push(run);
+ continue;
+ }
+ const superseded = byTopic.get(run.topicId);
+ byTopic.set(run.topicId, run);
+ // The newer entry recovers this topic, so the one it replaces is spent —
+ // left claimed, it would be retried at every launch until it runs out.
+ if (superseded) {
+ await heterogeneousAgentService
+ .releaseInterruptedRun(superseded.ipcSessionId)
+ .catch(() => {});
+ }
+ }
+
+ const results: RestartRecoveryResult[] = [];
+ for (const run of [...byTopic.values(), ...unkeyed]) {
+ try {
+ results.push(await recoverRun(run));
+ // Recovery reached an outcome, so the ledger entry has done its job.
+ // It is only released here: main hands entries over as CLAIMS, which is
+ // what lets a crash in the middle of all this be retried at next launch.
+ await heterogeneousAgentService.releaseInterruptedRun(run.ipcSessionId).catch(() => {});
+ } catch (error) {
+ console.error('[restartRecovery] recovery failed:', run.topicId, error);
+ results.push({
+ outcome: 'failed',
+ reason: error instanceof Error ? error.message : String(error),
+ topicId: run.topicId,
+ });
+ }
+ }
+ return results;
+};
diff --git a/src/routes/(main)/_layout/authMount.test.ts b/src/routes/(main)/_layout/authMount.test.ts
index fdb7a4247e8..26f18cb64fb 100644
--- a/src/routes/(main)/_layout/authMount.test.ts
+++ b/src/routes/(main)/_layout/authMount.test.ts
@@ -37,6 +37,7 @@ vi.mock('@/features/Electron/ActiveConversationBridge', nullComponent);
vi.mock('@/features/Electron/ScreenCapture/OverlayCaptureUploader', nullComponent);
vi.mock('@/features/Electron/ScreenCapture/OverlayMessageDispatcher', nullComponent);
vi.mock('@/features/Electron/ScreenCapture/OverlaySnapshotPublisher', nullComponent);
+vi.mock('@/features/Electron/HeterogeneousAgent/RestartRecovery', nullComponent);
vi.mock('@/features/Electron/system/ZoomHUD', nullComponent);
vi.mock('@/features/Electron/titlebar/TabBar/TabCacheBridges', nullComponent);
vi.mock('@/features/Electron/titlebar/TitleBar', nullComponent);
diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsx
index e457c8591a0..0269fb5d281 100644
--- a/src/routes/(main)/_layout/index.desktop.tsx
+++ b/src/routes/(main)/_layout/index.desktop.tsx
@@ -15,6 +15,7 @@ import DesktopLayoutContainer from '@/features/DesktopLayoutContainer';
import DesktopNavigationBridge from '@/features/DesktopNavigationBridge';
import ActiveConversationBridge from '@/features/Electron/ActiveConversationBridge';
import AuthRequiredModal from '@/features/Electron/AuthRequiredModal';
+import HeteroRestartRecovery from '@/features/Electron/HeterogeneousAgent/RestartRecovery';
import OverlayCaptureUploader from '@/features/Electron/ScreenCapture/OverlayCaptureUploader';
import OverlayMessageDispatcher from '@/features/Electron/ScreenCapture/OverlayMessageDispatcher';
import OverlaySnapshotPublisher from '@/features/Electron/ScreenCapture/OverlaySnapshotPublisher';
@@ -93,6 +94,7 @@ const Layout: FC = () => {
<Suspense fallback={null}>
<HotkeyHelperPanel />
<GatewayMuxWarmup />
+ <HeteroRestartRecovery />
<RegisterHotkeys />
<CmdkLazy />
<GlobalApprovalNotification />
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index 534b50bbda6..cf2f232b638 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -38,9 +38,23 @@ class HeterogeneousAgentService {
async sendPrompt(params: {
agentId?: string;
+ /** Assistant row this run streams into — recorded in the in-flight ledger. */
+ assistantMessageId?: string;
+ /** User the run belongs to — recovery is user-scoped. */
+ userId?: string;
+ /** Workspace the run belongs to — recovery is workspace-scoped. */
+ workspaceId?: string;
imageList?: Array<{ id: string; url: string }>;
operationId: string;
prompt: string;
+ /**
+ * Replay the session's on-disk transcript instead of spawning the CLI.
+ * Desktop main resolves with `{ replay: { complete } }`.
+ */
+ replayTranscript?: boolean;
+ /** Claude profile root the transcript was written under (restart recovery). */
+ replayTranscriptConfigDir?: string;
+ replayTranscriptStartedAt?: string;
/** Prior turns used to rebuild a GC-ed Claude Code transcript before `--resume`. */
resumeReplayMessages?: HeteroSessionImportMessage[];
sessionId: string;
@@ -62,6 +76,42 @@ class HeterogeneousAgentService {
return this.ipc.heterogeneousAgent.getSessionInfo({ sessionId });
}
+ /**
+ * Local CLI runs the previous desktop process left in flight, handed over
+ * once. Main reaps any surviving process before returning.
+ */
+ /**
+ * Local CLI runs the previous desktop process left in flight, handed over
+ * once. Only runs belonging to this user AND workspace are released: topic
+ * lookups are scoped to both, so an entry recorded elsewhere has to stay on
+ * the ledger until the launch that owns it.
+ */
+ async listInterruptedRuns(owner: { userId?: string; workspaceId?: string }) {
+ return this.ipc.heterogeneousAgent.listInterruptedRuns(owner);
+ }
+
+ /**
+ * Give a claimed run back once its recovery has an outcome. Until this call
+ * the entry stays on the ledger, so a crash mid-recovery can retry it.
+ */
+ async releaseInterruptedRun(ipcSessionId: string) {
+ return this.ipc.heterogeneousAgent.releaseInterruptedRun({ ipcSessionId });
+ }
+
+ /** Whether the on-disk CLI transcript for a run can be replayed, without spawning anything. */
+ async probeTranscriptReplay(params: {
+ agentType: string;
+ configDir?: string;
+ cwd?: string;
+ /** Prompt of the interrupted run; a transcript ending on a different turn is rejected. */
+ expectedPrompt?: string;
+ /** ISO spawn time of the interrupted run; a turn recorded before it is not this run's. */
+ notBefore?: string;
+ sessionId?: string;
+ }): Promise<{ available: boolean; complete?: boolean; reason?: string }> {
+ return this.ipc.heterogeneousAgent.probeTranscriptReplay(params);
+ }
+
async listModels(
params: ListHeterogeneousAgentModelsParams,
): Promise<HeterogeneousAgentModelCatalog> {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index 279f3b43abb..74ad42206e6 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -2106,6 +2106,42 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(store.completeOperation).toHaveBeenCalledWith('op-1');
});
+ it('forwards replayTranscript to sendPrompt and returns the replay outcome', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+ const ipc = setupIpcCapture();
+ mockSendPrompt.mockImplementationOnce(async (params: any) => {
+ // Desktop main streams the transcript and completes the session itself.
+ ipc.emitRawLine(params.sessionId, ccInit('cc-session-1'));
+ ipc.emitRawLine(params.sessionId, ccText('msg-1', 'replayed answer'));
+ ipc.emitRawLine(params.sessionId, ccResult());
+ ipc.emitComplete(params.sessionId);
+ return { replay: { complete: false, recordCount: 1 } };
+ });
+
+ const outcome = await executeHeterogeneousAgent(get, {
+ ...defaultParams,
+ replayTranscript: true,
+ resumeSessionId: 'cc-session-1',
+ });
+
+ expect(mockSendPrompt).toHaveBeenCalledWith(
+ expect.objectContaining({ replayTranscript: true, sessionId: 'ipc-sess-1' }),
+ );
+ expect(outcome).toEqual({ replay: { complete: false, recordCount: 1 } });
+ });
+
+ it('returns no outcome for a live run', async () => {
+ const store = createMockStore();
+ const get = vi.fn(() => store);
+ setupIpcCapture();
+
+ const outcome = await executeHeterogeneousAgent(get, defaultParams);
+
+ expect(mockSendPrompt.mock.calls[0][0].replayTranscript).toBeUndefined();
+ expect(outcome).toBeUndefined();
+ });
+
it('should forward imageList to heterogeneousAgentService.sendPrompt for Codex runs', async () => {
const store = createMockStore();
const get = vi.fn(() => store);
@@ -2123,6 +2159,9 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(mockSendPrompt).toHaveBeenCalledWith({
agentId: 'agent-1',
+ // Recorded in the in-flight ledger so restart recovery can scope to
+ // this run's own branch and workspace.
+ assistantMessageId: 'ast-initial',
imageList,
operationId: 'op-1',
prompt: 'test prompt',
@@ -2130,6 +2169,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
systemContext: undefined,
// Keys the run's in-app browser session (`topic:<topicId>`) in the main process.
topicId: 'topic-1',
+ workspaceId: undefined,
});
});
@@ -2942,7 +2982,12 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
const store = createMockStore();
const get = vi.fn(() => store);
- await expect(executeHeterogeneousAgent(get, defaultParams)).resolves.toBeUndefined();
+ // The run swallows its failure and persists a terminal error instead
+ // of throwing; the outcome is how a caller (restart recovery) tells
+ // that apart from a run that actually finished.
+ await expect(executeHeterogeneousAgent(get, defaultParams)).resolves.toEqual({
+ terminalError: true,
+ });
expect(mockUpdateMessageError).toHaveBeenCalledWith(
'ast-initial',
@@ -4958,6 +5003,24 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
expect(mockRecordQuotaUsage).not.toHaveBeenCalled();
});
+ it('does NOT ledger usage during a transcript replay', async () => {
+ // A replay re-reads a turn the provider already billed, and its rows get
+ // fresh message ids — the server dedupes by message id, so ledgering
+ // again would double-count the same spend.
+ await runWithEvents(
+ [
+ ccInit(),
+ ccMessageStart('msg_01', 'claude-opus-4-6'),
+ ccAssistant('msg_01', [{ text: 'Hello', type: 'text' }], { model: 'claude-opus-4-6' }),
+ ccMessageDelta({ input_tokens: 100, output_tokens: 20 }),
+ ccResult(),
+ ],
+ { params: { replayTranscript: true, resumeSessionId: 'cc-session-1' } },
+ );
+
+ expect(mockRecordQuotaUsage).not.toHaveBeenCalled();
+ });
+
it('does NOT create a Thread when topicId is missing (non-topic-scoped run)', async () => {
await runWithEvents(
[
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 1466eb1c88e..36bd781ee9c 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -51,6 +51,7 @@ import { createNanoId } from '@lobechat/utils';
import { toast } from '@lobehub/ui/base-ui';
import { t } from 'i18next';
+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import {
removeHeteroSessionBindingKeyForWorkingDirectory,
removeHeteroSessionIdForWorkingDirectory,
@@ -77,8 +78,8 @@ import {
import { type ChatStore, useChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { useUserStore } from '@/store/user';
-import { labPreferSelectors } from '@/store/user/selectors';
+import { getUserStoreState, useUserStore } from '@/store/user';
+import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
@@ -235,6 +236,15 @@ export interface HeterogeneousAgentExecutorParams {
message: string;
operationId: string;
pageSelections?: PageSelection[];
+ /**
+ * Replay the last turn of the topic's on-disk CLI transcript instead of
+ * spawning the CLI (desktop restart recovery). Requires `resumeSessionId`.
+ */
+ replayTranscript?: boolean;
+ /** Claude profile root the interrupted run's transcript was written under. */
+ replayTranscriptConfigDir?: string;
+ /** ISO spawn time of the interrupted run; pins the replay to that run's own turn. */
+ replayTranscriptStartedAt?: string;
/** CC session ID from previous execution in this topic (for --resume) */
resumeBindingKey?: string;
resumeSessionId?: string;
@@ -242,6 +252,21 @@ export interface HeterogeneousAgentExecutorParams {
workingDirectoryConfig?: WorkingDirConfig;
}
+export interface HeterogeneousAgentExecutionOutcome {
+ /** Present when the run was a transcript replay; see `replayTranscript`. */
+ replay?: {
+ /** False when the replayed turn was cut off and a `--resume` continuation is still owed. */
+ complete: boolean;
+ recordCount: number;
+ };
+ /**
+ * The run ended on a terminal error the executor already persisted and did
+ * NOT rethrow. Callers that judge success by the promise resolving — restart
+ * recovery reporting a continuation — have to read this instead.
+ */
+ terminalError?: boolean;
+}
+
const buildLocalHeterogeneousSystemContext = ({
agentSystemContext,
contextSelections,
@@ -467,7 +492,7 @@ const mutateMessageBatch = async (operations: MessageBatchOperation[]): Promise<
export const executeHeterogeneousAgent = async (
get: () => ChatStore,
params: HeterogeneousAgentExecutorParams,
-): Promise<void> => {
+): Promise<HeterogeneousAgentExecutionOutcome | void> => {
const {
heterogeneousProvider: persistedHeterogeneousProvider,
contextSelections,
@@ -477,11 +502,17 @@ export const executeHeterogeneousAgent = async (
message,
operationId,
pageSelections,
+ replayTranscript,
+ replayTranscriptConfigDir,
+ replayTranscriptStartedAt,
resumeBindingKey,
resumeSessionId,
workingDirectory,
workingDirectoryConfig,
} = params;
+ let outcome: HeterogeneousAgentExecutionOutcome | undefined;
+ /** Set by `persistTerminalError`; surfaced on the outcome, see its doc. */
+ let terminalErrorPersisted = false;
const heterogeneousProvider = normalizeHeterogeneousProviderConfig(
persistedHeterogeneousProvider,
@@ -513,6 +544,12 @@ export const executeHeterogeneousAgent = async (
model?: string;
usage: unknown;
}) => {
+ // A replay re-reads a turn the provider already billed, and the rows it
+ // writes carry fresh message ids — so the server's message-id dedupe
+ // cannot recognise them and the same spend would be counted twice,
+ // skewing account routing. The usage still lands on the message for
+ // display; only the ledger write is suppressed.
+ if (replayTranscript) return;
if (
(adapterType !== 'claude-code' && adapterType !== 'codex') ||
(heterogeneousProvider.authMode ?? 'subscription') !== 'subscription' ||
@@ -586,6 +623,7 @@ export const executeHeterogeneousAgent = async (
messageError: ChatMessageError,
options?: { clearContent?: boolean },
) => {
+ terminalErrorPersisted = true;
writeTopicStatus('failed');
get().internal_toggleToolCallingStreaming(mainState.currentAssistantId, undefined);
get().completeOperation(operationId);
@@ -2552,18 +2590,26 @@ export const executeHeterogeneousAgent = async (
: undefined;
// Send the prompt — blocks until process exits
- await heterogeneousAgentService.sendPrompt({
+ const sendResult = await heterogeneousAgentService.sendPrompt({
agentId: context.agentId,
+ assistantMessageId,
imageList,
+ userId: userProfileSelectors.userId(getUserStoreState()),
+ workspaceId: getActiveWorkspaceId() ?? undefined,
operationId,
// `/goal` travels as system-context instructions; the CLI gets only the
// request so its own `/goal` command does not take the message over.
prompt: stripGoalCommand(message),
+ ...(replayTranscript
+ ? { replayTranscript: true, replayTranscriptConfigDir, replayTranscriptStartedAt }
+ : {}),
...(resumeReplayMessages?.length ? { resumeReplayMessages } : {}),
sessionId: ipcRunSessionId,
systemContext: systemContext || undefined,
topicId: context.topicId ?? undefined,
});
+ const replayOutcome = (sendResult as HeterogeneousAgentExecutionOutcome | undefined)?.replay;
+ if (replayOutcome) outcome = { replay: replayOutcome };
await waitForCompletionCallback();
// Persist heterogeneous-agent session id + the cwd it was created under,
@@ -2719,4 +2765,8 @@ export const executeHeterogeneousAgent = async (
if (fallbackPromise) {
await fallbackPromise;
}
+
+ if (terminalErrorPersisted) return { ...outcome, terminalError: true };
+
+ return outcome;
};