π€― 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
β»οΈ refactor(desktop): keep local Claude Code stdin always open, aligned with lh hetero exec (#23249)
Bryan1583dc719f4a
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.tsindex 4ff89dcd860..b80064d1cff 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.backgroundTask.test.ts@@ -48,7 +48,7 @@ describe('HeterogeneousAgentCtr.stopBackgroundTask', () => {expect(stopTask).toHaveBeenCalledWith('bys1w0wxo');});- it('writes stop_task into a CLI spawned with live input (Steer)', async () => {+ it('writes stop_task into the open input of a CLI run', async () => {const stdin = new PassThrough();const written: any[] = [];stdin.on('data', (chunk: Buffer) => {@@ -72,7 +72,7 @@ describe('HeterogeneousAgentCtr.stopBackgroundTask', () => {await expect(stopping).resolves.toBeUndefined();});- it('refuses a one-shot CLI run, whose stdin closed after the prompt', async () => {+ it('refuses a run whose input has closed', async () => {const ctr = createCtr({ cli: { process: {} } });await expect(ctr.stopBackgroundTask({ sessionId: 'cli', taskId: 't' })).rejects.toThrow(diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.tsnew file mode 100644index 00000000000..af4dc47696d--- /dev/null+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.ts@@ -0,0 +1,219 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { claudeCodeDriver } from '../modules/heterogeneousAgent/drivers/claudeCode';+import HeterogeneousAgentCtr from './HeterogeneousAgentImpl';++vi.mock('electron', () => ({+ BrowserWindow: { getAllWindows: () => [] },+ app: {+ getAppPath: vi.fn(() => '/fake/appPath'),+ getPath: vi.fn((name: string) => `/fake/${name}`),+ getVersion: vi.fn(() => '1.0.0-test'),+ isPackaged: false,+ on: vi.fn(),+ quit: vi.fn(),+ },+ ipcMain: { handle: vi.fn() },+}));++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ verbose: vi.fn(),+ warn: vi.fn(),+ }),+}));++const line = (message: Record<string, unknown>) => `${JSON.stringify(message)}\n`;++/**+ * A local Claude Code CLI run in Queue mode, or with the Better Coding+ * Experience lab off: nothing is steered into it. Its stdin must still+ * stay open, as under `lh hetero exec`.+ */+const startQueueModeRun = async () => {+ const ctr = new HeterogeneousAgentCtr({+ appStoragePath: '/fake/storage',+ storeManager: { get: vi.fn() },+ } as any);+ const broadcasts: Array<{ channel: string; data: any }> = [];+ vi.spyOn(ctr as any, 'broadcast').mockImplementation((channel: any, data: any) => {+ broadcasts.push({ channel, data });+ });+ vi.spyOn(ctr as any, 'recordInflightRun').mockImplementation(() => {});++ const session: any = { agentType: 'claude-code', args: [], command: 'claude', sessionId: 's1' };+ (ctr as any).sessions.set('s1', session);++ const spawnPlan = await claudeCodeDriver.buildSpawnPlan({+ args: [],+ helpers: {+ buildAgentInput: async () => ({ args: [], stdin: line({ message: {}, type: 'user' }) }),+ },+ promptInput: 'run the long build in the background',+ });++ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ const stdinEnded = vi.fn();+ stdin.on('finish', stdinEnded);++ const proc: any = new EventEmitter();+ proc.stdin = stdin;+ proc.stdout = new PassThrough();+ proc.stderr = new PassThrough();+ proc.spawnargs = ['claude', ...spawnPlan.args];+ proc.spawnfile = 'claude';++ let settled: 'rejected' | 'resolved' | undefined;+ (ctr as any).handleSpawnedAgentProcess({+ cwd: '/tmp',+ params: { operationId: 'op-1', prompt: 'p', sessionId: 's1' },+ proc,+ reject: () => (settled = 'rejected'),+ resolve: () => (settled = 'resolved'),+ session,+ spawnEnv: {},+ spawnPlan,+ traceSession: undefined,+ useStdin: true,+ });++ const emit = (message: Record<string, unknown>) => proc.stdout.write(line(message));+ /** Claude Code reads the prompt: replays it under the uuid it was written with. */+ const readPrompt = async () => {+ await vi.waitFor(() => expect(written).toHaveLength(1));+ emit({ session_id: 'cc-1', subtype: 'init', type: 'system' });+ emit({ isReplay: true, message: {}, type: 'user', uuid: written[0].uuid });+ };+ const result = () =>+ emit({+ is_error: false,+ result: 'done',+ subtype: 'success',+ terminal_reason: 'completed',+ type: 'result',+ });+ const exit = async (code: number) => {+ proc.stdout.end();+ proc.stderr.end();+ proc.emit('exit', code, null);+ await vi.waitFor(() => expect(settled).toBeDefined(), { timeout: 3000 });+ };+ const events = () =>+ broadcasts.filter((b) => b.channel === 'heteroAgentEvent').map((b) => b.data.event);++ return {+ broadcasts,+ ctr,+ emit,+ events,+ exit,+ readPrompt,+ result,+ session,+ settled: () => settled,+ spawnPlan,+ stdinEnded,+ written,+ };+};++const tick = () => new Promise((resolve) => setImmediate(resolve));++describe('local Claude Code CLI input outside Steer mode', () => {+ beforeEach(() => {+ vi.useRealTimers();+ });+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('keeps stdin open after the prompt and replays what it reads', async () => {+ const run = await startQueueModeRun();++ expect(run.spawnPlan.args).toContain('--replay-user-messages');+ await vi.waitFor(() => expect(run.written).toHaveLength(1));+ await tick();+ expect(run.stdinEnded).not.toHaveBeenCalled();+ expect(run.session.liveInput?.isOpen).toBe(true);+ });++ it('ends a run without background tasks as soon as its turn finishes', async () => {+ const run = await startQueueModeRun();+ await run.readPrompt();+ run.result();++ await vi.waitFor(() => expect(run.stdinEnded).toHaveBeenCalled());+ await run.exit(0);++ expect(run.settled()).toBe('resolved');+ expect(run.events().filter((e) => e.type === 'agent_runtime_end')).toHaveLength(1);+ expect(run.broadcasts.some((b) => b.channel === 'heteroAgentSessionComplete')).toBe(true);+ });++ it('stays open while a background task runs, stops it, then ends the run', async () => {+ const run = await startQueueModeRun();+ await run.readPrompt();+ run.emit({+ is_backgrounded: true,+ subtype: 'task_started',+ task_id: 'bash-1',+ task_type: 'local_bash',+ tool_use_id: 'tool-1',+ type: 'system',+ });+ run.result();+ await tick();+ expect(run.stdinEnded).not.toHaveBeenCalled();++ const stopping = run.ctr.stopBackgroundTask({ sessionId: 's1', taskId: 'bash-1' });+ await vi.waitFor(() => expect(run.written).toHaveLength(2));+ expect(run.written[1]).toMatchObject({+ request: { subtype: 'stop_task', task_id: 'bash-1' },+ type: 'control_request',+ });+ run.emit({+ response: { request_id: run.written[1].request_id, response: {}, subtype: 'success' },+ type: 'control_response',+ });+ await expect(stopping).resolves.toBeUndefined();+ expect(run.stdinEnded).not.toHaveBeenCalled();++ // Claude Code wakes no turn for a stopped task: input closes right away.+ run.emit({+ status: 'stopped',+ subtype: 'task_notification',+ task_id: 'bash-1',+ type: 'system',+ });+ await vi.waitFor(() => expect(run.stdinEnded).toHaveBeenCalled());+ await run.exit(0);++ expect(run.settled()).toBe('resolved');+ expect(run.events().filter((e) => e.type === 'agent_runtime_end')).toHaveLength(1);+ });++ it('closes the open input when the run is cancelled', async () => {+ const run = await startQueueModeRun();+ await run.readPrompt();+ const proc = run.session.process;+ proc.kill = vi.fn();+ vi.spyOn(run.ctr as any, 'killProcessTree').mockImplementation(() => {+ setImmediate(() => proc.emit('exit', null, 'SIGINT'));+ });+ vi.spyOn(run.ctr as any, 'waitForProcessExit').mockResolvedValue(true);++ await run.ctr.cancelSession({ sessionId: 's1' });++ await vi.waitFor(() => expect(run.stdinEnded).toHaveBeenCalled());+ });+});diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 85ff544f720..9b821bbc153 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -162,11 +162,7 @@ import { createLogger } from '@/utils/logger';import BrowserControlCtr from './BrowserControlCtr';import { sendPromptWithCodexAppServer } from './codexAppServer';-import {- completeLiveCliRuntime,- createLiveCliAdapter,- writeCliPrompt,-} from './heterogeneousAgentLiveInput';+import { createLiveCliAdapter, endLiveCliRun, writeCliPrompt } from './heterogeneousAgentLiveInput';import type {AgentSession,CancelSessionParams,@@ -1662,7 +1658,6 @@ export default class HeterogeneousAgentCtr {}},},- liveInput: params.liveSteer,mcpConfigPath: intervention?.tmpConfigPath,promptInput,resumeSessionId: session.agentSessionId,@@ -1959,7 +1954,8 @@ export default class HeterogeneousAgentCtr {},onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),operationId: params.operationId,- replayUserMessages: params.liveSteer,+ // Like the CLI, in every Follow-up mode: a steer is confirmed by its replay.+ replayUserMessages: true,resumeSessionId: session.agentSessionId,sessionId: session.sessionId,stdinPayload: input.stdin,@@ -2366,7 +2362,7 @@ export default class HeterogeneousAgentCtr {reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));});- // In stdin mode, write the prepared payload; close stdin unless the session stays live.+ // In stdin mode, write the prepared payload; close stdin unless live (Claude Code always is).if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);const live = !!spawnPlan.liveInput;@@ -2406,9 +2402,11 @@ export default class HeterogeneousAgentCtr {uploadImage: this.uploadResultImage,});let stdoutBroadcastQueue: Promise<void> = Promise.resolve();+ let sawError = false;const broadcastStreamEvents = (events: AgentStreamEvent[]) => {for (const event of events) {+ if (event.type === 'error') sawError = true;this.broadcast('heteroAgentEvent', {event,sessionId: session.sessionId,@@ -2554,10 +2552,10 @@ export default class HeterogeneousAgentCtr {const liveInput = session.liveInput;session.liveInput = undefined;- if (code === 0) {- const exit = { cancelledByUs: false, code, signal };- broadcastStreamEvents(pipeline.validateCompletion());- broadcastStreamEvents(completeLiveCliRuntime(pipeline, liveInput, exit));+ if (code === 0) broadcastStreamEvents(pipeline.validateCompletion());+ const liveEnd = endLiveCliRun(pipeline, liveInput, { code, sawError, signal });+ if (code === 0 || liveEnd.length > 0) {+ broadcastStreamEvents(liveEnd);this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });resolve();} else {@@ -3157,6 +3155,7 @@ export default class HeterogeneousAgentCtr {}const proc = session.process;const gracefulExit = this.waitForProcessExit(proc, 2000);+ session.liveInput?.close();this.killProcessTree(proc, 'SIGINT');if (await gracefulExit) return;@@ -3171,10 +3170,10 @@ export default class HeterogeneousAgentCtr {}/**- * Stop one background task of a Claude Code run whose input is still open:- * the SDK session, or a CLI spawned with live input (Steer); a one-shot CLI- * closed its stdin. Resolves once CC accepted the request; its `stopped`- * report, the proof, reaches the renderer through the run's own stream.+ * Stop one background task of a Claude Code run, whose input (SDK stream or+ * CLI stdin) stays open in every Follow-up mode until the run winds down.+ * Resolves once CC accepted the request; its `stopped` report, the proof,+ * reaches the renderer through the run's own stream.*/async stopBackgroundTask({ sessionId, taskId }: StopBackgroundTaskParams): Promise<void> {const session = this.sessions.get(sessionId);@@ -3228,6 +3227,7 @@ export default class HeterogeneousAgentCtr {if (session.process && !session.process.killed) {session.cancelledByUs = true;const proc = session.process;+ session.liveInput?.close();this.killProcessTree(proc, 'SIGTERM');setTimeout(() => {if (session.process === proc && !proc.killed) {diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex a50a8b80684..fe21a0cd79c 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -678,14 +678,14 @@ const createFakeProc = ({const writes: string[] = [];proc.stdout = stdout;proc.stderr = stderr;- proc.stdin = {+ proc.stdin = Object.assign(new EventEmitter(), {end: vi.fn(),write: vi.fn((chunk: string, cb?: () => void) => {writes.push(chunk);cb?.();return true;}),- };+ });proc.kill = vi.fn();proc.killed = false;let started = false;@@ -1639,9 +1639,9 @@ describe('HeterogeneousAgentCtr', () => {commandPath: 'claude',cwd: FAKE_DESKTOP_PATH,operationId: 'op-test',+ replayUserMessages: true,stdinPayload: expect.stringContaining('watch ci'),- // `Read` on an image echoes base64; without this the SDK path would- // persist an `[Image: β¦]` placeholder instead of a thumbnail.+ // `Read` on an image echoes base64; without it an `[Image: β¦]` placeholder is stored.uploadImage: expect.any(Function),}),);@@ -4988,13 +4988,13 @@ describe('HeterogeneousAgentCtr', () => {const stderr = new PassThrough();proc.stdout = stdout;proc.stderr = stderr;- proc.stdin = {+ proc.stdin = Object.assign(new EventEmitter(), {end: vi.fn(),write: vi.fn((_chunk: any, cb?: () => void) => {cb?.();return true;}),- };+ });proc.kill = vi.fn();proc.killed = false;proc.__start = () => {@@ -5111,13 +5111,13 @@ describe('HeterogeneousAgentCtr', () => {const stderr = new PassThrough();proc.stdout = stdout;proc.stderr = stderr;- proc.stdin = {+ proc.stdin = Object.assign(new EventEmitter(), {end: vi.fn(),write: vi.fn((_chunk: any, cb?: () => void) => {cb?.();return true;}),- };+ });proc.kill = vi.fn();proc.killed = false;diff --git a/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.tsindex 7b09490703b..abcb2d753bb 100644--- a/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts@@ -3,7 +3,7 @@ import { PassThrough } from 'node:stream';import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';import { describe, expect, it, vi } from 'vitest';-import { completeLiveCliRuntime, writeCliPrompt } from '../heterogeneousAgentLiveInput';+import { endLiveCliRun, writeCliPrompt } from '../heterogeneousAgentLiveInput';import type { AgentSession } from '../heterogeneousAgentSession';import { steerAgentSession } from '../heterogeneousAgentSteer';@@ -110,26 +110,20 @@ describe('live Claude Code CLI input', () => {expect(ended).toHaveBeenCalled();});- it('reports the runtime end once, at a clean exit after a finished turn', () => {+ it('ends the run once, at a clean exit after a finished turn, like `lh hetero exec`', () => {const stdin = new PassThrough();stdin.resume();const input = writeCliPrompt(stdin, '{"type":"user","message":{}}\n', true)!;input.observe('{"type":"result","is_error":false,"terminal_reason":"completed"}\n');const completeRuntime = vi.fn(() => []);+ const exit = { code: 0, sawError: false, signal: null };- completeLiveCliRuntime({ completeRuntime }, input, {- cancelledByUs: false,- code: 0,- signal: null,- });+ endLiveCliRun({ completeRuntime }, input, exit);expect(completeRuntime).toHaveBeenCalledWith({ reason: 'complete', transport: 'cli-live' });completeRuntime.mockClear();- completeLiveCliRuntime({ completeRuntime }, input, {- cancelledByUs: false,- code: 2,- signal: null,- });+ endLiveCliRun({ completeRuntime }, input, { ...exit, code: 2 });+ endLiveCliRun({ completeRuntime }, input, { ...exit, sawError: true });expect(completeRuntime).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts b/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.tsindex 9cdea183b76..2482ea1cef1 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts@@ -2,14 +2,18 @@ import type { Writable } from 'node:stream';import { ClaudeCodeAdapter } from '@lobechat/heterogeneous-agents';import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';-import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';+import {+ ClaudeCodeLiveInput,+ resolveClaudeCodeLiveRuntimeEnd,+} from '@lobechat/heterogeneous-agents/spawn';/*- * Claude Code spawned on this machine with its input kept open (Follow-up- * behavior: Steer), so a message the user sends mid-run reaches the running- * session instead of waiting for it to end. The driver adds- * `--replay-user-messages`: the replay of a delivered message is how it is- * known to be read.+ * Claude Code spawned on this machine keeps its input open, like under+ * `lh hetero exec`, whatever the Follow-up mode: it carries control requests+ * (stop one background task) and, in Steer mode, the messages the user sends+ * mid-run. The driver adds `--replay-user-messages`: the replay of a delivered+ * message is how it is known to be read. The run ends at process exit, by the+ * rule shared with `lh` (`resolveClaudeCodeLiveRuntimeEnd`).*//**@@ -35,9 +39,10 @@ export const writeCliPrompt = (};/**- * A live session can run more turns after its first `result` (the one a steer- * interrupts, and the one answering it), so the runtime ends once, at process- * exit β the way the SDK transport and `lh hetero exec` report it.+ * A live session can run more turns after its first `result` (the one a+ * background task's completion wakes, the one answering a steer), so the+ * runtime ends once, at process exit β the way the SDK transport and+ * `lh hetero exec` report it.*/export const createLiveCliAdapter = () =>new ClaudeCodeAdapter({@@ -46,25 +51,17 @@ export const createLiveCliAdapter = () =>});/**- * The runtime end a live session reports at process exit: complete, or- * interrupted when its last turn was stopped. Only a clean exit after a- * finished turn ends the run here; anything else is the exit path's to report.- * Print mode exits 1 when its last turn was an interrupt.+ * The runtime end a live session reports at a process exit the host did not+ * cause, by the rule `lh hetero exec` uses (`resolveClaudeCodeLiveRuntimeEnd`):+ * complete, or interrupted when its last turn was stopped β print mode exits 1+ * then, and the run still ends cleanly. Empty when the run does not end here+ * (a crash, an error the run already reported, no finished turn).*/-export const completeLiveCliRuntime = (+export const endLiveCliRun = (pipeline: { completeRuntime: (data: Record<string, unknown>) => AgentStreamEvent[] },input: ClaudeCodeLiveInput | undefined,- exit: { cancelledByUs: boolean; code: number | null; signal: NodeJS.Signals | null },+ exit: { code: number | null; sawError: boolean; signal: NodeJS.Signals | null },): AgentStreamEvent[] => {- const lastTurn = input?.lastTurn;- if (!lastTurn || exit.cancelledByUs) return [];-- const cleanExit =- exit.code === 0 || (lastTurn.aborted && exit.code === 1 && exit.signal === null);- if (!cleanExit) return [];-- const end = lastTurn.aborted- ? { kind: 'aborted', reason: 'interrupted', terminalReason: lastTurn.terminalReason }- : { reason: 'complete' };- return pipeline.completeRuntime({ ...end, transport: 'cli-live' });+ const end = resolveClaudeCodeLiveRuntimeEnd(input?.lastTurn, { ...exit, killedByHost: false });+ return end ? pipeline.completeRuntime(end) : [];};diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex fdd82ac87ff..51549e12d44 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -67,11 +67,6 @@ export interface SendPromptParams {* Required: producer-side conversion is the V3 contract β by the time events* reach the renderer they must already carry the operation they belong to.*/- /**- * Keep the session able to take messages while it runs (Follow-up behavior:- * Steer): Claude Code keeps its input open and replays each message it reads.- */- liveSteer?: boolean;operationId: string;prompt: string;/**@@ -148,7 +143,7 @@ export interface AgentSession {env?: Record<string, string>;grokAcpSession?: GrokAcpSession;hostedProviderBinding?: HostedProviderBinding;- /** Open input of a live Claude Code CLI run (Follow-up behavior: Steer). */+ /** Open input of a Claude Code CLI run (kept open for every run, like `lh hetero exec`). */liveInput?: ClaudeCodeLiveInput;model?: string;modelSource?: string;diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.tsindex fd733026261..fd42dbb08fb 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts@@ -21,14 +21,11 @@ const buildParams = (});describe('claudeCodeDriver', () => {- it('keeps a Steer-mode run live: input stays open and each read message is replayed', async () => {- const live = await claudeCodeDriver.buildSpawnPlan(buildParams({ liveInput: true }));- const oneShot = await claudeCodeDriver.buildSpawnPlan(buildParams());-- expect(live.args).toContain('--replay-user-messages');- expect(live.liveInput).toBe(true);- expect(oneShot.args).not.toContain('--replay-user-messages');- expect(oneShot.liveInput).toBeUndefined();+ it('keeps every run live, as `lh hetero exec` does: input stays open and each read message is replayed', async () => {+ const plan = await claudeCodeDriver.buildSpawnPlan(buildParams());++ expect(plan.args).toContain('--replay-user-messages');+ expect(plan.liveInput).toBe(true);});it('prepares the namespaced server-default model without persisting the operation token', async () => {diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.tsindex b71001be299..4f1a5d6e146 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts@@ -25,7 +25,6 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {args,cliVersion,helpers,- liveInput,mcpConfigPath,promptInput,resumeSessionId,@@ -45,12 +44,17 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {// does not accept inline JSON for `--mcp-config`....(mcpConfigPath ? ['--mcp-config', mcpConfigPath] : []),...(resumeSessionId ? ['--resume', resumeSessionId] : []),- // A live session replays each message it reads: how a steer is known to be picked up.- ...(liveInput ? ['--replay-user-messages'] : []),+ // Input stays open (see `liveInput` below), and a live session replays+ // each message it reads: how a delivered message is known to be picked up.+ '--replay-user-messages',...lobeHubCli.args,...args,],- ...(liveInput && { liveInput: true }),+ // Like `lh hetero exec`, Claude Code always keeps its input open: it is+ // the control channel (stop one background task, deliver a steer) and+ // what keeps background tasks alive past the turn. Whether queued+ // messages are written mid-run is the Follow-up mode's call, not this.+ liveInput: true,stdinPayload,};},diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsindex 96e09e258f2..13abc0e6f76 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -18,7 +18,10 @@ export interface HeterogeneousAgentBuildPlan {* persisting conversation content for CLIs that cannot read prompts on stdin.*/argvPayload?: string;- /** Keep stdin open after the prompt so messages can reach the running session (Claude Code). */+ /**+ * Keep stdin open after the prompt for as long as the session can use it+ * (Claude Code, always): the channel for control requests and mid-run messages.+ */liveInput?: boolean;stdinPayload?: string;}@@ -32,8 +35,6 @@ export interface HeterogeneousAgentBuildPlanParams {/** CLI version spawn preflight detected, when known. */cliVersion?: string;helpers: HeterogeneousAgentBuildPlanHelpers;- /** The run takes messages while it runs (Follow-up behavior: Steer); drivers that can't ignore it. */- liveInput?: boolean;/*** Optional path to an MCP config JSON written by the controller (e.g. for* the local `lobe_cc` AskUserQuestion server). Drivers that recognize thediff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.tsindex 27b22d798b4..d46022e59cb 100644--- a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.test.ts@@ -2,7 +2,7 @@ import { PassThrough } from 'node:stream';import { afterEach, describe, expect, it, vi } from 'vitest';-import { ClaudeCodeLiveInput } from './claudeCodeLiveInput';+import { ClaudeCodeLiveInput, resolveClaudeCodeLiveRuntimeEnd } from './claudeCodeLiveInput';const userLine = (text: string) =>`${JSON.stringify({ message: { content: [{ text, type: 'text' }], role: 'user' }, type: 'user' })}\n`;@@ -413,3 +413,39 @@ describe('ClaudeCodeLiveInput', () => {expect(live.isOpen).toBe(false);});});++describe('resolveClaudeCodeLiveRuntimeEnd', () => {+ const finished = { aborted: false, terminalReason: 'completed' };+ const exit = { code: 0, killedByHost: false, sawError: false, signal: null };++ it('ends the run complete at a clean exit after a finished turn', () => {+ expect(resolveClaudeCodeLiveRuntimeEnd(finished, exit)).toEqual({+ reason: 'complete',+ transport: 'cli-live',+ });+ });++ it('ends an interrupted last turn as aborted, though print mode exits 1', () => {+ expect(+ resolveClaudeCodeLiveRuntimeEnd(+ { aborted: true, terminalReason: 'aborted_streaming' },+ { ...exit, code: 1 },+ ),+ ).toEqual({+ kind: 'aborted',+ reason: 'interrupted',+ terminalReason: 'aborted_streaming',+ transport: 'cli-live',+ });+ });++ it('leaves the end to the exit path for a crash, a host kill, a reported error or no turn', () => {+ expect(resolveClaudeCodeLiveRuntimeEnd(finished, { ...exit, code: 2 })).toBeUndefined();+ expect(resolveClaudeCodeLiveRuntimeEnd(finished, { ...exit, code: 1 })).toBeUndefined();+ expect(+ resolveClaudeCodeLiveRuntimeEnd(finished, { ...exit, killedByHost: true }),+ ).toBeUndefined();+ expect(resolveClaudeCodeLiveRuntimeEnd(finished, { ...exit, sawError: true })).toBeUndefined();+ expect(resolveClaudeCodeLiveRuntimeEnd(undefined, exit)).toBeUndefined();+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.tsindex a96eb6f126c..d45bec28057 100644--- a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts@@ -39,6 +39,44 @@ export interface ClaudeCodeTurnOutcome {const isAbortedResult = (message: any): boolean =>!!message.is_error && String(message.terminal_reason ?? '').startsWith('aborted');+/** How a live session's process ended, as its host saw it. */+export interface ClaudeCodeLiveExit {+ code: number | null;+ /** The host killed the process (cancel, stop, quit): its own path reports that end. */+ killedByHost: boolean;+ /** The run already reported an error event: that error is its end. */+ sawError: boolean;+ signal: NodeJS.Signals | null;+}++/**+ * The runtime end a live session (stdin kept open, see `ClaudeCodeLiveInput`)+ * reports once, at process exit: complete, or interrupted when its last turn+ * was stopped. Only a clean exit after a finished turn ends the run here β a+ * crash after a result is a failure, not a completion. Print mode exits 1 when+ * its last turn was an error result, which an interrupt is.+ *+ * Shared by every host of a live CLI (`lh hetero exec`, the desktop's local+ * spawn) so they end a run by the same rule.+ *+ * @returns the `completeRuntime` data, or undefined when the run does not end here+ */+export const resolveClaudeCodeLiveRuntimeEnd = (+ lastTurn: ClaudeCodeTurnOutcome | undefined,+ exit: ClaudeCodeLiveExit,+): Record<string, unknown> | undefined => {+ if (!lastTurn || exit.killedByHost || exit.sawError) return;++ const cleanExit =+ exit.code === 0 || (lastTurn.aborted && exit.code === 1 && exit.signal === null);+ if (!cleanExit) return;++ const end = lastTurn.aborted+ ? { kind: 'aborted', reason: 'interrupted', terminalReason: lastTurn.terminalReason }+ : { reason: 'complete' };+ return { ...end, transport: 'cli-live' };+};+/*** The `request` of a stream-json `control_request` line, e.g.* `{ subtype: 'interrupt' }`. Claude Code answers each one with adiff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex 2bf53496ad6..8dff1da04cf 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -205,7 +205,9 @@ export {type ClaudeCodeControlRequest,type ClaudeCodeControlRequestHandle,type ClaudeCodeControlResponse,+ type ClaudeCodeLiveExit,ClaudeCodeLiveInput,+ resolveClaudeCodeLiveRuntimeEnd,} from './claudeCodeLiveInput';export { readClaudeCodeSessionCost } from './claudeCodeSessionCost';export { STOP_TASK_ANSWER_TIMEOUT_MS, stopClaudeCodeTask } from './claudeCodeStopTask';diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 375299e42cf..a62800c1ff8 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -21,6 +21,7 @@ import {type ClaudeCodeControlRequest,type ClaudeCodeControlRequestHandle,ClaudeCodeLiveInput,+ resolveClaudeCodeLiveRuntimeEnd,} from './claudeCodeLiveInput';import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { resolveCliSpawnPlan } from './cliSpawn';@@ -699,19 +700,13 @@ const spawnCliAgent = async (if (code === 0 && !killedByUs) events.push(...pipeline.validateCompletion());sawErrorEvent ||= events.some((event) => event.type === 'error');for (const event of events) queue.push(event);- // Only a clean exit after a finished turn ends the run here: a crash- // after a result is a failure, not a completion. Print mode exits 1- // when its last turn was an error result, which an interrupt is.- const lastTurn = live?.lastTurn;- const cleanExit =- code === 0 || (lastTurn?.aborted === true && code === 1 && signal === null);- if (lastTurn && cleanExit && !killedByUs && !sawErrorEvent) {- const end = lastTurn.aborted- ? { kind: 'aborted', reason: 'interrupted', terminalReason: lastTurn.terminalReason }- : { reason: 'complete' };- for (const event of pipeline.completeRuntime({ ...end, transport: 'cli-live' }))- queue.push(event);- }+ const liveEnd = resolveClaudeCodeLiveRuntimeEnd(live?.lastTurn, {+ code,+ killedByHost: killedByUs,+ sawError: sawErrorEvent,+ signal,+ });+ if (liveEnd) for (const event of pipeline.completeRuntime(liveEnd)) queue.push(event);// Kimi Code reports usage only via its on-disk session wire log, so// it can only be collected now that the process has exited. The hook// is a no-op for every other agent type.diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex ebf01b4776f..2935f0425bf 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -54,8 +54,6 @@ class HeterogeneousAgentService {/** Workspace the run belongs to β recovery is workspace-scoped. */workspaceId?: string;imageList?: Array<{ id: string; url: string }>;- /** Keep the run able to take messages while it runs (Follow-up behavior: Steer). */- liveSteer?: boolean;operationId: string;prompt: string;/**diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.tsindex c1e16f87962..7ed46a08168 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts@@ -183,21 +183,28 @@ describe('heterogeneousAgentExecutor background tasks', () => {expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();});- it('offers no stop for a one-shot CLI spawn (Queue mode closes its stdin)', async () => {- await withSdkLab(false, () =>- executeHeterogeneousAgent(() => createMockStore(), defaultParams),- );- expect(mockSendPrompt.mock.calls[0][0]).not.toHaveProperty('liveSteer');- expect(stopperDuringRun).toBeUndefined();- });+ it.each(['queue', 'legacy'] as const)(+ 'offers a stop for a CLI run in %s mode, whose input stays open though nothing is steered',+ async (mode) => {+ followUp.mode = mode;+ await withSdkLab(false, () =>+ executeHeterogeneousAgent(() => createMockStore(), defaultParams),+ );++ expect(stopperDuringRun).toBeDefined();+ mockStopBackgroundTask.mockResolvedValue(undefined);+ await stopperDuringRun!('bys1w0wxo');+ expect(mockStopBackgroundTask).toHaveBeenCalledWith('ipc-sess-1', 'bys1w0wxo');+ expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();+ },+ );- it('offers a stop for a CLI spawned with live input for Steer', async () => {+ it('offers a stop for a CLI run in Steer mode', async () => {followUp.mode = 'steer';await withSdkLab(false, () =>executeHeterogeneousAgent(() => createMockStore(), defaultParams),);- expect(mockSendPrompt.mock.calls[0][0]).toMatchObject({ liveSteer: true });expect(stopperDuringRun).toBeDefined();mockStopBackgroundTask.mockResolvedValue(undefined);await stopperDuringRun!('bys1w0wxo');diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.tsindex c956797ac40..93f492f52b5 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks.ts@@ -18,8 +18,8 @@ const localStoppers = new Map<string, LocalBackgroundTaskStopper>();/*** Register how to stop the background tasks of a local run, for as long as- * its session lives. Only runtimes that can stop a single task register (the- * Claude Code SDK session); a plain CLI spawn has closed its stdin.+ * its session lives. Only runtimes that can stop a single task register:+ * Claude Code, whose input (SDK stream or CLI stdin) stays open for the run.** @returns Unregister; a no-op once a newer registration took the operation.*/diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 44654ed88e5..77a384cdf22 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -2493,8 +2493,8 @@ export const executeHeterogeneousAgent = async (set: (id) => void (mainState = { ...mainState, lastSpineMessageId: id }),},});- // A task stop needs open input (SDK, or a CLI kept open for Steer); a one-shot CLI has none.- if (adapterType === 'claude-code' && (useClaudeCodeSdk || localSteer)) {+ // Claude Code keeps its input (SDK stream or CLI stdin) open in every Follow-up mode.+ if (adapterType === 'claude-code') {unregisterTaskStopper = registerLocalBackgroundTaskStopper(operationId, (taskId) =>heterogeneousAgentService.stopBackgroundTask(sidForCancel, taskId),);@@ -2514,7 +2514,6 @@ export const executeHeterogeneousAgent = async (? { replayTranscript: true, replayTranscriptConfigDir, replayTranscriptStartedAt }: {}),...(resumeReplayMessages?.length ? { resumeReplayMessages } : {}),- ...(localSteer && { liveSteer: true }),sessionId: ipcRunSessionId,systemContext: systemContext || undefined,topicId: context.topicId ?? undefined,diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.tsindex aba1de15018..6c2b0a6541a 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts@@ -316,10 +316,11 @@ export const startLocalSteer = (get().updateOperationMetadata(operationId, { steerUnsupported: true });return;}- // Claude Code takes messages mid-run only when spawned for it (input kept- // open, each read replayed), so a run started in Queue mode stays queued.- // Codex app-server and Pi can take one at any point: their pump checks the- // mode before each delivery, so switching to Steer mid-run applies.+ // Claude Code keeps its input open in every mode, but a run takes messages+ // mid-run only when started in Steer (the SDK session replays what it reads+ // only then, which is how a steer is confirmed), so a run started in Queue+ // mode stays queued. Codex app-server and Pi can take one at any point: their+ // pump checks the mode before each delivery, so switching to Steer applies.if (options.agentType === 'claude-code' && mode !== 'steer') return;get().updateOperationMetadata(operationId, { liveSteer: true });