π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(heterogeneous-agent): avoid duplicate resume history (#18428)
AmAzing-519af39cff7b
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.tsindex 86827f5feba..778cc88153a 100644--- a/apps/cli/src/commands/connect.ts+++ b/apps/cli/src/commands/connect.ts@@ -898,6 +898,7 @@ function bindGatewayClientHandlers(client: GatewayClient, ctx: GatewayHandlerConjwt: request.jwt,operationId: request.operationId,prompt: request.prompt,+ resumeFallbackSystemContext: request.resumeFallbackSystemContext,resumeSessionId: request.resumeSessionId,serverUrl: getServerUrl(),systemContext: request.systemContext,diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 7f040e3307b..8b6100f1ac8 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -1089,6 +1089,95 @@ describe('hetero exec command', () => {});describe('--resume auto-retry on session-not-found', () => {+ it('uses recovery history only for the retry without native resume', async () => {+ const dir = await mkdtemp(`${tmpdir()}/hetero-resume-fallback-`);+ const file = path.join(dir, 'input.json');+ const primaryPrompt = [+ { text: 'workspace rules', type: 'text' },+ { text: 'continue', type: 'text' },+ ];+ const fallbackPrompt = [+ { text: 'workspace rules\n\nprevious conversation', type: 'text' },+ { text: 'continue', type: 'text' },+ ];+ await writeFile(+ file,+ JSON.stringify({ content: primaryPrompt, resumeFallback: fallbackPrompt }),+ );+ const resumeNotFoundEvent = {+ data: { message: 'No conversation found with session ID cc-stale' },+ operationId: 'op-fallback',+ stepIndex: 0,+ timestamp: 1,+ type: 'error',+ };+ mockSpawnAgent+ .mockReturnValueOnce(createFakeHandle({ events: [resumeNotFoundEvent], exitCode: 1 }))+ .mockReturnValueOnce(createFakeHandle({ exitCode: 0 }));++ try {+ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'claude-code',+ '--input-json',+ file,+ '--resume',+ 'cc-stale',+ '--operation-id',+ 'op-fallback',+ ]);+ } finally {+ await rm(dir, { force: true, recursive: true });+ }++ expect(mockSpawnAgent).toHaveBeenCalledTimes(2);+ expect(mockSpawnAgent.mock.calls[0][0]).toMatchObject({+ prompt: primaryPrompt,+ resumeSessionId: 'cc-stale',+ });+ expect(mockSpawnAgent.mock.calls[1][0]).toMatchObject({ prompt: fallbackPrompt });+ expect(mockSpawnAgent.mock.calls[1][0].resumeSessionId).toBeUndefined();+ });++ it('does not consume the recovery prompt when native resume succeeds', async () => {+ const dir = await mkdtemp(`${tmpdir()}/hetero-resume-primary-`);+ const file = path.join(dir, 'input.json');+ const primaryPrompt = [{ text: 'continue', type: 'text' }];+ await writeFile(+ file,+ JSON.stringify({+ content: primaryPrompt,+ resumeFallback: [{ text: 'previous conversation', type: 'text' }, ...primaryPrompt],+ }),+ );+ mockSpawnAgent.mockReturnValue(createFakeHandle({ exitCode: 0 }));++ try {+ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--input-json',+ file,+ '--resume',+ 'thread-existing',+ ]);+ } finally {+ await rm(dir, { force: true, recursive: true });+ }++ expect(mockSpawnAgent).toHaveBeenCalledOnce();+ expect(mockSpawnAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt: primaryPrompt,+ resumeSessionId: 'thread-existing',+ }),+ );+ });+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 eventconst resumeNotFoundEvent = {diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex f80be4da606..63e46ce5b2a 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -211,16 +211,28 @@ const parseImageArg = (value: string): AgentImageSource => {* Accepts:* - `'plain text'` β single text block* - `[{ type: 'text', text }, { type: 'image', source }]` β content blocks- * - `{ content: [...] }` (Anthropic message shape) β unwraps `content`+ * - `{ content: [...], resumeFallback?: [...] }` β unwraps the primary prompt+ * and reserves the fallback for a retry without native resume* - `{ type: 'text', ... } | { type: 'image', ... }` β single block*/-const coerceJsonPrompt = (parsed: unknown): AgentPromptInput => {- if (typeof parsed === 'string') return parsed;- if (Array.isArray(parsed)) return parsed as AgentContentBlock[];+const coerceJsonPrompt = (+ parsed: unknown,+): Pick<ResolvedPrompt, 'prompt' | 'resumeFallbackPrompt'> => {+ if (typeof parsed === 'string') return { prompt: parsed };+ if (Array.isArray(parsed)) return { prompt: parsed as AgentContentBlock[] };if (parsed && typeof parsed === 'object') {const obj = parsed as Record<string, unknown>;- if (Array.isArray(obj.content)) return obj.content as AgentContentBlock[];- if (obj.type === 'text' || obj.type === 'image') return [obj as AgentContentBlock];+ if (Array.isArray(obj.content)) {+ return {+ prompt: obj.content as AgentContentBlock[],+ ...(Array.isArray(obj.resumeFallback)+ ? { resumeFallbackPrompt: obj.resumeFallback as AgentContentBlock[] }+ : {}),+ };+ }+ if (obj.type === 'text' || obj.type === 'image') {+ return { prompt: [obj as unknown as AgentContentBlock] };+ }}throw new Error('Invalid --input-json shape: expected a string, array of content blocks, ' +@@ -232,6 +244,8 @@ interface ResolvedPrompt {/** Human-readable description for the empty-input check. */describe: () => string;prompt: AgentPromptInput;+ /** Full prompt used only when native resume fails and the CLI retries fresh. */+ resumeFallbackPrompt?: AgentPromptInput;}const buildPromptFromText = (text: string, images: string[]): ResolvedPrompt => {@@ -273,7 +287,7 @@ const resolvePrompt = async (options: ExecOptions): Promise<ResolvedPrompt> => {throw new Error('--image cannot be combined with --input-json (put images in the JSON).');}const raw = await readInputJson(options.inputJson);- return { describe: () => raw.trim(), prompt: coerceJsonPrompt(JSON.parse(raw)) };+ return { describe: () => raw.trim(), ...coerceJsonPrompt(JSON.parse(raw)) };}if (options.prompt !== undefined && options.prompt !== '-') {@@ -283,7 +297,7 @@ const resolvePrompt = async (options: ExecOptions): Promise<ResolvedPrompt> => {// No --prompt or --prompt -: read stdin and auto-detect.const raw = await readStdin();if (looksLikeJsonInput(raw)) {- return { describe: () => raw.trim(), prompt: coerceJsonPrompt(JSON.parse(raw)) };+ return { describe: () => raw.trim(), ...coerceJsonPrompt(JSON.parse(raw)) };}return buildPromptFromText(raw, images);};@@ -842,7 +856,7 @@ const exec = async (options: ExecOptions): Promise<void> => {includePartialMessages: options.type === 'claude-code',initialModel: options.type === 'trae' ? options.model : undefined,operationId,- prompt: resolved.prompt,+ prompt: resolved.resumeFallbackPrompt ?? resolved.prompt,uploadImage,// No resumeSessionId β start fresh},diff --git a/apps/cli/src/device/agentRun.test.ts b/apps/cli/src/device/agentRun.test.tsindex 0c1ac91a566..38da0f98412 100644--- a/apps/cli/src/device/agentRun.test.ts+++ b/apps/cli/src/device/agentRun.test.ts@@ -138,6 +138,34 @@ describe('spawnHeteroAgentRun', () => {);});+ it('sends recovery history only in the resume fallback prompt', async () => {+ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);++ const ackPromise = spawnHeteroAgentRun({+ ...baseParams,+ prompt: 'continue',+ resumeFallbackSystemContext: 'workspace rules\n\nprevious conversation',+ resumeSessionId: 'session-1',+ systemContext: 'workspace rules',+ });+ child.emit('spawn');+ await ackPromise;++ expect(child.stdin.write).toHaveBeenCalledWith(+ JSON.stringify({+ content: [+ { text: 'workspace rules', type: 'text' },+ { text: 'continue', type: 'text' },+ ],+ resumeFallback: [+ { text: 'workspace rules\n\nprevious conversation', type: 'text' },+ { text: 'continue', type: 'text' },+ ],+ }),+ );+ });+it('appends image blocks to stdin when imageList is provided', async () => {const child = makeFakeChild();spawnMock.mockReturnValue(child);diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex 413f4e797f2..4b5c0bdf6e9 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -16,6 +16,8 @@ export interface SpawnHeteroAgentRunParams {jwt: string;operationId: string;prompt: string;+ /** System context used only by the automatic retry without native resume. */+ resumeFallbackSystemContext?: string;resumeSessionId?: string;serverUrl: string;systemContext?: string;@@ -62,6 +64,7 @@ export function spawnHeteroAgentRun(jwt,operationId,prompt,+ resumeFallbackSystemContext,resumeSessionId,serverUrl,systemContext,@@ -95,7 +98,12 @@ export function spawnHeteroAgentRun(// array: context block first, then the user's prompt, then images β mirrors// the desktop path. `lh hetero exec` coerces both shapes via// coerceJsonPrompt.- const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });+ const stdinPayload = buildHeteroExecStdinPayload({+ imageList,+ prompt,+ resumeFallbackSystemContext,+ systemContext,+ });return new Promise<AgentRunAckResult>((resolve) => {let settled = false;diff --git a/apps/cli/vitest.config.mts b/apps/cli/vitest.config.mtsindex 99caf63e150..af3989664fc 100644--- a/apps/cli/vitest.config.mts+++ b/apps/cli/vitest.config.mts@@ -10,7 +10,7 @@ export default defineConfig({replacement: path.resolve(__dirname, '../../packages/device-gateway-client/src/index.ts'),},{- find: '@lobechat/local-file-shell',+ find: /^@lobechat\/local-file-shell$/,replacement: path.resolve(__dirname, '../../packages/local-file-shell/src/index.ts'),},{diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.tsindex b9e4e48660c..4f2ffbae0c5 100644--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts@@ -284,6 +284,7 @@ export default class GatewayConnectionCtr extends ControllerModule {jwt,operationId: request.operationId,prompt: request.prompt,+ resumeFallbackSystemContext: request.resumeFallbackSystemContext,resumeSessionId: request.resumeSessionId,serverUrl,systemContext: request.systemContext,diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 9778f558e35..83008a12e95 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -2442,6 +2442,7 @@ export default class HeterogeneousAgentCtr {jwt: string;operationId: string;prompt: string;+ resumeFallbackSystemContext?: string;resumeSessionId?: string;serverUrl: string;systemContext?: string;@@ -2456,6 +2457,7 @@ export default class HeterogeneousAgentCtr {jwt,operationId,prompt,+ resumeFallbackSystemContext,resumeSessionId,serverUrl,systemContext,@@ -2491,7 +2493,12 @@ export default class HeterogeneousAgentCtr {...(extraArgs ?? []),];- const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });+ const stdinPayload = buildHeteroExecStdinPayload({+ imageList,+ prompt,+ resumeFallbackSystemContext,+ systemContext,+ });const cliScript = resolveCliScript();if (!existsSync(cliScript)) {return Promise.resolve({diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex e954fd1cb43..e1a0c5c9b19 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -858,10 +858,11 @@ describe('GatewayConnectionCtr', () => {);});- it('forwards cwd and systemContext from the request to spawnLhHeteroExec', async () => {+ it('forwards cwd and primary/fallback context from the request to spawnLhHeteroExec', async () => {const client = await connectAndOpen();client.simulateAgentRunRequest('claude-code', 'op-ctx', 'hi', 'mock-jwt', {cwd: '/Users/alice/repo',+ resumeFallbackSystemContext: 'RECOVERY CONTEXT',systemContext: 'WORKSPACE CONTEXT',});await vi.advanceTimersByTimeAsync(0);@@ -869,6 +870,7 @@ describe('GatewayConnectionCtr', () => {expect(mockHeterogeneousAgentCtr.spawnLhHeteroExec).toHaveBeenCalledWith(expect.objectContaining({cwd: '/Users/alice/repo',+ resumeFallbackSystemContext: 'RECOVERY CONTEXT',systemContext: 'WORKSPACE CONTEXT',}),);diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex bd2464d85e8..0a489d171e7 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -2566,6 +2566,37 @@ describe('HeterogeneousAgentCtr', () => {expect(proc.stdin.end).toHaveBeenCalledOnce();});+ it('encodes primary and resume fallback contexts for the embedded CLI', async () => {+ const proc = createGatewayCliProc();+ nextFakeProc = proc;+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath,+ storeManager: { get: vi.fn() },+ } as any);++ const ack = ctr.spawnLhHeteroExec({+ ...params,+ resumeFallbackSystemContext: 'workspace rules\n\nprevious conversation',+ resumeSessionId: 'session-1',+ systemContext: 'workspace rules',+ });+ proc.emit('spawn');++ await expect(ack).resolves.toEqual({ status: 'accepted' });+ expect(proc.stdin.write).toHaveBeenCalledWith(+ JSON.stringify({+ content: [+ { text: 'workspace rules', type: 'text' },+ { text: 'inspect the repository', type: 'text' },+ ],+ resumeFallback: [+ { text: 'workspace rules\n\nprevious conversation', type: 'text' },+ { text: 'inspect the repository', type: 'text' },+ ],+ }),+ );+ });+it('rejects the gateway request when the embedded CLI cannot spawn', async () => {const proc = createGatewayCliProc();nextFakeProc = proc;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex e2616bbfbe9..edc379fc9d7 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -10,6 +10,7 @@ const {mockExecuteToolCall,mockGetHeterogeneousResumeSessionId,mockMessageCreate,+ mockMessageQuery,mockResolveAttachmentsByFileIds,mockSpawnHeteroSandbox,mockIngestAttachment,@@ -24,6 +25,7 @@ const {mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),mockIngestAttachment: vi.fn(),mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),mockPublishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),mockResolveAttachmentsByFileIds: vi.fn(),@@ -75,7 +77,7 @@ vi.mock('@/database/models/message', () => ({create: mockMessageCreate,getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),- query: vi.fn().mockResolvedValue([]),+ query: mockMessageQuery,update: vi.fn().mockResolvedValue({}),})),}));@@ -212,11 +214,16 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>topicMock.findById.mockResolvedValue(undefined);topicMock.updateMetadata.mockResolvedValue(undefined);mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockMessageQuery.mockResolvedValue([]);mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });mockSpawnHeteroSandbox.mockResolvedValue(undefined);mockDispatchAgentRun.mockResolvedValue({ success: true });mockExecuteToolCall.mockResolvedValue({ success: true });mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);+ mockMessageQuery.mockResolvedValue([]);+ mockBuildRemoteDeviceHeteroContext.mockImplementation(({ conversationHistory }) =>+ conversationHistory ? 'device recovery context' : 'device context',+ );mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);mockIngestAttachment.mockReset();@@ -352,6 +359,32 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();});+ it('resumes Amp natively without loading or injecting fallback history', async () => {+ mockGetHeterogeneousResumeSessionId.mockResolvedValue('amp-thread-existing');+ heteroAgentConfig.model = 'amp';+ heteroAgentConfig.provider = 'amp';+ heteroAgentConfig.agencyConfig = {+ boundDeviceId: 'device-1',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'amp' },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Continue the Amp thread',+ });++ expect(mockMessageQuery).not.toHaveBeenCalled();+ expect(mockBuildRemoteDeviceHeteroContext).toHaveBeenCalledOnce();+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({+ resumeFallbackSystemContext: undefined,+ resumeSessionId: 'amp-thread-existing',+ systemContext: 'device context',+ }),+ );+ });+it('should pass resolved Claude Code model and effort args to sandbox dispatch', async () => {heteroAgentConfig.agencyConfig.heterogeneousProvider = {effort: 'high',@@ -392,6 +425,35 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>);});+ it('reserves cloud conversation history for a retry without native resume', async () => {+ mockGetHeterogeneousResumeSessionId.mockResolvedValue('cloud-session-existing');+ mockMessageQuery.mockResolvedValue([+ { content: 'Earlier cloud question', id: 'old-user', role: 'user' },+ { content: 'Earlier cloud answer', id: 'old-assistant', role: 'assistant' },+ { content: 'Continue in cloud', id: 'msg-1', role: 'user' },+ ]);+ heteroAgentConfig.agencyConfig = {+ executionTarget: 'sandbox',+ heterogeneousProvider: { type: 'claude-code' },+ } as any;++ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Continue in cloud',+ });++ expect(mockSpawnHeteroSandbox).toHaveBeenCalledWith(+ expect.objectContaining({+ resumeFallbackSystemContext: expect.stringContaining('Earlier cloud question'),+ resumeSessionId: 'cloud-session-existing',+ systemContext: expect.not.stringContaining('<previous_conversation>'),+ }),+ );+ const { resumeFallbackSystemContext } = mockSpawnHeteroSandbox.mock.calls[0][0];+ expect(resumeFallbackSystemContext).toContain('Earlier cloud answer');+ expect(resumeFallbackSystemContext).not.toContain('Continue in cloud');+ });+it('should encode native Codex args before forwarding them to sandbox lh hetero exec', async () => {heteroAgentConfig.model = 'codex';heteroAgentConfig.provider = 'codex';@@ -496,6 +558,11 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>it('resumes a native device session with device-specific context', async () => {mockGetHeterogeneousResumeSessionId.mockResolvedValue('native-session-existing');+ mockMessageQuery.mockResolvedValue([+ { content: 'Earlier question', id: 'old-user', role: 'user' },+ { content: 'Earlier answer', id: 'old-assistant', role: 'assistant' },+ { content: 'Continue on my device', id: 'msg-1', role: 'user' },+ ]);heteroAgentConfig.agencyConfig = {boundDeviceId: 'device-1',executionTarget: 'device',@@ -509,10 +576,21 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>expect(mockDispatchAgentRun).toHaveBeenCalledWith(expect.objectContaining({+ resumeFallbackSystemContext: 'device recovery context',resumeSessionId: 'native-session-existing',systemContext: 'device context',}),);+ expect(mockBuildRemoteDeviceHeteroContext).toHaveBeenNthCalledWith(1, {+ agentSystemContext: undefined,+ });+ expect(mockBuildRemoteDeviceHeteroContext).toHaveBeenNthCalledWith(2, {+ agentSystemContext: undefined,+ conversationHistory: [+ { content: 'Earlier question', role: 'user' },+ { content: 'Earlier answer', role: 'assistant' },+ ],+ });});it('dispatches OpenCode to a bound device with its model args', async () => {diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 04bde7a7ac6..bb492b891e8 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -2345,13 +2345,12 @@ 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.+ // Recovery history is reserved for the CLI's retry without native resume.+ // The primary resumed attempt already has native history and must not get+ // a serialized duplicate. Amp threads are server-backed, so they rely on+ // native continuation exclusively and never need this local-file fallback.let conversationHistory: ConversationHistoryEntry[] | undefined;- if (resumeSessionId) {+ if (resumeSessionId && heteroType !== 'amp') {try {const recentMsgs = await this.messageModel.query({ topicId, pageSize: 200 });const turns = recentMsgs@@ -2359,6 +2358,7 @@ export class AiAgentService {(m) =>(m.role === 'user' || m.role === 'assistant') &&!m.threadId &&+ !selfMessageIds.has(m.id) &&m.content &&m.content !== LOADING_FLAT,)@@ -2373,13 +2373,22 @@ export class AiAgentService {}}- // Build cloud-specific system context (repo list + workspace info + optional agent-level static context).+ // Build the primary context without conversation history. If native resume+ // fails, the CLI switches to the complete fallback prompt on its fresh+ // retry; successful same-session runs never consume the duplicate history.const systemContext = buildCloudHeteroContext({agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,- conversationHistory,githubToken,repos: topicRepos,});+ const resumeFallbackSystemContext = conversationHistory+ ? buildCloudHeteroContext({+ agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,+ conversationHistory,+ githubToken,+ repos: topicRepos,+ })+ : undefined;// Feed the resolved images (signed URLs) to the dispatched CLI for vision β// mirrors the local-mode path, where the client feeds the persisted@@ -2406,6 +2415,7 @@ export class AiAgentService {operationId,prompt,repos: topicRepos,+ resumeFallbackSystemContext,resumeSessionId,systemContext,topicId,@@ -2731,14 +2741,20 @@ export class AiAgentService {// the agent). The spawned CLI already receives deviceCwd as its actual cwd.const deviceSystemContext = buildRemoteDeviceHeteroContext({agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,- conversationHistory,});+ const deviceResumeFallbackSystemContext = conversationHistory+ ? buildRemoteDeviceHeteroContext({+ agentSystemContext: agentConfig.agencyConfig?.heterogeneousProvider?.systemContext,+ conversationHistory,+ })+ : undefined;const result = await deviceGateway.dispatchAgentRun({...heteroParams,args: heteroExecArgs,cwd: deviceCwd,deviceId: dispatchDeviceId,+ resumeFallbackSystemContext: deviceResumeFallbackSystemContext,systemContext: deviceSystemContext,// Route to the workspace pool when this is a workspace device; the// operation JWT stays member-scoped (the run belongs to the member).diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.tsindex fc15cb5a8cb..633ea154815 100644--- a/apps/server/src/services/deviceGateway/index.ts+++ b/apps/server/src/services/deviceGateway/index.ts@@ -1283,6 +1283,7 @@ export class DeviceGateway {jwt: string;operationId: string;prompt: string;+ resumeFallbackSystemContext?: string;resumeSessionId?: string;systemContext?: string;topicId: string;diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex 0ccaf04caac..71e537cd5ad 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -40,6 +40,8 @@ export interface SandboxRunParams {prompt: string;/** GitHub repos to clone before running the agent (e.g. ['owner/repo', ...]). */repos?: string[];+ /** Full system context used only by the automatic retry without native resume. */+ resumeFallbackSystemContext?: string;resumeSessionId?: string;/*** Optional context injected as a text block BEFORE the user's prompt.@@ -183,6 +185,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidconst stdinPayload = buildHeteroExecStdinPayload({imageList: params.imageList,prompt,+ resumeFallbackSystemContext: params.resumeFallbackSystemContext,systemContext: params.systemContext,});const base64Payload = Buffer.from(stdinPayload).toString('base64');diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex 440facfc678..07fd62a5ffe 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -210,6 +210,7 @@ export class GatewayHttpClient {jwt: string;operationId: string;prompt: string;+ resumeFallbackSystemContext?: string;resumeSessionId?: string;systemContext?: string;timeout?: number;diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex ed4215275cb..8dba8939192 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -237,12 +237,19 @@ export interface AgentRunRequestMessage {jwt: string;operationId: string;prompt: string;+ /**+ * Full system context used only when native resume fails and the device CLI+ * retries with a fresh session. Optional for compatibility with older+ * servers and devices. Self-hosted gateways must forward this optional field;+ * older gateways safely degrade to a fresh retry without recovery history.+ */+ resumeFallbackSystemContext?: string;resumeSessionId?: string;/*** Static context injected before the user prompt (workspace conventions,- * conversation history on resume). The desktop sends it to `lh hetero exec`- * as the first text block of a content-block array. Optional β omitted for- * older servers that don't build a device-specific context.+ * selected context). The desktop sends it to `lh hetero exec` as the first+ * text block of a content-block array. Optional β omitted for older servers+ * that don't build a device-specific context.*/systemContext?: string;topicId: string;diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.tsindex f1643f3ba93..52999c55528 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts@@ -42,6 +42,36 @@ describe('buildHeteroExecStdinPayload', () => {]);});+ it('reserves recovery history for the resume fallback prompt', () => {+ const payload = buildHeteroExecStdinPayload({+ imageList: [{ id: 'file-1', url: 'https://x/a.png' }],+ prompt: 'continue',+ resumeFallbackSystemContext:+ 'workspace rules\n\n<previous_conversation>history</previous_conversation>',+ systemContext: 'workspace rules',+ });+ const parsed = JSON.parse(payload);++ expect(parsed).toEqual({+ content: [+ { text: 'workspace rules', type: 'text' },+ { text: 'continue', type: 'text' },+ { source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },+ ],+ resumeFallback: [+ {+ text: 'workspace rules\n\n<previous_conversation>history</previous_conversation>',+ type: 'text',+ },+ { text: 'continue', type: 'text' },+ { source: { id: 'file-1', type: 'url', url: 'https://x/a.png' }, type: 'image' },+ ],+ });+ // Older CLIs already unwrap `{ content: [...] }`, so they safely run the+ // history-free primary prompt and ignore the unknown fallback field.+ expect(parsed.content[0].text).not.toContain('<previous_conversation>');+ });+it('treats an empty imageList like no images', () => {const payload = buildHeteroExecStdinPayload({ imageList: [], prompt: 'hello' });expect(payload).toBe(JSON.stringify('hello'));diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.tsindex e6fef408066..a7b0db1770c 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts@@ -23,15 +23,31 @@ export interface HeteroExecImageRef {* Plain prompt with no context/images stays a JSON string (the historical* shape); anything richer becomes a content-block array, which* `lh hetero exec` coerces via `coerceJsonPrompt` β systemContext first, then- * the user prompt, then image blocks.+ * the user prompt, then image blocks. Resume recovery adds a backwards-+ * compatible `{ content, resumeFallback }` envelope: old CLIs unwrap `content`+ * and run the primary prompt, while new CLIs reserve `resumeFallback` for a+ * retry after native resume fails.*/export const buildHeteroExecStdinPayload = (params: {imageList?: HeteroExecImageRef[];prompt: string;+ resumeFallbackSystemContext?: string;systemContext?: string;}): string => {- const { imageList = [], prompt, systemContext } = params;+ const { imageList = [], prompt, resumeFallbackSystemContext, systemContext } = params;const blocks = buildHeterogeneousPrompt({ imageList, prompt, systemContext });++ if (resumeFallbackSystemContext !== undefined) {+ return JSON.stringify({+ content: blocks,+ resumeFallback: buildHeterogeneousPrompt({+ imageList,+ prompt,+ systemContext: resumeFallbackSystemContext,+ }),+ });+ }+if (blocks.length === 1 && blocks[0].type === 'text' && blocks[0].text === prompt) {return JSON.stringify(prompt);}