🤯 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(coding): Codex Plan switch with a plan block under Better Coding Experience (#23675)
Bryand373666f60fb
diff --git a/apps/cli/src/commands/connect.nativeRuntimes.test.ts b/apps/cli/src/commands/connect.nativeRuntimes.test.tsindex aafc1faf1f7..bd4920348d1 100644--- a/apps/cli/src/commands/connect.nativeRuntimes.test.ts+++ b/apps/cli/src/commands/connect.nativeRuntimes.test.ts@@ -199,7 +199,9 @@ describe('connect native agent runtimes', () => {await createProgram().parseAsync(['node', 'test', 'connect', 'capabilities']);/** @example Only a successful native handshake is advertised in machine-readable output. */expect(output).toHaveBeenCalledWith(- JSON.stringify({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ JSON.stringify({+ supportedAgentRuntimes: ['codex-app-server-v1', 'codex-collaboration-mode-v1'],+ }),);/** @example Capability discovery does not consume a user login or gateway connection. */expect(resolveToken).not.toHaveBeenCalled();@@ -229,6 +231,7 @@ describe('connect native agent runtimes', () => {expect(codexProbe.connect).toHaveBeenCalledOnce();expect(lastSentSystemInfoResponse.result.systemInfo.supportedAgentRuntimes).toEqual(['codex-app-server-v1',+ 'codex-collaboration-mode-v1',]);});diff --git a/apps/cli/src/commands/connect/handlers.ts b/apps/cli/src/commands/connect/handlers.tsindex 42734e22ae6..54d766f1873 100644--- a/apps/cli/src/commands/connect/handlers.ts+++ b/apps/cli/src/commands/connect/handlers.ts@@ -221,6 +221,7 @@ export function bindGatewayClientHandlers(args: request.args,claudeAccountRouting: request.claudeAccountRouting,claudeCodeEntrypoint: request.claudeCodeEntrypoint,+ collaborationMode: request.collaborationMode,cwd: request.cwd,imageList: request.imageList,jwt: request.jwt,diff --git a/apps/cli/src/commands/hetero/dispatchedModes.test.ts b/apps/cli/src/commands/hetero/dispatchedModes.test.tsnew file mode 100644index 00000000000..7baee68c06c--- /dev/null+++ b/apps/cli/src/commands/hetero/dispatchedModes.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest';++import { dispatchedModeSpawnOptions } from './dispatchedModes';++describe('dispatchedModeSpawnOptions', () => {+ it('gives each agent only its own mode', () => {+ const resolved = { collaborationMode: 'plan' as const, permissionMode: 'plan' as const };+ expect(dispatchedModeSpawnOptions('codex', resolved)).toEqual({ collaborationMode: 'plan' });+ expect(dispatchedModeSpawnOptions('claude-code', resolved)).toEqual({ permissionMode: 'plan' });+ expect(dispatchedModeSpawnOptions('cursor', resolved)).toEqual({});+ });+});diff --git a/apps/cli/src/commands/hetero/dispatchedModes.ts b/apps/cli/src/commands/hetero/dispatchedModes.tsnew file mode 100644index 00000000000..edef2928138--- /dev/null+++ b/apps/cli/src/commands/hetero/dispatchedModes.ts@@ -0,0 +1,20 @@+import type { spawnAgent } from '@lobechat/heterogeneous-agents/spawn';++import type { ResolvedPrompt } from './prompt';++type SpawnOptions = Parameters<typeof spawnAgent>[0];++/**+ * The Better Coding Experience modes the dispatch envelope carried, as spawn+ * options for the agent they belong to: Claude Code's permission mode, and the+ * Codex Plan switch (collaboration mode).+ */+export const dispatchedModeSpawnOptions = (+ agentType: string,+ resolved: Pick<ResolvedPrompt, 'collaborationMode' | 'permissionMode'>,+): Pick<SpawnOptions, 'collaborationMode' | 'permissionMode'> => ({+ ...(agentType === 'claude-code' &&+ resolved.permissionMode && { permissionMode: resolved.permissionMode }),+ ...(agentType === 'codex' &&+ resolved.collaborationMode && { collaborationMode: resolved.collaborationMode }),+});diff --git a/apps/cli/src/commands/hetero/index.ts b/apps/cli/src/commands/hetero/index.tsindex 40f5182e328..122d71230ba 100644--- a/apps/cli/src/commands/hetero/index.ts+++ b/apps/cli/src/commands/hetero/index.ts@@ -49,6 +49,7 @@ import { createLocalTraceStore } from '../../utils/traceStore';import { TrpcIngestSink } from '../../utils/TrpcIngestSink';import type { HeteroCliArgumentOptions } from './buildExtraArgs';import { buildExtraArgs } from './buildExtraArgs';+import { dispatchedModeSpawnOptions } from './dispatchedModes';import { type ResolvedPrompt, resolvePrompt } from './prompt';const DSH_AGENT_TYPE = 'deepseek-harness';@@ -140,6 +141,7 @@ const spawnAgentOrRuntime = (askUserBridge: spawnOpts.askUserBridge,clientVersion: cliVersion,args: spawnOpts.extraArgs ?? [],+ collaborationMode: spawnOpts.collaborationMode,commandPath: spawnOpts.command!,cwd: spawnOpts.cwd ?? process.cwd(),env: { ...process.env, ...spawnOpts.env },@@ -157,20 +159,16 @@ const spawnAgentOrRuntime = (/*** Patterns that indicate a `--resume <sessionId>` run should be retried* without `--resume`. Two classes of failure:- ** 1. Session file missing (sandbox recycled): the container is ephemeral* (~1 h idle TTL), so a new sandbox has an empty `~/.claude/projects/`* and the stored session id is stale.- ** 2. Context overflow (long conversation): the resumed session carries all- * accumulated history; when the combined token count exceeds the model's- * context window the API rejects the request immediately after CC- * initialises. Starting fresh (no `--resume`) drops the old history and- * lets CC respond to the new prompt alone.+ * accumulated history past the model's context window, so the API rejects+ * the request right after CC initialises. Starting fresh (no `--resume`)+ * drops the old history and lets CC respond to the new prompt alone.*- * Checked against:- * - `error` stream events emitted by the CC adapter from CC's result event- * - Accumulated stderr output (fallback when CC exits without a result event)+ * Checked against `error` stream events (from CC's result event) and, when CC+ * exits without a result event, the accumulated stderr output.*/const RESUME_RETRY_PATTERNS = [// Session file missing — sandbox was recycled@@ -1078,9 +1076,8 @@ const exec = async (options: ExecOptions): Promise<void> => {// input (live steer / background tasks).liveInput: options.type === 'claude-code' || options.type === 'antigravity',operationId,- // Better Coding Experience: Claude Code prompts answered on the bridge's cards.- ...(options.type === 'claude-code' &&- resolved.permissionMode && { permissionMode: resolved.permissionMode }),+ // Better Coding Experience: Claude Code permission mode, Codex Plan switch.+ ...dispatchedModeSpawnOptions(options.type, resolved),uploadImage,};diff --git a/apps/cli/src/commands/hetero/prompt.test.ts b/apps/cli/src/commands/hetero/prompt.test.tsindex e3296656fed..fa03de2b0fd 100644--- a/apps/cli/src/commands/hetero/prompt.test.ts+++ b/apps/cli/src/commands/hetero/prompt.test.ts@@ -53,4 +53,24 @@ describe('resolvePrompt — dispatch envelope', () => {resumeFallbackPrompt: [{ text: 'history + hi', type: 'text' }],});});++ it('takes the Codex Plan switch', async () => {+ const resolved = await resolvePrompt({+ inputJson: await inputFile({+ collaborationMode: 'plan',+ content: [{ text: 'hi', type: 'text' }],+ }),+ });+ expect(resolved.collaborationMode).toBe('plan');+ });++ it('ignores a collaboration mode it does not know', async () => {+ const resolved = await resolvePrompt({+ inputJson: await inputFile({+ collaborationMode: 'execute',+ content: [{ text: 'hi', type: 'text' }],+ }),+ });+ expect(resolved.collaborationMode).toBeUndefined();+ });});diff --git a/apps/cli/src/commands/hetero/prompt.ts b/apps/cli/src/commands/hetero/prompt.tsindex 36ab77471f5..3298ec0387b 100644--- a/apps/cli/src/commands/hetero/prompt.ts+++ b/apps/cli/src/commands/hetero/prompt.ts@@ -6,7 +6,12 @@ import type {AgentImageSource,AgentPromptInput,} from '@lobechat/heterogeneous-agents/spawn';-import { type HeteroPermissionMode, isHeteroPermissionMode } from '@lobechat/types';+import {+ type CodexCollaborationMode,+ type HeteroPermissionMode,+ isCodexCollaborationMode,+ isHeteroPermissionMode,+} from '@lobechat/types';/** The `lh hetero exec` options that choose where the prompt comes from. */interface ExecOptions {@@ -59,14 +64,18 @@ const parseImageArg = (value: string): AgentImageSource => {* Accepts:* - `'plain text'` → single text block* - `[{ type: 'text', text }, { type: 'image', source }]` → content blocks- * - `{ content: [...], resumeFallback?: [...], permissionMode? }` → unwraps the- * primary prompt, reserves the fallback for a retry without native resume,- * and takes the Claude Code permission mode the run was dispatched with+ * - `{ content: [...], resumeFallback?: [...], permissionMode?, collaborationMode? }`+ * → unwraps the primary prompt, reserves the fallback for a retry without+ * native resume, and takes the Claude Code permission mode / Codex Plan+ * switch the run was dispatched with* - `{ type: 'text', ... } | { type: 'image', ... }` → single block*/const coerceJsonPrompt = (parsed: unknown,-): Pick<ResolvedPrompt, 'permissionMode' | 'prompt' | 'resumeFallbackPrompt'> => {+): Pick<+ ResolvedPrompt,+ 'collaborationMode' | 'permissionMode' | 'prompt' | 'resumeFallbackPrompt'+> => {if (typeof parsed === 'string') return { prompt: parsed };if (Array.isArray(parsed)) return { prompt: parsed as AgentContentBlock[] };if (parsed && typeof parsed === 'object') {@@ -74,6 +83,9 @@ const coerceJsonPrompt = (if (Array.isArray(obj.content)) {return {...(isHeteroPermissionMode(obj.permissionMode) && { permissionMode: obj.permissionMode }),+ ...(isCodexCollaborationMode(obj.collaborationMode) && {+ collaborationMode: obj.collaborationMode,+ }),prompt: obj.content as AgentContentBlock[],...(Array.isArray(obj.resumeFallback)? { resumeFallbackPrompt: obj.resumeFallback as AgentContentBlock[] }@@ -91,6 +103,11 @@ const coerceJsonPrompt = (};export interface ResolvedPrompt {+ /**+ * Codex Plan switch (Better Coding Experience lab): the collaboration mode+ * a native Codex run sends on every turn.+ */+ collaborationMode?: CodexCollaborationMode;/** Human-readable description for the empty-input check. */describe: () => string;/**diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex f2bea572ed9..e8e2d88f2cd 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -13,7 +13,7 @@ import {} from '@lobechat/heterogeneous-agents/protocol';import type { ClaudeCodeAccountRouting } from '@lobechat/heterogeneous-agents/quota';import { resolveHeteroSpawnCwd } from '@lobechat/heterogeneous-agents/workingDirectory';-import type { HeteroPermissionMode } from '@lobechat/types';+import type { CodexCollaborationMode, HeteroPermissionMode } from '@lobechat/types';import { getTask, removeTask, saveTask } from '../daemon/taskRegistry';import { registerAgentRun } from './agentRunRegistry';@@ -28,6 +28,8 @@ export interface SpawnHeteroAgentRunParams {claudeAccountRouting?: ClaudeCodeAccountRouting;/** Entrypoint name the agent asked Claude Code to report. */claudeCodeEntrypoint?: string;+ /** Codex Plan switch, forwarded in the input envelope. */+ collaborationMode?: CodexCollaborationMode;cwd?: string;/** Image attachments (signed URLs) appended as image content blocks. */imageList?: HeteroExecImageRef[];@@ -144,6 +146,7 @@ function startHeteroAgentRun(// the desktop path. `lh hetero exec` coerces both shapes via// coerceJsonPrompt.const stdinPayload = buildHeteroExecStdinPayload({+ collaborationMode: params.collaborationMode,imageList,isNewSession: !resumeSessionId,permissionMode: params.permissionMode,diff --git a/apps/cli/src/device/systemInfo.test.ts b/apps/cli/src/device/systemInfo.test.tsindex 9dc06346a66..4c82ea2b448 100644--- a/apps/cli/src/device/systemInfo.test.ts+++ b/apps/cli/src/device/systemInfo.test.ts@@ -35,7 +35,10 @@ describe('probeNativeRuntimes', () => {});it('advertises native Codex after a successful handshake on the resolved binary', async () => {- await expect(probeNativeRuntimes()).resolves.toEqual(['codex-app-server-v1']);+ await expect(probeNativeRuntimes()).resolves.toEqual([+ 'codex-app-server-v1',+ 'codex-collaboration-mode-v1',+ ]);/** @example Resolution PATH is carried into the exact probed executable. */expect(codexProbe.options).toHaveBeenCalledWith(expect.objectContaining({diff --git a/apps/cli/src/device/systemInfo.ts b/apps/cli/src/device/systemInfo.tsindex 1984e9339f3..6f0b4ea2e73 100644--- a/apps/cli/src/device/systemInfo.ts+++ b/apps/cli/src/device/systemInfo.ts@@ -8,6 +8,7 @@ import { resolveHeteroSpawnCommand } from '@lobechat/heterogeneous-agents/resolvimport type { RuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';import { CodexAppServerClient } from '@lobechat/heterogeneous-agents/spawn';import { getShellInfo } from '@lobechat/local-file-shell';+import { CODEX_COLLABORATION_MODE_RUNTIME } from '@lobechat/types';import { CLI_CONFIG_DIR_NAME } from '../constants/identity';import { cliVersion } from '../pkg';@@ -71,9 +72,14 @@ async function supportsNativeCodex(): Promise<boolean> {}}-/** Native agent runtimes the resolved binaries support; one handshake per call. */+/**+ * Native agent runtimes the resolved binaries support; one handshake per call.+ * `codex-collaboration-mode-v1` says this `lh` also takes the Codex Plan switch.+ */export async function probeNativeRuntimes(): Promise<string[]> {- return (await supportsNativeCodex()) ? ['codex-app-server-v1'] : [];+ return (await supportsNativeCodex())+ ? ['codex-app-server-v1', CODEX_COLLABORATION_MODE_RUNTIME]+ : [];}/**diff --git a/apps/cli/src/utils/heteroCollaborationMode.test.ts b/apps/cli/src/utils/heteroCollaborationMode.test.tsnew file mode 100644index 00000000000..9b10d05d8ce--- /dev/null+++ b/apps/cli/src/utils/heteroCollaborationMode.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';++import { HETERO_SET_COLLABORATION_MODE_COMMAND } from './heteroCollaborationMode';+import { dispatchHeteroControl } from './heteroControl';++const setMode = (params: unknown, setCollaborationMode?: (mode: any) => Promise<void>) =>+ dispatchHeteroControl(+ { command: HETERO_SET_COLLABORATION_MODE_COMMAND, createdAt: 1, id: 'ctl-1', params },+ {+ operationId: 'op-1',+ sendControlRequest: () => undefined,+ setCollaborationMode,+ signal: new AbortController().signal,+ },+ );++describe('set_collaboration_mode control handler', () => {+ it('switches the native Codex thread and reports the mode', async () => {+ const setCollaborationMode = vi.fn().mockResolvedValue(undefined);++ await expect(setMode({ mode: 'plan' }, setCollaborationMode)).resolves.toEqual({+ data: { mode: 'plan' },+ status: 'ok',+ });+ expect(setCollaborationMode).toHaveBeenCalledWith('plan');+ });++ it('refuses an unknown mode and a run that is not a native Codex thread', async () => {+ await expect(setMode({ mode: 'execute' }, vi.fn())).resolves.toMatchObject({+ status: 'error',+ });+ await expect(setMode({ mode: 'default' })).resolves.toMatchObject({+ error: 'This run is not a native Codex thread',+ status: 'error',+ });+ });+});diff --git a/apps/cli/src/utils/heteroCollaborationMode.ts b/apps/cli/src/utils/heteroCollaborationMode.tsnew file mode 100644index 00000000000..80c6faa97bc--- /dev/null+++ b/apps/cli/src/utils/heteroCollaborationMode.ts@@ -0,0 +1,26 @@+import { isCodexCollaborationMode } from '@lobechat/types';++import { type HeteroControlHandler, registerHeteroControlHandler } from './heteroControl';++/** The control command the server queues when the Codex Plan switch flips mid-run. */+export const HETERO_SET_COLLABORATION_MODE_COMMAND = 'set_collaboration_mode';++/**+ * Switch a running native Codex thread's collaboration mode (the composer's+ * Plan switch). Codex takes it from the next turn: `thread/settings/update`+ * never changes the turn in flight. Reports the mode that was set.+ */+export const setCollaborationModeHandler: HeteroControlHandler = async ({+ params,+ setCollaborationMode,+}) => {+ const mode = (params as { mode?: unknown } | null)?.mode;+ if (!isCodexCollaborationMode(mode)) {+ throw new Error('set_collaboration_mode needs a valid mode');+ }+ if (!setCollaborationMode) throw new Error('This run is not a native Codex thread');+ await setCollaborationMode(mode);+ return { mode };+};++registerHeteroControlHandler(HETERO_SET_COLLABORATION_MODE_COMMAND, setCollaborationModeHandler);diff --git a/apps/cli/src/utils/heteroControl.ts b/apps/cli/src/utils/heteroControl.tsindex d141a269de4..523b8cffde6 100644--- a/apps/cli/src/utils/heteroControl.ts+++ b/apps/cli/src/utils/heteroControl.ts@@ -2,6 +2,7 @@ import type {ClaudeCodeControlRequest,ClaudeCodeControlRequestHandle,} from '@lobechat/heterogeneous-agents/spawn';+import type { CodexCollaborationMode } from '@lobechat/types';/*** A command the server queued for this run (`enqueueHeteroControl`), handed@@ -34,6 +35,8 @@ export interface HeteroControlContext {sendControlRequest: (request: ClaudeCodeControlRequest,) => ClaudeCodeControlRequestHandle | undefined;+ /** (native Codex) Switch the thread's collaboration mode from its next turn. */+ setCollaborationMode?: (mode: CodexCollaborationMode) => Promise<void>;/** Aborted when the run's event stream ends. */signal: AbortSignal;}diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.tsindex 6d3db235e5c..40f20fecb57 100644--- a/apps/cli/src/utils/heteroSteer.ts+++ b/apps/cli/src/utils/heteroSteer.ts@@ -1,4 +1,5 @@// Built-in control commands register themselves when the steer loop loads.+import './heteroCollaborationMode';import './heteroPermissionMode';import './heteroStopTask';@@ -8,6 +9,7 @@ import type {ClaudeCodeControlRequest,ClaudeCodeControlRequestHandle,} from '@lobechat/heterogeneous-agents/spawn';+import type { CodexCollaborationMode } from '@lobechat/types';import {dispatchHeteroControl,@@ -90,6 +92,7 @@ interface SteerableHandle {request: ClaudeCodeControlRequest,) => ClaudeCodeControlRequestHandle | undefined;sendUserMessage?: (prompt: AgentPromptInput, options?: { uuid?: string }) => Promise<boolean>;+ setCollaborationMode?: (mode: CodexCollaborationMode) => Promise<void>;supportsSteerImageAttachments?: true;supportsSteerImages?: boolean;}@@ -147,6 +150,7 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(const { operationId } = context;const sendControlRequest = handle.sendControlRequest;+ const setCollaborationMode = handle.setCollaborationMode;const delivered = new Set<string>();const abort = new AbortController();const handling = new Set<Promise<void>>();@@ -187,7 +191,9 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(log.debug('Control %s: %s', control.id, control.command);const outcome = await dispatchHeteroControl(control, {operationId,- sendControlRequest: sendControlRequest!,+ // A native Codex run has no stream-json input: its handlers say so.+ sendControlRequest: sendControlRequest ?? (() => undefined),+ setCollaborationMode,signal: abort.signal,});await report(client, control, outcome);@@ -200,7 +206,9 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(const poll = async () => {const client = await context.getTrpcClient();// Control messages need a way into the session and back to the server.- const acceptsControl = !!sendControlRequest && !!client.aiAgent.reportHeteroControlResult;+ const acceptsControl =+ (!!sendControlRequest || !!setCollaborationMode) &&+ !!client.aiAgent.reportHeteroControlResult;while (!abort.signal.aborted) {let message: HeteroSteerMessage | null;try {diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 1e6400f4fae..17b555c744c 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -218,6 +218,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {return (await this.getImplementation()).setPermissionMode(...args);}+ @IpcMethod()+ async setCollaborationMode(...args: Parameters<Implementation['setCollaborationMode']>) {+ return (await this.getImplementation()).setCollaborationMode(...args);+ }+@IpcMethod()async submitIntervention(...args: Parameters<Implementation['submitIntervention']>) {return (await this.getImplementation()).submitIntervention(...args);diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 01f086650c1..a4d3fd0933a 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -76,7 +76,6 @@ import {DSH_COMMAND,ensureClaudeCodeResumeTranscript,findClaudeCodeTranscriptPath,- getCodexAppServerUnsupportedArgs,getHeterogeneousAgentSpawnEnv,prepareClaudeCodeLobeHubCli,readClaudeCodeSessionCost,@@ -95,6 +94,7 @@ import {resolveHeteroSpawnCwd,} from '@lobechat/heterogeneous-agents/workingDirectory';import type {+ CodexCollaborationMode,HeterogeneousAgentModelCatalog,HeteroPermissionMode,ListHeterogeneousAgentModelsParams,@@ -160,7 +160,7 @@ import {import { createLogger } from '@/utils/logger';import BrowserControlCtr from './BrowserControlCtr';-import { sendPromptWithCodexAppServer } from './codexAppServer';+import { type CodexAppServerHost, dispatchCodexPrompt } from './codexAppServer';import { createLiveCliAdapter, endLiveCliRun, writeCliPrompt } from './heterogeneousAgentLiveInput';import {attachCliPermissionPrompts,@@ -173,6 +173,7 @@ import type {CliTraceSession,GetSessionInfoParams,SendPromptParams,+ SetCollaborationModeParams,SetPermissionModeParams,StopBackgroundTaskParams,StopSessionParams,@@ -476,34 +477,11 @@ export default class HeterogeneousAgentCtr {await session.hostedProviderBinding?.cleanup();}},- 'codex': async (params, session) => {- if (- session.hostedProviderBinding ||- session.codexAppServerFallback ||- !(session.useCodexAppServer || this.isCodexAppServerLabEnabled)- ) {- return false;- }- const unsupportedArgs = getCodexAppServerUnsupportedArgs(session.args, {- resume: !!session.agentSessionId,- });- if (unsupportedArgs.length === 0) {- // `true` = app-server handled the prompt; `false` = fall through to- // the generic `codex exec` spawn.- return this.sendPromptWithCodexAppServer(params, session);- }- if (session.agentSessionId) {- const message = `Codex app-server cannot safely resume this session without dropping CLI arguments: ${unsupportedArgs.join(', ')}`;- this.broadcast('heteroAgentSessionError', { error: message, sessionId: session.sessionId });- throw new Error(message);- }- session.codexAppServerFallback = true;- logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {- sessionId: session.sessionId,- unsupportedArgs,- });- return false;- },+ // `true` = app-server handled the prompt; `false` = the generic `codex exec` spawn.+ 'codex': (params, session) =>+ dispatchCodexPrompt(this.codexAppServerHost(), params, session, {+ appServerEnabled: !!(session.useCodexAppServer || this.isCodexAppServerLabEnabled),+ }),'copilot': async (params, session) => {await this.sendPromptWithAcp(params, session);return true;@@ -1996,39 +1974,32 @@ export default class HeterogeneousAgentCtr {}/**- * Delegates the Codex transport while retaining controller-owned session services.+ * Controller-owned session services the Codex transport runs on.** Call stack:*- * sendPrompt -> runtimeDispatchers -> {@link sendPromptWithCodexAppServer}+ * sendPrompt -> runtimeDispatchers -> {@link dispatchCodexPrompt}*/- private sendPromptWithCodexAppServer(- params: SendPromptParams,- session: AgentSession,- ): Promise<boolean> {- return sendPromptWithCodexAppServer(- {- clientState: this.codexAppServerState,- fileCacheDir: this.fileCacheDir,- appendCliTraceFile: this.appendCliTraceFile.bind(this),- broadcast: this.broadcast.bind(this),- buildSessionSpawnEnv: this.buildSessionSpawnEnv.bind(this),- completeCancelledSessionBeforeLaunch: this.completeCancelledSessionBeforeLaunch.bind(this),- createCliTraceSession: this.createCliTraceSession.bind(this),- flushCliTrace: this.flushCliTrace.bind(this),- getErrorMessage: this.getErrorMessage.bind(this),- getInflightRuns: this.getInflightRuns.bind(this),- getSessionErrorPayload: this.getSessionErrorPayload.bind(this),- needsSessionIntroduction: this.needsSessionIntroduction.bind(this),- recordInflightRun: this.recordInflightRun.bind(this),- resolveSessionCommand: this.resolveSessionCommand.bind(this),- setupAcpInterventionForOp: this.setupAcpInterventionForOp.bind(this),- writeCliTraceFile: this.writeCliTraceFile.bind(this),- writeCliTraceJson: this.writeCliTraceJson.bind(this),- },- params,- session,- );+ private codexAppServerHost(): CodexAppServerHost {+ return {+ clientState: this.codexAppServerState,+ fileCacheDir: this.fileCacheDir,+ appendCliTraceFile: this.appendCliTraceFile.bind(this),+ broadcast: this.broadcast.bind(this),+ buildSessionSpawnEnv: this.buildSessionSpawnEnv.bind(this),+ completeCancelledSessionBeforeLaunch: this.completeCancelledSessionBeforeLaunch.bind(this),+ createCliTraceSession: this.createCliTraceSession.bind(this),+ flushCliTrace: this.flushCliTrace.bind(this),+ getErrorMessage: this.getErrorMessage.bind(this),+ getInflightRuns: this.getInflightRuns.bind(this),+ getSessionErrorPayload: this.getSessionErrorPayload.bind(this),+ needsSessionIntroduction: this.needsSessionIntroduction.bind(this),+ recordInflightRun: this.recordInflightRun.bind(this),+ resolveSessionCommand: this.resolveSessionCommand.bind(this),+ setupAcpInterventionForOp: this.setupAcpInterventionForOp.bind(this),+ writeCliTraceFile: this.writeCliTraceFile.bind(this),+ writeCliTraceJson: this.writeCliTraceJson.bind(this),+ };}private sendPromptWithAcp(params: SendPromptParams, session: AgentSession): Promise<void> {@@ -2343,7 +2314,12 @@ export default class HeterogeneousAgentCtr {if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);const live = !!spawnPlan.liveInput;- session.liveInput = writeCliPrompt(proc.stdin as Writable, spawnPlan.stdinPayload, live, session.agentType);+ session.liveInput = writeCliPrompt(+ proc.stdin as Writable,+ spawnPlan.stdinPayload,+ live,+ session.agentType,+ );}session.process = proc;@@ -3227,6 +3203,13 @@ export default class HeterogeneousAgentCtr {return setSessionPermissionMode(this.sessions.get(sessionId), mode);}+ /** Flip a native Codex thread's Plan switch; it applies from the next turn. */+ async setCollaborationMode({ mode, sessionId }: SetCollaborationModeParams) {+ const appServerSession = this.sessions.get(sessionId)?.appServerSession;+ if (!appServerSession) throw new Error('This run is not a native Codex thread');+ await appServerSession.setCollaborationMode(mode);+ }+/*** Renderer → main: deliver the user's answer to a pending CC AskUserQuestion* (or signal cancellation). The matching bridge resolves its blocked@@ -3373,6 +3356,8 @@ export default class HeterogeneousAgentCtr {jwt: string;operationId: string;permissionMode?: HeteroPermissionMode;+ /** Codex Plan switch, forwarded into the `--input-json` envelope. */+ collaborationMode?: CodexCollaborationMode;prompt: string;resumeFallbackSystemContext?: string;resumeSessionId?: string;@@ -3440,6 +3425,7 @@ export default class HeterogeneousAgentCtr {];const stdinPayload = buildHeteroExecStdinPayload({+ collaborationMode: params.collaborationMode,imageList,isNewSession: !resumeSessionId,permissionMode: params.permissionMode,diff --git a/apps/desktop/src/main/controllers/codexAppServer.ts b/apps/desktop/src/main/controllers/codexAppServer.tsindex e65b71faf2d..06cc80d7072 100644--- a/apps/desktop/src/main/controllers/codexAppServer.ts+++ b/apps/desktop/src/main/controllers/codexAppServer.ts@@ -9,6 +9,7 @@ import {buildCodexAppServerThreadParams,CodexAppServerClient,CodexThreadSession,+ getCodexAppServerUnsupportedArgs,isCodexAppServerCompatibilityError,pickCodexRunProvenance,readCodexSessionModel,@@ -25,7 +26,7 @@ import type { AgentSession, CliTraceSession, SendPromptParams } from './heterogeconst logger = createLogger('controllers:HeterogeneousAgentCtr');/** Controller-owned services used by the Codex transport without owning other transports. */-interface CodexAppServerHost {+export interface CodexAppServerHost {appendCliTraceFile: (trace: CliTraceSession | undefined,name: string,@@ -77,6 +78,44 @@ interface CodexAppServerHost {) => Promise<void> | undefined;}+/**+ * Routes one desktop Codex turn: the native app-server when the lab is on and+ * it can honor the session's arguments, else `codex exec`.+ *+ * Returns:+ * - True after the app-server handled the turn; false for the generic exec spawn.+ *+ * Call stack:+ *+ * HeterogeneousAgentCtr.sendPrompt -> runtimeDispatchers.codex+ * -> {@link dispatchCodexPrompt} -> {@link sendPromptWithCodexAppServer}+ */+export async function dispatchCodexPrompt(+ host: CodexAppServerHost,+ params: SendPromptParams,+ session: AgentSession,+ { appServerEnabled }: { appServerEnabled: boolean },+): Promise<boolean> {+ if (session.hostedProviderBinding || session.codexAppServerFallback || !appServerEnabled) {+ return false;+ }+ const unsupportedArgs = getCodexAppServerUnsupportedArgs(session.args, {+ resume: !!session.agentSessionId,+ });+ if (unsupportedArgs.length === 0) return sendPromptWithCodexAppServer(host, params, session);+ if (session.agentSessionId) {+ const message = `Codex app-server cannot safely resume this session without dropping CLI arguments: ${unsupportedArgs.join(', ')}`;+ host.broadcast('heteroAgentSessionError', { error: message, sessionId: session.sessionId });+ throw new Error(message);+ }+ session.codexAppServerFallback = true;+ logger.warn('Falling back to codex exec because app-server cannot preserve CLI args:', {+ sessionId: session.sessionId,+ unsupportedArgs,+ });+ return false;+}+/*** Runs one desktop Codex turn through the shared app-server and its native thread.*@@ -230,6 +269,7 @@ export async function sendPromptWithCodexAppServer(try {await appServerSession.run({askUserBridge: intervention.bridge,+ collaborationMode: params.collaborationMode,input,onRawMessage: (line) => host.appendCliTraceFile(traceSession, 'stdout.jsonl', line),operationId: params.operationId,diff --git a/apps/desktop/src/main/controllers/gatewayAgentRun.ts b/apps/desktop/src/main/controllers/gatewayAgentRun.tsindex fe820a83c16..7ef3f6982a8 100644--- a/apps/desktop/src/main/controllers/gatewayAgentRun.ts+++ b/apps/desktop/src/main/controllers/gatewayAgentRun.ts@@ -95,6 +95,7 @@ export const executeGatewayAgentRun = async (agentType: request.agentType,assistantMessageId: request.assistantMessageId,args: request.args,+ collaborationMode: request.collaborationMode,cwd: request.cwd,imageList: request.imageList,jwt: request.jwt,diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex ae9ddcb6af7..15a966f65f7 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -39,6 +39,7 @@ import {TraeAcpSession,} from '@lobechat/heterogeneous-agents/spawn';import type {+ CodexCollaborationMode,HeterogeneousServerDefaultApiConfig,HeteroPermissionMode,HeteroSessionImportMessage,@@ -62,6 +63,11 @@ export interface SendPromptParams {agentId?: string;/** Assistant row this run streams into — recorded so recovery can scope to its branch. */assistantMessageId?: string;+ /**+ * (Codex, Better Coding Experience lab) The Plan switch: the collaboration+ * mode every native app-server turn sends. Absent sends none.+ */+ collaborationMode?: CodexCollaborationMode;/** Image attachments to include in the prompt (downloaded from url, cached by id) */imageList?: HeterogeneousAgentImageAttachment[];/**@@ -858,6 +864,11 @@ export interface SetPermissionModeParams {sessionId: string;}+export interface SetCollaborationModeParams {+ mode: CodexCollaborationMode;+ sessionId: string;+}+export interface StopBackgroundTaskParams {sessionId: string;/** Claude Code `task_id` of the background task to stop. */diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.tsindex c65df6dccc1..8d94bd02c0f 100644--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts@@ -74,7 +74,9 @@ describe('GatewayConnectionService system_info_request', () => {// Probe that bundled runtime instead of a potentially older global lh binary.getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });execFileMock.mockResolvedValue({- stdout: JSON.stringify({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ stdout: JSON.stringify({+ supportedAgentRuntimes: ['codex-app-server-v1', 'codex-collaboration-mode-v1', 'future'],+ }),});const client = createClient();await service['handleSystemInfoRequest'](client, {@@ -86,7 +88,10 @@ describe('GatewayConnectionService system_info_request', () => {expect.objectContaining({result: {success: true,- systemInfo: expect.objectContaining({ supportedAgentRuntimes: ['codex-app-server-v1'] }),+ // The Plan switch capability passes through; one this build does not know does not.+ systemInfo: expect.objectContaining({+ supportedAgentRuntimes: ['codex-app-server-v1', 'codex-collaboration-mode-v1'],+ }),},}),);diff --git a/apps/desktop/src/main/services/gatewaySystemInfo.ts b/apps/desktop/src/main/services/gatewaySystemInfo.tsindex 0e228ebc0be..db0eb35220b 100644--- a/apps/desktop/src/main/services/gatewaySystemInfo.ts+++ b/apps/desktop/src/main/services/gatewaySystemInfo.ts@@ -6,6 +6,7 @@ import { BROWSER_IDENTIFIER } from '@lobechat/device-control/agent-browser';import { COMPUTER_USE_IDENTIFIER } from '@lobechat/device-control/computer-use';import type { DeviceSystemInfo } from '@lobechat/device-gateway-client';import type { RuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';+import { CODEX_COLLABORATION_MODE_RUNTIME } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import { app } from 'electron';@@ -44,9 +45,11 @@ export const collectBundledCliAgentRuntimes = async (): Promise<string[]> => {);const result: unknown = JSON.parse(stdout);if (!isRecord(result) || !Array.isArray(result.supportedAgentRuntimes)) return [];- return result.supportedAgentRuntimes.includes('codex-app-server-v1')- ? ['codex-app-server-v1']- : [];+ // Forward only the native runtimes this build knows how to dispatch.+ return result.supportedAgentRuntimes.filter(+ (runtime): runtime is string =>+ runtime === 'codex-app-server-v1' || runtime === CODEX_COLLABORATION_MODE_RUNTIME,+ );} catch (error) {logger.debug('Bundled CLI native capability probe unavailable', error);return [];diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex 7a7675f189e..cf82a703a9f 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -1,5 +1,6 @@import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';import {+ CODEX_COLLABORATION_MODES,HETERO_PERMISSION_MODES,LocalExecutionHeterogeneousAgentTypeSchema,} from '@lobechat/types';@@ -25,6 +26,7 @@ import {returnHeteroSteer,takeHeteroSteer,} from '@/server/services/aiAgent/steerQueue/hetero';+import { setHeteroCollaborationMode } from '@/server/services/aiAgent/steerQueue/heteroCollaborationMode';import {type HeteroControlMessage,reportHeteroControlResult,@@ -187,6 +189,12 @@ const SetHeteroPermissionModeSchema = z.object({operationId: z.string().min(1),});+/** Schema for `aiAgent.setHeteroCollaborationMode` — the Codex Plan switch, mid-run. */+const SetHeteroCollaborationModeSchema = z.object({+ mode: z.enum(CODEX_COLLABORATION_MODES),+ operationId: z.string().min(1),+});+/** Schema for `aiAgent.returnHeteroSteer` — the session could not take the message. */const ReturnHeteroSteerSchema = z.object({messageId: z.string().min(1),@@ -745,6 +753,13 @@ export const heteroRouter = router({await assertControlsHeteroRun(ctx, input.operationId);return setHeteroPermissionMode(input.operationId, input.mode);}),+ /** Flip a running native Codex thread's Plan switch; it applies from the next turn. */+ setHeteroCollaborationMode: aiAgentWriteProcedure+ .input(SetHeteroCollaborationModeSchema)+ .mutation(async ({ input, ctx }) => {+ await assertControlsHeteroRun(ctx, input.operationId);+ return setHeteroCollaborationMode(input.operationId, input.mode);+ }),/** Token-only atomic resolution path used by Mobile review/deep links. */resolveHeteroIntervention: aiAgentWriteProcedure.input(ResolveHeteroInterventionReviewSchema)diff --git a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.tsindex 08d61b1e960..5549e321b70 100644--- a/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/index.procedures.test.ts@@ -58,6 +58,7 @@ function expected(): Array<[name: string, type: 'mutation' | 'query']> {['retryWorktreeTurn', 'mutation'],['returnHeteroSteer', 'mutation'],['scheduleAgentRun', 'mutation'],+ ['setHeteroCollaborationMode', 'mutation'],['setHeteroPermissionMode', 'mutation'],['setQueuedMessages', 'mutation'],['startExecution', 'mutation'],diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.tsindex 42e707f3581..1f6c17aaba1 100644--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts@@ -52,6 +52,7 @@ function expected(): Array<['drainWorktreeCleanups', 'mutation', 12],['getAgentDeviceBindings', 'query', 12],['getAgentProfile', 'query', 12],+ ['getAgentRunRuntimes', 'query', 12],['getAntigravityQuota', 'query', 12],['getAppUpdateState', 'query', 12],['getClaudeCodeQuota', 'query', 12],diff --git a/apps/server/src/routers/lambda/device/registry.ts b/apps/server/src/routers/lambda/device/registry.tsindex 70baff645c4..89c68109145 100644--- a/apps/server/src/routers/lambda/device/registry.ts+++ b/apps/server/src/routers/lambda/device/registry.ts@@ -21,6 +21,7 @@ import { managedDeviceProvider } from '@/business/server/managedDevice';import { getTopicDeviceId, TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';import { router } from '@/libs/trpc/lambda';+import { probeAgentRunRuntimes } from '@/server/services/aiAgent/pipeline/codexDeviceRuntime';import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGateway';import { filterAuthorizedDevicePresence } from '@/server/services/deviceGateway/scopedDevicePresence';@@ -200,6 +201,22 @@ export const registryRouter = router({.query(async ({ ctx, input }) => {return deviceGateway.queryDeviceSystemInfo(ctx.userId, input.deviceId, ctx.workspaceId);}),+ /**+ * The native runtimes of the connection an agent run on this device would+ * reach (`lh connect` before the Desktop app, as the dispatch routes it),+ * for controls that depend on them — e.g. the Codex Plan switch needs+ * `codex-collaboration-mode-v1`. Empty when nothing answered.+ */+ getAgentRunRuntimes: deviceProcedure+ .input(z.object({ deviceId: z.string() }))+ .query(async ({ ctx, input }) => {+ const probe = await probeAgentRunRuntimes((clientKinds) =>+ deviceGateway.readDeviceSystemInfo(ctx.userId, input.deviceId, ctx.workspaceId, {+ clientKinds,+ }),+ );+ return { runtimes: [...(probe.runtimes ?? [])] };+ }),/*** All devices the user has ever registered (incl. offline). A device is keyed* by its `deviceId`; the gateway's live WS sessions are NOT separate devices —diff --git a/apps/server/src/routers/lambda/user/index.procedures.test.ts b/apps/server/src/routers/lambda/user/index.procedures.test.tsindex 93274a48269..976e075e85c 100644--- a/apps/server/src/routers/lambda/user/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/user/index.procedures.test.ts@@ -50,6 +50,7 @@ function expected(): Array<['saveUserQuestion', 'mutation', 11],['sendOnboardingFirstMessage', 'mutation', 11],['setHeteroPermissionModeDir', 'mutation', 11],+ ['setHeteroPlanModeDir', 'mutation', 11],['setWorktreeModeDir', 'mutation', 11],['startOnboardingUnderstanding', 'mutation', 14],['updateAgentOnboarding', 'mutation', 11],diff --git a/apps/server/src/routers/lambda/user/settings.ts b/apps/server/src/routers/lambda/user/settings.tsindex 3bc7ae62656..88ce1520e4b 100644--- a/apps/server/src/routers/lambda/user/settings.ts+++ b/apps/server/src/routers/lambda/user/settings.ts@@ -70,6 +70,12 @@ export const settingsRouter = router({setWorktreeModeDir: userProcedure.input(z.object({ enabled: z.boolean(), key: z.string().min(1).max(4096) })).mutation(async ({ ctx, input }) => ctx.userModel.setWorktreeModeDir(input.key, input.enabled)),+ /** Personal-mode Codex Plan switch remembered for one directory. */+ setHeteroPlanModeDir: userProcedure+ .input(z.object({ enabled: z.boolean(), key: z.string().min(1).max(4096) }))+ .mutation(async ({ ctx, input }) =>+ ctx.userModel.setHeteroPlanModeDir(input.key, input.enabled),+ ),/** Personal-mode Claude Code permission mode remembered for one directory. */setHeteroPermissionModeDir: userProcedure.input(z.object({ key: z.string().min(1).max(4096), mode: z.enum(HETERO_PERMISSION_MODES) }))diff --git a/apps/server/src/routers/lambda/workspaceUserSettings.ts b/apps/server/src/routers/lambda/workspaceUserSettings.tsindex 24b27742caa..c2134a4e6c2 100644--- a/apps/server/src/routers/lambda/workspaceUserSettings.ts+++ b/apps/server/src/routers/lambda/workspaceUserSettings.ts@@ -78,6 +78,13 @@ export const workspaceUserSettingsRouter = router({ctx.workspaceUserSettingsModel.setWorktreeModeDir(input.key, input.enabled),),+ /** Whether this member last left the Codex Plan switch on for one directory. */+ setHeteroPlanModeDir: workspaceUserSettingsProcedure+ .input(z.object({ enabled: z.boolean(), key: z.string().min(1).max(4096) }))+ .mutation(async ({ ctx, input }) =>+ ctx.workspaceUserSettingsModel.setHeteroPlanModeDir(input.key, input.enabled),+ ),+/** The Claude Code permission mode this member last picked for one directory. */setHeteroPermissionModeDir: workspaceUserSettingsProcedure.input(z.object({ key: z.string().min(1).max(4096), mode: z.enum(HETERO_PERMISSION_MODES) }))diff --git a/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.ts b/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.tsindex 58f7c54e77e..380a230f28f 100644--- a/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.ts+++ b/apps/server/src/services/aiAgent/pipeline/codexDeviceRuntime.ts@@ -1,6 +1,7 @@import type { LobeChatDatabase } from '@lobechat/database';import { getCodexAppServerUnsupportedArgs } from '@lobechat/heterogeneous-agents/codexAppServerParams';import type { DeviceClient, LobeAgentAgencyConfig } from '@lobechat/types';+import { CODEX_COLLABORATION_MODE_RUNTIME } from '@lobechat/types';import debug from 'debug';import { UserModel } from '@/database/models/user';@@ -67,6 +68,8 @@ export type CodexDeviceRuntime =/** Extra `lh hetero exec` wrapper flags. */args: string[];kind: 'native';+ /** The `lh` also takes the Codex Plan switch (`codex-collaboration-mode-v1`). */+ supportsCollaborationMode: boolean;};export interface ResolveCodexDeviceRuntimeParams {@@ -117,7 +120,11 @@ export const resolveCodexDeviceRuntime = async (if (unsupported.length > 0) return { kind: 'exec' };const runtimes = await params.querySupportedRuntimes();if (!runtimes?.includes(CODEX_APP_SERVER_RUNTIME)) return { kind: 'exec' };- return { args: ['--codex-app-server'], kind: 'native' };+ return {+ args: ['--codex-app-server'],+ kind: 'native',+ supportsCollaborationMode: runtimes.includes(CODEX_COLLABORATION_MODE_RUNTIME),+ };};/** A {@link CodexDeviceRuntime} whose native variant names the connection to pin. */diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.tsnew file mode 100644index 00000000000..064f3fc27fa--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.ts@@ -0,0 +1,52 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { forDeviceRuntime, resolveDispatchCollaborationMode } from './codexCollaboration';++const preference = vi.hoisted(() => ({ lab: {} as Record<string, boolean> }));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function () {+ return { getUserPreference: vi.fn(async () => ({ lab: preference.lab })) };+ }),+}));++const resolve = (topicMetadata: Record<string, unknown> | undefined, heteroType = 'codex') =>+ resolveDispatchCollaborationMode({} as any, 'user-1', { heteroType, topicMetadata });++describe('resolveDispatchCollaborationMode', () => {+ beforeEach(() => {+ preference.lab = { enableBetterCodingExperience: true, enableCodexAppServer: true };+ });++ it('sends nothing for a topic that never turned Plan on, or another agent', async () => {+ await expect(resolve({})).resolves.toBeUndefined();+ await expect(resolve({ heteroPlanMode: true }, 'claude-code')).resolves.toBeUndefined();+ });++ it('sends the switch, off included, with both labs on', async () => {+ await expect(resolve({ heteroPlanMode: true })).resolves.toBe('plan');+ await expect(resolve({ heteroPlanMode: false })).resolves.toBe('default');+ });++ it('sends nothing with either lab off', async () => {+ for (const lab of [{ enableCodexAppServer: true }, { enableBetterCodingExperience: true }]) {+ preference.lab = lab;+ await expect(resolve({ heteroPlanMode: true })).resolves.toBeUndefined();+ }+ });+});++describe('forDeviceRuntime', () => {+ it('keeps the mode only for a native run on an lh that takes it', () => {+ expect(forDeviceRuntime('plan', { native: true, supportsCollaborationMode: true })).toBe(+ 'plan',+ );+ // An older lh, or `codex exec`, never receives it.+ expect(+ forDeviceRuntime('plan', { native: true, supportsCollaborationMode: false }),+ ).toBeUndefined();+ expect(+ forDeviceRuntime('plan', { native: false, supportsCollaborationMode: true }),+ ).toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.tsnew file mode 100644index 00000000000..dbd99cf772d--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.ts@@ -0,0 +1,43 @@+import type { ChatTopicMetadata, CodexCollaborationMode } from '@lobechat/types';+import { codexCollaborationModeOf } from '@lobechat/types';+import debug from 'debug';++import { UserModel } from '@/database/models/user';+import type { LobeChatDatabase } from '@/database/type';++const log = debug('lobe-server:hetero-dispatch:codex-collaboration');++/**+ * The collaboration mode a dispatched Codex run sends (Better Coding Experience+ * Plan switch), before the device's runtime is known: only with both labs on+ * (Better Coding Experience and the Codex app-server) and a topic that turned+ * Plan on at least once; otherwise none, exactly as before the lab. Codex keeps+ * the mode on the thread, so once used it is sent on every turn.+ *+ * A failed preference read sends no mode rather than guessing.+ */+export const resolveDispatchCollaborationMode = async (+ db: LobeChatDatabase,+ userId: string,+ params: { heteroType: string; topicMetadata: ChatTopicMetadata | null | undefined },+): Promise<CodexCollaborationMode | undefined> => {+ if (params.heteroType !== 'codex') return;+ const mode = codexCollaborationModeOf(params.topicMetadata?.heteroPlanMode);+ if (!mode) return;+ try {+ const lab = (await new UserModel(db, userId).getUserPreference())?.lab;+ return lab?.enableBetterCodingExperience && lab?.enableCodexAppServer ? mode : undefined;+ } catch (error) {+ log('Reading the lab preference of %s failed: %O', userId, error);+ }+};++/**+ * The mode a device run actually carries: only a native app-server run on an+ * `lh` that takes it (`codex-collaboration-mode-v1`); `codex exec` has none.+ */+export const forDeviceRuntime = (+ mode: CodexCollaborationMode | undefined,+ runtime: { native: boolean; supportsCollaborationMode: boolean },+): CodexCollaborationMode | undefined =>+ runtime.native && runtime.supportsCollaborationMode ? mode : undefined;diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.tsindex 3e6be7d2cb4..ea1fc3656b0 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts@@ -28,6 +28,7 @@ import { resolveDeviceWorkingDirectoryConfig } from '../../resolveDeviceWorkingDimport type { ExecRunContext } from '../../types';import { selectCodexDeviceDispatch } from '../codexDeviceRuntime';import { traceHeteroStage } from '../sendTracing';+import { forDeviceRuntime } from './codexCollaboration';import type { PreparedHeteroRun } from './prepare';import { scheduleTimedOutDispatchConfirmation } from './timeoutConfirmation';import type { HeteroDispatchDeps, HeteroDispatchInput, HeteroRun } from './types';@@ -190,6 +191,10 @@ export const dispatchToCliDevice = async ();}const nativeCodex = codexRuntime.kind === 'native' ? codexRuntime : undefined;+ const collaborationMode = forDeviceRuntime(heteroParams.collaborationMode, {+ native: !!nativeCodex,+ supportsCollaborationMode: !!nativeCodex?.supportsCollaborationMode,+ });// A turn the server starts on its own (a delegated task reporting back)// never passed the composer's restore step: bring back the worktree a@@ -310,6 +315,7 @@ export const dispatchToCliDevice = async (args: nativeCodex ? [...(heteroExecArgs ?? []), ...nativeCodex.args] : heteroExecArgs,...(claudeAccountRouting && { claudeAccountRouting }),clientKinds: nativeCodex?.clientKinds,+ collaborationMode,cwd: deviceCwd,deviceId: dispatchDeviceId,resumeFallbackSystemContext: deviceResumeFallbackSystemContext,diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex be00cbf5b92..001fffa7dd9 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -38,6 +38,7 @@ import { heteroOperationCapabilities } from '../heteroOperationCapabilities';import { buildHeteroProjectContext } from '../projectContext';import { traceHeteroStage } from '../sendTracing';import { buildViewedTaskContextPrompt, joinSystemContext } from '../viewedTaskContext';+import { resolveDispatchCollaborationMode } from './codexCollaboration';import { resolveDispatchPermissionMode } from './permissionMode';import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';import { settleInOrder } from './utils';@@ -208,6 +209,11 @@ export const prepareHeteroRun = async (return mode;});+ const collaborationModePromise = resolveDispatchCollaborationMode(deps.db, deps.userId, {+ heteroType,+ topicMetadata: topic?.metadata,+ });+// The primary resumed attempt already has native history and must not get// a serialized duplicate. A resumed session still needs the prompts of runs// stopped before the CLI recorded them; the history is withheld from it.@@ -395,6 +401,9 @@ export const prepareHeteroRun = async (heteroType === 'claude-code' && heterogeneousProvider?.type === heteroType? resolveDispatchedClaudeCodeEntrypoint(heterogeneousProvider.env): undefined,+ // The Codex Plan switch before the runtime is known; the device dispatch+ // narrows it (`forDeviceRuntime`), and the cloud sandbox (`codex exec`) ignores it.+ collaborationMode: await collaborationModePromise,githubToken,imageList: heteroImageList,jwt: operationJwt,diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.tsindex 1da97041089..e1578012a0d 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts@@ -96,6 +96,26 @@ describe('buildNewTopicMetadata — Claude Code permission mode', () => {});});+describe('buildNewTopicMetadata — Codex Plan switch', () => {+ it('is born with the switch the composer showed, off included', () => {+ for (const heteroPlanMode of [true, false]) {+ expect(+ buildNewTopicMetadata({+ appContext: { initialTopicMetadata: { heteroPlanMode } } as any,+ }),+ ).toMatchObject({ heteroPlanMode });+ }+ });++ it('records nothing when the composer showed no switch', () => {+ expect(+ buildNewTopicMetadata({+ appContext: { initialTopicMetadata: { workingDirectory: '/code/d' } } as any,+ }),+ ).not.toHaveProperty('heteroPlanMode');+ });+});+describe('sub-topic link (metadata.openedBy)', () => {it('records the opener read through the caller scope', async () => {const findById = vi.fn().mockResolvedValue({ agentId: 'agt_parent', id: 'tpc_parent' });diff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.tsindex e56fd9990ae..ce2409b8320 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts@@ -108,6 +108,11 @@ export const buildNewTopicMetadata = ({...(initialTopicMeta?.heteroPermissionMode && {heteroPermissionMode: initialTopicMeta.heteroPermissionMode,}),+ // Codex Plan switch the composer showed: `false` is a choice too (never+ // `&&`-dropped), while absent keeps a topic that sends no mode at all.+ ...(typeof initialTopicMeta?.heteroPlanMode === 'boolean' && {+ heteroPlanMode: initialTopicMeta.heteroPlanMode,+ }),...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),...pickSandboxPlacement(initialTopicMeta),...(initialTopicMeta?.workingDirectory && {diff --git a/apps/server/src/services/aiAgent/steerQueue/heteroCollaborationMode.ts b/apps/server/src/services/aiAgent/steerQueue/heteroCollaborationMode.tsnew file mode 100644index 00000000000..82de911db3b--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/heteroCollaborationMode.ts@@ -0,0 +1,34 @@+import type { CodexCollaborationMode } from '@lobechat/types';++import { sendHeteroControl } from './heteroControl';+import { type HeteroStopTaskResult, toHeteroStopTaskResult } from './heteroStopTask';++/** Command name the `lh` steer loop registers its Codex Plan handler under. */+export const HETERO_SET_COLLABORATION_MODE_COMMAND = 'set_collaboration_mode';++/** One local RPC on the device; the rest covers the steer poll. */+export const HETERO_SET_COLLABORATION_MODE_TIMEOUT_MS = 15_000;++/**+ * Switch the collaboration mode of a native Codex run hosted by `lh hetero+ * exec` (the composer's Plan switch, mid-run). Codex takes it from the next+ * turn. An `lh` without the handler answers `unsupported`; one that predates+ * control messages leaves it `unreachable`. Either way the topic keeps the+ * pick, and the next run sends it. The caller owns authorization.+ */+export const setHeteroCollaborationMode = async (+ operationId: string,+ mode: CodexCollaborationMode,+ options: { pollMs?: number; timeoutMs?: number } = {},+): Promise<HeteroStopTaskResult> => {+ const { state } = await sendHeteroControl(+ operationId,+ HETERO_SET_COLLABORATION_MODE_COMMAND,+ { mode },+ {+ pollMs: options.pollMs,+ timeoutMs: options.timeoutMs ?? HETERO_SET_COLLABORATION_MODE_TIMEOUT_MS,+ },+ );+ return toHeteroStopTaskResult(state);+};diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.tsindex f829e1fcd93..42c8c57275e 100644--- a/apps/server/src/services/deviceGateway/agents.ts+++ b/apps/server/src/services/deviceGateway/agents.ts@@ -19,6 +19,7 @@ import type {KimiCodeQuotaSnapshot,} from '@lobechat/heterogeneous-agents/quota';import type {+ CodexCollaborationMode,DeviceClient,DeviceUnavailableErrorData,HeterogeneousAgentModelCatalog,@@ -180,6 +181,8 @@ export async function dispatchAgentRun(claudeCodeEntrypoint?: string;/** Restricts the run to connections of these clients; omitted means any client. */clientKinds?: DeviceClient[];+ /** Codex Plan switch, forwarded into the `lh hetero exec` envelope. */+ collaborationMode?: CodexCollaborationMode;cwd?: string;deviceId?: string;/** Image attachments forwarded to the device as fetchable (signed) URLs. */diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.collaborationMode.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.collaborationMode.test.tsnew file mode 100644index 00000000000..d453f85b280--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.collaborationMode.test.ts@@ -0,0 +1,49 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { __resetOperationStatesForTesting } from '.';+import { buildEvent, createHarness } from './testUtils';++const OP = 'op-1';+const TOPIC = 'topic-1';++describe('HeterogeneousPersistenceHandler — Codex Plan switch', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ it('writes nothing for a read-back that confirms the request', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });++ await h.handler.ingest({+ events: [+ buildEvent('step_complete', 0, {+ collaborationMode: 'plan',+ phase: 'collaboration_mode',+ requested: 'plan',+ }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });++ expect(h.topicModel.updateMetadata).not.toHaveBeenCalled();+ });++ it('follows Codex when it disagrees with what the run asked for', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });++ await h.handler.ingest({+ events: [+ buildEvent('step_complete', 0, {+ collaborationMode: 'default',+ phase: 'collaboration_mode',+ requested: 'plan',+ }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });++ expect(h.topicModel.updateMetadata).toHaveBeenCalledWith(TOPIC, { heteroPlanMode: false });+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.tsindex 3bfdaaec09f..a8b75e9834b 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts@@ -9,6 +9,10 @@ import {isPermissionModeReport,permissionModeReportPatch,} from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';+import {+ collaborationModeReportPatch,+ isCollaborationModeReport,+} from '@lobechat/heterogeneous-agents/codexPlanMode';import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';import { createNanoId } from '@lobechat/utils';@@ -364,6 +368,15 @@ export class HeterogeneousPersistenceHandler {});return;}+ // Codex Plan switch: a thread back in `default` clears the pending reset;+ // the switch follows Codex only where Codex disagrees with the request.+ if (event.type === 'step_complete' && isCollaborationModeReport(event.data)) {+ const patch = collaborationModeReportPatch(event.data);+ if (Object.keys(patch).length > 0) {+ await this.deps.topicModel.updateMetadata(state.topicId, patch);+ }+ return;+ }await this.reduceAndApply(state, event);}diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b15042e23b6..74b7e70cfa3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1718,6 +1718,13 @@"heteroAgent.permissionMode.switchPendingNotice": "This run is still in “{{running}}”: the session couldn’t switch. “{{next}}” applies from the next message.","heteroAgent.permissionMode.switchUnsupported": "lh on this device can’t switch a running session. The new mode applies from the next message; update lh to switch mid-run.","heteroAgent.permissionMode.tooltip": "How Claude Code asks before acting. Applies to this topic; a new topic in this directory starts with your last pick.",+ "heteroAgent.planMode.label": "Plan",+ "heteroAgent.planMode.nextTurn": "Applies from the next turn",+ "heteroAgent.planMode.saveFailed": "Couldn’t save the Plan setting. Try again.",+ "heteroAgent.planMode.tooltipOff": "Plan first: Codex explores and proposes a plan instead of making changes. Codex still has full access. A new topic in this directory starts with your last choice.",+ "heteroAgent.planMode.tooltipOn": "Plan is on: Codex proposes a plan instead of making changes. Turn it off, or choose Execute plan, to let it carry the plan out.",+ "heteroAgent.planMode.unavailable.appServerLab": "Plan needs the Codex App Server Runtime. Turn it on in Settings → Labs.",+ "heteroAgent.planMode.unavailable.unsupported": "Plan isn’t available where this agent runs: it needs Codex app-server on this computer, or a device whose Codex and lh support it. Update lh on the device to use it.","heteroAgent.quota.compactLeft": "{{percent}}%","heteroAgent.quota.duration.day_one": "{{count}}d","heteroAgent.quota.duration.day_other": "{{count}}d",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex a237b6ff0b7..a50fc9d3d62 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -67,6 +67,7 @@"builtins.codex.apiName.file_change": "Edit files","builtins.codex.apiName.image_output": "Image result","builtins.codex.apiName.mcp_tool_call": "Call MCP tool",+ "builtins.codex.apiName.proposed_plan": "Plan","builtins.codex.apiName.todo_list": "Update tasks","builtins.codex.apiName.web_search": "Search the web","builtins.codex.collabTool.agentCount_one": "{{count}} subagent",@@ -96,6 +97,10 @@"builtins.codex.mcpTool.input": "Input","builtins.codex.mcpTool.result": "Result","builtins.codex.mcpTool.unknownTool": "MCP tool",+ "builtins.codex.proposedPlan.discuss": "Keep discussing",+ "builtins.codex.proposedPlan.execute": "Execute plan",+ "builtins.codex.proposedPlan.executeMessage": "Execute the plan above.",+ "builtins.codex.proposedPlan.failed": "Couldn’t do that. Try again.","builtins.codex.webSearch.query": "Query","builtins.devin.apiName.askUserQuestion": "Ask a question","builtins.devin.apiName.edit": "Edit file",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 664c0958f4a..b3a7819d84d 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1718,6 +1718,13 @@"heteroAgent.permissionMode.switchPendingNotice": "这次运行仍是「{{running}}」:会话没能切换。「{{next}}」从下一条消息开始生效。","heteroAgent.permissionMode.switchUnsupported": "这台设备上的 lh 不支持运行中切换,新模式会从下一条消息开始生效。升级 lh 后可在运行中切换。","heteroAgent.permissionMode.tooltip": "Claude Code 在执行操作前是否询问你。只对当前话题生效;在这个目录里新建话题时,会沿用你上次的选择。",+ "heteroAgent.planMode.label": "计划",+ "heteroAgent.planMode.nextTurn": "下一轮生效",+ "heteroAgent.planMode.saveFailed": "计划设置没能保存,请重试。",+ "heteroAgent.planMode.tooltipOff": "先出计划:Codex 会先了解情况并给出计划,不直接改动。Codex 仍有完全访问权限。在这个目录里新建话题时,会沿用你上次的选择。",+ "heteroAgent.planMode.tooltipOn": "计划已开启:Codex 会给出计划,不直接改动。关掉它,或点「执行计划」,Codex 才会按计划去做。",+ "heteroAgent.planMode.unavailable.appServerLab": "计划需要 Codex App Server 运行时。请在「设置 → 实验室」里打开它。",+ "heteroAgent.planMode.unavailable.unsupported": "这个 Agent 运行的地方用不了计划:需要本机的 Codex app-server,或设备上的 Codex 和 lh 支持它。在设备上更新 lh 后即可使用。","heteroAgent.quota.compactLeft": "{{percent}}%","heteroAgent.quota.duration.day_one": "{{count}}天","heteroAgent.quota.duration.day_other": "{{count}}天",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex cfb9eb91852..1b138d0faa2 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -67,6 +67,7 @@"builtins.codex.apiName.file_change": "编辑文件","builtins.codex.apiName.image_output": "图片结果","builtins.codex.apiName.mcp_tool_call": "调用 MCP 工具",+ "builtins.codex.apiName.proposed_plan": "计划","builtins.codex.apiName.todo_list": "更新任务","builtins.codex.apiName.web_search": "搜索网页","builtins.codex.collabTool.agentCount_one": "{{count}} 个子代理",@@ -96,6 +97,10 @@"builtins.codex.mcpTool.input": "输入","builtins.codex.mcpTool.result": "结果","builtins.codex.mcpTool.unknownTool": "MCP 工具",+ "builtins.codex.proposedPlan.discuss": "继续讨论",+ "builtins.codex.proposedPlan.execute": "执行计划",+ "builtins.codex.proposedPlan.executeMessage": "按上面的计划执行。",+ "builtins.codex.proposedPlan.failed": "操作没有完成,请重试。","builtins.codex.webSearch.query": "搜索词","builtins.devin.apiName.askUserQuestion": "向你提问","builtins.devin.apiName.edit": "编辑文件",diff --git a/packages/builtin-tools/src/codex/ProposedPlanDecision.tsx b/packages/builtin-tools/src/codex/ProposedPlanDecision.tsxnew file mode 100644index 00000000000..9d53f48b3cd--- /dev/null+++ b/packages/builtin-tools/src/codex/ProposedPlanDecision.tsx@@ -0,0 +1,108 @@+'use client';++import { Button, Flexbox, toast } from '@lobehub/ui';+import { ListChecks } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useConversationStore } from '@/features/Conversation/store';+import { useChatStore } from '@/store/chat';+import {+ dismissCodexPlan,+ executeCodexPlan,+ shouldShowCodexPlanDecision,+} from '@/store/chat/heteroPlanMode';+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';++interface ProposedPlanDecisionProps {+ messageId: string;+ toolCallId?: string;+}++/**+ * "Execute plan / Keep discussing" under the latest Codex plan. Codex's plan+ * turn already ended, so these only decide what the next message is:+ * executing turns Plan off and asks Codex to carry the plan out; discussing+ * just puts the buttons away (Plan stays on).+ */+const ProposedPlanDecision = ({ toolCallId }: ProposedPlanDecisionProps) => {+ const { t } = useTranslation('plugin');+ const [context, messages, sendMessage] = useConversationStore((s) => [+ s.context,+ s.dbMessages,+ s.sendMessage,+ ]);+ const topicId = context.topicId;+ const metadata = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,+ );+ const liveRun = useChatStore(operationSelectors.isAgentRuntimeRunningByContext(context));+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);+ const [busy, setBusy] = useState<'discuss' | 'execute'>();++ if (+ !topicId ||+ !shouldShowCodexPlanDecision({+ messages,+ metadata,+ running: liveRun || !!metadata?.runningOperation,+ toolCallId,+ })+ ) {+ return null;+ }+ const deps = { toolCallId: toolCallId!, topicId, updateTopicMetadata };++ const execute = async () => {+ setBusy('execute');+ try {+ await executeCodexPlan({+ ...deps,+ message: t('builtins.codex.proposedPlan.executeMessage'),+ sendMessage,+ });+ } catch (error) {+ console.error('[ProposedPlanDecision] execute failed', error);+ toast.error(t('builtins.codex.proposedPlan.failed'));+ } finally {+ setBusy(undefined);+ }+ };++ const discuss = async () => {+ setBusy('discuss');+ try {+ await dismissCodexPlan(deps);+ } catch (error) {+ console.error('[ProposedPlanDecision] dismiss failed', error);+ toast.error(t('builtins.codex.proposedPlan.failed'));+ } finally {+ setBusy(undefined);+ }+ };++ return (+ <Flexbox horizontal data-testid={'codex-plan-decision'} gap={8} paddingBlock={8}>+ <Button+ disabled={!!busy}+ icon={ListChecks}+ loading={busy === 'execute'}+ size={'small'}+ type={'primary'}+ onClick={() => void execute()}+ >+ {t('builtins.codex.proposedPlan.execute')}+ </Button>+ <Button+ disabled={!!busy}+ loading={busy === 'discuss'}+ size={'small'}+ onClick={() => void discuss()}+ >+ {t('builtins.codex.proposedPlan.discuss')}+ </Button>+ </Flexbox>+ );+};++export default ProposedPlanDecision;diff --git a/packages/builtin-tools/src/codex/ProposedPlanInspector.tsx b/packages/builtin-tools/src/codex/ProposedPlanInspector.tsxnew file mode 100644index 00000000000..0434901b178--- /dev/null+++ b/packages/builtin-tools/src/codex/ProposedPlanInspector.tsx@@ -0,0 +1,25 @@+'use client';++import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';+import type { BuiltinInspectorProps } from '@lobechat/types';+import { cx } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const ProposedPlanInspector = memo<BuiltinInspectorProps>(({ isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');+ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ {t('builtins.codex.apiName.proposed_plan', { defaultValue: 'Plan' })}+ </div>+ );+});++ProposedPlanInspector.displayName = 'CodexProposedPlanInspector';++export default ProposedPlanInspector;diff --git a/packages/builtin-tools/src/codex/ProposedPlanRender.tsx b/packages/builtin-tools/src/codex/ProposedPlanRender.tsxnew file mode 100644index 00000000000..e4104539024--- /dev/null+++ b/packages/builtin-tools/src/codex/ProposedPlanRender.tsx@@ -0,0 +1,53 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { Markdown } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++import ProposedPlanDecision from './ProposedPlanDecision';++/** Plugin state of a `proposed_plan` tool message (see `codexPlanMode` in heterogeneous-agents). */+export interface CodexProposedPlanState {+ plan?: { completed?: boolean; text?: string };+}++const styles = stylex.create({+ plan: {+ paddingBlock: '4px',+ paddingInline: '12px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ },+});++/**+ * A plan Codex proposed in plan mode. `item/plan/delta` streams the text; the+ * completed plan item (the tool result) is the plan of record. The latest+ * plan offers to carry it out or keep discussing.+ */+const ProposedPlanRender = memo<BuiltinRenderProps<unknown, CodexProposedPlanState, string>>(+ ({ content, messageId, pluginState, toolCallId }) => {+ const completed = pluginState?.plan?.completed === true || !!content;+ const text = (completed && content) || pluginState?.plan?.text || '';+ if (!text) return null;++ return (+ <>+ <div data-testid={'codex-proposed-plan'} {...stylex.props(styles.plan)}>+ <Markdown animated={!completed} variant={'chat'}>+ {text}+ </Markdown>+ </div>+ {completed && <ProposedPlanDecision messageId={messageId} toolCallId={toolCallId} />}+ </>+ );+ },+);++ProposedPlanRender.displayName = 'CodexProposedPlanRender';++export default ProposedPlanRender;diff --git a/packages/builtin-tools/src/codex/displayControls.ts b/packages/builtin-tools/src/codex/displayControls.tsindex 5c653216cb6..63b9a638539 100644--- a/packages/builtin-tools/src/codex/displayControls.ts+++ b/packages/builtin-tools/src/codex/displayControls.ts@@ -6,6 +6,7 @@ export const CodexRenderDisplayControls: Record<string, RenderDisplayControl> =file_change: 'collapsed',image_output: 'expand',mcp_tool_call: 'collapsed',+ proposed_plan: 'expand',todo_list: 'expand',web_search: 'collapsed',};diff --git a/packages/builtin-tools/src/codex/index.ts b/packages/builtin-tools/src/codex/index.tsindex d1e3aac26be..2db0b19fe8b 100644--- a/packages/builtin-tools/src/codex/index.ts+++ b/packages/builtin-tools/src/codex/index.ts@@ -11,6 +11,8 @@ import { ImageOutputInspector } from './ImageOutputInspector';import { ImageOutputRender } from './ImageOutputRender';import McpToolInspector from './McpToolInspector';import McpToolRender from './McpToolRender';+import ProposedPlanInspector from './ProposedPlanInspector';+import ProposedPlanRender from './ProposedPlanRender';import TodoListInspector from './TodoListInspector';import TodoListRender from './TodoListRender';import WebSearchInspector from './WebSearchInspector';@@ -23,6 +25,7 @@ export const CodexInspectors: Record<string, BuiltinInspector> = {file_change: FileChangeInspector as BuiltinInspector,image_output: ImageOutputInspector as BuiltinInspector,mcp_tool_call: McpToolInspector as BuiltinInspector,+ proposed_plan: ProposedPlanInspector as BuiltinInspector,todo_list: TodoListInspector as BuiltinInspector,web_search: WebSearchInspector as BuiltinInspector,};@@ -32,6 +35,7 @@ export const CodexRenders: Record<string, BuiltinRender> = {file_change: FileChangeRender as BuiltinRender,image_output: ImageOutputRender as BuiltinRender,mcp_tool_call: McpToolRender as BuiltinRender,+ proposed_plan: ProposedPlanRender as BuiltinRender,todo_list: TodoListRender as BuiltinRender,web_search: WebSearchRender as BuiltinRender,};diff --git a/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.ts b/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.tsindex 8e90ec68dbb..c01751dcc95 100644--- a/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.ts+++ b/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.ts@@ -61,3 +61,27 @@ describe('WorkspaceUserSettingsModel.setHeteroPermissionModeDir', () => {});});});++describe('setHeteroPlanModeDir (Codex Plan switch)', () => {+ it('keeps only directories left on, latest first, in the personal bucket', async () => {+ const model = new UserModel(serverDB, userId);+ await model.setHeteroPlanModeDir('d::/a', true);+ expect(await model.setHeteroPlanModeDir('d::/b', true)).toEqual(['d::/b', 'd::/a']);+ expect(await model.setHeteroPlanModeDir('d::/b', false)).toEqual(['d::/a']);+ const user = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });+ expect(user?.preference).toMatchObject({+ heteroPlanModeDirs: ['d::/a'],+ topicGroupMode: 'byTime',+ });+ });++ it('keeps the member list beside the other directory habits', async () => {+ const model = new WorkspaceUserSettingsModel(serverDB, userId, workspaceId);+ await model.setWorktreeModeDir('d::/a', true);+ expect(await model.setHeteroPlanModeDir('d::/a', true)).toEqual(['d::/a']);+ expect(await model.getPreference()).toMatchObject({+ heteroPlanModeDirs: ['d::/a'],+ worktreeModeDirs: ['d::/a'],+ });+ });+});diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex 7c291f42881..539d4a1893f 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -12,7 +12,11 @@ import type {UserSettings,WidgetDryRunGrant,} from '@lobechat/types';-import { applyHeteroPermissionModeDir, applyWorktreeModeDir } from '@lobechat/types';+import {+ applyHeteroPermissionModeDir,+ applyHeteroPlanModeDir,+ applyWorktreeModeDir,+} from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import { TRPCError } from '@trpc/server';import dayjs from 'dayjs';@@ -593,6 +597,16 @@ export class UserModel {return { next: { ...prev, worktreeModeDirs }, result: worktreeModeDirs };})) ?? [];+ /**+ * Personal-mode Codex Plan switch remembered for one directory; returns the+ * stored list, capped here like the worktree switch.+ */+ setHeteroPlanModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ (await this.mutatePreference((prev) => {+ const heteroPlanModeDirs = applyHeteroPlanModeDir(prev.heteroPlanModeDirs, key, enabled);+ return { next: { ...prev, heteroPlanModeDirs }, result: heteroPlanModeDirs };+ })) ?? [];+/*** Personal-mode Claude Code permission mode remembered for one directory;* returns the stored list. The cap is applied here (`applyHeteroPermissionModeDir`).diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.tsindex aeda33e4fbc..3a44168072c 100644--- a/packages/database/src/models/workspaceUserSettings.ts+++ b/packages/database/src/models/workspaceUserSettings.ts@@ -3,7 +3,11 @@ import type {HeteroPermissionModeDir,WorkspaceUserPreference,} from '@lobechat/types';-import { applyHeteroPermissionModeDir, applyWorktreeModeDir } from '@lobechat/types';+import {+ applyHeteroPermissionModeDir,+ applyHeteroPlanModeDir,+ applyWorktreeModeDir,+} from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import { and, eq } from 'drizzle-orm';@@ -166,6 +170,16 @@ export class WorkspaceUserSettingsModel {return { next: { ...current, worktreeModeDirs }, result: worktreeModeDirs };});+ /**+ * Remember whether this member left the Codex Plan switch on for one+ * directory and return the stored list (capped here, like the worktree switch).+ */+ setHeteroPlanModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ this.mutatePreference((current) => {+ const heteroPlanModeDirs = applyHeteroPlanModeDir(current.heteroPlanModeDirs, key, enabled);+ return { next: { ...current, heteroPlanModeDirs }, result: heteroPlanModeDirs };+ });+/*** Remember the Claude Code permission mode this member picked for one* directory and return the stored list (capped here, like the worktree switch).diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex a735e748405..cc0b59d8709 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -1,4 +1,9 @@-import type { DeviceClient, DeviceMetricSample, HeteroPermissionMode } from '@lobechat/types';+import type {+ CodexCollaborationMode,+ DeviceClient,+ DeviceMetricSample,+ HeteroPermissionMode,+} from '@lobechat/types';import {describeGatewayRequestFailure,@@ -333,6 +338,8 @@ export class GatewayHttpClient {claudeCodeEntrypoint?: string;/** Restricts the run to connections of these clients; omitted means any client. */clientKinds?: DeviceClient[];+ /** Codex Plan switch; see `AgentRunRequestMessage.collaborationMode`. */+ collaborationMode?: CodexCollaborationMode;cwd?: string;deviceId?: string;/** Image attachments forwarded into the `agent_run_request` message. */diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 41c6222b686..20f440c0626 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -1,4 +1,8 @@-import type { DeviceMetricSample, HeteroPermissionMode } from '@lobechat/types';+import type {+ CodexCollaborationMode,+ DeviceMetricSample,+ HeteroPermissionMode,+} from '@lobechat/types';// ─── Device Info ───@@ -345,6 +349,11 @@ export interface AgentRunRequestMessage {* set it; an older device ignores it.*/claudeCodeEntrypoint?: string;+ /**+ * Codex Plan switch (Better Coding Experience lab), forwarded into the same+ * envelope. Sent only to a device advertising `codex-collaboration-mode-v1`.+ */+ collaborationMode?: CodexCollaborationMode;cwd?: string;/*** Image attachments from the user message, as URLs the device can fetchdiff --git a/packages/heterogeneous-agents/browser-entries.json b/packages/heterogeneous-agents/browser-entries.jsonindex 94d4c667042..2ef2b273fef 100644--- a/packages/heterogeneous-agents/browser-entries.json+++ b/packages/heterogeneous-agents/browser-entries.json@@ -1 +1,9 @@-[".", "./claudeCodePermission/shared", "./client", "./errors", "./quota"]+[+ ".",+ "./claudeCodePermission/shared",+ "./client",+ "./codexAppServerArgs",+ "./codexPlanMode",+ "./errors",+ "./quota"+]diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 64212fdf36c..1a0bf32d7e7 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -11,7 +11,9 @@"./claudeCodePermission/shared": "./src/claudeCodePermission/shared.ts","./errors": "./src/errors/index.ts","./client": "./src/client/index.ts",+ "./codexAppServerArgs": "./src/codex/appServerArgs.ts","./codexAppServerParams": "./src/codex/appServerParams.ts",+ "./codexPlanMode": "./src/codexPlanMode/index.ts","./models": "./src/models/index.ts","./processFailure": "./src/spawn/classifyProcessFailure.ts","./protocol": "./src/protocol/index.ts",diff --git a/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-plan-turn.jsonl b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-plan-turn.jsonlnew file mode 100644index 00000000000..d19f2e01336--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/__fixtures__/codex/app-server-plan-turn.jsonl@@ -0,0 +1,82 @@+{"method": "thread/settings/updated", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "threadSettings": {"collaborationMode": {"mode": "plan", "settings": {"developer_instructions": null, "model": "gpt-6.1-sol", "reasoning_effort": "low"}}}}, "emittedAtMs": 1795386252879}+{"method": "turn/started", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turn": {"id": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "rootTurnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "items": [], "itemsView": "notLoaded", "status": "inProgress", "error": null, "startedAt": 1795386252, "completedAt": null, "durationMs": null}}, "emittedAtMs": 1795386253499}+{"method": "item/started", "params": {"item": {"type": "userMessage", "id": "01a2055c-47b1-7fe1-be00-1febf9c0e669", "clientId": null, "content": [{"type": "text", "text": "Plan how to add a file hello.txt containing \"hi\" to this directory. Do not ask me questions; the plan should have 2 steps.", "text_elements": []}], "startedAtMs": 1795386263628, "completedAtMs": null}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "startedAtMs": 1795386263628}, "emittedAtMs": 1795386263628}+{"method": "item/completed", "params": {"item": {"type": "userMessage", "id": "01a2055c-47b1-7fe1-be00-1febf9c0e669", "clientId": null, "content": [{"type": "text", "text": "Plan how to add a file hello.txt containing \"hi\" to this directory. Do not ask me questions; the plan should have 2 steps.", "text_elements": []}], "startedAtMs": 1795386263628, "completedAtMs": 1795386263628}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "contentTokenCount": null, "completedAtMs": 1795386263628}, "emittedAtMs": 1795386263663}+{"method": "item/started", "params": {"item": {"type": "reasoning", "id": "rs_00b93f0eb1d00b46016b036b9c407487d0b64883c29d0e7c7a", "summary": [], "content": [], "startedAtMs": 1795386268377, "completedAtMs": null}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "startedAtMs": 1795386268377}, "emittedAtMs": 1795386268377}+{"method": "item/completed", "params": {"item": {"type": "reasoning", "id": "rs_00b93f0eb1d00b46016b036b9c407487d0b64883c29d0e7c7a", "summary": [], "content": [], "startedAtMs": 1795386268377, "completedAtMs": 1795386268377}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "contentTokenCount": null, "completedAtMs": 1795386268377}, "emittedAtMs": 1795386268460}+{"method": "item/started", "params": {"item": {"type": "agentMessage", "moderation": null, "id": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "text": "", "phase": "commentary", "memoryCitation": null, "delivery": null, "questions": null, "startedAtMs": 1795386268616, "completedAtMs": null}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "startedAtMs": 1795386268616}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "I"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "’ll"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " check"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " whether"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " `"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "hello"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": ".txt"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "`"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " already"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " exists"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": ","}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " then"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " give"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " a"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " two"}, "emittedAtMs": 1795386268616}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "-step"}, "emittedAtMs": 1795386268617}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": " plan"}, "emittedAtMs": 1795386268818}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": ".\n"}, "emittedAtMs": 1795386268818}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "Z"}, "emittedAtMs": 1795386268818}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "EB"}, "emittedAtMs": 1795386268818}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "RA"}, "emittedAtMs": 1795386268818}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "-"}, "emittedAtMs": 1795386268818}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "delta": "42"}, "emittedAtMs": 1795386268818}+{"method": "item/completed", "params": {"item": {"type": "agentMessage", "moderation": null, "id": "msg_00b93f0eb1d00b46016b036b9c406887d09740ab326d919212", "text": "I’ll check whether `hello.txt` already exists, then give a two-step plan.\nZEBRA-42", "phase": "commentary", "memoryCitation": null, "delivery": null, "questions": null, "startedAtMs": 1795386268616, "completedAtMs": 1795386269086}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "contentTokenCount": 24, "completedAtMs": 1795386269086}, "emittedAtMs": 1795386269169}+{"method": "item/started", "params": {"item": {"type": "commandExecution", "id": "exec-4beff22f-c139-45b5-8b86-403e58a666d8", "pluginId": null, "scriptPath": null, "command": "/bin/zsh -lc \"pwd && if [ -e hello.txt ]; then ls -l hello.txt; cat hello.txt; else test -d . && test -w . && echo 'Directory is writable; hello.txt does not exist'; fi\"", "cwd": "/repo", "processId": "31851", "source": "unifiedExecStartup", "status": "inProgress", "commandActions": [{"type": "unknown", "command": "pwd && if [ -e hello.txt ]; then ls -l hello.txt; cat hello.txt; else test -d . && test -w . && echo 'Directory is writable; hello.txt does not exist'; fi"}], "aggregatedOutput": "", "exitCode": null, "durationMs": null, "startedAtMs": 1795386276501, "completedAtMs": null}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "startedAtMs": 1795386276501}, "emittedAtMs": 1795386276502}+{"method": "item/completed", "params": {"item": {"type": "commandExecution", "id": "exec-4beff22f-c139-45b5-8b86-403e58a666d8", "pluginId": null, "scriptPath": null, "command": "/bin/zsh -lc \"pwd && if [ -e hello.txt ]; then ls -l hello.txt; cat hello.txt; else test -d . && test -w . && echo 'Directory is writable; hello.txt does not exist'; fi\"", "cwd": "/repo", "processId": "31851", "source": "unifiedExecStartup", "status": "completed", "commandActions": [{"type": "unknown", "command": "pwd && if [ -e hello.txt ]; then ls -l hello.txt; cat hello.txt; else test -d . && test -w . && echo 'Directory is writable; hello.txt does not exist'; fi"}], "aggregatedOutput": "/repo\nDirectory is writable; hello.txt does not exist\n", "exitCode": 0, "durationMs": 17, "startedAtMs": 1795386276501, "completedAtMs": 1795386276518}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "contentTokenCount": null, "completedAtMs": 1795386276518}, "emittedAtMs": 1795386276587}+{"method": "item/started", "params": {"item": {"type": "plan", "id": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "text": "", "startedAtMs": 1795386279591, "completedAtMs": null}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "startedAtMs": 1795386279591}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "1"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "."}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " Create"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " `"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "hello"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": ".txt"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "`"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " in"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " the"}, "emittedAtMs": 1795386279591}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " current"}, "emittedAtMs": 1795386279990}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " directory"}, "emittedAtMs": 1795386279990}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " using"}, "emittedAtMs": 1795386279990}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " `"}, "emittedAtMs": 1795386279990}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "printf"}, "emittedAtMs": 1795386280000}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " '"}, "emittedAtMs": 1795386280000}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "hi"}, "emittedAtMs": 1795386280000}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "'"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " >"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " hello"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": ".txt"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "`.\n"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "2"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "."}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " Verify"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " that"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " `"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "hello"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": ".txt"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "`"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " contains"}, "emittedAtMs": 1795386280010}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " exactly"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " `"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "hi"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": "`"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " with"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " no"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " trailing"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": " newline"}, "emittedAtMs": 1795386280258}+{"method": "item/plan/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "delta": ".\n"}, "emittedAtMs": 1795386280400}+{"method": "item/started", "params": {"item": {"type": "agentMessage", "moderation": null, "id": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "text": "", "phase": "final_answer", "memoryCitation": null, "delivery": null, "questions": null, "startedAtMs": 1795386280400, "completedAtMs": null}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "startedAtMs": 1795386280400}, "emittedAtMs": 1795386280400}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "delta": "Z"}, "emittedAtMs": 1795386280400}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "delta": "EB"}, "emittedAtMs": 1795386280400}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "delta": "RA"}, "emittedAtMs": 1795386280400}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "delta": "-"}, "emittedAtMs": 1795386280400}+{"method": "item/agentMessage/delta", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "itemId": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "delta": "42"}, "emittedAtMs": 1795386280400}+{"method": "item/completed", "params": {"item": {"type": "plan", "id": "01a2055b-fe95-7b00-9f9a-a872bc489c22-plan", "text": "1. Create `hello.txt` in the current directory using `printf 'hi' > hello.txt`.\n2. Verify that `hello.txt` contains exactly `hi` with no trailing newline.\n", "startedAtMs": 1795386279591, "completedAtMs": 1795386280517}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "contentTokenCount": null, "completedAtMs": 1795386280517}, "emittedAtMs": 1795386280846}+{"method": "item/completed", "params": {"item": {"type": "agentMessage", "moderation": null, "id": "msg_00b93f0eb1d00b46016b036ba779c087d0b5f7b23e0a48150d", "text": "ZEBRA-42", "phase": "final_answer", "memoryCitation": null, "delivery": null, "questions": null, "startedAtMs": 1795386280400, "completedAtMs": 1795386280846}, "threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "contentTokenCount": 55, "completedAtMs": 1795386280846}, "emittedAtMs": 1795386281034}+{"method": "turn/completed", "params": {"threadId": "01a2055b-deed-7ae1-99c9-6f12e57239dd", "turn": {"id": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "rootTurnId": "01a2055b-fe95-7b00-9f9a-a872bc489c22", "items": [], "itemsView": "summary", "status": "completed", "error": null, "startedAt": 1795386252, "completedAt": 1795386281, "durationMs": 28743}}, "emittedAtMs": 1795386281751}diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.plan.test.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.plan.test.tsnew file mode 100644index 00000000000..2a2e114dc54--- /dev/null+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.plan.test.ts@@ -0,0 +1,106 @@+import { readFile } from 'node:fs/promises';++import { describe, expect, it } from 'vitest';++import { CODEX_PROPOSED_PLAN_API_NAME } from '../codexPlanMode';+import { CodexAppServerAdapter } from './codexAppServer';++/**+ * One plan-mode turn recorded from codex-cli 0.169.0 (`turn/start` with+ * `collaborationMode: plan`): an agent message, a read-only command, then the+ * plan item, with the closing agent message interleaved between the plan's+ * `item/started` and `item/completed`.+ */+const loadPlanTurn = async () =>+ (+ await readFile(+ new URL('./__fixtures__/codex/app-server-plan-turn.jsonl', import.meta.url),+ 'utf8',+ )+ )+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line) as { method: string; params: any });++describe('CodexAppServerAdapter — plan-mode plans', () => {+ it('streams the plan as a proposed_plan tool and records the completed item as its result', async () => {+ const notifications = await loadPlanTurn();+ const completedPlan = notifications.find(+ (n) => n.method === 'item/completed' && n.params.item.type === 'plan',+ )!.params.item;+ const adapter = new CodexAppServerAdapter({ sessionId: 'thread-1' });+ const events = notifications.flatMap(({ method, params }) => adapter.adapt(method, params));++ const toolsCalling = events.filter(+ (e) => e.type === 'stream_chunk' && (e.data as any).chunkType === 'tools_calling',+ );+ expect(+ toolsCalling.some((e) =>+ (e.data as any).toolsCalling.some(+ (tool: any) =>+ tool.apiName === CODEX_PROPOSED_PLAN_API_NAME &&+ tool.id === completedPlan.id &&+ tool.identifier === 'codex',+ ),+ ),+ ).toBe(true);++ // Deltas only stream a draft; the completed item is the plan of record.+ const drafts = events.filter(+ (e) =>+ e.type === 'stream_chunk' &&+ (e.data as any).chunkType === 'tool_state' &&+ (e.data as any).toolCallId === completedPlan.id,+ );+ expect(drafts.length).toBeGreaterThan(0);+ expect((drafts.at(-1)!.data as any).pluginState.plan.completed).toBe(false);++ const result = events.find(+ (e) => e.type === 'tool_result' && (e.data as any).toolCallId === completedPlan.id,+ );+ expect(result?.data).toMatchObject({+ content: completedPlan.text,+ pluginState: { plan: { completed: true, text: completedPlan.text } },+ });+ const end = events.find(+ (e) => e.type === 'tool_end' && (e.data as any).toolCallId === completedPlan.id,+ );+ expect(end?.data).toMatchObject({ isSuccess: true });++ // The plan ends before the turn does, and the turn still ends normally.+ const resultIndex = events.indexOf(result!);+ const runtimeEnd = events.findIndex((e) => e.type === 'agent_runtime_end');+ expect(resultIndex).toBeLessThan(runtimeEnd);+ expect(events[runtimeEnd].data).toEqual({});+ // The plan text is not duplicated into the reply text.+ const text = events+ .filter((e) => e.type === 'stream_chunk' && (e.data as any).chunkType === 'text')+ .map((e) => (e.data as any).content)+ .join('');+ expect(text).not.toContain(completedPlan.text.trim());+ });++ it('does not report an unfinished plan as a result when the turn is interrupted', () => {+ const adapter = new CodexAppServerAdapter({ sessionId: 'thread-1' });+ adapter.adapt('turn/started', { threadId: 'thread-1', turn: { id: 'turn-1' } });+ adapter.adapt('item/started', {+ item: { id: 'plan-1', text: '', type: 'plan' },+ threadId: 'thread-1',+ turnId: 'turn-1',+ });+ adapter.adapt('item/plan/delta', { delta: '1. half', itemId: 'plan-1', turnId: 'turn-1' });++ const events = adapter.adapt('turn/completed', {+ threadId: 'thread-1',+ turn: { error: null, id: 'turn-1', status: 'interrupted' },+ });++ expect(events.some((e) => e.type === 'tool_result')).toBe(false);+ expect(events).toContainEqual(+ expect.objectContaining({+ data: { isSuccess: false, toolCallId: 'plan-1' },+ type: 'tool_end',+ }),+ );+ });+});diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.tsindex dd6845bd744..b332053f85a 100644--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts@@ -21,6 +21,8 @@ import type {TurnPlanUpdatedNotification,TurnStartedNotification,} from '../codex/protocol';+import type { PlanDeltaNotification } from '../codex/protocol/experimental/v2/PlanDeltaNotification';+import { CODEX_PROPOSED_PLAN_API_NAME, type CodexProposedPlanState } from '../codexPlanMode';import type { HeteroErrorKind } from '../errors/specs';import type {HeterogeneousAgentEvent,@@ -49,6 +51,7 @@ type McpToolItem = Extract<ThreadItem, { type: 'mcpToolCall' }>;type DynamicToolItem = Extract<ThreadItem, { type: 'dynamicToolCall' }>;type CollabToolItem = Extract<ThreadItem, { type: 'collabAgentToolCall' }>;type WebSearchItem = Extract<ThreadItem, { type: 'webSearch' }>;+type PlanItem = Extract<ThreadItem, { type: 'plan' }>;type ToolItem =CollabToolItem | CommandItem | DynamicToolItem | FileChangeItem | McpToolItem | WebSearchItem;@@ -386,6 +389,8 @@ export class CodexAppServerAdapter {private readonly pendingTools = new Map<string, ToolCallPayload>();private readonly streamedAgentText = new Map<string, string>();private readonly streamedCommandOutput = new Map<string, StreamedOutput>();+ /** Plan-mode plans (`item/plan/delta`) streamed so far, by item id. */+ private readonly streamedPlans = new Map<string, string>();private readonly streamedReasoning = new Set<string>();private readonly toolStateSequence = new Map<string, number>();private stepToolCalls: ToolCallPayload[] = [];@@ -483,6 +488,9 @@ export class CodexAppServerAdapter {case 'turn/plan/updated': {return this.handlePlanUpdated(rawParams as TurnPlanUpdatedNotification);}+ case 'item/plan/delta': {+ return this.handleProposedPlanDelta(rawParams as PlanDeltaNotification);+ }case 'thread/tokenUsage/updated': {const { tokenUsage } = rawParams as ThreadTokenUsageUpdatedNotification;const cumulativeUsage = toUsage(tokenUsage.total);@@ -536,6 +544,7 @@ export class CodexAppServerAdapter {private handleItemStarted({ item }: ItemStartedNotification): HeterogeneousAgentEvent[] {if (item.type === 'userMessage') return this.handleSteeredUserMessage(item);+ if (item.type === 'plan') return this.startProposedPlan(item);if (!isToolItem(item)) return [];const opening = this.openStepAfterSteer();this.hasToolActivity = true;@@ -584,6 +593,7 @@ export class CodexAppServerAdapter {}return message.text ? this.emitText(message.id, message.text) : [];}+ if (item.type === 'plan') return this.completeProposedPlan(item);if (item.type === 'reasoning') {const reasoningItem = item as ReasoningItem;if (this.streamedReasoning.delete(reasoningItem.id)) return [];@@ -676,6 +686,75 @@ export class CodexAppServerAdapter {: [];}+ /**+ * A plan-mode plan (`ThreadItem { type: 'plan' }`) shows as a `proposed_plan`+ * tool: `item/plan/delta` only streams its text, the completed item is the+ * plan of record (Codex does not promise the deltas add up to it).+ */+ private startProposedPlan(item: PlanItem): HeterogeneousAgentEvent[] {+ if (this.pendingTools.has(item.id)) return [];+ const opening = this.openStepAfterSteer();+ const payload: ToolCallPayload = {+ apiName: CODEX_PROPOSED_PLAN_API_NAME,+ arguments: '{}',+ id: item.id,+ identifier: CODEX_IDENTIFIER,+ type: 'default',+ };+ this.hasToolActivity = true;+ this.pendingTools.set(item.id, payload);+ this.stepToolCalls.push(payload);+ this.streamedPlans.set(item.id, item.text ?? '');+ return [+ ...opening,+ this.makeEvent('stream_chunk', {+ chunkType: 'tools_calling',+ toolsCalling: [...this.stepToolCalls],+ }),+ this.makeEvent('tool_start', { toolCallId: item.id }),+ ];+ }++ private handleProposedPlanDelta(params: PlanDeltaNotification): HeterogeneousAgentEvent[] {+ if (!params.delta || !this.pendingTools.has(params.itemId)) return [];+ const text = `${this.streamedPlans.get(params.itemId) ?? ''}${params.delta}`;+ this.streamedPlans.set(params.itemId, text);+ return [+ this.toolState(params.itemId, {+ plan: { completed: false, text },+ } satisfies CodexProposedPlanState),+ ];+ }++ private completeProposedPlan(item: PlanItem): HeterogeneousAgentEvent[] {+ this.streamedPlans.delete(item.id);+ const payload = this.pendingTools.get(item.id) ?? {+ apiName: CODEX_PROPOSED_PLAN_API_NAME,+ arguments: '{}',+ id: item.id,+ identifier: CODEX_IDENTIFIER,+ type: 'default' as const,+ };+ const events = this.pendingTools.has(item.id) ? [] : this.startLateTool(payload);+ this.pendingTools.delete(item.id);+ const pluginState: CodexProposedPlanState = { plan: { completed: true, text: item.text } };+ events.push(+ this.makeEvent('tool_result', {+ content: item.text,+ isError: false,+ pluginState,+ toolCallId: item.id,+ } satisfies ToolResultData),+ this.makeEvent('tool_end', {+ isSuccess: true,+ payload: { toolCalling: payload },+ result: { content: item.text, state: pluginState, success: true },+ toolCallId: item.id,+ }),+ );+ return events;+ }+private handlePlanUpdated(params: TurnPlanUpdatedNotification): HeterogeneousAgentEvent[] {const id = `turn-plan-${params.turnId}`;let foundProcessing = false;diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.collaborationMode.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.collaborationMode.test.tsnew file mode 100644index 00000000000..70061e2e0e3--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.collaborationMode.test.ts@@ -0,0 +1,265 @@+import { describe, expect, it, vi } from 'vitest';++import { COLLABORATION_MODE_PHASE } from '../codexPlanMode';+import { CodexThreadSession } from './CodexThreadSession';++const THREAD = 'thread-1';++const turn = (id: string, status: 'completed' | 'inProgress' | 'interrupted') => ({+ completedAt: status === 'inProgress' ? null : 2,+ durationMs: null,+ error: null,+ id,+ items: [],+ itemsView: 'full',+ startedAt: 1,+ status,+});++/**+ * A Codex app-server stand-in that behaves like codex-cli 0.169.0 (probed):+ * `turn/start` with a collaboration mode first reports it with+ * `thread/settings/updated`, and a plan turn streams a `plan` item.+ */+const createHarness = (+ options: { hangTurns?: boolean; refuseMode?: boolean; slowAck?: boolean } = {},+) => {+ let notify: (method: string, params: unknown) => Promise<void> = async () => {};+ let threadMode: 'default' | 'plan' = 'default';+ let turnSequence = 0;+ const requests: Array<{ method: string; params: any }> = [];++ const settingsUpdated = (mode: 'default' | 'plan') =>+ notify('thread/settings/updated', {+ threadId: THREAD,+ threadSettings: {+ collaborationMode: {+ mode,+ settings: { developer_instructions: 'x', model: 'gpt-6.1-sol', reasoning_effort: 'high' },+ },+ },+ });++ const settledUpdated = (mode: 'default' | 'plan') => settingsUpdated(mode);++ const client = {+ acquireConsumer: vi.fn(() => vi.fn()),+ acquireThread: vi.fn(() => vi.fn()),+ connect: vi.fn().mockResolvedValue({ userAgent: 'codex-test' }),+ onDisconnect: vi.fn(() => vi.fn()),+ onRawMessage: vi.fn(() => vi.fn()),+ registerThread: vi.fn(() => vi.fn()),+ request: vi.fn(async (method: string, params: any) => {+ requests.push({ method, params });+ if (method === 'thread/start') {+ return { model: 'gpt-6.1-sol', reasoningEffort: 'high', thread: { id: THREAD } };+ }+ if (method === 'thread/name/set') return {};+ if (method === 'thread/settings/update') {+ if (threadMode !== params.collaborationMode.mode) {+ threadMode = params.collaborationMode.mode;+ const ack = threadMode;+ // `slowAck`: Codex answers after the caller already moved on.+ if (options.slowAck) setTimeout(() => void settingsUpdated(ack), 5);+ else void settingsUpdated(ack);+ }+ return {};+ }+ if (method === 'turn/interrupt') {+ setTimeout(() => {+ void notify('turn/completed', {+ threadId: THREAD,+ turn: turn(params.turnId, 'interrupted'),+ });+ }, 0);+ return {};+ }+ if (method === 'turn/start') {+ const turnId = `turn-${++turnSequence}`;+ // `refuseMode`: Codex keeps the thread where it was and says so.+ const mode = options.refuseMode ? undefined : params.collaborationMode?.mode;+ if (options.refuseMode && params.collaborationMode) await settledUpdated(threadMode);+ if (mode && mode !== threadMode) {+ threadMode = mode;+ await settingsUpdated(mode);+ }+ if (!options.hangTurns) {+ setTimeout(async () => {+ await notify('turn/started', { threadId: THREAD, turn: turn(turnId, 'inProgress') });+ if (threadMode === 'plan') {+ const item = { id: `plan-${turnId}`, text: '', type: 'plan' };+ await notify('item/started', { item, threadId: THREAD, turnId });+ await notify('item/plan/delta', {+ delta: '1. Step',+ itemId: item.id,+ threadId: THREAD,+ turnId,+ });+ await notify('item/completed', {+ item: { ...item, text: '1. Step\n' },+ threadId: THREAD,+ turnId,+ });+ }+ await notify('turn/completed', { threadId: THREAD, turn: turn(turnId, 'completed') });+ }, 0);+ }+ return { turn: turn(turnId, 'inProgress') };+ }+ return {};+ }),+ subscribe: vi.fn((_threadId: string, handler: typeof notify) => {+ notify = handler;+ return vi.fn();+ }),+ subscribeServerRequests: vi.fn(() => vi.fn()),+ };++ const events: any[] = [];+ const session = new CodexThreadSession({+ client: client as any,+ onEvents: (batch) => void events.push(...batch),+ onRuntimeStatus: vi.fn(),+ onSessionId: vi.fn(),+ sessionId: 'session-1',+ threadParams: { approvalPolicy: 'never', cwd: '/repo', sandbox: 'danger-full-access' },+ });+ const reports = () => events.filter((e) => e.data?.phase === COLLABORATION_MODE_PHASE);+ const turnStarts = () => requests.filter((r) => r.method === 'turn/start').map((r) => r.params);+ const settingsUpdates = () =>+ requests+ .filter((r) => r.method === 'thread/settings/update')+ .map((r) => r.params.collaborationMode.mode);+ return {+ events,+ reports,+ requests,+ session,+ settingsUpdates,+ threadMode: () => threadMode,+ turnStarts,+ };+};++const runOnce = (+ session: CodexThreadSession,+ options: Partial<Parameters<CodexThreadSession['run']>[0]> = {},+) =>+ session.run({+ input: [{ text: 'hi', text_elements: [], type: 'text' }],+ onRawMessage: vi.fn(),+ operationId: 'op-1',+ ...options,+ });++describe('CodexThreadSession — Codex Plan switch', () => {+ it('sends no collaboration mode and reports nothing for a topic that never used Plan', async () => {+ const harness = createHarness();++ await runOnce(harness.session);++ expect(harness.turnStarts()[0]).not.toHaveProperty('collaborationMode');+ expect(harness.settingsUpdates()).toEqual([]);+ expect(harness.reports()).toEqual([]);+ });++ it('sends plan with the thread model and effort, and the thread stays in plan', async () => {+ const harness = createHarness();++ await runOnce(harness.session, { collaborationMode: 'plan' });++ expect(harness.turnStarts()[0].collaborationMode).toEqual({+ mode: 'plan',+ settings: { developer_instructions: null, model: 'gpt-6.1-sol', reasoning_effort: 'high' },+ });+ // Plan is sticky: nothing puts the thread back once the turn ends.+ expect(harness.settingsUpdates()).toEqual([]);+ expect(harness.threadMode()).toBe('plan');+ // The read-back after `turn/start` confirms the request: nothing to sync.+ expect(harness.reports().map((e) => e.data)).toEqual([+ { collaborationMode: 'plan', phase: COLLABORATION_MODE_PHASE, requested: 'plan' },+ ]);+ // The plan item reaches the transcript as a `proposed_plan` tool.+ expect(+ harness.events.some((e) => e.type === 'tool_result' && e.data.content === '1. Step\n'),+ ).toBe(true);+ });++ it('sends the current mode on every turn once Plan was used, so turning it off takes effect', async () => {+ const harness = createHarness();++ await runOnce(harness.session, { collaborationMode: 'plan' });+ await runOnce(harness.session, { collaborationMode: 'plan' });+ await runOnce(harness.session, { collaborationMode: 'default' });++ expect(harness.turnStarts().map((p) => p.collaborationMode.mode)).toEqual([+ 'plan',+ 'plan',+ 'default',+ ]);+ expect(harness.threadMode()).toBe('default');+ // Only changes are reported: on, then off.+ expect(harness.reports().map((e) => e.data.collaborationMode)).toEqual(['plan', 'default']);+ });++ it('leaves the thread in plan when the user stops a plan turn', async () => {+ const harness = createHarness({ hangTurns: true });+ const run = runOnce(harness.session, { collaborationMode: 'plan' });+ await vi.waitFor(() => expect(harness.turnStarts()).toHaveLength(1));++ await harness.session.interrupt();+ await run;++ expect(harness.settingsUpdates()).toEqual([]);+ expect(harness.threadMode()).toBe('plan');+ });++ it('switches mid-run from the next turn, never the turn in flight', async () => {+ const harness = createHarness({ hangTurns: true });+ const run = runOnce(harness.session, { collaborationMode: 'default' });+ await vi.waitFor(() => expect(harness.turnStarts()).toHaveLength(1));++ await harness.session.setCollaborationMode('plan');++ expect(harness.settingsUpdates()).toEqual(['plan']);+ expect(harness.turnStarts()).toHaveLength(1);+ expect(harness.reports().at(-1)?.data).toEqual({+ collaborationMode: 'plan',+ phase: COLLABORATION_MODE_PHASE,+ requested: 'plan',+ });+ await harness.session.interrupt();+ await run;+ });++ it('reports what Codex says when it does not take the requested mode', async () => {+ const harness = createHarness({ refuseMode: true });++ await runOnce(harness.session, { collaborationMode: 'plan' });++ expect(harness.reports().map((e) => e.data)).toEqual([+ { collaborationMode: 'default', phase: COLLABORATION_MODE_PHASE, requested: 'plan' },+ ]);+ });++ it('reads an acknowledgement of an earlier flip as that flip, not a refusal of the latest', async () => {+ const harness = createHarness({ hangTurns: true, slowAck: true });+ const run = runOnce(harness.session, { collaborationMode: 'default' });+ await vi.waitFor(() => expect(harness.turnStarts()).toHaveLength(1));++ // On then off before Codex answers the first switch.+ await harness.session.setCollaborationMode('plan');+ await harness.session.setCollaborationMode('default');+ await vi.waitFor(() => expect(harness.reports()).toHaveLength(2));++ const reports = harness.reports().map((e) => e.data);+ expect(reports).toEqual([+ { collaborationMode: 'plan', phase: COLLABORATION_MODE_PHASE, requested: 'plan' },+ { collaborationMode: 'default', phase: COLLABORATION_MODE_PHASE, requested: 'default' },+ ]);+ // Neither report disagrees with its request, so the topic keeps the user's last pick.+ expect(reports.every((r) => r.collaborationMode === r.requested)).toBe(true);+ await harness.session.interrupt();+ await run;+ });+});diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.tsindex bd123be677c..94fe4f5f0fd 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts@@ -1,8 +1,11 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { CodexCollaborationMode } from '@lobechat/types';+import { isCodexCollaborationMode } from '@lobechat/types';import { isRecord, pickString } from '@lobechat/utils/object';import { CodexAppServerAdapter } from '../adapters/codexAppServer';import type { AskUserBridge, InterventionAnswer } from '../askUser';+import { COLLABORATION_MODE_PHASE, type CollaborationModeReportData } from '../codexPlanMode';import type { HeterogeneousAgentRuntimeStatus } from '../spawn/claudeAgentSdkSession';import { toStreamEvent } from '../spawn/streamEvent';import type { UsageData } from '../types';@@ -28,6 +31,10 @@ import type {TurnStartResponse,UserInput,} from './protocol';+import type { CollaborationMode } from './protocol/experimental/CollaborationMode';+import type { ReasoningEffort } from './protocol/experimental/ReasoningEffort';+import type { ThreadSettingsUpdatedNotification } from './protocol/experimental/v2/ThreadSettingsUpdatedNotification';+import type { ThreadSettingsUpdateParams } from './protocol/experimental/v2/ThreadSettingsUpdateParams';import {codexUserInputArguments,codexUserInputResponse,@@ -39,6 +46,9 @@ const CODEX_APP_SERVER_TRANSPORT = 'codex-app-server' as const;const RESUME_SETTLE_DELAY_MS = 200;const RESUME_SETTLE_TIMEOUT_MS = 10_000;+/** `turn/start.collaborationMode` is EXPERIMENTAL in 0.169 and absent from the stable params. */+type ExperimentalTurnStartParams = TurnStartParams & { collaborationMode?: CollaborationMode };+const toThreadResumeParams = (threadId: string, params: ThreadStartParams): ThreadResumeParams => {const resumeParams = { ...params };delete resumeParams.ephemeral;@@ -86,6 +96,12 @@ interface ThreadNameSetParams {export interface CodexThreadTurnOptions {askUserBridge?: AskUserBridge;+ /**+ * Codex Plan switch (Better Coding Experience): the collaboration mode every+ * native turn of this run sends. Omitted sends none, exactly as before. Codex+ * keeps the mode on the thread, so it stays until a turn sends another.+ */+ collaborationMode?: CodexCollaborationMode;input: UserInput[];onRawMessage: (line: string) => Promise<void> | void;operationId: string;@@ -121,6 +137,15 @@ export class CodexThreadSession {private interruptRequested = false;private lastOperationId?: string;private model?: string;+ private effort?: ReasoningEffort | null;+ /** The mode this run's turns send; a mid-run switch changes it for the next turn. */+ private collaborationMode?: CodexCollaborationMode;+ /**+ * Modes sent since the last `turn/start`, oldest first, that Codex has not+ * acknowledged yet. A `thread/settings/updated` naming one of them answers+ * that request (and supersedes the older ones), not the latest pick.+ */+ private pendingModeRequests: CodexCollaborationMode[] = [];private running = false;private readonly sessionUnsubscribers: Array<() => void> = [];private threadId?: string;@@ -149,6 +174,7 @@ export class CodexThreadSession {this.running = true;this.interruptRequested = false;this.lastOperationId = options.operationId;+ this.collaborationMode = options.collaborationMode;this.emitStatus('starting', options.operationId);const traceUnsubscribers: Array<() => void> = [];@@ -231,7 +257,14 @@ export class CodexThreadSession {};this.activeTurn = activeTurn;- const turnParams: TurnStartParams = { input, threadId };+ const collaborationMode = this.collaborationModeParams(this.collaborationMode);+ // Each turn states its mode afresh: earlier unanswered requests are moot.+ this.pendingModeRequests = collaborationMode ? [collaborationMode.mode] : [];+ const turnParams: ExperimentalTurnStartParams = {+ input,+ threadId,+ ...(collaborationMode && { collaborationMode }),+ };this.canFallback = false;const turn = await this.options.client.request<TurnStartResponse>('turn/start', turnParams);activeTurn.turnId = turn?.turn?.id;@@ -356,7 +389,7 @@ export class CodexThreadSession {toThreadResumeParams(this.threadId, this.threadParams),);if (!response || this.closedByHost) return;- await this.attachThread(response.thread.id, response.model);+ await this.attachThread(response.thread.id, response.model, response.reasoningEffort);return;}@@ -373,7 +406,7 @@ export class CodexThreadSession {);}- await this.attachThread(threadId, response.model);+ await this.attachThread(threadId, response.model, response.reasoningEffort);if (!this.options.threadParams.ephemeral) {await this.setThreadName(threadId);this.options.onSessionId(threadId);@@ -425,12 +458,19 @@ export class CodexThreadSession {}}- private async attachThread(threadId: string, model?: string): Promise<void> {+ private async attachThread(+ threadId: string,+ model?: string,+ effort?: ReasoningEffort | null,+ ): Promise<void> {this.releaseThread ??= this.options.client.acquireThread(threadId);this.threadId = threadId;this.attached = true;this.canFallback = false;if (model) this.updateModel(model);+ // The effort the thread resolved from this run's config (a pick made in+ // LobeHub reaches it here), which a collaboration mode must carry along.+ if (effort !== undefined) this.effort = effort;if (this.threadUnsubscribers.length > 0) return;this.threadUnsubscribers.push(@@ -460,10 +500,83 @@ export class CodexThreadSession {);}+ /**+ * The Plan switch flipped while this run goes: Codex takes the mode from its+ * next turn (`thread/settings/update` never changes the turn in flight), and+ * this run's own next turn — a continuation after async answers — sends it too.+ */+ async setCollaborationMode(mode: CodexCollaborationMode): Promise<void> {+ this.collaborationMode = mode;+ if (!this.running || !this.attached || !this.threadId || this.closedByHost) return;+ const collaborationMode = this.collaborationModeParams(mode);+ if (!collaborationMode) return;+ this.pendingModeRequests.push(mode);+ await this.options.client.request('thread/settings/update', {+ collaborationMode,+ threadId: this.threadId,+ } satisfies ThreadSettingsUpdateParams);+ }++ /**+ * The `collaborationMode` for `mode`, carrying the thread's own model and+ * effort (`developer_instructions: null` keeps the mode's built-in+ * instructions; the thread's developer instructions stay in force, verified+ * on codex-cli 0.169.0). Undefined without a mode, or before the thread+ * reported its model.+ */+ private collaborationModeParams(+ mode: CodexCollaborationMode | undefined,+ ): CollaborationMode | undefined {+ if (!mode || !this.model) return;+ return {+ mode,+ settings: {+ developer_instructions: null,+ model: this.model,+ reasoning_effort: this.effort ?? null,+ },+ };+ }++ /**+ * Codex reports the thread's mode after `turn/start` set it, or after a+ * mid-run switch (it only reports a change). The report carries the request+ * it answers, so the topic follows Codex only where the two disagree. A+ * notification naming a pending request acknowledges that one: with Plan+ * flipped on and back off before Codex answered, its `plan` answers the+ * first flip and must not read as Codex refusing the second.+ */+ private handleThreadSettingsUpdated(+ activeTurn: ActiveTurn,+ params: ThreadSettingsUpdatedNotification,+ ): Promise<void> {+ const mode = params?.threadSettings?.collaborationMode?.mode;+ if (params?.threadId !== this.threadId || !this.collaborationMode) return Promise.resolve();+ if (!isCodexCollaborationMode(mode)) return Promise.resolve();+ const acknowledged = this.pendingModeRequests.indexOf(mode);+ const requested = acknowledged >= 0 ? mode : this.collaborationMode;+ if (acknowledged >= 0) this.pendingModeRequests.splice(0, acknowledged + 1);+ const data: CollaborationModeReportData = {+ collaborationMode: mode,+ phase: COLLABORATION_MODE_PHASE,+ requested,+ };+ activeTurn.notificationQueue = activeTurn.notificationQueue.then(() =>+ this.options.onEvents([+ toStreamEvent(+ { data, stepIndex: 0, timestamp: Date.now(), type: 'step_complete' },+ activeTurn.operationId,+ ),+ ]),+ );+ return activeTurn.notificationQueue;+ }+private async handleReconnect(response: ThreadResumeResponse): Promise<void> {if (this.closedByHost) return;this.attached = true;if (response.model) this.updateModel(response.model);+ if (response.reasoningEffort !== undefined) this.effort = response.reasoningEffort;}private async requestUserInput(params: unknown) {@@ -554,6 +667,12 @@ export class CodexThreadSession {if (!activeTurn || !this.isCurrentTurnNotification(method, params, activeTurn)) {return Promise.resolve();}+ if (method === 'thread/settings/updated') {+ return this.handleThreadSettingsUpdated(+ activeTurn,+ params as ThreadSettingsUpdatedNotification,+ );+ }if (method === 'turn/completed') {const notification = params as TurnCompletedNotification;if (notification.turn.status !== 'inProgress') {diff --git a/packages/heterogeneous-agents/src/codex/appServerArgs.ts b/packages/heterogeneous-agents/src/codex/appServerArgs.tsnew file mode 100644index 00000000000..aa1c84cfd01--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/appServerArgs.ts@@ -0,0 +1,150 @@+import type { JsonValue, SandboxMode } from './protocol';++/*+ * Browser-safe: which Codex CLI arguments the native app-server thread can+ * honor. Shared by the device dispatch (server), the desktop transport and the+ * composer's Plan switch, which grays out where a run would fall back to exec.+ */++export const CODEX_DANGEROUS_BYPASS_FLAG = '--dangerously-bypass-approvals-and-sandbox';+export const CODEX_FULL_AUTO_FLAG = '--full-auto';+export const CODEX_APPROVAL_FLAGS = ['-a', '--ask-for-approval'] as const;+export const CODEX_CONFIG_FLAGS = ['-c', '--config'] as const;+export const CODEX_CWD_FLAGS = ['-C', '--cd'] as const;+export const CODEX_EPHEMERAL_FLAG = '--ephemeral';+export const CODEX_IGNORE_USER_CONFIG_FLAG = '--ignore-user-config';+export const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;+export const CODEX_PROFILE_FLAGS = ['-p', '--profile'] as const;+export const CODEX_SANDBOX_FLAGS = ['-s', '--sandbox'] as const;++export const getFlagValue = (arg: string, flags: readonly string[]) => {+ const flag = flags.find((candidate) => arg.startsWith(`${candidate}=`));+ return flag ? arg.slice(flag.length + 1) : undefined;+};++const parseConfigValue = (raw: string): JsonValue => {+ const value = raw.trim();+ if (value === 'true') return true;+ if (value === 'false') return false;+ if (value === 'null') return null;++ const number = Number(value);+ if (value && Number.isFinite(number)) return number;++ if (+ (value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith('[') && value.endsWith(']')) ||+ (value.startsWith('{') && value.endsWith('}'))+ ) {+ try {+ return JSON.parse(value) as JsonValue;+ } catch {+ // Keep non-JSON TOML values as strings; app-server validates the config.+ }+ }++ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1);+ return value;+};++export const parseConfigOverride = (raw: string) => {+ const separator = raw.indexOf('=');+ if (separator <= 0) return;+ const key = raw.slice(0, separator).trim();+ if (!key) return;+ return { key, value: parseConfigValue(raw.slice(separator + 1)) };+};++export const isSandboxMode = (value: string): value is SandboxMode =>+ value === 'danger-full-access' || value === 'read-only' || value === 'workspace-write';++/** Thread-scoped configuration is sent over RPC; the shared process needs only its subcommand. */+export const buildCodexAppServerArgs = (_args: string[] = []): string[] => ['app-server'];++/** Keep CLI semantics on exec when they cannot be represented by the app-server thread contract. */+export const getCodexAppServerUnsupportedArgs = (+ args: string[],+ options: { resume?: boolean } = {},+): string[] => {+ const unsupported: string[] = [];+ const hasSandboxFlag = args.some(+ (arg) =>+ CODEX_SANDBOX_FLAGS.includes(arg as (typeof CODEX_SANDBOX_FLAGS)[number]) ||+ getFlagValue(arg, CODEX_SANDBOX_FLAGS) !== undefined,+ );++ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];+ if (arg === CODEX_DANGEROUS_BYPASS_FLAG) {+ if (hasSandboxFlag) unsupported.push(arg);+ continue;+ }+ if (arg === CODEX_EPHEMERAL_FLAG) {+ if (options.resume) unsupported.push(arg);+ continue;+ }+ if (arg === CODEX_FULL_AUTO_FLAG || arg === CODEX_IGNORE_USER_CONFIG_FLAG) {+ unsupported.push(arg);+ continue;+ }++ const valueFlags = [+ ...CODEX_MODEL_FLAGS,+ ...CODEX_CONFIG_FLAGS,+ ...CODEX_CWD_FLAGS,+ ...CODEX_APPROVAL_FLAGS,+ ...CODEX_SANDBOX_FLAGS,+ ];+ const exactFlag = valueFlags.find((flag) => arg === flag);+ const inlineFlag = valueFlags.find((flag) => arg.startsWith(`${flag}=`));+ if (exactFlag || inlineFlag) {+ const value = inlineFlag ? arg.slice(inlineFlag.length + 1) : args[index + 1];+ if (!value || (!inlineFlag && value.startsWith('-'))) {+ unsupported.push(arg);+ continue;+ }+ if (!inlineFlag) index += 1;++ if (+ CODEX_APPROVAL_FLAGS.includes(+ (exactFlag ?? inlineFlag) as (typeof CODEX_APPROVAL_FLAGS)[number],+ ) &&+ value !== 'never'+ ) {+ unsupported.push(arg);+ }+ if (+ CODEX_SANDBOX_FLAGS.includes(+ (exactFlag ?? inlineFlag) as (typeof CODEX_SANDBOX_FLAGS)[number],+ ) &&+ !isSandboxMode(value)+ ) {+ unsupported.push(arg);+ }+ if (+ CODEX_CONFIG_FLAGS.includes(+ (exactFlag ?? inlineFlag) as (typeof CODEX_CONFIG_FLAGS)[number],+ )+ ) {+ const override = parseConfigOverride(value);+ if (override?.key === 'approval_policy' && override.value !== 'never') {+ unsupported.push(arg);+ }+ }+ continue;+ }++ if (+ CODEX_PROFILE_FLAGS.includes(arg as (typeof CODEX_PROFILE_FLAGS)[number]) ||+ getFlagValue(arg, CODEX_PROFILE_FLAGS) !== undefined+ ) {+ unsupported.push(arg);+ if (CODEX_PROFILE_FLAGS.includes(arg as (typeof CODEX_PROFILE_FLAGS)[number])) index += 1;+ continue;+ }++ unsupported.push(arg);+ }++ return unsupported;+};diff --git a/packages/heterogeneous-agents/src/codex/appServerParams.ts b/packages/heterogeneous-agents/src/codex/appServerParams.tsindex bc6f2387662..262d4a229b8 100644--- a/packages/heterogeneous-agents/src/codex/appServerParams.ts+++ b/packages/heterogeneous-agents/src/codex/appServerParams.ts@@ -1,150 +1,22 @@import path from 'node:path';import type { AgentInputPlan } from '../spawn/input';+import {+ CODEX_APPROVAL_FLAGS,+ CODEX_CONFIG_FLAGS,+ CODEX_CWD_FLAGS,+ CODEX_DANGEROUS_BYPASS_FLAG,+ CODEX_EPHEMERAL_FLAG,+ CODEX_FULL_AUTO_FLAG,+ CODEX_MODEL_FLAGS,+ CODEX_SANDBOX_FLAGS,+ getFlagValue,+ isSandboxMode,+ parseConfigOverride,+} from './appServerArgs';import type { JsonValue, SandboxMode, ThreadStartParams, UserInput } from './protocol';-const CODEX_DANGEROUS_BYPASS_FLAG = '--dangerously-bypass-approvals-and-sandbox';-const CODEX_FULL_AUTO_FLAG = '--full-auto';-const CODEX_APPROVAL_FLAGS = ['-a', '--ask-for-approval'] as const;-const CODEX_CONFIG_FLAGS = ['-c', '--config'] as const;-const CODEX_CWD_FLAGS = ['-C', '--cd'] as const;-const CODEX_EPHEMERAL_FLAG = '--ephemeral';-const CODEX_IGNORE_USER_CONFIG_FLAG = '--ignore-user-config';-const CODEX_MODEL_FLAGS = ['-m', '--model'] as const;-const CODEX_PROFILE_FLAGS = ['-p', '--profile'] as const;-const CODEX_SANDBOX_FLAGS = ['-s', '--sandbox'] as const;--const getFlagValue = (arg: string, flags: readonly string[]) => {- const flag = flags.find((candidate) => arg.startsWith(`${candidate}=`));- return flag ? arg.slice(flag.length + 1) : undefined;-};--const parseConfigValue = (raw: string): JsonValue => {- const value = raw.trim();- if (value === 'true') return true;- if (value === 'false') return false;- if (value === 'null') return null;-- const number = Number(value);- if (value && Number.isFinite(number)) return number;-- if (- (value.startsWith('"') && value.endsWith('"')) ||- (value.startsWith('[') && value.endsWith(']')) ||- (value.startsWith('{') && value.endsWith('}'))- ) {- try {- return JSON.parse(value) as JsonValue;- } catch {- // Keep non-JSON TOML values as strings; app-server validates the config.- }- }-- if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1);- return value;-};--const parseConfigOverride = (raw: string) => {- const separator = raw.indexOf('=');- if (separator <= 0) return;- const key = raw.slice(0, separator).trim();- if (!key) return;- return { key, value: parseConfigValue(raw.slice(separator + 1)) };-};--const isSandboxMode = (value: string): value is SandboxMode =>- value === 'danger-full-access' || value === 'read-only' || value === 'workspace-write';--/** Thread-scoped configuration is sent over RPC; the shared process needs only its subcommand. */-export const buildCodexAppServerArgs = (_args: string[] = []): string[] => ['app-server'];--/** Keep CLI semantics on exec when they cannot be represented by the app-server thread contract. */-export const getCodexAppServerUnsupportedArgs = (- args: string[],- options: { resume?: boolean } = {},-): string[] => {- const unsupported: string[] = [];- const hasSandboxFlag = args.some(- (arg) =>- CODEX_SANDBOX_FLAGS.includes(arg as (typeof CODEX_SANDBOX_FLAGS)[number]) ||- getFlagValue(arg, CODEX_SANDBOX_FLAGS) !== undefined,- );-- for (let index = 0; index < args.length; index += 1) {- const arg = args[index];- if (arg === CODEX_DANGEROUS_BYPASS_FLAG) {- if (hasSandboxFlag) unsupported.push(arg);- continue;- }- if (arg === CODEX_EPHEMERAL_FLAG) {- if (options.resume) unsupported.push(arg);- continue;- }- if (arg === CODEX_FULL_AUTO_FLAG || arg === CODEX_IGNORE_USER_CONFIG_FLAG) {- unsupported.push(arg);- continue;- }-- const valueFlags = [- ...CODEX_MODEL_FLAGS,- ...CODEX_CONFIG_FLAGS,- ...CODEX_CWD_FLAGS,- ...CODEX_APPROVAL_FLAGS,- ...CODEX_SANDBOX_FLAGS,- ];- const exactFlag = valueFlags.find((flag) => arg === flag);- const inlineFlag = valueFlags.find((flag) => arg.startsWith(`${flag}=`));- if (exactFlag || inlineFlag) {- const value = inlineFlag ? arg.slice(inlineFlag.length + 1) : args[index + 1];- if (!value || (!inlineFlag && value.startsWith('-'))) {- unsupported.push(arg);- continue;- }- if (!inlineFlag) index += 1;-- if (- CODEX_APPROVAL_FLAGS.includes(- (exactFlag ?? inlineFlag) as (typeof CODEX_APPROVAL_FLAGS)[number],- ) &&- value !== 'never'- ) {- unsupported.push(arg);- }- if (- CODEX_SANDBOX_FLAGS.includes(- (exactFlag ?? inlineFlag) as (typeof CODEX_SANDBOX_FLAGS)[number],- ) &&- !isSandboxMode(value)- ) {- unsupported.push(arg);- }- if (- CODEX_CONFIG_FLAGS.includes(- (exactFlag ?? inlineFlag) as (typeof CODEX_CONFIG_FLAGS)[number],- )- ) {- const override = parseConfigOverride(value);- if (override?.key === 'approval_policy' && override.value !== 'never') {- unsupported.push(arg);- }- }- continue;- }-- if (- CODEX_PROFILE_FLAGS.includes(arg as (typeof CODEX_PROFILE_FLAGS)[number]) ||- getFlagValue(arg, CODEX_PROFILE_FLAGS) !== undefined- ) {- unsupported.push(arg);- if (CODEX_PROFILE_FLAGS.includes(arg as (typeof CODEX_PROFILE_FLAGS)[number])) index += 1;- continue;- }-- unsupported.push(arg);- }-- return unsupported;-};+export { buildCodexAppServerArgs, getCodexAppServerUnsupportedArgs } from './appServerArgs';export const buildCodexAppServerThreadParams = (args: string[],diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandle.tsindex ca5a1686a69..7097f6b813b 100644--- a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts@@ -1,6 +1,8 @@import { randomUUID } from 'node:crypto';import { PassThrough } from 'node:stream';+import type { CodexCollaborationMode } from '@lobechat/types';+import type { AskUserBridge } from '../askUser';import type { AgentPromptInput } from '../protocol';import { createEventQueue } from '../spawn/agentEventQueue';@@ -23,6 +25,11 @@ export interface CodexAgentHandleOptions {askUserBridge?: AskUserBridge;/** Caller version sent in the native initialize handshake. */clientVersion: string;+ /**+ * Codex Plan switch: the collaboration mode every turn sends (omitted sends+ * none). Codex keeps it on the thread until a turn sends another.+ */+ collaborationMode?: CodexCollaborationMode;/** Resolved, validated Codex executable path. */commandPath: string;/** Working directory already authorized by device dispatch. */@@ -158,6 +165,7 @@ export const createCodexAgentHandle = async (options.onStartupControl?.({ cancel });const turnOptions = {askUserBridge: options.askUserBridge,+ collaborationMode: options.collaborationMode,// Keep the already materialized user input and attachment paths unchanged.input: buildCodexAppServerInput(input),onRawMessage: (line: string) => options.onRawStdout?.(Buffer.from(line)),@@ -219,6 +227,8 @@ export const createCodexAgentHandle = async (get sessionId() {return nativeSessionId;},+ /** The Plan switch flipped mid-run: Codex takes it from the next turn. */+ setCollaborationMode: (mode: CodexCollaborationMode) => session.setCollaborationMode(mode),stderr,supportsSteerImageAttachments: true,};diff --git a/packages/heterogeneous-agents/src/codex/protocol/README.md b/packages/heterogeneous-agents/src/codex/protocol/README.mdindex 1e72e4fa537..58215f0cc7e 100644--- a/packages/heterogeneous-agents/src/codex/protocol/README.md+++ b/packages/heterogeneous-agents/src/codex/protocol/README.md@@ -19,3 +19,20 @@ wire names and nullability identical to the generated files; do not hand-edit pr`codex app-server generate-ts --experimental --out <directory>` output. They describe thenative `item/tool/requestUserInput` request and its question-id-keyed answer contract;only repository formatting is applied after generation.++The Codex Plan switch (collaboration mode) files are generated by Codex CLI **0.169.0**'s+`codex app-server generate-ts --experimental --out <directory>`:++- `experimental/CollaborationMode.ts`, `ModeKind.ts`, `Settings.ts` and their imports+ (`ReasoningEffort.ts`, `Personality.ts`, `ReasoningSummary.ts`, `MultiAgentMode.ts`,+ `AbsolutePathBuf.ts`, `LegacyAppPathString.ts`);+- `experimental/v2/PlanDeltaNotification.ts` (`item/plan/delta`);+- `experimental/v2/ThreadSettingsUpdateParams.ts`, `ThreadSettingsUpdateResponse.ts`,+ `ThreadSettingsUpdatedNotification.ts`, `ThreadSettings.ts` and their imports+ (`ActivePermissionProfile.ts`, `ApprovalsReviewer.ts`, `AskForApproval.ts`, `NetworkAccess.ts`,+ `SandboxPolicy.ts`, `ThreadEnvironment.ts`, `TurnEnvironmentParams.ts`).++They keep the generator's relative layout so imports resolve unchanged. `turn/start.collaborationMode`+and `ThreadResumeResponse.collaborationMode` are experimental fields the stable `generated.ts` does not+carry; callers add them to the stable params type at the call site. The plan `ThreadItem` is already in+the stable set.diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/AbsolutePathBuf.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/AbsolutePathBuf.tsnew file mode 100644index 00000000000..dc1cde12410--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/AbsolutePathBuf.ts@@ -0,0 +1,14 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * A path that is guaranteed to be absolute and normalized (though it is not+ * guaranteed to be canonicalized or exist on the filesystem).+ *+ * IMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set+ * using [AbsolutePathBufGuard::new]. If no base path is set, the+ * deserialization will fail unless the path being deserialized is already+ * absolute.+ */+export type AbsolutePathBuf = string;diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/CollaborationMode.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/CollaborationMode.tsnew file mode 100644index 00000000000..3ffa252be71--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/CollaborationMode.ts@@ -0,0 +1,10 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { ModeKind } from './ModeKind';+import type { Settings } from './Settings';++/**+ * Collaboration mode for a Codex session.+ */+export type CollaborationMode = { mode: ModeKind; settings: Settings };diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/LegacyAppPathString.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/LegacyAppPathString.tsnew file mode 100644index 00000000000..5c0a1b1e446--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/LegacyAppPathString.ts@@ -0,0 +1,27 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * A UTF-8 path for preserving raw path compatibility at the app-server API+ * boundary while Codex migrates to [`PathUri`].+ *+ * Supports storing arbitrary strings read from the API and converting to and+ * from [`PathUri`] using an explicitly selected native path convention.+ *+ * When converting from [`PathUri`], "native" refers to the supplied+ * [`PathConvention`], which may be foreign to the operating system running+ * this process. The inner string is private so path-producing code must use a+ * path conversion method instead of bypassing the intended conversion+ * boundary. Non-UTF-8 paths are converted to UTF-8 lossily because this API+ * value is serialized as a JSON string.+ *+ * Deserialization and [`Self::from_string`] accept any UTF-8 string without+ * interpreting or validating it. Use [`Self::from_string`] when a caller+ * already owns legacy app-server path text and needs to preserve its wire+ * spelling; use [`Self::from_path`], [`Self::from_abs_path`], or+ * [`Self::from_path_uri`] when converting an actual path value. Relative+ * path text remains valid until an operation such as [`Self::to_path_uri`]+ * requires an absolute path.+ */+export type LegacyAppPathString = string;diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ModeKind.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ModeKind.tsnew file mode 100644index 00000000000..ae4d7c820b4--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ModeKind.ts@@ -0,0 +1,8 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * Initial collaboration mode to use when the TUI starts.+ */+export type ModeKind = 'plan' | 'default';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/MultiAgentMode.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/MultiAgentMode.tsnew file mode 100644index 00000000000..74f4255e0df--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/MultiAgentMode.ts@@ -0,0 +1,9 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * Controls the effective multi-agent delegation instructions for a turn. `custom` means the+ * configured mode hint defines the policy instead of a built-in policy.+ */+export type MultiAgentMode = { custom: string } | 'explicitRequestOnly' | 'proactive';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/Personality.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/Personality.tsnew file mode 100644index 00000000000..094bc704abb--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/Personality.ts@@ -0,0 +1,8 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * Deprecated: `friendly` and `pragmatic` no longer select a style.+ */+export type Personality = 'none' | 'friendly' | 'pragmatic';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ReasoningEffort.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ReasoningEffort.tsnew file mode 100644index 00000000000..d40f5bd6578--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ReasoningEffort.ts@@ -0,0 +1,8 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning+ */+export type ReasoningEffort = string;diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ReasoningSummary.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ReasoningSummary.tsnew file mode 100644index 00000000000..3a58aa85ccd--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ReasoningSummary.ts@@ -0,0 +1,10 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * A summary of the reasoning performed by the model. This can be useful for+ * debugging and understanding the model's reasoning process.+ * See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries+ */+export type ReasoningSummary = 'auto' | 'concise' | 'detailed' | 'none';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/Settings.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/Settings.tsnew file mode 100644index 00000000000..c240a37431d--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/Settings.ts@@ -0,0 +1,13 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { ReasoningEffort } from './ReasoningEffort';++/**+ * Settings for a collaboration mode.+ */+export type Settings = {+ model: string;+ reasoning_effort: ReasoningEffort | null;+ developer_instructions: string | null;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ActivePermissionProfile.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ActivePermissionProfile.tsnew file mode 100644index 00000000000..48f258ae9dc--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ActivePermissionProfile.ts@@ -0,0 +1,16 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++export type ActivePermissionProfile = {+ /**+ * Identifier from `default_permissions` or the implicit built-in default,+ * such as `:workspace` or a user-defined `[permissions.<id>]` profile.+ */+ id: string;+ /**+ * Parent profile identifier from the selected permissions profile's+ * `extends` setting, when present.+ */+ extends: string | null;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ApprovalsReviewer.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ApprovalsReviewer.tsnew file mode 100644index 00000000000..0dc8f7dcdd8--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ApprovalsReviewer.ts@@ -0,0 +1,12 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * Configures who approval requests are routed to for review. Examples+ * include sandbox escapes, blocked network access, MCP approval prompts, and+ * ARC escalations. Defaults to `user`. `auto_review` uses a carefully+ * prompted subagent to gather relevant context and apply a risk-based+ * decision framework before approving or denying the request.+ */+export type ApprovalsReviewer = 'user' | 'auto_review' | 'guardian_subagent';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/AskForApproval.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/AskForApproval.tsnew file mode 100644index 00000000000..385888eaadd--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/AskForApproval.ts@@ -0,0 +1,17 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++export type AskForApproval =+ | 'untrusted'+ | 'on-request'+ | {+ granular: {+ sandbox_approval: boolean;+ rules: boolean;+ skill_approval: boolean;+ request_permissions: boolean;+ mcp_elicitations: boolean;+ };+ }+ | 'never';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/NetworkAccess.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/NetworkAccess.tsnew file mode 100644index 00000000000..a8021b376ba--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/NetworkAccess.ts@@ -0,0 +1,5 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++export type NetworkAccess = 'restricted' | 'enabled';diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/PlanDeltaNotification.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/PlanDeltaNotification.tsnew file mode 100644index 00000000000..262f65204cf--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/PlanDeltaNotification.ts@@ -0,0 +1,14 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should+ * not assume concatenated deltas match the completed plan item content.+ */+export type PlanDeltaNotification = {+ threadId: string;+ turnId: string;+ itemId: string;+ delta: string;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/SandboxPolicy.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/SandboxPolicy.tsnew file mode 100644index 00000000000..a51244d6529--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/SandboxPolicy.ts@@ -0,0 +1,17 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { AbsolutePathBuf } from '../AbsolutePathBuf';+import type { NetworkAccess } from './NetworkAccess';++export type SandboxPolicy =+ | { type: 'dangerFullAccess' }+ | { type: 'readOnly'; networkAccess: boolean }+ | { type: 'externalSandbox'; networkAccess: NetworkAccess }+ | {+ type: 'workspaceWrite';+ writableRoots: Array<AbsolutePathBuf>;+ networkAccess: boolean;+ excludeTmpdirEnvVar: boolean;+ excludeSlashTmp: boolean;+ };diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadEnvironment.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadEnvironment.tsnew file mode 100644index 00000000000..de69504dd52--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadEnvironment.ts@@ -0,0 +1,13 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { LegacyAppPathString } from '../LegacyAppPathString';++/**+ * An environment selected by a loaded thread, independent of connection status.+ */+export type ThreadEnvironment = {+ environmentId: string;+ cwd: LegacyAppPathString;+ runtimeWorkspaceRoots: Array<LegacyAppPathString>;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettings.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettings.tsnew file mode 100644index 00000000000..eb75f37c122--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettings.ts@@ -0,0 +1,45 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { AbsolutePathBuf } from '../AbsolutePathBuf';+import type { CollaborationMode } from '../CollaborationMode';+import type { MultiAgentMode } from '../MultiAgentMode';+import type { Personality } from '../Personality';+import type { ReasoningEffort } from '../ReasoningEffort';+import type { ReasoningSummary } from '../ReasoningSummary';+import type { ActivePermissionProfile } from './ActivePermissionProfile';+import type { ApprovalsReviewer } from './ApprovalsReviewer';+import type { AskForApproval } from './AskForApproval';+import type { SandboxPolicy } from './SandboxPolicy';+import type { ThreadEnvironment } from './ThreadEnvironment';++export type ThreadSettings = {+ /**+ * Saved list of disabled plugin IDs. Does not yet filter plugin capabilities.+ */+ disabledPluginIds: Array<string>;+ cwd: AbsolutePathBuf;+ /**+ * Environments configured for future turns, in priority order, primary first.+ * `null` means the server does not expose the selection; [] means none are selected.+ */+ environments: Array<ThreadEnvironment> | null;+ approvalPolicy: AskForApproval;+ approvalsReviewer: ApprovalsReviewer;+ sandboxPolicy: SandboxPolicy;+ activePermissionProfile: ActivePermissionProfile | null;+ model: string;+ modelProvider: string;+ serviceTier: string | null;+ effort: ReasoningEffort | null;+ summary: ReasoningSummary | null;+ collaborationMode: CollaborationMode;+ /**+ * @deprecated Always `explicitRequestOnly`. Use `effort` for Ultra behavior.+ */+ multiAgentMode: MultiAgentMode;+ /**+ * @deprecated Reports the saved setting; `friendly` and `pragmatic` no longer select a style.+ */+ personality: Personality | null;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdateParams.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdateParams.tsnew file mode 100644index 00000000000..a4187c74947--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdateParams.ts@@ -0,0 +1,81 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { CollaborationMode } from '../CollaborationMode';+import type { MultiAgentMode } from '../MultiAgentMode';+import type { Personality } from '../Personality';+import type { ReasoningEffort } from '../ReasoningEffort';+import type { ReasoningSummary } from '../ReasoningSummary';+import type { ApprovalsReviewer } from './ApprovalsReviewer';+import type { AskForApproval } from './AskForApproval';+import type { SandboxPolicy } from './SandboxPolicy';+import type { TurnEnvironmentParams } from './TurnEnvironmentParams';++export type ThreadSettingsUpdateParams = {+ threadId: string;+ /**+ * Replace this thread's disabled plugin IDs.+ * Omitted/null preserves the list; [] clears it.+ */+ disabledPluginIds?: Array<string> | null;+ /**+ * Override the working directory for subsequent turns.+ */+ cwd?: string | null;+ /**+ * Replace the environments for future turns without changing the running turn.+ * Omitted/null preserves the selection unless `cwd` is also provided, which selects+ * the default environments for that directory. [] clears the selection.+ */+ environments?: Array<TurnEnvironmentParams> | null;+ /**+ * Override the approval policy for subsequent turns.+ */+ approvalPolicy?: AskForApproval | null;+ /**+ * Override where approval requests are routed for subsequent turns.+ */+ approvalsReviewer?: ApprovalsReviewer | null;+ /**+ * Override the sandbox policy for subsequent turns.+ */+ sandboxPolicy?: SandboxPolicy | null;+ /**+ * Select a named permissions profile id for subsequent turns. Cannot be+ * combined with `sandboxPolicy`.+ */+ permissions?: string | null;+ /**+ * Override the model for subsequent turns.+ */+ model?: string | null;+ /**+ * Override the service tier for subsequent turns. `null` clears the+ * current service tier; omission leaves it unchanged.+ */+ serviceTier?: string | null | null;+ /**+ * Override the reasoning effort for subsequent turns.+ */+ effort?: ReasoningEffort | null;+ /**+ * Override the reasoning summary for subsequent turns.+ */+ summary?: ReasoningSummary | null;+ /**+ * EXPERIMENTAL - Set a pre-set collaboration mode for subsequent turns.+ *+ * For `collaboration_mode.settings.developer_instructions`, `null` means+ * "use the built-in instructions for the selected mode".+ */+ collaborationMode?: CollaborationMode | null;+ /**+ * @deprecated Ignored. Use `effort: "ultra"` for proactive multi-agent behavior.+ */+ multiAgentMode?: MultiAgentMode | null;+ /**+ * @deprecated `friendly` and `pragmatic` no longer select a style.+ * Changing this does not rewrite the thread's existing instructions.+ */+ personality?: Personality | null;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdateResponse.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdateResponse.tsnew file mode 100644index 00000000000..06afb97597e--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdateResponse.ts@@ -0,0 +1,5 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++export type ThreadSettingsUpdateResponse = Record<string, never>;diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdatedNotification.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdatedNotification.tsnew file mode 100644index 00000000000..c03c81f927d--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/ThreadSettingsUpdatedNotification.ts@@ -0,0 +1,9 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { ThreadSettings } from './ThreadSettings';++export type ThreadSettingsUpdatedNotification = {+ threadId: string;+ threadSettings: ThreadSettings;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/TurnEnvironmentParams.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/TurnEnvironmentParams.tsnew file mode 100644index 00000000000..331b7ca4a05--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/v2/TurnEnvironmentParams.ts@@ -0,0 +1,13 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { LegacyAppPathString } from '../LegacyAppPathString';++export type TurnEnvironmentParams = {+ environmentId: string;+ cwd: LegacyAppPathString;+ /**+ * Environment-native runtime workspace roots. Omitted defaults to `cwd`.+ */+ runtimeWorkspaceRoots?: Array<LegacyAppPathString> | null;+};diff --git a/packages/heterogeneous-agents/src/codexPlanMode/index.test.ts b/packages/heterogeneous-agents/src/codexPlanMode/index.test.tsnew file mode 100644index 00000000000..ad564793977--- /dev/null+++ b/packages/heterogeneous-agents/src/codexPlanMode/index.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import {+ COLLABORATION_MODE_PHASE,+ collaborationModeReportPatch,+ isCollaborationModeReport,+} from '.';++describe('collaborationModeReportPatch', () => {+ it('writes nothing for a read-back that confirms the request', () => {+ // A user flip during the run must never be undone by the run's own report.+ expect(collaborationModeReportPatch({ collaborationMode: 'plan', requested: 'plan' })).toEqual(+ {},+ );+ });++ it('follows Codex where it disagrees with the request', () => {+ expect(+ collaborationModeReportPatch({ collaborationMode: 'default', requested: 'plan' }),+ ).toEqual({+ heteroPlanMode: false,+ });+ });+});++describe('isCollaborationModeReport', () => {+ it('accepts the phase with a known mode, and nothing else', () => {+ expect(isCollaborationModeReport({ phase: COLLABORATION_MODE_PHASE })).toBe(false);+ expect(+ isCollaborationModeReport({ collaborationMode: 'plan', phase: COLLABORATION_MODE_PHASE }),+ ).toBe(true);+ expect(+ isCollaborationModeReport({ collaborationMode: 'execute', phase: COLLABORATION_MODE_PHASE }),+ ).toBe(false);+ expect(isCollaborationModeReport({ phase: 'permission_mode' })).toBe(false);+ });+});diff --git a/packages/heterogeneous-agents/src/codexPlanMode/index.ts b/packages/heterogeneous-agents/src/codexPlanMode/index.tsnew file mode 100644index 00000000000..ae41b53596c--- /dev/null+++ b/packages/heterogeneous-agents/src/codexPlanMode/index.ts@@ -0,0 +1,57 @@+import type { ChatTopicMetadata, CodexCollaborationMode } from '@lobechat/types';+import { isCodexCollaborationMode } from '@lobechat/types';++/*+ * Browser-safe slice of the Codex Plan switch (Better Coding Experience lab):+ * the mode report a native Codex run emits and the topic patch it maps to.+ * The thread logic lives in `codex/CodexThreadSession` (Node only).+ */++/** `step_complete` phase carrying what a native Codex run reports about its collaboration mode. */+export const COLLABORATION_MODE_PHASE = 'collaboration_mode';++/** Tool api name of a completed Codex plan (`ThreadItem { type: 'plan' }`). */+export const CODEX_PROPOSED_PLAN_API_NAME = 'proposed_plan';++/** Plugin state of a `proposed_plan` tool message. */+export interface CodexProposedPlanState {+ plan: {+ /** False while `item/plan/delta` streams; the completed item replaces the text. */+ completed: boolean;+ text: string;+ };+}++export interface CollaborationModeReportData {+ /**+ * The mode Codex says the thread is in (`thread/settings/updated` after+ * `turn/start`, or a mid-run switch).+ */+ collaborationMode?: CodexCollaborationMode;+ phase: typeof COLLABORATION_MODE_PHASE;+ /** The mode this run asked for when Codex reported `collaborationMode`. */+ requested?: CodexCollaborationMode;+}++export const isCollaborationModeReport = (data: unknown): data is CollaborationModeReportData => {+ if (typeof data !== 'object' || data === null) return false;+ const record = data as Record<string, unknown>;+ return (+ record.phase === COLLABORATION_MODE_PHASE && isCodexCollaborationMode(record.collaborationMode)+ );+};++/**+ * The topic patch for a collaboration-mode report, shared by the server (runs+ * hosted by `lh hetero exec`) and the desktop renderer (local runs).+ *+ * The Plan switch follows Codex only where Codex disagrees with what the run+ * asked for; a report that merely confirms the request writes nothing, so it+ * can never undo a switch the user flipped while the run was going.+ */+export const collaborationModeReportPatch = (+ report: Pick<CollaborationModeReportData, 'collaborationMode' | 'requested'>,+): Pick<ChatTopicMetadata, 'heteroPlanMode'> =>+ report.collaborationMode && report.requested && report.collaborationMode !== report.requested+ ? { heteroPlanMode: report.collaborationMode === 'plan' }+ : {};diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.tsindex 5084a46d977..1729902bc87 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts@@ -113,4 +113,18 @@ describe('buildHeteroExecStdinPayload', () => {expect.arrayContaining([expect.objectContaining({ text: 'hello', type: 'text' })]),);});++ it('carries the Codex Plan switch in the envelope older lh releases unwrap', () => {+ const payload = JSON.parse(+ buildHeteroExecStdinPayload({ collaborationMode: 'default', prompt: 'hello' }),+ );+ expect(payload).toEqual({+ collaborationMode: 'default',+ content: [{ text: 'hello', type: 'text' }],+ });+ });++ it('keeps the historical plain shape without a Plan switch', () => {+ expect(buildHeteroExecStdinPayload({ prompt: 'hello' })).toBe(JSON.stringify('hello'));+ });});diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.tsindex b2f54e220bc..cbafb99704c 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts@@ -1,4 +1,4 @@-import type { HeteroPermissionMode } from '@lobechat/types';+import type { CodexCollaborationMode, HeteroPermissionMode } from '@lobechat/types';import { buildHeterogeneousPrompt } from './promptEngine';@@ -37,9 +37,11 @@ export interface HeteroExecImageRef {** `permissionMode` (Claude Code, Better Coding Experience lab) rides the same* envelope for the same reason: an `lh` that predates it unwraps `content` and- * keeps allowing everything, rather than failing on an unknown flag.+ * keeps allowing everything, rather than failing on an unknown flag. The+ * Codex Plan switch (`collaborationMode`) rides it for the same reason.*/export const buildHeteroExecStdinPayload = (params: {+ collaborationMode?: CodexCollaborationMode;imageList?: HeteroExecImageRef[];isNewSession?: boolean;permissionMode?: HeteroPermissionMode;@@ -48,6 +50,7 @@ export const buildHeteroExecStdinPayload = (params: {systemContext?: string;}): string => {const {+ collaborationMode,imageList = [],isNewSession,permissionMode,@@ -57,8 +60,9 @@ export const buildHeteroExecStdinPayload = (params: {} = params;const blocks = buildHeterogeneousPrompt({ imageList, isNewSession, prompt, systemContext });- if (resumeFallbackSystemContext !== undefined || permissionMode) {+ if (resumeFallbackSystemContext !== undefined || permissionMode || collaborationMode) {return JSON.stringify({+ ...(collaborationMode && { collaborationMode }),content: blocks,...(permissionMode && { permissionMode }),resumeFallback:diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex f65687f091f..d4a0dff7ea1 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -2,7 +2,7 @@ import type { ChildProcess } from 'node:child_process';import { platform } from 'node:os';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';-import type { HeteroPermissionMode } from '@lobechat/types';+import type { CodexCollaborationMode, HeteroPermissionMode } from '@lobechat/types';import { isHeteroPermissionMode } from '@lobechat/types';import { spawnManaged } from '@lobechat/utils/managedProcess';@@ -54,6 +54,11 @@ export interface SpawnAgentOptions {agentType: string;/** Bridge for bidirectional question requests emitted by ACP agents. */askUserBridge?: AskUserBridge;+ /**+ * (native Codex app-server only; `spawnAgent` ignores it) The Codex Plan+ * switch: the collaboration mode every turn sends.+ */+ collaborationMode?: CodexCollaborationMode;/*** Override the CLI binary name. Defaults to the agent's standard executable.* Use this when the binary lives at a non-default@@ -196,6 +201,11 @@ export interface SpawnAgentHandle {* server can persist it for `--resume` on the next turn.*/readonly sessionId: string | undefined;+ /**+ * (native Codex) The Codex Plan switch flipped mid-run: the thread takes the+ * collaboration mode from its next turn (`thread/settings/update`).+ */+ setCollaborationMode?: (mode: CodexCollaborationMode) => Promise<void>;/*** The child's stderr stream — caller can pipe to its own stderr or* collect for error reporting. The pipeline does not consume stderr.diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex a1481edf201..4a07456e8b5 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -709,6 +709,17 @@ export default {'heteroAgent.permissionMode.switchUnsupported':'lh on this device can’t switch a running session. The new mode applies from the next message; update lh to switch mid-run.','heteroAgent.permissionMode.saveFailed': 'Couldn’t save the permission mode. Try again.',+ 'heteroAgent.planMode.label': 'Plan',+ 'heteroAgent.planMode.tooltipOff':+ 'Plan first: Codex explores and proposes a plan instead of making changes. Codex still has full access. A new topic in this directory starts with your last choice.',+ 'heteroAgent.planMode.tooltipOn':+ 'Plan is on: Codex proposes a plan instead of making changes. Turn it off, or choose Execute plan, to let it carry the plan out.',+ 'heteroAgent.planMode.nextTurn': 'Applies from the next turn',+ 'heteroAgent.planMode.saveFailed': 'Couldn’t save the Plan setting. Try again.',+ 'heteroAgent.planMode.unavailable.appServerLab':+ 'Plan needs the Codex App Server Runtime. Turn it on in Settings → Labs.',+ 'heteroAgent.planMode.unavailable.unsupported':+ 'Plan isn’t available where this agent runs: it needs Codex app-server on this computer, or a device whose Codex and lh support it. Update lh on the device to use it.','heteroAgent.fullAccess.label': 'Full access','heteroAgent.fullAccess.tooltip':'The local coding agent runs with full read/write access to the working directory. Switching permission modes is not available yet.',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex ece857f37c9..7205bd14698 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -348,8 +348,13 @@ export default {'builtins.codex.apiName.image_output': 'Image result','builtins.codex.imageOutput.unavailable': 'The image could not be uploaded.','builtins.codex.apiName.mcp_tool_call': 'Call MCP tool',+ 'builtins.codex.apiName.proposed_plan': 'Plan','builtins.codex.apiName.todo_list': 'Update tasks','builtins.codex.apiName.web_search': 'Search the web',+ 'builtins.codex.proposedPlan.execute': 'Execute plan',+ 'builtins.codex.proposedPlan.discuss': 'Keep discussing',+ 'builtins.codex.proposedPlan.executeMessage': 'Execute the plan above.',+ 'builtins.codex.proposedPlan.failed': 'Couldn’t do that. Try again.','builtins.codex.collabTool.agentCount_one': '{{count}} subagent','builtins.codex.collabTool.agentCount_other': '{{count}} subagents','builtins.codex.collabTool.agentLabel': 'Subagent {{index}}',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 3d907358f83..3b442919830 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -30,6 +30,11 @@ export const initialTopicMetadataSchema = z.object({* Experience); the topic's first dispatched run starts in it.*/heteroPermissionMode: z.enum(HETERO_PERMISSION_MODES).optional(),+ /**+ * Codex Plan switch the composer showed (Better Coding Experience); the+ * topic's first native turn sends `plan` / `default` from it.+ */+ heteroPlanMode: z.boolean().optional(),repos: z.array(z.string()).optional(),/*** Cloud-sandbox placement the composer chose before any topic existed — andiff --git a/packages/types/src/agentExecution/initialTopicMetadata.test.ts b/packages/types/src/agentExecution/initialTopicMetadata.test.tsindex 144e4df300d..18e29205a14 100644--- a/packages/types/src/agentExecution/initialTopicMetadata.test.ts+++ b/packages/types/src/agentExecution/initialTopicMetadata.test.ts@@ -10,6 +10,7 @@ describe('initialTopicMetadataSchema', () => {// the assertion is on the parse rather than on any caller.const metadata = {heteroPermissionMode: 'plan' as const,+ heteroPlanMode: false,repos: ['lobehub/lobehub'],sandboxInstanceId: 'a2c1d0e4-0000-4000-8000-000000000000',sandboxWorkingDirectory: 'reports',diff --git a/packages/types/src/heteroPlanMode.ts b/packages/types/src/heteroPlanMode.tsnew file mode 100644index 00000000000..e0a4eaccb17--- /dev/null+++ b/packages/types/src/heteroPlanMode.ts@@ -0,0 +1,51 @@+import { applyWorktreeModeDir } from './worktreeMode';++/**+ * Codex collaboration modes the Plan switch (Better Coding Experience lab)+ * moves a native Codex thread between. Plan is not a permission mode: Codex+ * keeps allowing every action either way.+ */+export const CODEX_COLLABORATION_MODES = ['plan', 'default'] as const;++export type CodexCollaborationMode = (typeof CODEX_COLLABORATION_MODES)[number];++export const isCodexCollaborationMode = (value: unknown): value is CodexCollaborationMode =>+ typeof value === 'string' && (CODEX_COLLABORATION_MODES as readonly string[]).includes(value);++/**+ * Device capability an `lh` advertises (next to `codex-app-server-v1`) when it+ * takes the Plan switch: the `--input-json` envelope's `collaborationMode` and+ * the `set_collaboration_mode` control command.+ * An older `lh` ignores both, so the switch is unavailable on its device.+ */+export const CODEX_COLLABORATION_MODE_RUNTIME = 'codex-collaboration-mode-v1';++/**+ * The collaboration mode a topic's Codex run sends, or undefined when the+ * topic never turned Plan on (then nothing is sent, exactly as before the lab).+ */+export const codexCollaborationModeOf = (+ planMode: boolean | null | undefined,+): CodexCollaborationMode | undefined =>+ typeof planMode === 'boolean' ? (planMode ? 'plan' : 'default') : undefined;++/**+ * The "Execute plan / Keep discussing" decision under a Codex plan block: the+ * plan item it belongs to and whether the user put the buttons away.+ */+export interface CodexPlanDecision {+ dismissed: boolean;+ /** The plan item (tool call id) the decision belongs to. */+ itemId: string;+}++/**+ * The per-directory Plan switch a new Codex topic starts with, remembered like+ * the "New worktree" switch (same `getWorktreeModeKey` key, same bucket). Only+ * "on" is stored; off is the default.+ */+export const applyHeteroPlanModeDir = (+ current: readonly string[] | undefined,+ key: string,+ enabled: boolean,+): string[] => applyWorktreeModeDir(current, key, enabled);diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 77941801428..f2ae8dbe7a8 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -106,6 +106,7 @@ export * from './artboardReadiness';export * from './connector';export * from './connectorToolIdentifier';export * from './heteroPermissionMode';+export * from './heteroPlanMode';export * from './inboundWebhook';export * from './oauthApp';export * from './openai/chat';diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 30b8a0b0ca9..f88c796cf69 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -12,6 +12,7 @@ import type { WorkingDirConfig } from '../device';import { workingDirConfigSchema } from '../device';import type { HeteroPermissionMode, HeteroPermissionModeFallback } from '../heteroPermissionMode';import { HETERO_PERMISSION_MODES } from '../heteroPermissionMode';+import type { CodexPlanDecision } from '../heteroPlanMode';import type { BotSenderMetadata } from '../message';import type { BaseDataModel } from '../meta';import type { OwnedWorktree } from '../ownedWorktree';@@ -193,6 +194,8 @@ export interface ChatTopicMetadata {botCreator?: BotSenderMetadata | null;boundDeviceId?: string;+ /** The Execute plan / Keep discussing buttons under the latest Codex plan. */+ codexPlanDecision?: CodexPlanDecision | null;cronJobId?: string;/*** The conversation's device was chosen explicitly for it (the composer's@@ -267,6 +270,14 @@ export interface ChatTopicMetadata {* that `lh` predates permission modes (`outdatedCli`). Server-written only.*/heteroPermissionModeReportPending?: string | null;+ /**+ * Codex Plan switch of this topic (Better Coding Experience lab). Absent+ * until the user first turns it on: such a topic sends no collaboration+ * mode at all. Once set, every native turn sends `plan` (true) or+ * `default` (false) explicitly. Codex keeps the mode on the thread, so only+ * the user turns it off (the switch, or Execute plan).+ */+ heteroPlanMode?: boolean;/** Latest Task run's dispatched settings; no args, credentials or system context. */heteroRuntimeConfig?: {/** Per-field configuration and provenance captured before dispatch. */@@ -757,6 +768,11 @@ export const chatTopicMetadataUpdateSchema = z.object({heteroSessionIdByWorkingDirectory: z.record(z.string(), z.string()).optional(),heteroPermissionMode: z.enum(HETERO_PERMISSION_MODES).optional(),heteroPermissionModeFallback: z.enum(['outdatedCli', 'root']).nullable().optional(),+ heteroPlanMode: z.boolean().optional(),+ codexPlanDecision: z+ .object({ dismissed: z.boolean(), itemId: z.string().min(1) })+ .nullable()+ .optional(),heteroSpeed: z.enum(['default', 'normal', 'fast', 'ultrafast']).optional(),model: z.string().optional(),onboardingFeedback: zdiff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 0f1c3a47bab..ec9e3fb0f29 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -75,6 +75,12 @@ export interface WorkspaceUserPreference {* through `workspaceUserSettings.setHeteroPermissionModeDir`.*/heteroPermissionModeDirs?: HeteroPermissionModeDir[];+ /**+ * Directories (`getWorktreeModeKey`) where this member last left the Codex+ * Plan switch on, which a new Codex topic there starts with. Most recent+ * first and capped; written only through `workspaceUserSettings.setHeteroPlanModeDir`.+ */+ heteroPlanModeDirs?: string[];/*** This member's notification preferences for workspace-scoped scenarios* (the `workspace` category of the scenario registry). Same shape as the@@ -353,6 +359,12 @@ export interface UserPreference {* schema for the same reason as `worktreeModeDirs`.*/heteroPermissionModeDirs?: HeteroPermissionModeDir[];+ /**+ * Personal-mode counterpart of {@link WorkspaceUserPreference.heteroPlanModeDirs};+ * written only through `user.setHeteroPlanModeDir`, absent from the schema+ * for the same reason as `worktreeModeDirs`.+ */+ heteroPlanModeDirs?: string[];hideSyncAlert?: boolean;/*** lab experimental featuresdiff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsxnew file mode 100644index 00000000000..201175e469b--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsx@@ -0,0 +1,77 @@+'use client';++import { Button, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ClipboardList } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { usePlanMode } from './usePlanMode';++const styles = stylex.create({+ // Hidden on a narrow bar like the other chips' labels; the tooltip still names it.+ label: {+ display: {+ 'default': null,+ '@container runtimebar (width < 600px)': 'none',+ },+ },+ nextTurn: { fontSize: '12px', color: cssVar.colorTextDescription, whiteSpace: 'nowrap' },+ off: { fontSize: cssVar.fontSizeSM, color: cssVar.colorTextSecondary },+ on: {+ fontSize: cssVar.fontSizeSM,+ color: cssVar.colorPrimary,+ backgroundColor: cssVar.colorPrimaryBg,+ backgroundImage: 'none',+ },+});++interface PlanModeSwitchProps {+ agentId: string;+ topicId: string | null | undefined;+}++/**+ * The composer's Codex Plan switch (Better Coding Experience lab). Not a+ * permission mode: Codex keeps allowing every action; in plan it proposes a+ * plan instead of carrying the request out.+ */+const PlanModeSwitch = ({ agentId, topicId }: PlanModeSwitchProps) => {+ const { t } = useTranslation('chat');+ const { enabled, nextTurnPending, setEnabled, unavailable } = usePlanMode(agentId, topicId);++ const tooltip = unavailable+ ? t(`heteroAgent.planMode.unavailable.${unavailable}`)+ : t(enabled ? 'heteroAgent.planMode.tooltipOn' : 'heteroAgent.planMode.tooltipOff');++ return (+ <Flexbox horizontal align={'center'} data-testid={'hetero-plan-mode'} gap={6}>+ {nextTurnPending && (+ <span data-testid={'hetero-plan-mode-next-turn'} {...stylex.props(styles.nextTurn)}>+ {t('heteroAgent.planMode.nextTurn')}+ </span>+ )}+ <Tooltip title={tooltip}>+ {/* The wrapper keeps the tooltip on a disabled button. */}+ <span>+ <Button+ aria-label={t('heteroAgent.planMode.label')}+ aria-pressed={enabled}+ className={stylex.props(enabled && !unavailable ? styles.on : styles.off).className}+ disabled={!!unavailable}+ size="small"+ type={'text'}+ onClick={() => void setEnabled(!enabled)}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={ClipboardList} size={14} />+ <span {...stylex.props(styles.label)}>{t('heteroAgent.planMode.label')}</span>+ </Flexbox>+ </Button>+ </span>+ </Tooltip>+ </Flexbox>+ );+};++export default PlanModeSwitch;diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.test.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.test.tsnew file mode 100644index 00000000000..611510e7dde--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { resolvePlanModeAvailability } from './usePlanMode';++describe('resolvePlanModeAvailability', () => {+ const base = { appServerLab: true, executionTarget: 'local' };++ it('is available for a local run with the Codex app-server lab on', () => {+ expect(resolvePlanModeAvailability(base)).toBeUndefined();+ });++ it('needs the Codex app-server lab', () => {+ expect(resolvePlanModeAvailability({ ...base, appServerLab: false })).toBe('appServerLab');+ });++ it('is unavailable where Codex runs through exec: API auth, the cloud sandbox', () => {+ expect(resolvePlanModeAvailability({ ...base, authMode: 'api' })).toBe('unsupported');+ expect(resolvePlanModeAvailability({ ...base, executionTarget: 'sandbox' })).toBe(+ 'unsupported',+ );+ });++ it('is unavailable for provider arguments only codex exec honors', () => {+ expect(resolvePlanModeAvailability({ ...base, providerArgs: ['--profile', 'work'] })).toBe(+ 'unsupported',+ );+ expect(+ resolvePlanModeAvailability({ ...base, providerArgs: ['-m', 'gpt-6.1-sol'] }),+ ).toBeUndefined();+ });++ it('needs a device whose lh takes the switch', () => {+ const device = { ...base, executionTarget: 'device' };+ expect(+ resolvePlanModeAvailability({+ ...device,+ deviceRuntimes: ['codex-app-server-v1', 'codex-collaboration-mode-v1'],+ }),+ ).toBeUndefined();+ // An older lh advertises the app-server but not the switch.+ expect(+ resolvePlanModeAvailability({ ...device, deviceRuntimes: ['codex-app-server-v1'] }),+ ).toBe('unsupported');+ expect(resolvePlanModeAvailability(device)).toBe('unsupported');+ });+});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.tsnew file mode 100644index 00000000000..bfe2b4a4c82--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.ts@@ -0,0 +1,200 @@+import { isDesktop } from '@lobechat/const';+import { getCodexAppServerUnsupportedArgs } from '@lobechat/heterogeneous-agents/codexAppServerArgs';+import { CODEX_COLLABORATION_MODE_RUNTIME, getWorktreeModeKey } from '@lobechat/types';+import { toast } from '@lobehub/ui';+import { useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';+import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';+import { aiAgentService } from '@/services/aiAgent';+import { useChatStore } from '@/store/chat';+import { findRunningServerOperationId } from '@/store/chat/heteroPermissionMode';+import {+ getLocalCollaborationModeSwitcher,+ setPendingHeteroPlanMode,+} from '@/store/chat/heteroPlanMode';+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';+import { useAgentRunRuntimes } from '@/store/device/agentRunRuntimes/store';+import { useElectronStore } from '@/store/electron';+import { useUserStore } from '@/store/user';+import type { UserState } from '@/store/user/initialState';+import { labPreferSelectors } from '@/store/user/selectors';++/** Why the switch cannot be used here, as the tooltip explains it. */+export type PlanModeUnavailableReason = 'appServerLab' | 'unsupported';++/**+ * The remembered switches of whoever is acting now (workspace bucket, or+ * `users.preference` in personal mode); `undefined` while the bucket loads.+ */+const selectPlanModeDirs =+ (workspaceId: string | null | undefined) =>+ (state: UserState): string[] | undefined => {+ if (!workspaceId) return state.preference.heteroPlanModeDirs ?? [];+ return state.workspaceUserPreferenceWorkspaceId === workspaceId+ ? (state.workspaceUserPreference.heteroPlanModeDirs ?? [])+ : undefined;+ };++/**+ * Whether the Plan switch can reach Codex where this agent runs: the native+ * app-server, which needs its lab and arguments it can honor, and — on a+ * connected device — an `lh` that takes the switch (`codex-collaboration-mode-v1`).+ * The cloud sandbox, API auth and such arguments run `codex exec`, which has no+ * collaboration mode. Only the switch grays out: a topic keeps its choice.+ */+export const resolvePlanModeAvailability = ({+ appServerLab,+ authMode,+ deviceRuntimes,+ executionTarget,+ providerArgs,+}: {+ appServerLab: boolean;+ authMode?: string;+ /** The Codex provider's arguments: some (e.g. `--profile`) keep a run on `codex exec`. */+ providerArgs?: readonly string[];+ /** The device's agent-run runtimes; undefined while unknown. */+ deviceRuntimes?: readonly string[];+ executionTarget: string;+}): PlanModeUnavailableReason | undefined => {+ if (!appServerLab) return 'appServerLab';+ if (authMode === 'api') return 'unsupported';+ if (getCodexAppServerUnsupportedArgs([...(providerArgs ?? [])]).length > 0) return 'unsupported';+ if (executionTarget === 'local') return;+ if (executionTarget === 'device' && deviceRuntimes?.includes(CODEX_COLLABORATION_MODE_RUNTIME))+ return;+ return 'unsupported';+};++export interface PlanModeState {+ enabled: boolean;+ /** The switch flipped while this run goes: Codex takes it from the next turn. */+ nextTurnPending: boolean;+ setEnabled: (enabled: boolean) => Promise<void>;+ unavailable?: PlanModeUnavailableReason;+}++/**+ * The composer's Codex Plan switch (Better Coding Experience lab).+ *+ * - An existing topic shows its own `heteroPlanMode`; flipping it writes the+ * topic and, mid-run, tells the live thread, which takes it from the next turn.+ * - A new topic shows the switch last left for this device + directory, and is+ * born with it when it is on or was flipped here.+ *+ * Every flip is remembered for the directory, per workspace + user.+ */+export const usePlanMode = (agentId: string, topicId: string | null | undefined): PlanModeState => {+ const { t } = useTranslation('chat');+ const workspaceId = useActiveWorkspaceId();+ useUserStore((s) => s.useFetchWorkspaceUserPreference)();+ const dirs = useUserStore(selectPlanModeDirs(workspaceId));+ const setPlanModeDir = useUserStore((s) => s.setHeteroPlanModeDir);+ const appServerLab = useUserStore(labPreferSelectors.enableCodexAppServer);++ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, { workspaceScoped });+ const directory =+ getWorkingDirectoryPathString(useEffectiveWorkingDirectory(agentId, { topicId })) ?? '';+ const key = getWorktreeModeKey(targetDeviceId ?? 'local', directory);+ const executionTarget = resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ isHetero: true,+ workspaceScoped,+ });+ const runtimeDeviceId =+ executionTarget === 'device' && appServerLab ? agencyConfig?.boundDeviceId : undefined;+ const runtimes = useAgentRunRuntimes(runtimeDeviceId);+ const unavailable = resolvePlanModeAvailability({+ appServerLab,+ authMode: agencyConfig?.heterogeneousProvider?.authMode,+ providerArgs: agencyConfig?.heterogeneousProvider?.args,+ deviceRuntimes: runtimes,+ executionTarget,+ });++ const metadata = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,+ );+ const liveRun = useChatStore((s) =>+ topicId ? operationSelectors.isAgentRuntimeRunningByContext({ agentId, topicId })(s) : false,+ );+ // A run hosted by `lh` that this window did not start (a reload) is only on the topic.+ const running = liveRun || !!metadata?.runningOperation;+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);++ const remembered = !!dirs?.includes(key);+ // `undefined` until the user flips it in this composer: a new topic born off+ // inherits only an "on" it remembers, so it sends no mode at all.+ const [flipped, setFlipped] = useState<boolean | undefined>();+ const enabled = topicId ? metadata?.heteroPlanMode === true : (flipped ?? remembered);++ // Flipped during the run that is going now; cleared once that run ends.+ const [flippedDuringRun, setFlippedDuringRun] = useState(false);+ useEffect(() => {+ if (!running) setFlippedDuringRun(false);+ }, [running]);+ useEffect(() => {+ setFlipped(undefined);+ setFlippedDuringRun(false);+ }, [topicId, key]);++ // A topic created from this composer is born with what it shows. Not cleared+ // on unmount: the send switches the composer to the new topic first.+ useEffect(() => {+ if (topicId) return;+ setPendingHeteroPlanMode(+ agentId,+ unavailable ? undefined : (flipped ?? (remembered || undefined)),+ );+ }, [agentId, flipped, remembered, topicId, unavailable]);++ const setEnabled = useCallback(+ async (next: boolean) => {+ void setPlanModeDir(key, next).catch((error) => {+ console.error('[usePlanMode] remembering the switch failed', error);+ toast.error(t('heteroAgent.planMode.saveFailed'));+ });+ if (!topicId) {+ setFlipped(next);+ return;+ }+ try {+ await updateTopicMetadata(topicId, { heteroPlanMode: next });+ } catch (error) {+ console.error('[usePlanMode] save failed', error);+ toast.error(t('heteroAgent.planMode.saveFailed'));+ return;+ }+ if (!running) return;+ setFlippedDuringRun(true);+ const mode = next ? 'plan' : 'default';+ // Best effort: the topic already has the pick, and the next run sends it.+ const local = getLocalCollaborationModeSwitcher(topicId);+ if (local) {+ await local(mode).catch(() => {});+ return;+ }+ const state = useChatStore.getState();+ const operationId = findRunningServerOperationId(state, topicId, metadata);+ if (operationId) {+ await aiAgentService.setHeteroCollaborationMode({ mode, operationId }).catch(() => {});+ }+ },+ [key, metadata, running, setPlanModeDir, t, topicId, updateTopicMetadata],+ );++ return {+ enabled,+ nextTurnPending: running && flippedDuringRun,+ setEnabled,+ unavailable,+ };+};diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex f4ec8811c23..c4a732e1e45 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx@@ -28,6 +28,7 @@ import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';import PermissionModeSelector from './PermissionMode';+import PlanModeSwitch from './PlanMode';import {AntigravityQuotaMenu,ClaudeCodeQuotaMenu,@@ -178,6 +179,11 @@ const HeteroControlBar = memo(() => {betterCoding && heteroProvider?.type === 'claude-code' && agentId ? (<PermissionModeSelector agentId={agentId} topicId={topicId} />) : null;+ // Codex under the lab gets a Plan switch beside its unchanged full access.+ const planModeSwitch =+ betterCoding && heteroProvider?.type === 'codex' && agentId ? (+ <PlanModeSwitch agentId={agentId} topicId={topicId} />+ ) : null;const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,isHetero: !!heteroProvider,@@ -230,6 +236,7 @@ const HeteroControlBar = memo(() => {<DeviceSwitcher agentId={agentId} /><Flexbox horizontal align={'center'} gap={4}>{permissionModeChip}+ {planModeSwitch}{shouldShowApiCredits && <ChatInputCredits />}</Flexbox></Flexbox>@@ -259,6 +266,7 @@ const HeteroControlBar = memo(() => {<WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox>{(permissionModeChip ||+ planModeSwitch ||shouldShowApiCredits ||(shouldShowClaudeQuota && quotaDeviceId) ||(shouldShowCodexQuota && quotaDeviceId) ||@@ -271,6 +279,7 @@ const HeteroControlBar = memo(() => {gap={4}>{permissionModeChip}+ {planModeSwitch}{shouldShowApiCredits && <ChatInputCredits />}{shouldShowAntigravityQuota && quotaDeviceId && (<AntigravityQuotaMenu@@ -388,6 +397,7 @@ const HeteroControlBar = memo(() => {<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />)}{sdkRuntimeBadge}+ {planModeSwitch}{permissionModeChip ?? (<Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>)}diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.tsindex e75e7dfa257..0ce3413ecca 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.test.ts@@ -7,6 +7,7 @@ import { describe, expect, it } from 'vitest';import {getBreakoutPredicate,isBreakoutTool,+ isDeliverableTool,isImageBearingTool,isImageOutputTool,isImageReadTool,@@ -178,3 +179,19 @@ describe('getBreakoutPredicate', () => {expect(getBreakoutPredicate({ enableMcpApps: true, showImageReads: false })(mcpApp)).toBe(true);});});++describe('Codex proposed plan', () => {+ const plan = { apiName: 'proposed_plan', id: 'plan-1', identifier: 'codex' } as any;++ it('is the turn deliverable, so a finished turn keeps it out of the fold', () => {+ expect(isDeliverableTool(plan)).toBe(true);+ expect(isDeliverableTool({ ...plan, apiName: 'command_execution' })).toBe(false);+ });++ it('breaks out of a collapsed run whatever the image setting', () => {+ expect(isBreakoutTool(plan)).toBe(true);+ expect(getBreakoutPredicate({ showImageReads: false })(plan)).toBe(true);+ expect(getBreakoutPredicate({ enableMcpApps: true })(plan)).toBe(true);+ expect(getBreakoutPredicate({})({ ...plan, identifier: 'claude-code' })).toBe(false);+ });+});diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.tsindex d82cf95d88c..d963d9d8b3c 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts@@ -55,6 +55,13 @@ export const isImageOutputTool = (tool: ChatToolPayloadWithResult): boolean => {);};+/**+ * A plan Codex proposed in plan mode (`proposed_plan`): the turn delivers the+ * plan, and its Execute plan / Keep discussing buttons, so neither folds away.+ */+export const isProposedPlanTool = (tool: ChatToolPayloadWithResult): boolean =>+ tool.identifier === 'codex' && tool.apiName === 'proposed_plan';+const deliverableTools = new Set<string>();export const registerDeliverableTool = (identifier: string) => {@@ -62,7 +69,7 @@ export const registerDeliverableTool = (identifier: string) => {};export const isDeliverableTool = (tool: ChatToolPayloadWithResult): boolean =>- isImageOutputTool(tool) || deliverableTools.has(tool.identifier);+ isImageOutputTool(tool) || isProposedPlanTool(tool) || deliverableTools.has(tool.identifier);/*** Any tool whose result carries an image, output or read. Drives the workflow@@ -82,7 +89,7 @@ export const isMcpAppTool = (tool: ChatToolPayloadWithResult): boolean =>/** Tools that surface on their own between collapsed workflow runs. */export const isBreakoutTool = (tool: ChatToolPayloadWithResult): boolean =>- isImageBearingTool(tool) || isMcpAppTool(tool);+ isImageBearingTool(tool) || isMcpAppTool(tool) || isProposedPlanTool(tool);/*** A tool that only READ an image (Claude Code `Read`, `readFile`, a browser@@ -110,6 +117,8 @@ export const getBreakoutPredicate = ({showImageReads = true,}: BreakoutToolOptions): ((tool: ChatToolPayloadWithResult) => boolean) => {const isImageBreakout = showImageReads ? isImageBearingTool : isImageOutputTool;+ const isOutputBreakout = (tool: ChatToolPayloadWithResult) =>+ isImageBreakout(tool) || isProposedPlanTool(tool);- return enableMcpApps ? (tool) => isImageBreakout(tool) || isMcpAppTool(tool) : isImageBreakout;+ return enableMcpApps ? (tool) => isOutputBreakout(tool) || isMcpAppTool(tool) : isOutputBreakout;};diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 7fd2e3a3120..59342db6b7e 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -2,6 +2,7 @@ import type { AgentStreamClientFeature } from '@lobechat/agent-gateway-client';import { CLIENT_PROTOCOL_VERSION } from '@lobechat/agent-gateway-client';import type {ClientLlmWaitItem,+ CodexCollaborationMode,ComposerUserMessage,ContextSelection,ExecAgentAppContext,@@ -498,6 +499,11 @@ class AiAgentService {return await lambdaClient.aiAgent.setHeteroPermissionMode.mutate(params);}+ /** Flip the Codex Plan switch of a run hosted by `lh hetero exec`; it applies next turn. */+ async setHeteroCollaborationMode(params: { mode: CodexCollaborationMode; operationId: string }) {+ return await lambdaClient.aiAgent.setHeteroCollaborationMode.mutate(params);+ }+/*** Interrupt a running task*/diff --git a/src/services/device.ts b/src/services/device.tsindex b0fce3dcf92..ef853bb21eb 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -153,6 +153,11 @@ class DeviceService {return lambdaClient.device.getDeviceSystemInfo.query(input);}+ /** Native runtimes of the connection an agent run on the device reaches. */+ getAgentRunRuntimes(input: Parameters<DeviceClient['getAgentRunRuntimes']['query']>[0]) {+ return lambdaClient.device.getAgentRunRuntimes.query(input);+ }+/** Where the device's desktop app update stands; never starts a check. */getAppUpdateState(input: Parameters<DeviceClient['getAppUpdateState']['query']>[0]) {return lambdaClient.device.getAppUpdateState.query(input);diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex fae34539c2a..4abb738135d 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -15,6 +15,7 @@ import type {AntigravityQuotaSnapshot,} from '@lobechat/heterogeneous-agents/quota';import type {+ CodexCollaborationMode,HeterogeneousAgentModelCatalog,HeteroPermissionMode,HeteroSessionImportMessage,@@ -58,6 +59,8 @@ class HeterogeneousAgentService {operationId: string;/** Claude Code permission mode (Better Coding Experience lab); absent allows everything. */permissionMode?: HeteroPermissionMode;+ /** Codex Plan switch (Better Coding Experience lab); absent sends no collaboration mode. */+ collaborationMode?: CodexCollaborationMode;prompt: string;/*** Replay the session's on-disk transcript instead of spawning the CLI.@@ -105,6 +108,11 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.setPermissionMode({ mode, sessionId });}+ /** Flip a local native Codex thread's Plan switch; it applies from the next turn. */+ async setCollaborationMode(sessionId: string, mode: CodexCollaborationMode) {+ return this.ipc.heterogeneousAgent.setCollaborationMode({ mode, sessionId });+ }+async stopSession(sessionId: string) {return this.ipc.heterogeneousAgent.stopSession({ sessionId });}diff --git a/src/services/user/index.ts b/src/services/user/index.tsindex 4e88d55066f..ace56984a16 100644--- a/src/services/user/index.ts+++ b/src/services/user/index.ts@@ -140,6 +140,10 @@ export class UserService {return lambdaClient.user.setWorktreeModeDir.mutate({ enabled, key });};+ /** Personal-mode Codex Plan switch for one directory; resolves to the stored list. */+ setHeteroPlanModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ lambdaClient.user.setHeteroPlanModeDir.mutate({ enabled, key });+/** Personal-mode Claude Code permission mode for one directory; resolves to the stored list. */setHeteroPermissionModeDir = async (key: string,diff --git a/src/services/workspaceUserSettings.ts b/src/services/workspaceUserSettings.tsindex 57074e9f012..b1f5e594a38 100644--- a/src/services/workspaceUserSettings.ts+++ b/src/services/workspaceUserSettings.ts@@ -25,6 +25,10 @@ export class WorkspaceUserSettingsService {setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> =>lambdaClient.workspaceUserSettings.setWorktreeModeDir.mutate({ enabled, key });+ /** This member's Codex Plan switch for one directory; resolves to the stored list. */+ setHeteroPlanModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ lambdaClient.workspaceUserSettings.setHeteroPlanModeDir.mutate({ enabled, key });+/** This member's Claude Code permission mode for one directory; resolves to the stored list. */setHeteroPermissionModeDir = async (key: string,diff --git a/src/store/chat/heteroPlanMode.test.ts b/src/store/chat/heteroPlanMode.test.tsnew file mode 100644index 00000000000..dfd47037534--- /dev/null+++ b/src/store/chat/heteroPlanMode.test.ts@@ -0,0 +1,205 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ applyCollaborationModeReport,+ dismissCodexPlan,+ executeCodexPlan,+ pendingHeteroPlanModeMetadata,+ resolveRunCollaborationMode,+ setPendingHeteroPlanMode,+ shouldShowCodexPlanDecision,+} from './heteroPlanMode';++const lab = vi.hoisted(() => ({ appServer: true, betterCoding: true }));++vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));+vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: {+ enableBetterCodingExperience: () => lab.betterCoding,+ enableCodexAppServer: () => lab.appServer,+ },+}));++const storeWith = (metadata: Record<string, unknown> | undefined) => {+ const updateTopicMetadata = vi.fn(async () => {});+ const internal_dispatchTopic = vi.fn();+ const state = {+ internal_dispatchTopic,+ topicDataMap: metadata ? { k: { items: [{ id: 't', metadata }] } } : {},+ updateTopicMetadata,+ };+ return { get: () => state as any, internal_dispatchTopic, updateTopicMetadata };+};++describe('resolveRunCollaborationMode (local runs)', () => {+ beforeEach(() => {+ lab.appServer = true;+ lab.betterCoding = true;+ });++ it('sends nothing for a topic that never turned Plan on, or another agent', () => {+ expect(resolveRunCollaborationMode('codex', {})).toBeUndefined();+ expect(resolveRunCollaborationMode('claude-code', { heteroPlanMode: true })).toBeUndefined();+ });++ it('sends plan or default explicitly once the topic used Plan', () => {+ expect(resolveRunCollaborationMode('codex', { heteroPlanMode: true })).toBe('plan');+ expect(resolveRunCollaborationMode('codex', { heteroPlanMode: false })).toBe('default');+ });++ it('sends nothing when either lab is off', () => {+ for (const off of ['appServer', 'betterCoding'] as const) {+ lab.appServer = true;+ lab.betterCoding = true;+ lab[off] = false;+ expect(resolveRunCollaborationMode('codex', { heteroPlanMode: true })).toBeUndefined();+ }+ });+});++describe('pendingHeteroPlanModeMetadata (new topics)', () => {+ beforeEach(() => {+ lab.appServer = true;+ lab.betterCoding = true;+ });++ it('hands over the switch the composer showed, off included, with the labs on', () => {+ setPendingHeteroPlanMode('agt', false);+ expect(pendingHeteroPlanModeMetadata('agt', 'codex')).toEqual({ heteroPlanMode: false });+ setPendingHeteroPlanMode('agt', true);+ expect(pendingHeteroPlanModeMetadata('agt', 'codex')).toEqual({ heteroPlanMode: true });+ lab.appServer = false;+ expect(pendingHeteroPlanModeMetadata('agt', 'codex')).toEqual({});+ lab.appServer = true;+ setPendingHeteroPlanMode('agt', undefined);+ expect(pendingHeteroPlanModeMetadata('agt', 'codex')).toEqual({});+ });+});++describe('applyCollaborationModeReport', () => {+ it('leaves a switch the user flipped mid-run alone when Codex only confirms the request', async () => {+ const store = storeWith({ heteroPlanMode: false });+ await applyCollaborationModeReport(+ store.get,+ 't',+ { collaborationMode: 'plan', requested: 'plan' },+ { persist: true },+ );+ expect(store.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('follows Codex where it disagrees with the request, writing a local run', async () => {+ const store = storeWith({ heteroPlanMode: true });+ await applyCollaborationModeReport(+ store.get,+ 't',+ { collaborationMode: 'default', requested: 'plan' },+ { persist: true },+ );+ expect(store.updateTopicMetadata).toHaveBeenCalledWith('t', { heteroPlanMode: false });+ });++ it('follows the server-written report in memory for a run hosted by lh', async () => {+ const store = storeWith({ heteroPlanMode: true });+ await applyCollaborationModeReport(+ store.get,+ 't',+ { collaborationMode: 'default', requested: 'plan' },+ { persist: false },+ );+ expect(store.updateTopicMetadata).not.toHaveBeenCalled();+ expect(store.internal_dispatchTopic).toHaveBeenCalledWith(+ expect.objectContaining({ value: { metadata: { heteroPlanMode: false } } }),+ );+ });+});++describe('shouldShowCodexPlanDecision', () => {+ const plan = (id: string) => ({+ plugin: { apiName: 'proposed_plan', identifier: 'codex' },+ role: 'tool',+ tool_call_id: id,+ });+ const messages = [{ role: 'user' }, { role: 'assistant' }, plan('p1'), { role: 'assistant' }];+ const show = (overrides: Partial<Parameters<typeof shouldShowCodexPlanDecision>[0]> = {}) =>+ shouldShowCodexPlanDecision({+ messages,+ metadata: { heteroPlanMode: true },+ running: false,+ toolCallId: 'p1',+ ...overrides,+ });++ beforeEach(() => {+ lab.appServer = true;+ lab.betterCoding = true;+ });++ it('shows under the latest plan once the topic is idle with Plan on', () => {+ expect(show()).toBe(true);+ });++ it('hides while the topic runs, with Plan off, or once dismissed', () => {+ expect(show({ running: true })).toBe(false);+ expect(show({ metadata: { heteroPlanMode: false } })).toBe(false);+ expect(+ show({+ metadata: { codexPlanDecision: { dismissed: true, itemId: 'p1' }, heteroPlanMode: true },+ }),+ ).toBe(false);+ // A dismissal of an older plan does not hide a newer one.+ expect(+ show({+ metadata: { codexPlanDecision: { dismissed: true, itemId: 'p0' }, heteroPlanMode: true },+ }),+ ).toBe(true);+ });++ it('hides after the user wrote again or a newer plan arrived', () => {+ expect(show({ messages: [...messages, { role: 'user' }] })).toBe(false);+ expect(show({ messages: [...messages, plan('p2')] })).toBe(false);+ });++ it('hides with either lab off', () => {+ lab.appServer = false;+ expect(show()).toBe(false);+ });+});++describe('plan decision', () => {+ it('executes by turning Plan off before the message that carries the plan out', async () => {+ const order: string[] = [];+ const updateTopicMetadata = vi.fn(async (_id: string, patch: unknown) => {+ order.push(`update:${JSON.stringify(patch)}`);+ });+ const sendMessage = vi.fn(async ({ message }: { message: string }) => {+ order.push(`send:${message}`);+ });+ // A draft the user typed meanwhile is not what this sends: keep it.++ await executeCodexPlan({+ message: 'Execute the plan above.',+ sendMessage,+ toolCallId: 'p1',+ topicId: 't',+ updateTopicMetadata,+ });++ expect(order).toEqual([+ 'update:{"codexPlanDecision":{"dismissed":true,"itemId":"p1"},"heteroPlanMode":false}',+ 'send:Execute the plan above.',+ ]);+ expect(sendMessage).toHaveBeenCalledWith({+ message: 'Execute the plan above.',+ preserveComposer: true,+ });+ });++ it('keeps discussing by only putting the buttons away', async () => {+ const updateTopicMetadata = vi.fn(async () => {});+ await dismissCodexPlan({ toolCallId: 'p1', topicId: 't', updateTopicMetadata });+ expect(updateTopicMetadata).toHaveBeenCalledWith('t', {+ codexPlanDecision: { dismissed: true, itemId: 'p1' },+ });+ });+});diff --git a/src/store/chat/heteroPlanMode.ts b/src/store/chat/heteroPlanMode.tsnew file mode 100644index 00000000000..bd037073bf1--- /dev/null+++ b/src/store/chat/heteroPlanMode.ts@@ -0,0 +1,206 @@+import {+ CODEX_PROPOSED_PLAN_API_NAME,+ type CollaborationModeReportData,+ collaborationModeReportPatch,+} from '@lobechat/heterogeneous-agents/codexPlanMode';+import type { ChatTopicMetadata, CodexCollaborationMode } from '@lobechat/types';+import { codexCollaborationModeOf } from '@lobechat/types';++import { topicSelectors } from '@/store/chat/selectors';+import type { ChatStore } from '@/store/chat/store';+import { getUserStoreState } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++/*+ * Codex Plan switch (Better Coding Experience lab), renderer side.+ *+ * A topic's switch lives in `metadata.heteroPlanMode`: absent until the user+ * first turns it on, so a topic that never did sends no collaboration mode at+ * all. Every native Codex turn of a topic that did sends `plan` or `default`.+ * Codex keeps the mode on the thread: only the user turns Plan off (the+ * switch, or Execute plan under a plan).+ */++/** Whether the Plan switch applies at all: both labs on (it needs the native app-server). */+export const isCodexPlanModeEnabled = (): boolean => {+ const state = getUserStoreState();+ return (+ labPreferSelectors.enableBetterCodingExperience(state) &&+ labPreferSelectors.enableCodexAppServer(state)+ );+};++/**+ * The collaboration mode a local Codex run sends, or undefined to send none+ * (another agent, a topic that never turned Plan on, a lab off).+ */+export const resolveRunCollaborationMode = (+ agentType: string | undefined,+ metadata: ChatTopicMetadata | null | undefined,+): CodexCollaborationMode | undefined =>+ agentType === 'codex' && isCodexPlanModeEnabled()+ ? codexCollaborationModeOf(metadata?.heteroPlanMode)+ : undefined;++/** The new-topic switch per agent, while the composer shows it on or flipped. */+const pendingSwitches = new Map<string, boolean>();++/** The composer's new-topic switch for `agentId` (undefined: nothing to hand over). */+export const setPendingHeteroPlanMode = (agentId: string, enabled: boolean | undefined): void => {+ if (enabled === undefined) pendingSwitches.delete(agentId);+ else pendingSwitches.set(agentId, enabled);+};++/** Metadata a new Codex topic is born with: the switch its composer showed. */+export const pendingHeteroPlanModeMetadata = (+ agentId: string,+ agentType: string | undefined,+): Pick<ChatTopicMetadata, 'heteroPlanMode'> => {+ const enabled = pendingSwitches.get(agentId);+ return enabled !== undefined && agentType === 'codex' && isCodexPlanModeEnabled()+ ? { heteroPlanMode: enabled }+ : {};+};++/**+ * Write a collaboration-mode report onto the topic. `persist: false` when the+ * server already wrote it (a run hosted by `lh hetero exec`); the store follows.+ */+export const applyCollaborationModeReport = async (+ get: () => ChatStore,+ topicId: string | null | undefined,+ report: Pick<CollaborationModeReportData, 'collaborationMode' | 'requested'>,+ { persist }: { persist: boolean },+): Promise<void> => {+ if (!topicId) return;+ const patch = collaborationModeReportPatch(report);+ const topic = topicSelectors.getTopicById(topicId)(get());+ const current = topic?.metadata;+ const changed = (Object.keys(patch) as (keyof typeof patch)[]).some(+ (key) => (current?.[key] ?? null) !== (patch[key] ?? null),+ );+ if (!changed) return;+ if (persist) {+ await get().updateTopicMetadata(topicId, patch);+ return;+ }+ if (!topic) return;+ get().internal_dispatchTopic({+ id: topicId,+ type: 'updateTopic',+ value: { metadata: { ...topic.metadata, ...patch } },+ });+};++/** Switches the collaboration mode of a run hosted in this window (desktop IPC). */+export type LocalCollaborationModeSwitcher = (mode: CodexCollaborationMode) => Promise<void>;++const localSwitchers = new Map<string, LocalCollaborationModeSwitcher>();++/**+ * Register how to flip the Plan switch of a topic's local run, for as long as+ * its session lives.+ *+ * @returns Unregister; a no-op once a newer run of the topic registered.+ */+export const registerLocalCollaborationModeSwitcher = (+ topicId: string | null | undefined,+ switcher: LocalCollaborationModeSwitcher,+): (() => void) => {+ if (!topicId) return () => {};+ localSwitchers.set(topicId, switcher);+ return () => {+ if (localSwitchers.get(topicId) === switcher) localSwitchers.delete(topicId);+ };+};++export const getLocalCollaborationModeSwitcher = (+ topicId: string,+): LocalCollaborationModeSwitcher | undefined => localSwitchers.get(topicId);++/** The parts of a conversation message the plan decision looks at. */+interface DecisionMessage {+ plugin?: { apiName?: string; identifier?: string } | null;+ role: string;+ tool_call_id?: string | null;+}++/**+ * Whether the "Execute plan / Keep discussing" buttons show under a Codex plan.+ *+ * Only under the latest plan of a topic whose Plan switch is still on, once+ * the topic is idle, and until the user answered (a dismissal for this plan,+ * or any message of theirs after it). Nothing waits on Codex here: its turn+ * already ended, so the buttons never hold the run open.+ */+export const shouldShowCodexPlanDecision = ({+ messages,+ metadata,+ running,+ toolCallId,+}: {+ messages: readonly DecisionMessage[];+ metadata: ChatTopicMetadata | null | undefined;+ running: boolean;+ toolCallId: string | undefined;+}): boolean => {+ if (!toolCallId || running || !isCodexPlanModeEnabled()) return false;+ if (metadata?.heteroPlanMode !== true) return false;+ if (metadata.codexPlanDecision?.itemId === toolCallId && metadata.codexPlanDecision.dismissed) {+ return false;+ }+ const index = messages.findIndex((m) => m.role === 'tool' && m.tool_call_id === toolCallId);+ if (index < 0) return false;+ return !messages+ .slice(index + 1)+ .some(+ (m) =>+ m.role === 'user' ||+ (m.role === 'tool' &&+ m.plugin?.identifier === 'codex' &&+ m.plugin.apiName === CODEX_PROPOSED_PLAN_API_NAME),+ );+};++interface PlanDecisionDeps {+ toolCallId: string;+ topicId: string;+ updateTopicMetadata: (+ topicId: string,+ patch: Pick<ChatTopicMetadata, 'codexPlanDecision' | 'heteroPlanMode'>,+ ) => Promise<unknown>;+}++/**+ * "Execute plan": turn Plan off and put the buttons away, then ask Codex to+ * carry the plan out. The write lands first: the run the message dispatches+ * reads the topic (on the server for `lh` runs) and must send `default`. The+ * message is a turn of its own, so a draft in the composer stays there.+ */+export const executeCodexPlan = async ({+ message,+ sendMessage,+ toolCallId,+ topicId,+ updateTopicMetadata,+}: PlanDecisionDeps & {+ message: string;+ sendMessage: (params: { message: string; preserveComposer: true }) => Promise<unknown>;+}): Promise<void> => {+ await updateTopicMetadata(topicId, {+ codexPlanDecision: { dismissed: true, itemId: toolCallId },+ heteroPlanMode: false,+ });+ await sendMessage({ message, preserveComposer: true });+};++/** "Keep discussing": put the buttons away; Plan stays on. */+export const dismissCodexPlan = async ({+ toolCallId,+ topicId,+ updateTopicMetadata,+}: PlanDecisionDeps): Promise<void> => {+ await updateTopicMetadata(topicId, {+ codexPlanDecision: { dismissed: true, itemId: toolCallId },+ });+};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.tsindex 04651d81edc..d8888b58d5b 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts@@ -56,9 +56,19 @@ export const resolveInitialTopicMetadata = (params: {// The Claude Code permission mode the new-topic chip showed: the server// starts the topic's first run in it.- const permissionModeMetadata = callerTopicMetadata?.heteroPermissionMode- ? { heteroPermissionMode: callerTopicMetadata.heteroPermissionMode }- : undefined;+ const permissionModeMetadata =+ callerTopicMetadata?.heteroPermissionMode ||+ typeof callerTopicMetadata?.heteroPlanMode === 'boolean'+ ? {+ ...(callerTopicMetadata.heteroPermissionMode && {+ heteroPermissionMode: callerTopicMetadata.heteroPermissionMode,+ }),+ // The Codex Plan switch the new-topic composer showed; `false` is a pick too.+ ...(typeof callerTopicMetadata.heteroPlanMode === 'boolean' && {+ heteroPlanMode: callerTopicMetadata.heteroPlanMode,+ }),+ }+ : undefined;return cwdTopicMetadata || sandboxTopicMetadata || permissionModeMetadata? { ...cwdTopicMetadata, ...sandboxTopicMetadata, ...permissionModeMetadata }diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.tsindex eb2d3cfc800..9cb8bafb27e 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts@@ -5,9 +5,11 @@ import type {} from '@lobechat/agent-gateway-client';import type { BackgroundTaskEventData } from '@lobechat/heterogeneous-agents';import { isPermissionModeReport } from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';+import { isCollaborationModeReport } from '@lobechat/heterogeneous-agents/codexPlanMode';import type { ConversationContext } from '@lobechat/types';import { applyPermissionModeReport } from '@/store/chat/heteroPermissionMode';+import { applyCollaborationModeReport } from '@/store/chat/heteroPlanMode';import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -120,6 +122,14 @@ export const resolveStepSideEvent = (};}+ // Codex Plan switch: the server already wrote the report; the topic follows.+ if (isCollaborationModeReport(data)) {+ return {+ apply: () =>+ void applyCollaborationModeReport(get, context.topicId, data, { persist: false }),+ };+ }+if (data?.phase === 'user_message') {const steer = data.steerMessage;if (!steer) return {};diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex db5619f40d0..43b497a223f 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -18,7 +18,6 @@ import {type SubagentRunSnapshot,usesHeterogeneousSessionInitialModel,} from '@lobechat/heterogeneous-agents';-import { isPermissionModeReport } from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';import type {ChatMessageError,ChatToolPayload,@@ -63,11 +62,8 @@ import {import { hydrateProjectedToolMessages } from '@/services/message/hydrateProjectedTools';import { threadService } from '@/services/thread';import { workService } from '@/services/work';-import {- applyPermissionModeReport,- registerLocalPermissionModeSwitcher,- resolveRunPermissionMode,-} from '@/store/chat/heteroPermissionMode';+import { resolveRunPermissionMode } from '@/store/chat/heteroPermissionMode';+import { resolveRunCollaborationMode } from '@/store/chat/heteroPlanMode';import { topicSelectors } from '@/store/chat/selectors';import { type StreamRetryMetadata } from '@/store/chat/slices/operation/types';import { type ChatStore, useChatStore } from '@/store/chat/store';@@ -84,7 +80,7 @@ import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler } from '../gateway/gatewayEventHandler';import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';import { withHeteroContext } from '../viewedTaskPrompt';-import { registerLocalBackgroundTaskStopper, writeBackgroundTaskSnapshot } from './backgroundTasks';+import { writeBackgroundTaskSnapshot } from './backgroundTasks';import { markUnfinishedToolsCancelled } from './cancelledTools';import {shouldSuppressTerminalErrorEcho,@@ -92,6 +88,7 @@ import {} from './heteroMessageError';import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';import { preserveSkippedIntervention } from './interventionAck';+import { applyLocalModeReport, registerLocalRunControls } from './localRunControls';import { claimLocalRunFee, type LocalRunFeeClaim, settleLocalRunFee } from './localRunFee';import { type LocalSteer, startLocalSteer } from './localSteer';import { buildLocalHeterogeneousSystemContext } from './localSystemContext';@@ -1952,10 +1949,9 @@ export const executeHeterogeneousAgent = async (persistQueue = persistQueue.then(() => reduceAndApplyMain(event));return;}- if (event.type === 'step_complete' && isPermissionModeReport(event.data)) {- void applyPermissionModeReport(get, context.topicId, event.data, { persist: true });+ // Claude Code's permission mode, Codex's collaboration mode.+ if (event.type === 'step_complete' && applyLocalModeReport(get, context.topicId, event.data))return;- }// ─── stream_start with newStep: new LLM turn ───// The reducer flushes the prior turn's content/reasoning/model and opens@@ -2376,32 +2372,24 @@ export const executeHeterogeneousAgent = async (set: (id) => void (mainState = { ...mainState, lastSpineMessageId: id }),},});- // Claude Code keeps its input (SDK stream or CLI stdin) open in every Follow-up mode.- if (adapterType === 'claude-code') {- const unregisterStopper = registerLocalBackgroundTaskStopper(operationId, (taskId) =>- heterogeneousAgentService.stopBackgroundTask(sidForCancel, taskId),- );- // The mode chip switches this run's permission mode mid-run.- const unregisterSwitcher = registerLocalPermissionModeSwitcher(context.topicId, (mode) =>- heterogeneousAgentService.setPermissionMode(sidForCancel, mode),- );- unregisterTaskStopper = () => {- unregisterStopper();- unregisterSwitcher();- };- }+ unregisterTaskStopper = registerLocalRunControls({+ adapterType,+ operationId,+ sessionId: sidForCancel,+ topicId: context.topicId,+ });+ const runTopicMetadata = getTopicMetadataById(get(), context.topicId ?? undefined);// Send the prompt — blocks until process exitsconst sendResult = await heterogeneousAgentService.sendPrompt({agentId: context.agentId,assistantMessageId,+ // The Codex Plan switch (Better Coding Experience lab).+ collaborationMode: resolveRunCollaborationMode(adapterType, runTopicMetadata),imageList,userId: userProfileSelectors.userId(getUserStoreState()),workspaceId: workspaceId ?? undefined,operationId,- permissionMode: resolveRunPermissionMode(- adapterType,- getTopicMetadataById(get(), context.topicId ?? undefined),- ),+ permissionMode: resolveRunPermissionMode(adapterType, runTopicMetadata),// `/goal` travels as system-context instructions; the CLI gets only the// request so its own `/goal` command does not take the message over.prompt: appendAttachedFilesToPrompt(stripGoalCommand(message), attachedFiles),diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localRunControls.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localRunControls.tsnew file mode 100644index 00000000000..72ae989c545--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localRunControls.ts@@ -0,0 +1,74 @@+import { isPermissionModeReport } from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';+import { isCollaborationModeReport } from '@lobechat/heterogeneous-agents/codexPlanMode';++import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';+import {+ applyPermissionModeReport,+ registerLocalPermissionModeSwitcher,+} from '@/store/chat/heteroPermissionMode';+import {+ applyCollaborationModeReport,+ registerLocalCollaborationModeSwitcher,+} from '@/store/chat/heteroPlanMode';+import type { ChatStore } from '@/store/chat/store';++import { registerLocalBackgroundTaskStopper } from './backgroundTasks';++/**+ * Register the composer controls that reach a local run while it goes:+ * Claude Code's background-task stops and permission-mode chip, and the+ * native Codex Plan switch (the switcher fails when the run is `codex exec`,+ * and the pick then waits for the next run).+ *+ * @returns Unregister them all, or undefined when the agent has none.+ */+export const registerLocalRunControls = ({+ adapterType,+ operationId,+ sessionId,+ topicId,+}: {+ adapterType: string;+ operationId: string;+ sessionId: string;+ topicId: string | null | undefined;+}): (() => void) | undefined => {+ if (adapterType === 'codex') {+ return registerLocalCollaborationModeSwitcher(topicId, (mode) =>+ heterogeneousAgentService.setCollaborationMode(sessionId, mode),+ );+ }+ // Claude Code keeps its input (SDK stream or CLI stdin) open in every Follow-up mode.+ if (adapterType !== 'claude-code') return;+ const unregisterStopper = registerLocalBackgroundTaskStopper(operationId, (taskId) =>+ heterogeneousAgentService.stopBackgroundTask(sessionId, taskId),+ );+ // The mode chip switches this run's permission mode mid-run.+ const unregisterSwitcher = registerLocalPermissionModeSwitcher(topicId, (mode) =>+ heterogeneousAgentService.setPermissionMode(sessionId, mode),+ );+ return () => {+ unregisterStopper();+ unregisterSwitcher();+ };+};++/**+ * Apply a local run's mode report (Claude Code's permission mode, Codex's+ * collaboration mode) onto its topic. Resolves whether `data` was one.+ */+export const applyLocalModeReport = (+ get: () => ChatStore,+ topicId: string | null | undefined,+ data: unknown,+): boolean => {+ if (isPermissionModeReport(data)) {+ void applyPermissionModeReport(get, topicId, data, { persist: true });+ return true;+ }+ if (isCollaborationModeReport(data)) {+ void applyCollaborationModeReport(get, topicId, data, { persist: true });+ return true;+ }+ return false;+};diff --git a/src/store/chat/utils/snapshotAgentModel.ts b/src/store/chat/utils/snapshotAgentModel.tsindex f1ff9c52c82..f72b5004485 100644--- a/src/store/chat/utils/snapshotAgentModel.ts+++ b/src/store/chat/utils/snapshotAgentModel.ts@@ -9,6 +9,7 @@ import { agentByIdSelectors } from '@/store/agent/selectors';import { getAiInfraStoreState } from '@/store/aiInfra';import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';import { pendingHeteroPermissionModeMetadata } from '@/store/chat/heteroPermissionMode';+import { pendingHeteroPlanModeMetadata } from '@/store/chat/heteroPlanMode';/*** Snapshot the given agent's current model/provider so a newly created topic@@ -48,7 +49,7 @@ export const snapshotAgentModel = (export type TopicReasoningSnapshot = Pick<ChatTopicMetadata,- 'heteroEffort' | 'heteroPermissionMode' | 'heteroSpeed' | 'reasoningConfig'+ 'heteroEffort' | 'heteroPermissionMode' | 'heteroPlanMode' | 'heteroSpeed' | 'reasoningConfig'>;/**@@ -78,8 +79,9 @@ export const snapshotAgentReasoning = async (if (heterogeneousProvider) {const snapshot = {...resolveHeterogeneousTopicRuntimeSnapshot(heterogeneousProvider),- // The Claude Code permission mode the new-topic chip showed.+ // The Claude Code permission mode / Codex Plan switch the new-topic composer showed....pendingHeteroPermissionModeMetadata(agentId, heterogeneousProvider.type),+ ...pendingHeteroPlanModeMetadata(agentId, heterogeneousProvider.type),};return Object.keys(snapshot).length === 0 ? undefined : snapshot;}diff --git a/src/store/device/agentRunRuntimes/store.ts b/src/store/device/agentRunRuntimes/store.tsnew file mode 100644index 00000000000..8d85810a058--- /dev/null+++ b/src/store/device/agentRunRuntimes/store.ts@@ -0,0 +1,75 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import {+ createReplicaSlice,+ createReplicaState,+ defineReplica,+ recordLens,+ type ReplicaState,+} from '@/libs/replica';+import { deviceService } from '@/services/device';+import { createDevtools } from '@/store/middleware/createDevtools';+import { expose } from '@/store/middleware/expose';++/**+ * The native runtimes of the connection an agent run on a device reaches+ * (`device.getAgentRunRuntimes`), e.g. `codex-collaboration-mode-v1` for the+ * Codex Plan switch. Keyed by device id inside the cache scope (user ++ * workspace); a reload paints the last answer and the probe confirms it.+ */+export const agentRunRuntimesResource = defineReplica<string, string[]>({+ key: (deviceId) => deviceId,+ name: 'deviceAgentRunRuntimes',+ persist: { maxEntries: 20 },+ storage: 'indexedDB',+ version: 1,+});++interface AgentRunRuntimesStoreState {+ agentRunRuntimesMap: Record<string, string[]>;+ agentRunRuntimesReplica: ReplicaState<string[]>;+}++const createSlice = (+ set: (partial: Partial<AgentRunRuntimesStore>, replace?: false, action?: any) => void,+ get: () => AgentRunRuntimesStore,+) =>+ createReplicaSlice(agentRunRuntimesResource, {+ actionPrefix: 'agentRunRuntimes',+ fetcher: async (deviceId: string) =>+ (await deviceService.getAgentRunRuntimes({ deviceId })).runtimes,+ get,+ set,+ stateKey: 'agentRunRuntimesReplica',+ view: recordLens<AgentRunRuntimesStore, string[]>('agentRunRuntimesMap'),+ });++interface AgentRunRuntimesStore extends AgentRunRuntimesStoreState {+ /** @internal The replica slice; read through `useAgentRunRuntimes`. */+ slice: ReturnType<typeof createSlice>;+}++const devtools = createDevtools('agentRunRuntimes');++export const useAgentRunRuntimesStore = createWithEqualityFn<AgentRunRuntimesStore>()(+ devtools((set, get) => ({+ agentRunRuntimesMap: {},+ agentRunRuntimesReplica: createReplicaState(),+ slice: createSlice(set, get),+ })),+ shallow,+);++expose('agentRunRuntimes', useAgentRunRuntimesStore);++const SYNC_OPTIONS = { dedupingInterval: 60 * 1000, revalidateOnFocus: false };++/** The device's agent-run runtimes, or undefined while unknown (or without a device). */+export const useAgentRunRuntimes = (deviceId: string | undefined): string[] | undefined => {+ const data = useAgentRunRuntimesStore((s) =>+ deviceId ? s.agentRunRuntimesMap[deviceId] : undefined,+ );+ useAgentRunRuntimesStore.getState().slice.useSync(deviceId ?? null, SYNC_OPTIONS);+ return data;+};diff --git a/src/store/user/slices/workspaceUserSettings/action.planMode.test.ts b/src/store/user/slices/workspaceUserSettings/action.planMode.test.tsnew file mode 100644index 00000000000..6c4e3dcf309--- /dev/null+++ b/src/store/user/slices/workspaceUserSettings/action.planMode.test.ts@@ -0,0 +1,79 @@+import type { WorkspaceUserPreference } from '@lobechat/types';+import { act } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { userService } from '@/services/user';+import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';+import { useUserStore } from '@/store/user';++const active = vi.hoisted(() => ({ id: 'workspace-1' as string | null }));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => active.id,+ useActiveWorkspaceId: () => active.id,+}));++vi.mock('@/services/workspaceUserSettings', () => ({+ workspaceUserSettingsService: {+ getPreference: vi.fn(),+ setHeteroPlanModeDir: vi.fn(),+ updatePreference: vi.fn(),+ },+}));++vi.mock('@/services/user', async (importOriginal) => {+ const original = await importOriginal<{ userService: object }>();+ return {+ ...original,+ userService: { ...original.userService, setHeteroPlanModeDir: vi.fn() },+ };+});++const state = () => useUserStore.getState();++const seed = (preference: WorkspaceUserPreference) =>+ useUserStore.setState({+ workspaceUserPreference: preference,+ workspaceUserPreferenceWorkspaceId: 'workspace-1',+ });++describe('setHeteroPlanModeDir', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ active.id = 'workspace-1';+ useUserStore.setState({+ preference: { heteroPlanModeDirs: ['dev::/p'] } as any,+ workspaceUserPreference: {},+ workspaceUserPreferenceWorkspaceId: null,+ });+ });++ it('remembers the switch in the workspace bucket, beside the worktree switch', async () => {+ seed({ worktreeModeDirs: ['dev::/a'] });+ vi.mocked(workspaceUserSettingsService.setHeteroPlanModeDir).mockResolvedValue(['dev::/a']);++ await act(() => state().setHeteroPlanModeDir('dev::/a', true));++ expect(workspaceUserSettingsService.setHeteroPlanModeDir).toHaveBeenCalledWith('dev::/a', true);+ expect(state().workspaceUserPreference).toMatchObject({+ heteroPlanModeDirs: ['dev::/a'],+ worktreeModeDirs: ['dev::/a'],+ });+ // The personal bucket is a different person-context and stays untouched.+ expect(state().preference.heteroPlanModeDirs).toEqual(['dev::/p']);+ });++ it('writes users.preference in personal mode and rolls back a failed write', async () => {+ active.id = null;+ vi.mocked(userService.setHeteroPlanModeDir).mockRejectedValue(new Error('offline'));++ await expect(act(() => state().setHeteroPlanModeDir('dev::/p', false))).rejects.toThrow(+ 'offline',+ );+ expect(state().preference.heteroPlanModeDirs).toEqual(['dev::/p']);++ vi.mocked(userService.setHeteroPlanModeDir).mockResolvedValue([]);+ await act(() => state().setHeteroPlanModeDir('dev::/p', false));+ expect(state().preference.heteroPlanModeDirs).toEqual([]);+ });+});diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.tsindex 69b66309d08..866cc503aa5 100644--- a/src/store/user/slices/workspaceUserSettings/action.ts+++ b/src/store/user/slices/workspaceUserSettings/action.ts@@ -1,5 +1,9 @@import type { HeteroPermissionMode, WorkspaceUserPreference } from '@lobechat/types';-import { applyHeteroPermissionModeDir, applyWorktreeModeDir } from '@lobechat/types';+import {+ applyHeteroPermissionModeDir,+ applyHeteroPlanModeDir,+ applyWorktreeModeDir,+} from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import isEqual from 'fast-deep-equal';import type { ReplicaSlice } from 'local-replica/zustand';@@ -28,7 +32,7 @@ const n = setNamespace('workspaceUserSettings');/** Per-directory habits stored the same way in both preference buckets. */type DirectoryPreference = Pick<WorkspaceUserPreference,- 'heteroPermissionModeDirs' | 'worktreeModeDirs'+ 'heteroPermissionModeDirs' | 'heteroPlanModeDirs' | 'worktreeModeDirs'>;type Setter = StoreSetter<UserStore>;@@ -286,6 +290,22 @@ export class WorkspaceUserSettingsActionImpl {writeWorkspace: () => workspaceUserSettingsService.setWorktreeModeDir(key, enabled),});+ /**+ * Remember whether the Codex Plan switch was left on for one directory (same+ * key as the worktree switch), which a new Codex topic there starts with.+ */+ setHeteroPlanModeDir = async (key: string, enabled: boolean): Promise<void> =>+ this.#setDirectoryPreference({+ apply: (preference) => ({+ heteroPlanModeDirs: applyHeteroPlanModeDir(preference.heteroPlanModeDirs, key, enabled),+ }),+ name: 'setHeteroPlanModeDir',+ writePersonal: async () => ({+ heteroPlanModeDirs: await userService.setHeteroPlanModeDir(key, enabled),+ }),+ writeWorkspace: () => workspaceUserSettingsService.setHeteroPlanModeDir(key, enabled),+ });+/*** Remember the Claude Code permission mode picked for one directory (same key* as the worktree switch), which a new topic there starts in.