🤯 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
✨ feat(chat): Follow-up behavior (Queue / Steer) under the Better Coding Experience lab (#23186)
Bryan4ffc770792d3
diff --git a/apps/cli/src/commands/hetero/index.ts b/apps/cli/src/commands/hetero/index.tsindex 056b91b999c..11df2e0de38 100644--- a/apps/cli/src/commands/hetero/index.ts+++ b/apps/cli/src/commands/hetero/index.ts@@ -1064,7 +1064,12 @@ const exec = async (options: ExecOptions): Promise<void> => {let terminalErrorMessage: string | undefined;let terminalErrorData: Record<string, unknown> | undefined;try {- for await (const event of withHeteroSteer(handle, !!sink && { getTrpcClient, operationId })) {+ const steerContext = !!sink && {+ getTrpcClient,+ isWaitingForUser: () => (askBridge?.pendingCount ?? 0) > 0,+ operationId,+ };+ for await (const event of withHeteroSteer(handle, steerContext)) {if (interceptResumeErrors && event.type === 'error') {const data = event.data as Record<string, unknown> | undefined;const msg = String(data?.message ?? data?.error ?? '');@@ -1079,19 +1084,14 @@ const exec = async (options: ExecOptions): Promise<void> => {continue;}}- // A terminal `error` event (e.g. an API/rate-limit error relayed by CC)- // must mark the run as failed even when the child exits 0 — track it so- // the finish result is not derived from the exit code alone. Capture the- // message too, so the finish payload can surface it as the task-level- // error detail (CC relays these on stdout, not stderr).+ // A terminal `error` (e.g. a rate limit CC relays on stdout) fails the run even on+ // exit 0; its message becomes the finish payload's task-level error detail.if (event.type === 'error') {sawTerminalError = true;const data = event.data as Record<string, unknown> | undefined;terminalErrorMessage = String(data?.message ?? data?.error ?? '') || undefined;- // Keep the adapter's already-classified status-guide payload- // (overloaded / rate_limit carry `agentType` + `code`) so the finish- // leg doesn't flatten it back to a bare string — the process-failure- // classifier there only knows cli_not_found / auth_required.+ // Keep the adapter's classified status-guide payload (overloaded / rate_limit carry+ // `agentType` + `code`): the finish leg's classifier only knows cli/auth failures.terminalErrorData = isHeteroStatusGuideErrorData(data) ? data : undefined;}if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);diff --git a/apps/cli/src/utils/heteroSteer.test.ts b/apps/cli/src/utils/heteroSteer.test.tsindex a37b7f145c8..3bc1eb9e5c5 100644--- a/apps/cli/src/utils/heteroSteer.test.ts+++ b/apps/cli/src/utils/heteroSteer.test.ts@@ -97,6 +97,26 @@ describe('withHeteroSteer', () => {]);});+ it('holds follow-ups while the session waits for the user, and gives back one handed out then', async () => {+ const { client, giveBack, wait } = createClient([{ content: 'go', messageId: 'msg-1' }]);+ const sendUserMessage = vi.fn(async () => true);+ const stream = createStream();++ const out = collect(+ withHeteroSteer(+ { events: stream.events, sendUserMessage },+ { getTrpcClient: async () => client, isWaitingForUser: () => true, operationId: 'op-1' },+ ),+ );+ await vi.waitFor(() => expect(giveBack).toHaveBeenCalled());+ stream.end();+ await out;++ expect(sendUserMessage).not.toHaveBeenCalled();+ expect(giveBack).toHaveBeenCalledWith({ messageId: 'msg-1', operationId: 'op-1' });+ expect(wait.mock.calls[0][0]).toMatchObject({ holdSteer: true });+ });+it('types images pasted into a follow-up in as image blocks', async () => {const image = { id: 'file_1', url: 'https://bucket.example.com/1.png?sig=s' };const { client } = createClient([diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.tsindex 770ac0a308d..1217eeb56aa 100644--- a/apps/cli/src/utils/heteroSteer.ts+++ b/apps/cli/src/utils/heteroSteer.ts@@ -30,6 +30,7 @@ export interface HeteroSteerClient {acceptsControl?: boolean;acceptsImages?: boolean;blockMs?: number;+ holdSteer?: boolean;operationId: string;},options?: { signal?: AbortSignal },@@ -72,6 +73,8 @@ export const buildSteerPrompt = (message: HeteroSteerMessage): AgentPromptInputexport interface HeteroSteerContext {getTrpcClient: () => Promise<HeteroSteerClient>;+ /** Whether the session waits for the user (a question or an approval): nothing is steered then. */+ isWaitingForUser?: () => boolean;operationId: string;}@@ -145,6 +148,8 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(// its queue hint changed.let supported = false;let markedLive = false;+ // While the session waits on a question or approval nothing is steered.+ const waitingForUser = () => !!context.isWaitingForUser?.();const report = async (client: HeteroSteerClient,@@ -197,6 +202,7 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(acceptsImages: true,// The first poll answers at once, so the run is marked steerable early....(!answered && { blockMs: 1 }),+ ...(waitingForUser() && { holdSteer: true }),operationId,},{ signal: abort.signal },@@ -217,6 +223,14 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(continue;}if (!message) continue;+ // Handed out just as the session started waiting for the user: it goes+ // back, and comes again once the user answered.+ if (waitingForUser()) {+ await client.aiAgent.returnHeteroSteer+ .mutate({ messageId: message.messageId, operationId })+ .catch((error) => log.debug('Returning steer message failed: %s', String(error)));+ continue;+ }const steer = message;const options = { uuid: steer.messageId };diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex e0ca9ca0fde..f5f56028afd 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -193,6 +193,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return (await this.getImplementation()).getKimiCodeQuota(...args);}+ @IpcMethod()+ async steerSession(...args: Parameters<Implementation['steerSession']>) {+ return (await this.getImplementation()).steerSession(...args);+ }+@IpcMethod()async cancelSession(...args: Parameters<Implementation['cancelSession']>) {return (await this.getImplementation()).cancelSession(...args);diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 31dee1c828f..b38d895e0a5 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -161,6 +161,11 @@ import { createLogger } from '@/utils/logger';import BrowserControlCtr from './BrowserControlCtr';import { sendPromptWithCodexAppServer } from './codexAppServer';+import {+ completeLiveCliRuntime,+ createLiveCliAdapter,+ writeCliPrompt,+} from './heterogeneousAgentLiveInput';import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeneousAgentSession';import {claudeProfileDirOf,@@ -169,6 +174,12 @@ import {interruptActiveAcpSession,sendPromptWithAcpSession,} from './heterogeneousAgentSession';+import {+ steerAgentSession,+ type SteerSessionParams,+ type SteerSessionResult,+} from './heterogeneousAgentSteer';+import { redactPromptArgs } from './redactPromptArgs';import RemoteServerConfigCtr from './RemoteServerConfigCtr';const logger = createLogger('controllers:HeterogeneousAgentCtr');@@ -250,27 +261,7 @@ const PI_RPC_POOL_DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000;const waitForHeteroSessionCompleteGrace = () =>new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));-export const redactPromptArgs = (args: string[], agentType: HeterogeneousAgentType): string[] => {- let redactNext = false;- const supportsShortPromptFlag = agentType === 'kimi-code';-- return args.map((arg) => {- if (redactNext) {- redactNext = false;- return '[REDACTED]';- }-- if (arg === '--prompt' || (supportsShortPromptFlag && arg === '-p')) {- redactNext = true;- return arg;- }-- if (arg.startsWith('--prompt=')) return '--prompt=[REDACTED]';- if (supportsShortPromptFlag && arg.startsWith('-p=')) return '-p=[REDACTED]';-- return arg;- });-};+export { redactPromptArgs };// ─── IPC types ───@@ -1685,6 +1676,7 @@ export default class HeterogeneousAgentCtr {}},},+ liveInput: params.liveSteer,mcpConfigPath: intervention?.tmpConfigPath,promptInput,resumeSessionId: session.agentSessionId,@@ -1981,6 +1973,7 @@ export default class HeterogeneousAgentCtr {},onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),operationId: params.operationId,+ replayUserMessages: params.liveSteer,resumeSessionId: session.agentSessionId,sessionId: session.sessionId,stdinPayload: input.stdin,@@ -2387,13 +2380,11 @@ export default class HeterogeneousAgentCtr {reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));});- // In stdin mode, write the prepared payload and close stdin.+ // In stdin mode, write the prepared payload; close stdin unless the session stays live.if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);- const stdin = proc.stdin as Writable;- stdin.write(spawnPlan.stdinPayload, () => {- stdin.end();- });+ const live = !!spawnPlan.liveInput;+ session.liveInput = writeCliPrompt(proc.stdin as Writable, spawnPlan.stdinPayload, live);}session.process = proc;@@ -2417,6 +2408,7 @@ export default class HeterogeneousAgentCtr {// file-change diff/stat tracker when `agentType === 'codex'`, so this// controller stays agent-agnostic.const pipeline = new AgentStreamPipeline({+ ...(session.liveInput && { adapter: createLiveCliAdapter() }),agentType: session.agentType,cwd,env: spawnEnv,@@ -2493,9 +2485,11 @@ export default class HeterogeneousAgentCtr {const stdout = proc.stdout as Readable;stdout.on('data', (chunk: Buffer) => {void this.appendCliTraceFile(traceSession, 'stdout.jsonl', chunk);+ session.liveInput?.observe(chunk);broadcastPipelineBatch(() => pipeline.push(chunk));});stdout.on('end', () => {+ session.liveInput?.finish();broadcastPipelineBatch(() => pipeline.flush());});@@ -2557,11 +2551,8 @@ export default class HeterogeneousAgentCtr {// which the executor calls once its terminal handling and persistence// have settled, is the acknowledgement that releases it.- // If *we* killed it (cancel / stop / before-quit), treat the non-zero- // exit as a clean shutdown — surfacing it as an error would make a- // user-initiated cancel look like an agent failure, and an Electron- // shutdown affecting OTHER running CC sessions would pollute their- // topics with a misleading "Agent exited with code 143" message.+ // If *we* killed it (cancel / stop / before-quit), a non-zero exit is a clean shutdown: as an+ // error a cancel reads as an agent failure, a quit leaves "exited with code 143" elsewhere.if (session.cancelledByUs) {// Quit-driven kill: say nothing to the renderer. A `complete`// broadcast (or a settled `sendPrompt`) reaching a renderer that@@ -2575,8 +2566,12 @@ export default class HeterogeneousAgentCtr {return;}+ const liveInput = session.liveInput;+ session.liveInput = undefined;if (code === 0) {+ const exit = { cancelledByUs: false, code, signal };broadcastStreamEvents(pipeline.validateCompletion());+ broadcastStreamEvents(completeLiveCliRuntime(pipeline, liveInput, exit));this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });resolve();} else {@@ -3131,6 +3126,11 @@ export default class HeterogeneousAgentCtr {* Throws:* - When a CLI process remains active after the bounded SIGKILL escalation.*/+ /** Deliver a message into the session's running turn (Follow-up behavior: Steer). */+ steerSession(params: SteerSessionParams): Promise<SteerSessionResult> {+ return steerAgentSession(this.sessions.get(params.sessionId), params, this.fileCacheDir);+ }+async cancelSession(params: CancelSessionParams): Promise<void> {const session = this.sessions.get(params.sessionId);if (!session) return;diff --git a/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.tsnew file mode 100644index 00000000000..7b09490703b--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentSteer.test.ts@@ -0,0 +1,135 @@+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 type { AgentSession } from '../heterogeneousAgentSession';+import { steerAgentSession } from '../heterogeneousAgentSteer';++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+}));++const params = { messageId: 'steer-1', prompt: 'also run the tests', sessionId: 's1' };+const session = (extra: Partial<AgentSession>) =>+ ({+ agentType: 'claude-code',+ args: [],+ command: 'claude',+ sessionId: 's1',+ ...extra,+ }) as AgentSession;++const readLines = (stream: PassThrough) => {+ const lines: any[] = [];+ stream.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) lines.push(JSON.parse(raw));+ });+ return lines;+};++describe('steerAgentSession', () => {+ it('writes into a live Claude Code CLI under the delivery id, with no priority', async () => {+ const stdin = new PassThrough();+ const written = readLines(stdin);+ const liveInput = new ClaudeCodeLiveInput(stdin);++ await expect(steerAgentSession(session({ liveInput }), params, '/tmp')).resolves.toEqual({+ status: 'accepted',+ });+ await new Promise((resolve) => setImmediate(resolve));++ expect(written[0]).toMatchObject({ type: 'user', uuid: 'steer-1' });+ // Read at the next tool boundary: `priority: 'now'` would abort the running tool.+ expect(written[0]).not.toHaveProperty('priority');+ expect(JSON.stringify(written[0].message)).toContain('also run the tests');+ });++ it('refuses once the live input closed, so the message runs as the next turn', async () => {+ const liveInput = new ClaudeCodeLiveInput(new PassThrough());+ liveInput.close();++ await expect(steerAgentSession(session({ liveInput }), params, '/tmp')).resolves.toEqual({+ status: 'rejected',+ });+ });++ it('hands the message to the Claude Code SDK input stream', async () => {+ const steer = vi.fn(() => true);++ await expect(+ steerAgentSession(session({ sdkSession: { steer } as any }), params, '/tmp'),+ ).resolves.toEqual({ status: 'accepted' });+ expect(steer).toHaveBeenCalledWith(expect.objectContaining({ type: 'user' }), 'steer-1');+ });++ it('steers a Codex app-server turn', async () => {+ const steer = vi.fn(async () => 'rejected' as const);+ const codex = session({ agentType: 'codex', appServerSession: { steer } as any });++ await expect(steerAgentSession(codex, params, '/tmp')).resolves.toEqual({ status: 'rejected' });+ expect(steer).toHaveBeenCalledWith(+ [expect.objectContaining({ text: 'also run the tests', type: 'text' })],+ 'steer-1',+ );+ });++ it('steers a Pi run', async () => {+ const steer = vi.fn(async () => {});+ const pi = session({ agentType: 'pi', piRpcSession: { steer } as any });++ // Pi reports a read message by its text: hand back exactly what it received.+ await expect(steerAgentSession(pi, params, '/tmp')).resolves.toEqual({+ deliveredText: 'also run the tests',+ status: 'accepted',+ });+ expect(steer).toHaveBeenCalledWith('also run the tests', undefined);+ });++ it.each([+ ['an ACP agent', session({ agentType: 'copilot' })],+ ['Codex exec', session({ agentType: 'codex' })],+ ['a one-shot Claude Code CLI', session({ process: {} as any })],+ ])('has no way into %s', async (_label, target) => {+ await expect(steerAgentSession(target, params, '/tmp')).resolves.toEqual({+ status: 'unsupported',+ });+ });+});++describe('live Claude Code CLI input', () => {+ it('closes stdin after the prompt for a one-shot run', async () => {+ const stdin = new PassThrough();+ const ended = vi.fn();+ stdin.on('finish', ended);+ stdin.resume();++ expect(writeCliPrompt(stdin, '{"type":"user"}\n', false)).toBeUndefined();+ await new Promise((resolve) => setImmediate(resolve));+ expect(ended).toHaveBeenCalled();+ });++ it('reports the runtime end once, at a clean exit after a finished turn', () => {+ 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(() => []);++ completeLiveCliRuntime({ completeRuntime }, input, {+ cancelledByUs: false,+ code: 0,+ signal: null,+ });+ expect(completeRuntime).toHaveBeenCalledWith({ reason: 'complete', transport: 'cli-live' });++ completeRuntime.mockClear();+ completeLiveCliRuntime({ completeRuntime }, input, {+ cancelledByUs: false,+ code: 2,+ signal: null,+ });+ expect(completeRuntime).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts b/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.tsnew file mode 100644index 00000000000..9cdea183b76--- /dev/null+++ b/apps/desktop/src/main/controllers/heterogeneousAgentLiveInput.ts@@ -0,0 +1,70 @@+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';++/*+ * 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.+ */++/**+ * Write the prompt to the CLI's stdin. With `live`, stdin stays open for as+ * long as the session can still use input (see `ClaudeCodeLiveInput`);+ * otherwise it is closed after the prompt, as a one-shot run does.+ */+export const writeCliPrompt = (+ stdin: Writable,+ payload: string,+ live: boolean,+): ClaudeCodeLiveInput | undefined => {+ if (!live) {+ stdin.write(payload, () => {+ stdin.end();+ });+ return;+ }++ const input = new ClaudeCodeLiveInput(stdin);+ input.send(payload);+ return input;+};++/**+ * 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.+ */+export const createLiveCliAdapter = () =>+ new ClaudeCodeAdapter({+ runtimeEndStrategy: 'on-transport-close',+ signalBackgroundTaskCompletion: true,+ });++/**+ * 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.+ */+export const completeLiveCliRuntime = (+ pipeline: { completeRuntime: (data: Record<string, unknown>) => AgentStreamEvent[] },+ input: ClaudeCodeLiveInput | undefined,+ exit: { cancelledByUs: boolean; code: number | null; 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' });+};diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex 9805346ac40..09b806d0b42 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -8,6 +8,7 @@ import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocoimport type { PiRpcSession } from '@lobechat/heterogeneous-agents/rpc';import type {ClaudeAgentSdkSession,+ ClaudeCodeLiveInput,CodexThreadSession,DshAcpSessionHandle,} from '@lobechat/heterogeneous-agents/spawn';@@ -66,6 +67,11 @@ 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;/**@@ -142,6 +148,8 @@ export interface AgentSession {env?: Record<string, string>;grokAcpSession?: GrokAcpSession;hostedProviderBinding?: HostedProviderBinding;+ /** Open input of a live Claude Code CLI run (Follow-up behavior: Steer). */+ liveInput?: ClaudeCodeLiveInput;model?: string;modelSource?: string;modelVerificationLastAttemptAt?: number;diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSteer.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSteer.tsnew file mode 100644index 00000000000..51f30ce5412--- /dev/null+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSteer.ts@@ -0,0 +1,104 @@+import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocol';+import { toPiRpcPrompt } from '@lobechat/heterogeneous-agents/rpc';+import {+ buildAgentInput,+ buildClaudeSdkUserMessageFromStreamJson,+ buildCodexAppServerInput,+} from '@lobechat/heterogeneous-agents/spawn';++import type { HeterogeneousAgentImageAttachment } from '@/modules/heterogeneousAgent/types';+import { createLogger } from '@/utils/logger';++import type { AgentSession } from './heterogeneousAgentSession';++const logger = createLogger('controllers:HeterogeneousAgentSteer');++export interface SteerSessionParams {+ imageList?: HeterogeneousAgentImageAttachment[];+ /**+ * Names the delivery: the agent reports it back once it reads the message+ * (Claude Code replays it under this uuid, Codex echoes it as the user+ * message's client id). Pi reports no id; its text names it instead.+ */+ messageId: string;+ prompt: string;+ sessionId: string;+}++/**+ * How a steer ended in the main process.+ * - `accepted`: written into the running session; the agent confirms by+ * reporting the message back (`step_complete { phase: 'user_message' }`).+ * - `rejected`: the session takes no input now (its turn ended, or the turn+ * cannot be steered); nothing was written, so it can run as the next turn.+ * - `unsupported`: this runtime has no way into a running turn.+ */+export type SteerSessionResult = {+ /**+ * The text the agent received, when it reports a read message by its text+ * (Pi): the prompt transport can expand it (referenced-topic guidance).+ */+ deliveredText?: string;+ status: 'accepted' | 'rejected' | 'unsupported';+};++const accepted: SteerSessionResult = { status: 'accepted' };+const rejected: SteerSessionResult = { status: 'rejected' };+const unsupported: SteerSessionResult = { status: 'unsupported' };++/**+ * Deliver a user message into a session's running turn — the native steer of+ * each runtime: Claude Code (SDK input stream, or a live CLI's stdin, read at+ * its next tool boundary — never `priority: 'now'`, which aborts the running+ * tool), Codex app-server `turn/steer`, Pi `steer`. Runtimes with+ * no such channel (ACP agents, one-shot CLIs) answer `unsupported`.+ *+ * A failure while writing is thrown: the caller cannot tell whether the agent+ * got the message, so it must not send it again on its own.+ */+export const steerAgentSession = async (+ session: AgentSession | undefined,+ params: SteerSessionParams,+ cacheDir: string,+): Promise<SteerSessionResult> => {+ if (!session) return rejected;++ const promptInput = buildHeterogeneousPrompt({+ imageList: params.imageList,+ isNewSession: false,+ prompt: params.prompt,+ });++ if (session.sdkSession) {+ const plan = await buildAgentInput('claude-code', promptInput, { cacheDir });+ const message = buildClaudeSdkUserMessageFromStreamJson(plan.stdin);+ return session.sdkSession.steer(message, params.messageId) ? accepted : rejected;+ }++ if (session.agentType === 'claude-code') {+ const live = session.liveInput;+ if (!live) return session.process ? unsupported : rejected;+ const plan = await buildAgentInput('claude-code', promptInput, { cacheDir });+ return live.send(plan.stdin, params.messageId) ? accepted : rejected;+ }++ if (session.appServerSession) {+ const plan = await buildAgentInput('codex', promptInput, { cacheDir });+ const outcome = await session.appServerSession.steer(+ buildCodexAppServerInput(plan),+ params.messageId,+ );+ return outcome === 'accepted' ? accepted : rejected;+ }++ if (session.agentType === 'pi') {+ const rpc = session.piRpcSession;+ if (!rpc) return rejected;+ const { images, text } = await toPiRpcPrompt(promptInput, { cacheDir });+ await rpc.steer(text, images);+ return { deliveredText: text, status: 'accepted' };+ }++ logger.debug('No native steer for %s; the message waits for the run to end', session.agentType);+ return unsupported;+};diff --git a/apps/desktop/src/main/controllers/redactPromptArgs.ts b/apps/desktop/src/main/controllers/redactPromptArgs.tsnew file mode 100644index 00000000000..05c6f694f50--- /dev/null+++ b/apps/desktop/src/main/controllers/redactPromptArgs.ts@@ -0,0 +1,24 @@+import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';++/** Hide a prompt passed on argv from logs and traces. */+export const redactPromptArgs = (args: string[], agentType: HeterogeneousAgentType): string[] => {+ let redactNext = false;+ const supportsShortPromptFlag = agentType === 'kimi-code';++ return args.map((arg) => {+ if (redactNext) {+ redactNext = false;+ return '[REDACTED]';+ }++ if (arg === '--prompt' || (supportsShortPromptFlag && arg === '-p')) {+ redactNext = true;+ return arg;+ }++ if (arg.startsWith('--prompt=')) return '--prompt=[REDACTED]';+ if (supportsShortPromptFlag && arg.startsWith('-p=')) return '-p=[REDACTED]';++ return arg;+ });+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.tsindex ac1a2bb5bb3..fd733026261 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts@@ -21,6 +21,16 @@ 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('prepares the namespaced server-default model without persisting the operation token', async () => {const plan = await claudeCodeDriver.prepareServerDefaultBinding!({args: [],diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.tsindex bff453c4dd6..b71001be299 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts@@ -25,6 +25,7 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {args,cliVersion,helpers,+ liveInput,mcpConfigPath,promptInput,resumeSessionId,@@ -44,9 +45,12 @@ 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'] : []),...lobeHubCli.args,...args,],+ ...(liveInput && { liveInput: true }),stdinPayload,};},diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsindex 439ea443d30..96e09e258f2 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -18,6 +18,8 @@ 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). */+ liveInput?: boolean;stdinPayload?: string;}@@ -30,6 +32,8 @@ 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/apps/server/src/routers/lambda/aiAgent/hetero.control.test.ts b/apps/server/src/routers/lambda/aiAgent/hetero.control.test.tsindex e2904ccb0cd..b144c1d5b74 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.control.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.control.test.ts@@ -12,6 +12,7 @@ import { heteroRouter } from './hetero';const mocks = vi.hoisted(() => ({getRedisServiceClient: vi.fn(),operation: undefined as Record<string, unknown> | undefined,+ readFollowUpMode: vi.fn(),renewHeteroSteers: vi.fn(),takeHeteroSteer: vi.fn(),}));@@ -24,6 +25,9 @@ vi.mock('@/server/services/aiAgent/steerQueue/hetero', () => ({returnHeteroSteer: vi.fn(),takeHeteroSteer: mocks.takeHeteroSteer,}));+vi.mock('@/server/services/aiAgent/steerQueue/followUpMode', () => ({+ readFollowUpMode: mocks.readFollowUpMode,+}));vi.mock('./procedures', async () => {const { trpc } = await import('@/libs/trpc/lambda/init');// The operation row every `select().from().where().limit()` reads.@@ -60,6 +64,38 @@ beforeEach(() => {mocks.getRedisServiceClient.mockResolvedValue(createHeteroControlFakeRedis());mocks.operation = mainRun;mocks.takeHeteroSteer.mockResolvedValue(undefined);+ mocks.readFollowUpMode.mockResolvedValue('legacy');+});++describe('waitHeteroSteer and the Follow-up behavior', () => {+ it('takes no follow-up into the live session in Queue mode', async () => {+ mocks.readFollowUpMode.mockResolvedValue('queue');+ mocks.takeHeteroSteer.mockResolvedValue({ content: 'hi', messageId: 'msg-1' });++ expect(await caller.waitHeteroSteer({ blockMs: 1, operationId: 'op-1' })).toEqual({+ message: null,+ });+ expect(mocks.takeHeteroSteer).not.toHaveBeenCalled();+ });++ it('hands out no follow-up while the session waits for the user', async () => {+ mocks.readFollowUpMode.mockResolvedValue('steer');++ await caller.waitHeteroSteer({ blockMs: 1, holdSteer: true, operationId: 'op-1' });++ expect(mocks.takeHeteroSteer).not.toHaveBeenCalled();+ });++ it('asks for a merged steer in Steer mode', async () => {+ mocks.readFollowUpMode.mockResolvedValue('steer');++ await caller.waitHeteroSteer({ blockMs: 1, operationId: 'op-1' });++ expect(mocks.takeHeteroSteer).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ mode: 'steer', operationId: 'op-1' }),+ );+ });});describe('waitHeteroSteer control messages', () => {diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex f8b2b5a94ad..00a3fcca58c 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -20,6 +20,7 @@ import { signHeteroOperationJWT } from '@/libs/trpc/utils/internalJwt';import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';import { mapAgentInterventionTRPCError } from '@/server/routers/lambda/_helpers/agentInterventionError';import { AiAgentService } from '@/server/services/aiAgent';+import { readFollowUpMode } from '@/server/services/aiAgent/steerQueue/followUpMode';import {renewHeteroSteers,returnHeteroSteer,@@ -156,6 +157,11 @@ const WaitHeteroSteerSchema = z.object({*/acceptsImages: z.boolean().optional(),blockMs: z.number().int().positive().max(25_000).default(20_000),+ /**+ * The session waits for the user (a question or an approval): hand it no+ * follow-up now, only control messages. Older producers omit it.+ */+ holdSteer: z.boolean().optional(),operationId: z.string().min(1),});@@ -587,7 +593,7 @@ export const heteroRouter = router({waitHeteroSteer: heteroAgentProcedure.input(WaitHeteroSteerSchema).mutation(async ({ input, ctx, signal }): Promise<WaitHeteroSteerAnswer> => {- const { acceptsControl, acceptsImages, operationId, blockMs } = input;+ const { acceptsControl, acceptsImages, holdSteer, operationId, blockMs } = input;await authorizeOperationCallback(ctx, operationId, 'hetero:ingest');@@ -635,6 +641,8 @@ export const heteroRouter = router({: undefined;if (scope) await renewHeteroSteers(operationId);+ // Queue mode leaves the follow-ups to the run end; read once per poll.+ const followUpMode = scope ? await readFollowUpMode(ctx.serverDB, ctx.userId) : 'legacy';const deadline = Date.now() + blockMs;for (;;) {@@ -649,10 +657,11 @@ export const heteroRouter = router({const control = await takeHeteroControl(operationId);if (control) return answer(null, control);}- if (scope) {+ if (scope && followUpMode !== 'queue' && !holdSteer) {const message = await takeHeteroSteer(storeCtx, {acceptsImages,agentId: operation.agentId,+ mode: followUpMode,operationId,scope,});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.tsindex 45bb3196c72..2910c62882e 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts@@ -19,6 +19,9 @@ vi.mock('@/server/services/redis', () => ({},}));+const { readFollowUpMode } = vi.hoisted(() => ({ readFollowUpMode: vi.fn() }));+vi.mock('@/server/services/aiAgent/steerQueue/followUpMode', () => ({ readFollowUpMode }));+const stateOf = (overrides: Partial<AgentState> = {}) =>({origin: { topicId: 'tpc-1' },@@ -33,6 +36,55 @@ describe('server-side steer queue in the step loop', () => {steerQueueLength.mockResolvedValue(0);steerQueueSeal.mockResolvedValue(undefined);steerQueueUnseal.mockResolvedValue(undefined);+ readFollowUpMode.mockResolvedValue('legacy');+ });++ describe('Follow-up behavior: Queue', () => {+ beforeEach(() => readFollowUpMode.mockResolvedValue('queue'));++ it('lets the run finish instead of handing its turn back for queued follow-ups', async () => {+ steerQueueLength.mockResolvedValue(2);+ const deps = {+ coordinator: { hasQueuedMessages: vi.fn().mockResolvedValue(true) },+ userId: 'user-1',+ } as any;++ await expect(readQueuedMessagesFlag(deps, 'op-1', 1, stateOf())).resolves.toBe(false);+ });++ it('does not join a person’s follow-ups into the running turn', async () => {+ steerQueueLength.mockResolvedValue(1);+ const deps = {+ delegate: { injectQueuedFollowUp: vi.fn().mockResolvedValue({ messageId: 'm' }) },+ userId: 'user-1',+ } as any;++ await expect(+ injectQueuedFollowUp(deps, 'op-1', 2, stateOf({ status: 'running' })),+ ).resolves.toBeUndefined();+ expect(deps.delegate.injectQueuedFollowUp).not.toHaveBeenCalled();+ });++ it('still joins a parent’s steer into its running sub-agent', async () => {+ steerQueueLength.mockResolvedValue(1);+ const deps = {+ delegate: { injectQueuedFollowUp: vi.fn().mockResolvedValue({ messageId: 'm' }) },+ userId: 'user-1',+ } as any;+ const child = stateOf({+ origin: {+ agentId: 'agt-1',+ lineage: { isSubAgent: true, parentOperationId: 'op-parent' },+ threadId: 'thd-sub',+ topicId: 'tpc-1',+ },+ status: 'running',+ });++ await expect(injectQueuedFollowUp(deps, 'op-child', 2, child)).resolves.toEqual({+ messageId: 'm',+ });+ });});describe('readQueuedMessagesFlag', () => {diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsindex 6a4ec2ce473..3242a68dd6d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -2,6 +2,7 @@ import type { AgentState } from '@lobechat/agent-runtime';import { getLlmCallCount, isParkedStatus } from '@lobechat/agent-runtime';import debug from 'debug';+import { readFollowUpMode } from '@/server/services/aiAgent/steerQueue/followUpMode';import { redisService } from '@/server/services/redis';import { hookDispatcher } from '../hooks';@@ -38,6 +39,7 @@ export type OperationControlDeps = Pick<| 'endExpiredClientLlmWait'| 'messageModel'| 'queueService'+ | 'serverDB'| 'streamManager'| 'traceRecorder'| 'userId'@@ -280,10 +282,14 @@ export async function readQueuedMessagesFlag(state?: AgentState,): Promise<boolean> {try {- if (await deps.coordinator.hasQueuedMessages(operationId)) return true;-const scope = state && steerQueueScopeOf(state, deps.userId);- return scope ? (await redisService.steerQueue.length(scope, operationId)) > 0 : false;+ const pending =+ (await deps.coordinator.hasQueuedMessages(operationId)) ||+ (!!scope && (await redisService.steerQueue.length(scope, operationId)) > 0);+ if (!pending) return false;++ // Queue mode lets the run finish: its follow-ups start once it ends.+ return (await readFollowUpMode(deps.serverDB, deps.userId)) !== 'queue';} catch (error) {log('[%s][%d] Queued messages flag read failed: %O', operationId, stepIndex, error);return false;@@ -353,6 +359,9 @@ export async function injectQueuedFollowUp(try {if ((await redisService.steerQueue.length(scope, operationId)) === 0) return;+ // A person's follow-ups wait for the run to end in Queue mode; a parent's+ // steer of its sub-agent always joins.+ if (topLevelScope && (await readFollowUpMode(deps.serverDB, deps.userId)) === 'queue') return;const injected = await deps.delegate.injectQueuedFollowUp({ operationId, scope, state });// It answers again with the steer in context, so it reads its queue again.diff --git a/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.ts b/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.tsnew file mode 100644index 00000000000..75efb5f0d4a--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.ts@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { readFollowUpMode } from './followUpMode';++const mocks = vi.hoisted(() => ({ getUserPreference: vi.fn(), getUserSettings: vi.fn() }));+vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function () {+ return { getUserPreference: mocks.getUserPreference, getUserSettings: mocks.getUserSettings };+ }),+}));++const db = {} as any;+const lab = (enabled: boolean) => ({ lab: { enableBetterCodingExperience: enabled } });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.getUserSettings.mockResolvedValue(undefined);+});++describe('readFollowUpMode', () => {+ it('keeps the legacy behavior while the lab is off, without reading settings', async () => {+ mocks.getUserPreference.mockResolvedValue(lab(false));+ mocks.getUserSettings.mockResolvedValue({ general: { followUpBehavior: 'queue' } });++ await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('legacy');+ expect(mocks.getUserSettings).not.toHaveBeenCalled();+ });++ it('defaults to steer with the lab on', async () => {+ mocks.getUserPreference.mockResolvedValue(lab(true));++ await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('steer');+ });++ it('reads the stored setting with the lab on', async () => {+ mocks.getUserPreference.mockResolvedValue(lab(true));+ mocks.getUserSettings.mockResolvedValue({ general: { followUpBehavior: 'queue' } });++ await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('queue');+ });++ it('falls back to the legacy behavior when the read fails', async () => {+ mocks.getUserPreference.mockRejectedValue(new Error('db down'));++ await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('legacy');+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/followUpMode.ts b/apps/server/src/services/aiAgent/steerQueue/followUpMode.tsnew file mode 100644index 00000000000..9048773485c--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/followUpMode.ts@@ -0,0 +1,38 @@+import type { FollowUpBehavior, FollowUpMode, UserGeneralConfig } from '@lobechat/types';+import { resolveFollowUpMode } from '@lobechat/types';+import debug from 'debug';++import { UserModel } from '@/database/models/user';+import type { LobeChatDatabase } from '@/database/type';++const log = debug('lobe-server:steer-queue:mode');++/**+ * The run owner's Follow-up behavior (Settings → Chat, under the Better Coding+ * Experience lab): what the follow-ups queued behind their run do.+ *+ * - `steer`: join the running turn, merged into one message per join.+ * - `queue`: wait for the run to end and start one turn each.+ * - `legacy`: the lab is off, so the behavior from before the setting.+ *+ * Read when a queue has entries, so a change applies at the next decision+ * point. A read that fails falls back to `legacy`, which is what every run did+ * before the setting existed.+ */+export const readFollowUpMode = async (+ db: LobeChatDatabase,+ userId: string,+): Promise<FollowUpMode> => {+ try {+ const model = new UserModel(db, userId);+ const preference = await model.getUserPreference();+ if (!preference?.lab?.enableBetterCodingExperience) return 'legacy';++ const settings = await model.getUserSettings();+ const general = settings?.general as UserGeneralConfig | undefined;+ return resolveFollowUpMode(true, general?.followUpBehavior as FollowUpBehavior | undefined);+ } catch (error) {+ log('Reading the follow-up behavior of %s failed: %O', userId, error);+ return 'legacy';+ }+};diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.test.tsindex 38f8a80ef0e..131aac663ca 100644--- a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts@@ -125,6 +125,67 @@ describe('takeHeteroSteer', () => {expect(mocks.deliveries.get('msg-a')).toContain(`"drainId":"${drained}"`);});+ describe('Steer mode', () => {+ const steer = () =>+ takeHeteroSteer(ctx, { agentId: 'agt-1', mode: 'steer', operationId: 'op-1', scope });++ it('merges every leading follow-up that can join into one message', async () => {+ mocks.drain.mockResolvedValue([+ followUp('b', 2),+ followUp('a', 1),+ followUp('c', 3, { fileIds: ['f1'] }),+ followUp('d', 4),+ ]);++ const message = await steer();++ expect(message).toMatchObject({ content: 'prompt a\n\nprompt b' });+ // Read at the next tool boundary: a steer never cuts a running tool short.+ expect(message).not.toHaveProperty('priority');+ // A merged batch gets an id of its own, derived from its entries.+ expect(message?.messageId).toMatch(/^msg_[\da-f]{24}$/);+ // The attachment waits for a turn of its own, and `d` stays behind it.+ expect(mocks.settle.mock.calls[0][2]).toEqual(['c', 'd']);+ const delivery = JSON.parse(mocks.deliveries.get(message!.messageId)!);+ expect(delivery.entryIds).toEqual(['a', 'b']);+ });++ it('sends a single follow-up as it is', async () => {+ mocks.drain.mockResolvedValue([followUp('a', 1)]);++ await expect(steer()).resolves.toEqual({+ content: 'prompt a',+ messageId: 'msg-a',+ });+ });++ it('rebinds a merged delivery that lapsed back, instead of merging it again with newer ones', async () => {+ mocks.deliveries.set(+ 'msg_ab',+ JSON.stringify({ drainId: 'old', entryId: 'a', entryIds: ['a', 'b'], scope }),+ );+ mocks.drain.mockResolvedValue([followUp('a', 1), followUp('b', 2), followUp('c', 3)]);++ await expect(steer()).resolves.toBeUndefined();++ // The session already has A+B; only C goes back, for the next join.+ const [, drainId, returned] = mocks.settle.mock.calls[0];+ expect(returned).toEqual(['c']);+ expect(JSON.parse(mocks.deliveries.get('msg_ab')!).drainId).toBe(drainId);+ expect(mocks.deliveries.size).toBe(1);+ });++ it('returns every merged follow-up when the session refuses the message', async () => {+ mocks.drain.mockResolvedValue([followUp('a', 1), followUp('b', 2)]);+ const message = await steer();+ mocks.settle.mockClear();++ await returnHeteroSteer('op-1', message!.messageId);++ expect(mocks.settle).toHaveBeenCalledWith(scope, expect.any(String), ['a', 'b']);+ });+ });+it('leaves the queue to the run end when the first follow-up cannot join', async () => {mocks.drain.mockResolvedValue([followUp('a', 1, { fileIds: ['f1'] }), followUp('b', 2)]);diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.tsindex 856b0c40897..3a5d9bbba79 100644--- a/apps/server/src/services/aiAgent/steerQueue/hetero.ts+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.ts@@ -1,4 +1,4 @@-import type { AgentSenderMetadata } from '@lobechat/types';+import type { AgentSenderMetadata, FollowUpMode } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import debug from 'debug';@@ -17,9 +17,11 @@ import {ackFollowUps,checkFollowUpAccess,drainOwnFollowUps,+ mergeQueuedFollowUps,type QueuedFollowUp,queuedUserMessageId,returnFollowUps,+ takeSameSenderFollowUps,} from './index';const log = debug('lobe-server:steer-queue:hetero');@@ -37,6 +39,8 @@ export interface HeteroSteerDelivery {drainId: string;editorData?: unknown;entryId: string;+ /** Every follow-up merged into this delivery, when there were several (Steer mode). */+ entryIds?: string[];groupId?: string;scope: SteerQueueScope;trigger?: string;@@ -82,11 +86,20 @@ export const renewHeteroSteers = async (operationId: string) => {}};+/** Whether a session that takes image input only if `acceptsImages` can take this follow-up now. */+const fitsSession = (entry: QueuedFollowUp, acceptsImages: boolean | undefined) =>+ acceptsImages || collectMarkdownImageUrls(entry.request.prompt).length === 0;+/*** Take the next follow-up queued behind a heterogeneous run for delivery into- * its live session. One message per delivery, in queue order: the first- * follow-up that cannot join (an attachment, a tool selection…) stops the- * take, and it and everything behind it wait for the run to end.+ * its live session, in queue order: the first follow-up that cannot join (an+ * attachment, a tool selection…) stops the take, and it and everything behind+ * it wait for the run to end.+ *+ * In Steer mode (`mode: 'steer'`) every leading follow-up that can join, from+ * one author, goes as one merged message; otherwise one goes per delivery.+ * Either way the agent reads it when it is ready (Claude Code: at its next+ * tool boundary), so a running tool is never cut short.** Images pasted into the body go along as `imageList` when the session takes* image input (`acceptsImages`). Otherwise the follow-up waits for a turn of@@ -100,48 +113,73 @@ export const takeHeteroSteer = async (params: {acceptsImages?: boolean;agentId: string | null;+ mode?: FollowUpMode;operationId: string;scope: SteerQueueScope;},): Promise<HeteroSteerMessage | undefined> => {const { acceptsImages, agentId, operationId, scope } = params;+ const merging = params.mode === 'steer';const drained = await drainOwnFollowUps(ctx, scope, operationId);if (drained.entries.length === 0) return;const held = await redisService.steerQueue.listHeteroDeliveries<HeteroSteerDelivery>(operationId);- const [first, ...rest] = drained.entries;- if (!canSteerHeteroRun(first, agentId)) {- await returnFollowUps(scope, drained, drained.entries, 'needs a turn of its own');+ // A delivery whose lease lapsed while the session still held it came back+ // into the queue. It is the session's already: rebind it as it was, so a+ // merge with newer follow-ups (a new message id) never types its entries twice.+ const heldBy = new Map<string, string>();+ for (const [messageId, delivery] of Object.entries(held))+ for (const id of delivery.entryIds ?? [delivery.entryId]) heldBy.set(id, messageId);+ const lapsedId = drained.entries.map((entry) => heldBy.get(entry.id)).find(Boolean);+ if (lapsedId) {+ const delivery = held[lapsedId];+ const ids = new Set(delivery.entryIds ?? [delivery.entryId]);+ const others = drained.entries.filter((entry) => !ids.has(entry.id));+ await returnFollowUps(scope, drained, others, 'behind a delivery the session holds');+ await redisService.steerQueue.putHeteroDelivery(operationId, lapsedId, {+ ...delivery,+ drainId: drained.drainId,+ } satisfies HeteroSteerDelivery);return;}// A session that only takes text gets no image follow-up: decided from the// markdown alone, since the run asks again on every poll.- const hasImages = collectMarkdownImageUrls(first.request.prompt).length > 0;- if (hasImages && !acceptsImages) {- await returnFollowUps(scope, drained, drained.entries, 'its images need a turn of their own');+ const canGo = (entry: QueuedFollowUp) =>+ canSteerHeteroRun(entry, agentId) && fitsSession(entry, acceptsImages);+ const firstHeld = drained.entries.findIndex((entry) => !canGo(entry));+ const ready = firstHeld === -1 ? drained.entries : drained.entries.slice(0, firstHeld);+ const joining = merging ? takeSameSenderFollowUps(ready).taken : ready.slice(0, 1);+ if (joining.length === 0) {+ await returnFollowUps(scope, drained, drained.entries, 'needs a turn of its own');return;}+ const request = joining.length === 1 ? joining[0].request : mergeQueuedFollowUps(joining);let imageList: InlineImage[] = [];- if (hasImages) {+ if (collectMarkdownImageUrls(request.prompt).length > 0) {try {- imageList = await resolveInlineImages(ctx, first.request.prompt);+ imageList = await resolveInlineImages(ctx, request.prompt);} catch (error) {await returnFollowUps(scope, drained, drained.entries, error);return;}}- await returnFollowUps(scope, drained, rest, 'delivered one at a time');+ const rest = drained.entries.filter((entry) => !joining.includes(entry));+ await returnFollowUps(+ scope,+ drained,+ rest,+ merging ? 'waits for the next join' : 'delivered one at a time',+ );- const request = first.request;- const messageId = queuedUserMessageId(ctx.userId, [first], request);+ const messageId = queuedUserMessageId(ctx.userId, joining, request);try {if ((await checkFollowUpAccess(ctx, request, scope)) === 'denied') {- console.error('[takeHeteroSteer] dropped follow-up %s: access revoked', first.id);+ console.error('[takeHeteroSteer] dropped %d follow-ups: access revoked', joining.length);await ackFollowUps(scope, drained);return;}@@ -164,21 +202,22 @@ export const takeHeteroSteer = async (}await redisService.steerQueue.putHeteroDelivery(operationId, messageId, {- agentSender: first.agentSender,+ agentSender: joining[0].agentSender,content: request.prompt,drainId: drained.drainId,editorData: request.userMessage?.editorData,- entryId: first.id,+ entryId: joining[0].id,+ ...(joining.length > 1 && { entryIds: joining.map((entry) => entry.id) }),groupId: request.appContext?.groupId ?? undefined,scope,trigger: request.trigger,} satisfies HeteroSteerDelivery);} catch (error) {- await returnFollowUps(scope, drained, [first], error);+ await returnFollowUps(scope, drained, joining, error);return;}- log('[%s] Delivering follow-up %s as %s', operationId, first.id, messageId);+ log('[%s] Delivering %d follow-ups as %s', operationId, joining.length, messageId);return {content: request.prompt,...(imageList.length > 0 && { imageList }),@@ -196,9 +235,15 @@ export const returnHeteroSteer = async (operationId: string, messageId: string)const delivery = held[messageId];if (!delivery) return;- await returnFollowUps(delivery.scope, delivery, [{ id: delivery.entryId } as QueuedFollowUp], {- reason: 'the agent session no longer takes input',- });+ const entryIds = delivery.entryIds ?? [delivery.entryId];+ await returnFollowUps(+ delivery.scope,+ delivery,+ entryIds.map((id) => ({ id }) as QueuedFollowUp),+ {+ reason: 'the agent session no longer takes input',+ },+ );await redisService.steerQueue.removeHeteroDelivery(operationId, messageId);};diff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.tsindex 18a3c78c5fd..4cc1d81ee41 100644--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts@@ -33,6 +33,8 @@ vi.mock('@/server/services/redis', () => ({redisService: { steerQueue: { boundOperations, drain, restore, settle } },}));vi.mock('./liveRuns', () => ({ findOwnLiveRuns, isRunAlive }));+const { readFollowUpMode } = vi.hoisted(() => ({ readFollowUpMode: vi.fn() }));+vi.mock('./followUpMode', () => ({ readFollowUpMode }));const { findMessageById } = vi.hoisted(() => ({ findMessageById: vi.fn() }));vi.mock('@/database/models/message', () => ({MessageModel: class {@@ -177,6 +179,24 @@ describe('startQueuedFollowUp', () => {assertCanUseAgentRunConversation.mockResolvedValue(undefined);startComposerRun.mockResolvedValue({ operationId: 'op-2' });findMessageById.mockResolvedValue(undefined);+ readFollowUpMode.mockResolvedValue('legacy');+ });++ it('starts only the oldest follow-up in Queue mode; the rest wait for that turn to end', async () => {+ readFollowUpMode.mockResolvedValue('queue');+ drain.mockResolvedValue([followUp('b', 2, {}), followUp('a', 1, {})]);++ await expect(startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }))).resolves.toEqual({+ operationId: 'op-2',+ });++ expect(startComposerRun.mock.calls[0][1].prompt).toBe('a');+ // `b` goes back to the head of the queue, unbound, for the run just started.+ expect(settle).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'tpc-1' }),+ expect.any(String),+ ['b'],+ );});it('starts the drained follow-ups as their own turn on the same surface', async () => {diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.tsindex 3819b7c0c38..a6c66692fde 100644--- a/apps/server/src/services/aiAgent/steerQueue/index.ts+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts@@ -17,6 +17,7 @@ import { redisService } from '@/server/services/redis';import type { SteerQueueEntry, SteerQueueScope } from '@/server/services/redis/steerQueue';import { type ComposerRunContext, type ComposerRunRequest, startComposerRun } from '../composerRun';+import { readFollowUpMode } from './followUpMode';import { findOwnLiveRuns, isRunAlive } from './liveRuns';const log = debug('lobe-server:steer-queue');@@ -365,8 +366,13 @@ export const startQueuedFollowUp = async (if (drained.entries.length === 0) return;// One author per turn; the run this starts picks the others up when it ends.- const { agentSender, rest, taken: entries } = takeSameSenderFollowUps(drained.entries);- await returnFollowUps(scope, drained, rest, 'sent by another author');+ // Queue mode starts one follow-up per turn the same way.+ const sameSender = takeSameSenderFollowUps(drained.entries);+ const { agentSender } = sameSender;+ const oneEach = (await readFollowUpMode(ctx.db, ctx.userId)) === 'queue';+ const entries = oneEach ? sameSender.taken.slice(0, 1) : sameSender.taken;+ const rest = drained.entries.filter((entry) => !entries.includes(entry));+ await returnFollowUps(scope, drained, rest, oneEach ? 'one turn each' : 'sent by another author');const merged = mergeQueuedFollowUps(entries);const userMessageId = queuedUserMessageId(ctx.userId, entries, merged);diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 66b3ae86b88..d7655409002 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1756,10 +1756,16 @@"inputQueue.enqueueRejected": "Queue is full. Try again after the current run finishes.","inputQueue.queuedHint": "Sends when the current step finishes","inputQueue.queuedMergeHint": "Merged and sent when the current step finishes",+ "inputQueue.queuedOneByOneHint": "Sent one at a time after the current run finishes","inputQueue.queuedRunEndHint": "Sends when the current run finishes","inputQueue.queuedRunEndMergeHint": "Merged and sent when the current run finishes","inputQueue.sendNow": "Send now (interrupts current run)","inputQueue.sendNowFailed": "Couldn’t interrupt the current run. Try again.",+ "inputQueue.steerDeliveryUnknownHint": "Couldn’t confirm the agent got this. Send it again or delete it",+ "inputQueue.steerHint": "Joins the current run",+ "inputQueue.steerMergeHint": "Joins the current run as one message",+ "inputQueue.steerUnsupportedHint": "This agent can’t take messages mid-run. Queued until the run finishes",+ "inputQueue.steerUnsupportedMergeHint": "This agent can’t take messages mid-run. Queued, merged and sent when the run finishes","inputQueue.withdrawFailed": "Couldn’t take the message back. Try again.","intentUnderstanding.title": "Understanding your intent...","internalLink.agent.open": "Open agent",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 00b76cb603d..5db04a01c52 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1772,6 +1772,10 @@"settingChatAppearance.autoScrollOnStreaming.desc": "Automatically scroll to bottom when AI is generating response","settingChatAppearance.autoScrollOnStreaming.title": "Auto-scroll During AI Response","settingChatAppearance.chatBehavior.title": "Chat Behavior",+ "settingChatAppearance.followUpBehavior.desc": "Queue follow-ups while the agent runs, or steer the current run",+ "settingChatAppearance.followUpBehavior.options.queue": "Queue",+ "settingChatAppearance.followUpBehavior.options.steer": "Steer",+ "settingChatAppearance.followUpBehavior.title": "Follow-up behavior","settingChatAppearance.fontSize.desc": "Font size of messages","settingChatAppearance.fontSize.marks.normal": "Standard","settingChatAppearance.fontSize.title": "Font Size",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex edcd87ab2ba..926a6dbd321 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1756,10 +1756,16 @@"inputQueue.enqueueRejected": "队列已满。请在当前运行完成后再试。","inputQueue.queuedHint": "当前步骤完成后发送","inputQueue.queuedMergeHint": "当前步骤完成后合并发送",+ "inputQueue.queuedOneByOneHint": "当前运行完成后逐条发送","inputQueue.queuedRunEndHint": "当前运行完成后发送","inputQueue.queuedRunEndMergeHint": "当前运行完成后合并发送","inputQueue.sendNow": "立即发送(中断当前运行)","inputQueue.sendNowFailed": "没能中断当前运行,请重试",+ "inputQueue.steerDeliveryUnknownHint": "无法确认助理是否收到。可以重新发送或删除",+ "inputQueue.steerHint": "插入当前运行",+ "inputQueue.steerMergeHint": "合并成一条插入当前运行",+ "inputQueue.steerUnsupportedHint": "这个助理不支持运行中插入消息,已排队,运行完成后发送",+ "inputQueue.steerUnsupportedMergeHint": "这个助理不支持运行中插入消息,已排队,运行完成后合并发送","inputQueue.withdrawFailed": "没能撤回这条消息,请重试","intentUnderstanding.title": "正在理解你的意图…","internalLink.agent.open": "打开助理",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 2ca0d1c2863..90eb9ecaad9 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1772,6 +1772,10 @@"settingChatAppearance.autoScrollOnStreaming.desc": "当 AI 正在生成回复时,自动滚动到底部","settingChatAppearance.autoScrollOnStreaming.title": "AI 回复时自动滚动","settingChatAppearance.chatBehavior.title": "对话行为",+ "settingChatAppearance.followUpBehavior.desc": "Agent 运行时发出的消息:排到本次运行结束后再发,或插入当前运行",+ "settingChatAppearance.followUpBehavior.options.queue": "排队",+ "settingChatAppearance.followUpBehavior.options.steer": "插入",+ "settingChatAppearance.followUpBehavior.title": "运行中发送的消息","settingChatAppearance.fontSize.desc": "消息字体大小","settingChatAppearance.fontSize.marks.normal": "标准","settingChatAppearance.fontSize.title": "字体大小",diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.test.tsindex 2cbe4fd5740..785849ff68e 100644--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.test.ts@@ -29,6 +29,32 @@ const loadParityFixture = async () => {};describe('CodexAppServerAdapter', () => {+ it('reports a steered user message and answers it in a step of its own', () => {+ const adapter = new CodexAppServerAdapter({ sessionId: 'thread-1' });+ const item = (type: string, extra: Record<string, unknown>) => ({+ item: { id: `${type}-1`, type, ...extra },+ threadId: 'thread-1',+ turnId: 'turn-1',+ });+ adapter.adapt('turn/started', { threadId: 'thread-1', turn: { id: 'turn-1' } });+ adapter.adapt('item/agentMessage/delta', { delta: 'Working on it', itemId: 'm1' });++ // The prompt that started the turn carries no client id: not a steer.+ expect(adapter.adapt('item/started', item('userMessage', { clientId: null }))).toEqual([]);++ const steered = adapter.adapt('item/started', item('userMessage', { clientId: 'steer-1' }));+ expect(steered).toEqual([+ expect.objectContaining({+ data: { phase: 'user_message', uuid: 'steer-1' },+ type: 'step_complete',+ }),+ ]);++ const answer = adapter.adapt('item/agentMessage/delta', { delta: 'Sure', itemId: 'm2' });+ expect(answer.map(({ type }) => type)).toEqual(['stream_end', 'stream_start', 'stream_chunk']);+ expect(answer[1].data).toMatchObject({ newStep: true });+ });+it('carries the native turn boundary across tool-separated steps', async () => {const adapter = new CodexAppServerAdapter({ sessionId: 'native-thread' });const events = (await loadFixture()).flatMap(({ method, params }) =>diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.tsindex 6778486fa59..91778510ee0 100644--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts@@ -390,6 +390,8 @@ export class CodexAppServerAdapter {private readonly toolStateSequence = new Map<string, number>();private stepToolCalls: ToolCallPayload[] = [];private started = false;+ /** A steered message was read; the next visible output opens a new step. */+ private steerStepPending = false;private stepIndex = 0;private terminal = false;@@ -515,12 +517,15 @@ export class CodexAppServerAdapter {}private handleItemStarted({ item }: ItemStartedNotification): HeterogeneousAgentEvent[] {+ if (item.type === 'userMessage') return this.handleSteeredUserMessage(item);if (!isToolItem(item)) return [];+ const opening = this.openStepAfterSteer();this.hasToolActivity = true;const payload = toToolPayload(item);this.pendingTools.set(item.id, payload);this.stepToolCalls.push(payload);return [+ ...opening,this.makeEvent('stream_chunk', {chunkType: 'tools_calling',toolsCalling: [...this.stepToolCalls],@@ -529,6 +534,25 @@ export class CodexAppServerAdapter {];}+ /**+ * A message the host steered into the running turn (`turn/steer`): its+ * `clientId` names the delivery, so the host writes it into the+ * conversation. What the model does next answers it, in a step of its own.+ */+ private handleSteeredUserMessage(item: { clientId?: string | null }): HeterogeneousAgentEvent[] {+ if (!this.started || !item.clientId) return [];+ this.steerStepPending = true;+ return [this.makeEvent('step_complete', { phase: 'user_message', uuid: item.clientId })];+ }++ /** Close the step a steer interrupted, so the answer to it opens a new one. */+ private openStepAfterSteer(): HeterogeneousAgentEvent[] {+ if (!this.steerStepPending) return [];+ this.steerStepPending = false;+ this.hasToolActivity = true;+ return this.prepareVisibleContent('');+ }+private handleItemCompleted({ item }: ItemCompletedNotification): HeterogeneousAgentEvent[] {if (item.type === 'agentMessage') {const message = item as AgentMessageItem;@@ -739,6 +763,7 @@ export class CodexAppServerAdapter {}private prepareVisibleContent(_itemId: string): HeterogeneousAgentEvent[] {+ if (this.steerStepPending) return this.openStepAfterSteer();if (!this.hasToolActivity) return [];this.hasToolActivity = false;this.stepIndex += 1;diff --git a/packages/heterogeneous-agents/src/adapters/pi.test.ts b/packages/heterogeneous-agents/src/adapters/pi.test.tsindex 0367303d35a..b9ae2cc34b8 100644--- a/packages/heterogeneous-agents/src/adapters/pi.test.ts+++ b/packages/heterogeneous-agents/src/adapters/pi.test.ts@@ -7,6 +7,22 @@ const dataFor = (events: HeterogeneousAgentEvent[], type: HeterogeneousAgentEvenevents.filter((event) => event.type === type).map((event) => event.data);describe('PiAdapter', () => {+ it('reports a user message read mid-run by its text, and ignores the prompt', () => {+ const adapter = new PiAdapter();+ const userEnd = (content: unknown) => ({+ message: { content, role: 'user' },+ type: 'message_end',+ });++ expect(adapter.adapt(userEnd('start'))).toEqual([]);+ adapter.adapt({ type: 'turn_start' });++ const steered = adapter.adapt(userEnd([{ text: 'also run the tests', type: 'text' }]));+ expect(dataFor(steered, 'step_complete')).toEqual([+ { phase: 'user_message', text: 'also run the tests' },+ ]);+ });+it('captures the native session and maps streamed text, usage, and settlement', () => {const adapter = new PiAdapter();const events = [diff --git a/packages/heterogeneous-agents/src/adapters/pi.ts b/packages/heterogeneous-agents/src/adapters/pi.tsindex c2adf3870b1..d547d8ea0b0 100644--- a/packages/heterogeneous-agents/src/adapters/pi.ts+++ b/packages/heterogeneous-agents/src/adapters/pi.ts@@ -100,6 +100,17 @@ const normalizeToolResult = (result: any): Pick<ToolResultData, 'content' | 'plu};};+/** The text of a Pi user message (`content` is a string or text/image blocks). */+const userText = (message: any): string =>+ typeof message.content === 'string'+ ? message.content+ : Array.isArray(message.content)+ ? message.content+ .filter((block: any) => block?.type === 'text' && typeof block.text === 'string')+ .map((block: any) => block.text)+ .join('\n\n')+ : '';+/** Maps Pi's `--mode json` session event stream into shared heterogeneous events. */export class PiAdapter implements AgentEventAdapter {sessionId?: string;@@ -313,6 +324,13 @@ export class PiAdapter implements AgentEventAdapter {if (message.role === 'toolResult') {return this.completeTool(message.toolCallId, message, message.isError === true);}+ // A user message read mid-run is a steer the host sent (`steer`): Pi has+ // no id for it, so its text names the delivery. The run's own prompt is+ // read before the first turn opens.+ if (message.role === 'user') {+ if (!this.started || this.settled) return [];+ return [this.makeEvent('step_complete', { phase: 'user_message', text: userText(message) })];+ }if (message.role !== 'assistant') return [];const snapshotEvents = this.emitAssistantSnapshotSuffixes(message);if (message.stopReason === 'aborted') return [...snapshotEvents, ...this.handleAborted()];diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.tsindex c91d7f0644d..f2f1f0640fb 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts@@ -216,6 +216,68 @@ const createSession = (};describe('CodexThreadSession', () => {+ describe('steer', () => {+ const input = [{ text: 'also run the tests', text_elements: [], type: 'text' as const }];+ const startTurn = async () => {+ const harness = createClientHarness({ autoComplete: false });+ const ctx = createSession(harness);+ const running = ctx.run('op-1', 'Fix it');+ await vi.waitFor(() =>+ expect(harness.requests.some((r) => r.method === 'turn/start')).toBe(true),+ );+ const finish = async () => {+ await harness.notify('turn/completed', {+ threadId: 'thread-1',+ turn: turn('turn-1', 'completed'),+ });+ await running;+ ctx.session.close();+ };+ return { ...ctx, finish, harness };+ };++ it('adds the message to the running turn it started', async () => {+ const { finish, harness, session } = await startTurn();++ await expect(session.steer(input, 'steer-1')).resolves.toBe('accepted');++ expect(harness.requests.at(-1)).toEqual({+ method: 'turn/steer',+ params: {+ clientUserMessageId: 'steer-1',+ expectedTurnId: 'turn-1',+ input,+ threadId: 'thread-1',+ },+ });+ await finish();+ });++ it('leaves the message to a turn of its own when the turn refuses it', async () => {+ const { finish, harness, session } = await startTurn();+ const request = harness.client.request.getMockImplementation();+ harness.client.request.mockImplementation(async (method: string, params: unknown) => {+ if (method === 'turn/steer') {+ throw new CodexAppServerRpcError('not steerable', -32600, {+ codexErrorInfo: { activeTurnNotSteerable: { turnKind: 'review' } },+ });+ }+ return request!(method, params);+ });++ await expect(session.steer(input, 'steer-1')).resolves.toBe('rejected');+ await finish();+ });++ it('refuses with no turn running', async () => {+ const harness = createClientHarness();+ const { session } = createSession(harness);++ await expect(session.steer(input, 'steer-1')).resolves.toBe('rejected');+ expect(harness.requests).toEqual([]);+ });+ });+describe('native user input', () => {const contexts: Array<{ bridge: AskUserBridge; session: CodexThreadSession }> = [];afterEach(() => {diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.tsindex 2aa0d0232fb..93d1402f8ea 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts@@ -7,7 +7,7 @@ import type { HeterogeneousAgentRuntimeStatus } from '../spawn/claudeAgentSdkSesimport { toStreamEvent } from '../spawn/streamEvent';import type { UsageData } from '../types';import type { CodexAppServerClient } from './CodexAppServerClient';-import { CodexAppServerConnectionError } from './CodexAppServerClient';+import { CodexAppServerConnectionError, CodexAppServerRpcError } from './CodexAppServerClient';import type { CodexRunProvenance } from './environment';import { isSameCodexRunProvenance, withCodexThreadEnv } from './environment';import type {@@ -58,6 +58,17 @@ interface ActiveTurn {turnId?: string;}+/** `turn/steer` (app-server v2): add input to the active turn, which must still be `expectedTurnId`. */+interface TurnSteerParams {+ clientUserMessageId?: string | null;+ expectedTurnId: string;+ input: TurnStartParams['input'];+ threadId: string;+}++/** How a steer ended: taken by the active turn, or left for a turn of its own. */+export type CodexSteerOutcome = 'accepted' | 'rejected';+interface ThreadNameSetParams {name: string;threadId: string;@@ -215,6 +226,38 @@ export class CodexThreadSession {}}+ /**+ * Add a user message to the running turn (`turn/steer`). The model reads it+ * at its next step; the app-server reports it back as a `userMessage` item+ * carrying `clientUserMessageId`. A turn that cannot take input (none+ * running, a review or compaction turn, a different turn than the one+ * started here) refuses it, and the caller sends it as a turn of its own.+ */+ async steer(+ input: TurnStartParams['input'],+ clientUserMessageId: string,+ ): Promise<CodexSteerOutcome> {+ const activeTurn = this.activeTurn;+ const threadId = this.threadId;+ if (!activeTurn?.turnId || !threadId || activeTurn.interruptRequested || this.closedByHost)+ return 'rejected';++ try {+ const params: TurnSteerParams = {+ clientUserMessageId,+ expectedTurnId: activeTurn.turnId,+ input,+ threadId,+ };+ await this.options.client.request('turn/steer', params);+ return 'accepted';+ } catch (error) {+ // A definite refusal (`activeTurnNotSteerable`, a turn mismatch) was not stored.+ if (error instanceof CodexAppServerRpcError) return 'rejected';+ throw error;+ }+ }+async interrupt(): Promise<void> {if (!this.running) return;this.interruptRequested = true;diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.tsindex ad89e6a2ccd..dd92e23fe3d 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.test.ts@@ -260,3 +260,152 @@ describe('ClaudeAgentSdkSession plugins', () => {expect(options).not.toHaveProperty('plugins');});});++describe('ClaudeAgentSdkSession steer', () => {+ afterEach(() => {+ sdkQueryMock.mockReset();+ });++ it('hands a steered message to the running query, with no priority, and waits for its answer', async () => {+ const steeredInputs: any[] = [];+ let ready!: () => void;+ const started = new Promise<void>((resolve) => {+ ready = resolve;+ });+ let queryOptions: any;+ sdkQueryMock.mockImplementation(({ options, prompt }) => {+ queryOptions = options;+ const input = prompt[Symbol.asyncIterator]();+ return {+ async *[Symbol.asyncIterator]() {+ await input.next();+ yield { session_id: 's', subtype: 'init', type: 'system' };+ ready();+ const steered = await input.next();+ steeredInputs.push(steered.value);+ // Written as the cycle ended: its result comes before the message is read.+ yield {+ is_error: false,+ subtype: 'success',+ terminal_reason: 'completed',+ type: 'result',+ };+ yield {+ isReplay: true,+ message: { content: 'x', role: 'user' },+ type: 'user',+ uuid: 'steer-1',+ };+ yield { is_error: false, result: 'ok', subtype: 'success', type: 'result' };+ // Answered: input closes, and the query ends.+ expect((await input.next()).done).toBe(true);+ },+ close: vi.fn(),+ };+ });++ const session = new ClaudeAgentSdkSession({+ args: [],+ commandPath: 'claude',+ cwd: os.tmpdir(),+ env: {} as NodeJS.ProcessEnv,+ onEvents: () => {},+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-steer',+ replayUserMessages: true,+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({ message: { content: 'go', role: 'user' }, type: 'user' })}\n`,+ });+ const running = session.run();+ await started;++ expect(+ session.steer(+ {+ message: { content: 'also this', role: 'user' },+ parent_tool_use_id: null,+ type: 'user',+ } as any,+ 'steer-1',+ ),+ ).toBe(true);+ await running;++ expect(steeredInputs[0]).toMatchObject({ type: 'user', uuid: 'steer-1' });+ expect(steeredInputs[0]).not.toHaveProperty('priority');+ expect(queryOptions.extraArgs).toMatchObject({ 'replay-user-messages': null });+ // Input has closed: a later steer goes as a turn of its own.+ expect(session.steer({ message: { content: 'late', role: 'user' } } as any, 'steer-2')).toBe(+ false,+ );+ });+});++describe('ClaudeAgentSdkSession steer and background-task notifications', () => {+ afterEach(() => {+ sdkQueryMock.mockReset();+ });++ it('settles a notification turn that ends while a steer waits, so input still closes after it', async () => {+ let ready!: () => void;+ const started = new Promise<void>((resolve) => {+ ready = resolve;+ });+ let inputDone = false;+ sdkQueryMock.mockImplementation(({ prompt }) => {+ const input = prompt[Symbol.asyncIterator]();+ return {+ async *[Symbol.asyncIterator]() {+ await input.next();+ yield { session_id: 's', subtype: 'init', type: 'system' };+ yield { session_id: 's', subtype: 'task_started', task_id: 't1', type: 'system' };+ ready();+ await input.next(); // the steer+ yield { session_id: 's', subtype: 'task_notification', task_id: 't1', type: 'system' };+ // The notification's turn ends before the steer is read.+ yield {+ is_error: false,+ origin: { kind: 'task-notification' },+ subtype: 'success',+ type: 'result',+ };+ yield {+ isReplay: true,+ message: { content: 'x', role: 'user' },+ type: 'user',+ uuid: 'steer-1',+ };+ yield { is_error: false, subtype: 'success', type: 'result' };+ inputDone = (await input.next()).done === true;+ },+ close: vi.fn(),+ };+ });++ const session = new ClaudeAgentSdkSession({+ args: [],+ commandPath: 'claude',+ cwd: os.tmpdir(),+ env: {} as NodeJS.ProcessEnv,+ onEvents: () => {},+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-notify',+ replayUserMessages: true,+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({ message: { content: 'go', role: 'user' }, type: 'user' })}\n`,+ });+ const running = session.run();+ await started;+ session.steer({ message: { content: 'also', role: 'user' }, type: 'user' } as any, 'steer-1');+ await running;++ // The steer's answer closed input: no notification left pending holds it open.+ expect(inputDone).toBe(true);+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex f58d1353e51..090c769fb9e 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -18,6 +18,8 @@ import { resolveCliSpawnPlan } from './cliSpawn';const CLAUDE_SDK_DISALLOWED_TOOLS = ['AskUserQuestion', 'Monitor', 'ScheduleWakeup'] as const;const DEFAULT_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;const INPUT_CLOSE_POLL_MS = 1000;+/** How often the input stream checks for a steered message to hand over. */+const STEER_POLL_MS = 100;const readTimeoutMs = (name: string, fallback: number) => {const raw = process.env[name];@@ -183,6 +185,11 @@ export interface ClaudeAgentSdkSessionOptions {onSessionId: (sessionId: string) => void;onStderr: (data: string) => Promise<void> | void;operationId: string;+ /**+ * Have Claude Code replay every user message it reads (`--replay-user-messages`),+ * so a message `steer` delivers is known to be picked up.+ */+ replayUserMessages?: boolean;resumeSessionId?: string;sessionId: string;stdinPayload: string;@@ -243,6 +250,10 @@ export class ClaudeAgentSdkSession {private pipeline: AgentStreamPipeline;private queryHandle: ClaudeAgentSdkQuery | undefined;private sawErrorEvent = false;+ /** Messages `steer` queued for the input stream, not yet handed to the SDK. */+ private readonly steerQueue: SDKUserMessage[] = [];+ /** Steered messages Claude Code has not replayed yet; input stays open for them. */+ private readonly unconsumed = new Set<string>();private taskNotificationPending = false;constructor(private readonly options: ClaudeAgentSdkSessionOptions) {@@ -313,6 +324,23 @@ export class ClaudeAgentSdkSession {}}+ /**+ * Deliver a user message into the running session. Claude Code reads it at+ * its next tool boundary, so a running tool is never cut short (a message+ * sent with `priority: 'now'` would abort it). Claude Code replays it under+ * `uuid` once read (with `replayUserMessages`); until then+ * input stays open for it.+ *+ * @returns false once input has closed, so the caller runs it as a new turn+ */+ steer(message: SDKUserMessage, uuid: string): boolean {+ if (this.closeInput || this.abortController.signal.aborted) return false;++ this.unconsumed.add(uuid);+ this.steerQueue.push({ ...message, uuid: uuid as SDKUserMessage['uuid'] });+ return true;+ }+close(): void {this.closedByHost = true;this.closeInput = true;@@ -344,6 +372,9 @@ export class ClaudeAgentSdkSession {}),...(this.options.resumeSessionId ? { resume: this.options.resumeSessionId } : {}),...argOptions,+ ...(this.options.replayUserMessages && {+ extraArgs: { ...argOptions.extraArgs, 'replay-user-messages': null },+ }),stderr: (data) => {void this.options.onStderr(data);},@@ -354,7 +385,12 @@ export class ClaudeAgentSdkSession {yield message;while (!this.closeInput && !this.abortController.signal.aborted) {- await sleep(INPUT_CLOSE_POLL_MS);+ const steered = this.steerQueue.shift();+ if (steered) {+ yield steered;+ continue;+ }+ await sleep(this.unconsumed.size > 0 ? STEER_POLL_MS : INPUT_CLOSE_POLL_MS);}}@@ -362,6 +398,9 @@ export class ClaudeAgentSdkSession {this.lastEventAt = Date.now();this.armInactivityTimer();this.updateTaskState(message);+ if (message.type === 'user' && 'isReplay' in message && message.isReplay) {+ this.unconsumed.delete(message.uuid);+ }const line = `${JSON.stringify(message)}\n`;await this.options.onRawMessage(line);@@ -429,9 +468,14 @@ export class ClaudeAgentSdkSession {private maybeCloseInputAfterResult(message: SDKMessage): void {if (message.type !== 'result') return;-- if (message.origin?.kind === 'task-notification') {- this.taskNotificationPending = false;+ const notificationTurn = message.origin?.kind === 'task-notification';+ // The notification's turn is over, whether or not input closes now.+ if (notificationTurn) this.taskNotificationPending = false;+ // A message written as a cycle ends is read after that cycle's result;+ // it still has to be read and answered.+ if (this.unconsumed.size > 0 || this.steerQueue.length > 0) return;++ if (notificationTurn) {this.closeInput = true;return;}diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.tsindex 6e874c65eef..ebb4b636368 100644--- a/packages/heterogeneous-agents/src/types.ts+++ b/packages/heterogeneous-agents/src/types.ts@@ -351,6 +351,11 @@ export interface StepCompleteData {* CLI provider, not on the wrapped model's native vendor.*/provider?: string;+ /**+ * The text of a user message read mid-run (only on `user_message`), for an+ * agent that reports no id for it (Pi).+ */+ text?: string;usage?: UsageData;/** The replayed message's uuid (only on `user_message`). */uuid?: string;diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex ceea4dd2939..fdcedc7b06b 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1083,6 +1083,15 @@ export default {'inputQueue.queuedMergeHint': 'Merged and sent when the current step finishes','inputQueue.queuedRunEndHint': 'Sends when the current run finishes','inputQueue.queuedRunEndMergeHint': 'Merged and sent when the current run finishes',+ 'inputQueue.queuedOneByOneHint': 'Sent one at a time after the current run finishes',+ 'inputQueue.steerDeliveryUnknownHint':+ 'Couldn’t confirm the agent got this. Send it again or delete it',+ 'inputQueue.steerHint': 'Joins the current run',+ 'inputQueue.steerMergeHint': 'Joins the current run as one message',+ 'inputQueue.steerUnsupportedHint':+ 'This agent can’t take messages mid-run. Queued until the run finishes',+ 'inputQueue.steerUnsupportedMergeHint':+ 'This agent can’t take messages mid-run. Queued, merged and sent when the run finishes','inputQueue.sendNow': 'Send now (interrupts current run)','inputQueue.sendNowFailed': 'Couldn’t interrupt the current run. Try again.','inputQueue.alreadyDelivered': 'Already sent to the agent',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 0f316bf2105..7c6be341d42 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1565,6 +1565,11 @@ export default {'settingChatAppearance.autoScrollOnStreaming.title': 'Auto-scroll During AI Response','settingChatAppearance.chatBehavior.title': 'Chat Behavior','settingChatAppearance.workflowStreamingExpand.title': 'Expand Tool Steps While Running',+ 'settingChatAppearance.followUpBehavior.desc':+ 'Queue follow-ups while the agent runs, or steer the current run',+ 'settingChatAppearance.followUpBehavior.options.queue': 'Queue',+ 'settingChatAppearance.followUpBehavior.options.steer': 'Steer',+ 'settingChatAppearance.followUpBehavior.title': 'Follow-up behavior','settingChatAppearance.fontSize.desc': 'Font size of messages','settingChatAppearance.fontSize.marks.normal': 'Standard','settingChatAppearance.fontSize.title': 'Font Size',diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.tsindex a50a8ef14a3..ab0bd848954 100644--- a/packages/types/src/message/ui/params.ts+++ b/packages/types/src/message/ui/params.ts@@ -199,6 +199,11 @@ export interface SendMessageParams {* remain available after the audio-only turn is dispatched.*/preserveComposer?: boolean;+ /**+ * The head of a queue sent one message per turn (Follow-up behavior: Queue).+ * The rest of that queue waits behind this send instead of joining it.+ */+ queueHead?: boolean;/*** Cancels the send before the conversation lifecycle accepts ownership of the turn.* Once `onMessageAccepted` fires, later aborts are ignored and the existing runtime Stop flowdiff --git a/packages/types/src/user/settings/general.ts b/packages/types/src/user/settings/general.tsindex 95f7e87b645..0fc71856d1e 100644--- a/packages/types/src/user/settings/general.ts+++ b/packages/types/src/user/settings/general.ts@@ -6,6 +6,22 @@ export type AnimationMode = 'disabled' | 'agile' | 'elegant';export type ContextMenuMode = 'disabled' | 'default';+/**+ * What a message sent while the agent runs does (Better Coding Experience+ * lab): `queue` waits for the run to end and sends one message per turn;+ * `steer` joins the running turn at a point the agent picks.+ */+export type FollowUpBehavior = 'queue' | 'steer';++/** The behavior in effect: `legacy` while the lab is off (the setting is not read). */+export type FollowUpMode = FollowUpBehavior | 'legacy';++/** Resolve the behavior in effect from the lab switch and the stored setting. */+export const resolveFollowUpMode = (+ labEnabled: boolean | undefined,+ setting: FollowUpBehavior | undefined,+): FollowUpMode => (labEnabled ? (setting ?? 'steer') : 'legacy');+export interface UserGeneralConfig {animationMode?: AnimationMode;contextMenuMode?: ContextMenuMode;@@ -33,6 +49,12 @@ export interface UserGeneralConfig {* @default false*/expandWorkflowWhileStreaming?: boolean;+ /**+ * Messages sent while the agent runs; read only with the Better Coding+ * Experience lab on.+ * @default 'steer'+ */+ followUpBehavior?: FollowUpBehavior;/*** Grayscale font antialiasing on macOS. Off falls back to the system default rendering.* @default truediff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsxindex eaab6dbb136..95330e6f825 100644--- a/src/features/Conversation/ChatInput/QueueTray.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.tsx@@ -9,6 +9,7 @@ import FileIcon from '@/components/FileIcon';import { useSingleton } from '@/hooks/useSingleton';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';+import { canSteerClientRun } from '@/store/chat/slices/agentRun/actions/transports/client/clientSteer';import {isServerDeliveringQueuedMessage,type QueuedFile,@@ -17,6 +18,8 @@ import {} from '@/store/chat/slices/operation/types';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useFileStore } from '@/store/file';+import { useUserStore } from '@/store/user';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';import { useConversationResourceAccess } from '../hooks/useConversationResourceAccess';import { useConversationStore } from '../store';@@ -208,6 +211,7 @@ const QueueTray = memo(() => {const queuedMessages = useChatStore((s) => operationSelectors.getQueuedMessages(context)(s));const waitsForRunEnd = useChatStore(operationSelectors.isQueueDrainedAtRunEnd(context));+ const followUpMode = useUserStore(userGeneralSettingsSelectors.followUpBehavior);const withdrawQueuedMessage = useChatStore((s) => s.withdrawQueuedMessage);const dispatchChatUploadFileList = useFileStore((s) => s.dispatchChatUploadFileList);const editor = useConversationStore((s) => s.editor);@@ -310,8 +314,10 @@ const QueueTray = memo(() => {// CLI run only drains once the whole run ends, not after the current step.// One a run already took is no longer part of that merge: it says where it// is instead and offers nothing to do with it.- const waitingCount = queuedMessages.filter((msg) => !isServerDeliveringQueuedMessage(msg)).length;- const hintText = t(getQueuedHintKey({ count: waitingCount, waitsForRunEnd }));+ const waitingCount = queuedMessages.filter(+ (msg) => !isServerDeliveringQueuedMessage(msg) && !msg.localSteer,+ ).length;+ const hintText = t(getQueuedHintKey({ count: waitingCount, mode: followUpMode, waitsForRunEnd }));return (<Flexbox className={styles.container} gap={0}>@@ -319,8 +325,17 @@ const QueueTray = memo(() => {const previews = msg.filesPreview ?? [];// A "send now" in progress keeps its row as is: it is interrupting the// run to take this message back, and shows that with its spinner.- const delivering = isServerDeliveringQueuedMessage(msg) && sendingId !== msg.id;- const rowHint = delivering ? t('inputQueue.deliveringHint') : hintText;+ const delivering =+ (isServerDeliveringQueuedMessage(msg) || msg.localSteer === 'delivering') &&+ sendingId !== msg.id;+ const rowHint = delivering+ ? t('inputQueue.deliveringHint')+ : msg.localSteer === 'unknown'+ ? t('inputQueue.steerDeliveryUnknownHint')+ : // An attachment or selection cannot join a running turn; it starts the next one.+ followUpMode === 'steer' && !waitsForRunEnd && !canSteerClientRun(msg)+ ? t('inputQueue.queuedHint')+ : hintText;return (<Flexboxhorizontaldiff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.tsindex f7e71567269..a6cb3196cc3 100644--- a/src/features/Conversation/ChatInput/utils.test.ts+++ b/src/features/Conversation/ChatInput/utils.test.ts@@ -58,6 +58,35 @@ describe('createQueueSendNowGate', () => {});});+describe('getQueuedHintKey by Follow-up behavior', () => {+ it('says Queue sends one message per turn once the run ends', () => {+ expect(getQueuedHintKey({ count: 1, mode: 'queue', waitsForRunEnd: false })).toBe(+ 'inputQueue.queuedRunEndHint',+ );+ expect(getQueuedHintKey({ count: 2, mode: 'queue', waitsForRunEnd: false })).toBe(+ 'inputQueue.queuedOneByOneHint',+ );+ });++ it('says Steer joins the current run, merged', () => {+ expect(getQueuedHintKey({ count: 1, mode: 'steer', waitsForRunEnd: false })).toBe(+ 'inputQueue.steerHint',+ );+ expect(getQueuedHintKey({ count: 3, mode: 'steer', waitsForRunEnd: false })).toBe(+ 'inputQueue.steerMergeHint',+ );+ });++ it('says a run that cannot take a steer queues it until the end', () => {+ expect(getQueuedHintKey({ count: 1, mode: 'steer', waitsForRunEnd: true })).toBe(+ 'inputQueue.steerUnsupportedHint',+ );+ expect(getQueuedHintKey({ count: 2, mode: 'steer', waitsForRunEnd: true })).toBe(+ 'inputQueue.steerUnsupportedMergeHint',+ );+ });+});+describe('getQueuedHintKey', () => {it('promises the next step boundary for the built-in runtime', () => {expect(getQueuedHintKey({ count: 1, waitsForRunEnd: false })).toBe('inputQueue.queuedHint');diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.tsindex ece31119228..03ac01aabdf 100644--- a/src/features/Conversation/ChatInput/utils.ts+++ b/src/features/Conversation/ChatInput/utils.ts@@ -1,5 +1,10 @@import { getSlicedMessages } from '@lobechat/context-engine';-import type { ConversationContext, OpenAIChatMessage, UIChatMessage } from '@lobechat/types';+import type {+ ConversationContext,+ FollowUpMode,+ OpenAIChatMessage,+ UIChatMessage,+} from '@lobechat/types';import type { PlaceholderVariant } from '@/features/ChatInput/InputEditor/Placeholder';import type { ContextWindow, SendButtonProps } from '@/features/ChatInput/store/initialState';@@ -79,13 +84,26 @@ export const createQueueSendNowGate = (): QueueSendNowGate => {*/export const getQueuedHintKey = ({count,+ mode = 'legacy',waitsForRunEnd,}: {count: number;+ /** The Follow-up behavior in effect (`legacy` while its lab is off). */+ mode?: FollowUpMode;waitsForRunEnd: boolean;}) => {const merged = count > 1;+ // Queue: every follow-up waits for the run end, then goes one per turn.+ if (mode === 'queue')+ return merged ? 'inputQueue.queuedOneByOneHint' : 'inputQueue.queuedRunEndHint';+ // Steer: joins the running turn, unless this run cannot take one mid-run.+ if (mode === 'steer') {+ if (waitsForRunEnd)+ return merged ? 'inputQueue.steerUnsupportedMergeHint' : 'inputQueue.steerUnsupportedHint';+ return merged ? 'inputQueue.steerMergeHint' : 'inputQueue.steerHint';+ }+if (waitsForRunEnd)return merged ? 'inputQueue.queuedRunEndMergeHint' : 'inputQueue.queuedRunEndHint';diff --git a/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx b/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsxindex fe19e4ed61b..c746d6a9281 100644--- a/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx+++ b/src/features/Settings/chat-appearance/features/ChatAppearance/index.tsx@@ -11,7 +11,11 @@ import { ChatAppearanceSectionSkeleton } from '@/components/Skeleton/Settings/taimport { FORM_STYLE } from '@/const/layoutTokens';import { useSaveState } from '@/hooks/useSaveState';import { useUserStore } from '@/store/user';-import { settingsSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';+import {+ labPreferSelectors,+ settingsSelectors,+ userGeneralSettingsSelectors,+} from '@/store/user/selectors';import ChatTransitionPreview from './ChatTransitionPreview';import HighlighterPreview from './HighlighterPreview';@@ -22,6 +26,9 @@ const ChatAppearance = memo(() => {const { t } = useTranslation('setting');const { general } = useUserStore(settingsSelectors.currentSettings, isEqual);const enablePasteAutoConvert = useUserStore(userGeneralSettingsSelectors.enablePasteAutoConvert);+ const enableBetterCodingExperience = useUserStore(+ labPreferSelectors.enableBetterCodingExperience,+ );const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();const [savingKey, setSavingKey] = useState<string>();@@ -149,6 +156,35 @@ const ChatAppearance = memo(() => {label: t('settingChatAppearance.pasteAutoConvert.title'),minWidth: undefined,},+ ...(enableBetterCodingExperience+ ? [+ {+ children: (+ <Flexbox horizontal align={'center'} gap={8}>+ {renderSaveHint('followUpBehavior')}+ <Select+ style={{ width: 160 }}+ value={general.followUpBehavior ?? 'steer'}+ options={[+ {+ label: t('settingChatAppearance.followUpBehavior.options.queue'),+ value: 'queue',+ },+ {+ label: t('settingChatAppearance.followUpBehavior.options.steer'),+ value: 'steer',+ },+ ]}+ onChange={(value) => handleChange('followUpBehavior', value)}+ />+ </Flexbox>+ ),+ desc: t('settingChatAppearance.followUpBehavior.desc'),+ label: t('settingChatAppearance.followUpBehavior.title'),+ minWidth: undefined,+ },+ ]+ : []),],title: t('settingChatAppearance.chatBehavior.title'),},diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex 48c1a6271cc..b35e10d5b2f 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -54,6 +54,8 @@ 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;/**@@ -73,6 +75,21 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.sendPrompt(params);}+ /**+ * Deliver a message into the session's running turn (Follow-up behavior:+ * Steer). `accepted` means it was written; the agent confirms reading it+ * with a `step_complete { phase: 'user_message' }` event naming `messageId`+ * (or, for Pi, its text). Throws when the outcome is unknown.+ */+ async steerSession(params: {+ imageList?: Array<{ id: string; url: string }>;+ messageId: string;+ prompt: string;+ sessionId: string;+ }): Promise<{ deliveredText?: string; status: 'accepted' | 'rejected' | 'unsupported' }> {+ return this.ipc.heterogeneousAgent.steerSession(params);+ }+async cancelSession(sessionId: string) {return this.ipc.heterogeneousAgent.cancelSession({ sessionId });}diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.queueHead.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.queueHead.test.tsnew file mode 100644index 00000000000..0b9ba851dbc--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.queueHead.test.ts@@ -0,0 +1,97 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { agentService } from '@/services/agent';+import { aiAgentService } from '@/services/aiAgent';+import { getSessionStoreState } from '@/store/session';+import { useUserStore } from '@/store/user';++import { useChatStore } from '../../../../store';+import { messageMapKey } from '../../../../utils/messageMapKey';+import { createMockAgentConfig, TEST_IDS } from './fixtures';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';++vi.mock('../transports/hetero/heterogeneousAgentExecutor', () => ({+ executeHeterogeneousAgent: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },+ },+}));++const context = { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: TEST_IDS.TOPIC_ID };+const contextKey = messageMapKey(context);++beforeEach(() => {+ resetTestEnvironment();+ setupMockSelectors();+ spyOnMessageService();+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);+ vi.spyOn(aiAgentService, 'listQueuedFollowUps').mockResolvedValue([]);+ useUserStore.setState({ workspaceUserPreference: {} });++ act(() => {+ useChatStore.setState({+ executeClientAgent: vi.fn(),+ executeGatewayAgent: vi.fn(),+ isGatewayModeEnabled: () => false,+ mainInputEditor: null,+ // The run the queue waited behind has just completed.+ operations: {+ 'op-done': {+ childOperationIds: [],+ context,+ id: 'op-done',+ metadata: { startTime: 1 },+ status: 'completed',+ type: 'execAgentRuntime',+ },+ } as any,+ operationsByContext: { [contextKey]: ['op-done'] },+ queuedMessages: {+ [contextKey]: [{ content: 'second', createdAt: 2, id: 'queued-2', interruptMode: 'soft' }],+ },+ refreshMessages: vi.fn(),+ refreshTopic: vi.fn(),+ });+ });+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('sendMessage of a queue head (Follow-up behavior: Queue)', () => {+ it('starts its own turn and leaves the rest of the queue behind it', async () => {+ const { result } = renderHook(() => useChatStore());+ const enqueue = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({ context, message: 'first', queueHead: true });+ });++ expect(enqueue).not.toHaveBeenCalled();+ expect(useChatStore.getState().queuedMessages[contextKey].map((m) => m.id)).toEqual([+ 'queued-2',+ ]);+ });++ it('without the mark, a send behind a waiting queue joins it (legacy behavior)', async () => {+ const { result } = renderHook(() => useChatStore());+ const enqueue = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({ context, message: 'first' });+ });++ expect(enqueue).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({ content: 'first' }),+ undefined,+ );+ });+});diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.tsnew file mode 100644index 00000000000..7e3882a7ab8--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.ts@@ -0,0 +1,98 @@+import * as agentRuntime from '@lobechat/agent-runtime';+import type { UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { chatService } from '@/services/chat';+import { workService } from '@/services/work';+import { useAgentStore } from '@/store/agent';+import { useAiInfraStore } from '@/store/aiInfra';++import { useChatStore } from '../../../../store';+import { messageMapKey } from '../../../../utils/messageMapKey';+import { TEST_CONTENT, TEST_IDS } from './fixtures';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';++const mode = vi.hoisted(() => ({ value: 'legacy' as 'legacy' | 'queue' | 'steer' }));+vi.mock('../lifecycle/followUpMode', () => ({ getFollowUpMode: () => mode.value }));+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),+}));++const realExecAgentRuntime = useChatStore.getState().executeClientAgent;+const context = { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID };+const userMessage = {+ content: TEST_CONTENT.USER_MESSAGE,+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ sessionId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+} as UIChatMessage;++beforeEach(() => {+ resetTestEnvironment();+ setupMockSelectors();+ spyOnMessageService();+ vi.spyOn(workService, 'listByRootOperation').mockResolvedValue([]);+ vi.spyOn(chatService, 'buildAssistantMessageContext').mockImplementation(+ async (params, options) => ({+ options: options ?? {},+ params: { ...params, messages: params.messages as any } as any,+ replayAssistantReasoning: false,+ }),+ );+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (_params, options) => {+ options?.onMessageHandle?.({ text: TEST_CONTENT.AI_RESPONSE, type: 'text' } as any);+ await options?.onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);+ return new Response();+ });+ act(() => {+ useAgentStore.setState({ availableAgents: [] });+ useAiInfraStore.setState({ isInitAiProviderRuntimeState: true });+ useChatStore.setState((state) => ({+ dbMessagesMap: { ...state.dbMessagesMap, [messageMapKey(context)]: [userMessage] },+ executeClientAgent: realExecAgentRuntime,+ queuedMessages: {+ [messageMapKey(context)]: [+ { content: 'queued', createdAt: Date.now(), id: 'q1', interruptMode: 'soft' },+ ],+ },+ refreshMessages: vi.fn(),+ }));+ });+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++/** Whether the run was told, at its first step, that messages wait behind it. */+const firstStepSeesQueue = async () => {+ vi.useFakeTimers({ toFake: ['setTimeout'] });+ const stepSpy = vi.spyOn(agentRuntime.AgentRuntime.prototype, 'step');+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.executeClientAgent({+ context,+ messages: [userMessage],+ parentMessageId: userMessage.id,+ parentMessageType: 'user',+ });+ });++ return stepSpy.mock.calls[0][1]?.stepContext?.hasQueuedMessages;+};++describe('client run and the Follow-up behavior', () => {+ it('hands the turn back for queued messages on the legacy behavior', async () => {+ mode.value = 'legacy';+ await expect(firstStepSeesQueue()).resolves.toBe(true);+ });++ it('lets the run finish in Queue mode: the queue starts once it ends', async () => {+ mode.value = 'queue';+ await expect(firstStepSeesQueue()).resolves.toBeFalsy();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 92e31788001..8cce8f77e1f 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -69,8 +69,9 @@ import {import { resolveNewThreadIntent } from '@/store/chat/slices/agentRun/actions/dispatch/newThreadIntent';import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';import {+ drainQueuedTurn,findOrphanedQueueKey,- sendQueuedMessages,+ sendQueuedTurn,} from '@/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp';import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';import { buildQueuedFollowUpRequest } from '@/store/chat/slices/agentRun/actions/transports/gateway/execRequest';@@ -274,6 +275,7 @@ export class ConversationLifecycleActionImpl {onMessagePersisted,onTopicCreated,preserveComposer,+ queueHead,signal,sourceTopic,}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {@@ -299,8 +301,7 @@ export class ConversationLifecycleActionImpl {if (hasNotifiedMessageAccepted) return;hasNotifiedMessageAccepted = true;- // Queued messages are accepted before a send operation exists. For actual- // sends, acceptance ends the optimistic phase for every runtime.+ // Queued messages are accepted before a send operation exists; a send's acceptance ends its optimistic phase.if (sendOperationId) {this.#get().updateOperationMetadata(sendOperationId, { inputEditorTempState: null });}@@ -623,17 +624,14 @@ export class ConversationLifecycleActionImpl {const newTopicTitle = markdownToTxt(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });// ━━━ Message Queue: enqueue if this context is already busy ━━━- // Include the initial `sendMessage` persist/create-topic phase. Example:- // first send from a blank chat is still creating topic A (`topicId=null`);- // a fast second Enter must queue on `main_<agent>_new` instead of starting- // topic B.+ // Include the initial `sendMessage` persist/create-topic phase: while a first+ // send is still creating topic A, a fast second Enter queues on+ // `main_<agent>_new` instead of starting topic B.const currentContextKey = messageMapKey(operationContext);- // A new-topic send must ALSO queue behind a send that is still creating its- // topic for this same conversation surface. That earlier send's operation is- // registered under ITS minted topic's bucket (the context adopted the id up- // front), so probing only this send's key would miss it — a fast second- // Enter would start a concurrent topic instead of queueing. `creatingTopicIds`- // names exactly those in-flight buckets.+ // A new-topic send must ALSO queue behind a send still creating its topic for+ // this surface. That send's operation is registered under ITS minted topic's+ // bucket, so probing only this send's key would miss it and a fast second+ // Enter would start a concurrent topic. `creatingTopicIds` names those buckets.const queueCandidateKeys = [currentContextKey,...(willCreateNewTopic@@ -656,9 +654,11 @@ export class ConversationLifecycleActionImpl {break;}}+ // The head of a queue drained one per turn starts its turn; the rest waits behind it.const queueDrainPending =!runningQueueBlockingOp &&!onlyAddUserMessage &&+ !queueHead &&operationSelectors.isQueueDrainPending(operationContext)(this.#get());const canQueue = (key: string) =>!onlyAddUserMessage &&@@ -718,7 +718,7 @@ export class ConversationLifecycleActionImpl {queueCandidateKeys,willCreateNewTopic,);- if (orphanedQueueKey && !onlyAddUserMessage) {+ if (orphanedQueueKey && !onlyAddUserMessage && !queueHead) {this.#get().enqueueMessage(orphanedQueueKey, {content: message,createdAt: Date.now(),@@ -730,11 +730,11 @@ export class ConversationLifecycleActionImpl {interruptMode: 'soft',metadata: userMessageMetadata,});- const restarted = this.#get().drainQueuedMessages(orphanedQueueKey);+ const restarted = drainQueuedTurn(this.#get, orphanedQueueKey);notifyMessageAccepted();setTimeout(() => {- sendQueuedMessages(this.#get, operationContext, restarted).catch((error: unknown) => {+ sendQueuedTurn(this.#get, operationContext, restarted).catch((error: unknown) => {console.error('[sendMessage] restarting queued content after Stop failed:', error);});}, 0);diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.tsnew file mode 100644index 00000000000..1054f41d04a--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.ts@@ -0,0 +1,112 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { QueuedMessage } from '@/store/chat/slices/operation/types';+import type { ChatStore } from '@/store/chat/store';++import { drainQueuedTurn, findOrphanedQueueKey, scheduleQueuedFollowUp } from '../queuedFollowUp';++const mode = vi.hoisted(() => ({ value: 'legacy' as 'legacy' | 'queue' | 'steer' }));+vi.mock('../followUpMode', () => ({ getFollowUpMode: () => mode.value }));++const queued = (+ id: string,+ content: string,+ extra: Partial<QueuedMessage> = {},+): QueuedMessage => ({+ content,+ createdAt: Number(id.slice(1)),+ id,+ interruptMode: 'soft',+ ...extra,+});++const createStore = (messages: QueuedMessage[]) => {+ const state = { queue: [...messages] };+ const store = {+ drainQueuedMessages: vi.fn((_key: string, options?: { limit?: number }) => {+ const taken = options?.limit ? state.queue.slice(0, options.limit) : [...state.queue];+ state.queue = state.queue.slice(taken.length);+ return taken;+ }),+ operations: {},+ operationsByContext: {},+ sendMessage: vi.fn().mockResolvedValue(undefined),+ } as unknown as ChatStore;+ return { get: () => store, state, store };+};++describe('drainQueuedTurn', () => {+ it('takes the whole queue as one turn outside Queue mode', () => {+ mode.value = 'steer';+ const { get, state } = createStore([queued('q1', 'a'), queued('q2', 'b')]);++ const turn = drainQueuedTurn(get, 'key');++ expect(turn.messages.map((m) => m.id)).toEqual(['q1', 'q2']);+ expect(turn.queueHead).toBeUndefined();+ expect(state.queue).toEqual([]);+ });++ it('takes only the head in Queue mode and leaves the rest queued', () => {+ mode.value = 'queue';+ const { get, state } = createStore([queued('q1', 'a'), queued('q2', 'b')]);++ const turn = drainQueuedTurn(get, 'key');++ expect(turn.messages.map((m) => m.id)).toEqual(['q1']);+ expect(turn.queueHead).toBe(true);+ expect(state.queue.map((m) => m.id)).toEqual(['q2']);+ });+});++describe('scheduleQueuedFollowUp', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ const context = { agentId: 'agent-1', topicId: 'topic-1' };++ it('merges everything queued into one send on the legacy behavior', () => {+ mode.value = 'legacy';+ const { get, store } = createStore([queued('q1', 'first'), queued('q2', 'second')]);++ scheduleQueuedFollowUp(get, context, 'op-1');+ vi.advanceTimersByTime(100);++ expect(store.sendMessage).toHaveBeenCalledTimes(1);+ const params = vi.mocked(store.sendMessage).mock.calls[0][0];+ expect(params.message).toBe('first\n\nsecond');+ expect(params.queueHead).toBeUndefined();+ });++ it('sends one message per turn in Queue mode, marking it the queue head', () => {+ mode.value = 'queue';+ const { get, state, store } = createStore([queued('q1', 'first'), queued('q2', 'second')]);++ scheduleQueuedFollowUp(get, context, 'op-1');+ vi.advanceTimersByTime(100);++ expect(store.sendMessage).toHaveBeenCalledTimes(1);+ const params = vi.mocked(store.sendMessage).mock.calls[0][0];+ expect(params.message).toBe('first');+ expect(params.queueHead).toBe(true);+ expect(state.queue.map((m) => m.id)).toEqual(['q2']);+ });+});++describe('findOrphanedQueueKey', () => {+ it('ignores a steer that may already be with the agent', () => {+ const { get } = createStore([queued('q1', 'maybe', { localSteer: 'unknown' } as any)]);+ (get() as any).queuedMessages = {+ key: [queued('q1', 'maybe', { localSteer: 'unknown' } as any)],+ };++ expect(findOrphanedQueueKey(get, ['key'], false)).toBeUndefined();+ });++ it('still finds a queue a send must take along', () => {+ const { get } = createStore([]);+ (get() as any).queuedMessages = { key: [queued('q1', 'waiting')] };++ expect(findOrphanedQueueKey(get, ['key'], false)).toBe('key');+ });+});diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.ts b/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.tsnew file mode 100644index 00000000000..83be3c86e5b--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.ts@@ -0,0 +1,11 @@+import type { FollowUpMode } from '@lobechat/types';++import { getUserStoreState } from '@/store/user';+import { userGeneralSettingsSelectors } from '@/store/user/selectors';++/**+ * The user's Follow-up behavior in effect now: what a message sent while a run+ * is going does. Read at each decision, so a change applies to the next one.+ */+export const getFollowUpMode = (): FollowUpMode =>+ userGeneralSettingsSelectors.followUpBehavior(getUserStoreState());diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts b/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.tsindex cc2c9a47c54..c06dbaa3b5e 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/queuedFollowUp.ts@@ -2,6 +2,7 @@ import type { ConversationContext, UploadFileItem } from '@lobechat/types';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import {+ isSendableQueuedMessage,mergeQueuedMessages,type QueuedMessage,reconstructUploadFilesFromQueue,@@ -9,6 +10,8 @@ import {import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { getFollowUpMode } from './followUpMode';+/*** The conversation key whose queue nothing will drain, so a new send must* take it along instead of overtaking it: behind a Stop, or — on an existing@@ -20,7 +23,8 @@ export const findOrphanedQueueKey = (willCreateNewTopic: boolean,): string | undefined =>keys.find((key) => {- if ((get().queuedMessages[key]?.length ?? 0) === 0) return false;+ // A steer that may already be with the agent is not sent again on its own.+ if (!(get().queuedMessages[key] ?? []).some(isSendableQueuedMessage)) return false;if (!willCreateNewTopic) return true;return (get().operationsByContext[key] || []).some((id) => {const operation = get().operations[id];@@ -28,6 +32,24 @@ export const findOrphanedQueueKey = (});});+/** Queued messages taken to start one turn. */+export interface QueuedTurn {+ messages: QueuedMessage[];+ /** Taken from the head of a queue sent one message per turn; the rest waits behind it. */+ queueHead?: boolean;+}++/**+ * Take what the next turn sends from a queue nothing runs behind any more. In+ * Queue mode that is its head alone, one message per turn; otherwise all of it,+ * merged into one message.+ */+export const drainQueuedTurn = (get: () => ChatStore, contextKey: string): QueuedTurn => {+ if (getFollowUpMode() !== 'queue') return { messages: get().drainQueuedMessages(contextKey) };++ return { messages: get().drainQueuedMessages(contextKey, { limit: 1 }), queueHead: true };+};+/*** Send drained queued messages as one turn of their own. The run they waited* behind already ended, so this is a fresh turn — not a steer of it — and the@@ -37,6 +59,7 @@ export const sendQueuedMessages = (get: () => ChatStore,context: ConversationContext,messages: QueuedMessage[],+ options?: { queueHead?: boolean },): Promise<unknown> => {const merged = mergeQueuedMessages(messages);const mergedFiles =@@ -53,9 +76,18 @@ export const sendQueuedMessages = (...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),message: merged.content,metadata: merged.metadata,+ ...(options?.queueHead && { queueHead: true }),});};+/** Send a {@link QueuedTurn}. */+export const sendQueuedTurn = (+ get: () => ChatStore,+ context: ConversationContext,+ turn: QueuedTurn,+): Promise<unknown> =>+ sendQueuedMessages(get, context, turn.messages, { queueHead: turn.queueHead });+/** Shared by streamed completion and recovery from a server terminal snapshot. */export const scheduleQueuedFollowUp = (get: () => ChatStore,@@ -70,13 +102,13 @@ export const scheduleQueuedFollowUp = (// owner at that point: a user can start another turn during this hand-off.setTimeout(() => {if (operationSelectors.hasNewerConversationOperation(operationId, context)(get())) return;- const remainingQueued = get().drainQueuedMessages(contextKey);- if (remainingQueued.length === 0) {+ const turn = drainQueuedTurn(get, contextKey);+ if (turn.messages.length === 0) {onEmpty?.();return;}- sendQueuedMessages(get, execContext, remainingQueued).catch((error: unknown) => {+ sendQueuedTurn(get, execContext, turn).catch((error: unknown) => {console.error('[executeClientAgent] sendMessage for queued content failed:', error);});}, 100);diff --git a/src/store/chat/slices/agentRun/actions/transports/client/clientSteer.test.ts b/src/store/chat/slices/agentRun/actions/transports/client/clientSteer.test.tsnew file mode 100644index 00000000000..07493d911f2--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/client/clientSteer.test.ts@@ -0,0 +1,167 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';+import type { QueuedMessage } from '@/store/chat/slices/operation/types';+import type { ChatStore } from '@/store/chat/store';++import { canSteerClientRun, steerQueuedFollowUps } from './clientSteer';++vi.mock('@/services/message', () => ({ messageService: { createMessage: vi.fn() } }));++const queued = (+ id: string,+ content: string,+ extra: Partial<QueuedMessage> = {},+): QueuedMessage => ({+ content,+ createdAt: Number(id.slice(1)),+ id,+ interruptMode: 'soft',+ ...extra,+});++const createStore = (messages: QueuedMessage[]) => {+ const queue = { current: [...messages] };+ const store = {+ drainQueuedMessages: vi.fn((_key: string, options?: { limit?: number }) => {+ const taken = queue.current.slice(0, options?.limit ?? queue.current.length);+ queue.current = queue.current.slice(taken.length);+ return taken;+ }),+ internal_confirmClientMessages: vi.fn(),+ internal_dispatchMessage: vi.fn(),+ get queuedMessages() {+ return { key: queue.current };+ },+ requeueQueuedMessages: vi.fn((_key: string, back: QueuedMessage[]) => {+ queue.current = [...back, ...queue.current];+ }),+ } as unknown as ChatStore;+ return { get: () => store, queue, store };+};++const context = { agentId: 'agent-1', threadId: null, topicId: 'topic-1' };+const toolResultStep = {+ nextContext: { payload: { parentMessageId: 'tool-1' }, phase: 'tool_result' } as any,+ state: { messages: [{ id: 'tool-1', role: 'tool' }], status: 'running' } as any,+};+const steer = (get: () => ChatStore, step = toolResultStep) =>+ steerQueuedFollowUps(get, { context, contextKey: 'key', operationId: 'op-1', ...step });++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(messageService.createMessage).mockResolvedValue({ id: 'x' } as any);+});++describe('canSteerClientRun', () => {+ it('takes plain text', () => {+ expect(canSteerClientRun(queued('q1', 'also check the tests'))).toBe(true);+ });++ it.each([+ ['no text', queued('q1', ' ')],+ ['a file', queued('q1', 'see this', { files: ['file-1'] })],+ [+ 'a quoted selection',+ queued('q1', 'about this', {+ metadata: { contextSelections: [{ content: 'x', id: 's', source: 'text' }] } as any,+ }),+ ],+ ['a pinned runtime', queued('q1', 'go', { forceRuntime: 'gateway' })],+ [+ 'a selected tool',+ queued('q1', 'search this', {+ editorData: {+ root: {+ children: [+ {+ children: [+ {+ actionCategory: 'tool',+ actionLabel: 'Web Search',+ actionType: 'web-search',+ type: 'action-tag',+ },+ { text: ' search this', type: 'text' },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ },+ }),+ ],+ ['a goal', queued('q1', '/goal ship it')],+ ])('leaves a message with %s to a turn of its own', (_label, message) => {+ expect(canSteerClientRun(message)).toBe(false);+ });+});++describe('steerQueuedFollowUps', () => {+ it('joins the leading messages into the run as one steer user message', async () => {+ const { get, queue, store } = createStore([+ queued('q1', 'first'),+ queued('q2', 'second'),+ queued('q3', 'with a file', { files: ['f'] }),+ ]);++ const steered = await steer(get);++ expect(messageService.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'first\n\nsecond',+ metadata: expect.objectContaining({ steer: true }),+ parentId: 'tool-1',+ role: 'user',+ topicId: 'topic-1',+ }),+ );+ const id = vi.mocked(messageService.createMessage).mock.calls[0][0].id;+ expect(steered?.nextContext).toMatchObject({+ payload: { parentMessageId: id },+ phase: 'user_input',+ });+ expect(steered?.state.messages.at(-1)).toMatchObject({ content: 'first\n\nsecond', id });+ // The attachment waits for the hand-back.+ expect(queue.current.map((m) => m.id)).toEqual(['q3']);+ expect(store.internal_confirmClientMessages).toHaveBeenCalledWith([id]);+ });++ it('takes nothing while a tool of this turn waits for approval', async () => {+ const { get, queue } = createStore([queued('q1', 'first')]);+ const waiting = {+ ...toolResultStep,+ state: {+ messages: [+ { id: 'a1', role: 'assistant', tools: [{ id: 't' }] },+ { id: 't1', parentId: 'a1', pluginIntervention: { status: 'pending' }, role: 'tool' },+ ],+ } as any,+ };++ await expect(steer(get, waiting)).resolves.toBeUndefined();+ expect(queue.current).toHaveLength(1);+ });++ it('only steers right before a model call', async () => {+ const { get } = createStore([queued('q1', 'first')]);+ const llmResult = { ...toolResultStep, nextContext: { phase: 'llm_result' } as any };++ await expect(steer(get, llmResult)).resolves.toBeUndefined();+ expect(messageService.createMessage).not.toHaveBeenCalled();+ });++ it('puts the messages back at the head of the queue when the write fails', async () => {+ vi.mocked(messageService.createMessage).mockRejectedValue(new Error('offline'));+ const { get, queue, store } = createStore([queued('q1', 'first'), queued('q2', 'second')]);++ await expect(steer(get)).resolves.toBeUndefined();++ expect(queue.current.map((m) => m.id)).toEqual(['q1', 'q2']);+ expect(store.internal_dispatchMessage).toHaveBeenLastCalledWith(+ expect.objectContaining({ type: 'deleteMessage' }),+ { operationId: 'op-1' },+ );+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/client/clientSteer.ts b/src/store/chat/slices/agentRun/actions/transports/client/clientSteer.tsnew file mode 100644index 00000000000..470511f9bd3--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/client/clientSteer.ts@@ -0,0 +1,140 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import { findCurrentTurnPendingToolMessages } from '@lobechat/agent-runtime';+import { isGoalPrompt } from '@lobechat/builtin-tool-goal';+import type { ConversationContext, MessageMetadata } from '@lobechat/types';+import { COMPOSER_USER_MESSAGE_METADATA_KEYS } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import debug from 'debug';++import { messageService } from '@/services/message';+import {+ parseActionTagsFromEditorData,+ parseMentionedAgentsFromEditorData,+} from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';+import { mergeQueuedMessages, type QueuedMessage } from '@/store/chat/slices/operation/types';+import type { ChatStore } from '@/store/chat/store';++const log = debug('lobe-store:client-steer');++/** The decision points right before the run calls the model again — where the server steers too. */+const LLM_NEXT_PHASES = new Set([+ 'tool_result',+ 'tools_batch_result',+ 'sub_agent_result',+ 'sub_agents_batch_result',+]);++/**+ * Whether a queued message can join a running client turn: plain text sent+ * from the composer. Attachments, quoted selections, a pinned runtime or+ * anything else that needs a turn configured for it waits for a turn of its+ * own, as it did before.+ */+export const canSteerClientRun = (message: QueuedMessage): boolean => {+ if (!message.content.trim()) return false;+ if (message.files?.length || message.filesPreview?.length) return false;+ if (message.forceRuntime) return false;+ // Tool and skill selections, commands and @-mentions live in the rich text and+ // are turned into turn context only by a send of their own.+ if (parseActionTagsFromEditorData(message.editorData).length > 0) return false;+ if (parseMentionedAgentsFromEditorData(message.editorData).length > 0) return false;+ if (isGoalPrompt(message.content)) return false;+ const metadata = message.metadata as Record<string, unknown> | undefined;+ return !COMPOSER_USER_MESSAGE_METADATA_KEYS.some((key) => {+ const value = metadata?.[key];+ return Array.isArray(value) ? value.length > 0 : value !== undefined;+ });+};++export interface SteeredStep {+ nextContext: AgentRuntimeContext;+ state: AgentState;+}++/**+ * Steer a running client turn (Follow-up behavior: Steer): at a decision point+ * right before the next model call, take the leading queued messages that can+ * join into the run as ONE steer user message, and go on with the same run on+ * top of it — the way the server joins its queue (`injectQueuedFollowUp`).+ *+ * Nothing is taken while a tool waits for the user's approval: the messages+ * stay queued until the approval settles. Messages that cannot join stay in+ * the queue too; the run then hands its turn back for them as before.+ *+ * @returns the step to run instead, or `undefined` when nothing joined+ */+export const steerQueuedFollowUps = async (+ get: () => ChatStore,+ params: {+ context: ConversationContext;+ contextKey: string;+ nextContext: AgentRuntimeContext;+ operationId: string;+ state: AgentState;+ },+): Promise<SteeredStep | undefined> => {+ const { context, contextKey, nextContext, operationId, state } = params;+ if (!LLM_NEXT_PHASES.has(nextContext.phase)) return;+ if (findCurrentTurnPendingToolMessages(state.messages).length > 0) return;++ const queue = get().queuedMessages[contextKey] ?? [];+ const firstHeld = queue.findIndex((message) => !canSteerClientRun(message));+ const joinable = firstHeld === -1 ? queue.length : firstHeld;+ if (joinable === 0) return;++ const taken = get().drainQueuedMessages(contextKey, { limit: joinable });+ if (taken.length === 0) return;++ const merged = mergeQueuedMessages(taken);+ const parentId = (nextContext.payload as { parentMessageId?: string } | undefined)+ ?.parentMessageId;+ const id = nanoid();+ const metadata: MessageMetadata = { ...merged.metadata, steer: true };+ const message = {+ agentId: context.agentId,+ content: merged.content,+ editorData: merged.editorData,+ groupId: context.groupId ?? undefined,+ id,+ metadata,+ parentId,+ role: 'user' as const,+ threadId: context.threadId ?? undefined,+ topicId: context.topicId ?? undefined,+ };++ get().internal_dispatchMessage(+ { id, type: 'createMessage', value: { ...message } },+ { operationId },+ { creationOrigin: 'client' },+ );+ try {+ await messageService.createMessage(message);+ } catch (error) {+ // Not in the conversation: the messages go back to the head of the queue,+ // and the run hands its turn back for them.+ console.error('[clientSteer] writing the steer message failed:', error);+ get().internal_dispatchMessage({ id, type: 'deleteMessage' }, { operationId });+ get().requeueQueuedMessages(contextKey, taken);+ return;+ }+ get().internal_confirmClientMessages([id]);+ log('[%s] Joined %d queued messages as %s', operationId, taken.length, id);++ const now = Date.now();+ return {+ nextContext: {+ ...nextContext,+ payload: { parentMessageId: id },+ phase: 'user_input',+ } as AgentRuntimeContext,+ state: {+ ...state,+ lastModified: new Date(now).toISOString(),+ messages: [+ ...state.messages,+ { ...message, createdAt: now, updatedAt: now } as AgentState['messages'][number],+ ],+ },+ };+};diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 50ee88edf06..fed9a5f2597 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -66,8 +66,10 @@ import { toolInterventionSelectors } from '@/store/user/selectors';import { getUserStoreState } from '@/store/user/store';import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';+import { getFollowUpMode } from '../../lifecycle/followUpMode';import type { RunParkedReason, RunScope } from '../../lifecycle/types';import { buildViewedTaskPrompt } from '../viewedTaskPrompt';+import { steerQueuedFollowUps } from './clientSteer';import { buildRunManifestMap } from './discoverableManifests';import { clientInterventionAudits } from './interventionAudits';@@ -726,7 +728,20 @@ export class StreamingExecutorActionImpl {);// Accumulate activated skills from activateSkill messagesconst activatedSkills = selectActivatedSkillsFromMessages(currentDBMessages);- const hasQueuedMessages = (this.#get().queuedMessages[contextKey]?.length ?? 0) > 0;+ // Steer joins what can join right here; Queue lets the run finish first.+ const followUpMode = getFollowUpMode();+ if (followUpMode === 'steer') {+ const steered = await steerQueuedFollowUps(this.#get, {+ context,+ contextKey,+ nextContext,+ operationId,+ state,+ });+ if (steered) ({ nextContext, state } = steered);+ }+ const hasQueuedMessages =+ followUpMode !== 'queue' && (this.#get().queuedMessages[contextKey]?.length ?? 0) > 0;const stepContext = computeStepContext({activatedSkills,activatedToolIds,diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 4270a93a13a..af915d49efc 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -73,11 +73,7 @@ import { threadService } from '@/services/thread';import { workService } from '@/services/work';import { topicSelectors } from '@/store/chat/selectors';import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';-import {- mergeQueuedMessages,- reconstructUploadFilesFromQueue,- type StreamRetryMetadata,-} from '@/store/chat/slices/operation/types';+import { type StreamRetryMetadata } from '@/store/chat/slices/operation/types';import { type ChatStore, useChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -87,6 +83,7 @@ import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectorsimport { dispatchInterventionState } from '../../entries/interventionProjection';import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';+import { drainQueuedTurn, sendQueuedTurn } from '../../lifecycle/queuedFollowUp';import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';@@ -95,6 +92,7 @@ import { markUnfinishedToolsCancelled } from './cancelledTools';import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';import { preserveSkippedIntervention } from './interventionAck';import { claimLocalRunFee, type LocalRunFeeClaim, settleLocalRunFee } from './localRunFee';+import { type LocalSteer, startLocalSteer } from './localSteer';import { buildLocalHeterogeneousSystemContext } from './localSystemContext';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';@@ -662,6 +660,7 @@ export const executeHeterogeneousAgent = async (* + live UI. Reassigned (commit-on-success) by `reduceAndApplyMain`.*/let mainState: MainAgentRunState = createMainAgentRunState(assistantMessageId);+ let localSteer: LocalSteer | undefined;/*** Per-thread UI handles the reducer doesn't model: the thread-scoped store* dispatcher + its sub-operation id. Created on the `createThread` intent,@@ -2007,13 +2006,13 @@ export const executeHeterogeneousAgent = async (get().updateOperationMetadata?.(operationId, { streamRetry: undefined });}- // Requests, ACKs and tool/runtime completion share one state machine so- // a missing bridge response cannot leave a completed question pending.+ // Requests, ACKs and tool/runtime completion share one state machine so a missing+ // bridge response cannot leave a completed question pending. A settled one frees steers.if (event.type === 'agent_intervention_request' ||event.type === 'agent_intervention_response') {- persistQueue = persistQueue.then(() => reduceAndApplyMain(event));+ persistQueue = persistQueue.then(() => reduceAndApplyMain(event)).then(localSteer?.pump);return;}@@ -2048,6 +2047,10 @@ export const executeHeterogeneousAgent = async (// usage tray derives its total from these per-message usages directly// (OpStatusTray → calculateOperationUsageMetrics), so there is no separate// accumulation here. Not forwarded (bookkeeping).+ if (event.type === 'step_complete' && event.data?.phase === 'user_message') {+ persistQueue = persistQueue.then(async () => void (await localSteer?.confirm(event.data)));+ return;+ }if (event.type === 'step_complete' && event.data?.phase === 'turn_metadata') {persistQueue = persistQueue.then(() => reduceAndApplyMain(event));return;@@ -2480,6 +2483,23 @@ export const executeHeterogeneousAgent = async (): undefined;+ localSteer = startLocalSteer({+ agentType: adapterType,+ codexAppServer: labPreferSelectors.enableCodexAppServer(useUserStore.getState()),+ context,+ contextKey: messageMapKey(context),+ get,+ ipcSessionId: ipcRunSessionId,+ isReady: () => sawStreamedEvent,+ isWaitingForUser: () =>+ [...mainState.interventionsByCallId.values()].some((i) => i.transition === 'pending'),+ operationId,+ rows: pendingCreateLedger,+ spine: {+ get: () => mainState.lastSpineMessageId,+ set: (id) => void (mainState = { ...mainState, lastSpineMessageId: id }),+ },+ });// Send the prompt — blocks until process exitsconst sendResult = await heterogeneousAgentService.sendPrompt({agentId: context.agentId,@@ -2495,6 +2515,7 @@ export const executeHeterogeneousAgent = async (? { replayTranscript: true, replayTranscriptConfigDir, replayTranscriptStartedAt }: {}),...(resumeReplayMessages?.length ? { resumeReplayMessages } : {}),+ ...(localSteer && { liveSteer: true }),sessionId: ipcRunSessionId,systemContext: systemContext || undefined,topicId: context.topicId ?? undefined,@@ -2546,14 +2567,13 @@ export const executeHeterogeneousAgent = async (const drainableTerminal =terminalEvent?.type !== 'error' &&isCompletedRuntimeEnd((terminalEvent?.data as { reason?: string } | undefined)?.reason);+ localSteer?.settle();if (!isAborted() && drainableTerminal) {const contextKey = messageMapKey(context);- const remainingQueued = get().drainQueuedMessages?.(contextKey) ?? [];- if (remainingQueued.length > 0) {- // Force-complete this op + mark unread BEFORE the next sendMessage,- // otherwise its queue check (covering all AI_RUNTIME_OPERATION_TYPES)- // would still see this op as "running" and re-queue the merged content- // into a now-orphaned operation.+ const turn = drainQueuedTurn(get, contextKey); // Queue mode: the head alone+ if (turn.messages.length > 0) {+ // Complete this op + mark unread BEFORE the next sendMessage: its queue check would+ // still see this op as running and re-queue the content into an orphaned operation.get().completeOperation(operationId);const completedOp = get().operations?.[operationId];if (completedOp?.context.agentId) {@@ -2564,31 +2584,10 @@ export const executeHeterogeneousAgent = async (});}- const merged = mergeQueuedMessages(remainingQueued);- const mergedFiles =- merged.filesPreview.length > 0- ? reconstructUploadFilesFromQueue(merged.filesPreview)- : merged.files.length > 0- ? (merged.files.map((id) => ({ id })) as any)- : undefined;-setTimeout(() => {- useChatStore- .getState()- .sendMessage({- context: { ...context },- editorData: merged.editorData,- files: mergedFiles,- ...(merged.forceRuntime ? { forceRuntime: merged.forceRuntime } : {}),- message: merged.content,- metadata: merged.metadata,- })- .catch((e: unknown) => {- console.error(- '[heterogeneousAgentExecutor] sendMessage for queued content failed:',- e,- );- });+ sendQueuedTurn(useChatStore.getState, { ...context }, turn).catch((e: unknown) => {+ console.error('[heterogeneousAgentExecutor] sendMessage for queued content failed:', e);+ });}, 100);}}@@ -2625,6 +2624,7 @@ export const executeHeterogeneousAgent = async (.catch((err) => console.error('[HeterogeneousAgent] cancelled tool cleanup failed:', err));}unsubscribe?.();+ localSteer?.settle();// The desktop IPC session only owns this run's config and process handles.// Multi-turn resume uses the native agentSessionId persisted above, so the// IPC session must be released after every run instead of accumulating indiff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.tsnew file mode 100644index 00000000000..8348e5dc860--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.ts@@ -0,0 +1,378 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { messageService } from '@/services/message';+import type { QueuedMessage } from '@/store/chat/slices/operation/types';+import type { ChatStore } from '@/store/chat/store';++import { createLocalSteer, startLocalSteer, supportsLocalSteer } from './localSteer';++vi.mock('@/services/electron/heterogeneousAgent', () => ({+ heterogeneousAgentService: { steerSession: vi.fn() },+}));+vi.mock('@/services/message', () => ({ messageService: { createMessage: vi.fn() } }));+const mode = vi.hoisted(() => ({ value: 'steer' as 'legacy' | 'queue' | 'steer' }));+vi.mock('../../lifecycle/followUpMode', () => ({ getFollowUpMode: () => mode.value }));++const queued = (+ id: string,+ content: string,+ extra: Partial<QueuedMessage> = {},+): QueuedMessage => ({+ content,+ createdAt: Number(id.slice(1)),+ id,+ interruptMode: 'soft',+ ...extra,+});++/** A store with just the queue and the calls the steer makes, notifying on queue changes. */+const createHarness = (messages: QueuedMessage[], waiting = false, ready = { value: true }) => {+ let queue = [...messages];+ const listeners = new Set<() => void>();+ const setQueue = (next: QueuedMessage[]) => {+ queue = next;+ for (const listener of listeners) listener();+ };+ const store = {+ drainQueuedMessages: vi.fn((_key: string, options?: { limit?: number }) => {+ const taken = queue.slice(0, options?.limit ?? queue.length);+ setQueue(queue.slice(taken.length));+ return taken;+ }),+ internal_confirmClientMessages: vi.fn(),+ internal_dispatchMessage: vi.fn(),+ get queuedMessages() {+ return { key: queue };+ },+ removeQueuedMessage: vi.fn((_key: string, id: string) =>+ setQueue(queue.filter((m) => m.id !== id)),+ ),+ requeueQueuedMessages: vi.fn((_key: string, back: QueuedMessage[]) =>+ setQueue([...back, ...queue]),+ ),+ updateOperationMetadata: vi.fn(),+ updateQueuedMessage: vi.fn((_key: string, id: string, patch: Partial<QueuedMessage>) =>+ setQueue(queue.map((m) => (m.id === id ? { ...m, ...patch } : m))),+ ),+ } as unknown as ChatStore;+ let spine = 'assistant-1';+ const rows = { add: vi.fn(), ensureParentPersisted: vi.fn(async () => {}) };+ const steer = createLocalSteer({+ context: { agentId: 'agent-1', threadId: null, topicId: 'topic-1' },+ contextKey: 'key',+ get: () => store,+ ipcSessionId: 'ipc-1',+ isReady: () => ready.value,+ isWaitingForUser: () => waiting,+ operationId: 'op-1',+ rows,+ spine: { get: () => spine, set: (id) => (spine = id) },+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ });+ return { getQueue: () => queue, getSpine: () => spine, rows, setQueue, steer, store };+};++const steerCall = () => vi.mocked(heterogeneousAgentService.steerSession).mock.calls.at(-1)?.[0];++beforeEach(() => {+ vi.clearAllMocks();+ mode.value = 'steer';+ vi.mocked(heterogeneousAgentService.steerSession).mockResolvedValue({ status: 'accepted' });+ vi.mocked(messageService.createMessage).mockResolvedValue({ id: 'x' } as any);+});++describe('supportsLocalSteer', () => {+ it.each([+ ['claude-code', {}, true],+ ['pi', {}, true],+ ['codex', { codexAppServer: true }, true],+ ['codex', {}, false],+ ['copilot', {}, false],+ ['amp', {}, false],+ ])('%s %o → %s', (agentType, options, expected) => {+ expect(supportsLocalSteer(agentType, options)).toBe(expected);+ });+});++describe('createLocalSteer', () => {+ it('merges what waits into one message, shows it as being handed over, and writes it once read', async () => {+ const h = createHarness([+ queued('q1', 'first'),+ queued('q2', 'second'),+ queued('q3', 'file', { files: ['f'] }),+ ]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());++ const { messageId } = steerCall()!;+ expect(steerCall()).toMatchObject({ prompt: 'first\n\nsecond', sessionId: 'ipc-1' });+ expect(h.getQueue().map((m) => [m.id, m.localSteer])).toEqual([+ [messageId, 'delivering'],+ ['q3', undefined],+ ]);++ await expect(h.steer.confirm({ uuid: messageId })).resolves.toBe(true);++ expect(messageService.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'first\n\nsecond',+ id: messageId,+ metadata: { steer: true },+ parentId: 'assistant-1',+ role: 'user',+ }),+ );+ // The answer opens under the steer message.+ expect(h.getSpine()).toBe(messageId);+ expect(h.getQueue().map((m) => m.id)).toEqual(['q3']);+ });++ it('takes a confirmation that arrives before the write is answered', async () => {+ let answer!: (value: { status: 'accepted' }) => void;+ vi.mocked(heterogeneousAgentService.steerSession).mockReturnValue(+ new Promise((resolve) => {+ answer = resolve;+ }),+ );+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());++ await expect(h.steer.confirm({ uuid: steerCall()!.messageId })).resolves.toBe(true);+ answer({ status: 'accepted' });+ await new Promise((resolve) => setTimeout(resolve, 0));+ h.steer.settle();++ expect(messageService.createMessage).toHaveBeenCalledTimes(1);+ // Read, so nothing goes back for the next turn.+ expect(h.getQueue()).toEqual([]);+ });++ it('writes the steer message only once its parent row is persisted', async () => {+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());+ const order: string[] = [];+ h.rows.ensureParentPersisted.mockImplementation(async () => void order.push('parent'));+ vi.mocked(messageService.createMessage).mockImplementation(async () => {+ order.push('steer');+ return { id: 'x' } as any;+ });++ await h.steer.confirm({ uuid: steerCall()!.messageId });++ expect(h.rows.ensureParentPersisted).toHaveBeenCalledWith('assistant-1');+ expect(order).toEqual(['parent', 'steer']);+ });++ it('parks a failed steer write for the run’s in-order replay', async () => {+ vi.mocked(messageService.createMessage).mockRejectedValue(new Error('fk'));+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());+ const { messageId } = steerCall()!;++ await h.steer.confirm({ uuid: messageId });++ expect(h.rows.add).toHaveBeenCalledWith(messageId, expect.objectContaining({ id: messageId }));+ expect(h.getSpine()).toBe(messageId);+ });++ it('matches Pi’s report against the text it actually received', async () => {+ vi.mocked(heterogeneousAgentService.steerSession).mockResolvedValue({+ deliveredText: 'Referenced topic guidance\n\nsee <refer_topic id="t"/>',+ status: 'accepted',+ });+ const h = createHarness([queued('q1', 'see <refer_topic id="t"/>')]);+ await vi.waitFor(() => expect(h.getQueue()[0]?.localSteer).toBe('delivering'));+ await new Promise((resolve) => setTimeout(resolve, 0));++ await expect(h.steer.confirm({ text: 'see <refer_topic id="t"/>' })).resolves.toBe(false);+ await expect(+ h.steer.confirm({ text: 'Referenced topic guidance\n\nsee <refer_topic id="t"/>' }),+ ).resolves.toBe(true);+ });++ it('does not retry a refused steer, nor steer later messages ahead of it', async () => {+ vi.mocked(heterogeneousAgentService.steerSession).mockResolvedValue({ status: 'rejected' });+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(h.getQueue().map((m) => m.id)).toEqual(['q1']));+ h.setQueue([...h.getQueue(), queued('q2', 'second')]);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(heterogeneousAgentService.steerSession).toHaveBeenCalledTimes(1);+ expect(h.getQueue().map((m) => m.id)).toEqual(['q1', 'q2']);+ });++ it('ignores a replay that is not its steer (the run’s own prompt)', async () => {+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());++ await expect(h.steer.confirm({ uuid: 'other' })).resolves.toBe(false);+ expect(messageService.createMessage).not.toHaveBeenCalled();+ });++ it('matches by text for an agent that reports no id (Pi)', async () => {+ const h = createHarness([queued('q1', 'run the tests')]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());++ await expect(h.steer.confirm({ text: 'run the tests' })).resolves.toBe(true);+ expect(h.getQueue()).toEqual([]);+ });++ it('gives the messages back, unmerged, when the session refuses', async () => {+ vi.mocked(heterogeneousAgentService.steerSession).mockResolvedValue({ status: 'rejected' });+ const h = createHarness([queued('q1', 'first'), queued('q2', 'second')]);++ await vi.waitFor(() => expect(h.getQueue().map((m) => m.id)).toEqual(['q1', 'q2']));+ expect(h.store.updateOperationMetadata).not.toHaveBeenCalled();+ });++ it('marks a run with no native steer, so the tray says its queue waits for the end', async () => {+ vi.mocked(heterogeneousAgentService.steerSession).mockResolvedValue({ status: 'unsupported' });+ const h = createHarness([queued('q1', 'first')]);++ await vi.waitFor(() =>+ expect(h.store.updateOperationMetadata).toHaveBeenCalledWith('op-1', {+ liveSteer: false,+ steerUnsupported: true,+ }),+ );+ expect(h.getQueue().map((m) => m.id)).toEqual(['q1']);+ });++ it('never resends a steer whose delivery is unknown', async () => {+ vi.mocked(heterogeneousAgentService.steerSession).mockRejectedValue(new Error('ipc lost'));+ const h = createHarness([queued('q1', 'first')]);++ await vi.waitFor(() => expect(h.getQueue()[0]?.localSteer).toBe('unknown'));+ h.setQueue([...h.getQueue(), queued('q9', 'later')]);+ expect(heterogeneousAgentService.steerSession).toHaveBeenCalledTimes(1);++ // The agent can still report it read; then it is written in after all.+ const { messageId } = steerCall()!;+ await expect(h.steer.confirm({ uuid: messageId })).resolves.toBe(true);+ expect(messageService.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({ id: messageId, metadata: { steer: true } }),+ );+ expect(h.getQueue().map((m) => m.id)).toEqual(['q9']);+ });++ it('turns a steer written but never read into the next turn when the run ends', async () => {+ const h = createHarness([queued('q1', 'first'), queued('q2', 'second')]);+ await vi.waitFor(() => expect(heterogeneousAgentService.steerSession).toHaveBeenCalled());+ await vi.waitFor(() => expect(h.getQueue()[0]?.localSteer).toBe('delivering'));++ h.steer.settle();++ expect(h.getQueue().map((m) => m.id)).toEqual(['q1', 'q2']);+ });++ it('waits for the runtime to come up instead of taking a refusal for good', async () => {+ vi.useFakeTimers();+ const ready = { value: false };+ createHarness([queued('q1', 'first')], false, ready);+ await vi.advanceTimersByTimeAsync(1000);+ expect(heterogeneousAgentService.steerSession).not.toHaveBeenCalled();++ ready.value = true;+ await vi.advanceTimersByTimeAsync(600);+ expect(heterogeneousAgentService.steerSession).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it('leaves new messages for the run end once the user switches to Queue', async () => {+ const h = createHarness([]);+ mode.value = 'queue';+ h.setQueue([queued('q1', 'first')]);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(heterogeneousAgentService.steerSession).not.toHaveBeenCalled();+ expect(h.getQueue().map((m) => m.id)).toEqual(['q1']);+ });++ it('marks a steer still being written when the run ends as uncertain, never resent', async () => {+ let answer!: (value: { status: 'accepted' | 'rejected' }) => void;+ vi.mocked(heterogeneousAgentService.steerSession).mockReturnValue(+ new Promise((resolve) => {+ answer = resolve;+ }),+ );+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(h.getQueue()[0]?.localSteer).toBe('delivering'));++ h.steer.settle();+ expect(h.getQueue()[0]?.localSteer).toBe('unknown');++ answer({ status: 'accepted' });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(h.getQueue().map((m) => m.localSteer)).toEqual(['unknown']);+ });++ it('gives back a steer refused after the run ended', async () => {+ let answer!: (value: { status: 'accepted' | 'rejected' }) => void;+ vi.mocked(heterogeneousAgentService.steerSession).mockReturnValue(+ new Promise((resolve) => {+ answer = resolve;+ }),+ );+ const h = createHarness([queued('q1', 'first')]);+ await vi.waitFor(() => expect(h.getQueue()[0]?.localSteer).toBe('delivering'));++ h.steer.settle();+ answer({ status: 'rejected' });+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(h.getQueue().map((m) => [m.id, m.localSteer])).toEqual([['q1', undefined]]);+ });++ it('steers nothing while the run waits for the user', async () => {+ createHarness([queued('q1', 'first')], true);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(heterogeneousAgentService.steerSession).not.toHaveBeenCalled();+ });+});++describe('startLocalSteer', () => {+ const start = (agentType: string) =>+ startLocalSteer({+ agentType,+ codexAppServer: true,+ context: { agentId: 'agent-1', threadId: null, topicId: 'topic-1' },+ contextKey: 'key',+ get: () => ({ queuedMessages: {}, updateOperationMetadata: vi.fn() }) as unknown as ChatStore,+ ipcSessionId: 'ipc-1',+ isReady: () => true,+ isWaitingForUser: () => false,+ operationId: 'op-1',+ rows: { add: vi.fn(), ensureParentPersisted: vi.fn(async () => {}) },+ spine: { get: () => 'a', set: vi.fn() },+ });++ it('sets up steering for Codex app-server and Pi in Queue mode, so a switch to Steer applies mid-run', () => {+ mode.value = 'queue';+ const codex = start('codex');+ const pi = start('pi');++ expect(codex).toBeDefined();+ expect(pi).toBeDefined();+ codex?.settle();+ pi?.settle();+ });++ it('leaves a Claude Code run started in Queue mode queued: it was not spawned to take messages', () => {+ mode.value = 'queue';+ expect(start('claude-code')).toBeUndefined();++ mode.value = 'steer';+ const cc = start('claude-code');+ expect(cc).toBeDefined();+ cc?.settle();+ });++ it('does nothing with the lab off', () => {+ mode.value = 'legacy';+ expect(start('codex')).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.tsnew file mode 100644index 00000000000..aba1de15018--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts@@ -0,0 +1,333 @@+import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';+import type { ConversationContext } from '@lobechat/types';+import debug from 'debug';++import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import { messageService } from '@/services/message';+import { mergeQueuedMessages, type QueuedMessage } from '@/store/chat/slices/operation/types';+import { type ChatStore, useChatStore } from '@/store/chat/store';++import { getFollowUpMode } from '../../lifecycle/followUpMode';+import { canSteerClientRun } from '../client/clientSteer';++const log = debug('lobe-store:local-steer');++/** How often a message waiting for the runtime to come up checks again. */+const STARTUP_RETRY_MS = 500;++/**+ * Whether a local heterogeneous run can take a message mid-run: Claude Code+ * (SDK input stream, or a CLI whose input stays open), Codex over app-server+ * (`turn/steer`) and Pi (`steer`). The others — ACP agents, one-shot CLIs,+ * Codex `exec` — send it once the run ends.+ */+export const supportsLocalSteer = (+ agentType: HeterogeneousAgentType | string,+ options: { codexAppServer?: boolean },+): boolean =>+ agentType === 'claude-code' ||+ agentType === 'pi' ||+ (agentType === 'codex' && !!options.codexAppServer);++/** A `step_complete { phase: 'user_message' }` event: the agent read a user message. */+export interface SteerConfirmation {+ text?: string;+ uuid?: string;+}++export interface LocalSteerOptions {+ context: ConversationContext;+ /** Queue key the run's follow-ups wait under. */+ contextKey: string;+ get: () => ChatStore;+ ipcSessionId: string;+ /**+ * Whether the agent's runtime is up (it has streamed output). Before that the+ * session has no way in yet, so a message waits instead of being refused.+ */+ isReady: () => boolean;+ /** Whether the run waits for the user (a pending question or approval); nothing is steered then. */+ isWaitingForUser: () => boolean;+ operationId: string;+ /**+ * The run's write-behind rows: the steer message's parent can still be only+ * enqueued, so its write waits for it (`ensureParentPersisted`), and a failed+ * write is parked for the in-order replay (`add`) like the run's own rows.+ */+ rows: {+ add: (messageId: string, message: any) => void;+ ensureParentPersisted: (parentId?: string) => Promise<void>;+ };+ /** The message the next steer user message parents off (the run's spine), and its update. */+ spine: { get: () => string; set: (id: string) => void };+ subscribe: (listener: () => void) => () => void;+}++interface PendingSteer {+ content: string;+ /**+ * The text the agent received (Pi reports a read message by its text, which+ * the transport can expand with context); `content` when not reported.+ */+ deliveredText?: string;+ messageId: string;+ /** The run ended while the write was still unanswered: its row was marked uncertain. */+ settledInFlight?: boolean;+ /**+ * `delivering` until the IPC answers; `written` once accepted, until the+ * agent reads it; `unknown` when the write failed and it may still arrive.+ */+ state: 'delivering' | 'unknown' | 'written';+ taken: QueuedMessage[];+}++/**+ * Steer a local heterogeneous run (Follow-up behavior: Steer). The leading+ * queued messages that can join are merged into ONE message and written into+ * the running session; the tray shows it as being handed over. The agent's+ * confirmation (`confirm`) writes it into the conversation as a steer user+ * message, and the answer opens under it.+ *+ * A message the session refuses, or one written but never read when the run+ * ends (`settle`), goes back to the queue and starts the next turn. When the+ * write itself failed with an unknown outcome it stays in the tray, marked,+ * and is never sent again on its own.+ */+export const createLocalSteer = (options: LocalSteerOptions) => {+ const { context, contextKey, get, ipcSessionId, operationId } = options;+ let pending: PendingSteer | undefined;+ let pumping = false;+ let stopped = false;++ /** Swap the taken messages back in for the merged one, at the head of the queue. */+ const giveBack = (steer: PendingSteer) => {+ get().removeQueuedMessage(contextKey, steer.messageId);+ get().requeueQueuedMessages(contextKey, steer.taken);+ };++ const markUnsupported = () => {+ stopped = true;+ get().updateOperationMetadata(operationId, { liveSteer: false, steerUnsupported: true });+ };++ let startupTimer: ReturnType<typeof setTimeout> | undefined;++ const pump = async () => {+ if (stopped || pending || pumping || options.isWaitingForUser()) return;+ // Queue chosen meanwhile: what waits now goes once the run ends.+ if (getFollowUpMode() !== 'steer') return;+ if (!options.isReady()) {+ if (hasJoinable()) startupTimer ??= setTimeout(retryAfterStartup, STARTUP_RETRY_MS);+ return;+ }+ // Taking from the queue notifies its subscribers, this pump among them.+ pumping = true;+ let again = false;+ try {+ again = await pumpOnce();+ } finally {+ pumping = false;+ }+ // Read before its write was answered: what queued meanwhile can go now.+ if (again) schedule();+ };++ /** How many queued messages, from the head, can join a running turn. */+ const joinableCount = () => {+ const queue = get().queuedMessages[contextKey] ?? [];+ const firstHeld = queue.findIndex(+ (message) => !canSteerClientRun(message) || !!message.localSteer,+ );+ return firstHeld === -1 ? queue.length : firstHeld;+ };+ const hasJoinable = () => joinableCount() > 0;++ const retryAfterStartup = () => {+ startupTimer = undefined;+ schedule();+ };++ /** @returns whether the steer was read before its write was answered, so the pump runs again */+ const pumpOnce = async (): Promise<boolean> => {+ const joinable = joinableCount();+ if (joinable === 0) return false;++ const taken = get().drainQueuedMessages(contextKey, { limit: joinable });+ if (taken.length === 0) return false;++ const merged = mergeQueuedMessages(taken);+ const steer: PendingSteer = {+ content: merged.content,+ messageId: crypto.randomUUID(),+ state: 'delivering',+ taken,+ };+ pending = steer;+ // One row stands for what was merged, so the tray shows exactly what goes in.+ get().requeueQueuedMessages(contextKey, [+ {+ content: merged.content,+ createdAt: taken[0].createdAt,+ editorData: merged.editorData,+ id: steer.messageId,+ interruptMode: 'soft',+ localSteer: 'delivering',+ },+ ]);++ let status: 'accepted' | 'rejected' | 'unsupported';+ try {+ ({ deliveredText: steer.deliveredText, status } =+ await heterogeneousAgentService.steerSession({+ messageId: steer.messageId,+ prompt: merged.content,+ sessionId: ipcSessionId,+ }));+ } catch (error) {+ // The run ended first: the row is already marked uncertain and stays so.+ if (steer.settledInFlight) return false;+ // Read already (`confirm` ran first): it landed.+ if (pending !== steer) return true;+ // It may or may not be in the session: never sent again on its own, but+ // kept so the agent reporting it read still writes it in.+ console.error('[localSteer] steering the session failed:', error);+ get().updateQueuedMessage(contextKey, steer.messageId, { localSteer: 'unknown' });+ steer.state = 'unknown';+ stopped = true;+ return false;+ }++ if (steer.settledInFlight) {+ // A definite refusal wrote nothing: the messages run as the next turn.+ if (status !== 'accepted') giveBack(steer);+ return false;+ }+ // The agent can report reading it before the write is answered (Codex).+ if (pending !== steer) return true;+ if (status === 'accepted') {+ steer.state = 'written';+ log('[%s] Steered %d messages as %s', operationId, taken.length, steer.messageId);+ return false;+ }+ // Refused: the session takes no input now, so it and the rest wait for the+ // run end. Stop first: restoring the queue notifies this pump again.+ pending = undefined;+ stopped = true;+ if (status === 'unsupported') markUnsupported();+ giveBack(steer);+ return false;+ };++ const schedule = () => {+ pump().catch((error) => console.error('[localSteer] steer failed:', error));+ };++ const unsubscribe = options.subscribe(schedule);++ /**+ * The agent read a user message. When it is the one steered here, write it+ * into the conversation on the run's spine, so the next turn opens under it.+ *+ * @returns whether the event was this steer's confirmation+ */+ const confirm = async (data: SteerConfirmation): Promise<boolean> => {+ const steer = pending;+ if (!steer) return false;+ const matches = data.uuid+ ? data.uuid === steer.messageId+ : data.text !== undefined &&+ data.text.trim() === (steer.deliveredText ?? steer.content).trim();+ if (!matches) return false;++ pending = undefined;+ const message = {+ agentId: context.agentId,+ content: steer.content,+ groupId: context.groupId ?? undefined,+ id: steer.messageId,+ metadata: { steer: true },+ parentId: options.spine.get(),+ role: 'user' as const,+ threadId: context.threadId ?? undefined,+ topicId: context.topicId ?? undefined,+ };+ get().internal_dispatchMessage(+ { id: message.id, type: 'createMessage', value: { ...message } },+ { operationId },+ { creationOrigin: 'client' },+ );+ get().removeQueuedMessage(contextKey, steer.messageId);+ // The agent answers it under this message whatever the write does next.+ options.spine.set(message.id);+ try {+ await options.rows.ensureParentPersisted(message.parentId);+ await messageService.createMessage(message);+ get().internal_confirmClientMessages([message.id]);+ } catch (error) {+ // Parked for the run's in-order replay: the answer rows behind it wait too.+ console.error('[localSteer] writing the steer message failed:', error);+ options.rows.add(message.id, message);+ }+ schedule();+ return true;+ };++ /**+ * The run ended: stop steering. A message written but never read was not+ * taken by the agent, so it goes back to the queue for the next turn.+ */+ const settle = () => {+ stopped = true;+ if (startupTimer) clearTimeout(startupTimer);+ unsubscribe();+ const steer = pending;+ pending = undefined;+ if (steer?.state === 'written') giveBack(steer);+ // Still being written: it may have reached the agent, so it is never sent+ // again on its own unless the write comes back refused.+ if (steer?.state === 'delivering') {+ steer.settledInFlight = true;+ get().updateQueuedMessage(contextKey, steer.messageId, { localSteer: 'unknown' });+ }+ };++ schedule();+ return { confirm, pump: schedule, settle };+};++export type LocalSteer = ReturnType<typeof createLocalSteer>;++/**+ * Set up steering for a local heterogeneous run when the Follow-up behavior is+ * Steer. A runtime with no native steer is marked instead, so the tray says+ * its queue waits for the run end.+ */+export const startLocalSteer = (+ options: Omit<LocalSteerOptions, 'subscribe'> & {+ agentType: HeterogeneousAgentType | string;+ codexAppServer?: boolean;+ },+): LocalSteer | undefined => {+ const mode = getFollowUpMode();+ if (mode === 'legacy') return;++ const { contextKey, get, operationId } = options;+ if (!supportsLocalSteer(options.agentType, { codexAppServer: options.codexAppServer })) {+ 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.+ if (options.agentType === 'claude-code' && mode !== 'steer') return;++ get().updateOperationMetadata(operationId, { liveSteer: true });+ return createLocalSteer({+ ...options,+ subscribe: (listener) =>+ useChatStore.subscribe((state, prev) => {+ if (state.queuedMessages[contextKey] !== prev.queuedMessages[contextKey]) listener();+ }),+ });+};diff --git a/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.ts b/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.tsindex 578a002cc7e..47ce32fd6ff 100644--- a/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.ts+++ b/src/store/chat/slices/operation/__tests__/selectors.queueHandoff.test.ts@@ -50,6 +50,29 @@ describe('queue hand-off after a run stopped elsewhere', () => {expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(false);});+ it('holds no hand-off for a steer that may already be with the agent', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ const { operationId } = result.current.startOperation({+ context,+ metadata: { startTime: 1000 },+ type: 'execHeterogeneousAgent',+ });+ result.current.enqueueMessage(messageMapKey(context), {+ content: 'maybe delivered',+ createdAt: 2000,+ id: 'q-unknown',+ interruptMode: 'soft',+ localSteer: 'unknown',+ });+ result.current.completeOperation(operationId);+ });++ expect(operationSelectors.isQueueDrainPending(context)(result.current)).toBe(false);+ expect(operationSelectors.isInputVisiblyLoadingByContext(context)(result.current)).toBe(false);+ });+it('still hands the queue off behind a run that completed', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex 0cd6b1a59e6..65534a2b54b 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -19,6 +19,7 @@ import {type AfterCompletionCallback,AI_RUNTIME_OPERATION_TYPES,isClientHeldQueuedMessage,+ isSendableQueuedMessage,type Operation,type OperationCancelContext,type OperationContext,@@ -952,16 +953,23 @@ export class OperationActionsImpl {* Takes nothing while the server holds any of them: it delivers those* itself, and the ones queued after them must not overtake them.*/- drainQueuedMessages = (contextKey: string): QueuedMessage[] => {+ /**+ * Take the queue to send it. `limit` takes only that many from its head (a+ * queue sent one message per turn); the rest stays queued.+ */+ drainQueuedMessages = (contextKey: string, options?: { limit?: number }): QueuedMessage[] => {const queue = this.#get().queuedMessages[contextKey];if (!queue || queue.length === 0) return [];if (!queue.every(isClientHeldQueuedMessage)) return [];- const messages = [...queue];+ // A steer that may already be with the agent is never sent on its own.+ const sendable = queue.filter(isSendableQueuedMessage);+ const messages = options?.limit ? sendable.slice(0, options.limit) : sendable;+ if (messages.length === 0) return [];this.#set(produce((state: ChatStore) => {- state.queuedMessages[contextKey] = [];+ state.queuedMessages[contextKey] = queue.filter((message) => !messages.includes(message));}),false,n(`drainQueuedMessages/${contextKey}`),@@ -971,6 +979,22 @@ export class OperationActionsImpl {return messages;};+ /** Put messages taken from a queue back at its head, in their order (a failed hand-over). */+ requeueQueuedMessages = (contextKey: string, messages: QueuedMessage[]): void => {+ if (messages.length === 0) return;++ this.#set(+ produce((state: ChatStore) => {+ state.queuedMessages[contextKey] = [+ ...messages,+ ...(state.queuedMessages[contextKey] ?? []),+ ];+ }),+ false,+ n(`requeueQueuedMessages/${contextKey}`),+ );+ };+moveQueuedMessages = (fromContextKey: string, toContextKey: string): void => {if (fromContextKey === toContextKey) return;@@ -1018,7 +1042,12 @@ export class OperationActionsImpl {patch: Partial<Pick<QueuedMessage,- 'heldBehindOperationId' | 'serverDelivering' | 'serverDelivery' | 'serverRequest' | 'serverUnconfirmed'+ | 'heldBehindOperationId'+ | 'localSteer'+ | 'serverDelivering'+ | 'serverDelivery'+ | 'serverRequest'+ | 'serverUnconfirmed'>>,): void => {diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex 5e33d78e587..452a243ed5f 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -7,6 +7,7 @@ import {AI_RUNTIME_OPERATION_TYPES,INPUT_LOADING_OPERATION_TYPES,isQueueBlockingOperation,+ isSendableQueuedMessage,QUEUE_BLOCKING_OPERATION_TYPES,SEND_NOW_CANCEL_REASON,TOPIC_VISIBLY_RUNNING_OPERATION_TYPES,@@ -1010,7 +1011,8 @@ const getQueuedMessages = (context: MessageMapKeyInput) => (s: ChatStoreState) =};const getIdleQueueHost = (context: MessageMapKeyInput) => (s: ChatStoreState) => {- if (getQueuedMessages(context)(s).length === 0) return;+ // A steer that may already be with the agent waits for the user, not a hand-off.+ if (!getQueuedMessages(context)(s).some(isSendableQueuedMessage)) return;let latest: Operation | undefined;for (const op of getOperationsByContext(context)(s)) {diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex e861cf05a94..d8e27a25cf7 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -183,7 +183,6 @@ export interface OperationMetadata {* scheduling/execution index.*/llmCalls?: number;-// Progress informationprogress?: {current: number;@@ -204,6 +203,13 @@ export interface OperationMetadata {// Performance informationstartTime: number;+ /**+ * Follow-up behavior is Steer, but this run cannot take a message mid-run+ * (an agent with no native steer): its queue waits for the run end, and the+ * tray says so.+ */+ steerUnsupported?: boolean;+/*** Upstream stream retry state surfaced by heterogeneous agents while no* assistant output has arrived yet.@@ -343,6 +349,13 @@ export interface QueuedMessage {heldBehindOperationId?: string;id: string;interruptMode: 'soft' | 'hard';+ /**+ * A merged steer being written into a local agent session (Follow-up+ * behavior: Steer): `delivering` until the agent reads it, `unknown` when+ * the write failed and it may or may not have arrived. An `unknown` one is+ * never sent on its own; the user sends it again or deletes it.+ */+ localSteer?: 'delivering' | 'unknown';metadata?: MessageMetadata;/*** A run already took this follow-up from the server queue and is handing it@@ -371,6 +384,14 @@ export interface QueuedMessage {serverUnconfirmed?: boolean;}+/**+ * Whether the queued message is one a send can take: a steer that may already+ * be with the agent (`localSteer: 'unknown'`) is never sent on its own, so it+ * holds no turn and no queue hand-off back.+ */+export const isSendableQueuedMessage = (message: QueuedMessage): boolean =>+ message.localSteer !== 'unknown';+/** Whether only this client holds the queued message, so only it can send it. */export const isClientHeldQueuedMessage = (message: QueuedMessage): boolean =>!message.serverDelivery;diff --git a/src/store/user/slices/settings/selectors/general.test.ts b/src/store/user/slices/settings/selectors/general.test.tsindex d58eb3cba9d..d35dff1f90c 100644--- a/src/store/user/slices/settings/selectors/general.test.ts+++ b/src/store/user/slices/settings/selectors/general.test.ts@@ -58,6 +58,33 @@ describe('settingsSelectors', () => {});});+ describe('followUpBehavior', () => {+ it('should stay on the legacy behavior while the lab is off, whatever is stored', () => {+ const s: UserState = merge(initialState, {+ settings: { general: { followUpBehavior: 'queue' } },+ });++ expect(userGeneralSettingsSelectors.followUpBehavior(s as UserStore)).toBe('legacy');+ });++ it('should default to steer with the lab on', () => {+ const s: UserState = merge(initialState, {+ preference: { lab: { enableBetterCodingExperience: true } },+ });++ expect(userGeneralSettingsSelectors.followUpBehavior(s as UserStore)).toBe('steer');+ });++ it('should read the stored setting with the lab on', () => {+ const s: UserState = merge(initialState, {+ preference: { lab: { enableBetterCodingExperience: true } },+ settings: { general: { followUpBehavior: 'queue' } },+ });++ expect(userGeneralSettingsSelectors.followUpBehavior(s as UserStore)).toBe('queue');+ });+ });+describe('enablePasteAutoConvert', () => {it('should default to true when unset', () => {expect(userGeneralSettingsSelectors.enablePasteAutoConvert(initialState as UserStore)).toBe(diff --git a/src/store/user/slices/settings/selectors/general.ts b/src/store/user/slices/settings/selectors/general.tsindex b20081f94a7..73dfa008191 100644--- a/src/store/user/slices/settings/selectors/general.ts+++ b/src/store/user/slices/settings/selectors/general.ts@@ -1,4 +1,5 @@import { isDesktop } from '@lobechat/const';+import { type FollowUpMode, resolveFollowUpMode } from '@lobechat/types';import { DEFAULT_LANG } from '@/const/locale';import { type Locales, normalizeLocale } from '@/locales/resources';@@ -51,6 +52,16 @@ const fontAntialiasing = (s: UserStore) => generalConfig(s).fontAntialiasing ??const workflowStreamingExpandLevel = (s: UserStore) =>generalConfig(s).expandWorkflowWhileStreaming ? 'full' : 'collapsed';+/**+ * What a message sent during a run does. `legacy` (lab off) keeps the+ * behavior from before the setting existed; the setting defaults to steer.+ */+const followUpBehavior = (s: UserStore): FollowUpMode =>+ resolveFollowUpMode(+ s.preference.lab?.enableBetterCodingExperience,+ generalConfig(s).followUpBehavior,+ );+export const userGeneralSettingsSelectors = {animationMode,config: generalConfig,@@ -58,6 +69,7 @@ export const userGeneralSettingsSelectors = {enableAutoScrollOnStreaming,enableMessageLinkIcon,enablePasteAutoConvert,+ followUpBehavior,fontAntialiasing,fontSize,highlighterTheme,