🤯 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): Claude Code permission modes and plan approval under Better Coding Experience (#23403)
Bryana0aa905b4571
diff --git a/apps/cli/src/commands/connect/handlers.ts b/apps/cli/src/commands/connect/handlers.tsindex 872074c2e8b..42734e22ae6 100644--- a/apps/cli/src/commands/connect/handlers.ts+++ b/apps/cli/src/commands/connect/handlers.ts@@ -225,6 +225,7 @@ export function bindGatewayClientHandlers(imageList: request.imageList,jwt: request.jwt,operationId: request.operationId,+ permissionMode: request.permissionMode,prompt: request.prompt,resumeFallbackSystemContext: request.resumeFallbackSystemContext,resumeSessionId: request.resumeSessionId,diff --git a/apps/cli/src/commands/hetero/index.ts b/apps/cli/src/commands/hetero/index.tsindex b3c6c510322..c7ee0cc2fe0 100644--- a/apps/cli/src/commands/hetero/index.ts+++ b/apps/cli/src/commands/hetero/index.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import { once } from 'node:events';import { createWriteStream } from 'node:fs';-import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';+import { mkdir, unlink, writeFile } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';@@ -22,9 +22,6 @@ import {preparePiRpcInput,} from '@lobechat/heterogeneous-agents/rpc';import type {- AgentContentBlock,- AgentImageSource,- AgentPromptInput,AgentStreamEvent,UploadHeterogeneousImage,} from '@lobechat/heterogeneous-agents/spawn';@@ -51,6 +48,7 @@ import { createLocalTraceStore } from '../../utils/traceStore';import { TrpcIngestSink } from '../../utils/TrpcIngestSink';import type { HeteroCliArgumentOptions } from './buildExtraArgs';import { buildExtraArgs } from './buildExtraArgs';+import { type ResolvedPrompt, resolvePrompt } from './prompt';const DSH_AGENT_TYPE = 'deepseek-harness';export const SUPPORTED_AGENT_TYPES = new Set<string>([@@ -235,141 +233,6 @@ interface ExecOptions extends HeteroCliArgumentOptions {const collectImage = (value: string, previous: string[] = []): string[] => [...previous, value];const collectAgentArg = (value: string, previous: string[] = []): string[] => [...previous, value];-const readStdin = async (): Promise<string> => {- const chunks: Buffer[] = [];- for await (const chunk of process.stdin) {- chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));- }- return Buffer.concat(chunks).toString('utf8');-};--/**- * Resolve a raw `--input-json` argument: `'-'` (or empty) reads stdin, anything- * else is treated as a filesystem path.- */-const readInputJson = async (location: string): Promise<string> => {- if (location === '-' || location === '') return readStdin();- return readFile(location, 'utf8');-};--const looksLikeJsonInput = (value: string): boolean => {- const trimmed = value.trimStart();- return trimmed.startsWith('{') || trimmed.startsWith('[');-};--/**- * Convert an `--image <value>` argument into an image source. Recognized- * shapes: `https?://...` URL, `data:` URL, otherwise a filesystem path- * resolved relative to the CLI's cwd.- */-const parseImageArg = (value: string): AgentImageSource => {- if (/^https?:\/\//i.test(value)) return { type: 'url', url: value };- if (value.startsWith('data:')) {- const match = value.match(/^data:([^;,]+);base64,(.+)$/);- if (!match) {- throw new Error(`Invalid data URL for --image: ${value.slice(0, 40)}…`);- }- return { data: match[2]!, mediaType: match[1]!, type: 'base64' };- }- return { path: path.resolve(process.cwd(), value), type: 'path' };-};--/**- * Best-effort coercion of a JSON-decoded value into an `AgentPromptInput`.- * Accepts:- * - `'plain text'` → single text block- * - `[{ type: 'text', text }, { type: 'image', source }]` → content blocks- * - `{ content: [...], resumeFallback?: [...] }` → unwraps the primary prompt- * and reserves the fallback for a retry without native resume- * - `{ type: 'text', ... } | { type: 'image', ... }` → single block- */-const coerceJsonPrompt = (- parsed: unknown,-): Pick<ResolvedPrompt, 'prompt' | 'resumeFallbackPrompt'> => {- if (typeof parsed === 'string') return { prompt: parsed };- if (Array.isArray(parsed)) return { prompt: parsed as AgentContentBlock[] };- if (parsed && typeof parsed === 'object') {- const obj = parsed as Record<string, unknown>;- if (Array.isArray(obj.content)) {- return {- prompt: obj.content as AgentContentBlock[],- ...(Array.isArray(obj.resumeFallback)- ? { resumeFallbackPrompt: obj.resumeFallback as AgentContentBlock[] }- : {}),- };- }- if (obj.type === 'text' || obj.type === 'image') {- return { prompt: [obj as unknown as AgentContentBlock] };- }- }- throw new Error(- 'Invalid --input-json shape: expected a string, array of content blocks, ' +- 'or `{ content: [...] }` envelope.',- );-};--interface ResolvedPrompt {- /** Human-readable description for the empty-input check. */- describe: () => string;- prompt: AgentPromptInput;- /** Full prompt used only when native resume fails and the CLI retries fresh. */- resumeFallbackPrompt?: AgentPromptInput;-}--const buildPromptFromText = (text: string, images: string[]): ResolvedPrompt => {- if (images.length === 0) {- return { describe: () => text.trim(), prompt: text };- }- const blocks: AgentContentBlock[] = [];- if (text.length > 0) blocks.push({ text, type: 'text' });- for (const image of images) {- blocks.push({ source: parseImageArg(image), type: 'image' });- }- return {- describe: () =>- blocks- .map((b) => (b.type === 'text' ? b.text.trim() : '[image]'))- .filter(Boolean)- .join(' ')- .trim(),- prompt: blocks,- };-};--/**- * Decide which input mode the user requested and produce a unified prompt.- *- * Mode resolution (mutually exclusive):- * 1. `--input-json` → read JSON file or stdin, parse to content blocks- * 2. `--prompt` (with optional `--image` flags) → text + images- * 3. (default) read stdin: auto-detect JSON vs plain text by first char- */-const resolvePrompt = async (options: ExecOptions): Promise<ResolvedPrompt> => {- const images = options.image ?? [];-- if (options.inputJson !== undefined) {- if (options.prompt !== undefined) {- throw new Error('--prompt and --input-json are mutually exclusive.');- }- if (images.length > 0) {- throw new Error('--image cannot be combined with --input-json (put images in the JSON).');- }- const raw = await readInputJson(options.inputJson);- return { describe: () => raw.trim(), ...coerceJsonPrompt(JSON.parse(raw)) };- }-- if (options.prompt !== undefined && options.prompt !== '-') {- return buildPromptFromText(options.prompt, images);- }-- // No --prompt or --prompt -: read stdin and auto-detect.- const raw = await readStdin();- if (looksLikeJsonInput(raw)) {- return { describe: () => raw.trim(), ...coerceJsonPrompt(JSON.parse(raw)) };- }- return buildPromptFromText(raw, images);-};-interface RawStreamDumpAttempt {/** Flush + close both file streams. Resolves once the bytes are on disk. */close: () => Promise<void>;@@ -1215,6 +1078,9 @@ const exec = async (options: ExecOptions): Promise<void> => {// early makes print mode kill background tasks after 10 minutes.liveInput: options.type === 'claude-code',operationId,+ // Better Coding Experience: Claude Code prompts answered on the bridge's cards.+ ...(options.type === 'claude-code' &&+ resolved.permissionMode && { permissionMode: resolved.permissionMode }),uploadImage,};diff --git a/apps/cli/src/commands/hetero/prompt.test.ts b/apps/cli/src/commands/hetero/prompt.test.tsnew file mode 100644index 00000000000..e3296656fed--- /dev/null+++ b/apps/cli/src/commands/hetero/prompt.test.ts@@ -0,0 +1,56 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { resolvePrompt } from './prompt';++const dirs: string[] = [];+const inputFile = async (value: unknown) => {+ const dir = await mkdtemp(path.join(os.tmpdir(), 'lh-prompt-'));+ dirs.push(dir);+ const file = path.join(dir, 'input.json');+ await writeFile(file, JSON.stringify(value));+ return file;+};++afterEach(async () => {+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));+});++describe('resolvePrompt — dispatch envelope', () => {+ it('takes the permission mode the run was dispatched with', async () => {+ const resolved = await resolvePrompt({+ inputJson: await inputFile({+ content: [{ text: 'hi', type: 'text' }],+ permissionMode: 'plan',+ }),+ });+ expect(resolved.permissionMode).toBe('plan');+ expect(resolved.prompt).toEqual([{ text: 'hi', type: 'text' }]);+ });++ it('ignores a mode it does not know, and envelopes without one', async () => {+ for (const permissionMode of ['dontAsk', undefined]) {+ const resolved = await resolvePrompt({+ inputJson: await inputFile({ content: [{ text: 'hi', type: 'text' }], permissionMode }),+ });+ expect(resolved.permissionMode).toBeUndefined();+ }+ });++ it('keeps the resume fallback next to the mode', async () => {+ const resolved = await resolvePrompt({+ inputJson: await inputFile({+ content: [{ text: 'hi', type: 'text' }],+ permissionMode: 'default',+ resumeFallback: [{ text: 'history + hi', type: 'text' }],+ }),+ });+ expect(resolved).toMatchObject({+ permissionMode: 'default',+ resumeFallbackPrompt: [{ text: 'history + hi', type: 'text' }],+ });+ });+});diff --git a/apps/cli/src/commands/hetero/prompt.ts b/apps/cli/src/commands/hetero/prompt.tsnew file mode 100644index 00000000000..36ab77471f5--- /dev/null+++ b/apps/cli/src/commands/hetero/prompt.ts@@ -0,0 +1,160 @@+import { readFile } from 'node:fs/promises';+import path from 'node:path';++import type {+ AgentContentBlock,+ AgentImageSource,+ AgentPromptInput,+} from '@lobechat/heterogeneous-agents/spawn';+import { type HeteroPermissionMode, isHeteroPermissionMode } from '@lobechat/types';++/** The `lh hetero exec` options that choose where the prompt comes from. */+interface ExecOptions {+ image?: string[];+ inputJson?: string;+ prompt?: string;+}++const readStdin = async (): Promise<string> => {+ const chunks: Buffer[] = [];+ for await (const chunk of process.stdin) {+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : (chunk as Buffer));+ }+ return Buffer.concat(chunks).toString('utf8');+};++/**+ * Resolve a raw `--input-json` argument: `'-'` (or empty) reads stdin, anything+ * else is treated as a filesystem path.+ */+const readInputJson = async (location: string): Promise<string> => {+ if (location === '-' || location === '') return readStdin();+ return readFile(location, 'utf8');+};++const looksLikeJsonInput = (value: string): boolean => {+ const trimmed = value.trimStart();+ return trimmed.startsWith('{') || trimmed.startsWith('[');+};++/**+ * Convert an `--image <value>` argument into an image source. Recognized+ * shapes: `https?://...` URL, `data:` URL, otherwise a filesystem path+ * resolved relative to the CLI's cwd.+ */+const parseImageArg = (value: string): AgentImageSource => {+ if (/^https?:\/\//i.test(value)) return { type: 'url', url: value };+ if (value.startsWith('data:')) {+ const match = value.match(/^data:([^;,]+);base64,(.+)$/);+ if (!match) {+ throw new Error(`Invalid data URL for --image: ${value.slice(0, 40)}…`);+ }+ return { data: match[2]!, mediaType: match[1]!, type: 'base64' };+ }+ return { path: path.resolve(process.cwd(), value), type: 'path' };+};++/**+ * Best-effort coercion of a JSON-decoded value into an `AgentPromptInput`.+ * 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+ * - `{ type: 'text', ... } | { type: 'image', ... }` → single block+ */+const coerceJsonPrompt = (+ parsed: unknown,+): Pick<ResolvedPrompt, 'permissionMode' | 'prompt' | 'resumeFallbackPrompt'> => {+ if (typeof parsed === 'string') return { prompt: parsed };+ if (Array.isArray(parsed)) return { prompt: parsed as AgentContentBlock[] };+ if (parsed && typeof parsed === 'object') {+ const obj = parsed as Record<string, unknown>;+ if (Array.isArray(obj.content)) {+ return {+ ...(isHeteroPermissionMode(obj.permissionMode) && { permissionMode: obj.permissionMode }),+ prompt: obj.content as AgentContentBlock[],+ ...(Array.isArray(obj.resumeFallback)+ ? { resumeFallbackPrompt: obj.resumeFallback as AgentContentBlock[] }+ : {}),+ };+ }+ if (obj.type === 'text' || obj.type === 'image') {+ return { prompt: [obj as unknown as AgentContentBlock] };+ }+ }+ throw new Error(+ 'Invalid --input-json shape: expected a string, array of content blocks, ' ++ 'or `{ content: [...] }` envelope.',+ );+};++export interface ResolvedPrompt {+ /** Human-readable description for the empty-input check. */+ describe: () => string;+ /**+ * Claude Code permission mode (Better Coding Experience lab) carried by the+ * dispatch envelope. An older `lh` ignores it and keeps allowing everything.+ */+ permissionMode?: HeteroPermissionMode;+ prompt: AgentPromptInput;+ /** Full prompt used only when native resume fails and the CLI retries fresh. */+ resumeFallbackPrompt?: AgentPromptInput;+}++const buildPromptFromText = (text: string, images: string[]): ResolvedPrompt => {+ if (images.length === 0) {+ return { describe: () => text.trim(), prompt: text };+ }+ const blocks: AgentContentBlock[] = [];+ if (text.length > 0) blocks.push({ text, type: 'text' });+ for (const image of images) {+ blocks.push({ source: parseImageArg(image), type: 'image' });+ }+ return {+ describe: () =>+ blocks+ .map((b) => (b.type === 'text' ? b.text.trim() : '[image]'))+ .filter(Boolean)+ .join(' ')+ .trim(),+ prompt: blocks,+ };+};++/**+ * Decide which input mode the user requested and produce a unified prompt.+ *+ * Mode resolution (mutually exclusive):+ * 1. `--input-json` → read JSON file or stdin, parse to content blocks+ * 2. `--prompt` (with optional `--image` flags) → text + images+ * 3. (default) read stdin: auto-detect JSON vs plain text by first char+ */+export const resolvePrompt = async (+ options: Pick<ExecOptions, 'image' | 'inputJson' | 'prompt'>,+): Promise<ResolvedPrompt> => {+ const images = options.image ?? [];++ if (options.inputJson !== undefined) {+ if (options.prompt !== undefined) {+ throw new Error('--prompt and --input-json are mutually exclusive.');+ }+ if (images.length > 0) {+ throw new Error('--image cannot be combined with --input-json (put images in the JSON).');+ }+ const raw = await readInputJson(options.inputJson);+ return { describe: () => raw.trim(), ...coerceJsonPrompt(JSON.parse(raw)) };+ }++ if (options.prompt !== undefined && options.prompt !== '-') {+ return buildPromptFromText(options.prompt, images);+ }++ // No --prompt or --prompt -: read stdin and auto-detect.+ const raw = await readStdin();+ if (looksLikeJsonInput(raw)) {+ return { describe: () => raw.trim(), ...coerceJsonPrompt(JSON.parse(raw)) };+ }+ return buildPromptFromText(raw, images);+};diff --git a/apps/cli/src/device/agentRun.ts b/apps/cli/src/device/agentRun.tsindex 4b95ee4fee4..f2bea572ed9 100644--- a/apps/cli/src/device/agentRun.ts+++ b/apps/cli/src/device/agentRun.ts@@ -13,6 +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 { getTask, removeTask, saveTask } from '../daemon/taskRegistry';import { registerAgentRun } from './agentRunRegistry';@@ -32,6 +33,8 @@ export interface SpawnHeteroAgentRunParams {imageList?: HeteroExecImageRef[];jwt: string;operationId: string;+ /** Claude Code permission mode, forwarded in the input envelope. */+ permissionMode?: HeteroPermissionMode;prompt: string;/** System context used only by the automatic retry without native resume. */resumeFallbackSystemContext?: string;@@ -143,6 +146,7 @@ function startHeteroAgentRun(const stdinPayload = buildHeteroExecStdinPayload({imageList,isNewSession: !resumeSessionId,+ permissionMode: params.permissionMode,prompt,resumeFallbackSystemContext,systemContext,diff --git a/apps/cli/src/utils/heteroPermissionMode.test.ts b/apps/cli/src/utils/heteroPermissionMode.test.tsnew file mode 100644index 00000000000..fb534a94142--- /dev/null+++ b/apps/cli/src/utils/heteroPermissionMode.test.ts@@ -0,0 +1,74 @@+import { PassThrough } from 'node:stream';++import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { dispatchHeteroControl } from './heteroControl';+import { HETERO_SET_PERMISSION_MODE_COMMAND } from './heteroPermissionMode';++const createLiveInput = () => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ return { live: new ClaudeCodeLiveInput(stdin), written };+};++const setMode = (live: ClaudeCodeLiveInput | undefined, params: unknown) =>+ dispatchHeteroControl(+ { command: HETERO_SET_PERMISSION_MODE_COMMAND, createdAt: 1, id: 'ctl-1', params },+ {+ operationId: 'op-1',+ sendControlRequest: (request) => live?.sendControlRequest(request),+ signal: new AbortController().signal,+ },+ );++describe('set_permission_mode control handler', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('switches the running session and reports the mode Claude Code took', async () => {+ vi.spyOn(process, 'getuid').mockReturnValue(501);+ const { live, written } = createLiveInput();+ const report = setMode(live, { mode: 'acceptEdits' });++ await vi.waitFor(() => expect(written).toHaveLength(1));+ expect(written[0]).toMatchObject({+ request: { mode: 'acceptEdits', subtype: 'set_permission_mode' },+ type: 'control_request',+ });+ // Recorded from `claude` 2.1.308.+ live.observe(+ `${JSON.stringify({+ response: {+ request_id: written[0].request_id,+ response: { mode: 'acceptEdits' },+ subtype: 'success',+ },+ type: 'control_response',+ })}\n`,+ );+ await expect(report).resolves.toEqual({ data: { mode: 'acceptEdits' }, status: 'ok' });+ });++ it('asks for acceptEdits instead of bypass as root', async () => {+ vi.spyOn(process, 'getuid').mockReturnValue(0);+ const { live, written } = createLiveInput();+ void setMode(live, { mode: 'bypassPermissions' });+ await vi.waitFor(() => expect(written).toHaveLength(1));+ expect(written[0].request.mode).toBe('acceptEdits');+ });++ it('refuses an unknown mode and a closed session', async () => {+ const { live } = createLiveInput();+ await expect(setMode(live, { mode: 'dontAsk' })).resolves.toMatchObject({ status: 'error' });+ live.close();+ await expect(setMode(live, { mode: 'plan' })).resolves.toMatchObject({+ error: 'The Claude Code session no longer takes input',+ status: 'error',+ });+ });+});diff --git a/apps/cli/src/utils/heteroPermissionMode.ts b/apps/cli/src/utils/heteroPermissionMode.tsnew file mode 100644index 00000000000..98ed207adfb--- /dev/null+++ b/apps/cli/src/utils/heteroPermissionMode.ts@@ -0,0 +1,33 @@+import {+ isRunningAsRoot,+ setClaudeCodePermissionMode,+} from '@lobechat/heterogeneous-agents/claudeCodePermission';+import { isHeteroPermissionMode } from '@lobechat/types';++import { type HeteroControlHandler, registerHeteroControlHandler } from './heteroControl';++/** The control command the server queues when the user switches mode mid-run. */+export const HETERO_SET_PERMISSION_MODE_COMMAND = 'set_permission_mode';++/**+ * Switch the running Claude Code session's permission mode (the composer's+ * mode chip). Reports the mode Claude Code took — `acceptEdits` for+ * `bypassPermissions` as root; the mode report on the event stream follows.+ */+export const setPermissionModeHandler: HeteroControlHandler = async ({+ params,+ sendControlRequest,+ signal,+}) => {+ const mode = (params as { mode?: unknown } | null)?.mode;+ if (!isHeteroPermissionMode(mode)) throw new Error('set_permission_mode needs a valid mode');++ return {+ mode: await setClaudeCodePermissionMode(sendControlRequest, mode, {+ isRoot: isRunningAsRoot(),+ signal,+ }),+ };+};++registerHeteroControlHandler(HETERO_SET_PERMISSION_MODE_COMMAND, setPermissionModeHandler);diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.tsindex 34f97b09ca4..ec4fbafd3b1 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 './heteroPermissionMode';import './heteroStopTask';import type {diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 8a713f84668..1e6400f4fae 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -214,8 +214,8 @@ export default class HeterogeneousAgentCtr extends ControllerModule {}@IpcMethod()- async respondPermission(...args: Parameters<Implementation['respondPermission']>) {- return (await this.getImplementation()).respondPermission(...args);+ async setPermissionMode(...args: Parameters<Implementation['setPermissionMode']>) {+ return (await this.getImplementation()).setPermissionMode(...args);}@IpcMethod()diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 9b821bbc153..b626615efd0 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -47,7 +47,6 @@ import type {import {buildHeteroExecStdinPayload,buildHeterogeneousPrompt,- stripInheritedRunIdentity,} from '@lobechat/heterogeneous-agents/protocol';import {CLAUDE_CODE_QUOTA_FRESH_MS,@@ -85,7 +84,6 @@ import {resolveCliSpawnPlan,resolveCodexInitialModel,spawnDshAcpSession,- stopClaudeCodeTask,} from '@lobechat/heterogeneous-agents/spawn';import {buildClaudeCodeReplayTurn,@@ -98,6 +96,7 @@ import {} from '@lobechat/heterogeneous-agents/workingDirectory';import type {HeterogeneousAgentModelCatalog,+ HeteroPermissionMode,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';import {@@ -163,12 +162,18 @@ import { createLogger } from '@/utils/logger';import BrowserControlCtr from './BrowserControlCtr';import { sendPromptWithCodexAppServer } from './codexAppServer';import { createLiveCliAdapter, endLiveCliRun, writeCliPrompt } from './heterogeneousAgentLiveInput';+import {+ attachCliPermissionPrompts,+ setSessionPermissionMode,+ stopSessionBackgroundTask,+} from './heterogeneousAgentPermission';import type {AgentSession,CancelSessionParams,CliTraceSession,GetSessionInfoParams,SendPromptParams,+ SetPermissionModeParams,StopBackgroundTaskParams,StopSessionParams,SubmitInterventionParams,@@ -180,6 +185,7 @@ import {interruptActiveAcpSession,sendPromptWithAcpSession,} from './heterogeneousAgentSession';+import { appendLoopbackNoProxy, buildInheritedSpawnEnv } from './heterogeneousAgentSpawnEnv';import {steerAgentSession,type SteerSessionParams,@@ -190,47 +196,8 @@ import RemoteServerConfigCtr from './RemoteServerConfigCtr';const logger = createLogger('controllers:HeterogeneousAgentCtr');-// Anthropic auth env vars that must NOT be inherited from the desktop process-// when spawning a local CLI agent. A developer with `ANTHROPIC_API_KEY` (or an-// auth token / base url) exported in their shell would otherwise have it-// forwarded to `claude`, which then switches from its own subscription login to-// that key — an expired / wrong key surfaces as a baffling "Invalid API key"-// and the run exits non-zero. Agents that genuinely want an API key still set-// it through `session.env`, which is spread AFTER the inherited env below and-// therefore wins.-const STRIPPED_INHERITED_ENV_KEYS = [- 'ANTHROPIC_API_KEY',- 'ANTHROPIC_AUTH_TOKEN',- 'ANTHROPIC_BASE_URL',-] as const;+export { buildInheritedSpawnEnv } from './heterogeneousAgentSpawnEnv';-/**- * Inherited `process.env` without the Anthropic auth vars or an ancestor agent run's- * identity (a Desktop launched from an agent shell carries its JWT file, which the CLI- * prefers over any token). Pure and exported so the invariant is unit-tested directly.- */-export const buildInheritedSpawnEnv = (- sourceEnv: NodeJS.ProcessEnv = process.env,-): NodeJS.ProcessEnv => {- const env = stripInheritedRunIdentity(sourceEnv);- for (const key of STRIPPED_INHERITED_ENV_KEYS) delete env[key];- return env;-};--const appendLoopbackNoProxy = (env: NodeJS.ProcessEnv): void => {- const entries = new Set([- ...[env.NO_PROXY, env.no_proxy]- .filter((value): value is string => !!value)- .flatMap((value) => value.split(','))- .map((value) => value.trim())- .filter(Boolean),- '127.0.0.1',- 'localhost',- ]);- const noProxy = [...entries].join(',');- env.NO_PROXY = noProxy;- env.no_proxy = noProxy;-};const CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS = [/no conversation found/i,/thread .*not found/i,@@ -1659,6 +1626,8 @@ export default class HeterogeneousAgentCtr {},},mcpConfigPath: intervention?.tmpConfigPath,+ permissionMode: params.permissionMode,+ permissionPrompts: !!intervention,promptInput,resumeSessionId: session.agentSessionId,});@@ -1919,8 +1888,13 @@ export default class HeterogeneousAgentCtr {// Same floor as the spawned-CLI path: taken before the transport (and the// executable it launches) exists.const startedAt = new Date().toISOString();+ // Lab permission prompts raise cards on their own bridge (no MCP server).+ const prompts =+ params.permissionMode &&+ this.setupAcpInterventionForOp(params.operationId, session.sessionId, 'claude-code');const sdkSession = new ClaudeAgentSdkSession({args: [...session.args, ...input.args],+ askUserBridge: prompts ? prompts.bridge : undefined,commandPath,configDir: spawnEnv.CLAUDE_CONFIG_DIR ?? session.hostedProviderBinding?.profileDir,cwd,@@ -1954,6 +1928,7 @@ export default class HeterogeneousAgentCtr {},onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),operationId: params.operationId,+ permissionMode: params.permissionMode,// Like the CLI, in every Follow-up mode: a steer is confirmed by its replay.replayUserMessages: true,resumeSessionId: session.agentSessionId,@@ -2014,6 +1989,8 @@ export default class HeterogeneousAgentCtr {cause: error,});} finally {+ // Cancels a card still waiting: the run that asked is gone.+ if (prompts) await prompts.cleanup();await session.hostedProviderBinding?.cleanup();}}@@ -2463,6 +2440,15 @@ export default class HeterogeneousAgentCtr {});const slot = this.opIdToIntervention.get(params.operationId);if (slot) slot.pumpDone = pumpDone;+ if (session.liveInput && params.permissionMode && session.agentType === 'claude-code') {+ attachCliPermissionPrompts({+ bridge: intervention.bridge,+ emit: broadcastBridgeEvent,+ live: session.liveInput,+ operationId: params.operationId,+ permissionMode: params.permissionMode,+ });+ }}// Stream stdout events through the producer pipeline.@@ -3176,11 +3162,7 @@ export default class HeterogeneousAgentCtr {* reaches the renderer through the run's own stream.*/async stopBackgroundTask({ sessionId, taskId }: StopBackgroundTaskParams): Promise<void> {- const session = this.sessions.get(sessionId);- if (session?.sdkSession) return session.sdkSession.stopTask(taskId);- const live = session?.liveInput;- if (!live) throw new Error('This run cannot stop a single background task');- await stopClaudeCodeTask((request) => live.sendControlRequest(request), taskId);+ await stopSessionBackgroundTask(this.sessions.get(sessionId), taskId);}/**@@ -3240,8 +3222,9 @@ export default class HeterogeneousAgentCtr {this.sessions.delete(params.sessionId);}- async respondPermission(): Promise<void> {- // No-op for CLI mode (permissions handled by --permission-mode flag)+ /** Switch a running Claude Code's permission mode (the mode chip); see the helper. */+ async setPermissionMode({ mode, sessionId }: SetPermissionModeParams) {+ return setSessionPermissionMode(this.sessions.get(sessionId), mode);}/**@@ -3389,6 +3372,7 @@ export default class HeterogeneousAgentCtr {imageList?: HeteroExecImageRef[];jwt: string;operationId: string;+ permissionMode?: HeteroPermissionMode;prompt: string;resumeFallbackSystemContext?: string;resumeSessionId?: string;@@ -3458,6 +3442,7 @@ export default class HeterogeneousAgentCtr {const stdinPayload = buildHeteroExecStdinPayload({imageList,isNewSession: !resumeSessionId,+ permissionMode: params.permissionMode,prompt,resumeFallbackSystemContext,systemContext,diff --git a/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentPermission.test.ts b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentPermission.test.tsnew file mode 100644index 00000000000..901cb0d0ec7--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/heterogeneousAgentPermission.test.ts@@ -0,0 +1,105 @@+import { PassThrough } from 'node:stream';++import { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';+import { ClaudeCodeLiveInput } from '@lobechat/heterogeneous-agents/spawn';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ attachCliPermissionPrompts,+ setSessionPermissionMode,+} from '../heterogeneousAgentPermission';++const createLive = () => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const raw of chunk.toString().split('\n')) if (raw) written.push(JSON.parse(raw));+ });+ return { live: new ClaudeCodeLiveInput(stdin), written };+};++const line = (value: unknown) => `${JSON.stringify(value)}\n`;++describe('attachCliPermissionPrompts', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('answers a local CLI prompt from its card and emits the reported mode', async () => {+ vi.spyOn(process, 'getuid').mockReturnValue(501);+ const { live, written } = createLive();+ const bridge = new AskUserBridge('op-local');+ const requests: any[] = [];+ void (async () => {+ for await (const event of bridge.events()) requests.push(event);+ })();+ const emitted: any[] = [];+ attachCliPermissionPrompts({+ bridge,+ emit: (event) => emitted.push(event),+ live,+ operationId: 'op-local',+ permissionMode: 'default',+ });++ live.observe(line({ permissionMode: 'default', subtype: 'init', type: 'system' }));+ live.observe(+ line({+ request: {+ input: { command: 'npm test' },+ subtype: 'can_use_tool',+ tool_name: 'Bash',+ tool_use_id: 'toolu_b',+ },+ request_id: 'req-b',+ type: 'control_request',+ }),+ );+ await vi.waitFor(() => expect(requests).toHaveLength(1));+ bridge.resolve('cc-permission-req-b', { result: { q: 'deny', __note: 'run lint instead' } });+ await vi.waitFor(() => expect(written).toHaveLength(1));++ expect(emitted[0].data).toEqual({+ fallback: null,+ permissionMode: 'default',+ phase: 'permission_mode',+ });+ expect(written[0].response.response).toEqual({+ behavior: 'deny',+ message: 'The user denied this: run lint instead',+ toolUseID: 'toolu_b',+ });+ });+});++describe('setSessionPermissionMode', () => {+ it('uses the SDK query when the run has one', async () => {+ const setPermissionMode = vi.fn();+ await setSessionPermissionMode({ sdkSession: { setPermissionMode } as any }, 'plan');+ expect(setPermissionMode).toHaveBeenCalledWith('plan');+ });++ it('writes set_permission_mode into a live CLI and waits for Claude Code', async () => {+ const { live, written } = createLive();+ const switching = setSessionPermissionMode({ liveInput: live }, 'acceptEdits');+ await vi.waitFor(() => expect(written).toHaveLength(1));+ expect(written[0].request).toEqual({ mode: 'acceptEdits', subtype: 'set_permission_mode' });+ live.observe(+ line({+ response: {+ request_id: written[0].request_id,+ response: { mode: 'acceptEdits' },+ subtype: 'success',+ },+ type: 'control_response',+ }),+ );+ await expect(switching).resolves.toBe('acceptEdits');+ });++ it('refuses a run that has ended', async () => {+ await expect(setSessionPermissionMode(undefined, 'plan')).rejects.toThrow(+ 'cannot switch its permission mode',+ );+ });+});diff --git a/apps/desktop/src/main/controllers/gatewayAgentRun.ts b/apps/desktop/src/main/controllers/gatewayAgentRun.tsindex d757c73205f..fe820a83c16 100644--- a/apps/desktop/src/main/controllers/gatewayAgentRun.ts+++ b/apps/desktop/src/main/controllers/gatewayAgentRun.ts@@ -99,6 +99,7 @@ export const executeGatewayAgentRun = async (imageList: request.imageList,jwt: request.jwt,operationId: request.operationId,+ permissionMode: request.permissionMode,prompt: request.prompt,resumeFallbackSystemContext: request.resumeFallbackSystemContext,resumeSessionId: request.resumeSessionId,diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts b/apps/desktop/src/main/controllers/heterogeneousAgentPermission.tsnew file mode 100644index 00000000000..2ab194fae92--- /dev/null+++ b/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts@@ -0,0 +1,102 @@+import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';+import {+ askThroughBridge,+ attachClaudeCodePermissionResponder,+ isRunningAsRoot,+ PermissionModeReporter,+ resolveClaudeCodePermissionMode,+ setClaudeCodePermissionMode,+} from '@lobechat/heterogeneous-agents/claudeCodePermission';+import type {+ AgentStreamEvent,+ ClaudeAgentSdkSession,+ ClaudeCodeLiveInput,+} from '@lobechat/heterogeneous-agents/spawn';+import { stopClaudeCodeTask } from '@lobechat/heterogeneous-agents/spawn';+import type { HeteroPermissionMode } from '@lobechat/types';+import { isHeteroPermissionMode } from '@lobechat/types';++/*+ * Claude Code permission modes on this machine (Better Coding Experience lab).+ * The CLI asks over stdio (`--permission-prompt-tool stdio`, see the driver),+ * the SDK through `canUseTool`; both raise their cards on the run's+ * AskUserBridge, so the renderer answers them like any other question card+ * (`submitIntervention`).+ */++/**+ * Answer a live CLI session's permission requests through `bridge` and emit+ * the mode Claude Code reports, in stream order with the run's other events.+ */+export const attachCliPermissionPrompts = ({+ bridge,+ emit,+ live,+ operationId,+ permissionMode,+}: {+ bridge: AskUserBridge;+ emit: (event: AgentStreamEvent) => void;+ live: ClaudeCodeLiveInput;+ operationId: string;+ permissionMode: HeteroPermissionMode;+}): void => {+ const isRoot = isRunningAsRoot();+ attachClaudeCodePermissionResponder(live, {+ ask: askThroughBridge(bridge),+ cancel: (toolCallId) => bridge.cancel(toolCallId, 'session_ended'),+ isRoot,+ });+ const reporter = new PermissionModeReporter(+ operationId,+ resolveClaudeCodePermissionMode(permissionMode, isRoot).fallback,+ );+ // A mid-run switch: report against the pick (root takes acceptEdits for bypass).+ live.onControlRequestSent((request, meta) => {+ const requestedMode = meta?.requestedMode;+ if (request.subtype === 'set_permission_mode' && isHeteroPermissionMode(requestedMode)) {+ reporter.requested(requestedMode, isRoot);+ }+ });+ live.subscribe((message) => {+ const event = reporter.observe(message);+ if (event) emit(event);+ });+};++/** The parts of a local run a control request reaches: the SDK query, or the CLI stdin. */+interface ControllableSession {+ liveInput?: ClaudeCodeLiveInput;+ sdkSession?: ClaudeAgentSdkSession;+}++/**+ * Switch a running session's permission mode (the composer's mode chip).+ * Resolves once Claude Code confirmed, with the mode the session took (it+ * differs from the pick as root); its mode report follows on the stream.+ */+export const setSessionPermissionMode = async (+ session: ControllableSession | undefined,+ mode: HeteroPermissionMode,+): Promise<HeteroPermissionMode> => {+ if (session?.sdkSession) return session.sdkSession.setPermissionMode(mode);+ const live = session?.liveInput;+ if (!live) throw new Error('This run cannot switch its permission mode');+ return setClaudeCodePermissionMode((request) => live.sendControlRequest(request), mode, {+ isRoot: isRunningAsRoot(),+ });+};++/**+ * Stop one background task of a running session. Resolves once Claude Code+ * accepted; its `stopped` report reaches the renderer through the stream.+ */+export const stopSessionBackgroundTask = async (+ session: ControllableSession | undefined,+ taskId: string,+): Promise<void> => {+ if (session?.sdkSession) return session.sdkSession.stopTask(taskId);+ const live = session?.liveInput;+ if (!live) throw new Error('This run cannot stop a single background task');+ await stopClaudeCodeTask((request) => live.sendControlRequest(request), taskId);+};diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex 51549e12d44..159651524a6 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -39,6 +39,7 @@ import {} from '@lobechat/heterogeneous-agents/spawn';import type {HeterogeneousServerDefaultApiConfig,+ HeteroPermissionMode,HeteroSessionImportMessage,} from '@lobechat/types';import { app as electronApp } from 'electron';@@ -68,6 +69,12 @@ export interface SendPromptParams {* reach the renderer they must already carry the operation they belong to.*/operationId: string;+ /**+ * (Claude Code, Better Coding Experience lab) Permission mode the run starts+ * in; Claude Code then asks before acting as the mode requires and each+ * request raises a card. Absent: every action is allowed, as before the lab.+ */+ permissionMode?: HeteroPermissionMode;prompt: string;/*** Do not spawn the CLI. Instead, read the last turn of the session's on-disk@@ -845,6 +852,11 @@ export interface GetSessionInfoParams {sessionId: string;}+export interface SetPermissionModeParams {+ mode: HeteroPermissionMode;+ sessionId: string;+}+export interface StopBackgroundTaskParams {sessionId: string;/** Claude Code `task_id` of the background task to stop. */diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSpawnEnv.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSpawnEnv.tsnew file mode 100644index 00000000000..21160583750--- /dev/null+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSpawnEnv.ts@@ -0,0 +1,44 @@+import { stripInheritedRunIdentity } from '@lobechat/heterogeneous-agents/protocol';++// Anthropic auth env vars that must NOT be inherited from the desktop process+// when spawning a local CLI agent. A developer with `ANTHROPIC_API_KEY` (or an+// auth token / base url) exported in their shell would otherwise have it+// forwarded to `claude`, which then switches from its own subscription login to+// that key — an expired / wrong key surfaces as a baffling "Invalid API key"+// and the run exits non-zero. Agents that genuinely want an API key still set+// it through `session.env`, which is spread AFTER the inherited env below and+// therefore wins.+const STRIPPED_INHERITED_ENV_KEYS = [+ 'ANTHROPIC_API_KEY',+ 'ANTHROPIC_AUTH_TOKEN',+ 'ANTHROPIC_BASE_URL',+] as const;++/**+ * Inherited `process.env` without the Anthropic auth vars or an ancestor agent run's+ * identity (a Desktop launched from an agent shell carries its JWT file, which the CLI+ * prefers over any token). Pure and exported so the invariant is unit-tested directly.+ */+export const buildInheritedSpawnEnv = (+ sourceEnv: NodeJS.ProcessEnv = process.env,+): NodeJS.ProcessEnv => {+ const env = stripInheritedRunIdentity(sourceEnv);+ for (const key of STRIPPED_INHERITED_ENV_KEYS) delete env[key];+ return env;+};++/** Keep loopback traffic (the local MCP server) off any configured proxy. */+export const appendLoopbackNoProxy = (env: NodeJS.ProcessEnv): void => {+ const entries = new Set([+ ...[env.NO_PROXY, env.no_proxy]+ .filter((value): value is string => !!value)+ .flatMap((value) => value.split(','))+ .map((value) => value.trim())+ .filter(Boolean),+ '127.0.0.1',+ 'localhost',+ ]);+ const noProxy = [...entries].join(',');+ env.NO_PROXY = noProxy;+ env.no_proxy = noProxy;+};diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.tsindex fd42dbb08fb..2d1d69a6eed 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.test.ts@@ -28,6 +28,27 @@ describe('claudeCodeDriver', () => {expect(plan.liveInput).toBe(true);});+ it('allows every action without a mode, as before the lab', async () => {+ const { args } = await claudeCodeDriver.buildSpawnPlan(buildParams());+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('bypassPermissions');+ expect(args).not.toContain('--permission-prompt-tool');+ });++ it('starts in the picked mode and lets the host answer prompts over stdio', async () => {+ const { args } = await claudeCodeDriver.buildSpawnPlan(buildParams({ permissionMode: 'plan' }));+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('plan');+ expect(args[args.indexOf('--permission-prompt-tool') + 1]).toBe('stdio');+ expect(args).toContain('--allow-dangerously-skip-permissions');+ });++ it('keeps a picked mode and fails closed when the card bridge is not up', async () => {+ const { args } = await claudeCodeDriver.buildSpawnPlan(+ buildParams({ permissionMode: 'default', permissionPrompts: false }),+ );+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('default');+ expect(args).not.toContain('--permission-prompt-tool');+ });+it('prepares the namespaced server-default model without persisting the operation token', async () => {const plan = await claudeCodeDriver.prepareServerDefaultBinding!({args: [],diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.tsindex 4f1a5d6e146..6c65ecfa1a8 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/claudeCode.ts@@ -1,3 +1,4 @@+import { buildClaudeCodePermissionArgs } from '@lobechat/heterogeneous-agents/claudeCodePermission';import {buildClaudeCodeDirectEnv,CLAUDE_CODE_BASE_ARGS,@@ -9,16 +10,10 @@ import { formatServerDefaultHeterogeneousModel } from '@lobechat/types';import type { HeterogeneousAgentBuildPlanParams, HeterogeneousAgentDriver } from '../types';-// Desktop runs CC as the user (never root, so bypassPermissions is fine) and-// renders the chat bubble live, so it always wants partial deltas. Compose-// the shared invariant base args (`@lobechat/heterogeneous-agents/spawn`)-// with those caller-specific flags.-const DESKTOP_CLAUDE_CODE_ARGS = [- ...CLAUDE_CODE_BASE_ARGS,- '--include-partial-messages',- '--permission-mode',- 'bypassPermissions',-] as const;+// Desktop renders the chat bubble live, so it always wants partial deltas.+// Compose the shared invariant base args (`@lobechat/heterogeneous-agents/spawn`)+// with that caller-specific flag; permission flags depend on the run's mode.+const DESKTOP_CLAUDE_CODE_ARGS = [...CLAUDE_CODE_BASE_ARGS, '--include-partial-messages'] as const;export const claudeCodeDriver: HeterogeneousAgentDriver = {async buildSpawnPlan({@@ -26,6 +21,8 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {cliVersion,helpers,mcpConfigPath,+ permissionMode,+ permissionPrompts,promptInput,resumeSessionId,}: HeterogeneousAgentBuildPlanParams) {@@ -39,6 +36,12 @@ export const claudeCodeDriver: HeterogeneousAgentDriver = {return {args: [...DESKTOP_CLAUDE_CODE_ARGS,+ // Lab off (no mode): every action allowed, as before. With a mode the+ // host answers Claude Code's prompts over stdio.+ ...buildClaudeCodePermissionArgs({+ hostPrompts: permissionPrompts ?? true,+ mode: permissionMode,+ }),// Wire the controller-managed temp mcp.json (AskUserQuestion server,// see ) when present. Path-based config is required — CC// does not accept inline JSON for `--mcp-config`.diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsindex 13abc0e6f76..673f9e033c9 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -3,7 +3,10 @@ import type {HeterogeneousProviderBindingResolution,} from '@lobechat/heterogeneous-agents';import type { AgentInputPlan, AgentPromptInput } from '@lobechat/heterogeneous-agents/spawn';-import type { ServerDefaultHeterogeneousModelDescriptor } from '@lobechat/types';+import type {+ HeteroPermissionMode,+ ServerDefaultHeterogeneousModelDescriptor,+} from '@lobechat/types';export interface HeterogeneousAgentImageAttachment {id: string;@@ -41,6 +44,16 @@ export interface HeterogeneousAgentBuildPlanParams {* field append `--mcp-config <path>`; others ignore it.*/mcpConfigPath?: string;+ /**+ * (Claude Code) Better Coding Experience permission mode. Absent: every+ * action is allowed.+ */+ permissionMode?: HeteroPermissionMode;+ /**+ * (Claude Code) The host answers prompts (an AskUserBridge is up). Without,+ * a picked mode fails closed: print mode denies what it would ask about.+ */+ permissionPrompts?: boolean;promptInput: AgentPromptInput;resumeSessionId?: string;}diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.setPermissionMode.test.ts b/apps/server/src/routers/lambda/aiAgent/hetero.setPermissionMode.test.tsnew file mode 100644index 00000000000..1bf814729a9--- /dev/null+++ b/apps/server/src/routers/lambda/aiAgent/hetero.setPermissionMode.test.ts@@ -0,0 +1,60 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { heteroRouter } from './hetero';++const mocks = vi.hoisted(() => ({+ operation: undefined as Record<string, unknown> | undefined,+ setHeteroPermissionMode: vi.fn(),+}));++vi.mock('@/server/services/aiAgent/steerQueue/heteroPermissionMode', () => ({+ setHeteroPermissionMode: mocks.setHeteroPermissionMode,+}));+vi.mock('./procedures', async () => {+ const { trpc } = await import('@/libs/trpc/lambda/init');+ const serverDB = {+ select: () => ({+ from: () => ({+ where: () => ({ limit: async () => (mocks.operation ? [mocks.operation] : []) }),+ }),+ }),+ };+ const procedure = trpc.procedure.use((opts) =>+ opts.next({ ctx: { ...opts.ctx, serverDB: serverDB as never } }),+ );+ return {+ aiAgentBaseProcedure: procedure,+ aiAgentWriteProcedure: procedure,+ heteroAgentProcedure: procedure,+ };+});++const caller = heteroRouter.createCaller({ userId: 'user-1' } as never);++beforeEach(() => {+ vi.clearAllMocks();+ mocks.operation = { agentId: 'agent-1', userId: 'user-1' };+ mocks.setHeteroPermissionMode.mockResolvedValue({ status: 'accepted' });+});++describe('aiAgent.setHeteroPermissionMode', () => {+ it('switches the running Claude Code over its control channel', async () => {+ await expect(+ caller.setHeteroPermissionMode({ mode: 'acceptEdits', operationId: 'op-1' }),+ ).resolves.toEqual({ status: 'accepted' });+ expect(mocks.setHeteroPermissionMode).toHaveBeenCalledWith('op-1', 'acceptEdits');+ });++ it("refuses a mode it does not offer and another user's run", async () => {+ await expect(+ caller.setHeteroPermissionMode({ mode: 'dontAsk' as never, operationId: 'op-1' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ mocks.operation = { agentId: 'agent-1', userId: 'user-2' };+ await expect(+ caller.setHeteroPermissionMode({ mode: 'plan', operationId: 'op-1' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(mocks.setHeteroPermissionMode).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex cdd154ec2f1..d153fd980e1 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -1,5 +1,8 @@import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';-import { LocalExecutionHeterogeneousAgentTypeSchema } from '@lobechat/types';+import {+ HETERO_PERMISSION_MODES,+ LocalExecutionHeterogeneousAgentTypeSchema,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { eq } from 'drizzle-orm';@@ -27,6 +30,7 @@ import {reportHeteroControlResult,takeHeteroControl,} from '@/server/services/aiAgent/steerQueue/heteroControl';+import { setHeteroPermissionMode } from '@/server/services/aiAgent/steerQueue/heteroPermissionMode';import { stopHeteroBackgroundTask } from '@/server/services/aiAgent/steerQueue/heteroStopTask';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import {@@ -180,6 +184,12 @@ const StopHeteroBackgroundTaskSchema = z.object({taskId: z.string().min(1).max(256),});+/** Schema for `aiAgent.setHeteroPermissionMode` — switch a running Claude Code's mode. */+const SetHeteroPermissionModeSchema = z.object({+ mode: z.enum(HETERO_PERMISSION_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),@@ -283,6 +293,30 @@ const authorizeOperationCallback = async (}};+/** Only the user who started the run, still allowed to use its agent, controls its live process. */+const assertControlsHeteroRun = async (+ ctx: { serverDB: LobeChatDatabase; userId: string; workspaceId?: string | null },+ operationId: string,+) => {+ const [operation] = await ctx.serverDB+ .select({ userId: agentOperations.userId })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);+ if (operation?.userId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Operation not found or not owned by the caller',+ });+ }+ await assertCanUseOperationAgent({+ db: ctx.serverDB,+ operationId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+};+export const heteroRouter = router({/*** Ingest a batch of `AgentStreamEvent`s from a `lh hetero exec` producer@@ -700,26 +734,20 @@ export const heteroRouter = router({stopHeteroBackgroundTask: aiAgentWriteProcedure.input(StopHeteroBackgroundTaskSchema).mutation(async ({ input, ctx }) => {- // Only the user who started the run controls its live process.- const [operation] = await ctx.serverDB- .select({ userId: agentOperations.userId })- .from(agentOperations)- .where(eq(agentOperations.id, input.operationId))- .limit(1);- if (operation?.userId !== ctx.userId) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'Operation not found or not owned by the caller',- });- }- await assertCanUseOperationAgent({- db: ctx.serverDB,- operationId: input.operationId,- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });+ await assertControlsHeteroRun(ctx, input.operationId);return stopHeteroBackgroundTask(input.operationId, input.taskId);}),+ /**+ * Switch the permission mode of a running Claude Code hosted by+ * `lh hetero exec` (the composer's mode chip). Rides the run's control+ * channel; Claude Code's mode report then updates the topic.+ */+ setHeteroPermissionMode: aiAgentWriteProcedure+ .input(SetHeteroPermissionModeSchema)+ .mutation(async ({ input, ctx }) => {+ await assertControlsHeteroRun(ctx, input.operationId);+ return setHeteroPermissionMode(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 d4c1c314f0f..08d61b1e960 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'],+ ['setHeteroPermissionMode', 'mutation'],['setQueuedMessages', 'mutation'],['startExecution', 'mutation'],['stopHeteroBackgroundTask', 'mutation'],diff --git a/apps/server/src/routers/lambda/user/index.procedures.test.ts b/apps/server/src/routers/lambda/user/index.procedures.test.tsindex 3c42675e2e0..93274a48269 100644--- a/apps/server/src/routers/lambda/user/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/user/index.procedures.test.ts@@ -49,6 +49,7 @@ function expected(): Array<['reviseOnboardingUnderstanding', 'mutation', 14],['saveUserQuestion', 'mutation', 11],['sendOnboardingFirstMessage', 'mutation', 11],+ ['setHeteroPermissionModeDir', '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 e0c51d6f65d..3bc7ae62656 100644--- a/apps/server/src/routers/lambda/user/settings.ts+++ b/apps/server/src/routers/lambda/user/settings.ts@@ -2,6 +2,7 @@ import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope'import { MAX_ISLAND_DISMISSALS } from '@lobechat/const/goal';import type { UserSettings } from '@lobechat/types';import {+ HETERO_PERMISSION_MODES,NotificationSettingsSchema,PERSONAL_SYSTEM_AGENT_KEYS,UserPreferenceSchema,@@ -69,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 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) }))+ .mutation(async ({ ctx, input }) =>+ ctx.userModel.setHeteroPermissionModeDir(input.key, input.mode),+ ),/*** Personal chat-assist preferences (follow-up chips, input completion). They* act on the caller's own chat surface, so — unlike the rest ofdiff --git a/apps/server/src/routers/lambda/workspaceUserSettings.ts b/apps/server/src/routers/lambda/workspaceUserSettings.tsindex 929c81b28b9..24b27742caa 100644--- a/apps/server/src/routers/lambda/workspaceUserSettings.ts+++ b/apps/server/src/routers/lambda/workspaceUserSettings.ts@@ -1,5 +1,6 @@import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import type { WorkspaceUserPreference } from '@lobechat/types';+import { HETERO_PERMISSION_MODES } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -77,6 +78,13 @@ export const workspaceUserSettingsRouter = router({ctx.workspaceUserSettingsModel.setWorktreeModeDir(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) }))+ .mutation(async ({ ctx, input }) =>+ ctx.workspaceUserSettingsModel.setHeteroPermissionModeDir(input.key, input.mode),+ ),+/*** Merge `input` on top of the caller's current preference and persist via* UPSERT. First call for a `(workspace, user)` pair creates the row.diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.tsnew file mode 100644index 00000000000..f38360c4c07--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.ts@@ -0,0 +1,52 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveDispatchPermissionMode } from './permissionMode';++const getUserPreference = vi.hoisted(() => vi.fn());++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(function () {+ return { getUserPreference };+ }),+}));++const db = {} as any;++describe('resolveDispatchPermissionMode', () => {+ beforeEach(() => {+ getUserPreference.mockReset();+ });++ it('starts Claude Code in the topic mode when the lab is on', async () => {+ getUserPreference.mockResolvedValue({ lab: { enableBetterCodingExperience: true } });+ await expect(+ resolveDispatchPermissionMode(db, 'u', {+ heteroType: 'claude-code',+ topicMetadata: { heteroPermissionMode: 'plan' },+ }),+ ).resolves.toBe('plan');+ await expect(+ resolveDispatchPermissionMode(db, 'u', { heteroType: 'claude-code', topicMetadata: {} }),+ ).resolves.toBe('bypassPermissions');+ });++ it('sends no mode with the lab off, for other agents, or when the read fails', async () => {+ getUserPreference.mockResolvedValue({ lab: {} });+ await expect(+ resolveDispatchPermissionMode(db, 'u', {+ heteroType: 'claude-code',+ topicMetadata: { heteroPermissionMode: 'plan' },+ }),+ ).resolves.toBeUndefined();++ getUserPreference.mockResolvedValue({ lab: { enableBetterCodingExperience: true } });+ await expect(+ resolveDispatchPermissionMode(db, 'u', { heteroType: 'codex', topicMetadata: {} }),+ ).resolves.toBeUndefined();++ getUserPreference.mockRejectedValue(new Error('db down'));+ await expect(+ resolveDispatchPermissionMode(db, 'u', { heteroType: 'claude-code', topicMetadata: {} }),+ ).resolves.toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.tsnew file mode 100644index 00000000000..fc642ec0d7e--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.ts@@ -0,0 +1,36 @@+import type { ChatTopicMetadata, HeteroPermissionMode } from '@lobechat/types';+import { DEFAULT_HETERO_PERMISSION_MODE, isHeteroPermissionMode } 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:permission-mode');++/**+ * The Claude Code permission mode a dispatched run starts in, or undefined to+ * allow every action as before the Better Coding Experience lab.+ *+ * Only for Claude Code with the run owner's lab on. The topic carries the mode+ * (the composer's chip writes it, and Claude Code's own switches are written+ * back), defaulting to `bypassPermissions`. A failed preference read keeps the+ * pre-lab behavior rather than starting a run that asks.+ */+export const resolveDispatchPermissionMode = async (+ db: LobeChatDatabase,+ userId: string,+ params: { heteroType: string; topicMetadata: ChatTopicMetadata | null | undefined },+): Promise<HeteroPermissionMode | undefined> => {+ if (params.heteroType !== 'claude-code') return;++ try {+ const preference = await new UserModel(db, userId).getUserPreference();+ if (!preference?.lab?.enableBetterCodingExperience) return;+ } catch (error) {+ log('Reading the lab preference of %s failed: %O', userId, error);+ return;+ }++ const mode = params.topicMetadata?.heteroPermissionMode;+ return isHeteroPermissionMode(mode) ? mode : DEFAULT_HETERO_PERMISSION_MODE;+};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex c1c430560ee..be00cbf5b92 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -27,6 +27,7 @@ import { resolveInlineImages } from '@/server/services/file/inlineImages';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';import { buildCloudHeteroContext } from '@/server/services/heterogeneousAgent/cloudHeteroContext';+import { expectPermissionModeReport } from '@/server/services/heterogeneousAgent/permissionModeReport';import type { UnansweredUserTurn } from '@/server/services/heterogeneousAgent/unansweredUserTurns';import { collectUnansweredUserTurns } from '@/server/services/heterogeneousAgent/unansweredUserTurns';import { resolveSandboxSessionConfig } from '@/server/services/sandbox/session';@@ -37,6 +38,7 @@ import { heteroOperationCapabilities } from '../heteroOperationCapabilities';import { buildHeteroProjectContext } from '../projectContext';import { traceHeteroStage } from '../sendTracing';import { buildViewedTaskContextPrompt, joinSystemContext } from '../viewedTaskContext';+import { resolveDispatchPermissionMode } from './permissionMode';import type { HeteroDispatchDeps, HeteroDispatchInput } from './types';import { settleInOrder } from './utils';@@ -195,6 +197,16 @@ export const prepareHeteroRun = async (traceHeteroStage('topic', () => deps.topicModel.findById(topicId)),]);const topicRepos: string[] = topic?.metadata?.repos ?? [];+ const permissionModePromise = resolveDispatchPermissionMode(deps.db, deps.userId, {+ heteroType,+ topicMetadata: topic?.metadata,+ }).then(async (mode) => {+ // An `lh` that never reports the mode back is flagged when the run ends.+ await expectPermissionModeReport(deps.topicModel, { mode, operationId, topicId }).catch(+ (error) => log('execAgent: permission mode report marker failed: %O', error),+ );+ return mode;+ });// The primary resumed attempt already has native history and must not get// a serialized duplicate. A resumed session still needs the prompts of runs@@ -387,6 +399,7 @@ export const prepareHeteroRun = async (imageList: heteroImageList,jwt: operationJwt,operationId,+ permissionMode: await permissionModePromise,// The CLI receives only the request: `/goal` is already in the system// context, and Claude Code's own `/goal` command would otherwise take it.// Non-image attachments have no content block a CLI accepts, so they ridediff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.tsindex 71e33ce2de6..1da97041089 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.test.ts@@ -75,6 +75,27 @@ describe('buildNewTopicMetadata — project directory', () => {});});+describe('buildNewTopicMetadata — Claude Code permission mode', () => {+ it('is born with the mode the composer chip showed', () => {+ expect(+ buildNewTopicMetadata({+ appContext: {+ initialTopicMetadata: { heteroPermissionMode: 'plan', workingDirectory: '/code/d' },+ } as any,+ }),+ ).toMatchObject({ heteroPermissionMode: 'plan', workingDirectory: '/code/d' });+ });++ it('keeps the mode inside a project directory too', () => {+ expect(+ buildNewTopicMetadata({+ appContext: { initialTopicMetadata: { heteroPermissionMode: 'default' } } as any,+ projectDirectory: { path: '/code/lobehub' },+ }),+ ).toMatchObject({ heteroPermissionMode: 'default', workingDirectory: '/code/lobehub' });+ });+});+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 9a3e03dedc4..e56fd9990ae 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts@@ -104,6 +104,10 @@ export const buildNewTopicMetadata = ({...(openedBy && { openedBy }),taskId,...(webhookThread && { webhook: webhookThread }),+ // Claude Code permission mode the composer chip showed (Better Coding Experience).+ ...(initialTopicMeta?.heteroPermissionMode && {+ heteroPermissionMode: initialTopicMeta.heteroPermissionMode,+ }),...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),...pickSandboxPlacement(initialTopicMeta),...(initialTopicMeta?.workingDirectory && {diff --git a/apps/server/src/services/aiAgent/steerQueue/heteroPermissionMode.test.ts b/apps/server/src/services/aiAgent/steerQueue/heteroPermissionMode.test.tsnew file mode 100644index 00000000000..499a7aae67a--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/heteroPermissionMode.test.ts@@ -0,0 +1,54 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createHeteroControlFakeRedis } from '@/server/services/redis/heteroControl.fake';++import { reportHeteroControlResult, takeHeteroControl } from './heteroControl';+import { setHeteroPermissionMode } from './heteroPermissionMode';++const getRedisServiceClient = vi.hoisted(() => vi.fn());+vi.mock('@/server/services/redis/client', () => ({ getRedisServiceClient }));++beforeEach(() => {+ getRedisServiceClient.mockResolvedValue(createHeteroControlFakeRedis());+});++describe('setHeteroPermissionMode', () => {+ it('queues set_permission_mode for the run and reports Claude Code confirming', async () => {+ const switching = setHeteroPermissionMode('op-1', 'acceptEdits', {+ pollMs: 5,+ timeoutMs: 2000,+ });++ let message: Awaited<ReturnType<typeof takeHeteroControl>>;+ await vi.waitFor(async () => {+ message ??= await takeHeteroControl('op-1');+ expect(message).toBeDefined();+ });+ expect(message!).toMatchObject({+ command: 'set_permission_mode',+ params: { mode: 'acceptEdits' },+ });+ // As root, `lh` takes acceptEdits for a bypass pick and says so.+ await reportHeteroControlResult('op-1', message!.id, {+ data: { mode: 'acceptEdits' },+ status: 'ok',+ });++ await expect(switching).resolves.toEqual({ mode: 'acceptEdits', status: 'accepted' });+ });++ it('tells an lh without the handler apart from an unreachable run', async () => {+ const switching = setHeteroPermissionMode('op-old', 'plan', { pollMs: 5, timeoutMs: 2000 });+ let message: Awaited<ReturnType<typeof takeHeteroControl>>;+ await vi.waitFor(async () => {+ message ??= await takeHeteroControl('op-old');+ expect(message).toBeDefined();+ });+ await reportHeteroControlResult('op-old', message!.id, { status: 'unsupported' });+ await expect(switching).resolves.toEqual({ status: 'unsupported' });++ await expect(+ setHeteroPermissionMode('op-quiet', 'plan', { pollMs: 5, timeoutMs: 30 }),+ ).resolves.toEqual({ status: 'unreachable' });+ });+});diff --git a/apps/server/src/services/aiAgent/steerQueue/heteroPermissionMode.ts b/apps/server/src/services/aiAgent/steerQueue/heteroPermissionMode.tsnew file mode 100644index 00000000000..5f4f0733506--- /dev/null+++ b/apps/server/src/services/aiAgent/steerQueue/heteroPermissionMode.ts@@ -0,0 +1,43 @@+import type { HeteroPermissionMode } from '@lobechat/types';+import { isHeteroPermissionMode } from '@lobechat/types';++import { sendHeteroControl } from './heteroControl';+import { type HeteroStopTaskResult, toHeteroStopTaskResult } from './heteroStopTask';++/** Command name the `lh` steer loop registers its mode handler under. */+export const HETERO_SET_PERMISSION_MODE_COMMAND = 'set_permission_mode';++/** The `lh` handler gives Claude Code 10 s to confirm; the rest covers the steer poll. */+export const HETERO_SET_PERMISSION_MODE_TIMEOUT_MS = 20_000;++/**+ * Switch the permission mode of a Claude Code run hosted by `lh hetero exec`+ * (the composer's mode chip, mid-run). `accepted` means Claude Code confirmed;+ * its mode report then reaches the topic through the run's own stream. An `lh`+ * without the handler answers `unsupported`; one that predates control+ * messages leaves it `unreachable`. The caller owns authorization.+ *+ * An accepted switch also says which mode the session took, which differs from+ * the pick when the device runs as root (`bypassPermissions` → `acceptEdits`).+ */+export const setHeteroPermissionMode = async (+ operationId: string,+ mode: HeteroPermissionMode,+ options: { pollMs?: number; timeoutMs?: number } = {},+): Promise<HeteroStopTaskResult | { mode?: HeteroPermissionMode; status: 'accepted' }> => {+ const { state } = await sendHeteroControl(+ operationId,+ HETERO_SET_PERMISSION_MODE_COMMAND,+ { mode },+ {+ pollMs: options.pollMs,+ timeoutMs: options.timeoutMs ?? HETERO_SET_PERMISSION_MODE_TIMEOUT_MS,+ },+ );+ const result = toHeteroStopTaskResult(state);+ const taken =+ state?.status === 'ok' ? (state.data as { mode?: unknown } | undefined)?.mode : undefined;+ return result.status === 'accepted' && isHeteroPermissionMode(taken)+ ? { mode: taken, status: 'accepted' }+ : result;+};diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.tsindex 8349137bbe8..f829e1fcd93 100644--- a/apps/server/src/services/deviceGateway/agents.ts+++ b/apps/server/src/services/deviceGateway/agents.ts@@ -22,6 +22,7 @@ import type {DeviceClient,DeviceUnavailableErrorData,HeterogeneousAgentModelCatalog,+ HeteroPermissionMode,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';import debug from 'debug';@@ -185,6 +186,7 @@ export async function dispatchAgentRun(imageList?: Array<{ id?: string; url: string }>;jwt: string;operationId: string;+ permissionMode?: HeteroPermissionMode;prompt: string;resumeFallbackSystemContext?: string;resumeSessionId?: string;diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.permissionMode.test.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.permissionMode.test.tsnew file mode 100644index 00000000000..37c791b7d2f--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.permissionMode.test.ts@@ -0,0 +1,74 @@+// @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 — Claude Code permission mode', () => {+ beforeEach(() => __resetOperationStatesForTesting());+ afterEach(() => __resetOperationStatesForTesting());++ it('writes each mode Claude Code reports back to the topic', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });++ await h.handler.ingest({+ events: [+ buildEvent('step_complete', 0, {+ fallback: null,+ permissionMode: 'plan',+ phase: 'permission_mode',+ }),+ buildEvent('stream_start', 1, { model: 'claude-opus' }),+ // Approving the plan: Claude Code switched itself.+ buildEvent('step_complete', 2, {+ fallback: null,+ permissionMode: 'acceptEdits',+ phase: 'permission_mode',+ }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });++ expect(h.topicModel.updateMetadata.mock.calls).toEqual([+ [+ TOPIC,+ {+ heteroPermissionMode: 'plan',+ heteroPermissionModeFallback: null,+ heteroPermissionModeReportPending: null,+ },+ ],+ [+ TOPIC,+ {+ heteroPermissionMode: 'acceptEdits',+ heteroPermissionModeFallback: null,+ heteroPermissionModeReportPending: null,+ },+ ],+ ]);+ });++ it('records why a root run is not in the picked mode, keeping the pick', async () => {+ const h = createHarness({ assistantMessageId: 'asst-1', operationId: OP, topicId: TOPIC });+ await h.handler.ingest({+ events: [+ buildEvent('step_complete', 0, {+ fallback: 'root',+ permissionMode: 'acceptEdits',+ phase: 'permission_mode',+ }),+ ],+ operationId: OP,+ topicId: TOPIC,+ });+ expect(h.topicModel.updateMetadata).toHaveBeenCalledWith(TOPIC, {+ heteroPermissionModeFallback: 'root',+ heteroPermissionModeReportPending: null,+ });+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.tsindex 1bad295162e..3bfdaaec09f 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/index.ts@@ -5,6 +5,10 @@ import type {SubagentIntent,} from '@lobechat/heterogeneous-agents';import { getEventScope, reduceMainAgent } from '@lobechat/heterogeneous-agents';+import {+ isPermissionModeReport,+ permissionModeReportPatch,+} from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';import { isEchoedErrorText } from '@lobechat/heterogeneous-agents/errors';import { isHeteroStatusGuideErrorData } from '@lobechat/heterogeneous-agents/processFailure';import { createNanoId } from '@lobechat/utils';@@ -351,6 +355,15 @@ export class HeterogeneousPersistenceHandler {await this.consumeSteer(state, event.data.uuid);return;}+ // Claude Code's mode, incl. the switch it makes when a plan is approved:+ // the topic's next run starts in it, and the composer chip shows it.+ if (event.type === 'step_complete' && isPermissionModeReport(event.data)) {+ await this.deps.topicModel.updateMetadata(state.topicId, {+ ...permissionModeReportPatch(event.data),+ heteroPermissionModeReportPending: null,+ });+ return;+ }await this.reduceAndApply(state, event);}diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex 1ea04743189..0fcd16b57bd 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -37,6 +37,7 @@ import {StaleHeteroOperationError,} from './HeterogeneousPersistenceHandler';import { HeteroTraceRecorder } from './HeteroTraceRecorder';+import { settlePermissionModeReport } from './permissionModeReport';const log = debug('lobe-server:hetero-agent-service');@@ -472,6 +473,14 @@ export class HeterogeneousAgentService {result,topicId,});+ // `cancelled` is followed by the terminal callback, which settles this.+ if (result !== 'cancelled') {+ await settlePermissionModeReport(this.topicModel, {+ operationId,+ succeeded: result === 'success',+ topicId,+ }).catch((err) => log('heteroFinish: permission mode report (non-fatal): %O', err));+ }let serializedHooks: SerializedHook[] | undefined;let assistantMessageId = seedAssistantMessageId;diff --git a/apps/server/src/services/heterogeneousAgent/permissionModeReport.test.ts b/apps/server/src/services/heterogeneousAgent/permissionModeReport.test.tsnew file mode 100644index 00000000000..1ceb47f4795--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/permissionModeReport.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it, vi } from 'vitest';++import { expectPermissionModeReport, settlePermissionModeReport } from './permissionModeReport';++const topicModel = (metadata: Record<string, unknown> = {}) => ({+ findById: vi.fn(async () => ({ metadata })),+ updateMetadata: vi.fn(async () => {}),+});++describe('expectPermissionModeReport', () => {+ it('owes a report only for a mode that asks', async () => {+ const model = topicModel();+ await expectPermissionModeReport(model as any, {+ mode: 'plan',+ operationId: 'op',+ topicId: 't',+ });+ expect(model.updateMetadata).toHaveBeenCalledWith('t', {+ heteroPermissionModeReportPending: 'op',+ });++ const quiet = topicModel();+ await expectPermissionModeReport(quiet as any, {+ mode: 'bypassPermissions',+ operationId: 'op',+ topicId: 't',+ });+ await expectPermissionModeReport(quiet as any, { operationId: 'op', topicId: 't' });+ expect(quiet.updateMetadata).not.toHaveBeenCalled();+ });+});++describe('settlePermissionModeReport', () => {+ it('flags an lh that ran a clean turn without reporting the mode', async () => {+ const model = topicModel({ heteroPermissionModeReportPending: 'op' });+ await settlePermissionModeReport(model as any, {+ operationId: 'op',+ succeeded: true,+ topicId: 't',+ });+ expect(model.updateMetadata).toHaveBeenCalledWith('t', {+ heteroPermissionModeFallback: 'outdatedCli',+ heteroPermissionModeReportPending: null,+ });+ });++ it('only clears the marker after a failed run, and leaves a reported run alone', async () => {+ const failed = topicModel({ heteroPermissionModeReportPending: 'op' });+ await settlePermissionModeReport(failed as any, {+ operationId: 'op',+ succeeded: false,+ topicId: 't',+ });+ expect(failed.updateMetadata).toHaveBeenCalledWith('t', {+ heteroPermissionModeReportPending: null,+ });++ const reported = topicModel({ heteroPermissionModeReportPending: null });+ await settlePermissionModeReport(reported as any, {+ operationId: 'op',+ succeeded: true,+ topicId: 't',+ });+ expect(reported.updateMetadata).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/heterogeneousAgent/permissionModeReport.ts b/apps/server/src/services/heterogeneousAgent/permissionModeReport.tsnew file mode 100644index 00000000000..69ee480ba46--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/permissionModeReport.ts@@ -0,0 +1,40 @@+import type { HeteroPermissionMode } from '@lobechat/types';++import type { TopicModel } from '@/database/models/topic';++type TopicMetadataWriter = Pick<TopicModel, 'findById' | 'updateMetadata'>;++/**+ * Before dispatching a Claude Code run with a mode that asks, remember that+ * its mode report is owed. A current `lh` reports it as soon as Claude Code+ * starts (and the report clears this); one that predates permission modes+ * never does and runs with every action allowed.+ */+export const expectPermissionModeReport = async (+ topicModel: TopicMetadataWriter,+ {+ mode,+ operationId,+ topicId,+ }: { mode?: HeteroPermissionMode; operationId: string; topicId: string },+): Promise<void> => {+ if (!mode || mode === 'bypassPermissions') return;+ await topicModel.updateMetadata(topicId, { heteroPermissionModeReportPending: operationId });+};++/**+ * At a run's end: a run that finished cleanly without reporting its mode ran+ * on an `lh` that ignores modes, so the topic says so (and keeps the pick). A+ * failed or stopped run may never have started Claude Code, so it says nothing.+ */+export const settlePermissionModeReport = async (+ topicModel: TopicMetadataWriter,+ { operationId, succeeded, topicId }: { operationId: string; succeeded: boolean; topicId: string },+): Promise<void> => {+ const topic = await topicModel.findById(topicId);+ if (topic?.metadata?.heteroPermissionModeReportPending !== operationId) return;+ await topicModel.updateMetadata(topicId, {+ heteroPermissionModeReportPending: null,+ ...(succeeded && { heteroPermissionModeFallback: 'outdatedCli' as const }),+ });+};diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex 81f28f6247f..6ce10c746db 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -8,6 +8,7 @@ import {buildHeteroExecStdinPayload,type HeteroExecImageRef,} from '@lobechat/heterogeneous-agents/protocol';+import type { HeteroPermissionMode } from '@lobechat/types';import debug from 'debug';import { appEnv } from '@/envs/app';@@ -42,6 +43,8 @@ export interface SandboxRunParams {jwt: string;marketService: MarketService;operationId: string;+ /** Claude Code permission mode (Better Coding Experience lab). */+ permissionMode?: HeteroPermissionMode;prompt: string;/** GitHub repos to clone before running the agent (e.g. ['owner/repo', ...]). */repos?: string[];@@ -213,6 +216,7 @@ export async function spawnHeteroSandbox(params: SandboxRunParams): Promise<voidconst stdinPayload = buildHeteroExecStdinPayload({imageList: params.imageList,isNewSession: !resumeSessionId,+ permissionMode: params.permissionMode,prompt,resumeFallbackSystemContext: params.resumeFallbackSystemContext,systemContext: params.systemContext,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 57cb8f3ce16..d69512ccff0 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1657,6 +1657,24 @@"heteroAgent.modelSelector.speed.ultrafast": "Ultrafast","heteroAgent.modelSelector.speed.ultrafastDesc": "Highest speed, increased usage","heteroAgent.modelSelector.speed.unavailable": "Unavailable for this model on the execution device",+ "heteroAgent.permissionMode.acceptEdits.desc": "Edits go ahead; commands still ask",+ "heteroAgent.permissionMode.acceptEdits.title": "Accept edits",+ "heteroAgent.permissionMode.auto.desc": "Claude Code decides what needs asking",+ "heteroAgent.permissionMode.auto.title": "Auto",+ "heteroAgent.permissionMode.bypassPermissions.desc": "Never asks; runs every action",+ "heteroAgent.permissionMode.bypassPermissions.title": "Allow everything",+ "heteroAgent.permissionMode.default.desc": "Asks before every edit and command",+ "heteroAgent.permissionMode.default.title": "Ask every time",+ "heteroAgent.permissionMode.fallback.outdatedCli": "The last run allowed every action: lh on this device is too old for permission modes. Update lh to apply “{{mode}}”.",+ "heteroAgent.permissionMode.fallback.root": "Running as root can’t allow everything, so this run accepts edits and asks before other commands.",+ "heteroAgent.permissionMode.label": "Permission mode",+ "heteroAgent.permissionMode.plan.desc": "Reads and plans only; acts once you approve the plan",+ "heteroAgent.permissionMode.plan.title": "Plan",+ "heteroAgent.permissionMode.saveFailed": "Couldn’t save the permission mode. Try again.",+ "heteroAgent.permissionMode.switchFailed": "Couldn’t switch the running session. The new mode applies from the next message.",+ "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.quota.compactLeft": "{{percent}}%","heteroAgent.quota.duration.day_one": "{{count}}d","heteroAgent.quota.duration.day_other": "{{count}}d",diff --git a/locales/en-US/tool.json b/locales/en-US/tool.jsonindex 7540111f491..aade464aef7 100644--- a/locales/en-US/tool.json+++ b/locales/en-US/tool.json@@ -68,6 +68,35 @@"claudeCode.askUserQuestion.timeExpiredNoAnswer": "Time expired — this question can no longer be answered.","claudeCode.askUserQuestion.timeRemaining": "Time remaining: {{time}} · unanswered questions default to option 1 on timeout.","claudeCode.askUserQuestion.timeRemainingNoAnswer": "Time remaining: {{time}} · this question closes without an answer on timeout.",+ "claudeCode.permission.denyNote.placeholder": "Tell Claude what to do instead (optional)",+ "claudeCode.permission.enterPlan.desc": "It will read and plan only, and ask you to approve the plan before changing anything.",+ "claudeCode.permission.enterPlan.title": "Claude wants to enter plan mode",+ "claudeCode.permission.exitPlan.allowedPrompts": "Approving also lets Claude run:",+ "claudeCode.permission.exitPlan.title": "Claude’s plan is ready",+ "claudeCode.permission.inspector.permission": "Permission request",+ "claudeCode.permission.inspector.plan": "Plan approval",+ "claudeCode.permission.option.allow": "Allow",+ "claudeCode.permission.option.allow_session": "Always allow in this session",+ "claudeCode.permission.option.approve_accept_edits": "Approve, accept edits",+ "claudeCode.permission.option.approve_bypass": "Approve, don’t ask again",+ "claudeCode.permission.option.approve_default": "Approve, ask before each edit",+ "claudeCode.permission.option.deny": "Deny",+ "claudeCode.permission.option.keep_planning": "Keep planning",+ "claudeCode.permission.planNote.placeholder": "What should change in the plan? (optional)",+ "claudeCode.permission.resolving": "Sending your answer…",+ "claudeCode.permission.result.allow": "Allowed",+ "claudeCode.permission.result.allow_session": "Always allowed in this session",+ "claudeCode.permission.result.approve_accept_edits": "Plan approved, accepting edits",+ "claudeCode.permission.result.approve_bypass": "Plan approved, won’t ask again",+ "claudeCode.permission.result.approve_default": "Plan approved, asking before each edit",+ "claudeCode.permission.result.cancelled": "Not answered: the run stopped",+ "claudeCode.permission.result.deny": "Denied",+ "claudeCode.permission.result.keep_planning": "Asked Claude to keep planning",+ "claudeCode.permission.result.note": "Your note: {{note}}",+ "claudeCode.permission.tool.blockedPath": "Outside the allowed directories: {{path}}",+ "claudeCode.permission.tool.reason": "Why it asks",+ "claudeCode.permission.tool.title": "Claude wants to use {{tool}}",+ "claudeCode.permission.waiting": "Claude is waiting for your answer","codeInterpreter-legacy.error": "Execution Error","codeInterpreter-legacy.executing": "Executing...","codeInterpreter-legacy.files": "Files:",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex c39ec6a4a22..5dfed1e2827 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1657,6 +1657,24 @@"heteroAgent.modelSelector.speed.ultrafast": "极速","heteroAgent.modelSelector.speed.ultrafastDesc": "最高速度,消耗更多用量","heteroAgent.modelSelector.speed.unavailable": "执行设备上的此模型不可用此档位",+ "heteroAgent.permissionMode.acceptEdits.desc": "直接改文件,运行命令前先问你",+ "heteroAgent.permissionMode.acceptEdits.title": "自动接受改文件",+ "heteroAgent.permissionMode.auto.desc": "由 Claude Code 判断哪些操作需要问你",+ "heteroAgent.permissionMode.auto.title": "自动判断",+ "heteroAgent.permissionMode.bypassPermissions.desc": "不再询问,直接执行所有操作",+ "heteroAgent.permissionMode.bypassPermissions.title": "全部放行",+ "heteroAgent.permissionMode.default.desc": "改文件、运行命令前都先问你",+ "heteroAgent.permissionMode.default.title": "每次都问",+ "heteroAgent.permissionMode.fallback.outdatedCli": "上次运行没有应用权限模式,所有操作都直接执行了:这台设备上的 lh 版本过旧。升级 lh 后,「{{mode}}」才会生效。",+ "heteroAgent.permissionMode.fallback.root": "以 root 运行时无法全部放行,本次改为自动接受改文件,其他命令仍会先问你。",+ "heteroAgent.permissionMode.label": "权限模式",+ "heteroAgent.permissionMode.plan.desc": "只读和规划,你批准计划后再动手",+ "heteroAgent.permissionMode.plan.title": "计划模式",+ "heteroAgent.permissionMode.saveFailed": "权限模式没能保存,请重试。",+ "heteroAgent.permissionMode.switchFailed": "没能切换正在运行的会话,新模式会从下一条消息开始生效。",+ "heteroAgent.permissionMode.switchPendingNotice": "这次运行仍是「{{running}}」:会话没能切换。「{{next}}」从下一条消息开始生效。",+ "heteroAgent.permissionMode.switchUnsupported": "这台设备上的 lh 不支持运行中切换,新模式会从下一条消息开始生效。升级 lh 后可在运行中切换。",+ "heteroAgent.permissionMode.tooltip": "Claude Code 在执行操作前是否询问你。只对当前话题生效;在这个目录里新建话题时,会沿用你上次的选择。","heteroAgent.quota.compactLeft": "{{percent}}%","heteroAgent.quota.duration.day_one": "{{count}}天","heteroAgent.quota.duration.day_other": "{{count}}天",diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.jsonindex e6de2eb10d9..c3b3fc7716a 100644--- a/locales/zh-CN/tool.json+++ b/locales/zh-CN/tool.json@@ -68,6 +68,35 @@"claudeCode.askUserQuestion.timeExpiredNoAnswer": "已超时——这个提问已经无法再作答。","claudeCode.askUserQuestion.timeRemaining": "剩余时间:{{time}} · 超时后未作答题目默认选项 1。","claudeCode.askUserQuestion.timeRemainingNoAnswer": "剩余时间:{{time}} · 超时后结束提问,不会代为作答。",+ "claudeCode.permission.denyNote.placeholder": "告诉 Claude 应该怎么做(可选)",+ "claudeCode.permission.enterPlan.desc": "进入后只读和规划,改动之前会先请你批准计划。",+ "claudeCode.permission.enterPlan.title": "Claude 想进入计划模式",+ "claudeCode.permission.exitPlan.allowedPrompts": "批准后,Claude 还可以运行:",+ "claudeCode.permission.exitPlan.title": "Claude 拟好了计划",+ "claudeCode.permission.inspector.permission": "权限请求",+ "claudeCode.permission.inspector.plan": "计划审批",+ "claudeCode.permission.option.allow": "允许",+ "claudeCode.permission.option.allow_session": "本会话内总是允许",+ "claudeCode.permission.option.approve_accept_edits": "批准,并自动接受改文件",+ "claudeCode.permission.option.approve_bypass": "批准,并不再询问",+ "claudeCode.permission.option.approve_default": "批准,每次改文件都问",+ "claudeCode.permission.option.deny": "拒绝",+ "claudeCode.permission.option.keep_planning": "继续计划",+ "claudeCode.permission.planNote.placeholder": "说说计划要怎么改(可选)",+ "claudeCode.permission.resolving": "正在发送你的回答…",+ "claudeCode.permission.result.allow": "已允许",+ "claudeCode.permission.result.allow_session": "本会话内总是允许",+ "claudeCode.permission.result.approve_accept_edits": "已批准计划,自动接受改文件",+ "claudeCode.permission.result.approve_bypass": "已批准计划,不再询问",+ "claudeCode.permission.result.approve_default": "已批准计划,每次改文件都问",+ "claudeCode.permission.result.cancelled": "未回答:运行已停止",+ "claudeCode.permission.result.deny": "已拒绝",+ "claudeCode.permission.result.keep_planning": "已请 Claude 继续计划",+ "claudeCode.permission.result.note": "你的说明:{{note}}",+ "claudeCode.permission.tool.blockedPath": "不在允许的目录内:{{path}}",+ "claudeCode.permission.tool.reason": "询问原因",+ "claudeCode.permission.tool.title": "Claude 想使用 {{tool}}",+ "claudeCode.permission.waiting": "Claude 在等你回答","codeInterpreter-legacy.error": "执行出错","codeInterpreter-legacy.executing": "正在执行...","codeInterpreter-legacy.files": "文件:",diff --git a/packages/builtin-tool-claude-code/package.json b/packages/builtin-tool-claude-code/package.jsonindex b0eadf93fa6..4b1c8a749a6 100644--- a/packages/builtin-tool-claude-code/package.json+++ b/packages/builtin-tool-claude-code/package.json@@ -10,6 +10,7 @@},"main": "./src/index.ts","dependencies": {+ "@lobechat/heterogeneous-agents": "workspace:*","@lobechat/shared-tool-ui": "workspace:*"},"devDependencies": {diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsxindex cd133ac0ef0..9beb5bef44a 100644--- a/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx+++ b/packages/builtin-tool-claude-code/src/client/Inspector/AskUserQuestion.tsx@@ -1,5 +1,6 @@'use client';+import type { ClaudeCodePermissionInterventionArgs } from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';import { normalizeAskUserQuestions } from '@lobechat/shared-tool-ui/ask-user';import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';import type { BuiltinInspectorProps } from '@lobechat/types';@@ -56,16 +57,27 @@ const styles = createStaticStyles(({ css, cssVar }) => ({export const AskUserQuestionInspector = memo<BuiltinInspectorProps<AskUserQuestionArgs>>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {- const { t } = useTranslation('plugin');- const label = t(ClaudeCodeApiName.AskUserQuestion as any);+ const { t } = useTranslation(['plugin', 'tool']);+ // A Claude Code permission request rides the same card: say what it asks.+ const permission = (args as Partial<ClaudeCodePermissionInterventionArgs> | undefined)+ ?.claudeCodePermission;+ const label = permission+ ? t(+ permission.kind === 'exitPlan'+ ? 'tool:claudeCode.permission.inspector.plan'+ : 'tool:claudeCode.permission.inspector.permission',+ )+ : t(ClaudeCodeApiName.AskUserQuestion as any);const argsQuestions = normalizeAskUserQuestions(args);const questions = argsQuestions.length ? argsQuestions : normalizeAskUserQuestions(partialArgs);// One chip per question, so a collapsed card still says *what* was asked. The// old `header +N` named only the first and turned the rest into a count.- const headers = questions- .map((q) => q.header || q.question)- .filter((header): header is string => !!header);+ const headers = permission+ ? permission.kind === 'tool'+ ? [permission.displayName ?? permission.toolName]+ : []+ : questions.map((q) => q.header || q.question).filter((header): header is string => !!header);const shown = headers.slice(0, MAX_CHIPS);const rest = headers.length - shown.length;diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsxindex e5d478c2096..4ef2c573ea7 100644--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx@@ -6,19 +6,21 @@ import {AskUserQuestionView,DEFAULT_COUNTDOWN_MS,DRAFT_PLUGIN_STATE_KEY,- SUBMIT_ACK_TIMEOUT_MS,useAskUserForm,} from '@lobechat/shared-tool-ui/ask-user';import type { BuiltinInterventionProps } from '@lobechat/types';import { Flexbox, Icon, Text } from '@lobehub/ui';import { CircleAlert } from 'lucide-react';-import { memo, useCallback, useEffect } from 'react';+import { type ComponentProps, memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useConversationStore } from '@/features/Conversation/store';import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';import { useChatStore } from '@/store/chat';+import PermissionRequestIntervention from '../PermissionRequest';+import { useSubmissionReconcile } from '../useSubmissionReconcile';+/*** CC AskUserQuestion intervention component.*@@ -54,12 +56,9 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestio)?.heterogeneousIntervention?.deadline;return typeof stored === 'number' ? stored : undefined;});- const context = useConversationStore((s) => s.context);- const checkQuestionSubmission = useChatStore((s) => s.checkQuestionSubmission);const submissionPhase = useChatStore((s) => s.questionSubmissions[messageId]);- const resolving = useConversationStore(- (s) => dataSelectors.getDbMessageById(messageId)(s)?.pluginIntervention?.resolving === true,- );+ // Stream events normally settle the card; a missed ACK is re-read.+ useSubmissionReconcile(messageId);const setInterventionDraft = useChatStore((s) => s.setInterventionDraft);const writeDraft = useCallback((draft: AskUserDraft) => setInterventionDraft(messageId, draft),@@ -76,19 +75,6 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestiowriteDraft,});- // Stream events normally settle the card. Revalidate a missed ACK after- // remount or reconnect without asking the user to inspect runtime state.- useEffect(() => {- if (!resolving) return;- const reconcile = () => void checkQuestionSubmission(messageId, context);- const timer = window.setTimeout(reconcile, SUBMIT_ACK_TIMEOUT_MS);- window.addEventListener('online', reconcile);- return () => {- window.clearTimeout(timer);- window.removeEventListener('online', reconcile);- };- }, [checkQuestionSubmission, context, messageId, resolving]);-const labels = {customPlaceholder: t('claudeCode.askUserQuestion.customOption.placeholder'),escapeBack: t('claudeCode.askUserQuestion.escape.back'),@@ -132,4 +118,21 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestioAskUserQuestionIntervention.displayName = 'CCAskUserQuestionIntervention';-export default AskUserQuestionIntervention;+/**+ * A Claude Code permission request (Better Coding Experience) carries a+ * `claudeCodePermission` detail beside the AskUserQuestion-shaped question:+ * it gets its own card, which never counts down — Claude Code waits.+ */+const AskUserQuestionOrPermission = memo<BuiltinInterventionProps<AskUserQuestionArgs>>((props) =>+ (props.args as { claudeCodePermission?: unknown } | undefined)?.claudeCodePermission ? (+ <PermissionRequestIntervention+ {...(props as unknown as ComponentProps<typeof PermissionRequestIntervention>)}+ />+ ) : (+ <AskUserQuestionIntervention {...props} />+ ),+);++AskUserQuestionOrPermission.displayName = 'CCAskUserQuestionOrPermission';++export default AskUserQuestionOrPermission;diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsxnew file mode 100644index 00000000000..6686eeb4b4f--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsx@@ -0,0 +1,212 @@+'use client';++import {+ CLAUDE_CODE_PERMISSION_NOTE_KEY,+ type ClaudeCodePermissionInterventionArgs,+ type ClaudeCodePermissionOptionId,+} from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';+import type { BuiltinInterventionProps } from '@lobechat/types';+import { Button, Flexbox, Highlighter, Icon, Markdown, Text, TextArea } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CircleAlert, ClipboardList, ShieldQuestion } from 'lucide-react';+import { memo, useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';++import { useSubmissionReconcile } from '../useSubmissionReconcile';++const styles = stylex.create({+ detail: { fontSize: '12px', lineHeight: 1.5, color: cssVar.colorTextSecondary },+ plan: {+ overflowY: 'auto',+ maxHeight: '360px',+ paddingBlock: '8px',+ paddingInline: '12px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ },+ title: { fontSize: '14px', fontWeight: 500, lineHeight: 1.5, color: cssVar.colorText },+});++/** The option the user is most likely to want, drawn as the one primary button. */+const PRIMARY: Partial<Record<ClaudeCodePermissionOptionId, true>> = {+ allow: true,+ approve_accept_edits: true,+};++/** Options that answer "no", which carry the note to Claude. */+const TAKES_NOTE: Partial<Record<ClaudeCodePermissionOptionId, true>> = {+ deny: true,+ keep_planning: true,+};++const previewOf = (input: Record<string, unknown> | undefined) => {+ if (!input) return;+ if (typeof input.command === 'string') return { code: input.command, language: 'bash' };+ if (typeof input.file_path === 'string') return { text: input.file_path };+ if (typeof input.url === 'string') return { text: input.url };+ if (Object.keys(input).length === 0) return;+ return { code: JSON.stringify(input, null, 2), language: 'json' };+};++/**+ * Claude Code asking before it acts (Better Coding Experience permission+ * modes): a tool it wants to run, entering plan mode, or the plan it wants+ * approved. The buttons are Claude Code's own options; a denial or "keep+ * planning" carries the note the user typed, so Claude knows what to do+ * instead. Never times out: Claude Code waits until the user answers or stops+ * the run.+ */+const PermissionRequestIntervention = memo<+ BuiltinInterventionProps<ClaudeCodePermissionInterventionArgs>+>(({ actionsPortalTarget, args, disabled, messageId, onInteractionAction }) => {+ const { t } = useTranslation('tool');+ // A submitted answer whose producer ACK was missed is re-read, not left stuck.+ useSubmissionReconcile(messageId);+ const [note, setNote] = useState('');+ const [sending, setSending] = useState(false);+ const [failed, setFailed] = useState(false);+ // The store also says when a submission could not be confirmed.+ const submissionPhase = useChatStore((s) => s.questionSubmissions[messageId]);+ const showFailure = failed || submissionPhase === 'failed' || submissionPhase === 'uncertain';+ const detail = args.claudeCodePermission;+ const question = args.questions[0]?.question ?? '';+ const inert = disabled || sending;++ const answer = async (optionId: ClaudeCodePermissionOptionId) => {+ if (inert || !onInteractionAction) return;+ const trimmed = TAKES_NOTE[optionId] ? note.trim() : '';+ setSending(true);+ setFailed(false);+ try {+ await onInteractionAction({+ payload: {+ [question]: optionId,+ ...(trimmed && { [CLAUDE_CODE_PERMISSION_NOTE_KEY]: trimmed }),+ },+ type: 'submit',+ });+ } catch (error) {+ // The card is back to pending: say the answer did not reach Claude Code,+ // so the user answers again instead of waiting for nothing.+ console.error('[CCPermissionRequest] submit failed', error);+ setFailed(true);+ } finally {+ setSending(false);+ }+ };++ const title =+ detail.kind === 'exitPlan'+ ? t('claudeCode.permission.exitPlan.title')+ : detail.kind === 'enterPlan'+ ? t('claudeCode.permission.enterPlan.title')+ : (detail.title ??+ t('claudeCode.permission.tool.title', {+ tool: detail.displayName ?? detail.toolName,+ }));+ const preview = detail.kind === 'tool' ? previewOf(detail.input) : undefined;+ const takesNote = detail.options.some((option) => TAKES_NOTE[option]);++ const actions = (+ <Flexbox gap={8}>+ {showFailure && (+ <Text fontSize={12} role="alert" type="danger">+ <Icon icon={CircleAlert} size={14} /> {t('askUserQuestion.submitFailed')}+ </Text>+ )}+ {takesNote && (+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ disabled={inert}+ value={note}+ placeholder={t(+ detail.kind === 'exitPlan'+ ? 'claudeCode.permission.planNote.placeholder'+ : 'claudeCode.permission.denyNote.placeholder',+ )}+ onChange={(event) => setNote(event.target.value)}+ />+ )}+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ {detail.options.map((option) => (+ <Button+ danger={option === 'deny'}+ disabled={inert}+ key={option}+ size={'small'}+ type={PRIMARY[option] ? 'primary' : 'default'}+ onClick={() => void answer(option)}+ >+ {t(`claudeCode.permission.option.${option}`)}+ </Button>+ ))}+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ {t(inert ? 'claudeCode.permission.resolving' : 'claudeCode.permission.waiting')}+ </Text>+ </Flexbox>+ );++ return (+ <Flexbox gap={12}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon icon={detail.kind === 'tool' ? ShieldQuestion : ClipboardList} size={16} />+ <span {...stylex.props(styles.title)}>{title}</span>+ </Flexbox>++ {detail.kind === 'enterPlan' && (+ <div {...stylex.props(styles.detail)}>{t('claudeCode.permission.enterPlan.desc')}</div>+ )}++ {detail.description && detail.kind === 'tool' && (+ <div {...stylex.props(styles.detail)}>{detail.description}</div>+ )}+ {preview?.code !== undefined && (+ <Highlighter language={preview.language} style={{ maxHeight: 240, overflow: 'auto' }}>+ {preview.code}+ </Highlighter>+ )}+ {preview?.text && <Text code>{preview.text}</Text>}+ {detail.decisionReason && (+ <div {...stylex.props(styles.detail)}>+ {t('claudeCode.permission.tool.reason')}: {detail.decisionReason}+ </div>+ )}+ {detail.blockedPath && (+ <div {...stylex.props(styles.detail)}>+ {t('claudeCode.permission.tool.blockedPath', { path: detail.blockedPath })}+ </div>+ )}++ {detail.kind === 'exitPlan' && detail.plan && (+ <div {...stylex.props(styles.plan)}>+ <Markdown variant={'chat'}>{detail.plan}</Markdown>+ </div>+ )}+ {detail.allowedPrompts && (+ <Flexbox gap={4}>+ <div {...stylex.props(styles.detail)}>+ {t('claudeCode.permission.exitPlan.allowedPrompts')}+ </div>+ {detail.allowedPrompts.map(({ prompt, tool }) => (+ <Text code fontSize={12} key={`${tool}:${prompt}`}>+ {tool}: {prompt}+ </Text>+ ))}+ </Flexbox>+ )}++ {actionsPortalTarget ? createPortal(actions, actionsPortalTarget) : actions}+ </Flexbox>+ );+});++PermissionRequestIntervention.displayName = 'CCPermissionRequestIntervention';++export default PermissionRequestIntervention;diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/useSubmissionReconcile.ts b/packages/builtin-tool-claude-code/src/client/Intervention/useSubmissionReconcile.tsnew file mode 100644index 00000000000..8fb1f0e6c9d--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Intervention/useSubmissionReconcile.ts@@ -0,0 +1,37 @@+import { SUBMIT_ACK_TIMEOUT_MS } from '@lobechat/shared-tool-ui/ask-user';+import { useEffect } from 'react';++import { useConversationStore } from '@/features/Conversation/store';+import { dataSelectors } from '@/features/Conversation/store/slices/data/selectors';+import { useChatStore } from '@/store/chat';++/**+ * Settle a submitted Claude Code card whose producer ACK was missed. Stream+ * events normally settle it; after `SUBMIT_ACK_TIMEOUT_MS`, a remount or a+ * reconnect, re-read the submission instead of leaving the card disabled.+ *+ * Only runs once an answer was submitted (`resolving`): it never puts a clock+ * on the user's own decision.+ *+ * @returns whether the card is waiting for that acknowledgement+ */+export const useSubmissionReconcile = (messageId: string): boolean => {+ const context = useConversationStore((s) => s.context);+ const checkQuestionSubmission = useChatStore((s) => s.checkQuestionSubmission);+ const resolving = useConversationStore(+ (s) => dataSelectors.getDbMessageById(messageId)(s)?.pluginIntervention?.resolving === true,+ );++ useEffect(() => {+ if (!resolving) return;+ const reconcile = () => void checkQuestionSubmission(messageId, context);+ const timer = window.setTimeout(reconcile, SUBMIT_ACK_TIMEOUT_MS);+ window.addEventListener('online', reconcile);+ return () => {+ window.clearTimeout(timer);+ window.removeEventListener('online', reconcile);+ };+ }, [checkQuestionSubmission, context, messageId, resolving]);++ return resolving;+};diff --git a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsxindex e98668a1971..93e923d4686 100644--- a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx@@ -7,10 +7,11 @@ import {resolveAskUserAnswers,} from '@lobechat/shared-tool-ui/ask-user';import type { BuiltinRenderProps } from '@lobechat/types';-import { memo } from 'react';+import { type ComponentProps, memo } from 'react';import { useTranslation } from 'react-i18next';import type { AskUserQuestionArgs } from '../../../types';+import PermissionRequestResult from '../PermissionRequest';/*** Claude Code host for the shared completed AskUserQuestion result.@@ -41,4 +42,23 @@ const AskUserQuestion = memo<AskUserQuestion.displayName = 'CCAskUserQuestion';-export default AskUserQuestion;+/**+ * Claude Code's permission requests (Better Coding Experience) ride the same+ * AskUserQuestion-shaped card every review surface understands; their extra+ * `claudeCodePermission` detail gets the dedicated result instead.+ */+const AskUserQuestionOrPermission = memo<+ BuiltinRenderProps<AskUserQuestionArgs, AskUserQuestionResultState, string>+>((props) =>+ (props.args as { claudeCodePermission?: unknown } | undefined)?.claudeCodePermission ? (+ <PermissionRequestResult+ {...(props as unknown as ComponentProps<typeof PermissionRequestResult>)}+ />+ ) : (+ <AskUserQuestion {...props} />+ ),+);++AskUserQuestionOrPermission.displayName = 'CCAskUserQuestionOrPermission';++export default AskUserQuestionOrPermission;diff --git a/packages/builtin-tool-claude-code/src/client/Render/PermissionRequest/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/PermissionRequest/index.tsxnew file mode 100644index 00000000000..4761f9727e7--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Render/PermissionRequest/index.tsx@@ -0,0 +1,90 @@+'use client';++import {+ CLAUDE_CODE_PERMISSION_NOTE_KEY,+ type ClaudeCodePermissionInterventionArgs,+ type ClaudeCodePermissionOptionId,+} from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';+import {+ type AskUserQuestionResultState,+ resolveAskUserAnswers,+} from '@lobechat/shared-tool-ui/ask-user';+import type { BuiltinRenderProps } from '@lobechat/types';+import { Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { Check, CircleSlash, ClipboardList, X } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const styles = stylex.create({+ plan: {+ overflowY: 'auto',+ maxHeight: '240px',+ paddingBlock: '4px',+ paddingInline: '12px',+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ },+});++const DENIALS = new Set<ClaudeCodePermissionOptionId>(['deny', 'keep_planning']);++/**+ * A Claude Code permission request after it was answered: what the user chose+ * (and the note sent with a denial), or that the run stopped first. An+ * approved plan stays readable here.+ */+const PermissionRequestResult = memo<+ BuiltinRenderProps<ClaudeCodePermissionInterventionArgs, AskUserQuestionResultState, string>+>(({ args, content, pluginState }) => {+ const { t } = useTranslation('tool');+ const detail = args.claudeCodePermission;+ const answers = resolveAskUserAnswers(pluginState, content);+ const option = Object.entries(answers ?? {})+ .filter(([key]) => key !== CLAUDE_CODE_PERMISSION_NOTE_KEY)+ .flatMap(([, value]) => (Array.isArray(value) ? value : [value]))+ .find((value): value is ClaudeCodePermissionOptionId =>+ detail.options.includes(value as ClaudeCodePermissionOptionId),+ );+ const note = answers?.[CLAUDE_CODE_PERMISSION_NOTE_KEY];++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon+ size={14}+ icon={+ !option+ ? CircleSlash+ : DENIALS.has(option)+ ? X+ : detail.kind === 'exitPlan'+ ? ClipboardList+ : Check+ }+ />+ <Text fontSize={13}>+ {t(`claudeCode.permission.result.${option ?? 'cancelled'}`)}+ {detail.kind === 'tool' ? ` · ${detail.displayName ?? detail.toolName}` : ''}+ </Text>+ </Flexbox>+ {typeof note === 'string' && note && (+ <Text fontSize={12} type={'secondary'}>+ {t('claudeCode.permission.result.note', { note })}+ </Text>+ )}+ {detail.kind === 'exitPlan' && detail.plan && (+ <div {...stylex.props(styles.plan)}>+ <Markdown variant={'chat'}>{detail.plan}</Markdown>+ </div>+ )}+ </Flexbox>+ );+});++PermissionRequestResult.displayName = 'CCPermissionRequestResult';++export default PermissionRequestResult;diff --git a/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.ts b/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.tsnew file mode 100644index 00000000000..8e90ec68dbb--- /dev/null+++ b/packages/database/src/models/__tests__/heteroPermissionModeDirs.test.ts@@ -0,0 +1,63 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users, workspaces, workspaceUserSettings } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { UserModel } from '../user';+import { WorkspaceUserSettingsModel } from '../workspaceUserSettings';++const serverDB: LobeChatDatabase = await getTestDB();++const workspaceId = 'ws-permission-mode-test';+const userId = 'user-permission-mode-test';++const cleanup = async () => {+ await serverDB.delete(workspaceUserSettings);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values({ id: userId, preference: { topicGroupMode: 'byTime' } });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: 'ws-permission' });+});++afterEach(cleanup);++describe('UserModel.setHeteroPermissionModeDir', () => {+ const model = () => new UserModel(serverDB, userId);++ it('remembers the latest pick first, keeps other fields, and forgets the default', async () => {+ await model().setHeteroPermissionModeDir('d::/a', 'plan');+ expect(await model().setHeteroPermissionModeDir('d::/b', 'default')).toEqual([+ { key: 'd::/b', mode: 'default' },+ { key: 'd::/a', mode: 'plan' },+ ]);+ const user = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });+ expect(user?.preference).toMatchObject({ topicGroupMode: 'byTime' });++ expect(await model().setHeteroPermissionModeDir('d::/a', 'bypassPermissions')).toEqual([+ { key: 'd::/b', mode: 'default' },+ ]);+ });+});++describe('WorkspaceUserSettingsModel.setHeteroPermissionModeDir', () => {+ const model = () => new WorkspaceUserSettingsModel(serverDB, userId, workspaceId);++ it('keeps the member list beside the worktree switch', async () => {+ await model().setWorktreeModeDir('d::/a', true);+ expect(await model().setHeteroPermissionModeDir('d::/a', 'acceptEdits')).toEqual([+ { key: 'd::/a', mode: 'acceptEdits' },+ ]);+ expect(await model().getPreference()).toMatchObject({+ heteroPermissionModeDirs: [{ key: 'd::/a', mode: 'acceptEdits' }],+ worktreeModeDirs: ['d::/a'],+ });+ });+});diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex 9b50390f96e..382476df1fe 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -1,5 +1,7 @@import { mergeIslandDismissals } from '@lobechat/const/goal';import type {+ HeteroPermissionMode,+ HeteroPermissionModeDir,NotificationSettings,SSOProvider,SystemAgentItem,@@ -10,7 +12,7 @@ import type {UserSettings,WidgetDryRunGrant,} from '@lobechat/types';-import { applyWorktreeModeDir } from '@lobechat/types';+import { applyHeteroPermissionModeDir, applyWorktreeModeDir } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import { TRPCError } from '@trpc/server';import dayjs from 'dayjs';@@ -588,6 +590,23 @@ export class UserModel {return { next: { ...prev, worktreeModeDirs }, result: worktreeModeDirs };})) ?? [];+ /**+ * Personal-mode Claude Code permission mode remembered for one directory;+ * returns the stored list. The cap is applied here (`applyHeteroPermissionModeDir`).+ */+ setHeteroPermissionModeDir = async (+ key: string,+ mode: HeteroPermissionMode,+ ): Promise<HeteroPermissionModeDir[]> =>+ (await this.mutatePreference((prev) => {+ const heteroPermissionModeDirs = applyHeteroPermissionModeDir(+ prev.heteroPermissionModeDirs,+ key,+ mode,+ );+ return { next: { ...prev, heteroPermissionModeDirs }, result: heteroPermissionModeDirs };+ })) ?? [];+/*** Normalize unique user fields so empty strings become null, keeping unique constraints safe.*/diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.tsindex bc17316efdc..aeda33e4fbc 100644--- a/packages/database/src/models/workspaceUserSettings.ts+++ b/packages/database/src/models/workspaceUserSettings.ts@@ -1,5 +1,9 @@-import type { WorkspaceUserPreference } from '@lobechat/types';-import { applyWorktreeModeDir } from '@lobechat/types';+import type {+ HeteroPermissionMode,+ HeteroPermissionModeDir,+ WorkspaceUserPreference,+} from '@lobechat/types';+import { applyHeteroPermissionModeDir, applyWorktreeModeDir } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import { and, eq } from 'drizzle-orm';@@ -153,11 +157,36 @@ export class WorkspaceUserSettingsModel {/*** Turn the composer's "New worktree" switch on or off for one directory and- * return the stored list. Read → apply → write under the row lock, so the- * cap (see `applyWorktreeModeDir`) is enforced here rather than trusted from a- * client copy that may be stale.+ * return the stored list. The cap (see `applyWorktreeModeDir`) is enforced+ * here rather than trusted from a client copy that may be stale.*/setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> =>+ this.mutatePreference((current) => {+ const worktreeModeDirs = applyWorktreeModeDir(current.worktreeModeDirs, key, enabled);+ return { next: { ...current, worktreeModeDirs }, result: worktreeModeDirs };+ });++ /**+ * Remember the Claude Code permission mode this member picked for one+ * directory and return the stored list (capped here, like the worktree switch).+ */+ setHeteroPermissionModeDir = async (+ key: string,+ mode: HeteroPermissionMode,+ ): Promise<HeteroPermissionModeDir[]> =>+ this.mutatePreference((current) => {+ const heteroPermissionModeDirs = applyHeteroPermissionModeDir(+ current.heteroPermissionModeDirs,+ key,+ mode,+ );+ return { next: { ...current, heteroPermissionModeDirs }, result: heteroPermissionModeDirs };+ });++ /** Read → change → write this member's preference under the row lock. */+ private mutatePreference = async <T>(+ change: (current: WorkspaceUserPreference) => { next: WorkspaceUserPreference; result: T },+ ): Promise<T> =>this.db.transaction(async (trx) => {const [row] = await trx.select({ preference: workspaceUserSettings.preference })@@ -169,9 +198,7 @@ export class WorkspaceUserSettingsModel {),).for('update');- const current = row?.preference ?? {};- const worktreeModeDirs = applyWorktreeModeDir(current.worktreeModeDirs, key, enabled);- const next: WorkspaceUserPreference = { ...current, worktreeModeDirs };+ const { next, result } = change(row?.preference ?? {});await trx.insert(workspaceUserSettings).values({ preference: next, userId: this.userId, workspaceId: this.workspaceId })@@ -179,6 +206,6 @@ export class WorkspaceUserSettingsModel {set: { preference: next, updatedAt: new Date() },target: [workspaceUserSettings.workspaceId, workspaceUserSettings.userId],});- return worktreeModeDirs;+ return result;});}diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.tsindex d40f6d0e4bd..a735e748405 100644--- a/packages/device-gateway-client/src/http.ts+++ b/packages/device-gateway-client/src/http.ts@@ -1,4 +1,4 @@-import type { DeviceClient, DeviceMetricSample } from '@lobechat/types';+import type { DeviceClient, DeviceMetricSample, HeteroPermissionMode } from '@lobechat/types';import {describeGatewayRequestFailure,@@ -339,6 +339,8 @@ export class GatewayHttpClient {imageList?: Array<{ id?: string; url: string }>;jwt: string;operationId: string;+ /** Claude Code permission mode; see `AgentRunRequestMessage.permissionMode`. */+ permissionMode?: HeteroPermissionMode;prompt: string;resumeFallbackSystemContext?: string;resumeSessionId?: string;diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 4d86a207be9..41c6222b686 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -1,4 +1,4 @@-import type { DeviceMetricSample } from '@lobechat/types';+import type { DeviceMetricSample, HeteroPermissionMode } from '@lobechat/types';// ─── Device Info ───@@ -361,13 +361,18 @@ export interface AgentRunRequestMessage {ingestWorkspaceId?: string;jwt: string;operationId: string;- prompt: string;/*** Full system context used only when native resume fails and the device CLI* retries with a fresh session. Optional for compatibility with older* servers and devices. The gateway relay must preserve this optional field;* older deployments safely degrade to a fresh retry without recovery history.*/+ /**+ * Claude Code permission mode (Better Coding Experience lab), forwarded into+ * the `lh hetero exec` input envelope. Absent: every action is allowed.+ */+ permissionMode?: HeteroPermissionMode;+ prompt: string;resumeFallbackSystemContext?: string;resumeSessionId?: string;/**diff --git a/packages/heterogeneous-agents/browser-entries.json b/packages/heterogeneous-agents/browser-entries.jsonindex aaeff974308..94d4c667042 100644--- a/packages/heterogeneous-agents/browser-entries.json+++ b/packages/heterogeneous-agents/browser-entries.json@@ -1 +1 @@-[".", "./client", "./errors", "./quota"]+[".", "./claudeCodePermission/shared", "./client", "./errors", "./quota"]diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.jsonindex 2461400be4b..64212fdf36c 100644--- a/packages/heterogeneous-agents/package.json+++ b/packages/heterogeneous-agents/package.json@@ -7,6 +7,8 @@".": "./src/index.ts","./askUser": "./src/askUser/index.ts","./builtinMcp": "./src/builtinMcp/index.ts",+ "./claudeCodePermission": "./src/claudeCodePermission/index.ts",+ "./claudeCodePermission/shared": "./src/claudeCodePermission/shared.ts","./errors": "./src/errors/index.ts","./client": "./src/client/index.ts","./codexAppServerParams": "./src/codex/appServerParams.ts",diff --git a/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts b/packages/heterogeneous-agents/src/askUser/AskUserBridge.tsindex f8dd50f3651..bf9474031d6 100644--- a/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts+++ b/packages/heterogeneous-agents/src/askUser/AskUserBridge.ts@@ -59,11 +59,18 @@ export interface PendingOptions {/*** Absolute deadline (`Date.now() + timeoutMs`). When it elapses, the* pending promise resolves with `{ cancelled: true, cancelReason: 'timeout' }`.- * Default: 10 minutes.+ * Default: 10 minutes. `Infinity` never times out (a permission request+ * waits for the user); the wire deadline is then {@link NO_DEADLINE_MS} away.*/timeoutMs?: number;}+/**+ * Wire deadline of a request that never times out: durable review rows need a+ * finite one, and a year outlives any run.+ */+export const NO_DEADLINE_MS = 365 * 24 * 60 * 60 * 1000;+interface PendingEntry {cleanup: () => void;reject: (err: unknown) => void;@@ -155,10 +162,11 @@ export class AskUserBridge {const timeoutMs = options.timeoutMs ?? DEFAULT_ASK_USER_TIMEOUT_MS;const progressIntervalMs = options.progressIntervalMs ?? 30_000;const startedAt = Date.now();- const deadline = startedAt + timeoutMs;+ const expires = Number.isFinite(timeoutMs);+ const deadline = startedAt + (expires ? timeoutMs : NO_DEADLINE_MS);return new Promise<InterventionAnswer>((resolve, reject) => {- const timeoutTimer = setTimeout(() => {+ const onTimeout = () => {this.pending_.delete(toolCallId);clearInterval(progressTimer);// Mirror the terminal state onto the outbound stream so the consumer@@ -168,7 +176,8 @@ export class AskUserBridge {// given up.this.emitResponse(toolCallId, { cancelReason: 'timeout', cancelled: true });resolve({ cancelled: true, cancelReason: 'timeout' });- }, timeoutMs);+ };+ const timeoutTimer = expires ? setTimeout(onTimeout, timeoutMs) : undefined;const progressTimer: ReturnType<typeof setInterval> | undefined = options.onProgress? setInterval(() => {@@ -179,7 +188,7 @@ export class AskUserBridge {: undefined;const cleanup = () => {- clearTimeout(timeoutTimer);+ if (timeoutTimer) clearTimeout(timeoutTimer);if (progressTimer) clearInterval(progressTimer);};diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/args.test.ts b/packages/heterogeneous-agents/src/claudeCodePermission/args.test.tsnew file mode 100644index 00000000000..f31c6c2e21d--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/args.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest';++import { buildClaudeCodePermissionArgs, resolveClaudeCodePermissionMode } from './args';++describe('buildClaudeCodePermissionArgs', () => {+ it('keeps every action allowed when the lab picked no mode', () => {+ expect(buildClaudeCodePermissionArgs({ isRoot: false })).toEqual([+ '--permission-mode',+ 'bypassPermissions',+ ]);+ expect(buildClaudeCodePermissionArgs({ isRoot: true })).toEqual([+ '--permission-mode',+ 'acceptEdits',+ '--allowed-tools',+ 'Bash,Read,Write,Edit,MultiEdit,WebSearch,mcp__*',+ ]);+ });++ it.each(['default', 'acceptEdits', 'auto', 'plan', 'bypassPermissions'] as const)(+ 'starts in %s, asks over stdio and permits a later switch to bypass',+ (mode) => {+ expect(buildClaudeCodePermissionArgs({ isRoot: false, mode })).toEqual([+ '--permission-mode',+ mode,+ '--permission-prompt-tool',+ 'stdio',+ '--allow-dangerously-skip-permissions',+ ]);+ },+ );++ it('falls back to plain acceptEdits for bypass as root, pre-approving nothing', () => {+ // An allow rule would outlive a later switch to a stricter mode.+ expect(buildClaudeCodePermissionArgs({ isRoot: true, mode: 'bypassPermissions' })).toEqual([+ '--permission-mode',+ 'acceptEdits',+ '--permission-prompt-tool',+ 'stdio',+ ]);+ });++ it('never permits skipping permissions as root', () => {+ expect(buildClaudeCodePermissionArgs({ isRoot: true, mode: 'plan' })).toEqual([+ '--permission-mode',+ 'plan',+ '--permission-prompt-tool',+ 'stdio',+ ]);+ });+});++describe('buildClaudeCodePermissionArgs — no host to answer', () => {+ it('keeps a restrictive mode and lets print mode deny, never bypassing', () => {+ for (const mode of ['default', 'acceptEdits', 'auto', 'plan'] as const) {+ expect(buildClaudeCodePermissionArgs({ hostPrompts: false, isRoot: false, mode })).toEqual([+ '--permission-mode',+ mode,+ ]);+ }+ expect(+ buildClaudeCodePermissionArgs({+ hostPrompts: false,+ isRoot: true,+ mode: 'bypassPermissions',+ }),+ ).toEqual(['--permission-mode', 'acceptEdits']);+ });+});++describe('resolveClaudeCodePermissionMode', () => {+ it('reports the root fallback only for bypass', () => {+ expect(resolveClaudeCodePermissionMode('bypassPermissions', true)).toEqual({+ fallback: 'root',+ mode: 'acceptEdits',+ });+ expect(resolveClaudeCodePermissionMode('plan', true)).toEqual({ mode: 'plan' });+ expect(resolveClaudeCodePermissionMode('bypassPermissions', false)).toEqual({+ mode: 'bypassPermissions',+ });+ });+});diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/args.ts b/packages/heterogeneous-agents/src/claudeCodePermission/args.tsnew file mode 100644index 00000000000..7e532921cc6--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/args.ts@@ -0,0 +1,61 @@+import type { HeteroPermissionMode } from '@lobechat/types';++import { resolveClaudeCodePermissionMode } from './mode';++export { resolveClaudeCodePermissionMode } from './mode';++/**+ * Tools pre-approved for a root run with the lab off, where nobody can answer a+ * prompt. Never with a mode: an allow rule outlives a later switch to a+ * stricter mode (`set_permission_mode` keeps it), so it would silently approve+ * what the user then asked to be asked about.+ */+const ROOT_PRE_APPROVED_TOOLS = 'Bash,Read,Write,Edit,MultiEdit,WebSearch,mcp__*';++/** Claude Code refuses `bypassPermissions` as root (a cloud sandbox). */+export const isRunningAsRoot = (): boolean => process.getuid?.() === 0;++/**+ * Claude Code permission flags for one spawn, shared by every CLI host+ * (desktop IPC, `lh hetero exec`).+ *+ * - No `mode` (Better Coding Experience lab off): every action is allowed, as+ * before — `bypassPermissions`, or `acceptEdits` with the common tools+ * pre-approved as root. Nothing asks the host.+ * - With a `mode`: Claude Code asks the host over stdio+ * (`--permission-prompt-tool stdio`) whenever the mode wants a decision.+ * `--allow-dangerously-skip-permissions` only PERMITS a later switch to+ * `bypassPermissions` (the mode chip, approving a plan with "don't ask+ * again"): without it Claude Code silently turns that switch into `default`.+ * Root never gets it, since Claude Code refuses it there; root's stand-in+ * for `bypassPermissions` is plain `acceptEdits`, asking before commands.+ * - With a `mode` but no host to answer prompts (`hostPrompts: false`, e.g.+ * the card bridge failed to start): fail closed. The mode still applies and+ * print mode denies whatever it would have asked about; it never falls back+ * to allowing everything.+ */+export const buildClaudeCodePermissionArgs = ({+ hostPrompts = true,+ isRoot = isRunningAsRoot(),+ mode,+}: {+ hostPrompts?: boolean;+ isRoot?: boolean;+ mode?: HeteroPermissionMode;+}): string[] => {+ if (!mode) {+ return isRoot+ ? ['--permission-mode', 'acceptEdits', '--allowed-tools', ROOT_PRE_APPROVED_TOOLS]+ : ['--permission-mode', 'bypassPermissions'];+ }++ const resolved = resolveClaudeCodePermissionMode(mode, isRoot);+ if (!hostPrompts) return ['--permission-mode', resolved.mode];+ return [+ '--permission-mode',+ resolved.mode,+ '--permission-prompt-tool',+ 'stdio',+ ...(isRoot ? [] : ['--allow-dangerously-skip-permissions']),+ ];+};diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/index.ts b/packages/heterogeneous-agents/src/claudeCodePermission/index.tsnew file mode 100644index 00000000000..3d26df6acba--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/index.ts@@ -0,0 +1,39 @@+export {+ buildClaudeCodePermissionArgs,+ isRunningAsRoot,+ resolveClaudeCodePermissionMode,+} from './args';+export {+ isPermissionModeReport,+ PERMISSION_MODE_PHASE,+ type PermissionModeReportData,+ PermissionModeReporter,+ permissionModeReportPatch,+ readClaudeCodePermissionMode,+} from './modeReport';+export {+ buildClaudeCodePermissionIntervention,+ classifyClaudeCodePermission,+ CLAUDE_CODE_PERMISSION_NOTE_KEY,+ CLAUDE_CODE_PERMISSION_OPTION,+ type ClaudeCodePermissionDetail,+ type ClaudeCodePermissionInterventionArgs,+ type ClaudeCodePermissionKind,+ type ClaudeCodePermissionOptionId,+ type ClaudeCodePermissionRequest,+ type ClaudeCodePermissionResult,+ claudeCodePermissionToolCallId,+ fromCanUseTool,+ parseClaudeCodePermissionRequest,+ resolveClaudeCodePermissionDecision,+} from './request';+export {+ askThroughBridge,+ attachClaudeCodePermissionResponder,+ buildSetPermissionModeRequest,+ type ClaudeCodePermissionAsk,+ type ClaudeCodePermissionTransport,+ decideClaudeCodePermission,+ SET_PERMISSION_MODE_TIMEOUT_MS,+ setClaudeCodePermissionMode,+} from './responder';diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/mode.ts b/packages/heterogeneous-agents/src/claudeCodePermission/mode.tsnew file mode 100644index 00000000000..36ce5372e2b--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/mode.ts@@ -0,0 +1,12 @@+import type { HeteroPermissionMode, HeteroPermissionModeFallback } from '@lobechat/types';++/**+ * The mode Claude Code can actually run in: as root, `bypassPermissions` falls+ * back to `acceptEdits`. Pure (the caller says whether it runs as root), so the+ * browser-safe mode report can use it.+ */+export const resolveClaudeCodePermissionMode = (+ mode: HeteroPermissionMode,+ isRoot = false,+): { fallback?: HeteroPermissionModeFallback; mode: HeteroPermissionMode } =>+ isRoot && mode === 'bypassPermissions' ? { fallback: 'root', mode: 'acceptEdits' } : { mode };diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/modeReport.ts b/packages/heterogeneous-agents/src/claudeCodePermission/modeReport.tsnew file mode 100644index 00000000000..43ec46ed479--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/modeReport.ts@@ -0,0 +1,106 @@+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type {+ ChatTopicMetadata,+ HeteroPermissionMode,+ HeteroPermissionModeFallback,+} from '@lobechat/types';+import { isHeteroPermissionMode } from '@lobechat/types';++import { resolveClaudeCodePermissionMode } from './mode';++/** `step_complete` phase carrying the mode Claude Code reports it is in. */+export const PERMISSION_MODE_PHASE = 'permission_mode';++export interface PermissionModeReportData {+ /** Why the run is not in the picked mode; null when it is. */+ fallback: HeteroPermissionModeFallback | null;+ permissionMode: HeteroPermissionMode;+ phase: typeof PERMISSION_MODE_PHASE;+}++/**+ * The permission mode a Claude Code record reports: `system:init` at each+ * turn, `system:status` after a switch (the host's, or Claude Code's own when+ * a plan is approved). A mode not offered here (`dontAsk`) reports nothing.+ */+export const readClaudeCodePermissionMode = (+ message: unknown,+): HeteroPermissionMode | undefined => {+ if (typeof message !== 'object' || message === null) return;+ const record = message as Record<string, unknown>;+ if (record.type !== 'system' || (record.subtype !== 'init' && record.subtype !== 'status'))+ return;+ // A sub-agent reports its own session, not the topic's.+ if (record.parent_tool_use_id) return;+ return isHeteroPermissionMode(record.permissionMode) ? record.permissionMode : undefined;+};++export const isPermissionModeReport = (data: unknown): data is PermissionModeReportData =>+ typeof data === 'object' &&+ data !== null &&+ (data as { phase?: unknown }).phase === PERMISSION_MODE_PHASE &&+ isHeteroPermissionMode((data as { permissionMode?: unknown }).permissionMode);++/**+ * The topic patch for a mode report, shared by the server (runs hosted by+ * `lh hetero exec`) and the desktop renderer (local runs). A switch Claude Code+ * made or confirmed becomes the topic's mode; a fallback only records why,+ * keeping the pick, so the topic runs in it again wherever it can.+ */+export const permissionModeReportPatch = (+ report: Pick<PermissionModeReportData, 'fallback' | 'permissionMode'>,+): Pick<ChatTopicMetadata, 'heteroPermissionMode' | 'heteroPermissionModeFallback'> =>+ report.fallback+ ? { heteroPermissionModeFallback: report.fallback }+ : { heteroPermissionMode: report.permissionMode, heteroPermissionModeFallback: null };++/**+ * Turns Claude Code's mode reports into `step_complete` events, one per+ * change. Rides `step_complete` like other advisory phases, so the gateway+ * needs no change and consumers that do not know it ignore it.+ */+export class PermissionModeReporter {+ private last: HeteroPermissionMode | undefined;+ /** Why the session started outside the picked mode; dropped once it leaves that mode. */+ private fallback: HeteroPermissionModeFallback | undefined;++ constructor(+ private readonly operationId: string,+ fallback: HeteroPermissionModeFallback | undefined,+ ) {+ this.fallback = fallback;+ }++ /**+ * The user switched the running session to `mode`. Reports from now on+ * explain against that pick: as root a bypass pick runs as `acceptEdits`+ * with the root fallback, so the topic keeps the pick instead of taking+ * `acceptEdits`. The next report is emitted even if the mode is unchanged.+ */+ requested(mode: HeteroPermissionMode, isRoot: boolean): void {+ this.fallback = resolveClaudeCodePermissionMode(mode, isRoot).fallback;+ this.last = undefined;+ }++ /** The event for a record that reports a new mode, else undefined. */+ observe(message: unknown, stepIndex = 0): AgentStreamEvent | undefined {+ const mode = readClaudeCodePermissionMode(message);+ if (!mode || mode === this.last) return;+ this.last = mode;+ // The root fallback explains only the start mode it replaced. A later+ // `acceptEdits` (a plan approved with accepted edits) is the user's pick.+ if (this.fallback === 'root' && mode !== 'acceptEdits') this.fallback = undefined;+ const data: PermissionModeReportData = {+ fallback: this.fallback ?? null,+ permissionMode: mode,+ phase: PERMISSION_MODE_PHASE,+ };+ return {+ data,+ operationId: this.operationId,+ stepIndex,+ timestamp: Date.now(),+ type: 'step_complete',+ };+ }+}diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/request.test.ts b/packages/heterogeneous-agents/src/claudeCodePermission/request.test.tsnew file mode 100644index 00000000000..8c2e21a5fa2--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/request.test.ts@@ -0,0 +1,245 @@+import { sanitizeAgentInterventionRequestForReview } from '@lobechat/agent-gateway-client';+import { describe, expect, it } from 'vitest';++import {+ buildClaudeCodePermissionIntervention,+ CLAUDE_CODE_PERMISSION_NOTE_KEY,+ parseClaudeCodePermissionRequest,+ resolveClaudeCodePermissionDecision,+} from './request';++// Shapes recorded from Claude Code 2.1.308 under `--permission-prompt-tool stdio`.+const writeLine = {+ request: {+ description: 'a.txt',+ display_name: 'Write',+ input: { content: 'hi', file_path: '/tmp/a.txt' },+ permission_suggestions: [{ destination: 'session', mode: 'acceptEdits', type: 'setMode' }],+ subtype: 'can_use_tool',+ tool_name: 'Write',+ tool_use_id: 'toolu_write',+ },+ request_id: 'req-1',+ type: 'control_request',+};++const exitPlanLine = {+ request: {+ display_name: 'ExitPlanMode',+ input: {+ allowedPrompts: [{ prompt: 'run tests', tool: 'Bash' }],+ plan: '# Plan\n\n1. Create b.txt',+ planFilePath: '/home/u/.claude/plans/p.md',+ },+ requires_user_interaction: true,+ subtype: 'can_use_tool',+ tool_name: 'ExitPlanMode',+ tool_use_id: 'toolu_plan',+ },+ request_id: 'req-plan',+ type: 'control_request',+};++const answer = (optionId: string, note?: string) => ({+ result: { q: optionId, ...(note && { [CLAUDE_CODE_PERMISSION_NOTE_KEY]: note }) },+});++describe('parseClaudeCodePermissionRequest', () => {+ it('reads a can_use_tool control request', () => {+ expect(parseClaudeCodePermissionRequest(writeLine)).toEqual({+ blockedPath: undefined,+ decisionReason: undefined,+ description: 'a.txt',+ displayName: 'Write',+ input: { content: 'hi', file_path: '/tmp/a.txt' },+ requestId: 'req-1',+ suggestions: [{ destination: 'session', mode: 'acceptEdits', type: 'setMode' }],+ title: undefined,+ toolName: 'Write',+ toolUseId: 'toolu_write',+ });+ });++ it('ignores other records', () => {+ expect(parseClaudeCodePermissionRequest({ type: 'assistant' })).toBeUndefined();+ expect(+ parseClaudeCodePermissionRequest({+ request: { subtype: 'interrupt' },+ request_id: 'x',+ type: 'control_request',+ }),+ ).toBeUndefined();+ });+});++describe('buildClaudeCodePermissionIntervention', () => {+ it('raises a permission card a durable review accepts', () => {+ const request = parseClaudeCodePermissionRequest(writeLine)!;+ const intervention = buildClaudeCodePermissionIntervention(request);++ expect(intervention.toolCallId).toBe('cc-permission-req-1');+ expect(intervention.interactionKind).toBe('permission');+ expect(intervention.arguments.questions[0].options.map((o) => o.id)).toEqual([+ 'allow',+ 'allow_session',+ 'deny',+ ]);+ expect(+ sanitizeAgentInterventionRequestForReview({+ apiName: 'askUserQuestion',+ arguments: JSON.stringify(intervention.arguments),+ deadline: Date.now() + 1000,+ identifier: 'claude-code',+ interactionKind: intervention.interactionKind,+ provider: 'claude-code',+ toolCallId: intervention.toolCallId,+ }),+ ).toBeDefined();+ });++ it('offers no session-wide allow without suggestions', () => {+ const request = parseClaudeCodePermissionRequest({+ ...writeLine,+ request: { ...writeLine.request, permission_suggestions: undefined },+ })!;+ expect(+ buildClaudeCodePermissionIntervention(request).arguments.claudeCodePermission.options,+ ).toEqual(['allow', 'deny']);+ });++ it('raises a plan card with the plan and the requested prompts', () => {+ const intervention = buildClaudeCodePermissionIntervention(+ parseClaudeCodePermissionRequest(exitPlanLine)!,+ );+ expect(intervention.interactionKind).toBe('plan');+ expect(intervention.arguments.claudeCodePermission).toMatchObject({+ allowedPrompts: [{ prompt: 'run tests', tool: 'Bash' }],+ kind: 'exitPlan',+ options: ['approve_bypass', 'approve_accept_edits', 'approve_default', 'keep_planning'],+ plan: '# Plan\n\n1. Create b.txt',+ });+ expect(intervention.arguments.questions[0].question).toBe('# Plan\n\n1. Create b.txt');+ });++ it('hides "don\'t ask again" as root', () => {+ const intervention = buildClaudeCodePermissionIntervention(+ parseClaudeCodePermissionRequest(exitPlanLine)!,+ { isRoot: true },+ );+ expect(intervention.arguments.claudeCodePermission.options).not.toContain('approve_bypass');+ });++ it('asks to enter plan mode with allow / deny', () => {+ const intervention = buildClaudeCodePermissionIntervention(+ parseClaudeCodePermissionRequest({+ ...writeLine,+ request: { ...writeLine.request, input: {}, tool_name: 'EnterPlanMode' },+ })!,+ );+ expect(intervention.interactionKind).toBe('permission');+ expect(intervention.arguments.claudeCodePermission).toMatchObject({+ kind: 'enterPlan',+ options: ['allow', 'deny'],+ });+ });++ it('cuts long input strings in the preview', () => {+ const request = parseClaudeCodePermissionRequest({+ ...writeLine,+ request: { ...writeLine.request, input: { content: 'x'.repeat(5000), file_path: '/a' } },+ })!;+ const preview = buildClaudeCodePermissionIntervention(request).arguments.claudeCodePermission+ .input!.content as string;+ expect(preview.length).toBe(2000);+ });+});++describe('resolveClaudeCodePermissionDecision', () => {+ const write = parseClaudeCodePermissionRequest(writeLine)!;+ const plan = parseClaudeCodePermissionRequest(exitPlanLine)!;++ it('allows with the original input', () => {+ expect(resolveClaudeCodePermissionDecision(write, answer('allow'))).toEqual({+ behavior: 'allow',+ updatedInput: write.input,+ });+ });++ it('always-allow applies the suggestions to this session only', () => {+ const request = {+ ...write,+ suggestions: [+ {+ behavior: 'allow',+ destination: 'localSettings',+ rules: [{ toolName: 'Bash' }],+ type: 'addRules',+ },+ ],+ };+ expect(resolveClaudeCodePermissionDecision(request, answer('allow_session'))).toEqual({+ behavior: 'allow',+ updatedInput: write.input,+ updatedPermissions: [+ {+ behavior: 'allow',+ destination: 'session',+ rules: [{ toolName: 'Bash' }],+ type: 'addRules',+ },+ ],+ });+ });++ it('denies and interrupts without a note, carries on with one', () => {+ expect(resolveClaudeCodePermissionDecision(write, answer('deny'))).toEqual({+ behavior: 'deny',+ interrupt: true,+ message: 'The user denied this.',+ });+ expect(resolveClaudeCodePermissionDecision(write, answer('deny', 'use b.txt'))).toEqual({+ behavior: 'deny',+ message: 'The user denied this: use b.txt',+ });+ });++ it.each([+ ['approve_bypass', 'bypassPermissions'],+ ['approve_accept_edits', 'acceptEdits'],+ ['approve_default', 'default'],+ ])('%s approves the plan and switches to %s', (option, mode) => {+ expect(resolveClaudeCodePermissionDecision(plan, answer(option))).toEqual({+ behavior: 'allow',+ updatedInput: plan.input,+ updatedPermissions: [{ destination: 'session', mode, type: 'setMode' }],+ });+ });++ it('keep planning denies with the feedback', () => {+ expect(resolveClaudeCodePermissionDecision(plan, answer('keep_planning', 'add tests'))).toEqual(+ {+ behavior: 'deny',+ message: 'The user wants to keep planning. Revise the plan: add tests',+ },+ );+ });++ it('refuses bypass as root even if the answer names it', () => {+ expect(+ resolveClaudeCodePermissionDecision(plan, answer('approve_bypass'), { isRoot: true }),+ ).toMatchObject({ behavior: 'deny', interrupt: true });+ });++ it('denies and interrupts when the card ends unanswered', () => {+ expect(+ resolveClaudeCodePermissionDecision(write, {+ cancelReason: 'user_cancelled',+ cancelled: true,+ }),+ ).toEqual({+ behavior: 'deny',+ interrupt: true,+ message: 'The user stopped the run before answering.',+ });+ });+});diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/request.ts b/packages/heterogeneous-agents/src/claudeCodePermission/request.tsnew file mode 100644index 00000000000..f5019ad4f92--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/request.ts@@ -0,0 +1,345 @@+import type { AgentInterventionInteractionKind } from '@lobechat/agent-gateway-client';++import type { InterventionAnswer } from '../askUser/AskUserBridge';++/**+ * A Claude Code permission rule change, as `can_use_tool` suggests it and an+ * answer applies it (the SDK's `PermissionUpdate`).+ */+export type ClaudeCodePermissionUpdate = Record<string, unknown> & {+ destination?: string;+ type: string;+};++/** One `can_use_tool` control request Claude Code sent its host. */+export interface ClaudeCodePermissionRequest {+ blockedPath?: string;+ decisionReason?: string;+ description?: string;+ displayName?: string;+ input: Record<string, unknown>;+ /** The control request id the answer must carry. */+ requestId: string;+ suggestions?: ClaudeCodePermissionUpdate[];+ title?: string;+ toolName: string;+ toolUseId?: string;+}++/** Claude Code's decision payload (the SDK's `PermissionResult`). */+export type ClaudeCodePermissionResult =+ | {+ behavior: 'allow';+ updatedInput: Record<string, unknown>;+ updatedPermissions?: ClaudeCodePermissionUpdate[];+ }+ | { behavior: 'deny'; interrupt?: boolean; message: string };++/** What the request asks: a tool run, or a switch into / out of plan mode. */+export type ClaudeCodePermissionKind = 'enterPlan' | 'exitPlan' | 'tool';++export const CLAUDE_CODE_PERMISSION_OPTION = {+ allow: 'allow',+ allowSession: 'allow_session',+ approveAcceptEdits: 'approve_accept_edits',+ approveBypass: 'approve_bypass',+ approveDefault: 'approve_default',+ deny: 'deny',+ keepPlanning: 'keep_planning',+} as const;++export type ClaudeCodePermissionOptionId =+ (typeof CLAUDE_CODE_PERMISSION_OPTION)[keyof typeof CLAUDE_CODE_PERMISSION_OPTION];++/** Answer key for the note a user adds to a denial or to "keep planning". */+export const CLAUDE_CODE_PERMISSION_NOTE_KEY = '__note';++/**+ * Detail the dedicated card renders, carried next to the AskUserQuestion-shaped+ * `questions` every intervention surface understands.+ */+export interface ClaudeCodePermissionDetail {+ allowedPrompts?: Array<{ prompt: string; tool: string }>;+ blockedPath?: string;+ decisionReason?: string;+ description?: string;+ displayName?: string;+ /** Shallow copy of the tool input with long strings cut. */+ input?: Record<string, unknown>;+ kind: ClaudeCodePermissionKind;+ options: ClaudeCodePermissionOptionId[];+ plan?: string;+ title?: string;+ toolName: string;+}++export interface ClaudeCodePermissionInterventionArgs {+ claudeCodePermission: ClaudeCodePermissionDetail;+ questions: Array<{+ header: string;+ multiSelect: false;+ options: Array<{ id: ClaudeCodePermissionOptionId; label: string }>;+ question: string;+ }>;+}++const MAX_PREVIEW_CHARS = 2000;+/** Review surfaces accept at most this much question text. */+const MAX_QUESTION_CHARS = 4000;++const OPTION_LABELS: Record<ClaudeCodePermissionOptionId, string> = {+ allow: 'Allow',+ allow_session: 'Always allow in this session',+ approve_accept_edits: 'Approve and auto-accept edits',+ approve_bypass: "Approve and don't ask again",+ approve_default: 'Approve and ask before each edit',+ deny: 'Deny',+ keep_planning: 'Keep planning',+};++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const optionalString = (value: unknown): string | undefined =>+ typeof value === 'string' && value.length > 0 ? value : undefined;++const cut = (text: string, max: number): string =>+ text.length > max ? `${text.slice(0, max - 1)}…` : text;++/** The `can_use_tool` request in a parsed stdout line, if it is one. */+export const parseClaudeCodePermissionRequest = (+ message: unknown,+): ClaudeCodePermissionRequest | undefined => {+ if (!isRecord(message) || message.type !== 'control_request') return;+ const request = message.request;+ if (!isRecord(request) || request.subtype !== 'can_use_tool') return;+ if (typeof message.request_id !== 'string' || typeof request.tool_name !== 'string') return;++ return fromCanUseTool(message.request_id, request.tool_name, request.input, {+ blockedPath: request.blocked_path,+ decisionReason: request.decision_reason,+ description: request.description,+ displayName: request.display_name,+ suggestions: request.permission_suggestions,+ title: request.title,+ toolUseId: request.tool_use_id,+ });+};++/** The same request as the SDK's `canUseTool` callback receives it. */+export const fromCanUseTool = (+ requestId: string,+ toolName: string,+ input: unknown,+ extra: {+ blockedPath?: unknown;+ decisionReason?: unknown;+ description?: unknown;+ displayName?: unknown;+ suggestions?: unknown;+ title?: unknown;+ toolUseId?: unknown;+ },+): ClaudeCodePermissionRequest => ({+ blockedPath: optionalString(extra.blockedPath),+ decisionReason: optionalString(extra.decisionReason),+ description: optionalString(extra.description),+ displayName: optionalString(extra.displayName),+ input: isRecord(input) ? input : {},+ requestId,+ suggestions: Array.isArray(extra.suggestions)+ ? (extra.suggestions.filter(+ (entry) => isRecord(entry) && typeof entry.type === 'string',+ ) as ClaudeCodePermissionUpdate[])+ : undefined,+ title: optionalString(extra.title),+ toolName,+ toolUseId: optionalString(extra.toolUseId),+});++export const classifyClaudeCodePermission = (toolName: string): ClaudeCodePermissionKind =>+ toolName === 'ExitPlanMode' ? 'exitPlan' : toolName === 'EnterPlanMode' ? 'enterPlan' : 'tool';++const previewInput = (input: Record<string, unknown>): Record<string, unknown> =>+ Object.fromEntries(+ Object.entries(input).map(([key, value]) => [+ key,+ typeof value === 'string' ? cut(value, MAX_PREVIEW_CHARS) : value,+ ]),+ );++const readAllowedPrompts = (input: Record<string, unknown>) => {+ if (!Array.isArray(input.allowedPrompts)) return;+ const prompts = input.allowedPrompts.flatMap((entry) =>+ isRecord(entry) && typeof entry.prompt === 'string'+ ? [{ prompt: entry.prompt, tool: typeof entry.tool === 'string' ? entry.tool : 'Bash' }]+ : [],+ );+ return prompts.length > 0 ? prompts : undefined;+};++const optionsFor = (+ kind: ClaudeCodePermissionKind,+ request: ClaudeCodePermissionRequest,+ isRoot: boolean,+): ClaudeCodePermissionOptionId[] => {+ const o = CLAUDE_CODE_PERMISSION_OPTION;+ if (kind === 'exitPlan') {+ // "Don't ask again" is `bypassPermissions`, which root cannot run.+ return [+ ...(isRoot ? [] : [o.approveBypass]),+ o.approveAcceptEdits,+ o.approveDefault,+ o.keepPlanning,+ ];+ }+ if (kind === 'enterPlan') return [o.allow, o.deny];+ return request.suggestions?.length ? [o.allow, o.allowSession, o.deny] : [o.allow, o.deny];+};++/** Stable card id per request, distinct from the tool the request is about. */+export const claudeCodePermissionToolCallId = (requestId: string): string =>+ `cc-permission-${requestId}`;++/**+ * The intervention a request raises: the AskUserQuestion-shaped question every+ * surface (card, durable review, notification) understands, plus the detail+ * the dedicated Claude Code card renders.+ */+export const buildClaudeCodePermissionIntervention = (+ request: ClaudeCodePermissionRequest,+ { isRoot = false }: { isRoot?: boolean } = {},+): {+ arguments: ClaudeCodePermissionInterventionArgs;+ interactionKind: AgentInterventionInteractionKind;+ toolCallId: string;+} => {+ const kind = classifyClaudeCodePermission(request.toolName);+ const options = optionsFor(kind, request, isRoot);+ const plan = kind === 'exitPlan' ? optionalString(request.input.plan) : undefined;+ const toolLabel = request.displayName ?? request.toolName;+ const question =+ kind === 'exitPlan'+ ? (plan ?? 'Claude has finished planning.')+ : kind === 'enterPlan'+ ? 'Claude wants to enter plan mode.'+ : (request.title ?? `Claude wants to use ${toolLabel}.`);++ return {+ arguments: {+ claudeCodePermission: {+ allowedPrompts: kind === 'exitPlan' ? readAllowedPrompts(request.input) : undefined,+ blockedPath: request.blockedPath,+ decisionReason: request.decisionReason,+ description: request.description,+ displayName: request.displayName,+ input: kind === 'tool' ? previewInput(request.input) : undefined,+ kind,+ options,+ plan,+ title: request.title,+ toolName: request.toolName,+ },+ questions: [+ {+ header: kind === 'exitPlan' ? 'Review plan' : cut(toolLabel, 200),+ multiSelect: false,+ options: options.map((id) => ({ id, label: OPTION_LABELS[id] })),+ question: cut(question, MAX_QUESTION_CHARS),+ },+ ],+ },+ interactionKind: kind === 'exitPlan' ? 'plan' : 'permission',+ toolCallId: claudeCodePermissionToolCallId(request.requestId),+ };+};++const readAnswer = (+ answer: InterventionAnswer,+ options: readonly string[],+): { note?: string; optionId?: string } => {+ if (answer.cancelled || !isRecord(answer.result)) return {};+ const values = Object.entries(answer.result)+ .filter(([key]) => key !== CLAUDE_CODE_PERMISSION_NOTE_KEY)+ .flatMap(([, value]) => (Array.isArray(value) ? value : [value]));+ const optionId = values.find(+ (value): value is string => typeof value === 'string' && options.includes(value),+ );+ const note = answer.result[CLAUDE_CODE_PERMISSION_NOTE_KEY];+ return { note: typeof note === 'string' && note.trim() ? note.trim() : undefined, optionId };+};++const setMode = (mode: string): ClaudeCodePermissionUpdate => ({+ destination: 'session',+ mode,+ type: 'setMode',+});++/**+ * Turn the user's answer into Claude Code's decision.+ *+ * - "Always allow in this session" applies Claude Code's own suggestions, kept+ * to this session whatever destination it proposed.+ * - A denial without a note interrupts the turn, like "No" in Claude Code's+ * terminal: the user says what to do next. With a note Claude carries on+ * with it. "Keep planning" works the same way.+ * - No answer (the run stopped, the card was dismissed) denies and interrupts.+ */+export const resolveClaudeCodePermissionDecision = (+ request: ClaudeCodePermissionRequest,+ answer: InterventionAnswer,+ { isRoot = false }: { isRoot?: boolean } = {},+): ClaudeCodePermissionResult => {+ const o = CLAUDE_CODE_PERMISSION_OPTION;+ const kind = classifyClaudeCodePermission(request.toolName);+ const { note, optionId } = readAnswer(answer, optionsFor(kind, request, isRoot));+ const allow = (+ updatedPermissions?: ClaudeCodePermissionUpdate[],+ ): ClaudeCodePermissionResult => ({+ behavior: 'allow',+ // Required: an allow without the input reads to Claude Code as a failed callback.+ updatedInput: request.input,+ ...(updatedPermissions?.length ? { updatedPermissions } : {}),+ });++ switch (optionId) {+ case o.allow: {+ return allow();+ }+ case o.allowSession: {+ return allow(+ request.suggestions?.map((suggestion) => ({ ...suggestion, destination: 'session' })),+ );+ }+ case o.approveBypass: {+ return allow([setMode('bypassPermissions')]);+ }+ case o.approveAcceptEdits: {+ return allow([setMode('acceptEdits')]);+ }+ case o.approveDefault: {+ return allow([setMode('default')]);+ }+ case o.keepPlanning: {+ return note+ ? { behavior: 'deny', message: `The user wants to keep planning. Revise the plan: ${note}` }+ : {+ behavior: 'deny',+ interrupt: true,+ message: 'The user wants to keep planning and will say what to change.',+ };+ }+ case o.deny: {+ return note+ ? { behavior: 'deny', message: `The user denied this: ${note}` }+ : { behavior: 'deny', interrupt: true, message: 'The user denied this.' };+ }+ default: {+ return {+ behavior: 'deny',+ interrupt: true,+ message: 'The user stopped the run before answering.',+ };+ }+ }+};diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/responder.test.ts b/packages/heterogeneous-agents/src/claudeCodePermission/responder.test.tsnew file mode 100644index 00000000000..83fbb2b3065--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/responder.test.ts@@ -0,0 +1,207 @@+import { PassThrough } from 'node:stream';++import { describe, expect, it } from 'vitest';++import { AskUserBridge } from '../askUser/AskUserBridge';+import { ClaudeCodeLiveInput } from '../spawn/claudeCodeLiveInput';+import { PermissionModeReporter } from './modeReport';+import {+ askThroughBridge,+ attachClaudeCodePermissionResponder,+ buildSetPermissionModeRequest,+} from './responder';++const line = (value: unknown) => `${JSON.stringify(value)}\n`;++const setup = () => {+ const stdin = new PassThrough();+ const written: any[] = [];+ stdin.on('data', (chunk: Buffer) => {+ for (const text of chunk.toString().split('\n'))+ if (text.trim()) written.push(JSON.parse(text));+ });+ const live = new ClaudeCodeLiveInput(stdin, { idleCloseMs: 60_000 });+ const bridge = new AskUserBridge('op-1');+ const requests: any[] = [];+ void (async () => {+ for await (const event of bridge.events()) requests.push(event);+ })();+ attachClaudeCodePermissionResponder(live, {+ ask: askThroughBridge(bridge),+ cancel: (id) => bridge.cancel(id, 'session_ended'),+ });+ return { bridge, live, requests, written };+};++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++const canUseTool = {+ request: {+ input: { command: 'rm -rf build' },+ permission_suggestions: [],+ subtype: 'can_use_tool',+ tool_name: 'Bash',+ tool_use_id: 'toolu_bash',+ },+ request_id: 'req-7',+ type: 'control_request',+};++describe('attachClaudeCodePermissionResponder', () => {+ it('raises a card that never times out and writes the answer to stdin', async () => {+ const { bridge, live, requests, written } = setup();+ live.observe(line(canUseTool));+ await flush();++ expect(requests).toHaveLength(1);+ expect(requests[0].type).toBe('agent_intervention_request');+ expect(requests[0].data).toMatchObject({+ interactionKind: 'permission',+ provider: 'claude-code',+ toolCallId: 'cc-permission-req-7',+ });+ // The wire deadline is a year out: nothing on the producer side expires it.+ expect(requests[0].data.deadline - Date.now()).toBeGreaterThan(300 * 24 * 3600 * 1000);++ bridge.resolve('cc-permission-req-7', { result: { q: 'allow' } });+ await flush();++ expect(written.at(-1)).toEqual({+ response: {+ request_id: 'req-7',+ response: {+ behavior: 'allow',+ toolUseID: 'toolu_bash',+ updatedInput: { command: 'rm -rf build' },+ },+ subtype: 'success',+ },+ type: 'control_response',+ });+ });++ it('withdraws the card when Claude Code cancels the request', async () => {+ const { live, requests, written } = setup();+ live.observe(line(canUseTool));+ await flush();+ live.observe(line({ request_id: 'req-7', type: 'control_cancel_request' }));+ await flush();++ expect(requests.at(-1)).toMatchObject({+ data: { cancelled: true, toolCallId: 'cc-permission-req-7' },+ type: 'agent_intervention_response',+ });+ expect(written.at(-1).response.response).toMatchObject({ behavior: 'deny', interrupt: true });+ });++ it('answers no request once input closed', async () => {+ const { bridge, live, written } = setup();+ live.observe(line(canUseTool));+ await flush();+ live.close();+ bridge.resolve('cc-permission-req-7', { result: { q: 'allow' } });+ await flush();+ expect(written).toEqual([]);+ });+});++describe('buildSetPermissionModeRequest', () => {+ it('switches mode, turning bypass into acceptEdits as root, and keeps the pick for the host', () => {+ expect(buildSetPermissionModeRequest('plan', false)).toEqual({+ __host: { requestedMode: 'plan' },+ mode: 'plan',+ subtype: 'set_permission_mode',+ });+ expect(buildSetPermissionModeRequest('bypassPermissions', true)).toEqual({+ __host: { requestedMode: 'bypassPermissions' },+ mode: 'acceptEdits',+ subtype: 'set_permission_mode',+ });+ });++ it('never sends the host metadata to Claude Code, and hands it to listeners', () => {+ const { live, written } = setup();+ const sent: any[] = [];+ live.onControlRequestSent((request, meta) => sent.push({ meta, request }));+ live.sendControlRequest(buildSetPermissionModeRequest('bypassPermissions', true));+ expect(written[0].request).toEqual({ mode: 'acceptEdits', subtype: 'set_permission_mode' });+ expect(sent).toEqual([+ {+ meta: { requestedMode: 'bypassPermissions' },+ request: { mode: 'acceptEdits', subtype: 'set_permission_mode' },+ },+ ]);+ });+});++describe('PermissionModeReporter', () => {+ it('reports init and status modes once per change', () => {+ const reporter = new PermissionModeReporter('op-1', undefined);+ const init = reporter.observe({ permissionMode: 'plan', subtype: 'init', type: 'system' });+ expect(init).toMatchObject({+ data: { fallback: null, permissionMode: 'plan', phase: 'permission_mode' },+ operationId: 'op-1',+ type: 'step_complete',+ });+ expect(+ reporter.observe({ permissionMode: 'plan', subtype: 'init', type: 'system' }),+ ).toBeUndefined();+ // Approving the plan: Claude Code switches itself and says so.+ expect(+ reporter.observe({+ permissionMode: 'acceptEdits',+ status: null,+ subtype: 'status',+ type: 'system',+ })?.data.permissionMode,+ ).toBe('acceptEdits');+ });++ it('ignores sub-agents and modes it does not offer', () => {+ const reporter = new PermissionModeReporter('op-1', undefined);+ expect(+ reporter.observe({+ parent_tool_use_id: 'toolu_task',+ permissionMode: 'plan',+ subtype: 'init',+ type: 'system',+ }),+ ).toBeUndefined();+ expect(+ reporter.observe({ permissionMode: 'dontAsk', subtype: 'init', type: 'system' }),+ ).toBeUndefined();+ });++ it('keeps a bypass pick made mid-run as root instead of taking acceptEdits', () => {+ // Started in default on a root device; the user switches to Allow everything.+ const reporter = new PermissionModeReporter('op-1', undefined);+ reporter.observe({ permissionMode: 'default', subtype: 'init', type: 'system' });+ reporter.requested('bypassPermissions', true);+ expect(+ reporter.observe({ permissionMode: 'acceptEdits', subtype: 'status', type: 'system' })?.data,+ ).toEqual({ fallback: 'root', permissionMode: 'acceptEdits', phase: 'permission_mode' });+ // Re-reported even when the mode did not change, so the fallback reaches the topic.+ reporter.requested('bypassPermissions', true);+ expect(+ reporter.observe({ permissionMode: 'acceptEdits', subtype: 'status', type: 'system' })?.data+ .fallback,+ ).toBe('root');+ });++ it('explains the root fallback while it applies', () => {+ const reporter = new PermissionModeReporter('op-1', 'root');+ expect(+ reporter.observe({ permissionMode: 'acceptEdits', subtype: 'init', type: 'system' })?.data+ .fallback,+ ).toBe('root');+ expect(+ reporter.observe({ permissionMode: 'plan', subtype: 'status', type: 'system' })?.data+ .fallback,+ ).toBeNull();+ // Approving that plan with accepted edits is the user's own pick, not the fallback.+ expect(+ reporter.observe({ permissionMode: 'acceptEdits', subtype: 'status', type: 'system' })?.data+ .fallback,+ ).toBeNull();+ });+});diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/responder.ts b/packages/heterogeneous-agents/src/claudeCodePermission/responder.tsnew file mode 100644index 00000000000..c1aa73d4aa3--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/responder.ts@@ -0,0 +1,158 @@+import type { AgentInterventionInteractionKind } from '@lobechat/agent-gateway-client';+import type { HeteroPermissionMode } from '@lobechat/types';++import type { AskUserBridge, InterventionAnswer } from '../askUser/AskUserBridge';+import {+ type ClaudeCodeControlRequest,+ type ClaudeCodeControlRequestHandle,+ CONTROL_REQUEST_HOST_META,+} from '../spawn/claudeCodeLiveInput';+import { resolveClaudeCodePermissionMode } from './args';+import {+ buildClaudeCodePermissionIntervention,+ type ClaudeCodePermissionRequest,+ type ClaudeCodePermissionResult,+ claudeCodePermissionToolCallId,+ parseClaudeCodePermissionRequest,+ resolveClaudeCodePermissionDecision,+} from './request';++/** Raises one card and waits for the user's answer. */+export type ClaudeCodePermissionAsk = (intervention: {+ arguments: unknown;+ interactionKind: AgentInterventionInteractionKind;+ toolCallId: string;+}) => Promise<InterventionAnswer>;++/**+ * Ask through an `AskUserBridge` without a deadline: a permission request waits+ * for the user however long it takes (stopping the run ends it).+ */+export const askThroughBridge =+ (bridge: AskUserBridge): ClaudeCodePermissionAsk =>+ (intervention) =>+ bridge.pending(intervention, { timeoutMs: Number.POSITIVE_INFINITY });++/**+ * Answer one permission request: raise its card, wait, and turn the answer into+ * Claude Code's decision. Shared by the stdio responder and the SDK's+ * `canUseTool`, so both paths decide alike.+ */+export const decideClaudeCodePermission = async (+ request: ClaudeCodePermissionRequest,+ ask: ClaudeCodePermissionAsk,+ { isRoot = false }: { isRoot?: boolean } = {},+): Promise<ClaudeCodePermissionResult> => {+ const intervention = buildClaudeCodePermissionIntervention(request, { isRoot });+ let answer: InterventionAnswer;+ try {+ answer = await ask(intervention);+ } catch {+ answer = { cancelled: true, cancelReason: 'session_ended' };+ }+ return resolveClaudeCodePermissionDecision(request, answer, { isRoot });+};++/** The slice of a live Claude Code stdin the responder writes through. */+export interface ClaudeCodePermissionTransport {+ respondToControlRequest: (requestId: string, response: Record<string, unknown>) => boolean;+ subscribe: (listener: (message: unknown) => void) => () => void;+}++export interface ClaudeCodePermissionResponderOptions {+ ask: ClaudeCodePermissionAsk;+ /** Withdraw a card Claude Code no longer waits for (`control_cancel_request`). */+ cancel?: (toolCallId: string) => void;+ isRoot?: boolean;+}++/**+ * Host side of `--permission-prompt-tool stdio`: answers every `can_use_tool`+ * control request Claude Code writes to stdout with a `control_response` on+ * stdin, after the user decides on a card.+ *+ * @returns a detach function+ */+export const attachClaudeCodePermissionResponder = (+ transport: ClaudeCodePermissionTransport,+ { ask, cancel, isRoot = false }: ClaudeCodePermissionResponderOptions,+): (() => void) =>+ transport.subscribe((message) => {+ const record = message as { request_id?: unknown; type?: unknown } | undefined;+ if (record?.type === 'control_cancel_request' && typeof record.request_id === 'string') {+ cancel?.(claudeCodePermissionToolCallId(record.request_id));+ return;+ }++ const request = parseClaudeCodePermissionRequest(message);+ if (!request) return;+ void decideClaudeCodePermission(request, ask, { isRoot }).then((decision) => {+ transport.respondToControlRequest(request.requestId, {+ ...decision,+ ...(request.toolUseId && { toolUseID: request.toolUseId }),+ });+ });+ });++/**+ * The `set_permission_mode` control request for a mode the user picked mid-run,+ * adjusted to what Claude Code can run (root has no `bypassPermissions`).+ */+export const buildSetPermissionModeRequest = (+ mode: HeteroPermissionMode,+ isRoot?: boolean,+): {+ [CONTROL_REQUEST_HOST_META]: { requestedMode: HeteroPermissionMode };+ mode: HeteroPermissionMode;+ subtype: 'set_permission_mode';+} => ({+ // The pick itself, for the host's mode report; never sent to Claude Code.+ [CONTROL_REQUEST_HOST_META]: { requestedMode: mode },+ mode: resolveClaudeCodePermissionMode(mode, isRoot).mode,+ subtype: 'set_permission_mode',+});++/** How long Claude Code gets to confirm a mode switch. */+export const SET_PERMISSION_MODE_TIMEOUT_MS = 10_000;++/**+ * Switch a live CLI session's mode: write `set_permission_mode` into its stdin+ * and wait for Claude Code to confirm. The mode report follows on stdout.+ *+ * @param send Writes a control request; `undefined` once input has closed.+ * @returns the mode Claude Code switched to+ * @throws When input is closed, Claude Code refuses or never answers, or `signal` aborts.+ */+export const setClaudeCodePermissionMode = async (+ send: (request: ClaudeCodeControlRequest) => ClaudeCodeControlRequestHandle | undefined,+ mode: HeteroPermissionMode,+ {+ isRoot,+ signal,+ timeoutMs = SET_PERMISSION_MODE_TIMEOUT_MS,+ }: { isRoot?: boolean; signal?: AbortSignal; timeoutMs?: number } = {},+): Promise<HeteroPermissionMode> => {+ const request = buildSetPermissionModeRequest(mode, isRoot);+ const sent = send(request);+ if (!sent) throw new Error('The Claude Code session no longer takes input');++ let timer: NodeJS.Timeout | undefined;+ let onAbort: (() => void) | undefined;+ const cutOff = new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('Claude Code did not confirm the mode switch in time')),+ timeoutMs,+ );+ onAbort = () => reject(new Error('The run ended before Claude Code confirmed the mode'));+ if (signal?.aborted) onAbort();+ else signal?.addEventListener('abort', onAbort, { once: true });+ });+ try {+ const answer = await Promise.race([sent.response, cutOff]);+ if (answer.subtype === 'error') throw new Error(answer.error);+ return request.mode;+ } finally {+ clearTimeout(timer);+ if (onAbort) signal?.removeEventListener('abort', onAbort);+ }+};diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/shared.ts b/packages/heterogeneous-agents/src/claudeCodePermission/shared.tsnew file mode 100644index 00000000000..38fb92ab219--- /dev/null+++ b/packages/heterogeneous-agents/src/claudeCodePermission/shared.ts@@ -0,0 +1,19 @@+/**+ * Browser-safe slice of the Claude Code permission protocol: the card payload,+ * its option ids and the mode report. The responder and spawn args stay in+ * `./index` (Node only).+ */+export {+ isPermissionModeReport,+ PERMISSION_MODE_PHASE,+ type PermissionModeReportData,+ permissionModeReportPatch,+} from './modeReport';+export {+ CLAUDE_CODE_PERMISSION_NOTE_KEY,+ CLAUDE_CODE_PERMISSION_OPTION,+ type ClaudeCodePermissionDetail,+ type ClaudeCodePermissionInterventionArgs,+ type ClaudeCodePermissionKind,+ type ClaudeCodePermissionOptionId,+} from './request';diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.tsindex 853407cab4f..5084a46d977 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.test.ts@@ -89,4 +89,28 @@ describe('buildHeteroExecStdinPayload', () => {},]);});++ it('carries the permission mode in the envelope older lh releases unwrap', () => {+ const payload = JSON.parse(+ buildHeteroExecStdinPayload({ permissionMode: 'plan', prompt: 'hello' }),+ );+ expect(payload).toEqual({+ content: [{ text: 'hello', type: 'text' }],+ permissionMode: 'plan',+ });+ });++ it('keeps the resume fallback beside the permission mode', () => {+ const payload = JSON.parse(+ buildHeteroExecStdinPayload({+ permissionMode: 'default',+ prompt: 'hello',+ resumeFallbackSystemContext: 'history',+ }),+ );+ expect(payload.permissionMode).toBe('default');+ expect(payload.resumeFallback).toEqual(+ expect.arrayContaining([expect.objectContaining({ text: 'hello', type: 'text' })]),+ );+ });});diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.tsindex f0ecf1f0398..b2f54e220bc 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts@@ -1,3 +1,5 @@+import type { HeteroPermissionMode } from '@lobechat/types';+import { buildHeterogeneousPrompt } from './promptEngine';/**@@ -32,10 +34,15 @@ export interface HeteroExecImageRef {* always a new session by definition — it exists precisely because native* resume failed and the CLI is starting the agent from scratch — so it carries* session-scoped context regardless of what the primary attempt got.+ *+ * `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.*/export const buildHeteroExecStdinPayload = (params: {imageList?: HeteroExecImageRef[];isNewSession?: boolean;+ permissionMode?: HeteroPermissionMode;prompt: string;resumeFallbackSystemContext?: string;systemContext?: string;@@ -43,21 +50,26 @@ export const buildHeteroExecStdinPayload = (params: {const {imageList = [],isNewSession,+ permissionMode,prompt,resumeFallbackSystemContext,systemContext,} = params;const blocks = buildHeterogeneousPrompt({ imageList, isNewSession, prompt, systemContext });- if (resumeFallbackSystemContext !== undefined) {+ if (resumeFallbackSystemContext !== undefined || permissionMode) {return JSON.stringify({content: blocks,- resumeFallback: buildHeterogeneousPrompt({- imageList,- isNewSession: true,- prompt,- systemContext: resumeFallbackSystemContext,- }),+ ...(permissionMode && { permissionMode }),+ resumeFallback:+ resumeFallbackSystemContext === undefined+ ? undefined+ : buildHeterogeneousPrompt({+ imageList,+ isNewSession: true,+ prompt,+ systemContext: resumeFallbackSystemContext,+ }),});}diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.permission.test.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.permission.test.tsnew file mode 100644index 00000000000..e04d81eb092--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.permission.test.ts@@ -0,0 +1,158 @@+import os from 'node:os';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AskUserBridge } from '../askUser/AskUserBridge';+import { ClaudeAgentSdkSession, type ClaudeAgentSdkSessionOptions } from './claudeAgentSdkSession';++const sdkQueryMock = vi.hoisted(() => vi.fn());++vi.mock('@anthropic-ai/claude-agent-sdk', () => ({ query: sdkQueryMock }));++const baseOptions = (+ overrides: Partial<ClaudeAgentSdkSessionOptions> = {},+): ClaudeAgentSdkSessionOptions => ({+ args: [],+ commandPath: 'claude',+ cwd: os.tmpdir(),+ env: {} as NodeJS.ProcessEnv,+ onEvents: () => {},+ onRawMessage: () => {},+ onRuntimeStatus: () => {},+ onSessionId: () => {},+ onStderr: () => {},+ operationId: 'op-sdk-perm',+ sessionId: 'session-1',+ stdinPayload: `${JSON.stringify({ message: { content: 'hi', role: 'user' }, type: 'user' })}\n`,+ ...overrides,+});++describe('ClaudeAgentSdkSession permission modes', () => {+ beforeEach(() => {+ vi.spyOn(process, 'getuid').mockReturnValue(501);+ });++ afterEach(() => {+ sdkQueryMock.mockReset();+ vi.restoreAllMocks();+ });++ const optionsFor = async (overrides: Partial<ClaudeAgentSdkSessionOptions>) => {+ sdkQueryMock.mockImplementation(() => ({+ async *[Symbol.asyncIterator]() {},+ close: vi.fn(),+ }));+ await new ClaudeAgentSdkSession(baseOptions(overrides)).run();+ return sdkQueryMock.mock.calls[0][0].options;+ };++ it('bypasses every prompt when the lab picked no mode', async () => {+ const options = await optionsFor({ askUserBridge: new AskUserBridge('op') });+ expect(options.permissionMode).toBe('bypassPermissions');+ expect(options.allowDangerouslySkipPermissions).toBe(true);+ expect(options.canUseTool).toBeUndefined();+ });++ it('starts in the picked mode and asks through canUseTool', async () => {+ const options = await optionsFor({+ askUserBridge: new AskUserBridge('op'),+ permissionMode: 'default',+ });+ expect(options.permissionMode).toBe('default');+ // Permits a later switch to bypass (the chip, a plan approval).+ expect(options.allowDangerouslySkipPermissions).toBe(true);+ expect(typeof options.canUseTool).toBe('function');+ });++ it('answers canUseTool from the card, with no inactivity timeout while it waits', async () => {+ const bridge = new AskUserBridge('op-sdk-perm');+ const requests: any[] = [];+ void (async () => {+ for await (const event of bridge.events()) requests.push(event);+ })();+ let decision: unknown;+ let release!: () => void;+ const held = new Promise<void>((resolve) => {+ release = resolve;+ });++ sdkQueryMock.mockImplementation(({ options }: any) => ({+ async *[Symbol.asyncIterator]() {+ yield { permissionMode: 'default', session_id: 's', subtype: 'init', type: 'system' };+ decision = await options.canUseTool(+ 'Write',+ { content: 'hi', file_path: '/a.txt' },+ {+ requestId: 'req-sdk',+ signal: new AbortController().signal,+ suggestions: [{ destination: 'session', mode: 'acceptEdits', type: 'setMode' }],+ toolUseID: 'toolu_w',+ },+ );+ await held;+ },+ close: vi.fn(),+ }));++ process.env.LOBE_CLAUDE_CODE_SDK_INACTIVITY_TIMEOUT_MS = '20';+ const events: any[] = [];+ const session = new ClaudeAgentSdkSession(+ baseOptions({+ askUserBridge: bridge,+ onEvents: (batch) => {+ events.push(...batch);+ },+ permissionMode: 'default',+ }),+ );+ const running = session.run();+ await vi.waitFor(() => expect(requests).toHaveLength(1));+ // Longer than the inactivity timeout: the pending card holds the session.+ await new Promise((resolve) => setTimeout(resolve, 60));+ expect(requests[0].data).toMatchObject({+ interactionKind: 'permission',+ toolCallId: 'cc-permission-req-sdk',+ });++ bridge.resolve('cc-permission-req-sdk', { result: { q: 'allow_session' } });+ await vi.waitFor(() => expect(decision).toBeDefined());+ release();+ await running;+ delete process.env.LOBE_CLAUDE_CODE_SDK_INACTIVITY_TIMEOUT_MS;++ expect(decision).toEqual({+ behavior: 'allow',+ updatedInput: { content: 'hi', file_path: '/a.txt' },+ updatedPermissions: [{ destination: 'session', mode: 'acceptEdits', type: 'setMode' }],+ });+ expect(events.find((event) => event.data?.phase === 'permission_mode')?.data).toMatchObject({+ permissionMode: 'default',+ });+ });++ it('switches mode mid-run through Query.setPermissionMode', async () => {+ const setPermissionMode = vi.fn();+ let release!: () => void;+ const held = new Promise<void>((resolve) => {+ release = resolve;+ });+ sdkQueryMock.mockImplementation(() => ({+ async *[Symbol.asyncIterator]() {+ await held;+ yield* [];+ },+ close: vi.fn(),+ setPermissionMode,+ }));+ const session = new ClaudeAgentSdkSession(+ baseOptions({ askUserBridge: new AskUserBridge('op'), permissionMode: 'plan' }),+ );+ const running = session.run();+ await vi.waitFor(() => expect(sdkQueryMock).toHaveBeenCalled());+ await session.setPermissionMode('acceptEdits');+ expect(setPermissionMode).toHaveBeenCalledWith('acceptEdits');+ release();+ await running;+ await expect(session.setPermissionMode('plan')).rejects.toThrow('no longer running');+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex bba853c00e9..3358832f112 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -2,6 +2,7 @@ import { type ChildProcess } from 'node:child_process';import type {Options as ClaudeAgentSdkOptions,+ PermissionResult,Query as ClaudeAgentSdkQuery,SDKMessage,SDKUserMessage,@@ -9,8 +10,19 @@ import type {SpawnOptions as SdkSpawnOptions,} from '@anthropic-ai/claude-agent-sdk';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';+import type { HeteroPermissionMode } from '@lobechat/types';import { spawnManaged } from '@lobechat/utils/managedProcess';+import type { AskUserBridge } from '../askUser/AskUserBridge';+import {+ askThroughBridge,+ buildSetPermissionModeRequest,+ decideClaudeCodePermission,+ fromCanUseTool,+ isRunningAsRoot,+ PermissionModeReporter,+ resolveClaudeCodePermissionMode,+} from '../claudeCodePermission';import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';import { readClaudeCodeSessionCost } from './claudeCodeSessionCost';import { resolveCliSpawnPlan } from './cliSpawn';@@ -168,6 +180,8 @@ export interface HeterogeneousAgentRuntimeStatus {export interface ClaudeAgentSdkSessionOptions {args: string[];+ /** Raises the permission cards when `permissionMode` is set. */+ askUserBridge?: AskUserBridge;commandPath: string;/** Claude profile root the transcript lives under; defaults to `env.CLAUDE_CONFIG_DIR`. */configDir?: string;@@ -185,6 +199,12 @@ export interface ClaudeAgentSdkSessionOptions {onSessionId: (sessionId: string) => void;onStderr: (data: string) => Promise<void> | void;operationId: string;+ /**+ * Better Coding Experience permission mode. With `askUserBridge`, Claude+ * Code asks through `canUseTool` and each request raises a card; absent,+ * every action is allowed as before the lab.+ */+ permissionMode?: HeteroPermissionMode;/*** Have Claude Code replay every user message it reads (`--replay-user-messages`),* so a message `steer` delivers is known to be picked up.@@ -250,6 +270,10 @@ export class ClaudeAgentSdkSession {private pipeline: AgentStreamPipeline;private queryHandle: ClaudeAgentSdkQuery | undefined;private sawErrorEvent = false;+ /** Permission requests waiting for the user: no inactivity timeout meanwhile. */+ private pendingPermissions = 0;+ private readonly isRoot = isRunningAsRoot();+ private readonly modeReporter: PermissionModeReporter | undefined;/** Messages `steer` queued for the input stream, not yet handed to the SDK. */private readonly steerQueue: SDKUserMessage[] = [];/** Steered messages Claude Code has not replayed yet; input stays open for them. */@@ -265,6 +289,16 @@ export class ClaudeAgentSdkSession {operationId: options.operationId,uploadImage: options.uploadImage,});+ this.modeReporter = this.permissionPrompts+ ? new PermissionModeReporter(+ options.operationId,+ resolveClaudeCodePermissionMode(options.permissionMode!, this.isRoot).fallback,+ )+ : undefined;+ }++ private get permissionPrompts(): boolean {+ return !!this.options.permissionMode && !!this.options.askUserBridge;}async run(): Promise<void> {@@ -338,6 +372,22 @@ export class ClaudeAgentSdkSession {await this.queryHandle.stopTask(taskId);}+ /**+ * Switch the running session's permission mode (the mode chip). Claude Code+ * confirms with a `status` record, which the mode report follows.+ *+ * @returns the mode the session took (`acceptEdits` for a bypass pick as root)+ * @throws When no query is running any more.+ */+ async setPermissionMode(mode: HeteroPermissionMode): Promise<HeteroPermissionMode> {+ if (!this.queryHandle) throw new Error('The Claude Code session is no longer running');+ const taken = buildSetPermissionModeRequest(mode, this.isRoot).mode;+ // Report against the pick: as root a bypass pick runs as acceptEdits.+ this.modeReporter?.requested(mode, this.isRoot);+ await this.queryHandle.setPermissionMode(taken);+ return taken;+ }+/*** Deliver a user message into the running session. Claude Code reads it at* its next tool boundary, so a running tool is never cut short (a message@@ -371,14 +421,13 @@ export class ClaudeAgentSdkSession {);return {- allowDangerouslySkipPermissions: true,+ ...this.buildPermissionOptions(),abortController: this.abortController,cwd: this.options.cwd,disallowedTools: [...CLAUDE_SDK_DISALLOWED_TOOLS],env: this.options.env,includePartialMessages: true,pathToClaudeCodeExecutable: executablePath,- permissionMode: 'bypassPermissions',spawnClaudeCodeProcess: (spawnOptions) =>spawnClaudeCodeCliProcess(spawnOptions, {onProcessSpawn: this.options.onProcessSpawn,@@ -395,6 +444,54 @@ export class ClaudeAgentSdkSession {};}+ /**+ * Lab off: every action allowed, as before. Lab on: start in the picked mode+ * (`acceptEdits` as root, which cannot bypass) and ask through `canUseTool`.+ * Skipping permissions stays allowed off root so a later switch to+ * `bypassPermissions` takes (see `buildClaudeCodePermissionArgs`).+ */+ private buildPermissionOptions(): Pick<+ ClaudeAgentSdkOptions,+ 'allowDangerouslySkipPermissions' | 'canUseTool' | 'permissionMode'+ > {+ const bridge = this.options.askUserBridge;+ if (!this.permissionPrompts || !bridge) {+ return { allowDangerouslySkipPermissions: true, permissionMode: 'bypassPermissions' };+ }++ return {+ allowDangerouslySkipPermissions: !this.isRoot,+ canUseTool: async (toolName, input, extra) => {+ const request = fromCanUseTool(extra.requestId ?? extra.toolUseID, toolName, input, {+ ...extra,+ suggestions: extra.suggestions,+ toolUseId: extra.toolUseID,+ });+ const ask = askThroughBridge(bridge);+ this.pendingPermissions += 1;+ this.clearInactivityTimer();+ try {+ return (await decideClaudeCodePermission(+ request,+ (intervention) => {+ // Claude Code withdrew the request (the turn was interrupted).+ extra.signal.addEventListener('abort', () =>+ bridge.cancel(intervention.toolCallId, 'session_ended'),+ );+ return ask(intervention);+ },+ { isRoot: this.isRoot },+ )) as PermissionResult;+ } finally {+ this.pendingPermissions -= 1;+ this.armInactivityTimer();+ }+ },+ permissionMode: resolveClaudeCodePermissionMode(this.options.permissionMode!, this.isRoot)+ .mode,+ };+ }+private async *createInputStream(message: SDKUserMessage): AsyncIterable<SDKUserMessage> {yield message;@@ -420,6 +517,8 @@ export class ClaudeAgentSdkSession {await this.options.onRawMessage(line);const events = await this.pipeline.push(line);+ const modeReport = this.modeReporter?.observe(message);+ if (modeReport) events.unshift(modeReport);this.sawErrorEvent ||= events.some((event) => event.type === 'error');await this.options.onEvents(events);@@ -569,6 +668,8 @@ export class ClaudeAgentSdkSession {private armInactivityTimer(): void {this.clearInactivityTimer();+ // A permission request waits for the user, however long that takes.+ if (this.pendingPermissions > 0) return;this.inactivityTimer = setTimeout(() => {this.closeReason = new Error(`Claude SDK session produced no messages for ${this.inactivityTimeoutMs}ms`,diff --git a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.tsindex d45bec28057..7ddddc13887 100644--- a/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeCodeLiveInput.ts@@ -87,6 +87,13 @@ export interface ClaudeCodeControlRequest {subtype: string;}+/**+ * Key of host-only metadata on a control request (e.g. the mode the user+ * picked, where the request carries the mode Claude Code can run). Stripped+ * before the request reaches Claude Code; handed to `onControlRequestSent`.+ */+export const CONTROL_REQUEST_HOST_META = '__host';+/** Claude Code's answer to a control request. */export type ClaudeCodeControlResponse ={ response?: Record<string, unknown>; subtype: 'success' } | { error: string; subtype: 'error' };@@ -139,6 +146,10 @@ export class ClaudeCodeLiveInput {private readonly idleCloseMs: number;private lastOutcome: ClaudeCodeTurnOutcome | undefined;private lineBuffer = '';+ private readonly listeners = new Set<(message: unknown) => void>();+ private readonly sentListeners = new Set<+ (request: ClaudeCodeControlRequest, meta: Record<string, unknown> | undefined) => void+ >();private readonly pendingControl = new Map<string, (answer: ClaudeCodeControlResponse) => void>();private turnOpen = true;private readonly unconsumed = new Set<string>();@@ -194,16 +205,50 @@ export class ClaudeCodeLiveInput {): ClaudeCodeControlRequestHandle | undefined {if (this.closed) return;+ const { [CONTROL_REQUEST_HOST_META]: meta, ...wire } = request;const requestId = randomUUID();const response = new Promise<ClaudeCodeControlResponse>((resolve) => {this.pendingControl.set(requestId, resolve);});this.stdin.write(- `${JSON.stringify({ request, request_id: requestId, type: 'control_request' })}\n`,+ `${JSON.stringify({ request: wire, request_id: requestId, type: 'control_request' })}\n`,);+ for (const listener of this.sentListeners) {+ listener(wire as ClaudeCodeControlRequest, meta as Record<string, unknown> | undefined);+ }return { requestId, response };}+ /** Watch every control request the host writes, with its host-only metadata. */+ onControlRequestSent(+ listener: (+ request: ClaudeCodeControlRequest,+ meta: Record<string, unknown> | undefined,+ ) => void,+ ): () => void {+ this.sentListeners.add(listener);+ return () => this.sentListeners.delete(listener);+ }++ /**+ * Answer a control request Claude Code sent the host (`can_use_tool` under+ * `--permission-prompt-tool stdio`). Returns false once input has closed.+ */+ respondToControlRequest(requestId: string, response: Record<string, unknown>): boolean {+ if (this.closed) return false;++ this.stdin.write(+ `${JSON.stringify({ response: { request_id: requestId, response, subtype: 'success' }, type: 'control_response' })}\n`,+ );+ return true;+ }++ /** Watch every record Claude Code writes, as `observe` parses it. */+ subscribe(listener: (message: unknown) => void): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }+/** Feed raw stdout so the session state tracks what Claude Code reports. */observe(chunk: Buffer | string): void {this.lineBuffer += chunk.toString();@@ -222,6 +267,7 @@ export class ClaudeCodeLiveInput {}// Turns still run after input closes, so keep tracking them.this.observeMessage(message);+ for (const listener of this.listeners) listener(message);} catch {// Non-JSON noise on stdout carries no session state.}diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.permission.test.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.permission.test.tsnew file mode 100644index 00000000000..b9897262bb4--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.permission.test.ts@@ -0,0 +1,210 @@+import type * as ChildProcess from 'node:child_process';+import { EventEmitter } from 'node:events';+import type * as Os from 'node:os';+import { PassThrough } from 'node:stream';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AskUserBridge } from '../askUser/AskUserBridge';++const spawnCalls: Array<{ args: string[] }> = [];+let nextProc: any;++vi.mock('node:child_process', async () => {+ const actual = await vi.importActual<typeof ChildProcess>('node:child_process');+ return {+ ...actual,+ spawn: vi.fn((_command: string, args: string[]) => {+ spawnCalls.push({ args });+ return nextProc;+ }),+ };+});++vi.mock('node:os', async () => {+ const actual = await vi.importActual<typeof Os>('node:os');+ return { ...actual, platform: vi.fn(() => 'linux') };+});++/** A Claude Code child whose stdin stays readable, as a live session's does. */+const createLiveProc = () => {+ const proc = new EventEmitter() as any;+ proc.stdout = new PassThrough();+ proc.stderr = new PassThrough();+ proc.stdin = new PassThrough();+ proc.kill = vi.fn();+ proc.killed = false;+ proc.pid = 4242;+ const stdinLines: any[] = [];+ proc.stdin.on('data', (chunk: Buffer) => {+ for (const text of chunk.toString().split('\n'))+ if (text.trim()) stdinLines.push(JSON.parse(text));+ });+ const emit = (record: unknown) => proc.stdout.write(`${JSON.stringify(record)}\n`);+ const finish = () => {+ proc.stdout.end();+ proc.stderr.end();+ proc.emit('exit', 0, null);+ };+ return { emit, finish, proc, stdinLines };+};++const flush = () => new Promise((resolve) => setTimeout(resolve, 5));++describe('spawnAgent — Claude Code permission modes', () => {+ beforeEach(() => {+ spawnCalls.length = 0;+ vi.spyOn(process, 'getuid').mockReturnValue(501);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('asks over stdio, answers through the bridge and reports the mode', async () => {+ const live = createLiveProc();+ nextProc = live.proc;+ const bridge = new AskUserBridge('op-perm');+ const bridgeEvents: any[] = [];+ void (async () => {+ for await (const event of bridge.events()) bridgeEvents.push(event);+ })();++ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'claude-code',+ askUserBridge: bridge,+ liveInput: true,+ operationId: 'op-perm',+ permissionMode: 'plan',+ prompt: 'plan it',+ });++ const { args } = spawnCalls[0];+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('plan');+ expect(args[args.indexOf('--permission-prompt-tool') + 1]).toBe('stdio');+ expect(args).toContain('--allow-dangerously-skip-permissions');++ const events: any[] = [];+ const consumed = (async () => {+ for await (const event of handle.events) events.push(event);+ })();++ live.emit({ permissionMode: 'plan', session_id: 's1', subtype: 'init', type: 'system' });+ live.emit({+ request: {+ input: { plan: '# Plan' },+ subtype: 'can_use_tool',+ tool_name: 'ExitPlanMode',+ tool_use_id: 'toolu_plan',+ },+ request_id: 'req-plan',+ type: 'control_request',+ });+ await flush();++ expect(bridgeEvents[0]).toMatchObject({+ data: { interactionKind: 'plan', toolCallId: 'cc-permission-req-plan' },+ type: 'agent_intervention_request',+ });+ bridge.resolve('cc-permission-req-plan', { result: { q: 'approve_accept_edits' } });+ await flush();++ expect(live.stdinLines.at(-1)).toEqual({+ response: {+ request_id: 'req-plan',+ response: {+ behavior: 'allow',+ toolUseID: 'toolu_plan',+ updatedInput: { plan: '# Plan' },+ updatedPermissions: [{ destination: 'session', mode: 'acceptEdits', type: 'setMode' }],+ },+ subtype: 'success',+ },+ type: 'control_response',+ });++ live.emit({ permissionMode: 'acceptEdits', status: null, subtype: 'status', type: 'system' });+ await flush();+ live.finish();+ await consumed;++ expect(+ events+ .filter((event) => event.data?.phase === 'permission_mode')+ .map((event) => event.data.permissionMode),+ ).toEqual(['plan', 'acceptEdits']);+ });++ it('fails closed, never bypassing, when no bridge can answer a picked mode', async () => {+ const live = createLiveProc();+ nextProc = live.proc;+ const { spawnAgent } = await import('./spawnAgent');+ await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-nobridge',+ permissionMode: 'plan',+ prompt: 'hi',+ });+ const { args } = spawnCalls.at(-1)!;+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('plan');+ expect(args).not.toContain('--permission-prompt-tool');+ expect(args).not.toContain('--allow-dangerously-skip-permissions');+ live.finish();+ });++ it('allows everything, as before, without a mode', async () => {+ for (const options of [{ askUserBridge: new AskUserBridge('op-a') }]) {+ const live = createLiveProc();+ nextProc = live.proc;+ const { spawnAgent } = await import('./spawnAgent');+ await spawnAgent({+ agentType: 'claude-code',+ liveInput: true,+ operationId: 'op-a',+ prompt: 'hi',+ ...options,+ });+ const { args } = spawnCalls.at(-1)!;+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('bypassPermissions');+ expect(args).not.toContain('--permission-prompt-tool');+ live.finish();+ }+ });++ it('runs bypass as plain acceptEdits as root, and says why', async () => {+ vi.spyOn(process, 'getuid').mockReturnValue(0);+ const live = createLiveProc();+ nextProc = live.proc;+ const { spawnAgent } = await import('./spawnAgent');+ const handle = await spawnAgent({+ agentType: 'claude-code',+ askUserBridge: new AskUserBridge('op-root'),+ liveInput: true,+ operationId: 'op-root',+ permissionMode: 'bypassPermissions',+ prompt: 'hi',+ });++ const { args } = spawnCalls[0];+ expect(args[args.indexOf('--permission-mode') + 1]).toBe('acceptEdits');+ // Nothing pre-approved: a rule would outlive a switch to a stricter mode.+ expect(args).not.toContain('--allowed-tools');+ expect(args).not.toContain('--allow-dangerously-skip-permissions');++ const events: any[] = [];+ const consumed = (async () => {+ for await (const event of handle.events) events.push(event);+ })();+ live.emit({ permissionMode: 'acceptEdits', session_id: 's', subtype: 'init', type: 'system' });+ await flush();+ live.finish();+ await consumed;+ expect(events.find((event) => event.data?.phase === 'permission_mode')?.data).toEqual({+ fallback: 'root',+ permissionMode: 'acceptEdits',+ phase: 'permission_mode',+ });+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex fbe68de7652..e195fd583ef 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -2,10 +2,20 @@ 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 { isHeteroPermissionMode } from '@lobechat/types';import { spawnManaged } from '@lobechat/utils/managedProcess';import { ClaudeCodeAdapter } from '../adapters/claudeCode';import type { AskUserBridge } from '../askUser/AskUserBridge';+import {+ askThroughBridge,+ attachClaudeCodePermissionResponder,+ buildClaudeCodePermissionArgs,+ isRunningAsRoot,+ PermissionModeReporter,+ resolveClaudeCodePermissionMode,+} from '../claudeCodePermission';import { resolveHeterogeneousAgentCommand } from '../config';import {spawnCopilotAcpAgent,@@ -98,6 +108,14 @@ export interface SpawnAgentOptions {* events still carry the conventional shape.*/operationId: string;+ /**+ * (Claude Code `liveInput` with an `askUserBridge`) The permission mode the+ * Better Coding Experience lab picked. Claude Code then asks the host before+ * acting as the mode requires, the bridge raises a card per request, and the+ * mode Claude Code reports is emitted as `step_complete { phase:+ * 'permission_mode' }`. Absent: every action is allowed, as before the lab.+ */+ permissionMode?: HeteroPermissionMode;/*** User prompt. A plain string is sugar for a single text block; the array* form supports mixed text + image content blocks (URL / path / base64).@@ -229,21 +247,6 @@ export const CODEBUDDY_BASE_ARGS = [CODEBUDDY_DISALLOWED_TOOLS.join(','),] as const;-// bypassPermissions is blocked when running as root (e.g. cloud sandbox).-// Fall back to acceptEdits + pre-approved tools so the agent can still run-// headlessly without interactive permission prompts.-const isRunningAsRoot = () => process.getuid?.() === 0;--const CLAUDE_CODE_PERMISSION_ARGS = (): string[] =>- isRunningAsRoot()- ? [- '--permission-mode',- 'acceptEdits',- '--allowed-tools',- 'Bash,Read,Write,Edit,MultiEdit,WebSearch,mcp__*',- ]- : ['--permission-mode', 'bypassPermissions'];-export const CODEX_REQUIRED_ARGS = ['--json', '--skip-git-repo-check'] as const;export const CODEX_BYPASS_APPROVALS_AND_SANDBOX_ARG = '--dangerously-bypass-approvals-and-sandbox';export const CODEX_DEFAULT_EXECUTION_ARGS = [CODEX_BYPASS_APPROVALS_AND_SANDBOX_ARG] as const;@@ -298,6 +301,10 @@ interface BuildSpawnArgsParams {inputArgs: string[];/** (Claude Code only) Replay consumed user messages for live input. */liveInput?: boolean;+ /** (Claude Code only) Lab permission mode the host answers prompts for. */+ permissionMode?: HeteroPermissionMode;+ /** (Claude Code only) Someone answers prompts; without, a mode fails closed. */+ permissionPrompts?: boolean;/** Native session id for resume; undefined for fresh runs. */resumeSessionId: string | undefined;}@@ -307,12 +314,14 @@ const buildClaudeCodeArgs = ({includePartialMessages,inputArgs,liveInput,+ permissionMode,+ permissionPrompts,resumeSessionId,}: BuildSpawnArgsParams) => [...CLAUDE_CODE_BASE_ARGS,...(includePartialMessages ? ['--include-partial-messages'] : []),...(liveInput ? ['--replay-user-messages'] : []),- ...CLAUDE_CODE_PERMISSION_ARGS(),+ ...buildClaudeCodePermissionArgs({ hostPrompts: permissionPrompts, mode: permissionMode }),...(resumeSessionId ? ['--resume', resumeSessionId] : []),...inputArgs,...extraArgs,@@ -554,6 +563,10 @@ const spawnCliAgent = async (codexJwtFile: CodexJwtFile | undefined,): Promise<SpawnAgentHandle> => {const liveInput = options.agentType === 'claude-code' && options.liveInput === true;+ // Prompts need someone to answer them: the live stdin and a card bridge.+ // Without, a picked mode still applies and fails closed (never bypass).+ const permissionMode = options.agentType === 'claude-code' ? options.permissionMode : undefined;+ const permissionPrompts = liveInput && !!options.askUserBridge;const args = buildSpawnArgs({agentType: options.agentType,configArgs:@@ -564,6 +577,8 @@ const spawnCliAgent = async (includePartialMessages: options.includePartialMessages ?? false,inputArgs: inputPlan.args,liveInput,+ permissionMode,+ permissionPrompts,resumeSessionId: options.resumeSessionId,});const initialModel =@@ -660,6 +675,32 @@ const spawnCliAgent = async (}const live = liveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : undefined;+ if (live && permissionMode && permissionPrompts && options.askUserBridge) {+ const bridge = options.askUserBridge;+ const isRoot = isRunningAsRoot();+ attachClaudeCodePermissionResponder(live, {+ ask: askThroughBridge(bridge),+ cancel: (toolCallId) => bridge.cancel(toolCallId, 'session_ended'),+ isRoot,+ });+ const reporter = new PermissionModeReporter(+ options.operationId,+ resolveClaudeCodePermissionMode(permissionMode, isRoot).fallback,+ );+ // A mid-run switch: report against the pick (root takes acceptEdits for bypass).+ live.onControlRequestSent((request, meta) => {+ const requestedMode = meta?.requestedMode;+ if (request.subtype === 'set_permission_mode' && isHeteroPermissionMode(requestedMode)) {+ reporter.requested(requestedMode, isRoot);+ }+ });+ live.subscribe((message) => {+ const event = reporter.observe(message);+ if (!event) return;+ queue.push(event);+ wake();+ });+ }if (live) {live.send(inputPlan.stdin);} else if (proc.stdin) {diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 5e90e7fb1e2..0de6341c97f 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -682,6 +682,30 @@ export default {'groupWizard.searchTemplates': 'Search templates...','groupWizard.title': 'Create Group','groupWizard.useTemplate': 'Use Template',+ 'heteroAgent.permissionMode.label': 'Permission mode',+ '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.permissionMode.default.title': 'Ask every time',+ 'heteroAgent.permissionMode.default.desc': 'Asks before every edit and command',+ 'heteroAgent.permissionMode.acceptEdits.title': 'Accept edits',+ 'heteroAgent.permissionMode.acceptEdits.desc': 'Edits go ahead; commands still ask',+ 'heteroAgent.permissionMode.auto.title': 'Auto',+ 'heteroAgent.permissionMode.auto.desc': 'Claude Code decides what needs asking',+ 'heteroAgent.permissionMode.plan.title': 'Plan',+ 'heteroAgent.permissionMode.plan.desc': 'Reads and plans only; acts once you approve the plan',+ 'heteroAgent.permissionMode.bypassPermissions.title': 'Allow everything',+ 'heteroAgent.permissionMode.bypassPermissions.desc': 'Never asks; runs every action',+ 'heteroAgent.permissionMode.fallback.root':+ 'Running as root can’t allow everything, so this run accepts edits and asks before other commands.',+ 'heteroAgent.permissionMode.fallback.outdatedCli':+ 'The last run allowed every action: lh on this device is too old for permission modes. Update lh to apply “{{mode}}”.',+ 'heteroAgent.permissionMode.switchFailed':+ 'Couldn’t switch the running session. The new mode applies from the next message.',+ '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.saveFailed': 'Couldn’t save the permission mode. Try again.','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/tool.ts b/packages/locales/src/default/tool.tsindex 8946fa49825..34a0bfd3806 100644--- a/packages/locales/src/default/tool.ts+++ b/packages/locales/src/default/tool.ts@@ -67,6 +67,36 @@ export default {'claudeCode.askUserQuestion.multiSelectTag': '(multi-select)','claudeCode.askUserQuestion.recommendedTag': 'Recommended','claudeCode.askUserQuestion.skip': 'Skip',+ 'claudeCode.permission.tool.title': 'Claude wants to use {{tool}}',+ 'claudeCode.permission.tool.reason': 'Why it asks',+ 'claudeCode.permission.tool.blockedPath': 'Outside the allowed directories: {{path}}',+ 'claudeCode.permission.enterPlan.title': 'Claude wants to enter plan mode',+ 'claudeCode.permission.enterPlan.desc':+ 'It will read and plan only, and ask you to approve the plan before changing anything.',+ 'claudeCode.permission.exitPlan.title': 'Claude’s plan is ready',+ 'claudeCode.permission.exitPlan.allowedPrompts': 'Approving also lets Claude run:',+ 'claudeCode.permission.inspector.permission': 'Permission request',+ 'claudeCode.permission.inspector.plan': 'Plan approval',+ 'claudeCode.permission.option.allow': 'Allow',+ 'claudeCode.permission.option.allow_session': 'Always allow in this session',+ 'claudeCode.permission.option.deny': 'Deny',+ 'claudeCode.permission.option.approve_bypass': 'Approve, don’t ask again',+ 'claudeCode.permission.option.approve_accept_edits': 'Approve, accept edits',+ 'claudeCode.permission.option.approve_default': 'Approve, ask before each edit',+ 'claudeCode.permission.option.keep_planning': 'Keep planning',+ 'claudeCode.permission.denyNote.placeholder': 'Tell Claude what to do instead (optional)',+ 'claudeCode.permission.planNote.placeholder': 'What should change in the plan? (optional)',+ 'claudeCode.permission.waiting': 'Claude is waiting for your answer',+ 'claudeCode.permission.resolving': 'Sending your answer…',+ 'claudeCode.permission.result.allow': 'Allowed',+ 'claudeCode.permission.result.allow_session': 'Always allowed in this session',+ 'claudeCode.permission.result.deny': 'Denied',+ 'claudeCode.permission.result.approve_bypass': 'Plan approved, won’t ask again',+ 'claudeCode.permission.result.approve_accept_edits': 'Plan approved, accepting edits',+ 'claudeCode.permission.result.approve_default': 'Plan approved, asking before each edit',+ 'claudeCode.permission.result.keep_planning': 'Asked Claude to keep planning',+ 'claudeCode.permission.result.cancelled': 'Not answered: the run stopped',+ 'claudeCode.permission.result.note': 'Your note: {{note}}','claudeCode.askUserQuestion.submit': 'Submit','claudeCode.askUserQuestion.timeExpired': 'Time expired — using option 1 of each question.','claudeCode.askUserQuestion.timeExpiredNoAnswer':diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex ed1e3fbfdf7..3d907358f83 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -6,6 +6,7 @@ import type { DeviceUnavailableErrorData } from '../device';import { workingDirConfigSchema } from '../device';import type { EvalToolForwardingConfig } from '../eval/agentEval';import type { EvalMemoryReference } from '../eval/evalMemory';+import { HETERO_PERMISSION_MODES } from '../heteroPermissionMode';import type { ComposerUserMessage, TaskDetail, UIChatMessage } from '../message';import type { ChatTopic } from '../topic';@@ -24,6 +25,11 @@ export * from './modelFacts';* and the call still answers 200.*/export const initialTopicMetadataSchema = z.object({+ /**+ * Claude Code permission mode the composer chip showed (Better Coding+ * Experience); the topic's first dispatched run starts in it.+ */+ heteroPermissionMode: z.enum(HETERO_PERMISSION_MODES).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 73642ae3e14..144e4df300d 100644--- a/packages/types/src/agentExecution/initialTopicMetadata.test.ts+++ b/packages/types/src/agentExecution/initialTopicMetadata.test.ts@@ -9,6 +9,7 @@ describe('initialTopicMetadataSchema', () => {// still answers 200, so the loss is invisible from both ends — which is why// the assertion is on the parse rather than on any caller.const metadata = {+ heteroPermissionMode: 'plan' as const,repos: ['lobehub/lobehub'],sandboxInstanceId: 'a2c1d0e4-0000-4000-8000-000000000000',sandboxWorkingDirectory: 'reports',diff --git a/packages/types/src/heteroPermissionMode.test.ts b/packages/types/src/heteroPermissionMode.test.tsnew file mode 100644index 00000000000..078f9feddfc--- /dev/null+++ b/packages/types/src/heteroPermissionMode.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import {+ applyHeteroPermissionModeDir,+ HETERO_PERMISSION_MODE_DIRS_LIMIT,+ isHeteroPermissionMode,+ readHeteroPermissionModeDir,+} from './heteroPermissionMode';++describe('heteroPermissionMode', () => {+ it('accepts only the offered modes', () => {+ expect(isHeteroPermissionMode('plan')).toBe(true);+ expect(isHeteroPermissionMode('dontAsk')).toBe(false);+ expect(isHeteroPermissionMode(undefined)).toBe(false);+ });++ it('reads the remembered mode, defaulting to bypass', () => {+ const dirs = [{ key: 'd::/a', mode: 'plan' as const }];+ expect(readHeteroPermissionModeDir(dirs, 'd::/a')).toBe('plan');+ expect(readHeteroPermissionModeDir(dirs, 'd::/b')).toBe('bypassPermissions');+ expect(readHeteroPermissionModeDir(undefined, 'd::/a')).toBe('bypassPermissions');+ });++ it('moves the latest pick to the front and drops the default', () => {+ const start = [+ { key: 'd::/a', mode: 'plan' as const },+ { key: 'd::/b', mode: 'default' as const },+ ];+ expect(applyHeteroPermissionModeDir(start, 'd::/b', 'acceptEdits')).toEqual([+ { key: 'd::/b', mode: 'acceptEdits' },+ { key: 'd::/a', mode: 'plan' },+ ]);+ expect(applyHeteroPermissionModeDir(start, 'd::/a', 'bypassPermissions')).toEqual([+ { key: 'd::/b', mode: 'default' },+ ]);+ });++ it('caps the list, evicting the least recently set', () => {+ const full = Array.from({ length: HETERO_PERMISSION_MODE_DIRS_LIMIT }, (_, i) => ({+ key: `d::/${i}`,+ mode: 'plan' as const,+ }));+ const next = applyHeteroPermissionModeDir(full, 'd::/new', 'auto');+ expect(next).toHaveLength(HETERO_PERMISSION_MODE_DIRS_LIMIT);+ expect(next[0]).toEqual({ key: 'd::/new', mode: 'auto' });+ expect(next.at(-1)?.key).toBe(`d::/${HETERO_PERMISSION_MODE_DIRS_LIMIT - 2}`);+ });+});diff --git a/packages/types/src/heteroPermissionMode.ts b/packages/types/src/heteroPermissionMode.tsnew file mode 100644index 00000000000..d7f0be86b34--- /dev/null+++ b/packages/types/src/heteroPermissionMode.ts@@ -0,0 +1,72 @@+/**+ * Claude Code permission modes a topic can run in (Better Coding Experience+ * lab). Claude Code also has `dontAsk`, which is deliberately not offered.+ *+ * - `default`: ask before every edit and command.+ * - `acceptEdits`: edits run, commands still ask.+ * - `auto`: Claude Code's own classifier decides what to ask.+ * - `plan`: read-only until the plan is approved.+ * - `bypassPermissions`: never ask (what every run did before the lab).+ */+export const HETERO_PERMISSION_MODES = [+ 'default',+ 'acceptEdits',+ 'auto',+ 'plan',+ 'bypassPermissions',+] as const;++export type HeteroPermissionMode = (typeof HETERO_PERMISSION_MODES)[number];++/** Opening the lab changes nothing until the user picks another mode. */+export const DEFAULT_HETERO_PERMISSION_MODE: HeteroPermissionMode = 'bypassPermissions';++export const isHeteroPermissionMode = (value: unknown): value is HeteroPermissionMode =>+ typeof value === 'string' && (HETERO_PERMISSION_MODES as readonly string[]).includes(value);++/**+ * Why a run is not in the mode the user picked:+ *+ * - `root`: Claude Code refuses `bypassPermissions` as root (a cloud sandbox),+ * so the run uses `acceptEdits` with the common tools pre-approved.+ * - `outdatedCli`: the device's `lh` predates permission modes and ran the+ * topic with every action allowed.+ */+export type HeteroPermissionModeFallback = 'outdatedCli' | 'root';++/**+ * The mode a topic starts its next new topic with, remembered per device ++ * directory (see `getWorktreeModeKey`) and stored per workspace + user like the+ * "New worktree" switch. Most recently set first; the default mode is not+ * stored, so a list rather than a map keeps the eviction order jsonb loses.+ */+export interface HeteroPermissionModeDir {+ key: string;+ mode: HeteroPermissionMode;+}++export const HETERO_PERMISSION_MODE_DIRS_LIMIT = 200;++/** The remembered mode for `key`, or the default when none is stored. */+export const readHeteroPermissionModeDir = (+ dirs: readonly HeteroPermissionModeDir[] | undefined,+ key: string,+): HeteroPermissionMode => {+ const mode = dirs?.find((entry) => entry.key === key)?.mode;+ return isHeteroPermissionMode(mode) ? mode : DEFAULT_HETERO_PERMISSION_MODE;+};++/** The list after remembering `mode` for `key`: moved to the front, the default dropped, capped. */+export const applyHeteroPermissionModeDir = (+ current: readonly HeteroPermissionModeDir[] | undefined,+ key: string,+ mode: HeteroPermissionMode,+): HeteroPermissionModeDir[] => {+ const rest = (current ?? []).filter(+ (entry) => entry.key !== key && isHeteroPermissionMode(entry.mode),+ );+ return (mode === DEFAULT_HETERO_PERMISSION_MODE ? rest : [{ key, mode }, ...rest]).slice(+ 0,+ HETERO_PERMISSION_MODE_DIRS_LIMIT,+ );+};diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex a02a81cd806..cd846974719 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -100,6 +100,7 @@ export * from './agentRuntime';export * from './artboard';export * from './connector';export * from './connectorToolIdentifier';+export * from './heteroPermissionMode';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 e930cc85d8f..566b66c6533 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -10,6 +10,8 @@ import type {import type { SerializedAgentHook } from '../agentHook';import type { WorkingDirConfig } from '../device';import { workingDirConfigSchema } from '../device';+import type { HeteroPermissionMode, HeteroPermissionModeFallback } from '../heteroPermissionMode';+import { HETERO_PERMISSION_MODES } from '../heteroPermissionMode';import type { BotSenderMetadata } from '../message';import type { BaseDataModel } from '../meta';import type { OwnedWorktree } from '../ownedWorktree';@@ -238,6 +240,20 @@ export interface ChatTopicMetadata {* agent's effort" by `applyTopicModelToHeterogeneousProvider`.*/heteroEffort?: HeterogeneousReasoningEffort;+ /**+ * Claude Code permission mode of this topic (Better Coding Experience lab):+ * what its next run starts in, and the mode Claude Code last reported, so a+ * switch Claude Code made itself (leaving plan mode) sticks.+ */+ heteroPermissionMode?: HeteroPermissionMode;+ /** Why the last run was not in the picked mode; cleared by a run that was. */+ heteroPermissionModeFallback?: HeteroPermissionModeFallback | null;+ /**+ * Operation dispatched to `lh hetero exec` with a mode that asks, whose run+ * has not reported Claude Code's mode yet. Still set when it ends cleanly:+ * that `lh` predates permission modes (`outdatedCli`). Server-written only.+ */+ heteroPermissionModeReportPending?: string | null;/** Latest Task run's dispatched settings; no args, credentials or system context. */heteroRuntimeConfig?: {/** Per-field configuration and provenance captured before dispatch. */@@ -726,6 +742,8 @@ export const chatTopicMetadataUpdateSchema = z.object({heteroSessionBindingKeyByWorkingDirectory: z.record(z.string(), z.string()).optional(),heteroSessionId: z.string().optional(),heteroSessionIdByWorkingDirectory: z.record(z.string(), z.string()).optional(),+ heteroPermissionMode: z.enum(HETERO_PERMISSION_MODES).optional(),+ heteroPermissionModeFallback: z.enum(['outdatedCli', 'root']).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 e7519e96e60..ae834c2deff 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -3,6 +3,7 @@ import { z } from 'zod';import type { DeviceExecutionTarget } from '../agent/agencyConfig';import type { AgentModelOverride } from '../agent/modelSelection';+import type { HeteroPermissionModeDir } from '../heteroPermissionMode';import type { Plans } from '../subscription';import type { TopicGroupMode, TopicSortBy } from '../topic';import type { UserAgentOnboarding } from './agentOnboarding';@@ -68,6 +69,12 @@ export interface WorkspaceUserPreference {agentModelOverrides?: Record<string /* agentId */, AgentModelOverride>;/** Per-member Agent/Chat runtime mode for shared workspace agents. */agentModeOverrides?: Record<string /* agentId */, boolean>;+ /**+ * The Claude Code permission mode this member last picked per directory (see+ * `HeteroPermissionModeDir`), which a new topic there starts in. Written only+ * through `workspaceUserSettings.setHeteroPermissionModeDir`.+ */+ heteroPermissionModeDirs?: HeteroPermissionModeDir[];/*** This member's notification preferences for workspace-scoped scenarios* (the `workspace` category of the scenario registry). Same shape as the@@ -346,6 +353,12 @@ export interface UserPreference {*/fontFamily?: string;guide?: UserGuide;+ /**+ * Personal-mode counterpart of {@link WorkspaceUserPreference.heteroPermissionModeDirs};+ * written only through `user.setHeteroPermissionModeDir`, absent from the+ * schema for the same reason as `worktreeModeDirs`.+ */+ heteroPermissionModeDirs?: HeteroPermissionModeDir[];hideSyncAlert?: boolean;/*** lab experimental featuresdiff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsxnew file mode 100644index 00000000000..f69c8a024c3--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsx@@ -0,0 +1,169 @@+'use client';++import type { HeteroPermissionMode } from '@lobechat/types';+import { HETERO_PERMISSION_MODES } from '@lobechat/types';+import { type DropdownItem } from '@lobehub/ui';+import { Button, Center, DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ Check,+ ChevronDown,+ ClipboardList,+ FilePen,+ Hand,+ type LucideIcon,+ ShieldOff,+ Sparkles,+ TriangleAlert,+} from 'lucide-react';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { usePermissionMode } from './usePermissionMode';++const MODE_ICONS: Record<HeteroPermissionMode, LucideIcon> = {+ acceptEdits: FilePen,+ auto: Sparkles,+ bypassPermissions: ShieldOff,+ default: Hand,+ plan: ClipboardList,+};++const styles = stylex.create({+ desc: { fontSize: '12px', lineHeight: 1.4, color: cssVar.colorTextDescription },+ icon: {+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorFillTertiary,+ borderRadius: cssVar.borderRadius,+ backgroundColor: cssVar.colorBgElevated,+ backgroundImage: 'none',+ },+ label: {+ display: {+ 'default': null,+ '@container runtimebar (width < 600px)': 'none',+ },+ },+ modeButton: { fontSize: cssVar.fontSizeSM, color: cssVar.colorTextSecondary },+ notice: {+ maxWidth: '280px',+ paddingBlock: '4px',+ paddingInline: '4px',+ fontSize: '12px',+ lineHeight: 1.5,+ color: cssVar.colorWarning,+ },+ title: { fontSize: '14px', fontWeight: 500, lineHeight: 1.4, color: cssVar.colorText },+ trigger: { overflow: 'hidden', borderRadius: cssVar.borderRadius },+ warning: { color: cssVar.colorWarning },+});++const ModeItemLabel = memo<{ desc: string; icon: LucideIcon; title: string }>(+ ({ desc, icon, title }) => (+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <Center className={stylex.props(styles.icon).className} flex={'none'} height={32} width={32}>+ <Icon icon={icon} />+ </Center>+ <Flexbox flex={1} style={{ minWidth: 160 }}>+ <div {...stylex.props(styles.title)}>{title}</div>+ <div {...stylex.props(styles.desc)}>{desc}</div>+ </Flexbox>+ </Flexbox>+ ),+);++interface PermissionModeSelectorProps {+ agentId: string;+ topicId: string | null | undefined;+}++/**+ * The composer's Claude Code permission mode (Better Coding Experience lab).+ * The chip names the mode the topic's run is in; when that is not the picked+ * one (root, an outdated `lh`), it says why.+ */+const PermissionModeSelector = memo<PermissionModeSelectorProps>(({ agentId, topicId }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const { fallback, mode, runningMode, select, switchPending } = usePermissionMode(+ agentId,+ topicId,+ );++ const title = useCallback(+ (value: HeteroPermissionMode) => t(`heteroAgent.permissionMode.${value}.title`),+ [t],+ );+ const notice = switchPending+ ? t('heteroAgent.permissionMode.switchPendingNotice', {+ next: title(mode),+ running: title(runningMode),+ })+ : fallback+ ? t(`heteroAgent.permissionMode.fallback.${fallback}`, { mode: title(mode) })+ : undefined;+ const warn = switchPending || !!fallback;++ const items: DropdownItem[] = [+ ...(notice+ ? [+ {+ disabled: true,+ key: 'notice',+ label: <div {...stylex.props(styles.notice)}>{notice}</div>,+ } satisfies DropdownItem,+ { type: 'divider' as const },+ ]+ : []),+ ...HETERO_PERMISSION_MODES.map((value) => ({+ extra: value === mode ? <Icon icon={Check} /> : undefined,+ key: value,+ label: (+ <ModeItemLabel+ desc={t(`heteroAgent.permissionMode.${value}.desc`)}+ icon={MODE_ICONS[value]}+ title={title(value)}+ />+ ),+ onClick: () => void select(value),+ })),+ ];++ const button = (+ <Button+ aria-label={t('heteroAgent.permissionMode.label')}+ className={stylex.props(styles.modeButton).className}+ icon={ChevronDown}+ iconPosition="end"+ size="small"+ type={'text'}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon+ icon={warn ? TriangleAlert : MODE_ICONS[runningMode]}+ size={14}+ {...(warn ? stylex.props(styles.warning) : {})}+ />+ <span {...stylex.props(styles.label)}>{title(runningMode)}</span>+ </Flexbox>+ </Button>+ );++ return (+ <DropdownMenu items={items} open={open} placement="topRight" onOpenChange={setOpen}>+ <div data-testid={'hetero-permission-mode'} {...stylex.props(styles.trigger)}>+ {open ? (+ button+ ) : (+ <Tooltip title={notice ?? t('heteroAgent.permissionMode.tooltip')}>{button}</Tooltip>+ )}+ </div>+ </DropdownMenu>+ );+});++PermissionModeSelector.displayName = 'PermissionModeSelector';++export default PermissionModeSelector;diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.tsnew file mode 100644index 00000000000..1bb5e05dc81--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.ts@@ -0,0 +1,184 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { aiAgentService } from '@/services/aiAgent';+import { useChatStore } from '@/store/chat';+import {+ applyPermissionModeReport,+ clearSwitchUnapplied,+ pendingHeteroPermissionModeMetadata,+ registerLocalPermissionModeSwitcher,+} from '@/store/chat/heteroPermissionMode';+import { useUserStore } from '@/store/user';++import { usePermissionMode } from './usePermissionMode';++const toast = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn() }));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast,+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => null,+ useActiveWorkspaceId: () => null,+}));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ agencyConfig: { boundDeviceId: 'dev-1' },+ workspaceScoped: false,+ }),+}));+vi.mock('@/helpers/agentWorkingDirectory', () => ({ resolveTargetDeviceId: () => 'dev-1' }));+vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({+ useEffectiveWorkingDirectory: () => '/repo',+}));+vi.mock('@/services/aiAgent', () => ({+ aiAgentService: { setHeteroPermissionMode: vi.fn() },+}));++const setDir = vi.fn(async () => {});+// Writes the patch into the seeded topic, as the real action does optimistically.+const updateTopicMetadata = vi.fn(async (_id: string, patch: Record<string, unknown>) => {+ const item = (useChatStore.getState().topicDataMap as any).k.items[0];+ useChatStore.setState({+ topicDataMap: { k: { items: [{ ...item, metadata: { ...item.metadata, ...patch } }] } } as any,+ });+});++const seedTopic = (metadata: Record<string, unknown>) =>+ useChatStore.setState({+ topicDataMap: { k: { items: [{ id: 'topic-1', metadata, title: 't' }] } } as any,+ updateTopicMetadata,+ });++describe('usePermissionMode', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ clearSwitchUnapplied('topic-1');+ useUserStore.setState({+ preference: {+ heteroPermissionModeDirs: [{ key: 'dev-1::/repo', mode: 'plan' }],+ lab: { enableBetterCodingExperience: true },+ } as any,+ setHeteroPermissionModeDir: setDir,+ useFetchWorkspaceUserPreference: () => {},+ } as any);+ });++ it('starts a new topic in the mode last picked for this device + directory', () => {+ const { result } = renderHook(() => usePermissionMode('agent-1', undefined));+ expect(result.current.mode).toBe('plan');+ // The topic the send creates is born with it.+ expect(pendingHeteroPermissionModeMetadata('agent-1', 'claude-code')).toEqual({+ heteroPermissionMode: 'plan',+ });+ });++ it('writes a pick to the topic, remembers it and switches the local run', async () => {+ seedTopic({ heteroPermissionMode: 'default' });+ const switcher = vi.fn(async () => {});+ const unregister = registerLocalPermissionModeSwitcher('topic-1', switcher);+ const { result } = renderHook(() => usePermissionMode('agent-1', 'topic-1'));+ expect(result.current.mode).toBe('default');++ await act(() => result.current.select('acceptEdits'));++ expect(setDir).toHaveBeenCalledWith('dev-1::/repo', 'acceptEdits');+ expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ heteroPermissionMode: 'acceptEdits',+ heteroPermissionModeFallback: null,+ });+ expect(switcher).toHaveBeenCalledWith('acceptEdits');+ unregister();+ });++ it('switches a run hosted by lh, and says when that lh cannot', async () => {+ seedTopic({+ heteroPermissionMode: 'default',+ runningOperation: { assistantMessageId: 'a', operationId: 'op-remote' },+ });+ vi.mocked(aiAgentService.setHeteroPermissionMode).mockResolvedValue({+ status: 'unsupported',+ } as any);+ const { result } = renderHook(() => usePermissionMode('agent-1', 'topic-1'));++ await act(() => result.current.select('plan'));++ expect(aiAgentService.setHeteroPermissionMode).toHaveBeenCalledWith({+ mode: 'plan',+ operationId: 'op-remote',+ });+ expect(toast.info).toHaveBeenCalledWith('heteroAgent.permissionMode.switchUnsupported');+ // The running session never left "Ask every time": the chip says so, and the+ // pick waits for the next message.+ expect(result.current).toMatchObject({+ mode: 'plan',+ runningMode: 'default',+ switchPending: true,+ });++ // Claude Code reporting its mode again ends the guess.+ await act(() =>+ applyPermissionModeReport(+ () => useChatStore.getState(),+ 'topic-1',+ { fallback: null, permissionMode: 'plan' },+ { persist: false },+ ),+ );+ expect(result.current.switchPending).toBe(false);+ });++ it('still switches the run when remembering the directory pick fails', async () => {+ seedTopic({ heteroPermissionMode: 'bypassPermissions' });+ setDir.mockRejectedValueOnce(new Error('offline'));+ const switcher = vi.fn(async () => 'plan' as const);+ const unregister = registerLocalPermissionModeSwitcher('topic-1', switcher);+ const { result } = renderHook(() => usePermissionMode('agent-1', 'topic-1'));++ await act(() => result.current.select('plan'));++ expect(switcher).toHaveBeenCalledWith('plan');+ expect(result.current).toMatchObject({+ mode: 'plan',+ runningMode: 'plan',+ switchPending: false,+ });+ expect(toast.error).toHaveBeenCalledWith('heteroAgent.permissionMode.saveFailed');+ unregister();+ });++ it('keeps a bypass pick but shows the root stand-in the session took', async () => {+ seedTopic({+ heteroPermissionMode: 'default',+ runningOperation: { assistantMessageId: 'a', operationId: 'op-root' },+ });+ vi.mocked(aiAgentService.setHeteroPermissionMode).mockResolvedValue({+ mode: 'acceptEdits',+ status: 'accepted',+ } as any);+ const { result } = renderHook(() => usePermissionMode('agent-1', 'topic-1'));++ await act(() => result.current.select('bypassPermissions'));++ expect(updateTopicMetadata).toHaveBeenLastCalledWith('topic-1', {+ heteroPermissionModeFallback: 'root',+ });+ expect(result.current).toMatchObject({+ fallback: 'root',+ mode: 'bypassPermissions',+ runningMode: 'acceptEdits',+ });+ });++ it('shows the mode a fallback ran in', () => {+ seedTopic({ heteroPermissionMode: 'plan', heteroPermissionModeFallback: 'outdatedCli' });+ const { result } = renderHook(() => usePermissionMode('agent-1', 'topic-1'));+ expect(result.current).toMatchObject({+ fallback: 'outdatedCli',+ mode: 'plan',+ runningMode: 'bypassPermissions',+ });+ });+});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.tsnew file mode 100644index 00000000000..b8b0c77c842--- /dev/null+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.ts@@ -0,0 +1,205 @@+import type {+ HeteroPermissionMode,+ HeteroPermissionModeDir,+ HeteroPermissionModeFallback,+} from '@lobechat/types';+import { getWorktreeModeKey, readHeteroPermissionModeDir } from '@lobechat/types';+import { toast } from '@lobehub/ui';+import { useCallback, useEffect, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';+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 {+ clearSwitchUnapplied,+ effectivePermissionMode,+ findRunningServerOperationId,+ getLocalPermissionModeSwitcher,+ getUnappliedLiveMode,+ markSwitchUnapplied,+ readTopicPermissionMode,+ setPendingHeteroPermissionMode,+ subscribeUnappliedSwitches,+} from '@/store/chat/heteroPermissionMode';+import { topicSelectors } from '@/store/chat/selectors';+import { useElectronStore } from '@/store/electron';+import { useUserStore } from '@/store/user';+import type { UserState } from '@/store/user/initialState';++/**+ * The remembered modes of whoever is acting now: this member's workspace bucket+ * inside a workspace, `users.preference` in personal mode. `undefined` while the+ * workspace bucket has not loaded.+ */+const selectPermissionModeDirs =+ (workspaceId: string | null | undefined) =>+ (state: UserState): HeteroPermissionModeDir[] | undefined => {+ if (!workspaceId) return state.preference.heteroPermissionModeDirs ?? [];+ return state.workspaceUserPreferenceWorkspaceId === workspaceId+ ? (state.workspaceUserPreference.heteroPermissionModeDirs ?? [])+ : undefined;+ };++/** Why a mid-run switch did not reach the session, as the user should read it. */+type SwitchFailure = 'switchFailed' | 'switchUnsupported';++/**+ * Switch the topic's running session, if it has one. `taken` is the mode the+ * session reports it took — `acceptEdits` for a bypass pick as root — when+ * the host says.+ */+const switchRunningSession = async (+ topicId: string,+ mode: HeteroPermissionMode,+): Promise<{ failure?: SwitchFailure; taken?: HeteroPermissionMode }> => {+ const local = getLocalPermissionModeSwitcher(topicId);+ if (local) {+ try {+ return { taken: (await local(mode)) || undefined };+ } catch {+ return { failure: 'switchFailed' };+ }+ }+ const state = useChatStore.getState();+ const runningOperationId = findRunningServerOperationId(+ state,+ topicId,+ topicSelectors.getTopicById(topicId)(state)?.metadata,+ );+ if (!runningOperationId) return {};++ try {+ const result = await aiAgentService.setHeteroPermissionMode({+ mode,+ operationId: runningOperationId,+ });+ if (result.status === 'accepted') return { taken: 'mode' in result ? result.mode : undefined };+ return {+ failure:+ result.status === 'unsupported' || result.status === 'unreachable'+ ? 'switchUnsupported'+ : 'switchFailed',+ };+ } catch {+ return { failure: 'switchFailed' };+ }+};++export interface PermissionModeState {+ /** Why the last run was not in `mode`; the chip explains it. */+ fallback?: HeteroPermissionModeFallback | null;+ /** The picked mode: what the topic's next run starts in. */+ mode: HeteroPermissionMode;+ /** The mode the topic's run is actually in. */+ runningMode: HeteroPermissionMode;+ select: (mode: HeteroPermissionMode) => Promise<void>;+ /** The running session did not take `mode`; it applies from the next message. */+ switchPending: boolean;+}++/**+ * The composer's Claude Code permission mode (Better Coding Experience lab).+ *+ * - An existing topic shows its own mode, which Claude Code's reports keep+ * current (leaving plan mode). Picking one writes it to the topic and, while+ * a run is going, switches that session at once.+ * - A new topic shows the mode last picked for this device + directory and is+ * born with it.+ *+ * Every pick is also remembered for the directory, per workspace + user.+ */+export const usePermissionMode = (+ agentId: string,+ topicId: string | null | undefined,+): PermissionModeState => {+ const { t } = useTranslation('chat');+ const workspaceId = useActiveWorkspaceId();+ useUserStore((s) => s.useFetchWorkspaceUserPreference)();+ const dirs = useUserStore(selectPermissionModeDirs(workspaceId));+ const setPermissionModeDir = useUserStore((s) => s.setHeteroPermissionModeDir);++ 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 metadata = useChatStore((s) =>+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,+ );+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);++ const remembered = readHeteroPermissionModeDir(dirs, key);+ const mode = topicId ? readTopicPermissionMode(metadata) : remembered;+ const fallback = topicId ? metadata?.heteroPermissionModeFallback : undefined;+ const unappliedLiveMode = useSyncExternalStore(+ subscribeUnappliedSwitches,+ () => getUnappliedLiveMode(topicId),+ () => undefined,+ );+ const runningMode = unappliedLiveMode ?? effectivePermissionMode(mode, fallback);++ // 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 before the+ // topic's metadata is assembled.+ useEffect(() => {+ if (!topicId) setPendingHeteroPermissionMode(agentId, remembered);+ }, [agentId, remembered, topicId]);++ const select = useCallback(+ async (next: HeteroPermissionMode) => {+ // Remembering the pick for the directory is independent of this topic and+ // its run: a failure there must not stop the switch.+ void setPermissionModeDir(key, next).catch((error) => {+ console.error('[usePermissionMode] remembering the mode failed', error);+ toast.error(t('heteroAgent.permissionMode.saveFailed'));+ });+ if (!topicId) {+ setPendingHeteroPermissionMode(agentId, next);+ return;+ }++ try {+ await updateTopicMetadata(topicId, {+ heteroPermissionMode: next,+ heteroPermissionModeFallback: null,+ });+ } catch (error) {+ console.error('[usePermissionMode] save failed', error);+ toast.error(t('heteroAgent.permissionMode.saveFailed'));+ return;+ }++ // The mode the live session is in before this pick, should it not take it.+ const liveBefore = runningMode;+ const { failure, taken } = await switchRunningSession(topicId, next);+ if (failure) {+ if (liveBefore !== next) markSwitchUnapplied(topicId, liveBefore);+ toast.info(t(`heteroAgent.permissionMode.${failure}`));+ return;+ }+ clearSwitchUnapplied(topicId);+ // As root a bypass pick runs as acceptEdits: keep the pick, say why.+ if (taken && taken !== next) {+ await updateTopicMetadata(topicId, { heteroPermissionModeFallback: 'root' }).catch(+ () => {},+ );+ }+ },+ [agentId, key, runningMode, setPermissionModeDir, t, topicId, updateTopicMetadata],+ );++ return {+ fallback,+ mode,+ runningMode,+ select,+ switchPending: !!unappliedLiveMode && unappliedLiveMode !== mode,+ };+};diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex f953ed662a7..f4ec8811c23 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx@@ -24,7 +24,10 @@ import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';+import PermissionModeSelector from './PermissionMode';import {AntigravityQuotaMenu,ClaudeCodeQuotaMenu,@@ -169,6 +172,12 @@ const HeteroControlBar = memo(() => {const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });const heteroProvider = agencyConfig?.heterogeneousProvider;+ const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);+ // Claude Code under the lab picks how it asks before acting, per topic.+ const permissionModeChip =+ betterCoding && heteroProvider?.type === 'claude-code' && agentId ? (+ <PermissionModeSelector agentId={agentId} topicId={topicId} />+ ) : null;const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,isHetero: !!heteroProvider,@@ -219,7 +228,10 @@ const HeteroControlBar = memo(() => {justify={'space-between'}><DeviceSwitcher agentId={agentId} />- {shouldShowApiCredits && <ChatInputCredits />}+ <Flexbox horizontal align={'center'} gap={4}>+ {permissionModeChip}+ {shouldShowApiCredits && <ChatInputCredits />}+ </Flexbox></Flexbox>);}@@ -246,7 +258,8 @@ const HeteroControlBar = memo(() => {><WorkspaceControls alwaysShowWorkspace agentId={agentId} /></Flexbox>- {(shouldShowApiCredits ||+ {(permissionModeChip ||+ shouldShowApiCredits ||(shouldShowClaudeQuota && quotaDeviceId) ||(shouldShowCodexQuota && quotaDeviceId) ||(shouldShowKimiCodeQuota && quotaDeviceId) ||@@ -257,6 +270,7 @@ const HeteroControlBar = memo(() => {className={stylex.props(styles.rightGroup).className}gap={4}>+ {permissionModeChip}{shouldShowApiCredits && <ChatInputCredits />}{shouldShowAntigravityQuota && quotaDeviceId && (<AntigravityQuotaMenu@@ -374,7 +388,9 @@ const HeteroControlBar = memo(() => {<ClaudeCodeQuotaMenu deviceId={quotaDeviceId} env={heteroProvider?.env} />)}{sdkRuntimeBadge}- <Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>+ {permissionModeChip ?? (+ <Tooltip title={tChat('heteroAgent.fullAccess.tooltip')}>{fullAccessBadge}</Tooltip>+ )}</Flexbox></Flexbox>);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsxindex 891291029e0..0c5a190991a 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx@@ -69,7 +69,10 @@ const Render = memo<RenderProps>(return <RejectedResponse timedOut apiName={apiName} />;}- if (intervention?.status === 'rejected') {+ // The producer gave up because its session ended (the run stopped): no one+ // rejected anything, and the raw reason is not copy.+ const sessionEnded = intervention?.rejectedReason === 'session_ended';+ if (intervention?.status === 'rejected' && !sessionEnded) {return (<RejectedResponseapiName={apiName}@@ -79,8 +82,8 @@ const Render = memo<RenderProps>();}- if (intervention?.status === 'aborted') {- return <AbortResponse sessionEnded={intervention.rejectedReason === 'session_ended'} />;+ if (intervention?.status === 'aborted' || intervention?.status === 'rejected') {+ return <AbortResponse sessionEnded={sessionEnded} />;}// Handle arguments streaming statediff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex ef257720cf4..cf5bcfda902 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -8,6 +8,7 @@ import type {ExecAgentClientIds,ExecAgentLlmExecutor,ExecAgentResult,+ HeteroPermissionMode,PageSelection,ResumeClientLlmWaitResult,RuntimeMentionedAgent,@@ -483,6 +484,14 @@ class AiAgentService {return await lambdaClient.aiAgent.stopHeteroBackgroundTask.mutate(params);}+ /**+ * Switch the Claude Code permission mode of a run hosted by `lh hetero exec`+ * (the composer's mode chip, mid-run). `accepted` means Claude Code confirmed.+ */+ async setHeteroPermissionMode(params: { mode: HeteroPermissionMode; operationId: string }) {+ return await lambdaClient.aiAgent.setHeteroPermissionMode.mutate(params);+ }+/*** Interrupt a running task*/diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex 2935f0425bf..fae34539c2a 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -16,6 +16,7 @@ import type {} from '@lobechat/heterogeneous-agents/quota';import type {HeterogeneousAgentModelCatalog,+ HeteroPermissionMode,HeteroSessionImportMessage,ListHeterogeneousAgentModelsParams,} from '@lobechat/types';@@ -55,6 +56,8 @@ class HeterogeneousAgentService {workspaceId?: string;imageList?: Array<{ id: string; url: string }>;operationId: string;+ /** Claude Code permission mode (Better Coding Experience lab); absent allows everything. */+ permissionMode?: HeteroPermissionMode;prompt: string;/*** Replay the session's on-disk transcript instead of spawning the CLI.@@ -97,6 +100,11 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.stopBackgroundTask({ sessionId, taskId });}+ /** Switch a local Claude Code run's permission mode (Better Coding Experience mode chip). */+ async setPermissionMode(sessionId: string, mode: HeteroPermissionMode) {+ return this.ipc.heterogeneousAgent.setPermissionMode({ 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 31f1128ad6b..4e88d55066f 100644--- a/src/services/user/index.ts+++ b/src/services/user/index.ts@@ -2,6 +2,8 @@ import type { OnboardingUserInfo } from '@lobechat/context-engine';import { type MarkdownPatchHunk } from '@lobechat/markdown-patch';import type {ConfirmOnboardingUnderstandingInput,+ HeteroPermissionMode,+ HeteroPermissionModeDir,OnboardingUnderstandingPollingResult,PersonalSystemAgentKey,RetryOnboardingUnderstandingProviderInput,@@ -138,6 +140,13 @@ export class UserService {return lambdaClient.user.setWorktreeModeDir.mutate({ enabled, key });};+ /** Personal-mode Claude Code permission mode for one directory; resolves to the stored list. */+ setHeteroPermissionModeDir = async (+ key: string,+ mode: HeteroPermissionMode,+ ): Promise<HeteroPermissionModeDir[]> =>+ lambdaClient.user.setHeteroPermissionModeDir.mutate({ key, mode });+updateGuide = async (guide: Partial<UserGuide>) => {return lambdaClient.user.updateGuide.mutate(guide);};diff --git a/src/services/workspaceUserSettings.ts b/src/services/workspaceUserSettings.tsindex 28f2b9aa44d..57074e9f012 100644--- a/src/services/workspaceUserSettings.ts+++ b/src/services/workspaceUserSettings.ts@@ -1,4 +1,8 @@-import type { WorkspaceUserPreference } from '@lobechat/types';+import type {+ HeteroPermissionMode,+ HeteroPermissionModeDir,+ WorkspaceUserPreference,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -20,6 +24,13 @@ export class WorkspaceUserSettingsService {/** One directory's "New worktree" switch; resolves to the stored (capped) list. */setWorktreeModeDir = async (key: string, enabled: boolean): Promise<string[]> =>lambdaClient.workspaceUserSettings.setWorktreeModeDir.mutate({ enabled, key });++ /** This member's Claude Code permission mode for one directory; resolves to the stored list. */+ setHeteroPermissionModeDir = async (+ key: string,+ mode: HeteroPermissionMode,+ ): Promise<HeteroPermissionModeDir[]> =>+ lambdaClient.workspaceUserSettings.setHeteroPermissionModeDir.mutate({ key, mode });}export const workspaceUserSettingsService = new WorkspaceUserSettingsService();diff --git a/src/store/chat/heteroPermissionMode.test.ts b/src/store/chat/heteroPermissionMode.test.tsnew file mode 100644index 00000000000..dbbf85ac0fd--- /dev/null+++ b/src/store/chat/heteroPermissionMode.test.ts@@ -0,0 +1,123 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ applyPermissionModeReport,+ effectivePermissionMode,+ getLocalPermissionModeSwitcher,+ pendingHeteroPermissionModeMetadata,+ readTopicPermissionMode,+ registerLocalPermissionModeSwitcher,+ resolveRunPermissionMode,+ setPendingHeteroPermissionMode,+} from './heteroPermissionMode';++const lab = vi.hoisted(() => ({ on: true }));++vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));+vi.mock('@/store/user/selectors', () => ({+ labPreferSelectors: { enableBetterCodingExperience: () => lab.on },+}));++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('heteroPermissionMode (renderer)', () => {+ beforeEach(() => {+ lab.on = true;+ });++ it('starts local Claude Code runs in the topic mode only with the lab on', () => {+ expect(resolveRunPermissionMode('claude-code', { heteroPermissionMode: 'plan' })).toBe('plan');+ expect(resolveRunPermissionMode('claude-code', {})).toBe('bypassPermissions');+ expect(resolveRunPermissionMode('codex', { heteroPermissionMode: 'plan' })).toBeUndefined();+ lab.on = false;+ expect(+ resolveRunPermissionMode('claude-code', { heteroPermissionMode: 'plan' }),+ ).toBeUndefined();+ });++ it('hands the new-topic chip mode to the topic it creates', () => {+ setPendingHeteroPermissionMode('agent-1', 'acceptEdits');+ expect(pendingHeteroPermissionModeMetadata('agent-1', 'claude-code')).toEqual({+ heteroPermissionMode: 'acceptEdits',+ });+ expect(pendingHeteroPermissionModeMetadata('agent-1', 'codex')).toEqual({});+ expect(pendingHeteroPermissionModeMetadata('agent-2', 'claude-code')).toEqual({});+ });++ it('shows the mode a fallback actually ran in', () => {+ expect(readTopicPermissionMode({ heteroPermissionMode: 'auto' })).toBe('auto');+ expect(effectivePermissionMode('bypassPermissions', 'root')).toBe('acceptEdits');+ expect(effectivePermissionMode('plan', 'outdatedCli')).toBe('bypassPermissions');+ expect(effectivePermissionMode('plan', null)).toBe('plan');+ });++ it('persists a local report, and only follows a server-written one', async () => {+ const local = storeWith({ heteroPermissionMode: 'plan' });+ await applyPermissionModeReport(+ local.get,+ 't',+ { fallback: null, permissionMode: 'acceptEdits' },+ { persist: true },+ );+ expect(local.updateTopicMetadata).toHaveBeenCalledWith('t', {+ heteroPermissionMode: 'acceptEdits',+ heteroPermissionModeFallback: null,+ });++ const remote = storeWith({ heteroPermissionMode: 'plan' });+ await applyPermissionModeReport(+ remote.get,+ 't',+ { fallback: null, permissionMode: 'default' },+ { persist: false },+ );+ expect(remote.updateTopicMetadata).not.toHaveBeenCalled();+ expect(remote.internal_dispatchTopic).toHaveBeenCalledWith({+ id: 't',+ type: 'updateTopic',+ value: {+ metadata: { heteroPermissionMode: 'default', heteroPermissionModeFallback: null },+ },+ });+ });++ it('keeps the pick on a fallback and skips a report that changes nothing', async () => {+ const root = storeWith({ heteroPermissionMode: 'bypassPermissions' });+ await applyPermissionModeReport(+ root.get,+ 't',+ { fallback: 'root', permissionMode: 'acceptEdits' },+ { persist: true },+ );+ expect(root.updateTopicMetadata).toHaveBeenCalledWith('t', {+ heteroPermissionModeFallback: 'root',+ });++ const same = storeWith({ heteroPermissionMode: 'plan', heteroPermissionModeFallback: null });+ await applyPermissionModeReport(+ same.get,+ 't',+ { fallback: null, permissionMode: 'plan' },+ { persist: true },+ );+ expect(same.updateTopicMetadata).not.toHaveBeenCalled();+ });++ it('routes a mid-run switch to the topic latest local run', () => {+ const first = vi.fn();+ const second = vi.fn();+ const unregisterFirst = registerLocalPermissionModeSwitcher('t', first);+ registerLocalPermissionModeSwitcher('t', second);+ unregisterFirst();+ expect(getLocalPermissionModeSwitcher('t')).toBe(second);+ });+});diff --git a/src/store/chat/heteroPermissionMode.ts b/src/store/chat/heteroPermissionMode.tsnew file mode 100644index 00000000000..474e315e230--- /dev/null+++ b/src/store/chat/heteroPermissionMode.ts@@ -0,0 +1,220 @@+import {+ type PermissionModeReportData,+ permissionModeReportPatch,+} from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';+import type {+ ChatTopicMetadata,+ HeteroPermissionMode,+ HeteroPermissionModeFallback,+} from '@lobechat/types';+import { DEFAULT_HETERO_PERMISSION_MODE, isHeteroPermissionMode } 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';++/*+ * Claude Code permission modes (Better Coding Experience lab), renderer side.+ *+ * A topic's mode lives in `metadata.heteroPermissionMode`: the composer chip+ * writes it, every run starts in it, and Claude Code's own reports (leaving+ * plan mode) are written back. A topic that does not exist yet takes the mode+ * the chip shows for its directory, handed over at creation (see+ * `takePendingHeteroPermissionMode`).+ */++/** Whether runs of `agentType` have permission modes: Claude Code with the lab on. */+export const hasHeteroPermissionModes = (agentType: string | undefined): boolean =>+ agentType === 'claude-code' &&+ labPreferSelectors.enableBetterCodingExperience(getUserStoreState());++/** The mode a topic's runs start in; the default when it has none. */+export const readTopicPermissionMode = (+ metadata: ChatTopicMetadata | null | undefined,+): HeteroPermissionMode => {+ const mode = metadata?.heteroPermissionMode;+ return isHeteroPermissionMode(mode) ? mode : DEFAULT_HETERO_PERMISSION_MODE;+};++/** The mode a local run starts in, or undefined to allow every action (lab off, other agents). */+export const resolveRunPermissionMode = (+ agentType: string | undefined,+ metadata: ChatTopicMetadata | null | undefined,+): HeteroPermissionMode | undefined =>+ hasHeteroPermissionModes(agentType) ? readTopicPermissionMode(metadata) : undefined;++/** The new-topic chip's mode per agent, while the composer shows it. */+const pendingModes = new Map<string, HeteroPermissionMode>();++/** The composer's new-topic chip shows `mode` for `agentId` (undefined: it is gone). */+export const setPendingHeteroPermissionMode = (+ agentId: string,+ mode: HeteroPermissionMode | undefined,+): void => {+ if (mode) pendingModes.set(agentId, mode);+ else pendingModes.delete(agentId);+};++/**+ * Metadata a new Claude Code topic is born with: the mode its chip showed.+ * Empty when no chip showed one (the lab off, another agent, a send from+ * elsewhere), so the topic starts in the default.+ */+export const pendingHeteroPermissionModeMetadata = (+ agentId: string,+ agentType: string | undefined,+): Pick<ChatTopicMetadata, 'heteroPermissionMode'> => {+ const mode = pendingModes.get(agentId);+ return mode && hasHeteroPermissionModes(agentType) ? { heteroPermissionMode: mode } : {};+};++/**+ * Write the mode Claude Code reports onto the topic, so the chip shows it and+ * the next run starts in it. `persist: false` when the server already wrote it+ * (a run hosted by `lh hetero exec`); the store just follows.+ */+export const applyPermissionModeReport = async (+ get: () => ChatStore,+ topicId: string | null | undefined,+ report: Pick<PermissionModeReportData, 'fallback' | 'permissionMode'>,+ { persist }: { persist: boolean },+): Promise<void> => {+ if (!topicId) return;+ // Claude Code said which mode it is in: the chip no longer has to guess.+ clearSwitchUnapplied(topicId);+ const patch = permissionModeReportPatch(report);+ const topic = topicSelectors.getTopicById(topicId)(get());+ const current = topic?.metadata;+ if (+ (!patch.heteroPermissionMode || current?.heteroPermissionMode === patch.heteroPermissionMode) &&+ (current?.heteroPermissionModeFallback ?? null) === patch.heteroPermissionModeFallback+ ) {+ return;+ }++ if (persist) {+ await get().updateTopicMetadata(topicId, patch);+ return;+ }+ if (!topic) return;+ get().internal_dispatchTopic({+ id: topicId,+ type: 'updateTopic',+ value: { metadata: { ...topic.metadata, ...patch } },+ });+};++/**+ * Record why a topic's last run was not in its picked mode (an outdated `lh`+ * on the device). The pick stays, so the topic gets it once the device can.+ */+export const markPermissionModeFallback = async (+ get: () => ChatStore,+ topicId: string | null | undefined,+ fallback: HeteroPermissionModeFallback,+): Promise<void> => {+ if (!topicId) return;+ await get().updateTopicMetadata(topicId, { heteroPermissionModeFallback: fallback });+};++/** The mode a fallback runs in instead of the picked one. */+export const effectivePermissionMode = (+ mode: HeteroPermissionMode,+ fallback: HeteroPermissionModeFallback | null | undefined,+): HeteroPermissionMode =>+ fallback === 'outdatedCli'+ ? 'bypassPermissions'+ : fallback === 'root' && mode === 'bypassPermissions'+ ? 'acceptEdits'+ : mode;++/** Switches the permission mode of a run hosted in this window (desktop IPC). */+/** Resolves with the mode the session took, when the host says. */+export type LocalPermissionModeSwitcher = (+ mode: HeteroPermissionMode,+) => Promise<HeteroPermissionMode | void>;++const localSwitchers = new Map<string, LocalPermissionModeSwitcher>();++/**+ * Register how to switch the mode of a topic's local run, for as long as its+ * session lives (the chip switches mid-run through it).+ *+ * @returns Unregister; a no-op once a newer run of the topic registered.+ */+export const registerLocalPermissionModeSwitcher = (+ topicId: string | null | undefined,+ switcher: LocalPermissionModeSwitcher,+): (() => void) => {+ if (!topicId) return () => {};+ localSwitchers.set(topicId, switcher);+ return () => {+ if (localSwitchers.get(topicId) === switcher) localSwitchers.delete(topicId);+ };+};++export const getLocalPermissionModeSwitcher = (+ topicId: string,+): LocalPermissionModeSwitcher | undefined => localSwitchers.get(topicId);++/**+ * The server operation of a topic's run hosted by `lh hetero exec`, which a+ * mid-run switch is sent to: the live Gateway operation this window started+ * (its server id arrives with the first response), else the topic's persisted+ * `runningOperation` (a run picked up after a reload).+ */+export const findRunningServerOperationId = (+ state: Pick<ChatStore, 'operations'>,+ topicId: string,+ metadata: ChatTopicMetadata | null | undefined,+): string | undefined => {+ for (const operation of Object.values(state.operations ?? {})) {+ if (+ operation.type !== 'execServerAgentRuntime' ||+ operation.status !== 'running' ||+ operation.context.topicId !== topicId ||+ !operation.metadata.serverOperationId+ ) {+ continue;+ }+ const parent = operation.parentOperationId+ ? state.operations[operation.parentOperationId]+ : undefined;+ if (parent?.type === 'execServerAgentRuntime') continue;+ return operation.metadata.serverOperationId;+ }+ return metadata?.runningOperation?.operationId;+};++/**+ * Topics whose running session did not take the mode the user just picked+ * (the device's `lh` cannot switch mid-run, or the request failed): the mode+ * that run is still in. The pick is saved for the next run; until Claude Code+ * reports a mode again, the chip shows this one and says so.+ */+const unappliedSwitches = new Map<string, HeteroPermissionMode>();+const unappliedListeners = new Set<() => void>();++const notifyUnapplied = () => {+ for (const listener of unappliedListeners) listener();+};++export const markSwitchUnapplied = (topicId: string, liveMode: HeteroPermissionMode): void => {+ unappliedSwitches.set(topicId, liveMode);+ notifyUnapplied();+};++export const clearSwitchUnapplied = (topicId: string | null | undefined): void => {+ if (!topicId || !unappliedSwitches.delete(topicId)) return;+ notifyUnapplied();+};++export const getUnappliedLiveMode = (+ topicId: string | null | undefined,+): HeteroPermissionMode | undefined => (topicId ? unappliedSwitches.get(topicId) : undefined);++export const subscribeUnappliedSwitches = (listener: () => void): (() => void) => {+ unappliedListeners.add(listener);+ return () => unappliedListeners.delete(listener);+};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.tsindex 12ad1f11055..04651d81edc 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts@@ -54,7 +54,13 @@ export const resolveInitialTopicMetadata = (params: {}: undefined;- return cwdTopicMetadata || sandboxTopicMetadata- ? { ...cwdTopicMetadata, ...sandboxTopicMetadata }+ // 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;++ return cwdTopicMetadata || sandboxTopicMetadata || permissionModeMetadata+ ? { ...cwdTopicMetadata, ...sandboxTopicMetadata, ...permissionModeMetadata }: undefined;};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.tsindex 246ddd19b5a..eb2d3cfc800 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/stepSideEvent.ts@@ -4,8 +4,10 @@ import type {SubAgentProgressData,} from '@lobechat/agent-gateway-client';import type { BackgroundTaskEventData } from '@lobechat/heterogeneous-agents';+import { isPermissionModeReport } from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';import type { ConversationContext } from '@lobechat/types';+import { applyPermissionModeReport } from '@/store/chat/heteroPermissionMode';import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -111,6 +113,13 @@ export const resolveStepSideEvent = (};}+ // The server already wrote Claude Code's mode onto the topic; the chip follows.+ if (isPermissionModeReport(data)) {+ return {+ apply: () => void applyPermissionModeReport(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/heteroMessageError.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heteroMessageError.tsnew file mode 100644index 00000000000..f7bbbfdcb67--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heteroMessageError.ts@@ -0,0 +1,127 @@+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';+import {+ buildHeterogeneousAgentAuthRequiredError,+ isHeterogeneousAgentAuthRequired,+ isLocalHeterogeneousType,+} from '@lobechat/heterogeneous-agents';+import {+ isEchoedErrorText,+ normalizeHeterogeneousMessageError,+} from '@lobechat/heterogeneous-agents/errors';+import type { ChatMessageError } from '@lobechat/types';+import { AgentRuntimeErrorType } from '@lobechat/types';++const maybeClassifyCliAuthRequiredError = (+ error: unknown,+ agentType?: string,+): HeterogeneousAgentSessionError | undefined => {+ if (!agentType || !isLocalHeterogeneousType(agentType)) return;++ const message =+ error instanceof Error+ ? error.message+ : typeof error === 'string'+ ? error+ : typeof error === 'object' &&+ error &&+ 'message' in error &&+ typeof error.message === 'string'+ ? error.message+ : undefined;++ if (!message) return;+ if (!isHeterogeneousAgentAuthRequired(agentType, message)) return;++ return buildHeterogeneousAgentAuthRequiredError({ agentType, stderr: message });+};++/** Whether the streamed text only echoes a terminal CLI error that the error card already shows. */+export const shouldSuppressTerminalErrorEcho = (+ content: string,+ error: ChatMessageError,+): boolean => {+ const errorBody = error.body as+ (HeterogeneousAgentSessionError & { clearEchoedContent?: boolean }) | undefined;+ if (+ !errorBody?.clearEchoedContent &&+ errorBody?.code !== HeterogeneousAgentSessionErrorCode.AuthRequired+ ) {+ return false;+ }++ return isEchoedErrorText(content, errorBody?.stderr || errorBody?.message || error.message);+};++const toRawHeterogeneousAgentMessageError = (+ error: unknown,+ agentType?: string,+): ChatMessageError => {+ const authRequiredError = maybeClassifyCliAuthRequiredError(error, agentType);+ if (authRequiredError) {+ return {+ body: authRequiredError,+ message: authRequiredError.message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+ }++ if (+ typeof error === 'object' &&+ error &&+ 'message' in error &&+ typeof error.message === 'string' &&+ ('agentType' in error || 'code' in error || 'docsUrl' in error || 'installCommands' in error)+ ) {+ return {+ body: error as HeterogeneousAgentSessionError,+ message: error.message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+ }++ // A plain `{message}` object (adapter wire data / IPC error envelope)+ // without the session-error marker keys above still carries the only+ // human-readable reason — don't flatten it to the generic fallback.+ const objectMessage =+ typeof error === 'object' && error && 'message' in error && typeof error.message === 'string'+ ? error.message+ : undefined;+ const message =+ error instanceof Error+ ? error.message+ : typeof error === 'string'+ ? error+ : (objectMessage ?? 'Agent execution failed');++ // Surface the underlying `cause` (e.g. undici's `ENOTFOUND` / `ECONNREFUSED`+ // hidden under a generic `TypeError: fetch failed`). The desktop IPC layer+ // ferries `cause` across via an error envelope (see `~common/ipcError`).+ // Flatten any Error cause to a plain object — `ChatMessageError.body` is+ // persisted as DB JSONB, where a raw Error would serialize to `{}`.+ const rawCause = error instanceof Error ? error.cause : undefined;+ const cause =+ rawCause instanceof Error+ ? {+ code: (rawCause as { code?: unknown }).code,+ message: rawCause.message,+ name: rawCause.name,+ }+ : rawCause;++ return {+ body: cause === undefined || cause === null ? { message } : { cause, message },+ message,+ type: AgentRuntimeErrorType.AgentRuntimeError,+ };+};++/** The persisted message error for a heterogeneous run failure (CLI auth, session error, plain). */+export const toHeterogeneousAgentMessageError = (+ error: unknown,+ agentType?: string,+): ChatMessageError =>+ normalizeHeterogeneousMessageError(+ toRawHeterogeneousAgentMessageError(error, agentType),+ agentType,+ );diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex bb76926a122..4088c7c0269 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -1,16 +1,12 @@import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { stripGoalCommand } from '@lobechat/builtin-tool-goal';import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';-import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import {appendAttachedFilesToPrompt,- buildHeterogeneousAgentAuthRequiredError,buildSubagentRunSnapshot,createMainAgentRunState,type HeteroAttachedFileRef,- isHeterogeneousAgentAuthRequired,isHeterogeneousProviderBindingSupported,- isLocalHeterogeneousType,isServerDefaultHeterogeneousAgentType,type MainAgentIntent,type MainAgentReduceCtx,@@ -22,10 +18,7 @@ import {type SubagentRunSnapshot,usesHeterogeneousSessionInitialModel,} from '@lobechat/heterogeneous-agents';-import {- isEchoedErrorText,- normalizeHeterogeneousMessageError,-} from '@lobechat/heterogeneous-agents/errors';+import { isPermissionModeReport } from '@lobechat/heterogeneous-agents/claudeCodePermission/shared';import type {ChatMessageError,ChatToolPayload,@@ -41,7 +34,6 @@ import type {WorkingDirConfig,} from '@lobechat/types';import {- AgentRuntimeErrorType,buildHeteroSpawnArgs,HETEROGENEOUS_AGENT_DEFAULT_SELECTION,normalizeHeterogeneousProviderConfig,@@ -71,6 +63,11 @@ 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 { topicSelectors } from '@/store/chat/selectors';import { type StreamRetryMetadata } from '@/store/chat/slices/operation/types';import { type ChatStore, useChatStore } from '@/store/chat/store';@@ -89,6 +86,10 @@ import { isCompletedRuntimeEnd } from '../gateway/runtimeEndReason';import { withHeteroContext } from '../viewedTaskPrompt';import { registerLocalBackgroundTaskStopper, writeBackgroundTaskSnapshot } from './backgroundTasks';import { markUnfinishedToolsCancelled } from './cancelledTools';+import {+ shouldSuppressTerminalErrorEcho,+ toHeterogeneousAgentMessageError,+} from './heteroMessageError';import { getNativeHeteroSessionBindingKey, isRecoverableResumeError } from './heteroResume';import { preserveSkippedIntervention } from './interventionAck';import { claimLocalRunFee, type LocalRunFeeClaim, settleLocalRunFee } from './localRunFee';@@ -117,112 +118,6 @@ const markSkipMessageFetch = (event: AgentStreamEvent): void => {event.data = { ...event.data, skipMessageFetch: true };};-const maybeClassifyCliAuthRequiredError = (- error: unknown,- agentType?: string,-): HeterogeneousAgentSessionError | undefined => {- if (!agentType || !isLocalHeterogeneousType(agentType)) return;-- const message =- error instanceof Error- ? error.message- : typeof error === 'string'- ? error- : typeof error === 'object' &&- error &&- 'message' in error &&- typeof error.message === 'string'- ? error.message- : undefined;-- if (!message) return;- if (!isHeterogeneousAgentAuthRequired(agentType, message)) return;-- return buildHeterogeneousAgentAuthRequiredError({ agentType, stderr: message });-};--const shouldSuppressTerminalErrorEcho = (content: string, error: ChatMessageError): boolean => {- const errorBody = error.body as- (HeterogeneousAgentSessionError & { clearEchoedContent?: boolean }) | undefined;- if (- !errorBody?.clearEchoedContent &&- errorBody?.code !== HeterogeneousAgentSessionErrorCode.AuthRequired- ) {- return false;- }-- return isEchoedErrorText(content, errorBody?.stderr || errorBody?.message || error.message);-};--const toRawHeterogeneousAgentMessageError = (- error: unknown,- agentType?: string,-): ChatMessageError => {- const authRequiredError = maybeClassifyCliAuthRequiredError(error, agentType);- if (authRequiredError) {- return {- body: authRequiredError,- message: authRequiredError.message,- type: AgentRuntimeErrorType.AgentRuntimeError,- };- }-- if (- typeof error === 'object' &&- error &&- 'message' in error &&- typeof error.message === 'string' &&- ('agentType' in error || 'code' in error || 'docsUrl' in error || 'installCommands' in error)- ) {- return {- body: error as HeterogeneousAgentSessionError,- message: error.message,- type: AgentRuntimeErrorType.AgentRuntimeError,- };- }-- // A plain `{message}` object (adapter wire data / IPC error envelope)- // without the session-error marker keys above still carries the only- // human-readable reason — don't flatten it to the generic fallback.- const objectMessage =- typeof error === 'object' && error && 'message' in error && typeof error.message === 'string'- ? error.message- : undefined;- const message =- error instanceof Error- ? error.message- : typeof error === 'string'- ? error- : (objectMessage ?? 'Agent execution failed');-- // Surface the underlying `cause` (e.g. undici's `ENOTFOUND` / `ECONNREFUSED`- // hidden under a generic `TypeError: fetch failed`). The desktop IPC layer- // ferries `cause` across via an error envelope (see `~common/ipcError`).- // Flatten any Error cause to a plain object — `ChatMessageError.body` is- // persisted as DB JSONB, where a raw Error would serialize to `{}`.- const rawCause = error instanceof Error ? error.cause : undefined;- const cause =- rawCause instanceof Error- ? {- code: (rawCause as { code?: unknown }).code,- message: rawCause.message,- name: rawCause.name,- }- : rawCause;-- return {- body: cause === undefined || cause === null ? { message } : { cause, message },- message,- type: AgentRuntimeErrorType.AgentRuntimeError,- };-};--const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): ChatMessageError =>- normalizeHeterogeneousMessageError(- toRawHeterogeneousAgentMessageError(error, agentType),- agentType,- );-export interface HeterogeneousAgentExecutorParams {assistantMessageId: string;/**@@ -2048,6 +1943,10 @@ 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 });+ return;+ }// ─── stream_start with newStep: new LLM turn ───// The reducer flushes the prior turn's content/reasoning/model and opens@@ -2495,9 +2394,17 @@ export const executeHeterogeneousAgent = async (});// Claude Code keeps its input (SDK stream or CLI stdin) open in every Follow-up mode.if (adapterType === 'claude-code') {- unregisterTaskStopper = registerLocalBackgroundTaskStopper(operationId, (taskId) =>+ 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();+ };}// Send the prompt — blocks until process exitsconst sendResult = await heterogeneousAgentService.sendPrompt({@@ -2507,6 +2414,10 @@ export const executeHeterogeneousAgent = async (userId: userProfileSelectors.userId(getUserStoreState()),workspaceId: workspaceId ?? undefined,operationId,+ permissionMode: resolveRunPermissionMode(+ adapterType,+ getTopicMetadataById(get(), context.topicId ?? undefined),+ ),// `/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/utils/snapshotAgentModel.ts b/src/store/chat/utils/snapshotAgentModel.tsindex 09f9d40c259..f1ff9c52c82 100644--- a/src/store/chat/utils/snapshotAgentModel.ts+++ b/src/store/chat/utils/snapshotAgentModel.ts@@ -8,6 +8,7 @@ import { getAgentStoreState } from '@/store/agent';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';/*** Snapshot the given agent's current model/provider so a newly created topic@@ -47,7 +48,7 @@ export const snapshotAgentModel = (export type TopicReasoningSnapshot = Pick<ChatTopicMetadata,- 'heteroEffort' | 'heteroSpeed' | 'reasoningConfig'+ 'heteroEffort' | 'heteroPermissionMode' | 'heteroSpeed' | 'reasoningConfig'>;/**@@ -75,7 +76,11 @@ export const snapshotAgentReasoning = async (const heterogeneousProvider =agentByIdSelectors.getAgencyConfigById(agentId)(getAgentStoreState())?.heterogeneousProvider;if (heterogeneousProvider) {- const snapshot = resolveHeterogeneousTopicRuntimeSnapshot(heterogeneousProvider);+ const snapshot = {+ ...resolveHeterogeneousTopicRuntimeSnapshot(heterogeneousProvider),+ // The Claude Code permission mode the new-topic chip showed.+ ...pendingHeteroPermissionModeMetadata(agentId, heterogeneousProvider.type),+ };return Object.keys(snapshot).length === 0 ? undefined : snapshot;}diff --git a/src/store/user/slices/workspaceUserSettings/action.permissionMode.test.ts b/src/store/user/slices/workspaceUserSettings/action.permissionMode.test.tsnew file mode 100644index 00000000000..6bd4082690f--- /dev/null+++ b/src/store/user/slices/workspaceUserSettings/action.permissionMode.test.ts@@ -0,0 +1,87 @@+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(),+ setHeteroPermissionModeDir: vi.fn(),+ updatePreference: vi.fn(),+ },+}));++vi.mock('@/services/user', async (importOriginal) => {+ const original = await importOriginal<{ userService: object }>();+ return {+ ...original,+ userService: { ...original.userService, setHeteroPermissionModeDir: vi.fn() },+ };+});++const state = () => useUserStore.getState();++const seed = (preference: WorkspaceUserPreference) =>+ useUserStore.setState({+ workspaceUserPreference: preference,+ workspaceUserPreferenceWorkspaceId: 'workspace-1',+ });++describe('setHeteroPermissionModeDir', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ active.id = 'workspace-1';+ useUserStore.setState({+ preference: { heteroPermissionModeDirs: [{ key: 'dev::/p', mode: 'plan' }] } as any,+ workspaceUserPreference: {},+ workspaceUserPreferenceWorkspaceId: null,+ });+ });++ it('remembers the mode in the workspace bucket, beside the worktree switch', async () => {+ seed({ worktreeModeDirs: ['dev::/a'] });+ vi.mocked(workspaceUserSettingsService.setHeteroPermissionModeDir).mockResolvedValue([+ { key: 'dev::/a', mode: 'acceptEdits' },+ ]);++ await act(() => state().setHeteroPermissionModeDir('dev::/a', 'acceptEdits'));++ expect(workspaceUserSettingsService.setHeteroPermissionModeDir).toHaveBeenCalledWith(+ 'dev::/a',+ 'acceptEdits',+ );+ expect(state().workspaceUserPreference).toMatchObject({+ heteroPermissionModeDirs: [{ key: 'dev::/a', mode: 'acceptEdits' }],+ worktreeModeDirs: ['dev::/a'],+ });+ expect(state().preference.heteroPermissionModeDirs).toEqual([{ key: 'dev::/p', mode: 'plan' }]);+ });++ it('writes users.preference in personal mode and rolls back a failed write', async () => {+ active.id = null;+ vi.mocked(userService.setHeteroPermissionModeDir).mockRejectedValue(new Error('offline'));++ await expect(+ act(() => state().setHeteroPermissionModeDir('dev::/p', 'default')),+ ).rejects.toThrow('offline');+ expect(state().preference.heteroPermissionModeDirs).toEqual([{ key: 'dev::/p', mode: 'plan' }]);++ vi.mocked(userService.setHeteroPermissionModeDir).mockResolvedValue([+ { key: 'dev::/p', mode: 'default' },+ ]);+ await act(() => state().setHeteroPermissionModeDir('dev::/p', 'default'));+ expect(state().preference.heteroPermissionModeDirs).toEqual([+ { key: 'dev::/p', mode: 'default' },+ ]);+ });+});diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.tsindex 42b72d69c9d..69b66309d08 100644--- a/src/store/user/slices/workspaceUserSettings/action.ts+++ b/src/store/user/slices/workspaceUserSettings/action.ts@@ -1,5 +1,5 @@-import type { WorkspaceUserPreference } from '@lobechat/types';-import { applyWorktreeModeDir } from '@lobechat/types';+import type { HeteroPermissionMode, WorkspaceUserPreference } from '@lobechat/types';+import { applyHeteroPermissionModeDir, applyWorktreeModeDir } from '@lobechat/types';import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';import isEqual from 'fast-deep-equal';import type { ReplicaSlice } from 'local-replica/zustand';@@ -25,6 +25,12 @@ import {const n = setNamespace('workspaceUserSettings');+/** Per-directory habits stored the same way in both preference buckets. */+type DirectoryPreference = Pick<+ WorkspaceUserPreference,+ 'heteroPermissionModeDirs' | 'worktreeModeDirs'+>;+type Setter = StoreSetter<UserStore>;type PreferenceSlice = ReplicaSlice<@@ -266,43 +272,82 @@ export class WorkspaceUserSettingsActionImpl {/*** Turn the composer's "New worktree" switch on or off for one directory- * (`getWorktreeModeKey`). Inside a workspace it lives in this member's- * workspace bucket, in personal mode in `users.preference`. Applied- * optimistically so the switch flips at once, rolled back if the write fails- * (rethrown, so the caller can say so); the server applies the cap.+ * (`getWorktreeModeKey`). See `#setDirectoryPreference` for where it lives.+ */+ setWorktreeModeDir = async (key: string, enabled: boolean): Promise<void> =>+ this.#setDirectoryPreference({+ apply: (preference) => ({+ worktreeModeDirs: applyWorktreeModeDir(preference.worktreeModeDirs, key, enabled),+ }),+ name: 'setWorktreeModeDir',+ writePersonal: async () => ({+ worktreeModeDirs: await userService.setWorktreeModeDir(key, enabled),+ }),+ writeWorkspace: () => workspaceUserSettingsService.setWorktreeModeDir(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.*/- setWorktreeModeDir = async (key: string, enabled: boolean): Promise<void> => {+ setHeteroPermissionModeDir = async (key: string, mode: HeteroPermissionMode): Promise<void> =>+ this.#setDirectoryPreference({+ apply: (preference) => ({+ heteroPermissionModeDirs: applyHeteroPermissionModeDir(+ preference.heteroPermissionModeDirs,+ key,+ mode,+ ),+ }),+ name: 'setHeteroPermissionModeDir',+ writePersonal: async () => ({+ heteroPermissionModeDirs: await userService.setHeteroPermissionModeDir(key, mode),+ }),+ writeWorkspace: () => workspaceUserSettingsService.setHeteroPermissionModeDir(key, mode),+ });++ /**+ * One per-directory habit of whoever is acting now: inside a workspace it+ * lives in this member's workspace bucket, in personal mode in+ * `users.preference`. Applied optimistically so the control changes at once,+ * rolled back if the write fails (rethrown, so the caller can say so); the+ * server applies the list's cap.+ */+ #setDirectoryPreference = async ({+ apply,+ name,+ writePersonal,+ writeWorkspace,+ }: {+ apply: (preference: DirectoryPreference) => DirectoryPreference;+ name: string;+ writePersonal: () => Promise<DirectoryPreference>;+ writeWorkspace: () => Promise<unknown>;+ }): Promise<void> => {const workspaceId = getActiveWorkspaceId();if (!workspaceId) {const previous = this.#get().preference;- this.#set(- {- preference: {- ...previous,- worktreeModeDirs: applyWorktreeModeDir(previous.worktreeModeDirs, key, enabled),- },- },- false,- n('setWorktreeModeDir'),- );+ const optimistic = apply(previous);+ this.#set({ preference: { ...previous, ...optimistic } }, false, n(name));try {- const worktreeModeDirs = await userService.setWorktreeModeDir(key, enabled);+ const stored = await writePersonal();this.#set(- { preference: { ...this.#get().preference, worktreeModeDirs } },+ { preference: { ...this.#get().preference, ...stored } },false,- n('setWorktreeModeDir/confirmed'),+ n(`${name}/confirmed`),);} catch (error) {+ const rollback = Object.fromEntries(+ Object.keys(optimistic).map((field) => [+ field,+ previous[field as keyof DirectoryPreference],+ ]),+ );this.#set(- {- preference: {- ...this.#get().preference,- worktreeModeDirs: previous.worktreeModeDirs,- },- },+ { preference: { ...this.#get().preference, ...rollback } },false,- n('setWorktreeModeDir/rollback'),+ n(`${name}/rollback`),);throw error;}@@ -316,15 +361,9 @@ export class WorkspaceUserSettingsActionImpl {}const previous = this.#get().workspaceUserPreference;replica.update(workspaceId, (data) => data ?? previous, { persist: false });- await replica.optimistic(- workspaceId,- (data) => ({- ...data,- worktreeModeDirs: applyWorktreeModeDir(data.worktreeModeDirs, key, enabled),- }),- () => workspaceUserSettingsService.setWorktreeModeDir(key, enabled),- { revalidate: true },- );+ await replica.optimistic(workspaceId, (data) => ({ ...data, ...apply(data) }), writeWorkspace, {+ revalidate: true,+ });};}