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.

πŸ› fix(hetero): fix cloud CC agent execution failures and improve error messages (#15107)

LiJiand15651bbecc0
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1
index 751cab12498..c29cba4c59b 100644
--- a/apps/cli/man/man1/lh.1
+++ b/apps/cli/man/man1/lh.1
@@ -1,6 +1,6 @@
.\" Code generated by `npm run man:generate`; DO NOT EDIT.
.\" Manual command details come from the Commander command tree.
-.TH LH 1 "" "@lobehub/cli 0.0.17" "User Commands"
+.TH LH 1 "" "@lobehub/cli 0.0.18" "User Commands"
.SH NAME
lh \- LobeHub CLI \- manage and connect to LobeHub services
.SH SYNOPSIS
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 7f0f61baf67..5e530716cf1 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@lobehub/cli",
- "version": "0.0.17",
+ "version": "0.0.18",
"type": "module",
"bin": {
"lh": "./dist/index.js",
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index d6d9b287721..7eef0f67f20 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -341,4 +341,160 @@ describe('hetero exec command', () => {
expect(exitSpy).toHaveBeenCalledWith(2);
expect(mockSpawnAgent).not.toHaveBeenCalled();
});
+
+ describe('--resume auto-retry on session-not-found', () => {
+ it('retries without --resume when the error stream event indicates the session is gone', async () => {
+ // First spawn: exits non-zero, emits a resume-not-found error event
+ const resumeNotFoundEvent = {
+ data: { error: 'No conversation found with session ID cc-stale', message: 'No conversation found with session ID cc-stale' },
+ operationId: 'op-r1',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ };
+ mockSpawnAgent
+ .mockReturnValueOnce(
+ createFakeHandle({ events: [resumeNotFoundEvent], exitCode: 1 }),
+ )
+ // Second spawn: succeeds
+ .mockReturnValueOnce(createFakeHandle({ exitCode: 0 }));
+
+ await runCmd([
+ 'hetero', 'exec',
+ '--type', 'claude-code',
+ '--prompt', 'do the thing',
+ '--resume', 'cc-stale',
+ '--operation-id', 'op-r1',
+ ]);
+
+ // Two spawns: first with --resume, retry without
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(2);
+ expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({ resumeSessionId: 'cc-stale' });
+ expect(mockSpawnAgent.mock.calls[1][0]).not.toHaveProperty('resumeSessionId');
+ expect(mockSpawnAgent.mock.calls[1][0].resumeSessionId).toBeUndefined();
+
+ // Final exit code comes from the retry (0 β†’ success)
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ });
+
+ it('retries without --resume when stderr contains a session-not-found message', async () => {
+ // First spawn: exits non-zero with no events, but stderr has the pattern
+ mockSpawnAgent
+ .mockReturnValueOnce(
+ createFakeHandle({
+ exitCode: 1,
+ stderrChunks: ['Error: No conversation found with session ID xyz\n'],
+ }),
+ )
+ .mockReturnValueOnce(createFakeHandle({ exitCode: 0 }));
+
+ await runCmd([
+ 'hetero', 'exec',
+ '--type', 'claude-code',
+ '--prompt', 'continue',
+ '--resume', 'xyz',
+ '--operation-id', 'op-r2',
+ ]);
+
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(2);
+ expect(mockSpawnAgent.mock.calls[1][0].resumeSessionId).toBeUndefined();
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ });
+
+ it('retries without --resume when the error indicates context overflow', async () => {
+ const contextOverflowEvent = {
+ data: { error: 'prompt is too long: 215168 tokens > 200000 maximum', message: 'prompt is too long: 215168 tokens > 200000 maximum' },
+ operationId: 'op-ctx',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ };
+ mockSpawnAgent
+ .mockReturnValueOnce(createFakeHandle({ events: [contextOverflowEvent], exitCode: 1 }))
+ .mockReturnValueOnce(createFakeHandle({ exitCode: 0 }));
+
+ await runCmd([
+ 'hetero', 'exec',
+ '--type', 'claude-code',
+ '--prompt', 'next question',
+ '--resume', 'cc-longctx',
+ '--operation-id', 'op-ctx',
+ ]);
+
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(2);
+ expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({ resumeSessionId: 'cc-longctx' });
+ expect(mockSpawnAgent.mock.calls[1][0].resumeSessionId).toBeUndefined();
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ });
+
+ it('does NOT retry on a non-resume error exit', async () => {
+ // Exit code 1 but no resume-related error message
+ mockSpawnAgent.mockReturnValueOnce(
+ createFakeHandle({ exitCode: 1, stderrChunks: ['rate limit exceeded\n'] }),
+ );
+
+ await runCmd([
+ 'hetero', 'exec',
+ '--type', 'claude-code',
+ '--prompt', 'hi',
+ '--resume', 'cc-valid',
+ ]);
+
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('does NOT retry when --resume is not provided', async () => {
+ const errorEvent = {
+ data: { error: 'No conversation found', message: 'No conversation found' },
+ operationId: 'op-nr',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ };
+ mockSpawnAgent.mockReturnValueOnce(createFakeHandle({ events: [errorEvent], exitCode: 1 }));
+
+ await runCmd([
+ 'hetero', 'exec',
+ '--type', 'claude-code',
+ '--prompt', 'fresh run',
+ '--operation-id', 'op-nr',
+ ]);
+
+ // No --resume β†’ no interception β†’ no retry
+ expect(mockSpawnAgent).toHaveBeenCalledTimes(1);
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('does NOT suppress the resume-error event from JSONL output', async () => {
+ const resumeNotFoundEvent = {
+ data: { error: 'No conversation found with session ID old', message: 'No conversation found with session ID old' },
+ operationId: 'op-jsonl',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ };
+ mockSpawnAgent
+ .mockReturnValueOnce(createFakeHandle({ events: [resumeNotFoundEvent], exitCode: 1 }))
+ .mockReturnValueOnce(createFakeHandle({ exitCode: 0 }));
+
+ await runCmd([
+ 'hetero', 'exec',
+ '--type', 'claude-code',
+ '--prompt', 'do thing',
+ '--resume', 'old',
+ '--render', 'jsonl',
+ ]);
+
+ // The error event is still emitted to JSONL (for observability) even
+ // though it was withheld from the ingester.
+ const lines = stdoutSpy.mock.calls
+ .map((c) => c[0])
+ .filter((s): s is string => typeof s === 'string');
+ const errorLine = lines.find((l) => {
+ try { return JSON.parse(l).type === 'error'; } catch { return false; }
+ });
+ expect(errorLine).toBeDefined();
+ });
+ });
});
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 05bb004f82a..e8db5086448 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -17,6 +17,40 @@ import { TrpcIngestSink } from '../utils/TrpcIngestSink';
const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);
+/**
+ * Patterns that indicate a `--resume <sessionId>` run should be retried
+ * without `--resume`. Two classes of failure:
+ *
+ * 1. Session file missing (sandbox recycled): the container is ephemeral
+ * (~1 h idle TTL), so a new sandbox has an empty `~/.claude/projects/`
+ * and the stored session id is stale.
+ *
+ * 2. Context overflow (long conversation): the resumed session carries all
+ * accumulated history; when the combined token count exceeds the model's
+ * context window the API rejects the request immediately after CC
+ * initialises. Starting fresh (no `--resume`) drops the old history and
+ * lets CC respond to the new prompt alone.
+ *
+ * Checked against:
+ * - `error` stream events emitted by the CC adapter from CC's result event
+ * - Accumulated stderr output (fallback when CC exits without a result event)
+ */
+const RESUME_RETRY_PATTERNS = [
+ // Session file missing β€” sandbox was recycled
+ /no conversation found/i,
+ /session.*not found/i,
+ /conversation.*not found/i,
+ /resume.*not found/i,
+ // Context overflow β€” API rejected the resumed session's accumulated history
+ /prompt.*too long/i,
+ /context.*too long/i,
+ /context window.*exceed/i,
+ /maximum.*context.*length/i,
+] as const;
+
+const looksLikeNeedsRetryWithoutResume = (text: string): boolean =>
+ RESUME_RETRY_PATTERNS.some((p) => p.test(text));
+
interface ExecOptions {
command?: string;
cwd?: string;
@@ -218,95 +252,197 @@ const exec = async (options: ExecOptions): Promise<void> => {
}
const ingester = new BatchIngester(sink);
- // `spawnAgent` is async and can reject DURING image normalization β€” fetch
- // failures, missing local --image paths, decode errors. Surface those as a
- // clean error + exit code instead of an unhandled promise rejection / stack
- // trace, mirroring the validation try/catch above.
- let handle: Awaited<ReturnType<typeof spawnAgent>>;
- try {
- handle = await spawnAgent({
+ /**
+ * Spawn one agent process and stream all its events into `ingester`.
+ *
+ * When `interceptResumeErrors` is true, any `error`-type event whose
+ * message matches `RESUME_RETRY_PATTERNS` is withheld from the
+ * ingester and signals a retry instead. This keeps the server's
+ * operation state clean: no terminal error event is pushed, so the
+ * retry's events land on the same operationId without confusing the
+ * renderer.
+ *
+ * Returns:
+ * code / signal β€” child exit info
+ * sessionId β€” CC session id from `system.init` (undefined on resume failure)
+ * ingestError β€” true when a batch could not be flushed after retries
+ * resumeNotFound β€” true when a resume-not-found error was intercepted
+ * stderrContent β€” accumulated stderr (only when interceptResumeErrors=true)
+ */
+ const runOneAgent = async (
+ spawnOpts: Parameters<typeof spawnAgent>[0],
+ interceptResumeErrors: boolean,
+ ): Promise<{
+ code: number | null;
+ ingestError: boolean;
+ resumeNotFound: boolean;
+ sessionId: string | undefined;
+ signal: NodeJS.Signals | null;
+ stderrContent: string;
+ }> => {
+ // `spawnAgent` is async and can reject DURING image normalization β€” fetch
+ // failures, missing local --image paths, decode errors.
+ let handle: Awaited<ReturnType<typeof spawnAgent>>;
+ try {
+ handle = await spawnAgent(spawnOpts);
+ } catch (err) {
+ log.error('Failed to start agent:', err instanceof Error ? err.message : String(err));
+ process.exit(1);
+ }
+
+ // Always collect stderr β€” used for resume-error detection AND for
+ // surfacing a meaningful error message to the server when CC fails
+ // without emitting a structured error event. Cap at 8 KB so the
+ // collector doesn't grow unboundedly on a chatty run.
+ // Always pipe to process.stderr too so users see auth prompts / warnings.
+ const STDERR_CAP = 8 * 1024;
+ let stderrContent = '';
+ handle.stderr.on('data', (chunk: Buffer) => {
+ if (stderrContent.length < STDERR_CAP) {
+ stderrContent += chunk.toString();
+ }
+ });
+ handle.stderr.pipe(process.stderr);
+
+ // Ctrl-C β†’ SIGINT to the child's process group.
+ // Repeated Ctrl-C escalates to SIGKILL.
+ let interrupted = false;
+ const onSigint = async () => {
+ if (interrupted) {
+ handle.kill('SIGKILL');
+ return;
+ }
+ interrupted = true;
+ handle.kill('SIGINT');
+ if (serverIngest) {
+ try {
+ await ingester.drain();
+ await sink.finish({ result: 'cancelled' });
+ } catch {
+ // best-effort; process is exiting anyway
+ }
+ }
+ };
+ const onSigterm = async () => {
+ handle.kill('SIGTERM');
+ if (serverIngest) {
+ try {
+ await ingester.drain();
+ await sink.finish({ result: 'cancelled' });
+ } catch {
+ // best-effort
+ }
+ }
+ };
+ process.on('SIGINT', onSigint);
+ process.on('SIGTERM', onSigterm);
+
+ // Stream events. Each event is optionally written as JSONL and pushed
+ // into the ingester. When intercepting resume errors, a matching
+ // `error` event is withheld from the ingester and flags a retry instead.
+ let resumeNotFound = false;
+ let ingestError = false;
+ try {
+ for await (const event of handle.events) {
+ if (interceptResumeErrors && event.type === 'error') {
+ const data = event.data as Record<string, unknown> | undefined;
+ const msg = String(data?.message ?? data?.error ?? '');
+ if (looksLikeNeedsRetryWithoutResume(msg)) {
+ resumeNotFound = true;
+ // Emit to JSONL for observability but do NOT push to ingester β€”
+ // we are about to retry; the server must not see a terminal error.
+ if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
+ continue;
+ }
+ }
+ if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
+ ingester.push(event);
+ }
+ } catch (err) {
+ log.error(
+ 'Stream error from agent process:',
+ err instanceof Error ? err.message : String(err),
+ );
+ if (serverIngest) {
+ try {
+ await ingester.drain();
+ await sink.finish({
+ error: { message: String(err), type: 'stream_error' },
+ result: 'error',
+ });
+ } catch {
+ // best-effort
+ }
+ }
+ process.exit(1);
+ } finally {
+ process.off('SIGINT', onSigint);
+ process.off('SIGTERM', onSigterm);
+ }
+
+ const { code, signal } = await handle.exit;
+
+ // Fallback stderr detection: CC may exit non-zero without emitting a
+ // result event (e.g. it writes to stderr and quits immediately).
+ if (
+ interceptResumeErrors &&
+ !resumeNotFound &&
+ code !== 0 &&
+ looksLikeNeedsRetryWithoutResume(stderrContent)
+ ) {
+ resumeNotFound = true;
+ }
+
+ return { code, ingestError, resumeNotFound, sessionId: handle.sessionId, signal, stderrContent };
+ };
+
+ // ─── First run (with --resume if provided) ───────────────────────────────
+
+ const interceptResume = !!options.resume;
+ const first = await runOneAgent(
+ {
agentType: options.type,
command: options.command,
cwd: options.cwd || process.cwd(),
operationId,
prompt: resolved.prompt,
resumeSessionId: options.resume,
- });
- } catch (err) {
- log.error('Failed to start agent:', err instanceof Error ? err.message : String(err));
- process.exit(1);
- }
-
- // Forward the child's stderr to ours so users see CLI errors / warnings
- // (auth prompts, missing-binary errors, etc.) in the terminal.
- handle.stderr.pipe(process.stderr);
-
- // Ctrl-C β†’ SIGINT to the child's process group so the spawned CLI gets a
- // chance to clean up. Repeated Ctrl-C escalates to SIGKILL via the
- // standard "double-tap" pattern most CLIs implement themselves.
- // In server-ingest mode, drain the ingester and call heteroFinish before
- // exiting so the server knows the operation was cancelled.
- let interrupted = false;
- const onSigint = async () => {
- if (interrupted) {
- handle.kill('SIGKILL');
- return;
- }
- interrupted = true;
- handle.kill('SIGINT');
- if (serverIngest) {
- try {
- await ingester.drain();
- await sink.finish({ result: 'cancelled' });
- } catch {
- // best-effort; process is exiting anyway
- }
- }
- };
- process.on('SIGINT', onSigint);
- process.on('SIGTERM', async () => {
- handle.kill('SIGTERM');
- if (serverIngest) {
- try {
- await ingester.drain();
- await sink.finish({ result: 'cancelled' });
- } catch {
- // best-effort
- }
- }
- });
+ },
+ interceptResume,
+ );
- // Stream events. Each event is optionally written as JSONL and always
- // pushed into the ingester (which batches and sends to the server).
- let ingestError = false;
- try {
- for await (const event of handle.events) {
- if (emitJsonl) {
- process.stdout.write(`${JSON.stringify(event)}\n`);
- }
- ingester.push(event);
- }
- } catch (err) {
- log.error('Stream error from agent process:', err instanceof Error ? err.message : String(err));
- if (serverIngest) {
- try {
- await ingester.drain();
- await sink.finish({
- result: 'error',
- error: { message: String(err), type: 'stream_error' },
- });
- } catch {
- // best-effort
- }
- }
- process.exit(1);
- } finally {
- process.off('SIGINT', onSigint);
+ // ─── Auto-retry without --resume when the session cannot be used ─────────
+ //
+ // Two classes of failure detected via `RESUME_RETRY_PATTERNS`:
+ // A. Sandbox recycled: container is ephemeral (~1 h idle TTL); new sandbox
+ // has no CC session files so `--resume <staleId>` is rejected with a
+ // "no conversation found" error.
+ // B. Context overflow: the resumed session carries accumulated history that
+ // pushes the combined token count past the model limit; the API rejects
+ // the call with a "prompt is too long" error.
+ //
+ // In both cases we transparently restart CC without `--resume` so it starts a
+ // fresh session. The server's `heteroSessionId` is updated with the new id,
+ // breaking the stale-session loop.
+ let result = first;
+ if (first.resumeNotFound) {
+ log.info('Resume failed (session not found or context overflow) β€” retrying without --resume');
+ result = await runOneAgent(
+ {
+ agentType: options.type,
+ command: options.command,
+ cwd: options.cwd || process.cwd(),
+ operationId,
+ prompt: resolved.prompt,
+ // No resumeSessionId β€” start fresh
+ },
+ false, // no need to intercept resume errors on a fresh run
+ );
}
- // Pass the child's exit code through. In server-ingest mode, drain the
- // ingester and call heteroFinish before exiting.
- const { code, signal } = await handle.exit;
+ // ─── Drain + finish ───────────────────────────────────────────────────────
+
+ const { code, signal, sessionId } = result;
if (serverIngest) {
try {
@@ -316,21 +452,33 @@ const exec = async (options: ExecOptions): Promise<void> => {
'Failed to flush events to server:',
err instanceof Error ? err.message : String(err),
);
- ingestError = true;
+ result = { ...result, ingestError: true };
}
- const exitedClean = !ingestError && (code === 0 || signal === 'SIGTERM');
+ const exitedClean = !result.ingestError && (code === 0 || signal === 'SIGTERM');
+
+ // When the run failed, pass stderr as the error detail so the server can
+ // surface a useful message instead of the generic "Agent execution failed"
+ // fallback. Trim to the last 1 KB β€” the tail is most informative and
+ // keeps the tRPC payload small.
+ const stderrTail = result.stderrContent.trim();
+ const finishError =
+ !exitedClean && stderrTail
+ ? { message: stderrTail.slice(-1024), type: 'AgentRuntimeError' }
+ : undefined;
+
try {
await sink.finish({
+ error: finishError,
result: exitedClean ? 'success' : 'error',
- sessionId: handle.sessionId,
+ sessionId,
});
} catch (err) {
log.error('Failed to send heteroFinish:', err instanceof Error ? err.message : String(err));
}
}
- if (code !== null) process.exit(ingestError ? 1 : code);
+ if (code !== null) process.exit(result.ingestError ? 1 : code);
if (signal === 'SIGINT') process.exit(130);
if (signal === 'SIGTERM') process.exit(143);
if (signal === 'SIGKILL') process.exit(137);
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 3dce1ab0194..185826e9ae0 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -77,6 +77,7 @@ import {
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
+import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
import { KlavisService } from '@/server/services/klavis';
import { MarketService } from '@/server/services/market';
import { deviceProxy } from '@/server/services/toolExecution/deviceProxy';
@@ -733,11 +734,40 @@ export class AiAgentService {
log('execAgent: failed to resolve GitHub token: %O', err);
}
+ // When resuming, inject the recent conversation turns as context so CC can
+ // orient itself even if the native session file was cleared (sandbox recycled
+ // or context overflow caused the CLI to start a fresh session).
+ // Only fetch when there IS a stored session id β€” for first-turn runs CC has
+ // no prior history to inject.
+ let conversationHistory: ConversationHistoryEntry[] | undefined;
+ if (resumeSessionId) {
+ try {
+ const recentMsgs = await this.messageModel.query({ topicId, pageSize: 200 });
+ const turns = recentMsgs
+ .filter(
+ (m) =>
+ (m.role === 'user' || m.role === 'assistant') &&
+ !m.threadId &&
+ m.content &&
+ m.content !== LOADING_FLAT,
+ )
+ .slice(-30)
+ .map((m) => ({
+ content: m.content ?? '',
+ role: m.role as 'assistant' | 'user',
+ }));
+ if (turns.length > 0) conversationHistory = turns;
+ } catch (err) {
+ log('execAgent: failed to load conversation history for hetero context: %O', err);
+ }
+ }
+
// Build cloud-specific system context (repo list + workspace info + optional agent-level static context).
const { buildCloudHeteroContext } =
await import('@/server/services/heterogeneousAgent/cloudHeteroContext');
const systemContext = buildCloudHeteroContext({
agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,
+ conversationHistory,
githubToken,
repos: topicRepos,
});
diff --git a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index a2860664a90..20287c37a0d 100644
--- a/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/src/server/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -380,6 +380,17 @@ export class HeterogeneousPersistenceHandler {
await this.flushFinalState(state, params.error, params.result);
if (params.sessionId) {
await this.persistSessionId(state.topicId, params.sessionId);
+ } else if (params.result === 'error') {
+ // No new session id was produced and the run failed. The most common
+ // cause in cloud sandboxes is `--resume <staleId>` failing because the
+ // container was recycled and session files are gone. Clear any persisted
+ // `heteroSessionId` so the next turn starts a fresh CC session instead
+ // of looping on the same stale id.
+ //
+ // When CC ran (system.init was emitted) but produced an error result,
+ // `params.sessionId` is set β€” so this branch is NOT reached and the
+ // valid session id is kept for resume on the next turn.
+ await this.clearSessionId(state.topicId);
}
} finally {
operationStates.delete(params.operationId);
@@ -400,6 +411,21 @@ export class HeterogeneousPersistenceHandler {
}
}
+ /**
+ * Remove a stale `heteroSessionId` from topic metadata. Called when a run
+ * fails without producing a new session id (e.g. `--resume` rejected because
+ * the sandbox was recycled). Prevents the next turn from inheriting a session
+ * id that will never succeed.
+ */
+ private async clearSessionId(topicId: string): Promise<void> {
+ try {
+ await this.deps.topicModel.updateMetadata(topicId, { heteroSessionId: undefined });
+ log('cleared stale sessionId topic=%s', topicId);
+ } catch (err) {
+ log('clearSessionId failed topic=%s err=%O', topicId, err);
+ }
+ }
+
// ─── State management ────────────────────────────────────────────────────
private async loadOrCreateState(operationId: string, topicId: string): Promise<OperationState> {
diff --git a/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts b/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts
index eee035782d7..481a6118695 100644
--- a/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts
+++ b/src/server/services/heterogeneousAgent/__tests__/sessionResume.test.ts
@@ -73,7 +73,7 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
});
});
- it('skips the metadata write when no sessionId is provided', async () => {
+ it('skips the metadata write when no sessionId is provided on success', async () => {
const updateMetadata = vi.fn(async () => undefined);
const findById = vi.fn(async () => ({
agentId: null,
@@ -125,6 +125,60 @@ describe('HeterogeneousAgentService β€” phase 2c session id persistence + resume
expect(updateMetadata).not.toHaveBeenCalled();
});
+ it('clears stale heteroSessionId when result=error and no sessionId (sandbox recycled)', async () => {
+ const updateMetadata = vi.fn(async () => undefined);
+ const findById = vi.fn(async () => ({
+ agentId: null,
+ id: 'topic-stale',
+ metadata: {
+ heteroSessionId: 'cc-dead-session',
+ runningOperation: { assistantMessageId: 'asst-s', operationId: 'op-stale' },
+ },
+ }));
+
+ const handler = new HeterogeneousPersistenceHandler({
+ messageModel: {
+ findById: vi.fn(async () => null),
+ listMessagePluginsByTopic: vi.fn(async () => []),
+ update: vi.fn(async () => ({ success: true })),
+ } as any,
+ threadModel: {} as any,
+ topicModel: { findById, updateMetadata } as any,
+ });
+
+ await handler.ingest({
+ events: [
+ {
+ data: { chunkType: 'text', content: '' },
+ operationId: 'op-stale',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'stream_chunk',
+ },
+ ],
+ operationId: 'op-stale',
+ topicId: 'topic-stale',
+ });
+
+ const service = new HeterogeneousAgentService({} as any, 'user-1', {
+ persistenceHandler: handler,
+ streamEventManager: createSilentStreamManager(),
+ });
+
+ // Simulate: sandbox was recycled, CC exited before emitting system.init
+ // so `sessionId` is undefined.
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-stale',
+ result: 'error',
+ // no sessionId β€” CC never initialized (resume failed)
+ topicId: 'topic-stale',
+ });
+
+ // Must clear the stale session id so the next turn starts fresh
+ expect(updateMetadata).toHaveBeenCalledWith('topic-stale', { heteroSessionId: undefined });
+ });
+
it('persists sessionId even when result=error (so the next run can still resume context)', async () => {
const updateMetadata = vi.fn(async () => undefined);
const findById = vi.fn(async () => ({
diff --git a/src/server/services/heterogeneousAgent/cloudHeteroContext.ts b/src/server/services/heterogeneousAgent/cloudHeteroContext.ts
index 46c0a584288..845e6000d12 100644
--- a/src/server/services/heterogeneousAgent/cloudHeteroContext.ts
+++ b/src/server/services/heterogeneousAgent/cloudHeteroContext.ts
@@ -1,3 +1,8 @@
+export interface ConversationHistoryEntry {
+ content: string;
+ role: 'assistant' | 'user';
+}
+
/**
* Builds the system context injected before every user prompt for cloud Claude Code runs.
*
@@ -16,10 +21,16 @@ export function buildCloudHeteroContext(params: {
repos: string[];
/** Static systemContext from HeterogeneousProviderConfig.systemContext (agent-level). */
agentSystemContext?: string;
+ /**
+ * Recent conversation turns to inject when resuming a session whose context
+ * was cleared (sandbox recycled or context overflow). Helps CC understand
+ * what happened in prior turns even without a native session file.
+ */
+ conversationHistory?: ConversationHistoryEntry[];
/** GitHub OAuth token injected as GITHUB_TOKEN env var in the sandbox. */
githubToken?: string;
}): string {
- const { repos, agentSystemContext, githubToken } = params;
+ const { repos, agentSystemContext, conversationHistory, githubToken } = params;
const parts: string[] = [];
@@ -132,6 +143,26 @@ export function buildCloudHeteroContext(params: {
parts.push(workspaceLines.join('\n'));
+ // --- Previous conversation context (injected when session was reset) ---
+ // Truncate per-message to avoid ballooning the system context:
+ // user turns β†’ 1 KB (prompts are usually short)
+ // assistant turns β†’ 2 KB (responses may be longer but we want the gist)
+ if (conversationHistory && conversationHistory.length > 0) {
+ const USER_MAX = 1024;
+ const ASST_MAX = 2048;
+ const entries = conversationHistory.map((entry) => {
+ const limit = entry.role === 'user' ? USER_MAX : ASST_MAX;
+ const body =
+ entry.content.length > limit
+ ? `${entry.content.slice(0, limit)}… [truncated]`
+ : entry.content;
+ return `<${entry.role}>\n${body}\n</${entry.role}>`;
+ });
+ parts.push(
+ `<previous_conversation>\n${entries.join('\n')}\n</previous_conversation>`,
+ );
+ }
+
return parts.join('\n\n');
}