Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): unify ordinary session opening and plugin model controls (#5333)
Chris Zhang44f78204d582
diff --git a/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts b/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.tsindex c818b7ecbe..d0ba1e5b4d 100644--- a/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts+++ b/apps/desktop/src/main/__tests__/pluginWorkspaceSessions.test.ts@@ -1,17 +1,17 @@+import { setSessionOpeningModelAdmission } from '../localDb/sessionOpening';import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => {const run = vi.fn(async () => undefined);- const values = vi.fn(() => ({ run }));+ const values = vi.fn((_row: Record<string, unknown>) => ({ run }));return {run, values, insert: vi.fn(() => ({ values })),bootstrap: vi.fn(async (): Promise<void> => undefined), recent: vi.fn(async () => undefined),workspace: vi.fn(),};});-vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: { insert: mocks.insert } }) }));+vi.mock('../localDb/client/current', () => ({ getCurrentDbClientSnapshot: () => mocks, getDbClient: () => ({ drizzle: { insert: mocks.insert } }) }));vi.mock('../localDb/schema', () => ({ sessions: {} }));-vi.mock('../localDb/mapper', () => ({ sessionCreateToRow: (id: string, row: object) => ({ id, ...row }) }));vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: mocks.workspace }));vi.mock('../git-snapshot/projectGitBootstrap', () => ({ ensureProjectGitInitialized: mocks.bootstrap }));vi.mock('../maker-host/git-safety-settings-store', () => ({ readGitSafetySettings: () => ({ mode: 'all-projects', autoSnapshotEnabled: true, autoInitProjectGit: true }) }));@@ -19,9 +19,10 @@ vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: mocks.recvi.mock('../localDb/pluginWorkspaceDedupe', () => ({ pickSessionForWorkdir: vi.fn() }));vi.mock('../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));-import { createGhostErrandSession, createPluginDraftSession } from '../localDb/ipc/pluginWorkspaceSessions';+import { createPluginTaskSession, createPluginDraftSession } from '../localDb/ipc/pluginWorkspaceSessions';beforeEach(() => {+ setSessionOpeningModelAdmission(async body => ({ ...body, model: body.model ?? 'test-model', effort: body.effort ?? '' }));vi.clearAllMocks();mocks.bootstrap.mockResolvedValue(undefined);mocks.run.mockResolvedValue(undefined);@@ -34,7 +35,7 @@ describe('plugin errand creation persistence boundary', () => {if (phase === 'workspace allocation') mocks.workspace.mockImplementationOnce(() => { throw new Error('Workspace unavailable'); });if (phase === 'bootstrap') mocks.bootstrap.mockRejectedValueOnce(new Error('Workspace unavailable'));const shouldContinue = () => phase !== 'initial' && (phase !== 'after bootstrap' || !mocks.bootstrap.mock.calls.length);- await expect(createGhostErrandSession({ ...params, shouldContinue, onPersistenceStarted })).rejects.toThrow();+ await expect(createPluginTaskSession({ ...params, shouldContinue, onPersistenceStarted })).rejects.toThrow();expect(onPersistenceStarted).not.toHaveBeenCalled();expect(mocks.insert).not.toHaveBeenCalled();});@@ -46,7 +47,7 @@ describe('plugin errand creation persistence boundary', () => {return { run: mocks.run };});const shouldContinue = () => phase !== 'after insert' || !mocks.values.mock.calls.length;- const result = createGhostErrandSession({ ...params, shouldContinue, onPersistenceStarted });+ const result = createPluginTaskSession({ ...params, shouldContinue, onPersistenceStarted });if (phase === 'success') await expect(result).resolves.toBe('task');else await expect(result).rejects.toThrow();expect(onPersistenceStarted).toHaveBeenCalledOnce();@@ -69,7 +70,7 @@ describe('plugin draft creation commit boundary', () => {mocks.bootstrap.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));const notify = vi.fn();const result = createPluginDraftSession({ ...params, shouldContinue: () => active, notifySessionCreated: notify });- expect(mocks.bootstrap).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(mocks.bootstrap).toHaveBeenCalledOnce());active = false;finish();expect(await result).toBeNull();@@ -101,3 +102,8 @@ describe('plugin draft creation commit boundary', () => {expect(mocks.run).toHaveBeenCalledOnce();});});++it('persists empty reasoning for models without effort controls instead of defaulting high', async () => {+ await createPluginTaskSession({ ghostId: 'plugin', title: 'Task', model: 'plain-model', effort: '', permissionMode: 'plan' });+ expect(mocks.values.mock.calls[0][0]).toMatchObject({ model: 'plain-model', effort: '' });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.tsindex ea4b2e8c38..28a3a7381d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts@@ -577,3 +577,19 @@ describe('可见任务自动切过去', () => {expect(reveal).not.toHaveBeenCalled();});});++ describe('shared task model context through the legacy adapter', () => {+ it('passes only the Host-resolved source, ignoring a plugin-claimed session', async () => {+ const resolveSourceSessionId = vi.fn(() => 'actual-caller');+ const { slot, runner } = makeSlot({ resolveSourceSessionId });+ await slot.handleRequest('helper', { ...RUN, mode: 'wait', callId: 'active', sourceSessionId: 'foreign' });+ expect(resolveSourceSessionId).toHaveBeenCalledWith('helper', 'active');+ expect(runner).toHaveBeenCalledWith(expect.objectContaining({ sourceSessionId: 'actual-caller' }), expect.anything());+ });+ it('a real panel gesture carries no arbitrary caller model or permission', async () => {+ const { slot, runner } = makeSlot({ resolveSourceSessionId: () => undefined });+ slot.noteUserGesture('helper');+ await slot.handleRequest('helper', { ...RUN, mode: 'wait' });+ expect(runner).toHaveBeenCalledWith(expect.objectContaining({ sourceSessionId: undefined, origin: 'user-action' }), expect.anything());+ });+ });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginTaskPrefsStore.test.tssimilarity index 69%rename from apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.tsrename to apps/desktop/src/main/cindy-brain/__tests__/pluginTaskPrefsStore.test.tsindex 8669548da2..460d85986e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/errandPrefsStore.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginTaskPrefsStore.test.ts@@ -1,5 +1,5 @@/**- * errandPrefsStore.test.ts — 派活配置存储的 normalize 单测。+ * pluginTaskPrefsStore.test.ts — 派活配置存储的 normalize 单测。* 存储真身经 createOverrideSettingsFile 落 userData,依赖 electron;这里* 只测纯函数(坏形态清洗与权限档白名单),读写链路由 IPC 层与 runner 测试覆盖。*/@@ -11,7 +11,7 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({desktopMakerLogger: { child: () => ({ info: () => {}, warn: () => {}, error: () => {} }) },}));-const { __testing } = await import('../errandPrefsStore');+const { __testing, validatePluginTaskConfig, setPluginTaskConfigValidator } = await import('../pluginTaskPrefsStore');describe('normalizeConfig(单插件配置清洗)', () => {it('合法字段保留,非法值逐字段丢弃(= 回到跟随默认)', () => {@@ -38,7 +38,7 @@ describe('normalizeConfig(单插件配置清洗)', () => {__testing.normalizeConfig({agentKind: 'claude',model: '',- effort: 'minimal',+ effort: 'unknown',fastMode: 'yes',permissionMode: 'bypassPermissions',workingDir: 42,@@ -46,7 +46,7 @@ describe('normalizeConfig(单插件配置清洗)', () => {).toEqual({});});- it('permissionMode 白名单:bypassPermissions / ask 等一律清掉', () => {+ it('保留普通任务的 ask 和旧 plan 配置,拒绝完全访问', () => {expect(__testing.normalizeConfig({ permissionMode: 'plan' })).toEqual({permissionMode: 'plan',});@@ -54,7 +54,7 @@ describe('normalizeConfig(单插件配置清洗)', () => {permissionMode: 'auto',});expect(__testing.normalizeConfig({ permissionMode: 'bypassPermissions' })).toEqual({});- expect(__testing.normalizeConfig({ permissionMode: 'ask' })).toEqual({});+ expect(__testing.normalizeConfig({ permissionMode: 'ask' })).toEqual({ permissionMode: 'ask' });});it('Pi 是合法的代办 agent', () => {@@ -109,3 +109,22 @@ describe('sessionMapKey(会话映射键)', () => {expect(__testing.sessionMapKey('helper', 'pr-123')).toBe('helper#pr-123');});});+++describe('validating user task preferences before saving', () => {+ it('rejects unavailable explicit routes and malformed authority instead of silently saving defaults', async () => {+ const validate = vi.fn(async () => { throw new Error('供应商未连接,请修复连接'); });+ setPluginTaskConfigValidator(validate);+ await expect(validatePluginTaskConfig({ agentKind: 'codex', model: 'selected', providerId: 'removed' }))+ .rejects.toThrow('修复连接');+ await expect(validatePluginTaskConfig({ permissionMode: 'bypassPermissions' })).rejects.toThrow('permissionMode');+ expect(validate).toHaveBeenCalledOnce();+ });+ it('lets the user clear a broken model without losing independent permissions or directory', async () => {+ const validate = vi.fn(async () => { throw new Error('model unavailable'); });+ setPluginTaskConfigValidator(validate);+ await expect(validatePluginTaskConfig({ permissionMode: 'auto', workingDir: '/user-selected' })).resolves.toBeUndefined();+ await expect(validatePluginTaskConfig(null)).resolves.toBeUndefined();+ expect(validate).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.tsindex 3477219f69..20facc1d4f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts@@ -95,6 +95,23 @@ it('allows an Auto request but never Full access', () => {expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own',mode:'bypassPermissions'})).toBe(false);});+ it('accepts opt-in call context only for creation, never a claimed source session', () => {+ const create = { type: 'tasks-request', kind: 'create', requestKey: 'one', title: 'Work' };+ expect(validPluginTaskRequest({ ...create, callId: 'active-call' })).toBe(true);+ expect(validPluginTaskRequest({ ...create, sourceSessionId: 'foreign' })).toBe(false);+ expect(validPluginTaskRequest({ ...create, callId: '' })).toBe(false);+ expect(validPluginTaskRequest({ ...create, route: { agentKind: 'pi', providerId: 'mine', model: 'no-reasoning', effort: '', fastMode: false } })).toBe(true);+ });++it('exposes catalog and guarded model changes without accepting permission overrides', () => {+ expect(validPluginTaskRequest({ type: 'tasks-request', kind: 'models' })).toBe(true);+ const request = { type: 'tasks-request', kind: 'setModel', taskId: 'own', expectedRevision: 1,+ route: { agentKind: 'codex', model: 'm', providerId: 'p', effort: '', fastMode: false } };+ expect(validPluginTaskRequest(request)).toBe(true);+ expect(validPluginTaskRequest({ ...request, expectedRevision: undefined })).toBe(false);+ expect(validPluginTaskRequest({ ...request, permissionMode: 'bypassPermissions' })).toBe(false);+});+it('accepts bounded plugin-authored scope, never caller-supplied authority', () => {const item={label:'sample',workingDir:'/answer',route:{agentKind:'pi',providerId:'p',model:'m',effort:'high',fastMode:false},task:'Run tests'};const request={type:'tasks-request',kind:'setTeamPlan',taskId:'lead',plan:{concurrency:null,task:'Coordinate',items:[item]}};diff --git a/apps/desktop/src/main/cindy-brain/agentSlot.ts b/apps/desktop/src/main/cindy-brain/agentSlot.tsindex 2195e4005b..a938da4b4e 100644--- a/apps/desktop/src/main/cindy-brain/agentSlot.ts+++ b/apps/desktop/src/main/cindy-brain/agentSlot.ts@@ -415,7 +415,7 @@ export class GhostAgentSlot {if (code.startsWith('FORK_') || code === 'SOURCE_NEVER_RAN' || code === 'NO_PRIOR_ASSISTANT') {return { ok: false, errorCode: 'FORK_FAILED', message: result.message };}- if (code === 'ARCHIVED' || code === 'DELETED' || code === 'BUSY') {+ if (code === 'MODEL_UNAVAILABLE' || code === 'ARCHIVED' || code === 'DELETED' || code === 'BUSY') {return { ok: false, errorCode: 'SESSION_UNAVAILABLE', message: result.message };}return { ok: false, errorCode: 'INTERNAL', message: result.message };diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.tsindex 0f08b88882..352253219e 100644--- a/apps/desktop/src/main/cindy-brain/errandSlot.ts+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts@@ -45,6 +45,8 @@ const MAX_SETTLED_JOBS_PER_GHOST = 16;export type GhostErrandOrigin = 'user-action' | 'background';export interface GhostErrandRunRequest {+ /** Host-resolved model context; never accepted from plugin payload. */+ sourceSessionId?: string;ghostId: string;ghostVersion: string;/** 主机归因的来源;切任务只认 user-action。 */@@ -94,6 +96,7 @@ export type GhostErrandRunner = () => Promise<GhostErrandRunOutcome>;export interface GhostErrandSlotDeps {+ resolveSourceSessionId?(ghostId: string, callId: string): string | undefined;getGhost(id: string): InstalledGhost | null;runner?: GhostErrandRunner | null;/** 管子续命挂钩(同 cindySlot 契约;wait 模式的署名单在途期间续命)。 */@@ -320,6 +323,7 @@ export class GhostErrandSlot {{ghostId,ghostVersion: ghost.manifest.version,+ sourceSessionId: this.deps.resolveSourceSessionId?.(ghostId, callId),origin,message,...(typeof payload.title === 'string' ? { title: payload.title.trim() } : {}),diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex d9cfef5c85..b489fc30cf 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3771,10 +3771,10 @@ await cindy.agent.run({一条 Agent 请求,后台请求之间至少间隔 10 秒。这个能力可能自动产生模型费用,只在产品确实需要时申请,不要把 \`sessionId\` 当作任意跨会话控制口。-### 4.11.1 派活取件:让 Agent 替你干活并取回结果(errand)+### 4.11.1 旧版任务接口:让 Agent 替你干活并取回结果(errand)-\`agent.run\` 把回合发进**用户的会话**,结果是给用户看的;派活(errand)相反:-任务在**你的专属 errand 会话**里跑,Agent 的最终回复文字交回**你**手里继续用。+\`agent.run\` 用于用户已关联任务的交互;旧版 \`errand\` 接口提供结果查询适配:+任务在宿主按 sessionKey 关联的普通任务里运行,Agent 的最终回复文字交回**你**手里继续用。需声明 \`"agent": { "errand": true }\`(插件详情高风险单列)。\`\`\`js@@ -3782,7 +3782,7 @@ await cindy.agent.run({const r = await cindy.agent.errand({task: '阅读工作目录下的 README 并总结要点(200 字以内)',// context: { anything: '结构化上下文,主机 JSON 化后附在任务消息尾部' },- // title: '我的插件 · 代办', // 仅首次创建对应 errand 会话时用作标题+ // title: '我的插件任务', // 仅首次创建对应 errand 会话时用作标题// workingDir: repoDir, // 可选:请求建在某目录(只认用户亲选过的,见下)// sessionKey: 'pr-123', // 可选:分会话钥匙(1–64 位字母/数字/._-)。// // 不传 = 插件共用一间;同钥匙同间、异钥匙各间,@@ -3804,16 +3804,22 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });- **任务只进普通 user 消息**,绝不进 system prompt;- errand 会话在**侧边栏可见**,用户可随时旁观、叫停——没有隐身会话;-- 用哪个 agent/模型/思考强度、多大动手权限、在哪个目录干活,全部由**用户**在- 你的插件详情页「AI 代办」卡里配置;缺省跟随用户新建草稿的选择,权限档缺省- **只读**(不能改任何文件),目录缺省是插件专属文件夹。别假设你能写文件——- 只读档下让 Agent"分析/回答"没问题,"修改"类任务要在文案里引导用户先放开- 权限档;+- 这是旧版任务接口,不是插件全部 AI 能力。普通任务管理用 §4.11.3,继续用户任务用 §4.11,+ 快问快答用 §4.0.2;不要把这些能力统一称为代办。+- 新建任务共用插件详情「任务设置」中的模型组合(Agent、供应商、模型、推理强度、Fast)。+ 没有覆盖时,沿用宿主核实的同插件本机在途 \`callId\` 所属任务;面板直接创建使用当前新任务选择。+ 无显式覆盖的已有专属任务保留自身模型,用户在任务中改选后可继续复用。+ 显式配置发生冲突时,新任务创建成功才替换映射,旧任务与历史保留。+- 保存、创建与派发前校验真实的模型/Agent/供应商组合;失效时引导用户到任务设置改选,+ 或修复供应商连接。不静默换模型、不从报错猜凭证失效,也不把目录可用当作远端推理一定成功。+- 权限独立来自用户插件设置;旧接口缺省保留历史 plan 值及原 Agent 行为,不将它宣称为+ 跨 Agent 的只读保证。新插件应使用普通任务接口,其缺省为普通任务的 ask 权限。+ 用户可显式选择 ask / acceptEdits / auto;不继承调用任务的完全访问。工作目录由宿主分配。- 目录有一个受控例外:run 请求可带 \`workingDir\`(绝对路径)**转述**一个目录,让 errand 会话建在项目里(Agent 能看到代码)。这不是授权——主机只认用户此前用 pick 能力(§4.14)在系统选目录窗口里**亲手选过**的目录(主机自己记的台账),别的路径一律 \`INVALID_REQUEST\`,此时应引导用户去你的设置页重新- 选一次目录;用户在「AI 代办」卡里配置了目录时,以用户配置优先、本字段忽略;+ 选一次目录;用户在「任务设置」卡里配置了目录时,以用户配置优先、本字段忽略;- 每插件同时 1 单在途、相邻提交至少隔 10 秒;结果超过 64K 字符会截断(尾部带标记);完成结果保留 30 分钟,应用重启后查无此单(按可重新提交处理);\`sessionKey\` 只是分间,**不放大并发**——不同钥匙的两单同样要排队;@@ -3897,10 +3903,19 @@ const r = await cindy.agent.requestSchedule({"将在此处打开",写"去自动化页确认"之类更准;- 一个都没有主窗口时(极端情况)→ \`HOST_NOT_READY\`。-什么时候**不该**用它:一次性的、当场就要结果的事,用快问快答(§4.0.2)或派活取件-(§4.11.1)。这个加档是给"长期定期刷新"用的,每条任务都会反复产生模型费用。+什么时候**不该**用它:一次性的事,用快问快答(§4.0.2)或普通任务接口+(§4.11.3)。这个加档是给"长期定期刷新"用的,每条任务都会反复产生模型费用。-### 4.11.3 普通任务接口(实验性)+### 4.11.3 新建任务与继续任务(普通 Session)++先按业务选择:+- 当前 Agent 已在处理你的工具:返回数据让它继续,不新建任务。+- 用户在稿件面板提交修改:\`cindy.agent.run({mode: 'continue', ...})\` 继续已关联原任务。OpenDesign 当前采用这一方式。+- 独立完成一项工作:\`cindy.tasks.create\` 新建普通任务,再用 \`send\` 开始执行。保存 taskId 后可继续同一任务。+- 需要更新插件页面:查询 \`getRun/listRuns\` 与 \`readMessages\`;没有默认回叫,不自动唤醒伙伴或 Agent。++用户界面统一叫「新建任务」「打开任务」「继续任务」。任务能使用什么模型、工具和权限,由普通任务配置与用户授权决定。+插件身份/业务关联在调用方保存,不把普通任务做成另一种产品对象。伙伴的完成回叫只属于伙伴自己的流程。声明 \`"agent": { "tasks": true }\` 后,逻辑页可使用 \`cindy.tasks\`。它是独立权限,旧 \`errand\` 声明不自动取得该权限;用户仍可在侧边栏查看和接手这些任务。@@ -3909,7 +3924,7 @@ const r = await cindy.agent.requestSchedule({面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:-\`create\`、\`get\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。+\`models\`、\`create\`、\`get\`、\`setModel\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`。可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,调用方已无正在执行的输入或已接受新真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限,自动回报和插件输入重试不构成真人接管。这不恢复插件控制权,也不保证停止已接受执行,不构成通用执行沙箱。在首次派发前调用 \`setTeamPlan({taskId,plan:{concurrency,task,items}})\`,每项包含@@ -3923,7 +3938,8 @@ const r = await cindy.agent.requestSchedule({计划不授予目录权限。Worker 仅可使用宿主任务目录及解析后仍在其中的子目录、插件 AI 配置目录或用户亲选的确切目录;Library 绑定不自动变成 Agent 工作根。宿主在登记和创建时均复核。这描述准入检查,不是持续的 OS 目录隔离保证。首版用于可信本地工作区;同权限进程在检查后恶意置换目录对象仍可能改变实际 cwd,不提供此类对抗性沙箱。-暂不支持选择现有任务、远程/伙伴任务、任意更新配置、归档、队列暂停或事件订阅。+\`models()\` 返回统一目录可选项的完整 route、efforts 和 supportsFastMode。用户明确选择后将 route 原样传给 create,或用 \`setModel({taskId, expectedRevision, route})\` 修改已有自有任务。运行中按普通任务的安全边界切换,不修改应用默认。两方法使用前检查 capabilities.operations。+暂不支持接管任意现有任务、远程/伙伴任务、其它配置修改、归档、队列暂停或事件订阅。旧 \`agent.errand\` 接口不变。\`\`\`js@@ -3945,14 +3961,21 @@ SDK 成功返回 data,失败抛出带 code 的错误。原始管子响应为 \create/send 的 requestKey 持久去重;同键不同内容拒绝。删除后的记录不自动重建。请求键及 taskId/runId 需要由插件保存。取消仅作用于该输入,不能停止用户后来的执行。-省略 route 时在接收时解析用户给本插件的 AI 配置;可显式传-\`{agentKind:'codex',providerId:'...',model:'...',effort:'high',fastMode:false}\`。-来源/模型/强度必须当前可用,派发前再次核对,不自动改用其它账号。+省略 route 时使用用户给本插件的任务模型覆盖;无覆盖则沿用发起任务,面板直接创建时+沿用当前新任务选择。可显式传+\`{agentKind:'codex',providerId:'...',model:'...',effort:'high',fastMode:false}\`;无推理档位模型用空 effort。+先查 \`capabilities().sourceCallContext\`:支持时,Agent 在途调用可在 create 中转传 \`callId\`。+宿主核对同插件本机调用后读取其模型;不能自报 sourceSessionId 或权限。面板直接创建省略 callId。+新字段需该能力为 true 才发送,旧客户端不能假定支持;同 requestKey 的重放保留原创建结果。+来源/模型/强度必须当前可用,派发前再次核对;失败引导改选或修复连接,不自动换模型或账号。+已有普通任务保留自身配置,用户在任务内修复后继续使用原任务。工作目录由宿主分配,或沿用用户已在插件设置中选择的目录;不接受任意路径或权限覆盖。-权限沿用 AI 代办配置,默认只读,禁止 bypassPermissions。+权限来自用户的插件任务设置,缺省使用普通任务的 ask 权限;工作区内行为及询问规则与所选+Agent 的普通任务一致。允许用户显式选择 acceptEdits / auto,禁止 bypassPermissions,+不继承发起任务的权限。既有任务与显式历史 plan 配置保留原行为,不自动提权;需要改变时由用户选择。create 可传 \`isolatedWorkspace:true\`,使用宿主为该任务生成的独立空目录,忽略插件的项目目录偏好。返回 workingDir 仅属于本插件创建的任务,可交给插件 Node 进程放入候选项目;不接受插件自报任意目录。-任务视图同时返回 permissionMode,插件在只读时应明确提示,不能暗中升级权限。+任务视图同时返回 permissionMode;按实际权限展示,不将历史 plan 值视作跨 Agent 的只读保证,不能暗中升级权限。run 的 acceptedConfig 是接收配置,execution 是观测到的原生 instance/generation,不冒充完整实际用量/重试清单。outputMessageId 来自产品终态,不是文字猜测。diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 2a9aa250e8..dcff37e6ac 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -287,7 +287,7 @@ import {} from './cindySlot.js';import { GhostAgentSlot, type GhostAgentTurnRunner } from './agentSlot.js';import { GhostErrandSlot, type GhostErrandRunner } from './errandSlot.js';-import { readGhostErrandConfig, writeGhostErrandConfig } from './errandPrefsStore.js';+import { readPluginTaskConfig, writePluginTaskConfig, validatePluginTaskConfig } from './pluginTaskPrefsStore.js';import {GhostNodeRuntimeBroker,type NodeRuntimeStartAttemptContext,@@ -1742,10 +1742,18 @@ export function isPluginTaskAuthorized(id: string): boolean {let errandSlotSingleton: GhostErrandSlot | null = null;-/** 派活取件槽单例(agent 槽 errand 加档):资格审/频控/任务表的统一守门点。 */+/** Only the Host's active same-plugin call can supply model context. Not an authority grant. */+export function getPluginTaskSourceSessionId(ghostId: string, callId?: string): string | undefined {+ if (!callId) return undefined;+ const call = getGhostCardService().inFlightCallInfoOf(callId);+ return call?.ghostId === ghostId && !call.remoteHostId ? call.sessionId ?? undefined : undefined;+}++/** Legacy result-returning adapter; does not own ordinary task configuration. */export function getGhostErrandSlot(): GhostErrandSlot {if (!errandSlotSingleton) {errandSlotSingleton = new GhostErrandSlot({+ resolveSourceSessionId: getPluginTaskSourceSessionId,getGhost: findAvailableGhost,// wait 模式的署名单在途期间替管子那头的 tool-call 续命(同 cindy 槽契约)。holdPipeCall: (ghostId, callId, budgetMs) =>@@ -7869,26 +7877,28 @@ export function registerGhostIpc(): void {},);- // ── agent 槽派活(errand)每插件配置(插件详情页「AI 代办」卡)──- // 读走 sendSync(与 cindy-prefs 同理:详情页首帧同帧渲染);写走 invoke,- // 整卡替换,值域清洗在存储层(errandPrefsStore.normalizeConfig 白名单,- // permissionMode 只认 plan/acceptEdits/auto——bypassPermissions 协议上不存在)。- // model/providerId 不在此处对目录校验:与 sessions:create 同一信任面- // (可信 renderer 配置面),过期值由 errand runner 建会话时按 mapper 兜底。+ // Plugin task preferences: ordinary tasks and the legacy errand adapter share+ // this configuration. Keep existing IPC names for renderer compatibility.+ // Save validates the current route; creation/execution revalidate independently.ipcMain.on('ghosts:errand-prefs', (event, ghostId: unknown) => {event.returnValue = {- config: typeof ghostId === 'string' ? readGhostErrandConfig(ghostId) : {},+ config: typeof ghostId === 'string' ? readPluginTaskConfig(ghostId) : {},};});- ipcMain.handle('ghosts:errand-prefs:set', (_event, ghostId: unknown, config: unknown) => {+ ipcMain.handle('ghosts:errand-prefs:set', async (event, ghostId: unknown, config: unknown) => {+ assertTrustedAppRendererEvent(event);+ const owner = captureGhostMutationOwner();if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');}if (config !== null && (typeof config !== 'object' || Array.isArray(config))) {throwIpcError('INVALID_PARAMS', 'config must be an object or null');}- const saved = writeGhostErrandConfig(ghostId, config as Record<string, unknown> | null);- return { config: saved };+ try { await validatePluginTaskConfig(config); }+ catch (error) { throwIpcError('INVALID_PARAMS', error instanceof Error ? error.message : '任务配置不可用'); }+ const release = beginGhostMutation(owner);+ try { return { config: writePluginTaskConfig(ghostId, config) }; }+ finally { release(); }});ipcMain.handle('ghosts:install', async (event, lizFilePath: unknown, opts: unknown) => {diff --git a/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.tssimilarity index 55%rename from apps/desktop/src/main/cindy-brain/errandPrefsStore.tsrename to apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.tsindex 9c479fa335..27fd851c3f 100644--- a/apps/desktop/src/main/cindy-brain/errandPrefsStore.ts+++ b/apps/desktop/src/main/cindy-brain/pluginTaskPrefsStore.ts@@ -1,18 +1,12 @@/**- * errandPrefsStore —— agent 槽「派活取件(errand)」的每插件用户配置持久化。- *- * File: <userData>/ghost-errand-prefs.json- *- * 形态:{ errand: { <ghostId>: { agentKind?, model?, effort?, fastMode?,- * providerId?, permissionMode?, workingDir? } } }- * - 全部字段缺省 = 跟随默认:agent/模型/effort/fast/供应商跟随「新建草稿」- * 偏好快照(与 Orca worker 同源,见 newMakerDefaultsCache),permissionMode- * 缺省 'plan'(只读,2026-07-31 定案),workingDir 缺省专属对话目录;- * - permissionMode 只收 GHOST_ERRAND_PERMISSION_MODES(plan/acceptEdits/auto),- * **bypassPermissions 在协议层就不存在**,存储层照单执法;- * - 抽离插件**不**清配置——与 cindy 槽覆盖同语义,重装回来钉的配置还在;- * - 模型/供应商的白名单校验由消费方(errand 服务)按当下目录做,存储层- * 不感知清单(过期值静默落回默认并留日志,同 cindySlot override 契约)。+ * User preferences for plugin-created ordinary tasks. The legacy errand adapter+ * consumes these same preferences; it does not own the model/permission policy.+ * Keep ghost-errand-prefs.json and its `errand`/`sessions` keys for installed-plugin+ * compatibility. `sessions` belongs only to the old errand sessionKey adapter.+ * Empty model preferences use the originating task or the current new-task route.+ * New ordinary tasks use ask; the legacy adapter retains its historical default.+ * Permissions stay independently user-owned, never caller-inherited.+ * Model admission belongs to the shared ordinary-session resolver, never this store.*/import {@@ -23,21 +17,27 @@ import { desktopMakerLogger } from '../maker-host/logger-adapter.js';import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';import { ownerScopedUserDataPath } from '../appSessionState.js';+/** User-owned plugin task permission policy. A model source never grants authority. */+export function clampPluginTaskPermissionMode(value: unknown, fallback: GhostErrandPermissionMode = 'ask'): GhostErrandPermissionMode {+ return typeof value === 'string' && (GHOST_ERRAND_PERMISSION_MODES as readonly string[]).includes(value)+ ? value as GhostErrandPermissionMode : fallback;+}+const log = desktopMakerLogger.child('errand-prefs-store');-/** errand 会话可选的 agent 种类(与 sessions.agent_kind 同词汇表)。 */-export const GHOST_ERRAND_AGENT_KINDS = ['cc', 'codex', 'pi'] as const;-export type GhostErrandAgentKind = (typeof GHOST_ERRAND_AGENT_KINDS)[number];+/** 插件任务可选的 agent 种类(与 sessions.agent_kind 同词汇表)。 */+export const PLUGIN_TASK_AGENT_KINDS = ['cc', 'codex', 'pi'] as const;+export type PluginTaskAgentKind = (typeof PLUGIN_TASK_AGENT_KINDS)[number];-/** errand 会话可选的思考强度(与 worker 同集合;minimal 刻意不收)。 */-export const GHOST_ERRAND_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;-export type GhostErrandEffort = (typeof GHOST_ERRAND_EFFORTS)[number];+/** 插件任务可选的思考强度(与 worker 同集合;包含 minimal)。 */+export const PLUGIN_TASK_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;+export type PluginTaskEffort = (typeof PLUGIN_TASK_EFFORTS)[number];-/** 单插件的 errand 配置(全部可缺省;缺省语义见文件头)。 */-export interface GhostErrandConfig {- agentKind?: GhostErrandAgentKind;+/** 单插件的任务配置(全部可缺省;缺省语义见文件头)。 */+export interface PluginTaskConfig {+ agentKind?: PluginTaskAgentKind;model?: string;- effort?: GhostErrandEffort;+ effort?: PluginTaskEffort;fastMode?: boolean;providerId?: string;permissionMode?: GhostErrandPermissionMode;@@ -45,8 +45,8 @@ export interface GhostErrandConfig {workingDir?: string;}-interface GhostErrandPrefs {- errand: Record<string, GhostErrandConfig>;+interface PluginTaskPrefs {+ errand: Record<string, PluginTaskConfig>;/*** 映射键 → 专属 errand 会话 id(runner 复用映射)。键形态两种:* `ghostId` = 该插件的缺省共用间;`ghostId#sessionKey` = 按钥匙分的间@@ -57,32 +57,32 @@ interface GhostErrandPrefs {sessions: Record<string, string>;}-/** sessions 表的映射键(见 GhostErrandPrefs.sessions 注释)。 */+/** sessions 表的映射键(见 PluginTaskPrefs.sessions 注释)。 */function sessionMapKey(ghostId: string, sessionKey?: string): string {return sessionKey ? `${ghostId}#${sessionKey}` : ghostId;}-const DEFAULTS: GhostErrandPrefs = { errand: {}, sessions: {} };+const DEFAULTS: PluginTaskPrefs = { errand: {}, sessions: {} };/** 单字段清洗:类型/值域不合法一律丢弃(= 回到跟随默认),不迁就脏数据。 */-function normalizeConfig(raw: unknown): GhostErrandConfig {+function normalizeConfig(raw: unknown): PluginTaskConfig {if (!raw || typeof raw !== 'object') return {};const r = raw as Record<string, unknown>;- const cfg: GhostErrandConfig = {};+ const cfg: PluginTaskConfig = {};if (typeof r.agentKind === 'string' &&- (GHOST_ERRAND_AGENT_KINDS as readonly string[]).includes(r.agentKind)+ (PLUGIN_TASK_AGENT_KINDS as readonly string[]).includes(r.agentKind)) {- cfg.agentKind = r.agentKind as GhostErrandAgentKind;+ cfg.agentKind = r.agentKind as PluginTaskAgentKind;}if (typeof r.model === 'string' && r.model.length > 0 && r.model.length <= 128) {cfg.model = r.model;}if (typeof r.effort === 'string' &&- (GHOST_ERRAND_EFFORTS as readonly string[]).includes(r.effort)+ (PLUGIN_TASK_EFFORTS as readonly string[]).includes(r.effort)) {- cfg.effort = r.effort as GhostErrandEffort;+ cfg.effort = r.effort as PluginTaskEffort;}if (typeof r.fastMode === 'boolean') cfg.fastMode = r.fastMode;if (typeof r.providerId === 'string' && r.providerId.length > 0 && r.providerId.length <= 128) {@@ -100,10 +100,10 @@ function normalizeConfig(raw: unknown): GhostErrandConfig {return cfg;}-function normalize(raw: unknown): GhostErrandPrefs {+function normalize(raw: unknown): PluginTaskPrefs {if (!raw || typeof raw !== 'object') return { errand: {}, sessions: {} };const errandRaw = (raw as { errand?: unknown }).errand;- const errand: GhostErrandPrefs['errand'] = {};+ const errand: PluginTaskPrefs['errand'] = {};if (errandRaw && typeof errandRaw === 'object') {for (const [ghostId, cfgRaw] of Object.entries(errandRaw as Record<string, unknown>)) {const cfg = normalizeConfig(cfgRaw);@@ -111,7 +111,7 @@ function normalize(raw: unknown): GhostErrandPrefs {}}const sessionsRaw = (raw as { sessions?: unknown }).sessions;- const sessions: GhostErrandPrefs['sessions'] = {};+ const sessions: PluginTaskPrefs['sessions'] = {};if (sessionsRaw && typeof sessionsRaw === 'object') {for (const [ghostId, v] of Object.entries(sessionsRaw as Record<string, unknown>)) {if (typeof v === 'string' && v.length > 0 && v.length <= 128) sessions[ghostId] = v;@@ -120,7 +120,7 @@ function normalize(raw: unknown): GhostErrandPrefs {return { errand, sessions };}-const store = createOverrideSettingsFile<GhostErrandPrefs>({+const store = createOverrideSettingsFile<PluginTaskPrefs>({filePath: () => ownerScopedUserDataPath('ghost-errand-prefs.json'),defaults: DEFAULTS,normalize,@@ -128,19 +128,38 @@ const store = createOverrideSettingsFile<GhostErrandPrefs>({label: 'ghost-errand-prefs',});-/** 读某插件的 errand 配置(缺省空对象 = 全跟随默认)。 */-export function readGhostErrandConfig(ghostId: string): GhostErrandConfig {+// Register owns the runtime catalog; configuration persistence never builds another picker.+let validateSelection: ((config: PluginTaskConfig) => Promise<void>) | null = null;+export function setPluginTaskConfigValidator(validator: (config: PluginTaskConfig) => Promise<void>): void {+ validateSelection = validator;+}+export async function validatePluginTaskConfig(raw: unknown): Promise<void> {+ const config = normalizeConfig(raw);+ if (raw && typeof raw === 'object') {+ for (const key of ['agentKind', 'model', 'providerId', 'effort', 'fastMode', 'permissionMode', 'workingDir'] as const) {+ if ((raw as Record<string, unknown>)[key] !== undefined && config[key] === undefined) {+ throw new Error(`任务配置 ${key} 无效,请重新选择`);+ }+ }+ }+ if (![config.agentKind, config.model, config.providerId, config.effort, config.fastMode].some(v => v !== undefined)) return;+ if (!validateSelection) throw new Error('模型服务尚未就绪,请稍后重试');+ await validateSelection(config);+}++/** 读某插件的任务配置(缺省空对象 = 全跟随默认)。 */+export function readPluginTaskConfig(ghostId: string): PluginTaskConfig {// mtime 守卫现读:直接改文件也算配置入口(与 cindy prefs 同契约)。store.invalidateIfChanged();return store.read().errand[ghostId] ?? {};}/**- * 整份替换某插件的 errand 配置(设置卡整卡提交);传 null / 清洗后为空+ * 整份替换某插件的任务配置(设置卡整卡提交);传 null / 清洗后为空* 即删除条目(恢复全跟随默认,规则 20 语义)。入参收 unknown:IPC 层只做* 形状粗筛,逐字段值域清洗统一在这里(单一执法点)。返回清洗后的落盘值。*/-export function writeGhostErrandConfig(ghostId: string, config: unknown): GhostErrandConfig {+export function writePluginTaskConfig(ghostId: string, config: unknown): PluginTaskConfig {store.invalidateIfChanged();const errand = { ...store.read().errand };const cfg = config === null ? {} : normalizeConfig(config);diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.tsindex 1257036bb6..9c58d5d257 100644--- a/apps/desktop/src/main/cindy-brain/taskSlot.ts+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts@@ -5,6 +5,8 @@ import { hasPluginTaskApproval } from './taskCapability.js';export const PLUGIN_TASK_OPERATIONS = ['capabilities',+ 'models',+ 'setModel','requestWriteAccess','startTeam','getTeam',@@ -28,7 +30,9 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskRequeif (!object(value) || value.type !== 'tasks-request') return false;const allowed: Record<string, string[]> = {capabilities: [],- create: ['requestKey', 'title', 'route', 'isolatedWorkspace'],+ models: [],+ setModel: ['taskId', 'expectedRevision', 'route'],+ create: ['requestKey', 'title', 'route', 'isolatedWorkspace', 'callId'],list: ['after', 'limit'],get: ['taskId'],requestWriteAccess: ['taskId', 'mode'],@@ -49,9 +53,11 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskRequeif (kind === 'requestWriteAccess' && value.mode !== undefined && !['acceptEdits', 'auto'].includes(String(value.mode))) return false;const requires = (key: string) => text(value[key], 128);if (['create', 'send', 'cancel'].includes(value.kind) && !requires('requestKey')) return false;- if (['get', 'send', 'listRuns', 'readMessages', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker'].includes(value.kind) && !requires('taskId'))+ if (['get', 'setModel', 'send', 'listRuns', 'readMessages', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker'].includes(value.kind) && !requires('taskId'))return false;if (['getRun', 'cancel'].includes(value.kind) && !requires('runId')) return false;+ if (kind === 'setModel' && (!object(value.route) || !Number.isSafeInteger(value.expectedRevision) || (value.expectedRevision as number) < 0)) return false;+ if (value.callId !== undefined && !text(value.callId, 128)) return false;if (value.isolatedWorkspace !== undefined && typeof value.isolatedWorkspace !== 'boolean') return false;if (value.kind === 'create' && !text(value.title, 100)) return false;if (@@ -97,7 +103,7 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskReque!['cc', 'codex', 'pi'].includes(String(r.agentKind)) ||!text(r.providerId, 128) ||!text(r.model, 256) ||- !text(r.effort, 32) ||+ (typeof r.effort !== 'string' || r.effort.length > 32) ||typeof r.fastMode !== 'boolean')return false;@@ -138,6 +144,7 @@ export async function handlePluginTaskRequest(targets: ['own-plugin-local-session'],maxPageSize: 100,exactRoute: true,+ sourceCallContext: true,},};if (!deps.handler) return error('HOST_NOT_READY', 'Task service is not ready', true);diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.tsindex 4c4b50882e..7a85d214fc 100644--- a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts@@ -49,6 +49,7 @@ export interface WorkspaceSessionService {findActiveSessionByWorkdir(dirAbs: string): Promise<string | null>;/** 创建 plugin 来源的空 draft 会话(不拉起 agent 进程),返回会话 id。 */createDraftSession(params: {+ sourceSessionId?: string;dirAbs: string;title: string | null;ghostId: string;@@ -159,6 +160,7 @@ export class GhostWorkspaceSlot {// ── 目录授权 ────────────────────────────────────────────────────────let dirAbs: string;+ let sourceSessionId: string | undefined;let callIsCurrent: (() => boolean) | undefined;if (request.mode === 'pick') {this.consentInFlight = true;@@ -202,6 +204,7 @@ export class GhostWorkspaceSlot {'本次调用没有会话语境,无法向用户弹确认卡;请改用 mode:"pick" 让用户亲自选目录',);}+ sourceSessionId = ctx.sessionId;const authorization = service.captureSessionAuthorization?.(ctx.sessionId, ctx.sessionInstanceId);if (service.captureSessionAuthorization && !authorization) {return fail('PERMISSION_DENIED', 'The originating task cannot authorize this workspace operation.');@@ -280,6 +283,7 @@ export class GhostWorkspaceSlot {return { ok: true, sessionId: existing, created: false, name };}const sessionId = await service.createDraftSession({ dirAbs, title, ghostId,+ ...(sourceSessionId ? { sourceSessionId } : {}),...(callIsCurrent ? { shouldContinue: callIsCurrent } : {}),});if (!sessionId || (callIsCurrent && !callIsCurrent())) return fail('CANCELLED', 'The originating tool call has ended.');diff --git a/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.tsnew file mode 100644index 0000000000..ab13a885e8--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/sessionOpening.test.ts@@ -0,0 +1,64 @@+import { beforeEach, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({ owner: {} as object | null,+ run: vi.fn(async () => undefined), values: vi.fn(), bootstrap: vi.fn(async () => undefined),+}));+vi.mock('../client/current', () => ({ getCurrentDbClientSnapshot: () => h.owner,+ getDbClient: () => ({ drizzle: { insert: () => ({ values: h.values }) } }) }));+vi.mock('../dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: (id: string) => `/dialogue/${id}` }));+vi.mock('../../git-snapshot/projectGitBootstrap', () => ({ ensureProjectGitInitialized: h.bootstrap }));+vi.mock('../../maker-host/git-safety-settings-store', () => ({ readGitSafetySettings: () => ({ autoSnapshotEnabled: false, autoInitProjectGit: false }) }));+import { openSession, setSessionOpeningModelAdmission, type OpenedSessionRow } from '../sessionOpening';+import { resolveSessionExecutionSelection } from '../../maker-ipc/sessionExecutionSelection';++const body = { agentKind: 'codex' as const, model: 'model', providerId: 'connected', effort: '', fastMode: false,+ workspaceKind: 'dialogue' as const, permissionMode: 'ask', title: 'Normal task' };+beforeEach(() => {+ vi.clearAllMocks(); h.owner = {}; h.values.mockReturnValue({ run: h.run });+ h.bootstrap.mockResolvedValue(undefined);+ setSessionOpeningModelAdmission(async request => {+ const route = resolveSessionExecutionSelection({ selection: request,+ availableAgents: ['codex'], availableModels: [{ id: 'model', efforts: [] }], hasCindyAiApiKey: false,+ providerRouting: { availability: { 'claude-code': [], pi: [], codex: [{ id: 'connected', name: 'Connected', models: ['model'] }] },+ resolveDefaultProviderIdForModel: () => 'connected' } });+ return { ...request, model: route.model, providerId: route.providerId, effort: route.effort ?? '' };+ });+});+it.each(['desktop', 'plugin'] as const)('opens the same normal Session for %s without inventing model/permission defaults', async source => {+ const opened = await openSession({ id: 'session', body, source });+ expect(opened.row).toMatchObject({ id: 'session', model: 'model', providerId: 'connected', agentKind: 'codex',+ effort: '', permissionMode: 'ask', source, workingDir: '/dialogue/session' });+ expect(h.run).toHaveBeenCalledOnce();+});+it('rejects an unavailable route before directory preparation and persistence', async () => {+ await expect(openSession({ body: { ...body, providerId: 'disconnected' } })).rejects.toThrow('供应商');+ expect(h.bootstrap).not.toHaveBeenCalled(); expect(h.values).not.toHaveBeenCalled();+});+it('commits a companion receipt with the admitted Session while sampling current permission after preparation', async () => {+ let permission = 'bypassPermissions';+ h.bootstrap.mockImplementationOnce(async () => { permission = 'plan'; });+ const commit = vi.fn(async (row: OpenedSessionRow) => ({ receiptSessionId: row.id, permission: row.permissionMode }));+ const opened = await openSession({ body, finalize: () => ({ permissionMode: permission, parentSessionId: 'parent' }) }, commit);+ expect(opened.value).toEqual({ receiptSessionId: opened.row.id, permission: 'plan' });+ expect(opened.row.parentSessionId).toBe('parent');+ expect(h.values).not.toHaveBeenCalled(); expect(commit).toHaveBeenCalledOnce();+});+it('does not retry a failed atomic commit as an ordinary insert', async () => {+ const commit = vi.fn(async () => { throw new Error('transaction failed'); });+ await expect(openSession({ body }, commit)).rejects.toThrow('transaction failed');+ expect(commit).toHaveBeenCalledOnce(); expect(h.values).not.toHaveBeenCalled();+});+it('rejects account changes during directory preparation before committing', async () => {+ h.bootstrap.mockImplementationOnce(async () => { h.owner = {}; });+ await expect(openSession({ body })).rejects.toThrow('账号已变化');+ expect(h.values).not.toHaveBeenCalled();+});++it('lets a queued commit recheck the account before its actual insert', async () => {+ await expect(openSession({ body }, async (_row, assertCurrent) => {+ await Promise.resolve();+ h.owner = {};+ assertCurrent();+ await h.run();+ })).rejects.toThrow('账号已变化');+ expect(h.run).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex f00bb2c8ea..04d5cfe216 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -1,3 +1,4 @@+import { setSessionOpeningModelAdmission } from '../../sessionOpening';import { ScriptTarget, transpileModule } from 'typescript';import { canResumeAfterRuntimeFallback } from '../../../maker-ipc/botCandidateRecovery';import { createDrizzleProxy } from '../../client/drizzleProxy';@@ -53,7 +54,7 @@ vi.mock('electron-store', () => ({ default: class {} }));vi.mock('../../../maker-ipc/appDefaultModelControl.js', async importOriginal => ({...await importOriginal<typeof import('../../../maker-ipc/appDefaultModelControl.js')>(),- validateBotTaskModel: vi.fn(async () => true),+ validateTaskModel: vi.fn(async () => true),}));const h = await vi.hoisted(async () => {@@ -135,6 +136,7 @@ vi.mock('electron', () => ({dialog: { showOpenDialog: h.showOpenDialog },}));vi.mock('../../client/current', () => ({+ getCurrentDbClientSnapshot: () => h,getDbClient: () => ({ drizzle: h.db, tx: h.tx }),tryGetDbClient: () => ({ drizzle: h.db, tx: h.tx }),}));@@ -481,6 +483,7 @@ const capabilityDeps = {const { list: findBotCapabilities, select: selectBotCapability } = createBotCapabilityService(capabilityDeps);beforeEach(async () => {+ setSessionOpeningModelAdmission(async body => body);setModelVisibilityMirror({}, { fallback: true });h.toolsetsAvailable = false;h.validateCapabilityAdditions.mockReset().mockResolvedValue(undefined);@@ -3614,6 +3617,7 @@ describe('Bot Session task end-to-end runtime', () => {getWorktree?: Parameters<typeof createBotDelegationService>[0]['getWorktree'];withTransferredWorktree?: Parameters<typeof createBotDelegationService>[0]['withTransferredWorktree'];prepareWorktree?: Parameters<typeof createBotDelegationService>[0]['prepareWorktree'];+ discardUnusedWorktree?: Parameters<typeof createBotDelegationService>[0]['discardUnusedWorktree'];taskQueue?: Parameters<typeof createBotDelegationService>[0]['taskQueue'];taskRoute?: Parameters<typeof createBotDelegationService>[0]['taskRoute'];taskControl?: boolean;@@ -3859,6 +3863,7 @@ describe('Bot Session task end-to-end runtime', () => {: undefined),withSessionLock: options.withSessionLock,prepareWorktree: options.prepareWorktree,+ discardUnusedWorktree: options.discardUnusedWorktree,getWorktree: options.getWorktree,reconcileWorktree: options.reconcileWorktree,withTransferredWorktree: options.withTransferredWorktree,@@ -4309,7 +4314,7 @@ describe('Bot Session task end-to-end runtime', () => {const runtime = createDelegationRuntime({ readCallerPermission: () => permission });const starting = runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Run the requested checks.' });try {- await vi.waitFor(() => expect(h.ensureGit).toHaveBeenCalledWith(expect.objectContaining({ source: 'bot-delegation' })));+ await vi.waitFor(() => expect(h.ensureGit).toHaveBeenCalledWith(expect.objectContaining({ source: 'session-open' })));permission = settledMode;finishPreparation();const result = await starting;@@ -5695,6 +5700,29 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it('keeps a committed task workspace when a later authority read fails', async () => {+ await seedPair();+ const discard = vi.fn(async () => undefined);+ const runtime = createDelegationRuntime({+ prepareWorktree: async () => ({ ok: true, sessionId: 'committed-task', workingDir: h.userDataDir }),+ discardUnusedWorktree: discard,+ readCallerPermission: () => {+ if (h.sqlite!.prepare('SELECT id FROM sessions WHERE id = ?').get('committed-task')) {+ throw new Error('authority temporarily unavailable');+ }+ return 'auto';+ },+ });+ try {+ await expect(runtime.delegation.startSessionTask({ callerSessionId: 'session-1',+ objective: 'Keep committed history and workspace.', workingDir: h.userDataDir, useWorktree: true }))+ .rejects.toThrow('authority temporarily unavailable');+ expect(h.sqlite!.prepare('SELECT id FROM sessions WHERE id = ?').get('committed-task')).toBeTruthy();+ expect(discard).not.toHaveBeenCalled();+ expect(runtime.started).toEqual([]);+ } finally { runtime.dispose(); }+ });+it('still publishes and dispatches a committed worktree task when its display snapshot fails', async () => {await seedPair();const runtime = createDelegationRuntime({ prepareWorktree: async () => ({ ok: true,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex b1338857fa..991e137ed7 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -1,3 +1,4 @@+import { setSessionOpeningModelAdmission, type SessionOpenBody } from '../../sessionOpening';/*** sessionsUpdate.test.ts — `local-db:sessions:update` handler 集成接线。* -------------------------------------------------------------------@@ -106,6 +107,7 @@ vi.mock('../../../logger', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));vi.mock('../../client/current', () => ({+ getCurrentDbClientSnapshot: () => h,getDbClient: () => h.client,getCurrentDbClientUserId: () => 'test-user',}));@@ -317,6 +319,7 @@ async function invokeCreate(body: Record<string, unknown>): Promise<unknown> {}beforeEach(() => {+ setSessionOpeningModelAdmission(async body => body);vi.clearAllMocks();h.relocate.mockImplementation(async () => ({ persistedSdkSessionId: null }));h.commitBotProfileDeletion.mockResolvedValue({ status: 'archived', sessionIds: [] });@@ -1373,3 +1376,18 @@ describe('local-db:sessions:set-pinned-card-summaries', () => {expect(h.setPinnedSectionCardMode).not.toHaveBeenCalled();});});++it('opens a normal renderer task through shared model admission', async () => {+ const admission = vi.fn(async (body: SessionOpenBody) => ({ ...body, agentKind: 'codex' as const,+ model: 'selected-model', providerId: 'selected-provider', effort: '', fastMode: false }));+ setSessionOpeningModelAdmission(admission);+ await invokeCreate({ id: 'normal-open', title: 'Normal task', workspaceKind: 'project', permissionMode: 'auto' });+ expect(admission).toHaveBeenCalledOnce();+ expect(h.sqlite!.prepare('SELECT model, provider_id, effort, permission_mode FROM sessions WHERE id = ?').get('normal-open'))+ .toEqual({ model: 'selected-model', provider_id: 'selected-provider', effort: '', permission_mode: 'auto' });+});+it('does not create a renderer task when common model admission fails', async () => {+ setSessionOpeningModelAdmission(async () => { throw new Error('model unavailable'); });+ await expect(invokeCreate({ id: 'rejected-open', title: 'Rejected task' })).rejects.toThrow('model unavailable');+ expect(h.sqlite!.prepare('SELECT id FROM sessions WHERE id = ?').get('rejected-open')).toBeUndefined();+});diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex a7d78b4664..38eba34d95 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -76,7 +76,7 @@ import {NEW_BOT_DEFAULT_PI_PROVIDER,} from '../../../shared/botDefaults.js';import { normalizeBotModelChain, readBotTaskModelOverride } from '../../../shared/botModelChain.js';-import { validateBotTaskModel } from '../../maker-ipc/appDefaultModelControl.js';+import { validateTaskModel } from '../../maker-ipc/appDefaultModelControl.js';import {activeOwnerScopeKey,isAppSessionBoundaryPending,@@ -1532,7 +1532,7 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,const normalizedNextConfig = normalizeBotModelCapabilitiesOrThrow(nextConfig);if (JSON.stringify(previous.taskModelOverride ?? null) !== JSON.stringify(normalizedNextConfig.taskModelOverride ?? null)) {const taskModel = readBotTaskModelOverride(normalizedNextConfig.taskModelOverride);- if (taskModel && !await validateBotTaskModel(taskModel)) {+ if (taskModel && !await validateTaskModel(taskModel)) {throwIpcError('INVALID_PARAMS', '任务模型不可用,请重新选择模型、来源与引擎');}owner.assertCurrent();diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.tsindex c00de03aba..464ae0a45d 100644--- a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts@@ -1,3 +1,4 @@+import { openSession } from '../sessionOpening.js';/*** pluginWorkspaceSessions —— workspace 槽的会话判重与创建(main 侧服务)。*@@ -25,10 +26,6 @@ import { and, eq, isNull, isNotNull, ne, or } from 'drizzle-orm';import { getDbClient } from '../client/current';import { sessions } from '../schema';-import { sessionCreateToRow } from '../mapper';-import { ensureDialogueWorkspaceDir } from '../dialogueWorkspace';-import { ensureProjectGitInitialized } from '../../git-snapshot/projectGitBootstrap';-import { readGitSafetySettings } from '../../maker-host/git-safety-settings-store';import { upsertRecentWorkdir } from './recentWorkdirs';import { createLogger } from '../../logger';import { pickSessionForWorkdir } from '../pluginWorkspaceDedupe';@@ -72,10 +69,10 @@ export async function createPluginDraftSession(params: {/** Existing originating-call predicate; checked before bootstrap and DB submission. */shouldContinue?: () => boolean;/**- * 会话默认值(register 侧从 New Maker 面板缓存解析;缓存未就绪时为空,- * 由 mapper 兜底)——让插件建的 draft 跟随用户当前的模型/强度选择。+ * 由宿主解析的完整模型配置;缺省时交普通 Session 入口读取当前新任务选择。*/defaults?: {+ permissionMode?: 'ask' | 'plan' | 'acceptEdits' | 'auto';agentKind?: 'cc' | 'codex' | 'pi';model?: string;effort?: string;@@ -89,47 +86,19 @@ export async function createPluginDraftSession(params: {notifySessionCreated?: (info: { sessionId: string; workdir?: string }) => void;}): Promise<string | null> {if (params.shouldContinue && !params.shouldContinue()) return null;- const db = getDbClient().drizzle;const now = Date.now();const id = randomUUID();const workingDir = normalizeWorkingDirForStorage(params.dirAbs) ?? undefined;- const insertRow = {- ...sessionCreateToRow(- id,- {- workingDir,- workspaceKind: 'project',- ...(params.defaults?.agentKind ? { agentKind: params.defaults.agentKind } : {}),- ...(params.defaults?.model ? { model: params.defaults.model } : {}),- ...(params.defaults?.effort ? { effort: params.defaults.effort } : {}),- ...(params.defaults?.fastMode !== undefined ? { fastMode: params.defaults.fastMode } : {}),- ...(params.defaults?.providerId !== undefined- ? { providerId: params.defaults.providerId }- : {}),- },- now,- ),- // mapper 不透传 source(renderer 面向的 create 不允许自选来源);插件- // 会话的来源只在这条 main 侧路径上显式落值。- source: 'plugin' as const,- ...(params.title ? { title: params.title } : {}),- };- // 与 local-db:sessions:create 同流程:只有“所有项目”模式才会给空目录 git init,- // 已有 Git 项目仍可在“已有 Git 项目”模式下记录保存点。- const gitSafety = readGitSafetySettings();- await ensureProjectGitInitialized({- workingDir: insertRow.workingDir,- workspaceKind: insertRow.workspaceKind,- remoteHostId: insertRow.remoteHostId,- sessionId: id,- autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,- autoInitProjectGit: gitSafety.autoInitProjectGit,- source: 'plugin-workspace-session',- });- if (params.shouldContinue && !params.shouldContinue()) return null;- // Explicit run() submits the async DB request in this synchronous segment.- // The worker may queue it; cancellation cannot retract an already submitted write.- await db.insert(sessions).values(insertRow).run();+ let insertRow;+ try {+ ({ row: insertRow } = await openSession({ id, now, source: 'plugin',+ body: { ...params.defaults, workingDir, workspaceKind: 'project', ...(params.title ? { title: params.title } : {}) },+ assertCurrent: () => { if (params.shouldContinue && !params.shouldContinue()) throw new Error('SESSION_OPEN_CANCELLED'); },+ }));+ } catch (error) {+ if (error instanceof Error && error.message === 'SESSION_OPEN_CANCELLED') return null;+ throw error;+ }if (insertRow.workingDir) {// 用户刚为这个目录做过授权动作(亲选/确认卡),进"最近项目"列表合理;// 失败仅日志,不阻断创建流程(与既有 create 同纪律)。@@ -157,16 +126,13 @@ export async function createPluginDraftSession(params: {}/**- * 创建 agent 槽「派活取件(errand)」的专属会话行(不拉起 agent 进程)。- *- * 与 createPluginDraftSession 的分工:workspace 槽建的是用户项目里的普通- * draft;errand 会话是插件的干活间——缺省落在专属 dialogue 目录(不碰用户- * 项目),只有用户在插件详情页亲手选了项目目录才落 project。权限档由调用方- * (errand runner)按用户配置传入,缺省档 plan(只读,2026-07-31 定案)在- * runner 侧兜底,这里照传入值落库。source='plugin' 语义同上;Orca 字段- * 显式排除——errand 会话在侧边栏可见、可旁观,不做隐藏会话。+ * Persist a visible ordinary local task created by a plugin, without starting an Agent.+ * The tasks API and legacy errand adapter both use this creator. The caller resolves+ * and validates the complete model tuple and user permission before reaching here.+ * No directory preference means a Host-managed dialogue directory; a project root+ * must have been selected/authorized by the user. This function adds no Orca identity.*/-export async function createGhostErrandSession(params: {+export async function createPluginTaskSession(params: {ghostId: string;/** Host-allocated durable task identity; never taken directly from plugin payload. */sessionId?: string;@@ -179,53 +145,27 @@ export async function createGhostErrandSession(params: {effort?: string;fastMode?: boolean;providerId?: string | null;- permissionMode: 'plan' | 'acceptEdits' | 'auto';+ permissionMode: 'ask' | 'plan' | 'acceptEdits' | 'auto';/** 用户亲选的项目目录(绝对路径);缺省 = 专属 dialogue 目录。 */workingDir?: string;notifySessionCreated?: (info: { sessionId: string; workdir?: string }) => void;}): Promise<string> {if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');- const db = getDbClient().drizzle;const now = Date.now();const id = params.sessionId ?? randomUUID();const projectDir = params.workingDir? (normalizeWorkingDirForStorage(params.workingDir) ?? undefined): undefined;const workspaceKind = projectDir ? ('project' as const) : ('dialogue' as const);- const workingDir = projectDir ?? ensureDialogueWorkspaceDir(id, now);- const insertRow = {- ...sessionCreateToRow(- id,- {- workingDir,- workspaceKind,- permissionMode: params.permissionMode,- ...(params.agentKind ? { agentKind: params.agentKind } : {}),- ...(params.model ? { model: params.model } : {}),- ...(params.effort ? { effort: params.effort } : {}),- ...(params.fastMode !== undefined ? { fastMode: params.fastMode } : {}),- ...(params.providerId !== undefined ? { providerId: params.providerId } : {}),- },- now,- ),- source: 'plugin' as const,- ...(params.title ? { title: params.title } : {}),- };- // 与既有 create 同流程;dialogue 目录由 projectGitBootstrap 自带守卫跳过。- const gitSafety = readGitSafetySettings();- await ensureProjectGitInitialized({- workingDir: insertRow.workingDir,- workspaceKind: insertRow.workspaceKind,- remoteHostId: insertRow.remoteHostId,- sessionId: id,- autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,- autoInitProjectGit: gitSafety.autoInitProjectGit,- source: 'plugin-errand-session',+ const { row: insertRow } = await openSession({ id, now, source: 'plugin',+ body: { workingDir: projectDir, workspaceKind, permissionMode: params.permissionMode,+ agentKind: params.agentKind, model: params.model, effort: params.effort,+ fastMode: params.fastMode, providerId: params.providerId,+ ...(params.title ? { title: params.title } : {}) },+ assertCurrent: () => { if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed'); },+ onPersistenceStarted: params.onPersistenceStarted,});if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');- params.onPersistenceStarted?.();- await db.insert(sessions).values(insertRow);- if (params.shouldContinue && !params.shouldContinue()) throw new Error('Plugin task owner changed');if (projectDir && insertRow.workingDir) {// 项目目录是用户在插件详情页亲手选的,进"最近项目"合理;dialogue 目录// 是 app 管理的临时间,不进。失败仅日志,不阻断创建。@@ -237,12 +177,12 @@ export async function createGhostErrandSession(params: {...(insertRow.workingDir ? { workdir: insertRow.workingDir } : {}),});} catch (error) {- log.warn('[plugin-errand] notifySessionCreated failed', {+ log.warn('[plugin-task] notifySessionCreated failed', {sessionId: id,err: error instanceof Error ? error.message : String(error),});}- log.info('[plugin-errand] errand session created', {+ log.info('[plugin-task] session created', {sessionId: id,ghostId: params.ghostId,workspaceKind,diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 8e4b448857..bd6e0685e0 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1,3 +1,4 @@+import { openSession } from '../sessionOpening.js';/*** chat-data-localization F5:Sessions IPC handlers(C6)。*@@ -61,8 +62,6 @@ import {} from '../mapper';import { ensureDialogueWorkspaceDir } from '../dialogueWorkspace';import { recomputePrRefsForSession } from '../../git-context/prRefsStore';-import { ensureProjectGitInitialized } from '../../git-snapshot/projectGitBootstrap';-import { readGitSafetySettings } from '../../maker-host/git-safety-settings-store';import * as imageCacheStore from '../../imageCacheStore';import { removeSessionRefsIfDeleted as removeDeletedSessionMediaRefs } from '../../cindy-media/ledger';import { removeWechatSessionAttachmentDir } from '../../im/wechat/mediaStaging';@@ -1437,27 +1436,15 @@ export function registerSessionIpc();}}- // body 透传 agentKind / orcaRole 给 mapper;非法值已由上方校验拦截,默认值由 mapper 兜底。- const insertRow = sessionCreateToRow(id, { ...createBody, workspaceKind, workingDir }, now);- const gitSafety = readGitSafetySettings();- await ensureProjectGitInitialized({- workingDir: insertRow.workingDir,- workspaceKind: insertRow.workspaceKind,- remoteHostId: insertRow.remoteHostId,- sessionId: id,- autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,- autoInitProjectGit: gitSafety.autoInitProjectGit,- source: 'local-db:sessions:create',+ const { row: insertRow } = await openSession({ id, now,+ body: { ...createBody, workspaceKind, workingDir },+ }, async (prepared, assertCurrent) => {+ const resource = !prepared.remoteHostId && prepared.workingDir+ ? managedWorktreeRoot(prepared.workingDir) : null;+ const insert = async () => { assertCurrent(); await db.insert(sessions).values(prepared); };+ if (resource) await withWorktreeMutation([resource], insert);+ else await insert();});- const resource =- !insertRow.remoteHostId && insertRow.workingDir- ? managedWorktreeRoot(insertRow.workingDir)- : null;- const insert = async () => {- await db.insert(sessions).values(insertRow);- };- if (resource) await withWorktreeMutation([resource], insert);- else await insert();const [row] = await db.select().from(sessions).where(eq(sessions.id, id));if (!row) throwIpcError('NOT_FOUND', 'Session 创建后查询失败');// recent-workdirs: 项目目录走 sidebar 分组,要进"最近"列表;dialogue 目录是diff --git a/apps/desktop/src/main/localDb/sessionOpening.ts b/apps/desktop/src/main/localDb/sessionOpening.tsnew file mode 100644index 0000000000..10de9b09f6--- /dev/null+++ b/apps/desktop/src/main/localDb/sessionOpening.ts@@ -0,0 +1,67 @@+import { randomUUID } from 'node:crypto';+import { sessionCreateToRow } from './mapper.js';+import { getDbClient, getCurrentDbClientSnapshot } from './client/current.js';+import { sessions } from './schema.js';+import { ensureDialogueWorkspaceDir } from './dialogueWorkspace.js';+import { ensureProjectGitInitialized } from '../git-snapshot/projectGitBootstrap.js';+import { readGitSafetySettings } from '../maker-host/git-safety-settings-store.js';+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';++export type SessionOpenBody = NonNullable<Parameters<typeof sessionCreateToRow>[1]>;+export type OpenedSessionRow = ReturnType<typeof sessionCreateToRow> & { model: string };+type ModelAdmission = (body: SessionOpenBody) => Promise<SessionOpenBody>;+let admitModel: ModelAdmission | null = null;++/** Host installs its ordinary model catalog once; UI, tools, companions and plugins share it. */+export function setSessionOpeningModelAdmission(admission: ModelAdmission): void {+ admitModel = admission;+}++/**+ * Open a normal Cindy Session. No messages are sent and no callback Agent is started.+ * Entry adapters authorize the caller/directory. A companion may atomically commit+ * its own receipt with the Session, while its timeline and completion signal remain outside.+ */+export async function openSession<T = void>(input: {+ id?: string;+ now?: number;+ body: SessionOpenBody;+ source?: OpenedSessionRow['source'];+ assertCurrent?: () => void;+ /** Sample effective authority after async preparation, directly before committing. */+ finalize?: () => Pick<SessionOpenBody, 'permissionMode' | 'parentSessionId'>;+ onPersistenceStarted?: () => void;+}, commit?: (row: OpenedSessionRow, assertCurrent: () => void) => Promise<T>): Promise<{ row: OpenedSessionRow; value: T }> {+ const owner = getCurrentDbClientSnapshot();+ const assertCurrent = () => {+ if (!owner || getCurrentDbClientSnapshot() !== owner) throw new Error('账号已变化,请重新新建任务');+ input.assertCurrent?.();+ };+ assertCurrent();+ const db = getDbClient().drizzle;+ const id = input.id ?? randomUUID();+ const now = input.now ?? Date.now();+ if (!admitModel) throw new Error('任务模型服务尚未就绪,请稍后重试');+ // Remote model admission belongs to the execution host. Preserve the existing remote path.+ const selected = input.body.remoteHostId ? input.body : await admitModel({ ...input.body });+ assertCurrent();+ const workspaceKind = selected.workspaceKind ?? 'project';+ const explicitDir = normalizeWorkingDirForStorage(selected.workingDir) ?? undefined;+ const workingDir = workspaceKind === 'dialogue' && !explicitDir+ ? ensureDialogueWorkspaceDir(id, now) : explicitDir;+ const prepared = { ...selected, workspaceKind, workingDir };+ const safety = readGitSafetySettings();+ await ensureProjectGitInitialized({ workingDir, workspaceKind, remoteHostId: prepared.remoteHostId ?? null,+ sessionId: id, autoSnapshotEnabled: safety.autoSnapshotEnabled,+ autoInitProjectGit: safety.autoInitProjectGit, source: 'session-open' });+ assertCurrent();+ const mapped = sessionCreateToRow(id, { ...prepared, ...input.finalize?.() }, now);+ if (!mapped.model) throw new Error('任务模型不可用,请重新选择');+ const row = { ...mapped, model: mapped.model, ...(input.source ? { source: input.source } : {}) };+ input.onPersistenceStarted?.();+ let value: T;+ if (commit) value = await commit(row, assertCurrent);+ else { await db.insert(sessions).values(row).run(); value = undefined as T; }+ assertCurrent();+ return { row, value };+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.tsindex 5f27ff3e23..6e92e9b0ec 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/appDefaultModelControl.test.ts@@ -1,7 +1,7 @@import type { BotModelRoute } from '../../../shared/botModelChain';import type { ProviderView } from '@cindy/model-providers';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { changeAppDefaultModel, configureAppDefaultModelSelection, inspectAppDefaultModel, validateBotTaskModel, resolveBotTaskModelSelection } from '../appDefaultModelControl';+import { changeAppDefaultModel, configureAppDefaultModelSelection, inspectAppDefaultModel, validateTaskModel, resolveTaskModelSelection } from '../appDefaultModelControl';import { setNewMakerDraftCache, syncNewMakerDraftCache } from '../../maker-host/newMakerDefaultsCache';const host = vi.hoisted(() => ({ owner: 'owner:1', enabled: true, connected: true, agents: ['codex'],@@ -47,18 +47,18 @@ describe('Bot control of the real Cindy default', () => {expect(dispatch).not.toHaveBeenCalled();});it('validates the complete task route including harness, account and tuning without changing defaults', async () => {- expect(await validateBotTaskModel(route)).toBe(true);+ expect(await validateTaskModel(route)).toBe(true);for (const patch of [{ harness: 'pi' as const }, { providerId: 'another-account' }, { effort: 'ultra' }]) {- expect(await validateBotTaskModel({ ...route, ...patch })).toBe(false);+ expect(await validateTaskModel({ ...route, ...patch })).toBe(false);}host.connected = false;- expect(await validateBotTaskModel(route)).toBe(false);+ expect(await validateTaskModel(route)).toBe(false);expect((await inspectAppDefaultModel()).current).toEqual(route);});it('resolves a one-task selection without changing application preferences', async () => {const dispatch = vi.fn(); configureAppDefaultModelSelection(dispatch);- expect(await resolveBotTaskModelSelection({ id, effort: 'low', fastMode: true })).toEqual({ ...route, effort: 'low', fastMode: true });- expect(await resolveBotTaskModelSelection({ id })).toEqual(route);+ expect(await resolveTaskModelSelection({ id, effort: 'low', fastMode: true })).toEqual({ ...route, effort: 'low', fastMode: true });+ expect(await resolveTaskModelSelection({ id })).toEqual(route);expect((await inspectAppDefaultModel()).current).toEqual(route);expect(dispatch).not.toHaveBeenCalled();});@@ -73,7 +73,7 @@ describe('Bot control of the real Cindy default', () => {const providers = await host.providers(); providers[0].models.codex[0].supportsFastMode = false;host.providers.mockResolvedValue(providers); selection.fastMode = true;}- await expect(resolveBotTaskModelSelection(selection)).rejects.toThrow();+ await expect(resolveTaskModelSelection(selection)).rejects.toThrow();});it('waits for the real owner-fenced mirror instead of mutating the cache itself', async () => {const dispatch = vi.fn(selection => mirror(selection.route, selection.requestId));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.tsindex 6d70a710a0..30a8cb58b4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/ghostErrandRunner.test.ts@@ -7,11 +7,11 @@import { describe, it, expect, vi } from 'vitest';import {- clampErrandPermissionMode,createGhostErrandRunner,type GhostErrandRunnerDeps,type GhostErrandSessionRow,} from '../ghostErrandRunner';+import { clampPluginTaskPermissionMode } from '../../cindy-brain/pluginTaskPrefsStore';import type { AgentEvent } from '@cindy/maker-core';/** 最小可观察会话替身:测试手动放事件。 */@@ -82,7 +82,12 @@ function makeDeps(overrides: Partial<GhostErrandRunnerDeps> = {}): {getSessionRow: async () => ACTIVE_ROW,createSession: vi.fn(async () => 'sess-new'),getGhostName: () => '帮手',- getDraftDefaults: () => ({}),+ resolveExecution: async (cfg, _caller, row) => ({+ agentKind: cfg.agentKind === 'cc' ? 'claude-code' : cfg.agentKind ?? (row?.agentKind === 'codex' ? 'codex' : row?.agentKind === 'pi' ? 'pi' : 'claude-code'),+ model: cfg.model ?? row?.model ?? 'claude-x', providerId: cfg.providerId ?? row?.providerId,+ effort: cfg.effort ?? undefined, fastMode: cfg.fastMode ?? row?.fastMode ?? false,+ }),+ captureOwner: () => () => {},normalizeWorkingDir: (dir) => dir.replace(/\/+$/, ''),isUserPickedDir: () => false,isSessionBusy: () => false,@@ -105,23 +110,25 @@ const REQUEST = {};describe('权限档钳制', () => {- it('白名单外/缺省一律收敛到 plan;bypassPermissions 不存在', () => {- expect(clampErrandPermissionMode(undefined)).toBe('plan');- expect(clampErrandPermissionMode('bypassPermissions')).toBe('plan');- expect(clampErrandPermissionMode('ask')).toBe('plan');- expect(clampErrandPermissionMode('acceptEdits')).toBe('acceptEdits');- expect(clampErrandPermissionMode('auto')).toBe('auto');+ it('普通任务使用 ask;旧适配器可保留 plan;完全访问不能进入配置', () => {+ expect(clampPluginTaskPermissionMode(undefined)).toBe('ask');+ expect(clampPluginTaskPermissionMode(undefined, 'plan')).toBe('plan');+ expect(clampPluginTaskPermissionMode('bypassPermissions')).toBe('ask');+ expect(clampPluginTaskPermissionMode('bypassPermissions', 'plan')).toBe('plan');+ expect(clampPluginTaskPermissionMode('ask')).toBe('ask');+ expect(clampPluginTaskPermissionMode('acceptEdits')).toBe('acceptEdits');+ expect(clampPluginTaskPermissionMode('auto')).toBe('auto');});});describe('Pi 代办路由', () => {- it('读取 Pi 草稿默认并创建 Pi 会话', async () => {+ it('使用通用任务配置创建 Pi 会话', async () => {const createSession = vi.fn(async () => 'sess-pi');- const getDraftDefaults = vi.fn(() => ({ model: 'gpt-5.5' }));+ const resolveExecution = vi.fn(async () => ({ agentKind: 'pi' as const, model: 'gpt-5.5', fastMode: false }));const { deps, emitters } = makeDeps({readConfig: () => ({ agentKind: 'pi' }),createSession,- getDraftDefaults,+ resolveExecution,});const runner = createGhostErrandRunner(deps);const pending = runner(REQUEST);@@ -129,7 +136,7 @@ describe('Pi 代办路由', () => {emitters.get('sess-pi')!.emit(doneEvent());await pending;- expect(getDraftDefaults).toHaveBeenCalledWith('pi');+ expect(resolveExecution).toHaveBeenCalledWith({ agentKind: 'pi' }, undefined, undefined);expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ agentKind: 'pi', model: 'gpt-5.5' }),);@@ -187,7 +194,7 @@ describe('专属会话建/复用', () => {const e = emitters.get('sess-new')!;e.emit(doneEvent());await p;- expect(writes[0]).toEqual(['helper', null]);+ expect(writes).not.toContainEqual(['helper', null]);expect(writes).toContainEqual(['helper', 'sess-new']);});@@ -437,3 +444,53 @@ describe('收口与取文', () => {expect(await p).toMatchObject({ ok: false, errorCode: 'TIMEOUT' });});});++ describe('model admission and recovery before legacy execution', () => {+ it('retains a failed task mapping and never dispatches an unavailable route', async () => {+ const { deps, writes } = makeDeps({ readSessionId: () => 'old',+ resolveExecution: async () => { throw Error('供应商未连接,请重新选择'); } });+ expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({ ok: false, errorCode: 'SESSION_UNAVAILABLE' });+ expect(deps.createSession).not.toHaveBeenCalled();+ expect(deps.dispatch).not.toHaveBeenCalled();+ expect(writes).toEqual([]);+ });+ it('retains the old history mapping when replacement creation fails', async () => {+ const { deps, writes } = makeDeps({ readSessionId: () => 'old',+ readConfig: () => ({ model: 'new-model' }), createSession: vi.fn(async () => { throw Error('create failed'); }) });+ expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({ ok: false });+ expect(writes).toEqual([]);+ expect(deps.dispatch).not.toHaveBeenCalled();+ });+ it('keeps user-repaired Codex tasks and their history when app defaults change', async () => {+ const repaired = { ...ACTIVE_ROW, agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' };+ const { deps, emitters, writes } = makeDeps({ readSessionId: () => 'repaired', getSessionRow: async () => repaired });+ const result = createGhostErrandRunner(deps)({ ...REQUEST, sourceSessionId: 'caller' });+ await vi.waitFor(() => expect(emitters.has('repaired')).toBe(true));+ emitters.get('repaired')!.emit(doneEvent());+ expect(await result).toMatchObject({ ok: true, sessionId: 'repaired', model: 'gpt-6-astra' });+ expect(deps.createSession).not.toHaveBeenCalled();+ expect(writes).toEqual([]);+ });+ it('does not send after the user changes a validated task route', async () => {+ let reads = 0;+ const { deps } = makeDeps({ readSessionId: () => 'old', getSessionRow: async () =>+ ++reads === 1 ? ACTIVE_ROW : { ...ACTIVE_ROW, model: 'changed-model' } });+ expect(await createGhostErrandRunner(deps)(REQUEST)).toMatchObject({ ok: false, errorCode: 'SESSION_UNAVAILABLE' });+ expect(deps.dispatch).not.toHaveBeenCalled();+ });+ });++it('does not dispatch when plugin permission changes during model admission', async () => {+ let permissionMode: 'auto' | 'plan' = 'auto';+ const { deps } = makeDeps({+ readConfig: () => ({ permissionMode }),+ resolveExecution: async () => {+ permissionMode = 'plan';+ return { agentKind: 'claude-code', model: 'claude-x', fastMode: false };+ },+ });+ const result = await createGhostErrandRunner(deps)(REQUEST);+ expect(result).toMatchObject({ ok: false, errorCode: 'SESSION_UNAVAILABLE' });+ expect(deps.createSession).not.toHaveBeenCalled();+ expect(deps.dispatch).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.tsindex b2d53fef96..13fe62efe5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts@@ -1157,7 +1157,7 @@ describe('retained tasks after explicit plugin uninstall', () => {maker:{getSession:()=>null},inputCoordinator:{getAcceptedInputProvenance:()=>active},createPluginTaskStore:()=>({get:async(id:string)=>id==='run'?{operation:'send',targetId:'lead',pluginId:'plugin',payload:'{"inputMessageId":"plugin-task:run"}'}:{operation:'create',pluginId:'plugin',payload:JSON.stringify({ownershipRevoked:state==='revoked'})}}),pluginTaskServiceForCurrentOwner:()=>({get:async()=>({status:'active',permissionMode:state==='ask'?'default':'auto',planModeEnabled:state==='plan'})}),- isPluginTaskAuthorized:()=>state!=='disabled',readGhostErrandConfig:()=>({permissionMode:'auto'})};+ isPluginTaskAuthorized:()=>state!=='disabled',readPluginTaskConfig:()=>({permissionMode:'auto'})};const override=new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),js)(hasAcceptedUserTaskInput, ...Object.values(bindings));const ordinary=state==='revoked'&&['human','idle'].includes(input);if(state==='healthy'||ordinary)await expect(override('lead')).resolves.toMatchObject({permissionMode:ordinary?undefined:'auto'});@@ -1170,7 +1170,7 @@ describe('retained tasks after explicit plugin uninstall', () => {maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },createPluginTaskStore: () => ({ get: async () => ({ operation: 'create', pluginId: 'plugin', payload: '{}' }) }),pluginTaskServiceForCurrentOwner: () => ({ get: async () => ({ status, permissionMode: 'auto', planModeEnabled }) }),- isPluginTaskAuthorized: () => true, readGhostErrandConfig: () => ({ permissionMode: 'auto' }),+ isPluginTaskAuthorized: () => true, readPluginTaskConfig: () => ({ permissionMode: 'auto' }),};const override = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbacks), js)(hasAcceptedUserTaskInput, ...Object.values(callbacks));const { deps, service } = createDeps({ getWorkerPermissionModeOverride: override,@@ -1193,7 +1193,7 @@ describe('retained tasks after explicit plugin uninstall', () => {maker: {getSession:()=>null}, inputCoordinator: { getAcceptedInputProvenance: () => null },createPluginTaskStore: () => ({ get: async () => ({ operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: true }) }) }),pluginTaskServiceForCurrentOwner: () => ({ get }), isPluginTaskAuthorized: () => false,- readGhostErrandConfig: () => ({ permissionMode: 'auto' }),+ readPluginTaskConfig: () => ({ permissionMode: 'auto' }),};const override = new Function('hasAcceptedUserTaskInput', ...Object.keys(callbacks), js)(hasAcceptedUserTaskInput, ...Object.values(callbacks));const { deps, service } = createDeps({diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.tsindex 1f3ab4f788..62ad01d1ea 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts@@ -404,7 +404,7 @@ describe('OrcaTeamService', () => {? {operation:'send',targetId:'lead-1',pluginId:'plugin',payload:'{"inputMessageId":"plugin-task:run"}'}: {operation:'create',pluginId:'plugin',payload:JSON.stringify({ownershipRevoked:revoked})}}),pluginTaskServiceForCurrentOwner:()=>({get:async()=>({status:'active',permissionMode:'auto'})}),- isPluginTaskAuthorized:()=>!revoked,readGhostErrandConfig:()=>({permissionMode:'auto'})};+ isPluginTaskAuthorized:()=>!revoked,readPluginTaskConfig:()=>({permissionMode:'auto'})};const capture = new Function('hasAcceptedUserTaskInput', ...Object.keys(bindings),ts.transpileModule(`${helper}\nreturn captureOrcaPluginAuthority;`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(hasAcceptedUserTaskInput, ...Object.values(bindings));const {deps,service,getWorker}=createDeps({captureControlAuthority:async id=>(await capture(id)).assertCurrent});const list=deps.listWorkersByLead;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.tsindex f944c739e0..522a2f14e4 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts@@ -81,7 +81,7 @@ describe('Host provenance across Orca creation waits', () => {if (!receipt || receipt.pluginId !== pluginId || JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Revoked');return { ...task };} }),- isPluginTaskAuthorized: () => enabled, readGhostErrandConfig: () => ({ permissionMode: 'auto', workingDir: directoryCase ? configured : task.workingDir }),+ isPluginTaskAuthorized: () => enabled, readPluginTaskConfig: () => ({ permissionMode: 'auto', workingDir: directoryCase ? configured : task.workingDir }),resolvePluginWorkerDirectory: async () => {directoryResolved = true; directoryReads = 0;if (directoryCase && !configured && !picked) throw new PluginTaskError('PERMISSION_DENIED', 'Directory revoked');@@ -2982,7 +2982,7 @@ describe('production plugin Auto admission after reservation', () => {if (JSON.parse(receipt.payload).ownershipRevoked) throw new PluginTaskError('TASK_NOT_FOUND', 'Not owned');return { ...task };} }),- readGhostErrandConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }),+ readPluginTaskConfig: () => ({ permissionMode: 'auto', workingDir: task.workingDir }),isPluginTaskAuthorized: () => enabled,resolvePluginWorkerDirectory: async () => task.workingDir,isGhostPickedDir: () => false, PluginTaskError,@@ -3046,7 +3046,7 @@ describe('production plugin Auto admission after reservation', () => {const callbackDeps = { getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginWorkerDirectoryScope,createPluginTaskStore: () => ({ get: async () => ({ operation: 'create', pluginId: 'plugin', payload: state === 'malformed' ? '{' : JSON.stringify({ ownershipRevoked: true, teamPlan: { items: [] } }) }) }),pluginTaskServiceForCurrentOwner: () => ({ get }), isPluginTaskAuthorized: () => state === 'reinstalled',- readGhostErrandConfig: () => ({ permissionMode: 'auto' }),+ readPluginTaskConfig: () => ({ permissionMode: 'auto' }),};const validateCreationPlan = new Function(...Object.keys(callbackDeps), js)(...Object.values(callbackDeps));const { deps, service } = createDeps({ validateCreationPlan });@@ -3101,7 +3101,7 @@ describe('production plugin Auto admission after reservation', () => {}return task();} }),- readGhostErrandConfig: () => ({ permissionMode: mode, workingDir: path.resolve('repo') }),+ readPluginTaskConfig: () => ({ permissionMode: mode, workingDir: path.resolve('repo') }),isPluginTaskAuthorized: () => enabled,resolvePluginWorkerDirectory: async ({requested}: {requested: string}) => { if (reserved && point === 'directory') revoke(); return requested === path.resolve('other') ? requested : path.resolve('repo'); },realpathWorkingDirectory: async (dir: string) => dir === path.resolve('other') ? dir : path.resolve('repo'),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.tsindex b8a58cac59..7d4ea15912 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginPlanHistory.test.ts@@ -31,7 +31,7 @@ it('holds the real send lock from directory validation through plan persistence'const epoch={};const task={workingDir:'/root',revision:1};let release!:()=>void;const saving=new Promise<void>(resolve=>{release=resolve;});const save=vi.fn(async()=>{expect(hasSendToSessionLock('plan-history')).toBe(true);await saving;return {ok:true};});- const deps={withSendToSessionLock,getCurrentDbClientSnapshot:()=>epoch,service:{get:async()=>task,setTeamPlan:save},readGhostErrandConfig:()=>({workingDir:'/root'}),isPluginTaskAuthorized:()=>true,isGhostPickedDir:()=>false,PluginTaskError,resolvePluginWorkerDirectory:async()=>{expect(hasSendToSessionLock('plan-history')).toBe(true);}};+ const deps={withSendToSessionLock,getCurrentDbClientSnapshot:()=>epoch,service:{get:async()=>task,setTeamPlan:save},readPluginTaskConfig:()=>({workingDir:'/root'}),isPluginTaskAuthorized:()=>true,isGhostPickedDir:()=>false,PluginTaskError,resolvePluginWorkerDirectory:async()=>{expect(hasSendToSessionLock('plan-history')).toBe(true);}};const run=new Function(...Object.keys(deps),compile(`return async function(pluginId,request){switch(request.kind){${branch}}}`))(...Object.values(deps));const pending=run('plugin',{kind:'setTeamPlan',taskId:'plan-history',plan:{items:[{workingDir:'/root'}]}});try {await vi.waitFor(()=>expect(save).toHaveBeenCalledOnce());expect(hasSendToSessionLock('plan-history')).toBe(true);}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.tsindex 5ee1bbd2aa..deeda2f415 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginReviewSnapshotFreshness.test.ts@@ -79,7 +79,7 @@ function fixture() {getCurrentDbClientSnapshot:()=>control.accountChanged ? null : epoch,sessions,orcaWorkers,orcaTeams,eq,createPluginTaskStore:()=>({get:async()=>db.prepare('SELECT id,target_id AS targetId,plugin_id AS pluginId,operation,payload,revision FROM plugin_task_requests').get()}),drainPersistQueue:async()=>mutate('drain'),pluginTaskServiceForCurrentOwner:()=>({get:async()=>{mutate('ownership');if(!control.ownershipValid)throw Error('ownership revoked');}}),- readGhostErrandConfig:()=>({permissionMode:control.permissionMode}),readPluginTaskPlanReceipt,+ readPluginTaskConfig:()=>({permissionMode:control.permissionMode}),readPluginTaskPlanReceipt,pluginTaskAuthorizationRevision:()=>control.approvalRevision,isPluginTaskAuthorized:()=>control.authorized,};new Function(...Object.keys(deps),js)(...Object.values(deps));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.tsindex f4e9a86b27..e9021ea420 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginStartTeamAdmission.test.ts@@ -24,7 +24,7 @@ function fixture(initial = 'active', afterConfirmation = initial) {return create();});const deps = { service, getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginTaskResult, startOrcaTeamForCaller: start,- isPluginTaskAuthorized: () => true, readGhostErrandConfig: () => ({ permissionMode: 'auto' }) };+ isPluginTaskAuthorized: () => true, readPluginTaskConfig: () => ({ permissionMode: 'auto' }) };const run = new Function(...Object.keys(deps), js)(...Object.values(deps));return { run: () => run('plugin', { kind: 'startTeam', taskId: 'task' }), start, create };}@@ -84,7 +84,7 @@ describe('public start_team Full access admission', () => {createPluginTaskStore: () => ({ get: async () => state === 'ordinary' ? null: { operation: 'create', pluginId: 'plugin', payload: JSON.stringify({ ownershipRevoked: revoked }) } }),pluginTaskServiceForCurrentOwner: () => ({ get: async () => task }),- isPluginTaskAuthorized: () => state !== 'disabled', readGhostErrandConfig: () => ({ permissionMode: 'auto' }),+ isPluginTaskAuthorized: () => state !== 'disabled', readPluginTaskConfig: () => ({ permissionMode: 'auto' }),assertLeadCollabProjectEnabled: async () => {}, getWorkerPermissionModeFromCreationPrefs: () => preference,orcaWorkerPermissionConfirmBridge: { request }, t: (key: string) => key, orcaLifecycleService: lifecycle,};@@ -163,7 +163,7 @@ describe('plugin team activation uses the native lifecycle compensation', () =>sendWorkerReadyPlaceholder: vi.fn(), rollbackCreatedWorker: vi.fn(), broadcastSessionCreated: vi.fn(), broadcastOrcaWorkerChanged: vi.fn(),};const callbacks = { service, getCurrentDbClientSnapshot: () => epoch, PluginTaskError, assertPluginTaskResult,- isPluginTaskAuthorized: () => authorized, readGhostErrandConfig: () => ({ ...cfg }),+ isPluginTaskAuthorized: () => authorized, readPluginTaskConfig: () => ({ ...cfg }),assertLeadCollabProjectEnabled: async () => {}, getWorkerPermissionModeFromCreationPrefs: () => 'auto',startOrcaTeamWithPermissionGate, orcaWorkerPermissionConfirmBridge: { request: vi.fn() }, t: (key: string) => key,orcaLifecycleService: createOrcaLifecycleService(deps) };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.tsindex 69e95ed81c..ed31217e0f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskCreateDirectory.test.ts@@ -8,7 +8,7 @@ import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';import { PluginTaskError } from '../pluginTaskService.js';const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');-const start = source.indexOf(' createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted) => {');+const start = source.indexOf(' createSession: async (pluginId, taskId, title, route,');const branch = source.slice(start, source.indexOf(' readSession:', start)).trim().replace(/,$/, '');const js = ts.transpileModule(`return ({ ${branch} }).createSession;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;const roots: string[] = [];@@ -36,10 +36,10 @@ function fixture(workingDir?: string, afterResolve?: () => void) {snapshot, PluginTaskError,resolveRoute: async () => ({}),assertPlugin: () => { if (owner !== snapshot || !authorized) throw new PluginTaskError('PERMISSION_DENIED', 'Owner changed'); },- readGhostErrandConfig: () => ({ ...cfg }),+ readPluginTaskConfig: () => ({ ...cfg }),resolvePluginWorkerDirectory: resolve,- createGhostErrandSession: create,- clampErrandPermissionMode: (mode: string) => mode,+ createPluginTaskSession: create,+ clampPluginTaskPermissionMode: (mode: string) => mode,getCurrentDbClientSnapshot: () => owner,isPluginTaskAuthorized: () => authorized,notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex 030893261c..5b581aada8 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -39,7 +39,7 @@ it.each([false,true])('production Auto context checks uninstall after its projecconst deps={setAutoReviewContextResolver:(callback:typeof load)=>{load=callback;},createPluginTaskReviewResolver:(callback:typeof load)=>callback,getCurrentDbClientSnapshot:()=>epoch,sessions:{},orcaWorkers:{},orcaTeams:{},eq:()=>true,createPluginTaskStore:()=>f.deps.store,drainPersistQueue:async()=>{},- pluginTaskServiceForCurrentOwner:()=>f.service,readGhostErrandConfig:()=>({permissionMode:'auto'}),+ pluginTaskServiceForCurrentOwner:()=>f.service,readPluginTaskConfig:()=>({permissionMode:'auto'}),readPluginTaskPlanReceipt,pluginTaskAuthorizationRevision:()=> 'new-install',isPluginTaskAuthorized:()=>true};const source=readFileSync(new URL('../register.ts',import.meta.url),'utf8');const start=source.indexOf(' setAutoReviewContextResolver(createPluginTaskReviewResolver(async sessionId => {');@@ -333,13 +333,24 @@ describe('plugin ordinary task receipts', () => {const f = fixture();const input = { requestKey: 'isolated', title: 'Test', isolatedWorkspace: true };const task = await f.service.create('p', input);- expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, true, undefined, expect.any(Function));+ expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, true, undefined, expect.any(Function), undefined);await f.service.create('p', input);expect(f.deps.createSession).toHaveBeenCalledTimes(1);await expect(f.service.create('p', { ...input, isolatedWorkspace: false })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });});+ it('binds the originating call to creation without re-resolving it on receipt replay', async () => {+ const f = fixture();+ const input = { requestKey: 'call-source', title: 'Test', callId: 'active-call' };+ const task = await f.service.create('p', input);+ expect(f.deps.resolveRoute).toHaveBeenCalledWith('p', undefined, 'active-call');+ expect(f.deps.createSession).toHaveBeenCalledWith('p', task.taskId, 'Test', f.route, undefined, undefined, expect.any(Function), 'active-call');+ vi.mocked(f.deps.resolveRoute).mockRejectedValue(new Error('call ended'));+ expect((await f.service.create('p', input)).taskId).toBe(task.taskId);+ await expect(f.service.create('p', { ...input, callId: 'other-call' })).rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });+ });+it('creates once under concurrent retries and rejects conflicting keys', async () => {const f = fixture();const [a, b] = await Promise.all([f.create(), f.create()]);@@ -754,8 +765,8 @@ describe('current plugin dispatch authority', () => {await expect(f.service.get('p',run.taskId)).resolves.toMatchObject({planModeEnabled:true});await expect(f.service.cancel('p',run.runId)).resolves.toMatchObject({status:'cancelled'});});- it.each(['plan', 'acceptEdits', 'auto'])('allows only authority within %s configuration', configured => {- const modes = ['plan', 'acceptEdits', 'auto'];+ it.each(['plan', 'ask', 'acceptEdits', 'auto'])('allows only authority within %s configuration', configured => {+ const modes = ['plan', 'ask', 'acceptEdits', 'auto'];for (const mode of [...modes, 'bypassPermissions', 'unknown', undefined]) {expect(isPluginTaskPermissionAllowed(mode, configured)).toBe(modes.includes(mode!) && modes.indexOf(mode!) <= modes.indexOf(configured));}@@ -878,6 +889,35 @@ describe('current plugin dispatch authority', () => {});});+it('changes only the owned task model through the ordinary runtime adapter', async () => {+ const f = fixture();+ const task = await f.create();+ const route = task.resolvedConfig;+ const next = { ...route, model: 'next-model' };+ f.deps.setModel = vi.fn<NonNullable<PluginTaskServiceDeps['setModel']>>(async (id, selected, assertCurrent) => {+ await assertCurrent();+ const stored = f.tasks.get(id)!;+ f.tasks.set(id, { ...stored, revision: stored.revision + 1, resolvedConfig: selected });+ return { status: 'applied' };+ });+ const changed = await f.service.setModel('p', { taskId: task.taskId, expectedRevision: task.revision, route: next });+ expect(changed.task).toMatchObject({ taskId: task.taskId, permissionMode: task.permissionMode, resolvedConfig: next });+ expect(f.tasks.size).toBe(1);+ await expect(f.service.setModel('other', { taskId: task.taskId, expectedRevision: 2, route: next })).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });+ await expect(f.service.setModel('p', { taskId: task.taskId, expectedRevision: 1, route: next })).rejects.toMatchObject({ code: 'STALE_REVISION' });+ expect(f.deps.setModel).toHaveBeenCalledOnce();+});++it('does not apply a model after the task changes while route admission is pending', async () => {+ const f = fixture();+ const task = await f.create();+ const route = task.resolvedConfig;+ f.deps.resolveRoute = async () => { f.tasks.get(task.taskId)!.revision++; return route; };+ f.deps.setModel = vi.fn();+ await expect(f.service.setModel('p', { taskId: task.taskId, expectedRevision: task.revision, route })).rejects.toMatchObject({ code: 'STALE_REVISION' });+ expect(f.deps.setModel).not.toHaveBeenCalled();+});+it('keeps taskless plans immutable instead of retroactively granting scope', async () => {const f=fixture(),task=await f.create();const old={concurrency:2,items:[{label:'sample',workingDir:'/answer',route:f.route}]};diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.tsindex a92fd69491..f3b6e38ea0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts@@ -9,6 +9,8 @@ import { PluginTaskError, readPluginTaskPlanReceipt } from '../pluginTaskServiceimport type { PluginTaskRoute } from '../../../shared/pluginTasks.js';import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';+import { createSessionExecutionResolver } from '../sessionExecutionSelection';+const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');function compile(text: string, deps: Record<string, unknown>) {return new Function(...Object.keys(deps), ts.transpileModule(text, {@@ -20,12 +22,32 @@ function handler(kind: string, next: string, deps: Record<string, unknown>) {return compile(`return async function(pluginId,request){switch(request.kind){${branch}}}`, deps);}+it.each([+ {pending:'claude-code', target:'codex', harness:'codex'},+ {pending:undefined, target:'cc', harness:'claude-code'},+ {pending:undefined, target:'codex', harness:undefined},+])('routes an explicit model choice through the correct runtime controller: %j', async ({pending,target,harness}) => {+ const start = source.indexOf(' setModel: async (taskId, route, assertUnchanged) =>');+ const property = source.slice(start, source.indexOf(' assertTeamPlanUnstarted:',start)).trim().replace(/,$/, '');+ const set = vi.fn(async () => ({ok:true,status:'applied'}));+ const apply = compile(`return ({${property}}).setModel;`, {PluginTaskError,sessionControlService:{+ getSessionRuntime:async()=>({ok:true,runtime:{runtimeGeneration:7,effectiveProfile:{agentKind:'codex'},pendingMutation:pending ? {profile:{agentKind:pending}} : null}}),+ setSessionRuntime:set,+ }});+ const assertCurrent=vi.fn();+ await apply('task',{agentKind:target,providerId:'chosen',model:'chosen-model',effort:'medium',fastMode:false},assertCurrent);+ expect(assertCurrent).toHaveBeenCalledOnce();+ expect(set).toHaveBeenCalledWith({targetSessionId:'task',expectedGeneration:7,patch:{+ ...(harness ? {harness} : {}),providerId:'chosen',model:'chosen-model',effort:'medium',fastMode:false,+ }});+});+it.each(['auto', 'acceptEdits'])('exposes independent Plan Mode alongside stored %s permission', async permissionMode => {const start = source.indexOf(' readSession: async taskId =>');const property = source.slice(start, source.indexOf(' dispatch:', start)).trim().replace(/,$/, '');const row = {id:'task',source:'plugin',agentKind:'codex',status:'active',permissionMode,planModeEnabled:true};const query = {from:()=>query,where:()=>query,limit:async()=>[row]};- const read = compile(`return ({${property}}).readSession;`, {assertCurrent:()=>{},snapshot:{client:{drizzle:{select:()=>query}}},sessions:{},eq:()=>true,pluginTaskConfigHash:createHash});+ const read = compile(`return ({${property}}).readSession;`, {assertCurrent:()=>{},snapshot:{client:{drizzle:{select:()=>query}}},sessions:{},eq:()=>true,pluginTaskConfigHash:createHash,readSessionRuntimeProfiles:async()=>null});const plan = await read('task');expect(plan).toMatchObject({permissionMode,planModeEnabled:true});row.planModeEnabled=false;@@ -34,6 +56,27 @@ it.each(['auto', 'acceptEdits'])('exposes independent Plan Mode alongside storedexpect(normal.revision).not.toBe(plan.revision);});+it.each(['codex', 'claude-code'] as const)('keeps the accepted next-input route stable when a deferred %s switch settles', async agentKind => {+ const start = source.indexOf(' readSession: async taskId =>');+ const property = source.slice(start, source.indexOf(' dispatch:', start)).trim().replace(/,$/, '');+ const old = {agentKind:'codex',providerId:'old-provider',model:'old',effort:'medium',fastMode:false};+ const next = {agentKind,providerId:'selected-provider',model:'selected',effort:'high',fastMode:false};+ const row = {id:'task',source:'plugin',status:'active',permissionMode:'ask',planModeEnabled:false,...old};+ let pending = true;+ const query = {from:()=>query,where:()=>query,limit:async()=>[row]};+ const read = compile(`return ({${property}}).readSession;`, {+ assertCurrent:()=>{}, snapshot:{client:{drizzle:{select:()=>query}}}, sessions:{},eq:()=>true,pluginTaskConfigHash:createHash,+ readSessionRuntimeProfiles:async()=>({effective:pending ? old : next,pendingMutation:pending ? {profile:next} : null}),+ });+ const accepted = await read('task');+ expect(accepted.resolvedConfig).toEqual({...next,agentKind:agentKind==='claude-code'?'cc':agentKind});+ pending=false;+ Object.assign(row,next,{agentKind:agentKind==='claude-code'?'cc':agentKind});+ const applied = await read('task');+ expect(applied.resolvedConfig).toEqual(accepted.resolvedConfig);+ expect(applied.revision).toBe(accepted.revision);+});+it('freezes the directory returned by admission without mutating the caller plan', async () => {const epoch = {};const save = vi.fn();@@ -42,7 +85,7 @@ it('freezes the directory returned by admission without mutating the caller planPluginTaskError, withSendToSessionLock: async (_: string, fn: () => unknown) => fn(),getCurrentDbClientSnapshot: () => epoch,service: { get: async () => ({ revision: 1, workingDir: '/root' }), setTeamPlan: save },- readGhostErrandConfig: () => ({ workingDir: '/root' }), isPluginTaskAuthorized: () => true,+ readPluginTaskConfig: () => ({ workingDir: '/root' }), isPluginTaskAuthorized: () => true,isGhostPickedDir: () => false, resolvePluginWorkerDirectory: async () => '/root/original',});await run('plugin', { kind: 'setTeamPlan', taskId: 'task', plan });@@ -63,7 +106,7 @@ it('retargeting a real symlink cannot change the stored plan directory', async (PluginTaskError, withSendToSessionLock: async (_: string, fn: () => unknown) => fn(),getCurrentDbClientSnapshot: () => epoch,service: { get: async () => ({ revision: 1, workingDir: root }), setTeamPlan: save },- readGhostErrandConfig: () => ({ workingDir: root }), isPluginTaskAuthorized: () => true,+ readPluginTaskConfig: () => ({ workingDir: root }), isPluginTaskAuthorized: () => true,isGhostPickedDir: () => false, resolvePluginWorkerDirectory,});await run('plugin', { kind: 'setTeamPlan', taskId: 'task', plan });@@ -98,16 +141,21 @@ it.each(['provider', 'receipt', 'directory', 'creator'])('keeps default-route co});const api = compile(`${resolveSource}\nreturn {resolveRoute, create: ({${createSource}}).createSession};`, {PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),- readGhostErrandConfig: () => ({ ...cfg }), getWorkerDefaultsFromNewMaker: () => ({}),- getDesktopProviderService: () => ({ listProviders: async () => {- if (++lookups === 1 && phase === 'provider') change();- return ['one', 'two'].map(id => ({ id, connected: true }));- } }), getActiveCatalog: () => ({}),- findCatalogModel: () => ({ efforts: ['high', 'low'], supportsFastMode: true }),- isModelSelectableForNewRoute: () => true,+ readPluginTaskConfig: () => ({ ...cfg }), getPluginTaskSourceSessionId: () => undefined,+ resolveSessionExecution: createSessionExecutionResolver({+ captureOwner: () => () => {}, readCaller: async () => { throw Error('unexpected caller'); }, readDefault: () => undefined,+ availableAgents: () => ['claude-code', 'codex', 'pi'],+ availableModels: () => ['model', 'other'].map(id => ({ id, efforts: ['high', 'low'], supportsFastMode: true })),+ hasCindyAiApiKey: () => true,+ readProviderRouting: async () => {+ if (++lookups === 1 && phase === 'provider') change();+ const providers = ['one','two'].map(id => ({ id, name: id, models: ['model','other'] }));+ return { availability: { 'claude-code': providers, codex: providers, pi: providers }, resolveDefaultProviderIdForModel: () => 'one' };+ },+ }),routeUnavailable: () => { throw Error('unavailable'); },resolvePluginWorkerDirectory: async () => { if (phase === 'directory') change(); return '/root'; },- createGhostErrandSession: create, clampErrandPermissionMode: (value: string) => value,+ createPluginTaskSession: create, clampPluginTaskPermissionMode: (value: string) => value,getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => true,notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),});@@ -127,13 +175,13 @@ it('forwards the explicit route when revalidating creation', async () => {const create = vi.fn();const run = compile(`return ({${property}}).createSession;`, {PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),- readGhostErrandConfig: () => ({ model: 'different-default', permissionMode: 'plan' }),- resolveRoute, createGhostErrandSession: create, clampErrandPermissionMode: (x: string) => x,+ readPluginTaskConfig: () => ({ model: 'different-default', permissionMode: 'plan' }),+ resolveRoute, createPluginTaskSession: create, clampPluginTaskPermissionMode: (x: string) => x,getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => true,notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),});await run('plugin', 'task', 'title', route, true, route);- expect(resolveRoute).toHaveBeenCalledWith('plugin', route);+ expect(resolveRoute).toHaveBeenCalledWith('plugin', route, undefined);expect(create).toHaveBeenCalledOnce();});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.tsindex 25bad95be8..95c037cb89 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginWriteAccess.test.ts@@ -38,7 +38,7 @@ function fixture() {const slots = new Set<string>();const dialog = { showMessageBox: vi.fn(async () => ({ response: 0 })) };const write = vi.fn((_id: string, value: Record<string, unknown>) => { cfg = value; });- const deps = { isPluginTaskPermissionAllowed, withSessionPermissionChange, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => ownership.current, readGhostErrandConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => cold ? null : live }, inputCoordinator: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampErrandPermissionMode: (x: string) => x, writeGhostErrandConfig: write, broadcastSessionPatched: vi.fn() };+ const deps = { isPluginTaskPermissionAllowed, withSessionPermissionChange, withSessionRestartLock, drainPersistQueue:drain,messages,sessions,eq:()=>true,and:()=>true,service, getCurrentDbClientSnapshot: () => ownership.current, readPluginTaskConfig: () => cfg, pluginPermissionRequests: slots, PluginTaskError, maker: { getSession: () => cold ? null : live }, inputCoordinator: queue, dialog, t: (x: string) => x, getInstalledGhostName: () => 'fixture', clampPluginTaskPermissionMode: (x: string) => x, writePluginTaskConfig: write, broadcastSessionPatched: vi.fn() };const allDeps = {...deps, pluginWriteAccessGate:gate, pluginWriteAccessIdentity:()=>identity};const run = new Function(...Object.keys(allDeps), js)(...Object.values(allDeps));let setMode!: (event: unknown, sessionId: string, mode: string) => Promise<unknown>;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionExecutionSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionExecutionSelection.test.tsnew file mode 100644index 0000000000..5ccb53fc93--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionExecutionSelection.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it, vi } from 'vitest';+import { createSessionExecutionResolver, type SessionExecutionResolverDeps } from '../sessionExecutionSelection';++const caller = { agentKind: 'codex' as const, model: 'gpt-6-astra', providerId: 'openai', effort: 'high' as const, fastMode: false };+const panel = { agentKind: 'pi' as const, model: 'z-ai/glm-5.3-flash', providerId: 'xd', effort: 'medium' as const, fastMode: false };+const metadata = (id: string) => ({ id, efforts: ['medium', 'high'], defaultEffort: 'medium', supportsFastMode: false });+const routing = {+ availability: {+ codex: [{ id: 'openai', name: 'OpenAI', models: [caller.model] }],+ pi: [{ id: 'xd', name: 'Cindy AI', models: [panel.model] }],+ 'claude-code': [{ id: 'xd', name: 'Cindy AI', models: [panel.model] }, { id: 'glm', name: 'GLM', models: ['glm-5.3'] }],+ },+ resolveDefaultProviderIdForModel: (agent: string, model: string) =>+ routing.availability[agent as keyof typeof routing.availability]?.find(p => p.models.includes(model))?.id ?? null,+};+function setup(overrides: Partial<SessionExecutionResolverDeps> = {}) {+ const deps: SessionExecutionResolverDeps = {+ captureOwner: () => () => {}, readCaller: vi.fn(async () => caller), readDefault: vi.fn(() => panel),+ availableAgents: () => ['codex', 'claude-code', 'pi'],+ availableModels: agent => agent === 'codex' ? [metadata(caller.model)] : [metadata(panel.model), metadata('glm-5.3')],+ readProviderRouting: async () => routing, hasCindyAiApiKey: () => true, ...overrides,+ };+ return { deps, resolve: createSessionExecutionResolver(deps) };+}++describe('ordinary Session model selection', () => {+ it('inherits a complete caller route; no old CC draft or permission is read', async () => {+ const { deps, resolve } = setup();+ expect(await resolve({}, 'caller')).toEqual(caller);+ expect(deps.readDefault).not.toHaveBeenCalled();+ });+ it('panel creation follows the selected engine and provider as one tuple', async () => {+ const { deps, resolve } = setup();+ expect(await resolve({})).toEqual(panel);+ expect(deps.readCaller).not.toHaveBeenCalled();+ });+ it('an explicit plugin selection works independently of a missing caller', async () => {+ const { deps, resolve } = setup({ readCaller: vi.fn(async () => { throw Error('gone'); }) });+ expect(await resolve(caller, 'caller')).toEqual(caller);+ expect(deps.readCaller).not.toHaveBeenCalled();+ });+ it('preserves a user-repaired existing task across default-model changes', async () => {+ const { deps, resolve } = setup();+ expect(await resolve({}, undefined, caller)).toEqual(caller);+ expect(deps.readDefault).not.toHaveBeenCalled();+ });+ it('does not treat a valid GLM catalog model as invalid because SDK logs add a wire suffix', async () => {+ expect(await setup().resolve({ agentKind: 'cc', model: panel.model, providerId: 'xd' }))+ .toMatchObject({ agentKind: 'claude-code', model: panel.model, providerId: 'xd' });+ });+ it('rejects a withdrawn model on creation and reuse instead of substituting one', async () => {+ const { resolve } = setup();+ const invalid = { agentKind: 'cc' as const, model: 'withdrawn-model', providerId: 'xd' };+ await expect(resolve(invalid)).rejects.toThrow('not available');+ await expect(resolve({}, undefined, invalid)).rejects.toThrow('不会自动更换');+ });+ it('does not borrow credentials from an unrelated model/provider route', async () => {+ await expect(setup().resolve({ agentKind: 'cc', model: panel.model, providerId: 'glm' })).rejects.toThrow('不再为');+ });+ it('rejects disconnected saved routes and unavailable Agents', async () => {+ const disconnected = setup({ readProviderRouting: async () => ({ ...routing, availability: { ...routing.availability, codex: [] } }) });+ await expect(disconnected.resolve({}, 'caller')).rejects.toThrow('没有已连接');+ await expect(setup({ availableAgents: () => ['pi'] }).resolve({}, 'caller')).rejects.toThrow('Agent codex');+ });+ it('validates requested tuning with the selected provider', async () => {+ await expect(setup().resolve({ effort: 'ultra' }, 'caller')).rejects.toThrow('not supported');+ await expect(setup().resolve({ fastMode: true }, 'caller')).rejects.toThrow('fast mode is not supported');+ });+ it('preserves old partial overrides without mixing unrelated source credentials', async () => {+ expect(await setup().resolve({ agentKind: 'cc', model: 'glm-5.3' }))+ .toMatchObject({ providerId: 'glm', model: 'glm-5.3', effort: 'medium' });+ });+ it('supports models without a reasoning selector instead of inventing high', async () => {+ const { resolve } = setup({ availableModels: () => [{ id: 'glm-5.3', efforts: [] }] });+ expect(await resolve({ agentKind: 'cc', model: 'glm-5.3', providerId: 'glm' })).toMatchObject({ effort: undefined });+ });+ it('does not silently choose a hardcoded model when default selection is missing', async () => {+ await expect(setup({ readDefault: () => undefined }).resolve({})).rejects.toThrow('尚未选择');+ });+ it('rejects owner changes during provider lookup', async () => {+ let changed = false;+ const { resolve } = setup({ captureOwner: () => () => { if (changed) throw Error('owner changed'); },+ readProviderRouting: async () => { changed = true; return routing; } });+ await expect(resolve({})).rejects.toThrow('owner changed');+ });+});diff --git a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.tsindex 5f285251b8..a599e590d4 100644--- a/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts+++ b/apps/desktop/src/main/maker-ipc/appDefaultModelControl.ts@@ -73,14 +73,14 @@ export async function inspectAppDefaultModel() {return { current, available };}-export interface BotTaskModelSelection {+export interface TaskModelSelection {id: string;effort?: string;fastMode?: boolean;}/** Resolve one per-task selection from the live catalog; never mutate picker/default preferences. */-export async function resolveBotTaskModelSelection(selection: BotTaskModelSelection): Promise<BotModelRoute> {+export async function resolveTaskModelSelection(selection: TaskModelSelection): Promise<BotModelRoute> {const { available } = await inspectAppDefaultModel();const option = available.find(entry => entry.id === selection.id);if (!option) throw new Error('任务模型已不可用,请重新查询可用模型');@@ -97,7 +97,7 @@ export async function resolveBotTaskModelSelection(selection: BotTaskModelSelect}/** Check a saved full route without changing the application or teammate's primary model. */-export async function validateBotTaskModel(route: BotModelRoute): Promise<boolean> {+export async function validateTaskModel(route: BotModelRoute): Promise<boolean> {const { available } = await inspectAppDefaultModel();return available.some(entry => entry.route.harness === route.harness&& entry.route.model === route.model && entry.route.providerId === route.providerIddiff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex 2f9e2b77c4..ecfc30d066 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -1,3 +1,4 @@+import { openSession } from '../localDb/sessionOpening.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';import { existsSync, statSync } from 'node:fs';import type { AgentInputCoordinator } from './agent-input-coordinator.js';@@ -7,7 +8,6 @@ import { createHash, randomUUID } from 'node:crypto';import { app } from 'electron';import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';-import { ensureProjectGitInitialized } from '../git-snapshot/projectGitBootstrap.js';import { getDbClient } from '../localDb/client/current.js';import type { BotsFinishDelegationResult } from '../localDb/client/tx/types.js';import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';@@ -23,7 +23,6 @@ import {messages,sessions,} from '../localDb/schema.js';-import { readGitSafetySettings } from '../maker-host/git-safety-settings-store.js';import type { InteractionDecision, InteractionRequest } from '@cindy/maker-core';import { permissionModeOrAsk } from '@cindy/maker-shared/permission-mode';import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';@@ -52,7 +51,7 @@ import type { SessionQueuedMessageControlResult, SessionSteerResult, SessionStopimport { ownerScopedUserDataPath } from '../appSessionState.js';import type { SessionRuntimeProfile } from './sessionRuntimeControl.js';import { readBotTaskModelOverride, type BotModelRoute } from '../../shared/botModelChain.js';-import { validateBotTaskModel, resolveBotTaskModelSelection, type BotTaskModelSelection } from './appDefaultModelControl.js';+import { validateTaskModel, resolveTaskModelSelection, type TaskModelSelection } from './appDefaultModelControl.js';const ACTIVE_DELEGATION_STATUSES = ['queued', 'running', 'waiting'] as const;/** 一条补充消息的正文上限:够写清「先别做 X,改做 Y」,又不至于变成另一项任务。 */@@ -176,8 +175,8 @@ export interface BotDelegationServiceDeps {typeof sessions.$inferSelect,'model' | 'agentKind' | 'providerId' | 'fastMode'> & { effort?: (typeof sessions.$inferSelect)['effort'] }) | null;- validateTaskModel?: typeof validateBotTaskModel;- resolveTaskModelSelection?: typeof resolveBotTaskModelSelection;+ validateTaskModel?: typeof validateTaskModel;+ resolveTaskModelSelection?: typeof resolveTaskModelSelection;/** null means the live permission is changing or the caller is closing. */readCallerPermission?: (sessionId: string) => string | { mode: string; generation: number } | null;/** Narrow, owner-checked bridge to the ordinary Session runtime controller. */@@ -199,7 +198,7 @@ export interface BotDelegationServiceDeps {/** Start one tracked Cindy Session task from a persistent Bot task. */export interface SessionTaskInput {/** One task only; the catalog id includes source and Harness. */- modelSelection?: BotTaskModelSelection;+ modelSelection?: TaskModelSelection;callerSessionId: string;objective: string;contextRefs?: string[];@@ -2130,108 +2129,88 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {childSessionId = prepared.sessionId;input.session = { ...input.session, workingDir: prepared.workingDir, workspaceKind: 'project' };}- const gitSafety = readGitSafetySettings();- await ensureProjectGitInitialized({- workingDir: input.session.workingDir,- workspaceKind: input.session.workspaceKind ?? 'dialogue',- remoteHostId: null,- sessionId: childSessionId,- autoSnapshotEnabled: gitSafety.autoSnapshotEnabled,- autoInitProjectGit: gitSafety.autoInitProjectGit,- source: 'bot-delegation',- }).catch(async error => {- if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);- throw error;- });- // Read stable authority after asynchronous preparation, with no await before- // submitting creation. Both persisted records must use this same snapshot.- const callerPermission = deps.readCallerPermission- ? deps.readCallerPermission(input.callerSessionId)- : input.caller.permissionMode;- if (callerPermission === null) {- if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);- return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };- }- const permissionMode = permissionModeOrAsk(typeof callerPermission === 'string' ? callerPermission : callerPermission.mode);- const isCreationPermissionCurrent = (): boolean => {- if (!deps.readCallerPermission) return true;- const current = deps.readCallerPermission(input.callerSessionId);- if (current === null) return false;- if (typeof callerPermission === 'string') return current === callerPermission;- return typeof current !== 'string' && current.mode === callerPermission.mode- && current.generation === callerPermission.generation;- };- const plan: BotDelegationPlanSnapshot = {- ...input.plan,- permission: {- mode: permissionMode,- requesterMode: permissionMode,- // Legacy target-profile field; the effective child permission is mode.- targetConfigured: 'ask',- },- };- const createdAt = plan.createdAt;- const permissionSnapshotJson = JSON.stringify({ ...plan,- ...(input.taskModelOverride ? { taskModelOverride: input.taskModelOverride } : {}),- taskInput: { runSequence: 1, originalObjective: input.objective, followUp: null } satisfies SessionTaskInputSnapshot,- });- const childRow = {- ...sessionCreateToRow(- childSessionId,- {- workspaceKind: input.session.workspaceKind ?? 'dialogue',- workingDir: input.session.workingDir,- model: input.session.model,- // Persist the selected task route, including its source, Harness and tuning.- ...(input.session.effort !== undefined ? { effort: input.session.effort } : {}),- ...(input.session.fastMode !== undefined ? { fastMode: input.session.fastMode } : {}),- ...(input.session.providerId !== undefined- ? { providerId: input.session.providerId }- : {}),- agentKind: input.session.agentKind,- permissionMode,- parentSessionId: input.callerSessionId,- },- createdAt,- ),- title: input.session.title,- source: input.session.source,- };+ let creationCommitted = false;+ let permissionMode: ReturnType<typeof permissionModeOrAsk>;+ let isCreationPermissionCurrent!: () => boolean;+ let plan!: BotDelegationPlanSnapshot;+ let permissionSnapshotJson!: string;+ const createdAt = input.plan.createdAt;+ const { source: taskSource, ...sessionBody } = input.session;try {- await getDbClient().tx('bots.createDelegation', {- maxActiveChildren,- session: {- id: childRow.id,- title: childRow.title,- workingDir: childRow.workingDir ?? null,- workspaceKind: childRow.workspaceKind,- model: childRow.model,- effort: childRow.effort,- fastMode: childRow.fastMode,- permissionMode: childRow.permissionMode,- agentKind: childRow.agentKind,- remoteHostId: null,- providerId: childRow.providerId ?? null,- parentSessionId: input.callerSessionId,- extraDirs: childRow.extraDirs,- source: childRow.source,- createdAt: childRow.createdAt,- updatedAt: childRow.updatedAt,- },- delegation: {- id: delegationId,- requestingBotId: input.caller.botId,- targetBotId: null,- parentSessionId: input.callerSessionId,- childSessionId,- objective: input.objective,- contextRefsJson: JSON.stringify(input.contextRefs),- permissionSnapshotJson,- lineageJson: JSON.stringify([input.caller.botId]),- targetProfileVersion: null,- depth: 1,- createdAt,+ await openSession({ id: childSessionId, now: createdAt, source: taskSource,+ body: { ...sessionBody, workspaceKind: input.session.workspaceKind ?? 'dialogue' },+ finalize: () => {+ // Read stable authority after asynchronous preparation, with no await before+ // submitting creation. Both persisted records must use this same snapshot.+ const callerPermission = deps.readCallerPermission+ ? deps.readCallerPermission(input.callerSessionId)+ : input.caller.permissionMode;+ if (callerPermission === null) {+ throw new Error('CALLER_PERMISSION_UNAVAILABLE');+ }+ permissionMode = permissionModeOrAsk(typeof callerPermission === 'string' ? callerPermission : callerPermission.mode);+ isCreationPermissionCurrent = (): boolean => {+ if (!deps.readCallerPermission) return true;+ const current = deps.readCallerPermission(input.callerSessionId);+ if (current === null) return false;+ if (typeof callerPermission === 'string') return current === callerPermission;+ return typeof current !== 'string' && current.mode === callerPermission.mode+ && current.generation === callerPermission.generation;+ };+ plan = {+ ...input.plan,+ permission: {+ mode: permissionMode,+ requesterMode: permissionMode,+ // Legacy target-profile field; the effective child permission is mode.+ targetConfigured: 'ask',+ },+ };++ permissionSnapshotJson = JSON.stringify({ ...plan,+ ...(input.taskModelOverride ? { taskModelOverride: input.taskModelOverride } : {}),+ taskInput: { runSequence: 1, originalObjective: input.objective, followUp: null } satisfies SessionTaskInputSnapshot,+ });++ return { permissionMode, parentSessionId: input.callerSessionId };},+ }, async childRow => {+ await getDbClient().tx('bots.createDelegation', {+ maxActiveChildren,+ session: {+ id: childRow.id,+ title: childRow.title,+ workingDir: childRow.workingDir ?? null,+ workspaceKind: childRow.workspaceKind,+ model: childRow.model,+ effort: childRow.effort,+ fastMode: childRow.fastMode,+ permissionMode: childRow.permissionMode,+ agentKind: childRow.agentKind,+ remoteHostId: null,+ providerId: childRow.providerId ?? null,+ parentSessionId: input.callerSessionId,+ extraDirs: childRow.extraDirs,+ source: childRow.source,+ createdAt: childRow.createdAt,+ updatedAt: childRow.updatedAt,+ },+ delegation: {+ id: delegationId,+ requestingBotId: input.caller.botId,+ targetBotId: null,+ parentSessionId: input.callerSessionId,+ childSessionId,+ objective: input.objective,+ contextRefsJson: JSON.stringify(input.contextRefs),+ permissionSnapshotJson,+ lineageJson: JSON.stringify([input.caller.botId]),+ targetProfileVersion: null,+ depth: 1,+ createdAt,+ },+ });+ creationCommitted = true;});// The worktree store and workingDir already own the binding. A failed// display snapshot must not strand the committed task before dispatch.@@ -2252,7 +2231,10 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {status: 'queued',});} catch (error) {- if (input.useWorktree) await deps.discardUnusedWorktree?.(childSessionId);+ if (input.useWorktree && !creationCommitted) await deps.discardUnusedWorktree?.(childSessionId);+ if (error instanceof Error && error.message === 'CALLER_PERMISSION_UNAVAILABLE') {+ return { ok: false, errorCode: 'CALLER_PERMISSION_UNAVAILABLE', message: '伙伴权限正在切换或任务正在关闭,请稍后重试' };+ }// The Profile workspace is durable and shared across the Bot's Sessions.// A failed child creation never owns it and must not compensate by deleting it.if (error instanceof Error && error.message === 'BOT_DELEGATION_CONCURRENCY_LIMIT') {@@ -2366,9 +2348,9 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {let taskModel: BotModelRoute | null;try {taskModel = input.modelSelection !== undefined- ? await (deps.resolveTaskModelSelection ?? resolveBotTaskModelSelection)(input.modelSelection)+ ? await (deps.resolveTaskModelSelection ?? resolveTaskModelSelection)(input.modelSelection): readBotTaskModelOverride(parseRecord(profile?.config).taskModelOverride);- if (input.modelSelection === undefined && taskModel && !await (deps.validateTaskModel ?? validateBotTaskModel)(taskModel)) {+ if (input.modelSelection === undefined && taskModel && !await (deps.validateTaskModel ?? validateTaskModel)(taskModel)) {return { ok: false, errorCode: 'TASK_MODEL_UNAVAILABLE', message: '任务模型不可用,请在伙伴模型设置中重新选择后重试' };}} catch {diff --git a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.tsindex 0fd6f8e1c7..92654b85ff 100644--- a/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts+++ b/apps/desktop/src/main/maker-ipc/ghostErrandRunner.ts@@ -3,7 +3,7 @@** errandSlot(cindy-brain)只负责资格审/频控/任务表;真正的干活链在这里:*- * 解析用户配置(errandPrefsStore,缺省跟随 New Maker 草稿偏好)+ * 通过普通任务模型校验解析用户配置(pluginTaskPrefsStore)* → 确保专属 errand 会话(映射存 prefs;失效/配置关键项变更则重建;* 请求带 sessionKey 时按 ghostId+key 分间——同钥匙同间、异钥匙各间)* → 忙检(errand 会话正被占用即 BUSY,不排队——排队会让结果对不上单)@@ -12,7 +12,7 @@* → 取最终回复文字(观察器累积为主,DB 最新 assistant 消息兜底)** 安全不变量(与 errandSlot 头注释同一契约):任务文本只进普通 user 消息;- * 权限档只认 plan/acceptEdits/auto(存储层与本层双重钳制,bypassPermissions+ * 权限档只认 ask/plan/acceptEdits/auto(存储层与本层双重钳制,bypassPermissions* 在协议上不存在);errand 会话侧边栏可见,用户可旁观可随时停;工作目录* 用户配置优先,插件转述的目录只认 pick 亲选台账(isUserPickedDir),* 台账没有即明拒——插件不能凭空指路。@@ -21,14 +21,14 @@*/import {- GHOST_ERRAND_PERMISSION_MODES,type GhostErrandPermissionMode,} from '../../shared/ghost.js';import type {GhostErrandRunner,GhostErrandRunOutcome,} from '../cindy-brain/errandSlot.js';-import type { GhostErrandConfig } from '../cindy-brain/errandPrefsStore.js';+import { clampPluginTaskPermissionMode, type PluginTaskConfig } from '../cindy-brain/pluginTaskPrefsStore.js';+import type { SessionExecutionSelection } from './sessionExecutionSelection.js';import { observeHookTurn, type ObservableSession } from '../hook-control/turnObserver.js';/** turn 收口的兜底超时(25 分钟:低于管子 30 分钟天花板,给交卷留余量)。 */@@ -43,13 +43,16 @@ export interface GhostErrandSessionRow {status: string;agentKind: string;model: string;+ providerId?: string | null;+ effort?: string | null;+ fastMode?: boolean;permissionMode: string;workingDir: string | null;workspaceKind: string;}export interface GhostErrandRunnerDeps {- readConfig(ghostId: string): GhostErrandConfig;+ readConfig(ghostId: string): PluginTaskConfig;/** sessionKey 缺省 = 插件共用间;带钥匙 = 该钥匙专属间(映射按 ghostId+key)。 */readSessionId(ghostId: string, sessionKey?: string): string | null;writeSessionId(ghostId: string, sessionId: string | null, sessionKey?: string): void;@@ -57,6 +60,7 @@ export interface GhostErrandRunnerDeps {/** 建 errand 会话 DB 行(不拉 agent);config 已由本层解析合并完毕。 */createSession(params: {ghostId: string;+ shouldContinue?: () => boolean;title: string | null;agentKind?: 'cc' | 'codex' | 'pi';model?: string;@@ -68,13 +72,9 @@ export interface GhostErrandRunnerDeps {}): Promise<string>;/** 该插件的展示名(errand 会话默认标题用)。 */getGhostName(ghostId: string): string | null;- /** 缺省选型来源:New Maker 草稿偏好快照(与 Orca worker 同源)。 */- getDraftDefaults(vendor: 'claude-code' | 'codex' | 'pi'): {- model?: string;- effort?: string;- fastMode?: boolean;- providerId?: string | null;- };+ /** Shared ordinary-task model policy; errand only adapts its own lifecycle. */+ resolveExecution(config: PluginTaskConfig, sourceSessionId?: string, existing?: GhostErrandSessionRow): Promise<SessionExecutionSelection>;+ captureOwner(): () => void;/*** 目录规范化(与 sessions 落库同一实现):配置目录必须先规范化再与 DB 行* 比对,否则"带尾斜杠 vs 不带"会让复用判定永远失败、每单都建新会话。@@ -114,27 +114,22 @@ function failure(return { ok: false, errorCode, message };}-/** 权限档钳制:任何来路的值都收敛进白名单,缺省 plan(只读)。 */-export function clampErrandPermissionMode(value: unknown): GhostErrandPermissionMode {- return typeof value === 'string' &&- (GHOST_ERRAND_PERMISSION_MODES as readonly string[]).includes(value)- ? (value as GhostErrandPermissionMode)- : 'plan';-}-export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErrandRunner {const now = deps.now ?? (() => Date.now());const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));- /** 既有会话还能不能当这单的干活间:关键配置(agent/权限档/目录)变了就换新间。 */+ /** 既有会话还能不能当这单的干活间:完整模型组合/权限档/目录变了就换新间。 */const sessionMatchesConfig = (row: GhostErrandSessionRow,- cfg: GhostErrandConfig,+ execution: SessionExecutionSelection,permissionMode: GhostErrandPermissionMode,effectiveDir: string | undefined,): boolean => {if (row.status !== 'active') return false;- if (cfg.agentKind && row.agentKind !== cfg.agentKind) return false;+ if (row.agentKind !== (execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind)) return false;+ if (row.model !== execution.model || (row.providerId ?? null) !== (execution.providerId ?? null)) return false;+ if (row.effort && row.effort !== execution.effort) return false;+ if (!!row.fastMode !== execution.fastMode) return false;if (row.permissionMode !== permissionMode) return false;// 这单要目录(用户配置或已对账的插件转述):目录不同(或旧间还是// dialogue)就换新间;这单不要目录:旧的 project 间不再复用,回到@@ -148,13 +143,23 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran};return async (request, hooks) => {- const cfg = deps.readConfig(request.ghostId);- const permissionMode = clampErrandPermissionMode(cfg.permissionMode);+ const assertOwner = deps.captureOwner();+ assertOwner();+ const cfg = { ...deps.readConfig(request.ghostId) };+ const assertConfig = () => {+ assertOwner();+ const current = deps.readConfig(request.ghostId);+ if ((['agentKind', 'model', 'providerId', 'effort', 'fastMode', 'permissionMode', 'workingDir'] as const)+ .some(key => current[key] !== cfg[key])) throw new Error('插件任务设置已变化,请重新发起任务');+ };+ // Compatibility only: existing errand callers keep their original authority.+ // New ordinary task creation uses the shared ask default instead.+ const permissionMode = clampPluginTaskPermissionMode(cfg.permissionMode, 'plan');// 与落库同一套规范化再参与比对/创建;规范化失败视为没配(回专属间)。const configuredDir = cfg.workingDir? (deps.normalizeWorkingDir(cfg.workingDir) ?? undefined): undefined;- // 目录取值:用户在「AI 代办」卡里的配置永远优先;没配置时才看插件在+ // 目录取值:用户在任务设置卡里的配置永远优先;没配置时才看插件在// 请求里转述的目录,且只认 pick 台账里用户亲手选过的——插件不能凭空// 指路,否则等于让它借 Agent 的手读任意文件夹。查不到时明拒,不静默// 落回专属对话间:静默降级会建出一间看不到代码的会话,插件还以为成了。@@ -164,7 +169,7 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErranif (!requested || !deps.isUserPickedDir(request.ghostId, requested)) {return failure('INVALID_REQUEST',- '这个目录不在用户亲选记录里,不能把 errand 会话建在那里;请引导用户在插件设置里重新选一次该目录(经系统选目录窗口),或在插件详情页「AI 代办」卡里配置工作目录',+ '这个目录不在用户亲选记录里,不能在那里新建任务;请引导用户在插件设置里重新选一次该目录(经系统选目录窗口),或在插件详情页任务设置卡里配置工作目录',);}effectiveDir = requested;@@ -173,53 +178,65 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran// ── 确保专属 errand 会话(sessionKey 缺省共用间,带钥匙各开各间) ────const sessionKey = request.sessionKey;let sessionId = deps.readSessionId(request.ghostId, sessionKey);- if (sessionId) {- const row = await deps.getSessionRow(sessionId);- if (!row || !sessionMatchesConfig(row, cfg, permissionMode, effectiveDir)) {- // 旧间不可用/配置已变:解除映射换新间(旧会话留在侧边栏,历史可查)。- deps.writeSessionId(request.ghostId, null, sessionKey);- sessionId = null;+ const originalSessionId = sessionId;+ let row: GhostErrandSessionRow | null;+ let execution: SessionExecutionSelection;+ try {+ row = sessionId ? await deps.getSessionRow(sessionId) : null;+ assertOwner();+ if (sessionId && deps.isSessionBusy(sessionId)) {+ hooks?.onSession?.(sessionId);+ return failure('BUSY', '任务正在使用中,请稍后重试');}+ execution = await deps.resolveExecution(cfg, request.sourceSessionId,+ row?.status === 'active' ? row : undefined);+ assertConfig();+ } catch (error) {+ return failure('SESSION_UNAVAILABLE', error instanceof Error ? error.message : String(error));}+ if (sessionId && (!row || !sessionMatchesConfig(row, execution, permissionMode, effectiveDir))) sessionId = null;if (!sessionId) {- // 缺省选型跟随 New Maker 草稿偏好(与 Orca worker / workspace 槽同源);- // 配置项逐字段覆盖。model/effort 缺省最终由 mapper 兜底,这里不硬编码。- const vendor = cfg.agentKind === 'codex' ? 'codex' : cfg.agentKind === 'pi' ? 'pi' : 'claude-code';- const draft = deps.getDraftDefaults(vendor);const ghostName = deps.getGhostName(request.ghostId);try {sessionId = await deps.createSession({ghostId: request.ghostId,- title: request.title ?? (ghostName ? `${ghostName} · 代办` : null),- ...(cfg.agentKind ? { agentKind: cfg.agentKind } : {}),- ...(cfg.model ?? draft.model ? { model: cfg.model ?? draft.model } : {}),- ...(cfg.effort ?? draft.effort ? { effort: cfg.effort ?? draft.effort } : {}),- ...((cfg.fastMode ?? draft.fastMode) !== undefined- ? { fastMode: cfg.fastMode ?? draft.fastMode }- : {}),- ...((cfg.providerId ?? draft.providerId) !== undefined- ? { providerId: cfg.providerId ?? draft.providerId }- : {}),+ title: request.title ?? ghostName,+ ...execution,+ effort: execution.effort ?? '',+ agentKind: execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind,+ shouldContinue: () => { assertConfig(); return true; },permissionMode,...(effectiveDir ? { workingDir: effectiveDir } : {}),});} catch (err) {const message = err instanceof Error ? err.message : String(err);deps.log.warn('ghost errand session create failed', { ghostId: request.ghostId, error: message });- return failure('SESSION_UNAVAILABLE', `errand 会话创建失败:${message}`);+ return failure('SESSION_UNAVAILABLE', `新建任务失败:${message}`);}+ assertOwner();deps.writeSessionId(request.ghostId, sessionId, sessionKey);}+ if (row && sessionId === originalSessionId) {+ const current = await deps.getSessionRow(sessionId);+ assertOwner();+ if (!current || !sessionMatchesConfig(current, execution, permissionMode, effectiveDir)) {+ return failure('SESSION_UNAVAILABLE', '任务配置已变化,请重新发起;不会使用旧模型继续执行');+ }+ }hooks?.onSession?.(sessionId);// ── 忙检 + 投递 ──────────────────────────────────────────────────────// 不排队:排队会让"这单的结果"对不上"正在跑的那轮"。errandSlot 已保证// 同插件单在途,这里挡的是用户恰好正在这间会话里亲自聊天的情况。if (deps.isSessionBusy(sessionId)) {- return failure('BUSY', 'errand 会话正被占用(可能正被用户使用),请稍后再试');+ return failure('BUSY', '任务正被占用,请稍后再试');+ }+ try { assertConfig(); } catch (error) {+ return failure('SESSION_UNAVAILABLE', error instanceof Error ? error.message : String(error));}const dispatchedAt = now();const dispatched = await deps.dispatch({ targetSessionId: sessionId, message: request.message });+ assertOwner();if (!dispatched.ok) {if (dispatched.errorCode === 'BUSY') return failure('BUSY', dispatched.message);if (@@ -242,13 +259,13 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran});return failure('BUSY',- 'errand 会话恰好正忙,本单任务已排队进该会话但结果不再取回;请稍后查看会话或重新提交',+ '目标任务恰好正忙,本次输入已排队但结果无法自动取回;请稍后打开任务查看结果',);}// ── 收口:观察这一轮直到 done / 终态错误 / 超时 ─────────────────────const session = deps.getObservableSession(sessionId);if (!session) {- return failure('SESSION_UNAVAILABLE', 'errand 会话进程不可用,请稍后再试');+ return failure('SESSION_UNAVAILABLE', '任务进程不可用,请稍后再试');}hooks?.onDispatched?.(sessionId);const observer = observeHookTurn(session, {@@ -273,10 +290,10 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErran} catch (err) {observer.stop();if (timedOut) {- return failure('TIMEOUT', '派活超时(任务可能仍在会话里继续,可打开 errand 会话查看)');+ return failure('TIMEOUT', '任务超时(可能仍在继续运行,可打开任务查看)');}const message = err instanceof Error ? err.message : String(err);- return failure('TURN_FAILED', `派活这一轮失败:${message}`);+ return failure('TURN_FAILED', `任务执行失败:${message}。请在任务中检查模型和供应商连接,修复后重试;不会自动更换模型。`);} finally {if (timer !== undefined) clearTimeout(timer);}@@ -288,11 +305,15 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErranif (!text) {for (let i = 0; i < DB_TEXT_RETRIES && !text; i++) {if (i > 0) await sleep(DB_TEXT_RETRY_DELAY_MS);+ assertOwner();text = ((await deps.readLatestAssistantText(sessionId, dispatchedAt)) ?? '').trim();+ assertOwner();}}if (!text) text = '(本轮没有可取回的文字回复)';- const row = await deps.getSessionRow(sessionId);+ assertOwner();+ const finalRow = await deps.getSessionRow(sessionId);+ assertOwner();deps.log.info('ghost errand turn finished', {ghostId: request.ghostId,sessionId,@@ -303,8 +324,8 @@ export function createGhostErrandRunner(deps: GhostErrandRunnerDeps): GhostErranok: true,sessionId,text,- ...(row?.agentKind ? { agentKind: row.agentKind } : {}),- ...(row?.model ? { model: row.model } : {}),+ ...(finalRow?.agentKind ? { agentKind: finalRow.agentKind } : {}),+ ...(finalRow?.model ? { model: finalRow.model } : {}),};};}diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex f92f8c3996..3b58373dda 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -74,7 +74,7 @@ export function assertPluginTaskResult(result: { ok: boolean; errorCode?: string}/** A live task cannot exercise more authority than the plugin's current setting. */export function isPluginTaskPermissionAllowed(taskMode: unknown, configuredMode: unknown, planModeEnabled = false): boolean {- const rank = (mode: unknown) => mode === 'plan' ? 0 : mode === 'acceptEdits' ? 1 : mode === 'auto' ? 2 : -1;+ const rank = (mode: unknown) => mode === 'plan' ? 0 : mode === 'ask' ? 1 : mode === 'acceptEdits' ? 2 : mode === 'auto' ? 3 : -1;const task = rank(taskMode);return !planModeEnabled && task >= 0 && task <= Math.max(0, rank(configuredMode));}@@ -97,7 +97,7 @@ export interface PluginTaskServiceDeps {assertCurrent(): void;assertAuthorized(pluginId: string): void;readPermissionMode(pluginId: string): unknown;- resolveRoute(pluginId: string, route?: PluginTaskRoute): Promise<PluginTaskRoute>;+ resolveRoute(pluginId: string, route?: PluginTaskRoute, callId?: string): Promise<PluginTaskRoute>;createSession(pluginId: string,taskId: string,@@ -106,7 +106,9 @@ export interface PluginTaskServiceDeps {isolatedWorkspace: boolean | undefined,requestedRoute: PluginTaskRoute | undefined,onPersistenceStarted: () => void,+ callId?: string,): Promise<void>;+ setModel?(taskId: string, route: PluginTaskRoute, assertCurrent: () => Promise<void>): Promise<{ status: string }>;readSession(taskId: string): Promise<PluginTaskView | null>;assertTeamPlanUnstarted?(taskId: string): Promise<void>;dispatch(@@ -247,11 +249,11 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {},create: (pluginId: string,- request: { requestKey: string; title: string; route?: PluginTaskRoute; isolatedWorkspace?: boolean },+ request: { requestKey: string; title: string; route?: PluginTaskRoute; isolatedWorkspace?: boolean; callId?: string },) =>exclusive(async () => {deps.assertAuthorized(pluginId);- const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : [])];+ const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : []), ...(request.callId ? [{ callId: request.callId }] : [])];const fingerprint = hash(input);let row = replay(await deps.store.find(pluginId, 'create', '', request.requestKey),@@ -263,7 +265,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {// Do not recreate a deleted/ambiguous task on replay.return ownTask(pluginId, row.id);}- const route = await deps.resolveRoute(pluginId, request.route);+ const route = await deps.resolveRoute(pluginId, request.route, request.callId);deps.assertCurrent();const taskId = id();row = newReceipt(@@ -280,7 +282,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {try {deps.assertCurrent();await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route,- () => { persistenceStarted = true; });+ () => { persistenceStarted = true; }, request.callId);} catch (error) {// Once INSERT starts, even an error is ambiguous. Never free that key// or infer failure from a subsequently deleted/filtered Session.@@ -314,6 +316,19 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {await save(row,{...data,settledLabels:[...new Set([...(data.settledLabels||[]),label])]});}),assertDispatch,+ setModel: (pluginId: string, request: { taskId: string; expectedRevision: number; route: PluginTaskRoute }) => exclusive(async () => {+ const assertUnchanged = async () => {+ const task = await ownTask(pluginId, request.taskId);+ if (task.status !== 'active') return fail('TASK_BUSY', '任务已归档,请先恢复任务');+ if (task.revision !== request.expectedRevision) return fail('STALE_REVISION', '任务配置已变化,请刷新后重试');+ };+ await assertUnchanged();+ const route = await deps.resolveRoute(pluginId, request.route);+ await assertUnchanged();+ if (!deps.setModel) return fail('HOST_NOT_READY', '任务模型服务尚未就绪');+ const result = await deps.setModel(request.taskId, route, assertUnchanged);+ return { ...result, task: await ownTask(pluginId, request.taskId) };+ }),get: (pluginId: string, taskId: string) => exclusive(() => ownTask(pluginId, taskId)),list: (pluginId: string, after = '', limit = 50) =>exclusive(async () => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex d533ba43ef..60376f3fae 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,3 +1,4 @@+import { openSession, setSessionOpeningModelAdmission } from '../localDb/sessionOpening.js';import { createPluginTaskReviewResolver } from './pluginTaskReviewContext.js';import { isPluginTaskPermissionAllowed, assertPluginTaskResult, createPluginTaskService, readPluginTaskPlanReceipt, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';import { assertPluginWorkerDirectoryScope, resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';@@ -6,7 +7,7 @@ import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';import { createPluginTaskStore } from './pluginTaskStore.js';import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';-import { setPluginTaskHandler, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';+import { setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';import { createHash as pluginTaskConfigHash } from 'node:crypto';import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';@@ -23,7 +24,7 @@ import { getSelfDeviceId, remoteInvoke as invokeBotPeer } from '../device-link/iimport { registerModelFavoritesSync } from './modelFavoritesSync.js';import { advanceRuntimeRecoveryNotice } from '../im/shared/runtimeRecoveryNotice.js';import { markImSessionManualRouteOverride } from '../im/shared/manualRouteOverride.js';-import { configureAppDefaultModelSelection } from './appDefaultModelControl.js';+import { configureAppDefaultModelSelection, inspectAppDefaultModel } from './appDefaultModelControl.js';import type { BuiltinApiKeyBridgeDeps } from '../secrets/builtinApiKeyBridge.js';import { setBotInvitationWelcomeDispatch } from './botInvitation.js';import { createQueuedDispatchReceipts } from './queuedDispatchReceipts.js';@@ -76,6 +77,7 @@ import { AUTO_REVIEW_DELEGATED_CONTINUATION, readAutoReviewUserText, restoreAutoimport type {AgentEvent,AgentKind,+ Effort,ContextUsageData,InteractionDecision,InteractionRequest,@@ -544,6 +546,7 @@ import {getRemoteNewMakerDefaults,getRemoteNewMakerDefaultsByVendor,getWorkerDefaultsFromNewMaker,+ getSelectedNewMakerRoute,getWorkerPermissionModeFromCreationPrefs,type ProviderModelMemorySnapshot,syncNewMakerDraftCache,@@ -1202,19 +1205,22 @@ import {getInstalledGhostName,} from '../cindy-brain/index.js';import {- readGhostErrandConfig,- writeGhostErrandConfig,+ readPluginTaskConfig,+ clampPluginTaskPermissionMode,+ setPluginTaskConfigValidator,+ writePluginTaskConfig,readGhostErrandSessionId,writeGhostErrandSessionId,-} from '../cindy-brain/errandPrefsStore.js';+} from '../cindy-brain/pluginTaskPrefsStore.js';import { isGhostPickedDir } from '../cindy-brain/pickGrantsStore.js';import {resolveGhostUserHookModel,withGhostUserHookModel,} from '../cindy-brain/subscriptionGateway.js';-import { createGhostErrandRunner, clampErrandPermissionMode } from './ghostErrandRunner.js';+import { createSessionExecutionResolver } from './sessionExecutionSelection.js';+import { createGhostErrandRunner } from './ghostErrandRunner.js';import {- createGhostErrandSession,+ createPluginTaskSession,createPluginDraftSession,findActiveSessionByWorkdir,} from '../localDb/ipc/pluginWorkspaceSessions.js';@@ -9371,7 +9377,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)title: newTitle,permissionMode: inherited.permissionMode ?? 'bypassPermissions',});- const { session } = await bootstrapSession(createOpts);+ const { row: openedRow, value: { session } } = await openSession({+ id: createOpts.id, body: { title: newTitle,+ agentKind: inherited.agentKind === 'claude-code' ? 'cc' : inherited.agentKind,+ model: inherited.model, providerId: inherited.providerId, effort: inherited.effort,+ fastMode: !!inherited.fastMode, permissionMode: createOpts.permissionMode,+ workspaceKind: inherited.workspaceKind, workingDir: createOpts.workingDir },+ }, async (row, assertCurrent) => {+ const created = await bootstrapSession({ ...createOpts, id: row.id, model: row.model,+ providerId: row.providerId, effort: (row.effort || undefined) as CreateOpts['effort'],+ fastMode: row.fastMode, workingDir: row.workingDir ?? createOpts.workingDir }, assertCurrent);+ // A later owner check must not reclaim a worktree whose Session already exists.+ createdPreviewSessionId = created.session.id;+ return created;+ });// worktree 场景补写 sessions.worktree_path 反范式快照:createWorktree 时// session 行还不存在,worktreeStore.set 的 DB 同步落空(仅 warn),这里 session// 行已建,补一次。失败非致命——徽标以 worktreeStore 为准。@@ -9439,10 +9458,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)targetTitle: newTitle,targetLastUserSendAt: null,worktreePath: handoffWorktree?.meta.path ?? null,- model: inherited.model,- effort: inherited.effort ?? null,- fastMode: !!inherited.fastMode,- providerId: inherited.providerId ?? null,+ model: openedRow.model,+ effort: openedRow.effort || null,+ fastMode: openedRow.fastMode,+ providerId: openedRow.providerId ?? null,};} catch (err) {if (createdPreviewStarted && createdPreviewSessionId && createdPreviewClientId) {@@ -10495,6 +10514,42 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return delegationForRestore.cancelDelegation(parentSessionId, delegationId);},);+ const captureSessionOwner = () => {+ const owner = getCurrentDbClientSnapshot();+ return () => {+ if (!owner || isAppSessionBoundaryPending() || getCurrentDbClientSnapshot() !== owner) throw new Error('账号已变化,请重新发起任务');+ };+ };+ const resolveSessionExecution = createSessionExecutionResolver({+ captureOwner: captureSessionOwner,+ readCaller: async sessionId => {+ const meta = await maker.getSessionMeta(sessionId);+ if (!meta || meta.remoteHostId) throw new Error('无法读取发起任务的本机模型配置,请明确选择新任务的模型');+ const profile = await readSessionRuntimeProfiles(sessionId);+ if (!profile || profile.pendingMutation) throw new Error('发起任务正在切换模型,请稍后重试');+ return { ...profile.effective, effort: profile.effective.effort ?? undefined };+ },+ readDefault: () => {+ const route = getSelectedNewMakerRoute(activeOwnerScopeKey());+ return route ? { agentKind: route.harness === 'claude' ? 'claude-code' : route.harness,+ model: route.model, providerId: route.providerId, effort: (route.effort || undefined) as Effort | undefined,+ fastMode: route.fastMode } : undefined;+ },+ availableAgents: () => maker.listAvailableAgents(),+ availableModels: agent => maker.getCapabilities(agent).availableModels,+ readProviderRouting: () => getProviderRoutingContext(),+ hasCindyAiApiKey: () => readClaudeApiKey() != null,+ });+ setSessionOpeningModelAdmission(async body => {+ const execution = await resolveSessionExecution({+ agentKind: body.agentKind, model: body.model, providerId: body.providerId,+ effort: body.effort, fastMode: body.fastMode,+ });+ return { ...body, ...execution, effort: execution.effort ?? '',+ agentKind: execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind };+ });+ setPluginTaskConfigValidator(async config => { await resolveSessionExecution(config); });+// Ghost 的 Agent 槽只负责验证权限和整理 prompt;真正的新回合仍走// sendToSessionInternal 这一条主机通路,因此会话恢复、繁忙排队、消息落库与// 费用行为都和用户亲自在聊天框发送一致。runner 通过回调注入,避免@@ -10515,6 +10570,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}};+ // This surface acts on the user's task, so keep its own route/permissions.+ // Admission is shared with plugin-owned tasks; their defaults must not replace it.+ try {+ // A remote task's model is owned by its execution host, not this device's catalog.+ const source = await maker.getSessionMeta(request.sourceSessionId);+ if (!source?.remoteHostId) await resolveSessionExecution({}, request.sourceSessionId);+ }+ catch (error) { return { ok: false, errorCode: 'MODEL_UNAVAILABLE',+ message: error instanceof Error ? error.message : '任务模型不可用,请在任务中重新选择' }; }+if (request.mode === 'new') {const result = await sendToSessionInternal({dispatcherSessionId: request.sourceSessionId,@@ -10597,10 +10662,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});setGhostSessionRevealer((sessionId) => openMainWindowSession(sessionId));- // Ghost 的派活取件(agent 槽 errand 加档):守门在 cindy-brain/errandSlot,- // 这里注入真实执行链——专属会话确保/统一投递/turn 收口。投递仍走- // sendToSessionInternal 这一条主机通路(消息落库、进程拉起与用户亲发一致);- // 收口复用 hook-control 的 observeHookTurn(与飞书 bot 同一套 turn 观察语义)。// One receipt service per account/database epoch. No mutable current-DB lookup// is retained by an asynchronous task request.let pluginTaskEpoch: ReturnType<typeof getCurrentDbClientSnapshot> = null;@@ -10618,24 +10679,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!isPluginTaskAuthorized(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task capability is unavailable');};const routeUnavailable = (): never => { throw new PluginTaskError('ROUTE_UNAVAILABLE', 'The selected provider, model or effort is unavailable'); };- const resolveRoute = async (pluginId: string, requested?: PluginTaskRoute): Promise<PluginTaskRoute> => {- assertPlugin(pluginId);- const cfg = readGhostErrandConfig(pluginId);- const agentKind = requested?.agentKind ?? cfg.agentKind ?? 'cc';- const defaults = getWorkerDefaultsFromNewMaker(agentKind === 'cc' ? 'claude-code' : agentKind);- const modelId = requested?.model ?? cfg.model ?? defaults.model;- if (!modelId) return routeUnavailable();- const providers = await getDesktopProviderService().listProviders({ allowSideEffects: false, catalog: getActiveCatalog() });+ const resolveRoute = async (pluginId: string, requested?: PluginTaskRoute, callId?: string): Promise<PluginTaskRoute> => {assertPlugin(pluginId);- const providerId = requested?.providerId ?? cfg.providerId ?? defaults.providerId ?? effectiveSourceIdForModel(providers, null, modelId, agentKind === 'cc' ? 'claude-code' : agentKind);- const provider = providers.find(p => p.id === providerId && p.connected && !p.suspended && !p.removed);- const model = findCatalogModel(provider, modelId, agentKind === 'cc' ? 'claude-code' : agentKind, { exact: true });- if (!provider || !model || !isModelSelectableForNewRoute(model, { userProvider: provider.source === 'user' })) return routeUnavailable();- const effort = requested?.effort ?? cfg.effort ?? defaults.effort ?? model.defaultEffort ?? 'high';- const fastMode = requested?.fastMode ?? cfg.fastMode ?? defaults.fastMode ?? false;- if (!model.efforts.some(e => e === effort)) return routeUnavailable();- if (fastMode && model.supportsFastMode !== true) return routeUnavailable();- return { agentKind, providerId: provider.id, model: modelId, effort, fastMode };+ const selection = { ...readPluginTaskConfig(pluginId), ...requested };+ const sourceSessionId = getPluginTaskSourceSessionId(pluginId, callId);+ if (callId && !sourceSessionId && !(selection.agentKind && selection.model && selection.providerId)) throw new PluginTaskError('ROUTE_UNAVAILABLE', '发起任务已不可用,请重新调用,或在面板选择模型后创建任务');+ try {+ const execution = await resolveSessionExecution(selection, sourceSessionId);+ assertPlugin(pluginId);+ if (!execution.providerId) return routeUnavailable();+ return { ...execution, agentKind: execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind,+ providerId: execution.providerId, effort: execution.effort ?? '' };+ } catch (error) {+ throw new PluginTaskError('ROUTE_UNAVAILABLE', error instanceof Error ? error.message : '任务模型不可用,请重新选择');+ }};const readExecution = (taskId: string) => {const live = maker.getSession(taskId);@@ -10644,7 +10701,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)pluginTaskEpoch = snapshot;pluginTasks = createPluginTaskService({store: createPluginTaskStore(snapshot.client), assertCurrent, assertAuthorized: assertPlugin, resolveRoute,- readPermissionMode: pluginId => readGhostErrandConfig(pluginId).permissionMode,+ readPermissionMode: pluginId => clampPluginTaskPermissionMode(readPluginTaskConfig(pluginId).permissionMode),+ setModel: async (taskId, route, assertUnchanged) => {+ const current = await sessionControlService.getSessionRuntime({ targetSessionId: taskId });+ if (!current.ok) throw new PluginTaskError('TASK_NOT_FOUND', current.message);+ await assertUnchanged();+ const targetAgent = route.agentKind === 'cc' ? 'claude-code' : route.agentKind;+ const pendingAgent = current.runtime.pendingMutation?.profile.agentKind;+ const selectHarness = current.runtime.effectiveProfile.agentKind !== targetAgent+ || (pendingAgent !== undefined && pendingAgent !== targetAgent);+ const result = await sessionControlService.setSessionRuntime({ targetSessionId: taskId,+ expectedGeneration: current.runtime.runtimeGeneration,+ patch: { ...(selectHarness ? { harness: targetAgent } : {}),+ model: route.model, providerId: route.providerId, effort: (route.effort || null) as Effort | null,+ fastMode: route.fastMode } });+ if (!result.ok) throw new PluginTaskError(result.errorCode, result.message);+ return { status: result.status };+ },assertTeamPlanUnstarted: async taskId => {assertCurrent();await drainPersistQueue();@@ -10658,11 +10731,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertCurrent();if (workers.length || reservations.length) throw new PluginTaskError('TASK_BUSY', 'Register the team plan before creating Workers');},- createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted) => {+ createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted, callId) => {assertPlugin(pluginId);- const cfg = readGhostErrandConfig(pluginId);+ const cfg = readPluginTaskConfig(pluginId);const configurationIsCurrent = () => {- const current = readGhostErrandConfig(pluginId);+ const current = readPluginTaskConfig(pluginId);return current.workingDir === cfg.workingDir && current.permissionMode === cfg.permissionMode&& current.agentKind === cfg.agentKind && current.model === cfg.model&& current.providerId === cfg.providerId && current.effort === cfg.effort@@ -10671,7 +10744,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Receipt persistence/provider lookup can yield after the first resolution.// Reuse the resolver with the original request, then guard this configuration// through directory validation and the creator's final continuation.- const currentRoute = await resolveRoute(pluginId, requestedRoute);+ const currentRoute = await resolveRoute(pluginId, requestedRoute, callId);if ((Object.keys(currentRoute) as Array<keyof PluginTaskRoute>).some(key => currentRoute[key] !== route[key]))throw new PluginTaskError('ROUTE_UNAVAILABLE', 'Plugin task route changed');const workingDir = !isolatedWorkspace && cfg.workingDir@@ -10686,10 +10759,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): undefined;assertPlugin(pluginId);if (!configurationIsCurrent()) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task configuration changed');- await createGhostErrandSession({+ await createPluginTaskSession({ghostId: pluginId, sessionId: taskId, title, ...route,onPersistenceStarted,- permissionMode: clampErrandPermissionMode(cfg.permissionMode),+ permissionMode: clampPluginTaskPermissionMode(cfg.permissionMode),...(workingDir ? { workingDir } : {}),shouldContinue: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId) && configurationIsCurrent(),notifySessionCreated: ({ sessionId, workdir }) => {@@ -10703,7 +10776,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const [row] = await snapshot.client.drizzle.select().from(sessions).where(eq(sessions.id, taskId)).limit(1);assertCurrent();if (!row || row.source !== 'plugin' || row.remoteHostId || (row.orcaRole && row.orcaRole !== 'lead') || !['cc', 'codex', 'pi'].includes(row.agentKind)) return null;- const resolvedConfig: PluginTaskRoute = { agentKind: row.agentKind as PluginTaskRoute['agentKind'], providerId: row.providerId ?? '', model: row.model, effort: row.effort, fastMode: row.fastMode };+ const runtime = await readSessionRuntimeProfiles(taskId);+ assertCurrent();+ // A queued input will execute the accepted next-send route. Keep its+ // receipt stable as a deferred model/Harness switch reaches that boundary.+ const selected = runtime?.pendingMutation?.profile ?? runtime?.effective;+ const resolvedConfig: PluginTaskRoute = selected+ ? { agentKind: selected.agentKind === 'claude-code' ? 'cc' : selected.agentKind,+ providerId: selected.providerId ?? '', model: selected.model,+ effort: selected.effort ?? '', fastMode: selected.fastMode }+ : { agentKind: row.agentKind as PluginTaskRoute['agentKind'], providerId: row.providerId ?? '', model: row.model, effort: row.effort, fastMode: row.fastMode };const revision = Number.parseInt(pluginTaskConfigHash('sha256').update(JSON.stringify([resolvedConfig, row.permissionMode, row.planModeEnabled, row.workingDir, row.status, row.orcaRole])).digest('hex').slice(0, 12), 16);return { taskId, title: row.title, status: row.status, revision, resolvedConfig, workingDir: row.workingDir ?? undefined, permissionMode: row.permissionMode, planModeEnabled: !!row.planModeEnabled };},@@ -10836,7 +10918,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertPlanInactive();if (task.planModeEnabled) throw new PluginTaskError('PERMISSION_DENIED', 'Exit Plan Mode before requesting write access');const mode = request.mode ?? 'acceptEdits';- const cfg = readGhostErrandConfig(pluginId);+ const cfg = readPluginTaskConfig(pluginId);assertCallerCurrent();if (isPluginTaskPermissionAllowed(task.permissionMode, cfg.permissionMode) && (mode === 'acceptEdits' ? task.permissionMode === 'acceptEdits' || task.permissionMode === 'auto' : task.permissionMode === 'auto')) return { granted: true, task };if (pluginPermissionRequests.size) throw new PluginTaskError('TASK_BUSY', 'A permission request is already open');@@ -10883,7 +10965,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// permission writers never hold that fence while awaiting this queue.return await withSessionPermissionChange(task.taskId, () => service.completeOperation(() => withSessionRestartLock(task.taskId, async () => {assertRequestCurrent();- if (snapshot !== getCurrentDbClientSnapshot() || before !== JSON.stringify(readGhostErrandConfig(pluginId))) throw new PluginTaskError('PERMISSION_DENIED', 'Account or permission settings changed');+ if (snapshot !== getCurrentDbClientSnapshot() || before !== JSON.stringify(readPluginTaskConfig(pluginId))) throw new PluginTaskError('PERMISSION_DENIED', 'Account or permission settings changed');const fresh = await service.get(pluginId, task.taskId);if (fresh.status !== 'active') throw new PluginTaskError('TASK_BUSY', 'Archived tasks cannot request write access');if (fresh.planModeEnabled) throw new PluginTaskError('PERMISSION_DENIED', 'Exit Plan Mode before requesting write access');@@ -10906,9 +10988,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)assertRequestCurrent();if (snapshot !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');assertPlanInactive();- const currentConfig = readGhostErrandConfig(pluginId);+ const currentConfig = readPluginTaskConfig(pluginId);if (currentConfig.permissionMode !== cfg.permissionMode) throw new PluginTaskError('PERMISSION_DENIED', 'Permission settings changed');- if (mode === 'auto' || clampErrandPermissionMode(currentConfig.permissionMode) === 'plan') writeGhostErrandConfig(pluginId, {...currentConfig, permissionMode: mode});+ if (mode === 'auto' || ['ask', 'plan'].includes(clampPluginTaskPermissionMode(currentConfig.permissionMode))) writePluginTaskConfig(pluginId, {...currentConfig, permissionMode: mode});broadcastSessionPatched(task.taskId, {permissionMode: mode});return { granted: true, task: updatedTask };} catch (error) {@@ -10923,7 +11005,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)case 'startTeam': {const epoch = getCurrentDbClientSnapshot();const task = await service.get(pluginId, request.taskId);- const configuredDirectory = readGhostErrandConfig(pluginId).workingDir;+ const configuredDirectory = readPluginTaskConfig(pluginId).workingDir;// Becoming Lead changes revision through orcaRole, but may not change admission facts.const admission = (view: typeof task) => JSON.stringify([view.resolvedConfig, view.permissionMode, view.planModeEnabled, view.workingDir]);const expectedAdmission = admission(task);@@ -10933,7 +11015,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const fresh = await service.get(pluginId, task.taskId);if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');assertPluginWorkerAutoAuthorized(pluginId, fresh);- if (configuredDirectory !== readGhostErrandConfig(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');+ if (configuredDirectory !== readPluginTaskConfig(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');if ((!activationStarted && fresh.revision !== task.revision) || admission(fresh) !== expectedAdmission) throw new PluginTaskError('STALE_REVISION', 'Task changed during team activation');}, service.completeOperation);assertPluginTaskResult(result, 'Collaboration could not be started');@@ -10942,9 +11024,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)case 'setTeamPlan': return withSendToSessionLock(request.taskId, async () => {const epoch = getCurrentDbClientSnapshot();const task = await service.get(pluginId, request.taskId);- const cfg = readGhostErrandConfig(pluginId);+ const cfg = readPluginTaskConfig(pluginId);const assertCurrent = () => {- if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId) || cfg.workingDir !== readGhostErrandConfig(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId) || cfg.workingDir !== readPluginTaskConfig(pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin directory authorization changed');};const items = [];for (const item of request.plan.items) {@@ -11017,6 +11099,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const live = maker.getSession(request.taskId);return {...team, capacity:{hardLimit,occupiedSlots,remainingSlots:Math.max(0,hardLimit-occupiedSlots),advisory:true}, coordinatorUsage:{scope:'session-total',tokens:leadRow?.totalTokenUsage ?? null,costUSD:leadRow?.totalCostCurrency==='USD' && leadRow.totalCostAmount>0 ? leadRow.totalCostAmount : null, approximate:leadRow?.totalCostIsApproximate ?? false}, workers, waitingForUser:!!live && live.getTurnControlSnapshot().pendingInteractionCount > 0, leadWorking:(!!live && (live.isTurnRunning() || live.getTurnControlSnapshot().pendingInteractionCount > 0)) || inputCoordinator.getQueueControlSnapshot(request.taskId).pendingQueue.length > 0};}+ case 'models': {+ const snapshot = getCurrentDbClientSnapshot();+ const { available } = await inspectAppDefaultModel();+ if (snapshot !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(pluginId)) throw new PluginTaskError('PERMISSION_DENIED', '账号或插件授权已变化');+ return { models: available.map(option => ({ id: option.id,+ route: { agentKind: option.route.harness === 'claude' ? 'cc' : option.route.harness,+ model: option.route.model, providerId: option.route.providerId,+ effort: option.route.effort, fastMode: option.route.fastMode },+ efforts: option.efforts, supportsFastMode: option.supportsFastMode })) };+ }+ case 'setModel': return service.setModel(pluginId, request);case 'create': return service.create(pluginId, request);case 'get': return service.get(pluginId, request.taskId);case 'list': return service.list(pluginId, request.after, request.limit);@@ -11085,9 +11178,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle('maker:get-plugin-write-access-recovery', (event, taskId: unknown) => pluginWriteAccessFromHost(event, taskId, false));ipcMain.handle('maker:retry-plugin-write-access', (event, taskId: unknown) => pluginWriteAccessFromHost(event, taskId, true));+ // Legacy result-returning adapter; ordinary task configuration lives above.setGhostErrandRunner(createGhostErrandRunner({- readConfig: readGhostErrandConfig,+ readConfig: readPluginTaskConfig,readSessionId: readGhostErrandSessionId,writeSessionId: writeGhostErrandSessionId,getSessionRow: async (sessionId) => {@@ -11096,6 +11190,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)status: sessions.status,agentKind: sessions.agentKind,model: sessions.model,+ providerId: sessions.providerId,+ effort: sessions.effort,+ fastMode: sessions.fastMode,permissionMode: sessions.permissionMode,workingDir: sessions.workingDir,workspaceKind: sessions.workspaceKind,@@ -11103,10 +11200,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions).from(sessions).where(eq(sessions.id, sessionId)).limit(1);- return row ?? null;+ if (!row) return null;+ const profile = await readSessionRuntimeProfiles(sessionId);+ if (profile?.pendingMutation) throw new Error('任务正在切换模型,请稍后重试');+ const live = maker.getSession(sessionId);+ const mode = live ? live.stablePermissionModeState?.mode : row.permissionMode;+ if (live && !mode) throw new Error('任务正在切换权限,请稍后重试');+ return { ...row, ...(profile ? { ...profile.effective,+ agentKind: profile.effective.agentKind === 'claude-code' ? 'cc' : profile.effective.agentKind } : {}),+ permissionMode: mode ?? row.permissionMode };},createSession: async (params) => {- const sessionId = await createGhostErrandSession({+ const sessionId = await createPluginTaskSession({...params,notifySessionCreated: (info) => notifyGhostSessionEvent('created', info),});@@ -11116,7 +11221,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return sessionId;},getGhostName: getInstalledGhostName,- getDraftDefaults: getWorkerDefaultsFromNewMaker,+ resolveExecution: resolveSessionExecution,+ captureOwner: captureSessionOwner,normalizeWorkingDir: (dir) => normalizeWorkingDirForStorage(dir),isUserPickedDir: isGhostPickedDir,isSessionBusy: isSessionInTurn,@@ -11177,34 +11283,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},findActiveSessionByWorkdir,createDraftSession: async (params) => {- // draft 跟随用户在 New Maker 面板的当前选择,与用户手建草稿的默认体验- // 一致。main 侧缓存没有"当前激活 vendor"信号,取有选择记录的一档:- // cc 有记录用 cc;cc 无则 codex;再无则 pi(整套跟随,避免给 pi-only 用户- // 建出带 Claude 默认值的会话);都没有走 mapper 兜底。- const ccDefaults = getWorkerDefaultsFromNewMaker('claude-code');- const codexDefaults = ccDefaults.model ? null : getWorkerDefaultsFromNewMaker('codex');- const piDefaults =- ccDefaults.model || codexDefaults?.model ? null : getWorkerDefaultsFromNewMaker('pi');- const picked = ccDefaults.model- ? { agentKind: 'cc' as const, d: ccDefaults }- : codexDefaults?.model- ? { agentKind: 'codex' as const, d: codexDefaults }- : piDefaults?.model- ? { agentKind: 'pi' as const, d: piDefaults }- : null;+ const assertOwner = captureSessionOwner();+ const config = readPluginTaskConfig(params.ghostId);+ const execution = await resolveSessionExecution(config, params.sourceSessionId);+ assertOwner();const sessionId = await createPluginDraftSession({...params,- ...(picked- ? {- defaults: {- agentKind: picked.agentKind,- ...(picked.d.model ? { model: picked.d.model } : {}),- ...(picked.d.effort ? { effort: picked.d.effort } : {}),- ...(picked.d.fastMode !== undefined ? { fastMode: picked.d.fastMode } : {}),- ...(picked.d.providerId !== undefined ? { providerId: picked.d.providerId } : {}),- },- }- : {}),+ shouldContinue: () => { assertOwner(); return (params.shouldContinue?.() ?? true)+ && JSON.stringify(readPluginTaskConfig(params.ghostId)) === JSON.stringify(config); },+ defaults: { ...execution, effort: execution.effort ?? '', permissionMode: clampPluginTaskPermissionMode(config.permissionMode), agentKind: execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind },notifySessionCreated: (info) => notifyGhostSessionEvent('created', info),});if (!sessionId) return null;@@ -12093,7 +12180,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (task.status !== 'active') {throw new PluginTaskError('TASK_BUSY', 'Archived tasks cannot create Workers');}- if (!isPluginTaskAuthorized(pluginId) || task.planModeEnabled || task.permissionMode !== 'auto' || readGhostErrandConfig(pluginId).permissionMode !== 'auto') {+ if (!isPluginTaskAuthorized(pluginId) || task.planModeEnabled || task.permissionMode !== 'auto' || readPluginTaskConfig(pluginId).permissionMode !== 'auto') {throw new PluginTaskError('PERMISSION_DENIED', 'Authorize Auto for the plugin coordinator before creating Workers');}};@@ -12159,12 +12246,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const task = await pluginTaskServiceForCurrentOwner!().get(receipt.pluginId,params.leadSessionId);if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED','Account changed');assertPluginWorkerAutoAuthorized(receipt.pluginId, task);- const cfg = readGhostErrandConfig(receipt.pluginId);+ const cfg = readPluginTaskConfig(receipt.pluginId);const resolveAuthorizedDirectory = (requested: string) => resolvePluginWorkerDirectory({requested, leadDirectory: task.workingDir,configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId,dir),assertCurrent: () => {- if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');+ if (epoch !== getCurrentDbClientSnapshot() || !isPluginTaskAuthorized(receipt.pluginId) || cfg.workingDir !== readPluginTaskConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');},});const directory = await resolveAuthorizedDirectory(params.workingDir ?? task.workingDir ?? '');@@ -12186,7 +12273,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Last admission check also covers no-plan plugin tasks and revocation// while directory/receipt reads or the existing reservation were pending.assertPluginWorkerAutoAuthorized(receipt.pluginId, currentTask);- if (cfg.workingDir !== readGhostErrandConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');+ if (cfg.workingDir !== readPluginTaskConfig(receipt.pluginId).workingDir) throw new PluginTaskError('PERMISSION_DENIED','Plugin directory authorization changed');assertPluginWorkerDirectoryScope({ requested: directory, leadDirectory: currentTask.workingDir,configuredDirectory: cfg.workingDir, isPickedDirectory: dir => isGhostPickedDir(receipt.pluginId, dir) });if (!data.teamPlan) return undefined; // Existing plugins retain their original behavior.@@ -13839,7 +13926,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)projection.revision,]);if (epoch !== getCurrentDbClientSnapshot()) throw new Error('Account changed');- const config = readGhostErrandConfig(receipt.pluginId);+ const config = readPluginTaskConfig(receipt.pluginId);const approvalRevision = pluginTaskAuthorizationRevision(receipt.pluginId);return {pluginId: receipt.pluginId,diff --git a/apps/desktop/src/main/maker-ipc/sessionExecutionSelection.ts b/apps/desktop/src/main/maker-ipc/sessionExecutionSelection.tsnew file mode 100644index 0000000000..2a621caed7--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/sessionExecutionSelection.ts@@ -0,0 +1,86 @@+import type { AgentKind, Effort } from '@cindy/maker-core';+import { resolveSendToSessionExecutionConfig, type SendToSessionExecutionConfig } from './sendToSessionExecutionConfig.js';++export type SessionExecutionSelection = SendToSessionExecutionConfig;+export interface SessionModelSelection {+ agentKind?: 'cc' | AgentKind;+ model?: string;+ providerId?: string | null;+ effort?: string;+ fastMode?: boolean;+}+type Selection = SessionModelSelection;+type Admission = Parameters<typeof resolveSendToSessionExecutionConfig>[0];++/** Shared Session model selection. Callers supply authorized defaults; no caller-specific lifecycle or permissions. */+export function resolveSessionExecutionSelection(params: {+ selection: Selection;+ source?: SessionExecutionSelection;+ availableAgents: readonly AgentKind[];+ availableModels: Admission['availableModels'];+ providerRouting: Admission['providerRouting'];+ hasCindyAiApiKey: boolean;+}): SessionExecutionSelection {+ const { selection, source, providerRouting } = params;+ const agentKind = selection.agentKind === 'cc' ? 'claude-code' : selection.agentKind ?? source?.agentKind;+ const model = selection.model ?? source?.model;+ const recover = '请在任务中重新选择模型,或在「设置 → 模型供应商」修复连接后重试。';+ if (!agentKind || !model) throw new Error(`尚未选择任务模型。请先选择新任务模型,或${recover}`);+ if (!params.availableAgents.includes(agentKind)) throw new Error(`Agent ${agentKind} 当前不可用。${recover}`);+ // An old partial override may change engines/models. Never borrow the previous+ // model's provider or tuning; choose only a route for this exact requested model.+ const sameIdentity = source?.agentKind === agentKind && source.model === model;+ const providerId = selection.providerId ?? (sameIdentity ? source?.providerId : undefined)+ ?? providerRouting.resolveDefaultProviderIdForModel(agentKind, model);+ const routeModel = providerRouting.availability[agentKind]?.find(p => p.id === providerId)?.effortMetaByModel?.[model];+ const metadata = routeModel ?? params.availableModels.find(m => m.id === model);+ const defaultEffort = metadata?.defaultEffort;+ const effort = selection.effort ?? (sameIdentity ? source?.effort : undefined)+ ?? (defaultEffort && metadata?.efforts?.includes(defaultEffort) ? defaultEffort : undefined);+ const candidate: SessionExecutionSelection = {+ agentKind, model, providerId, effort: (effort || undefined) as Effort | undefined,+ fastMode: selection.fastMode ?? (sameIdentity ? source?.fastMode : false) ?? false,+ };+ const result = resolveSendToSessionExecutionConfig({+ source: candidate, overrides: { effort: candidate.effort, fastMode: candidate.fastMode },+ availableModels: params.availableModels, providerRouting, hasCindyAiApiKey: params.hasCindyAiApiKey,+ });+ if (!result.ok) throw new Error(`${result.message} ${recover}不会自动更换模型或供应商。`);+ return result.config;+}++export interface SessionExecutionResolverDeps {+ captureOwner(): () => void;+ readCaller(sessionId: string): Promise<SessionExecutionSelection>;+ readDefault(): SessionExecutionSelection | undefined;+ availableAgents(): readonly AgentKind[];+ availableModels(agent: AgentKind): Admission['availableModels'];+ readProviderRouting(): Promise<Admission['providerRouting']>;+ hasCindyAiApiKey(): boolean;+}++/** sourceSessionId is Host-resolved from an authenticated call, never plugin-supplied. */+export function createSessionExecutionResolver(deps: SessionExecutionResolverDeps) {+ return async (selection: Selection, sourceSessionId?: string,+ existing?: { agentKind: string; model: string; providerId?: string | null; effort?: string | null; fastMode?: boolean },+ ): Promise<SessionExecutionSelection> => {+ const assertOwner = deps.captureOwner();+ assertOwner();+ let source: SessionExecutionSelection | undefined;+ if (existing) {+ if (!['cc', 'claude-code', 'codex', 'pi'].includes(existing.agentKind)) throw new Error('任务 Agent 不可用,请重新选择模型');+ source = { agentKind: (existing.agentKind === 'cc' ? 'claude-code' : existing.agentKind) as AgentKind,+ model: existing.model, providerId: existing.providerId,+ effort: (existing.effort || undefined) as Effort | undefined, fastMode: existing.fastMode === true };+ } else if (!(selection.agentKind && selection.model && selection.providerId)) {+ source = sourceSessionId ? await deps.readCaller(sourceSessionId) : deps.readDefault();+ assertOwner();+ }+ const providerRouting = await deps.readProviderRouting();+ assertOwner();+ const agent = selection.agentKind === 'cc' ? 'claude-code' : selection.agentKind ?? source?.agentKind;+ return resolveSessionExecutionSelection({ selection, source, providerRouting,+ availableAgents: deps.availableAgents(), availableModels: agent ? deps.availableModels(agent) : [],+ hasCindyAiApiKey: deps.hasCindyAiApiKey() });+ };+}diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex b4279adfd8..1227ceb8db 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -70,7 +70,7 @@ contextBridge.exposeInMainWorld('cindy', {library: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),tasks: Object.fromEntries(- ['capabilities', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages'].map(kind => [+ ['capabilities', 'models', 'setModel', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages'].map(kind => [kind, async (req: Record<string, unknown> = {}): Promise<unknown> => {const result = await ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'tasks-request', kind });if (result?.ok === true) return result.data;diff --git a/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsxsimilarity index 66%rename from apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsxrename to apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsxindex b5792a2fd4..8b7ef74ec0 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostErrandPrefs.tsx+++ b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx@@ -1,31 +1,12 @@import { Button } from '@/components/ui/button';-/**- * Host-rendered errand (派活取件) preferences for a Plugin that declares- * `agent.errand`. Settings 详情与 Plugin 详情共用(同 CindyCapabilityPrefs)。- *- * 选择器复用草稿页同一套组件(2026-07-31 Lizi 要求,不另搭下拉),展示与- * 交互与新建对话一致,不暴露「跟随默认 / 钉住」这层概念:- * - Harness 与模型作为完整配置由共享选择器一起保存;- * - 模型/推理强度/Fast/供应商 = ModelSelector 的 field 形态,占满整行(标题在上、- * 控件 w-full 在下,与 IM 默认配置同款);面板宽度绑定 trigger(DESIGN.md §4);- * - 动手权限 = PermissionSelector(权限下拉全仓只此一份,不得私搭),- * errand 不允许的档位经 disabledModes 灰置并带原因。- *- * 底层仍是「未写的字段跟随草稿」语义(与 main 侧 errandPrefsStore 同一契约):- * 没单独选过时实时展示并跟随「新建草稿」当前选择(草稿默认变,这里跟着变);- * 用户一旦点选即把该组值钉进本插件配置。UI 不再显示跟随/恢复的文案 —— 呈现的- * 永远是一个具体的当前模型+强度(2026-07-31 Lizi 要求)。权限档与工作目录是- * errand 自己的事,不参与跟随:权限缺省 plan(只读,协议层不存在- * bypassPermissions),目录缺省插件专属文件夹,选真实项目必须经系统窗口- * 亲选(与 pick 槽同一哲学)。- */+/** User preferences for new plugin tasks; uses the ordinary model/permission controls. */import { useModelPickerAgents } from '@/hooks/useAvailableAgents';import { useCallback, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { Bot, FolderOpen, X } from 'lucide-react';-import { toast } from '@/lib/toast';+import { extractIpcError } from '@/utils/ipcError';import { cn } from '@/lib/utils';import { ModelSelector } from '@/components/new-chat/ModelSelector';import { PermissionSelector } from '@/components/new-chat/PermissionSelector';@@ -36,74 +17,78 @@ import {} from '@/state/newMakerDraft';import type { Effort } from '@/lib/userPreferences.types';-const PERMISSION_ALLOWED = new Set(['plan', 'acceptEdits', 'auto']);+const PERMISSION_ALLOWED = new Set(['ask', 'acceptEdits', 'auto']);-/** errand 只收 worker 同集合的思考档(minimal 不收,与 main 侧存储层一致)。 */-const ERRAND_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max', 'ultra']);+/** Values accepted by the ordinary model picker and Host configuration. */+const TASK_EFFORTS = new Set(['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']);-interface ErrandConfig {+interface TaskConfig {agentKind?: 'cc' | 'codex' | 'pi';model?: string;effort?: string;fastMode?: boolean;providerId?: string;- permissionMode?: 'plan' | 'acceptEdits' | 'auto';+ permissionMode?: 'ask' | 'plan' | 'acceptEdits' | 'auto';workingDir?: string;}-export function GhostErrandPrefs({+export function PluginTaskPrefs({ghostId,appearance = 'settings',+ legacyDefault = false,}: {ghostId: string;/** Plugin detail aligns the card with the shared Plugin surface. */appearance?: 'settings' | 'plugin';+ /** Old errand-only plugins retain their original default until the user chooses a mode. */+ legacyDefault?: boolean;}) {const { t } = useTranslation();- const [config, setConfig] = useState<ErrandConfig>(- () => (window.electronAPI.ghosts.errandPrefsSync(ghostId).config ?? {}) as ErrandConfig,+ const [config, setConfig] = useState<TaskConfig>(+ () => (window.electronAPI.ghosts.errandPrefsSync(ghostId).config ?? {}) as TaskConfig,);- // 跟随态的展示值实时来自草稿偏好(useNewMakerDraft 订阅变更):用户在- // 草稿页换了模型,这里的「跟随默认」立刻显示新值——所见即将用。+ // This previews panel creation. Calls from a task use its current route.const draft = useNewMakerDraft();+ const [error, setError] = useState<string | null>(null);+ const [saving, setSaving] = useState(false);const save = useCallback(- async (next: ErrandConfig) => {+ async (next: TaskConfig) => {const prev = config;+ setError(null);+ setSaving(true);setConfig(next);try {const result = await window.electronAPI.ghosts.setErrandConfig(ghostId,next as Record<string, unknown>,);- setConfig((result.config ?? {}) as ErrandConfig);+ setConfig((result.config ?? {}) as TaskConfig);return true;- } catch {+ } catch (cause) {setConfig(prev);- toast.error(t('settings.ghosts.errors.generic'));+ setError(extractIpcError(cause)?.message || t('settings.ghosts.errors.generic'));return false;- }+ } finally { setSaving(false); }},[config, ghostId, t],);- // 展示口径:钉住的值优先,没钉的跟随草稿(vendor → 该 vendor 的草稿模型- // → 该模型的 per-model effort/fast 记忆)。- // 跟随模型取 lastByVendor[vendor].model —— 与新建对话展示的当前模型同一份(sanitize- // 保证非空,种子默认兜底)。不能用 getPersistedVendorModel:那是调度专用的严格口径,- // 仅当用户在新建对话里显式选过该 vendor 模型才返回,否则返回 '',会让 trigger 落到- // 「选择模型」占位(2026-07-31 Lizi 反馈:应像草稿一样直接显示当前模型)。const followVendor: 'cc' | 'codex' | 'pi' =draft.vendor === 'pi' ? 'pi' : draft.vendor === 'codex' ? 'codex' : 'cc';const vendor: 'cc' | 'codex' | 'pi' = config.agentKind ?? followVendor;const pickerAgents = useModelPickerAgents(vendor === 'cc' ? 'claude-code' : vendor);+ const customized = [config.agentKind, config.model, config.providerId, config.effort, config.fastMode]+ .some(value => value !== undefined);+ const shownProvider = config.providerId ?? draft.lastByVendor[vendor]?.providerId ?? null;const shownModel = config.model ?? draft.lastByVendor[vendor].model;- const shownEffort = (config.effort ??+ const routeEffort = customized ? config.effort : draft.lastByVendor[vendor]?.effort;+ const shownEffort = (routeEffort ??getEffortForModel(shownModel) ??- draft.lastByVendor[vendor]?.effort ??'high') as Effort;const shownFast = config.fastMode ?? getFastModeForModel(shownModel);+ const permissionMode = config.permissionMode ?? (legacyDefault ? 'plan' : 'ask');const pickWorkingDir = async (): Promise<void> => {const result = await window.electronAPI.showOpenDirectoryDialog();@@ -124,7 +109,7 @@ export function GhostErrandPrefs({);return (- <div+ <fieldset disabled={saving}className={cn('ghost-errand-prefs min-w-0 max-w-full flex flex-col gap-3 rounded-xl border px-5 py-4',appearance === 'plugin'@@ -149,49 +134,60 @@ export function GhostErrandPrefs({appearance === 'plugin' ? 'text-13 leading-5' : 'text-12',)}>- {t('settings.ghosts.detail.errandPrefs.desc')}+ {t(`settings.ghosts.detail.errandPrefs.${legacyDefault ? 'legacyDesc' : 'desc'}`)}</p>{/* 模型选择器占满整行(标题在上、控件 w-full 在下,与 IM 默认配置同款):field 形态的面板宽度绑定 trigger 宽度(DESIGN.md §4),压到 60% 会让下拉窄到把模型名截断,所以这里给它整行宽度。 */}<div className="flex min-w-0 flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <span className="text-12 leading-4 text-[var(--text-secondary)]">+ {t(`settings.ghosts.detail.errandPrefs.${customized ? 'sourceCustom' : 'sourceDefault'}`)}+ </span>+ {customized ? <Button type="button" variant="secondary" tone="quiet" size="sm" disabled={saving}+ onClick={() => save({ permissionMode: config.permissionMode, workingDir: config.workingDir })}>+ {t('settings.ghosts.detail.errandPrefs.restoreModel')}+ </Button> : null}+ </div><span className={labelCls}>{t('settings.ghosts.detail.errandPrefs.model')}</span><ModelSelector+ disabled={saving}unifiedAgents={pickerAgents}onUnifiedSelect={({ engine, providerId, modelId, effort, fast }) => save({...config,agentKind: engine,providerId,model: modelId,- effort: ERRAND_EFFORTS.has(effort ?? '') ? effort : undefined,+ effort: TASK_EFFORTS.has(effort ?? '') ? effort : undefined,fastMode: fast,})}modelId={shownModel}effort={shownEffort}fastMode={shownFast}vendorKey={vendor}- currentProviderId={config.providerId ?? null}+ currentProviderId={shownProvider}triggerVariant="field"popoverSide="bottom"ariaContext={t('settings.ghosts.detail.errandPrefs.model')}onModelChange={(modelId) =>// 选模型即整组钉住(agent 一起钉,防草稿随后换 vendor 让模型悬空)。- save({ ...config, agentKind: vendor, model: modelId, effort: undefined })+ save({ ...config, agentKind: vendor, providerId: shownProvider ?? undefined, model: modelId, effort: undefined, fastMode: false })}onEffortChange={(effort) => {- if (!ERRAND_EFFORTS.has(effort)) return;- return save({ ...config, agentKind: vendor, model: shownModel, effort });+ if (!TASK_EFFORTS.has(effort)) return;+ return save({ ...config, agentKind: vendor, providerId: shownProvider ?? undefined, model: shownModel, effort, fastMode: shownFast });}}onFastModeChange={(enabled) =>- save({ ...config, agentKind: vendor, model: shownModel, fastMode: enabled })+ save({ ...config, agentKind: vendor, providerId: shownProvider ?? undefined, model: shownModel,+ effort: TASK_EFFORTS.has(routeEffort ?? '') ? routeEffort : undefined, fastMode: enabled })}onProviderChange={(providerId, modelId, reconciledEffort, reconciledFast) =>save({...config,agentKind: vendor,model: modelId ?? shownModel,- effort: ERRAND_EFFORTS.has(reconciledEffort ?? '')+ effort: TASK_EFFORTS.has(reconciledEffort ?? '')? reconciledEffort: undefined,providerId: providerId ?? undefined,@@ -201,15 +197,18 @@ export function GhostErrandPrefs({/></div>+ {error ? <p role="alert" className="text-12 leading-5 text-[var(--text-secondary)]">{error}</p> : null}+{row('permission',<PermissionSelector- permissionMode={config.permissionMode ?? 'plan'}+ disabled={saving}+ permissionMode={permissionMode}+ fallbackModeLabel={permissionMode === 'plan' ? t('settings.ghosts.detail.errandPrefs.legacyPermission') : undefined}vendorKey={vendor}triggerVariant="field"ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}disabledModes={{- ask: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),}}@@ -219,7 +218,7 @@ export function GhostErrandPrefs({if (!PERMISSION_ALLOWED.has(mode)) return;save({...config,- permissionMode: mode === 'plan' ? undefined : (mode as 'acceptEdits' | 'auto'),+ permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',});}}/>,@@ -260,6 +259,6 @@ export function GhostErrandPrefs({</Button></div>,)}- </div>+ </fieldset>);}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsxnew file mode 100644index 0000000000..9dd5b51ccb--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/PluginTaskPrefs.test.tsx@@ -0,0 +1,66 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { PluginTaskPrefs } from '../PluginTaskPrefs';++const state = vi.hoisted(() => ({ config: {} as Record<string, unknown>, save: vi.fn() }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/hooks/useAvailableAgents', () => ({ useModelPickerAgents: () => [] }));+vi.mock('@/state/newMakerDraft', () => ({+ useNewMakerDraft: () => ({ vendor: 'codex', lastByVendor: { codex: { model: 'gpt-6-astra', providerId: 'openai', effort: 'high' } } }),+ getEffortForModel: () => undefined, getFastModeForModel: () => false,+}));+vi.mock('@/components/new-chat/ModelSelector', () => ({ ModelSelector: (props: any) => (+ <>+ <button disabled={props.disabled} data-testid="model" onClick={() => props.onUnifiedSelect({ engine: 'codex', providerId: 'openai', modelId: 'chosen', effort: 'high', fast: false })}>+ {props.vendorKey}/{props.currentProviderId}/{props.modelId}+ </button>+ <button data-testid="fast" onClick={() => props.onFastModeChange(true)}>Fast</button>+ </>+) }));+vi.mock('@/components/new-chat/PermissionSelector', () => ({ PermissionSelector: (props: any) => (+ <button disabled={props.disabled} data-testid="permission" data-legacy-label={props.fallbackModeLabel}+ onClick={() => props.onPermissionModeChange('ask')}>{props.permissionMode}</button>+) }));++beforeEach(() => {+ state.config = {};+ state.save.mockReset().mockImplementation(async (_id, config) => ({ config }));+ (window as any).electronAPI = { ghosts: { errandPrefsSync: () => ({ config: state.config }), setErrandConfig: state.save } };+});+afterEach(cleanup);+it.each([undefined, 'medium'])('changing Fast preserves only the configured effort (%s), never the display fallback', async effort => {+ state.config = {agentKind:'codex',providerId:'openai',model:'configured-model',effort};+ render(<PluginTaskPrefs ghostId="plugin" />);+ fireEvent.click(screen.getByTestId('fast'));+ await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', {...state.config, fastMode:true}));+});+it('previews the complete current panel route and uses ordinary task permissions independently', () => {+ render(<PluginTaskPrefs ghostId="plugin" />);+ expect(screen.getByTestId('model').textContent).toBe('codex/openai/gpt-6-astra');+ expect(screen.getByTestId('permission').textContent).toBe('ask');+ expect(screen.getByText('settings.ghosts.detail.errandPrefs.sourceDefault')).toBeTruthy();+});+it('preserves legacy permissions until the user explicitly chooses an ordinary mode', async () => {+ render(<PluginTaskPrefs ghostId="plugin" legacyDefault />);+ expect(screen.getByTestId('permission').textContent).toBe('plan');+ expect(screen.getByTestId('permission').getAttribute('data-legacy-label')).toBe('settings.ghosts.detail.errandPrefs.legacyPermission');+ expect(state.save).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId('permission'));+ await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', { permissionMode: 'ask' }));+});+it('resetting the model preserves explicitly selected permissions and directory', async () => {+ state.config = { agentKind: 'codex', model: 'old', providerId: 'old-connection', permissionMode: 'auto', workingDir: '/selected' };+ render(<PluginTaskPrefs ghostId="plugin" />);+ fireEvent.click(screen.getByText('settings.ghosts.detail.errandPrefs.restoreModel'));+ await waitFor(() => expect(state.save).toHaveBeenCalledWith('plugin', { permissionMode: 'auto', workingDir: '/selected' }));+ expect(screen.getByTestId('model').textContent).toBe('codex/openai/gpt-6-astra');+});+it('shows actionable host validation errors and restores the saved selection', async () => {+ state.save.mockRejectedValue(new Error('[INVALID_PARAMS] 供应商未连接,请修复连接后重试'));+ render(<PluginTaskPrefs ghostId="plugin" />);+ fireEvent.click(screen.getByTestId('model'));+ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('修复连接'));+ expect(screen.getByTestId('model').textContent).toBe('codex/openai/gpt-6-astra');+ expect((screen.getByTestId('model') as HTMLButtonElement).disabled).toBe(false);+});diff --git a/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx b/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsxindex a8f3378bf4..e638821bdb 100644--- a/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx@@ -53,6 +53,8 @@ interface PermissionSelectorProps {disabledModes?: Partial<Record<PermissionMode, string>>;/** Restrict the shared picker to a smaller product-approved subset. */allowedModes?: readonly PermissionMode[];+ /** Show a retained legacy value honestly instead of presenting the first available mode as selected. */+ fallbackModeLabel?: string;}/**@@ -114,6 +116,7 @@ export function PermissionSelector({ariaContext,disabledModes,allowedModes,+ fallbackModeLabel,}: PermissionSelectorProps) {const { t } = useTranslation();const [open, setOpen] = useState(false);@@ -127,7 +130,7 @@ export function PermissionSelector({(option) => allowedModes === undefined || allowedModes.includes(option.id),);const effectiveMode =- options.length > 0 ? normalizeMode(permissionMode, options) : permissionMode;+ options.length > 0 && !fallbackModeLabel ? normalizeMode(permissionMode, options) : permissionMode;const current = options.find((o) => o.id === effectiveMode);const TriggerIcon = PERMISSION_ICONS[effectiveMode] ?? Hand;const triggerTone = getModeTone(effectiveMode);@@ -143,7 +146,7 @@ export function PermissionSelector({defaultValue: option?.description ?? '',});};- const triggerLabel = labelOf(current, effectiveMode);+ const triggerLabel = !current && fallbackModeLabel ? fallbackModeLabel : labelOf(current, effectiveMode);const triggerDescription = descriptionOf(current, effectiveMode);const isCreateAgentVariant = visualVariant === 'create-agent';const isFieldTrigger = triggerVariant === 'field';diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 41ce65df0d..3f5f984b49 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -30,7 +30,7 @@ import { useTranslation } from 'react-i18next';import { CindyCapabilityPrefs } from '@/cindy-brain/CindyCapabilityPrefs';import { GhostLibrarySection } from './GhostLibrarySection';-import { GhostErrandPrefs } from '@/cindy-brain/GhostErrandPrefs';+import { PluginTaskPrefs } from '@/cindy-brain/PluginTaskPrefs';import { GhostSettingsWebview } from '@/cindy-brain/GhostSettingsWebview';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import {@@ -155,7 +155,7 @@ export function GhostPluginDetailView({detail.hasSettingsUi ||detail.hostCapability === 'ios-simulator' ||cindyCapabilities.length > 0 ||- detail.hasErrand;+ detail.hasTaskPreferences;const summary = hasGithubConnection? t('ccAgent.gitContext.pr.setup.account.summary'): ghostPluginSummary(detail.description, detail.id);@@ -522,8 +522,9 @@ export function GhostPluginDetailView({appearance="plugin"/>) : null}- {detail.hasErrand ? (- <GhostErrandPrefs ghostId={detail.id} appearance="plugin" />+ {detail.hasTaskPreferences ? (+ <PluginTaskPrefs ghostId={detail.id} appearance="plugin"+ legacyDefault={ghost?.manifest.agent?.errand === true && !ghost.manifest.agent?.tasks && !ghost.manifest.workspace} />) : null}</div></section>diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex 54caeb2663..a393a9663b 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -157,7 +157,7 @@ const detail: GhostPluginDetail = {tools: [],hasSettingsUi: false,cindyCapabilities: [],- hasErrand: false,+ hasTaskPreferences: false,panelMinWidth: 320,installDir: '/tmp/cindy-brain/builtin.example',trust: {diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex 9e60051e69..42c54066e9 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -81,8 +81,8 @@ export interface GhostPluginDetail extends GhostPluginListItem {tools: readonly GhostToolDecl[];hasSettingsUi: boolean;cindyCapabilities: readonly string[];- /** 申请了派活取件(agent.errand)——详情页据此渲染宿主统一的「AI 代办」配置卡。 */- hasErrand: boolean;+ /** 新建普通任务的能力共用宿主「任务设置」,包含旧 errand 适配器。 */+ hasTaskPreferences: boolean;panelMinWidth: number | null;installDir: string | null;}@@ -314,7 +314,7 @@ export function toGhostPluginDetail(cindyCapabilities: PINNABLE_CINDY_CATEGORIES.flatMap((category) =>(manifest.cindy?.[category] ?? []).map((action) => `${category}.${action}`),),- hasErrand: manifest.agent?.errand === true || manifest.agent?.tasks === true,+ hasTaskPreferences: !!manifest.workspace || manifest.agent?.errand === true || manifest.agent?.tasks === true,panelMinWidth: manifest.panel ? (manifest.panel.minWidth ?? 280) : null,installDir: ghost.dir,};diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 89edb7a5d5..5d69b4a8ed 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5501,8 +5501,8 @@"agentTasksRequest": "Review task permission","agentTasks": "Can create and manage its own Cindy tasks","agentTasksDetail": "Can send messages, read results and stop its own executions. Tasks remain visible to you. Uses this plugin’s AI settings and may incur model charges; does not grant access to other tasks.",- "agentErrand": "Can hand tasks to the Cindy Agent and collect the result",- "agentErrandDetail": "Tasks run in this plugin's dedicated session, always visible in the sidebar and stoppable at any time. Read-only by default; raising the level requires your change in the plugin settings. Model charges may apply.",+ "agentErrand": "Create tasks, perform work, and read results",+ "agentErrandDetail": "Created tasks appear in Cindy’s task list, where you can view progress and continue the conversation.","agentSchedule": "Can ask you to create an automation","agentScheduleDetail": "It can only open the new-automation panel with the fields filled in; whether it is created is up to you — pick a model and save it yourself. Once created, Cindy runs it on the schedule you set. Model charges may apply.","nodeRuntime": "Can run a bundled Node program on this computer",@@ -5641,16 +5641,21 @@"noModels": "No models available"},"errandPrefs": {- "title": "AI errands",- "desc": "How this plugin's tasks run when it hands work to the Cindy Agent. Unset fields follow your new-draft preferences; the helper is read-only by default and works in a dedicated folder.",+ "title": "Task settings",+ "desc": "For tasks created by this plugin. New tasks use the originating task’s model, or the current new-task selection when created from a panel. Existing tasks keep their own model. Permissions are set separately and use ordinary task defaults. Full access is never inherited.",+ "legacyDesc": "For tasks created by this plugin. New tasks use the originating task’s model, or the current new-task selection when created from a panel. Existing tasks keep their own model. The legacy API retains its original permissions until you explicitly choose a mode.",+ "legacyPermission": "Keep original permissions","agent": "Agent","model": "Model","permission": "Write access",- "permissionDisabled": "Not available for errand sessions",+ "permissionDisabled": "This permission mode is unavailable to plugins","workdir": "Working folder","workdirDefault": "Plugin's dedicated folder (default)","workdirPick": "Choose…",- "workdirClear": "Reset to default folder"+ "workdirClear": "Reset to default folder",+ "sourceDefault": "Follow the originating task; panel default shown below",+ "sourceCustom": "Use the model selected for this plugin",+ "restoreModel": "Reset model"},"toolsTitle": "Tools","permissionsTitle": "Permissions",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7fe06051f1..6117443ee7 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5500,8 +5500,8 @@"agentTasksRequest": "セッション権限を確認","agentTasks": "このプラグインの Cindy セッションを作成・管理できます","agentTasksDetail": "メッセージの送信、結果の読み取り、自身の実行の停止ができます。セッションはユーザーに表示されます。プラグインの AI 設定を使用し、モデル料金が発生する場合があります。他のセッションへのアクセスは許可されません。",- "agentErrand": "Cindy Agent にタスクを任せて結果を受け取れます",- "agentErrandDetail": "タスクはこのプラグイン専用のセッションで実行され、サイドバーから常に確認・停止できます。既定では読み取り専用で、権限の引き上げはプラグイン設定であなた自身が行う必要があります。モデル料金が発生する場合があります。",+ "agentErrand": "タスクを作成し、作業を実行して結果を取得できます",+ "agentErrandDetail": "作成したタスクは Cindy のタスク一覧に表示され、進行状況を確認して会話を続けられます。","agentSchedule": "自動化の新規作成をあなたに依頼できます","agentScheduleDetail": "できるのは内容が入力済みの新規自動化パネルを開くことだけで、作成するかどうかはあなたがモデルを選んで自分で保存して決めます。作成後は Cindy があなたの設定した時間に実行します。モデル料金が発生する場合があります。","nodeRuntime": "同梱された Node プログラムをこのコンピューターで実行できます",@@ -5640,16 +5640,21 @@"noModels": "利用可能なモデルなし"},"errandPrefs": {- "title": "AI 代行",- "desc": "このプラグインが Cindy Agent にタスクを任せるときの実行設定です。未設定の項目は新規ドラフトの選択に従います。既定では読み取り専用で、専用フォルダー内で作業します。",+ "title": "タスク設定",+ "desc": "このプラグインが作成するタスクの設定です。新規タスクは呼び出し元のモデルを使い、パネルから作成する場合は現在の新規タスクの選択を使います。既存タスクのモデルは維持されます。権限は別途設定し、通常のタスクの既定権限を使います。フルアクセスは継承しません。",+ "legacyDesc": "このプラグインが作成するタスクの設定です。新規タスクは呼び出し元のモデルを使い、パネルから作成する場合は現在の新規タスクの選択を使います。既存タスクのモデルは維持されます。旧 API は元の権限を維持します。権限を選ぶと、その設定を使用します。",+ "legacyPermission": "元の権限を維持","agent": "Agent","model": "モデル","permission": "書き込み権限",- "permissionDisabled": "代行セッションでは選べません",+ "permissionDisabled": "プラグインではこの権限を選べません","workdir": "作業フォルダー","workdirDefault": "プラグイン専用フォルダー(既定)","workdirPick": "選択…",- "workdirClear": "既定のフォルダーに戻す"+ "workdirClear": "既定のフォルダーに戻す",+ "sourceDefault": "呼び出し元に従う(下はパネル作成時のモデル)",+ "sourceCustom": "このプラグイン用に選択したモデル",+ "restoreModel": "モデルをリセット"},"toolsTitle": "Tools","permissionsTitle": "権限",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 4a6ad670b4..e69f25d19d 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5500,8 +5500,8 @@"agentTasksRequest": "세션 권한 확인","agentTasks": "이 플러그인의 Cindy 세션을 만들고 관리할 수 있음","agentTasksDetail": "메시지를 보내고 결과를 읽으며 자신의 실행을 중지할 수 있습니다. 세션은 사용자에게 표시됩니다. 플러그인의 AI 설정을 사용하며 모델 비용이 발생할 수 있습니다. 다른 세션에 대한 접근 권한은 부여하지 않습니다.",- "agentErrand": "Cindy Agent에게 작업을 맡기고 결과를 받아올 수 있음",- "agentErrandDetail": "작업은 이 플러그인 전용 세션에서 실행되며, 사이드바에서 언제든 확인하고 중단할 수 있습니다. 기본은 읽기 전용이며, 권한 상향은 플러그인 설정에서 직접 해야 합니다. 모델 비용이 발생할 수 있습니다.",+ "agentErrand": "작업을 만들고 실행하며 결과를 읽을 수 있습니다",+ "agentErrandDetail": "생성된 작업은 Cindy 작업 목록에 표시되며 진행 상황을 확인하고 대화를 이어갈 수 있습니다.","agentSchedule": "자동화 새로 만들기를 요청할 수 있음","agentScheduleDetail": "내용이 미리 채워진 자동화 만들기 패널을 여는 것만 할 수 있으며, 실제로 만들지는 사용자가 모델을 고르고 직접 저장해 결정합니다. 만든 뒤에는 Cindy가 설정한 시간에 실행합니다. 모델 비용이 발생할 수 있습니다.","nodeRuntime": "함께 제공된 Node 프로그램을 이 컴퓨터에서 실행할 수 있음",@@ -5640,16 +5640,21 @@"noModels": "사용 가능한 모델 없음"},"errandPrefs": {- "title": "AI 대행",- "desc": "이 플러그인이 Cindy Agent에게 작업을 맡길 때 사용하는 실행 설정입니다. 설정하지 않은 항목은 새 초안 선택을 따르며, 기본은 읽기 전용이고 전용 폴더에서 작업합니다.",+ "title": "작업 설정",+ "desc": "이 플러그인이 만드는 작업의 설정입니다. 새 작업은 호출한 작업의 모델을 사용하며, 패널에서 만들면 현재 새 작업의 선택을 사용합니다. 기존 작업은 자신의 모델을 유지합니다. 권한은 별도로 설정하며 일반 작업의 기본 권한을 사용합니다. 전체 접근 권한은 상속하지 않습니다.",+ "legacyDesc": "이 플러그인이 만드는 작업의 설정입니다. 새 작업은 호출한 작업의 모델을 사용하며, 패널에서 만들면 현재 새 작업의 선택을 사용합니다. 기존 작업은 자신의 모델을 유지합니다. 기존 API는 원래 권한을 유지합니다. 권한을 선택하면 해당 설정을 사용합니다.",+ "legacyPermission": "기존 권한 유지","agent": "Agent","model": "모델","permission": "쓰기 권한",- "permissionDisabled": "대행 세션에서는 선택할 수 없음",+ "permissionDisabled": "플러그인은 이 권한을 사용할 수 없습니다","workdir": "작업 폴더","workdirDefault": "플러그인 전용 폴더(기본)","workdirPick": "선택…",- "workdirClear": "기본 폴더로 되돌리기"+ "workdirClear": "기본 폴더로 되돌리기",+ "sourceDefault": "호출한 작업 따르기 · 아래는 패널의 기본 모델",+ "sourceCustom": "이 플러그인용으로 선택한 모델 사용",+ "restoreModel": "모델 초기화"},"toolsTitle": "Tools","permissionsTitle": "권한",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex cfa69ebfeb..f5fdec1947 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5500,8 +5500,8 @@"agentTasksRequest": "确认任务权限","agentTasks": "可创建和管理本插件的 Cindy 任务","agentTasksDetail": "可发送消息、读取结果和停止本插件的执行,任务对你可见。沿用插件的 AI 配置,可能产生模型费用;不授予其他任务的访问权。",- "agentErrand": "可把任务交给 Cindy Agent 代办并取回结果",- "agentErrandDetail": "这些代办会在这个插件的专属任务里进行,你随时可以在侧边栏看到并叫停;默认只能读不能改,要放开需你在插件配置里亲手调整,可能产生模型费用。",+ "agentErrand": "可以新建任务、执行工作并读取结果",+ "agentErrandDetail": "创建的任务会出现在 Cindy 的任务列表中,可以查看过程并继续交流。","agentSchedule": "可以请你新建自动化","agentScheduleDetail": "它只能为你打开新建自动化的面板并把内容填好,是否创建由你在面板上选好模型后亲手保存决定。创建后由 Cindy 按你设定的时间运行,可能产生模型费用。","nodeRuntime": "可在本机运行随插件附带的 Node 程序",@@ -5640,16 +5640,21 @@"noModels": "暂无可用模型"},"errandPrefs": {- "title": "AI 代办",- "desc": "这个插件把任务交给 Cindy Agent 时用哪套配置干活。不配就跟随你新建草稿时的选择;帮工默认只能看不能改,工作目录默认是插件专属文件夹。",+ "title": "任务设置",+ "desc": "用于插件创建的任务。默认沿用发起任务的模型;从面板新建时使用当前新任务选择。已有任务保留自己的模型。权限独立设置,默认使用普通任务的默认权限,不继承完全访问。",+ "legacyDesc": "用于插件创建的任务。默认沿用发起任务的模型;从面板新建时使用当前新任务选择。已有任务保留自己的模型。旧接口保留原有权限行为;选择权限后按你的设置执行。",+ "legacyPermission": "保留原权限设置","agent": "Agent","model": "模型","permission": "动手权限",- "permissionDisabled": "派活时不提供这一档",+ "permissionDisabled": "插件不能使用这一档权限","workdir": "工作目录","workdirDefault": "插件专属文件夹(默认)","workdirPick": "选择…",- "workdirClear": "恢复默认目录"+ "workdirClear": "恢复默认目录",+ "sourceDefault": "跟随发起任务;下方预览面板新建模型",+ "sourceCustom": "使用为此插件选择的模型",+ "restoreModel": "恢复默认模型"},"toolsTitle": "Tools","permissionsTitle": "权限",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 6224bd5376..54f83be2e1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -5500,8 +5500,8 @@"agentTasksRequest": "確認任務權限","agentTasks": "可建立和管理本插件的 Cindy 任務","agentTasksDetail": "可傳送訊息、讀取結果和停止本插件的執行,任務對你可見。沿用插件的 AI 配置,可能產生模型費用;不授予其他任務的存取權。",- "agentErrand": "可把任務交給 Cindy Agent 代辦並取回結果",- "agentErrandDetail": "這些代辦會在這個插件的專屬任務裡進行,你隨時可以在側邊欄看到並叫停;預設只能讀不能改,要放開需你在插件配置裡親手調整,可能產生模型費用。",+ "agentErrand": "可建立任務、執行工作並讀取結果",+ "agentErrandDetail": "建立的任務會顯示在 Cindy 任務列表中,可查看過程並繼續交流。","agentSchedule": "可以請你新建自動化","agentScheduleDetail": "它只能為你開啟新建自動化的面板並把內容填好,是否建立由你在面板上選好模型後親手儲存決定。建立後由 Cindy 按你設定的時間執行,可能產生模型費用。","nodeRuntime": "可在本機執行隨插件附帶的 Node 程式",@@ -5640,16 +5640,21 @@"noModels": "暫無可用模型"},"errandPrefs": {- "title": "AI 代辦",- "desc": "這個插件把任務交給 Cindy Agent 時用哪套配置幹活。不配就跟隨你新建草稿時的選擇;幫工預設只能看不能改,工作目錄預設是插件專屬資料夾。",+ "title": "任務設定",+ "desc": "用於插件建立的任務。預設沿用發起任務的模型;從面板新建時使用目前的新任務選擇。已有任務保留自己的模型。權限獨立設定,預設使用一般任務的預設權限,不繼承完全存取。",+ "legacyDesc": "用於插件建立的任務。預設沿用發起任務的模型;從面板新建時使用目前的新任務選擇。已有任務保留自己的模型。舊介面保留原有權限行為;選擇權限後依你的設定執行。",+ "legacyPermission": "保留原權限設定","agent": "Agent","model": "模型","permission": "動手權限",- "permissionDisabled": "派活時不提供這一檔",+ "permissionDisabled": "插件不能使用此權限","workdir": "工作目錄","workdirDefault": "插件專屬資料夾(預設)","workdirPick": "選擇…",- "workdirClear": "恢復預設目錄"+ "workdirClear": "恢復預設目錄",+ "sourceDefault": "跟隨發起任務;下方預覽面板新建模型",+ "sourceCustom": "使用為此插件選擇的模型",+ "restoreModel": "還原預設模型"},"toolsTitle": "Tools","permissionsTitle": "權限",diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 2688b1c0a9..8d8248a778 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -6282,11 +6282,11 @@ export const GHOST_ERRAND_MIN_INTERVAL_MS = 10_000;export const GHOST_ERRAND_SESSION_KEY_RE = /^[A-Za-z0-9._-]{1,64}$/;/**- * errand 会话允许的权限档。plan = 只读默认档;acceptEdits / auto 由用户在- * 插件详情页显式放开。**bypassPermissions 刻意不在此列**(2026-07-31 定案:+ * 插件创建普通任务使用 ask;plan 仅保留旧配置兼容,其执行语义由原 Agent 决定。+ * acceptEdits / auto 由用户显式选择。**bypassPermissions 刻意不在此列**(2026-07-31 定案:* 被骗的插件配上不设防会话 = 无人看守的用户全权,风险不可接受)。*/-export const GHOST_ERRAND_PERMISSION_MODES = ['plan', 'acceptEdits', 'auto'] as const;+export const GHOST_ERRAND_PERMISSION_MODES = ['ask', 'plan', 'acceptEdits', 'auto'] as const;export type GhostErrandPermissionMode = (typeof GHOST_ERRAND_PERMISSION_MODES)[number];/** 上行:派活提交与取件查询。 */@@ -6311,7 +6311,7 @@ export type GhostPipeAgentErrandRequest =* 可选:请求把 errand 会话建在这个目录(绝对路径,≤1024 字符)。* 只是**转述**,不是授权——主机只认用户此前在 pick 槽系统窗口里* 亲手选过的目录(pickGrantsStore 台账);台账里没有 → INVALID_REQUEST。- * 用户在「AI 代办」卡里配置了工作目录时以用户配置优先,本字段忽略。+ * 用户在「任务设置」卡里配置了工作目录时以用户配置优先,本字段忽略。*/workingDir?: string;/**diff --git a/apps/desktop/src/shared/pluginTasks.ts b/apps/desktop/src/shared/pluginTasks.tsindex c137b348ed..541ce4d2a9 100644--- a/apps/desktop/src/shared/pluginTasks.ts+++ b/apps/desktop/src/shared/pluginTasks.ts@@ -57,10 +57,13 @@ export function isPluginTeamPlanWithinBudget(plan: unknown): boolean {} catch { return false; }}export type PluginTaskRequest =- | { type: 'tasks-request'; kind: 'capabilities' }+ | { type: 'tasks-request'; kind: 'capabilities' | 'models' }+ | { type: 'tasks-request'; kind: 'setModel'; taskId: string; expectedRevision: number; route: PluginTaskRoute }| {type: 'tasks-request';kind: 'create';+ /** Optional active tool-call context; Host resolves its task and checks plugin ownership. */+ callId?: string;requestKey: string;title: string;route?: PluginTaskRoute;diff --git a/apps/desktop/src/shared/utilityModelProfiles.ts b/apps/desktop/src/shared/utilityModelProfiles.tsindex 52a4f080c3..aa09ab24d8 100644--- a/apps/desktop/src/shared/utilityModelProfiles.ts+++ b/apps/desktop/src/shared/utilityModelProfiles.ts@@ -198,7 +198,7 @@ function normalizeTokenCount(value: number | undefined): number {** 与图像/视频的"钉后端"同一口径:每一项就是一组**供应商 × 模型**。这里带上* 传输通道当后缀——`gpt-5.4-mini` 同时经 Codex 订阅和网关提供,只写模型名会- * 出现两行同名项、用户选不中(GhostErrandPrefs 踩过同一个坑)。后缀用中立的+ * 出现两行同名项、用户选不中(PluginTaskPrefs 踩过同一个坑)。后缀用中立的* 通道名而非中文,避免在 shared 层塞 UI 文案。*/export function utilityModelPinOptions(): Array<{ id: string; label: string }> {diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex f4dc4f81d4..33f91bd961 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -357,15 +357,28 @@- `network.secrets[].url` 可由 Host 作为 Setup 字段旁的辅助获取入口展示。该地址必须继续满足 manifest 安装期的 `https`、无内嵌凭证校验;它不是 Agent 文案或 plan的一部分,插件也不能通过 `settings.js` 动态替换 Setup 卡地址。-- 模型调用一律走 Cindy 统一通道,不允许插件自建绕过通道的推理请求。两条 AI 代办- 通道的固定边界(2026-07-31 定案,主机代码强制):- - 快问快答(`cindy.text.oneshot`)只走主机轻量任务模型链,无 agent、无工具、- 不进会话;选型不在插件手里,链上无候选时返回结构化 `NO_CANDIDATE`。- - 派活取件(`agent.errand`)的任务文本**只进普通 user 消息、绝不进 system- prompt**;errand 会话侧边栏可见、可旁观可叫停;agent/模型/权限档/工作- 目录全部由用户在插件详情页配置,权限档只有 `plan`(默认)/`acceptEdits`/- `auto` 三档,**`bypassPermissions` 在协议层就不存在**,不得以任何形式放开;- 工作目录缺省为插件专属对话目录,指向真实项目必须由用户亲手选择。+- 模型调用一律走 Cindy 统一通道,不允许插件自建绕过通道的推理请求。+- 插件是沙箱小程序,不等于 AI 代办。模型与任务相关能力必须分别描述:+ - 快问快答(`cindy.text.oneshot`)不创建任务、没有 Agent 工具;沿用其统一轻量模型通道。+ - `agent.run` 承接已有用户任务的继续/新建/分叉,保留原任务的交互与权限语义;+ 真实点击票/后台关联授权不因共用模型校验而扩大。+ - `cindy.tasks` 创建并管理插件自己的普通任务,有独立的 tasks 声明、批准与持久回执;+ 不依赖旧 errand 权限,不把任务完成等同于取到一段文本。+ - `workspace.ensureSession` 只定位/创建工作区任务入口;不因创建入口就自动执行模型。+ - `agent.errand` 是旧的派活取件适配器,保留专属任务映射与结果回传,不作为其它能力的产品抽象。+- 用户界面、Agent 工具、伙伴和插件的新建任务共用普通 Session 创建入口。伙伴的完成回报、+ 时间线与信号留在伙伴层;插件按需查询结果,不默认唤醒伙伴或另一个 Agent。+- 插件详情「任务设置」是插件新建任务的共用偏好,普通任务、工作区新建与旧 errand 使用+ 同一配置。显式完整模型组合优先;缺省从宿主验证的发起任务继承,面板无发起任务则使用+ 当前新任务的完整选择,不优先翻找 Claude Code 的历史草稿。模型选择不授予权限或目录。+ 保存、新建和插件派发前复用普通独立任务的模型/供应商/Agent 准入,不另建目录或选择器。+ 连接状态不等于额度、网络及远端参数一定可用;执行失败如实返回,不静默换型号或账号。+- 插件新建普通任务的权限仅来自用户的插件设置或既有宿主确认流程,默认普通任务的 `ask`,允许+ 用户显式选择 `acceptEdits`/`auto`,不新增 `bypassPermissions`;不继承发起任务的权限。+ 旧 errand 适配器保留历史缺省 `plan` 与原 Agent 行为;已有任务及显式历史设置不自动改权。+ 不把历史 `plan` 值宣称为跨 Agent 的只读保证,也不为它改造各 Agent 的权限引擎。+ 旧存储文件名、键及 IPC 保持兼容,升级不丢配置、不重批权限。来源优先级、复用和恢复+ 详见 [插件普通任务接口](plugin-task-api-implementation.md#模型配置与创建来源)。- 附件、媒体、目录和保存路径通过归属校验后的 grant/deposit/ledger 交接,**禁止把宿主绝对路径或不必要的字节暴露给沙箱**。媒体字节须走[`media-storage-and-protocols.md`](media-storage-and-protocols.md) 的统一入库。diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 2a404c7ce7..e5b741778f 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -1,10 +1,141 @@-# 插件普通任务接口:第一阶段实现+# 插件调用普通任务(Session)状态:实验接口,尚未发布。入口为插件逻辑页 `cindy.tasks`,声明 `agent.tasks: true` 后由既有插件权限流程确认。存量 `errand` 声明不自动获得此权限。+## 新建任务、继续任务与读取结果++插件调用的是 Cindy 普通任务(Session)能力。界面、工具说明和文档统一使用「新建任务」「打开任务」「继续任务」,不另设 AI 代办或插件专属任务概念。++| 作者要实现的事情 | 使用方式 | 是否创建新任务/自动回叫 |+| --- | --- | --- |+| 当前任务正在用你的工具,只需读写稿件或业务数据 | 工具直接返回数据,由当前 Agent 继续工作 | 不新建,不回叫 |+| 用户在稿件、批注面板中提交新的修改意见 | `cindy.agent.run({mode: 'continue', ...})`,走原有点击票或已关联任务授权 | 继续原任务,不另开任务 |+| 独立完成一项工作,需要单独的历史与模型 | `cindy.tasks.create(...)`,随后 `cindy.tasks.send(...)` | 创建普通任务;创建本身不启动模型 |+| 再给同一项工作追加要求 | 保存 taskId;`get` 获取最新 revision,再 `send` | 保留同一任务与历史 |+| 查询进度/完成后更新插件页面 | `getRun` / `listRuns`,完成后 `readMessages` | 查询状态和结果,不唤醒任何伙伴或 Agent |+| 只需一次短文本结果,无工具、无任务历史 | 原有 `cindy.text.oneshot` | 使用现有轻量模型通道,不创建任务 |++伙伴任务完成后向伙伴自己的时间线回报,是伙伴的业务流程。插件新建任务不默认附带该流程;+普通任务创建入口不发送完成回叫。插件根据需要读取回执和结果,无需模拟一个伙伴。+当前没有任务事件订阅接口,请查询持久回执;不要把「已创建」或「已接受输入」显示成「执行完成」。++### 作者使用示例++先声明 `agent.tasks: true`,按既有插件能力授权使用。面板按钮应转交逻辑页执行,不能访问宿主内部 IPC。++```js+const capabilities = await cindy.tasks.capabilities();+// 每个逻辑操作保存一个稳定 requestKey;重试沿用,不能每次生成新键。+const task = await cindy.tasks.create({+ requestKey: 'course:git:create', title: '学习 Git',+ // 处理在途工具调用时可传 callId,使用其发起任务的当前模型。+ // 面板直接点击省略 callId,使用 Cindy 当前的新任务选择。+});+// taskId 必须存到插件自己的业务记录里。新建成功并不表示模型已运行。+const run = await cindy.tasks.send({+ taskId: task.taskId, expectedRevision: task.revision,+ requestKey: 'course:git:first-input', text: '请生成 Git 第一课。',+});+const state = await cindy.tasks.getRun({ runId: run.runId });+if (state.status === 'completed') {+ const page = await cindy.tasks.readMessages({ taskId: task.taskId, limit: 50 });+ // 使用 outputMessageId 与消息游标读取本次结果,保存 nextCursor 后可继续分页。+}+```++需要显式选模时,使用现有统一目录的投影,不拼接供应商或型号:++```js+if (capabilities.operations.includes('models')) {+ const { models } = await cindy.tasks.models();+ // 让用户选择或按其明确偏好匹配 models 中的项,不擅自取第一项作为降级。+ // selected 是所选目录项;直接把 selected.route 传给 create 的 route。+}+// 已有任务要改模型,先 get 获取最新 revision,再调用:+// await cindy.tasks.setModel({taskId, expectedRevision: task.revision, route: selected.route});+// 遵循返回 status 和最新 get 的配置;运行中的切换可能推迟到安全边界。+```++`models` 与 `setModel` 是可发现的增量能力;调用前检查 `capabilities.operations`。+旧客户端不支持时显示不支持或使用当前任务选择,不自行调用私有 IPC。模型清单只包含宿主当前可选来源;+连接存在不等于远端凭证、配额和请求一定成功。保存、创建、发送/改模仍分别验证,错误应显示给用户,+允许恢复连接或明确改选同一任务的模型;不得自动改成另一型号、另一个账号或清掉历史后重建。++`setModel` 返回 `deferred` 时,当前执行仍按原模型完成,下一条输入才应用新组合。+任务 `resolvedConfig` 与 revision 表示宿主已接受的下一条输入配置;在切换实际生效前后保持+一致,避免先用旧模型登记发送回执、再因新模型生效而拒绝首条续发。读取历史不受切模影响。++### 宿主实现边界++`localDb/sessionOpening.openSession` 是普通新建任务的公共入口:模型准入、目录准备、Session 行构造与提交。+普通新建任务 UI、`send_to_session` 新建、伙伴普通任务、插件普通任务和工作区创建均使用该入口。+伙伴通过提交回调把 Session 与原有委派回执保存在同一个事务中;伙伴信号、卡片、超时及完成回报留在伙伴层。+插件继续使用自己的持久操作回执。公共入口不认识伙伴/插件身份,不创建回叫任务。+`sessionExecutionSelection` 复用普通模型能力及供应商校验;显式目录选项沿用 `appDefaultModelControl`。+已有任务改模复用 `sessionControlService`,不另造运行时或供应商选择器。++## 模型配置与创建来源++插件是小程序;普通任务 API、用户任务交互、快速调用和旧派活接口是不同能力。+共用的是普通 Session 的模型配置与可用性校验,不是 errand 的取件生命周期。++2026-10-01 确认的默认行为:新建任务沿用发起任务的模型;从面板直接新建时使用当前+新任务选择;用户可为插件单独覆盖。模型、Agent、供应商、推理强度和 Fast 作为完整组合+解析,绝不从另一 Agent 的历史草稿拼出一组值。权限独立设置,不随模型来源继承。++| 入口 | 模型来源与复用 | 权限与结果 |+| --- | --- | --- |+| `tasks.create` | 显式 route → 插件任务设置 → 经验证的 callId 发起任务 → 当前新任务选择;保存准入后的完整 route | 用户插件权限,默认普通任务的 ask;返回普通任务及持久创建回执 |+| `tasks.send` | 使用该任务当前 route,检查 revision 和当前可用性;不因新默认变化重建任务 | 复核插件归属与权限;结果使用逐输入 run 回执 |+| `agent.errand` | 共用模型解析;无显式覆盖时优先保留已有专属任务的当前模型。配置冲突时只在新任务创建成功后替换映射,旧历史保留 | 旧权限边界、sessionKey、jobId 与结果取回协议保持兼容 |+| `workspace.ensureSession` | 已有工作区入口照常复用;新建才使用插件设置/发起任务/当前新任务完整组合 | 目录仍经亲选或原有确认流程;只建入口、不运行 Agent |+| `agent.run` | 操作已有用户任务;本机任务校验其当前组合,远程任务交由执行宿主校验,继续/新建/分叉仍按原接口继承用户任务 | 保留原有点击票、任务关联和源权限限制;不套用插件自有任务权限或取件协议 |+| 快问快答/媒体生成 | 各自已有通道,不受任务默认配置支配 | 不变成普通任务或代办 |++`tasks.capabilities().sourceCallContext` 声明支持 create 的可选 `callId`。Agent 在处理+在途插件工具时可转传该调用 ID;宿主只接受同插件、本机、仍在途的归属,不接受插件+自报 sourceSessionId。失效来源且没有完整显式模型配置时拒绝创建,不悄悄改用面板默认。+面板直接创建省略 callId。旧客户端不支持该能力时不能发送新字段;旧插件无新字段的+创建请求保持兼容。来源字段参与新请求的幂等摘要;已有回执重放不重新读取过期调用。++设置页使用现有 ModelSelector/PermissionSelector,显示默认来源与面板模型预览。+选择模型时保存完整组合;「恢复默认模型」只清除模型覆盖,保留目录与权限。保存被拒时+恢复原选项并就地展示可操作原因。普通任务、工作区及旧 errand 插件均可见这份设置。+新普通任务缺省使用 `ask`,与所选 Agent 的普通任务一致;已有任务不因默认值变化改权。+旧 errand 缺省及显式 `plan` 配置保留原行为,设置页显示保留的权限而不冒充 `ask` 或+跨 Agent 的只读保证。用户明确选择普通权限后才覆盖旧值;完全访问不在可选范围。++`pluginTaskPrefsStore` 保留历史 `ghost-errand-prefs.json`、`errand` 与 `sessions` 键以及+既有 IPC 名;无需重装、重新授权或人工迁移。`sessions` 键只供旧 errand 映射使用。+`sessionExecutionSelection` 只处理来源组合,调用 `resolveSendToSessionExecutionConfig`+及实时已连接供应商快照,复用普通任务准入,不定义平行模型目录。++恢复路径:未就绪 Agent 则完成安装或改选;失效连接则修复供应商连接或明确改选;已有普通+任务在任务内修正模型后继续使用原历史。校验失败不创建任务、不投递首条消息、不自动换+廉价模型或其它账号。无推理档位模型使用空 effort,不凭空写 high。++### 2026-10-01 失败场景的证据边界++日志证明:旧 errand 在没有插件覆盖的情况下采用 Claude Code 的历史草稿,执行收到+API 400 / code 1210;该路径未做完整路由准入。不能由这一错误推断凭证失效。+Claude Code 适配层 `toSdkModelString` 会按目录窗口自动追加 `[1m]`;日志中的该后缀+不是用户保存了无效模型 ID 的证据,不能用简单拒绝带后缀 ID 的测试宣称修好了远端 400。++本次配置修复应分别验证来源选择、宿主准入以及真实 provider 推理。实时目录/已连接+快照能证明当前路由存在,不证明额度及远端参数有效。原失败请求的上游参数原因和新版+真实点击执行,在没有对应运行证据前继续标为未验证;不把单测、桥接替身或目录回放当作+已部署修复,也不重跑用户正在使用的学习任务。++隔离开发版的真实验收已覆盖:面板创建及 Astra 执行、同任务继续、Agent 经真实插件工具+发起创建、不可用供应商拒绝及明确选模恢复、旧 errand 执行并读取结果。补充验收确认:+面板默认 Sol 时工具调用仍继承 Astra;插件选择 Luna 后采用 Luna,单次指定 Astra 优先。+原任务切到 GPT-6.1-Sol 后返回 `MODEL_SWITCH_OK`,执行回执与实际模型一致,任务 ID 和+历史保留。新任务落库为 `ask`,与设置页「默认权限」一致;旧任务权限不随默认变化覆盖。+这些结果不证明原 GLM 请求的参数、凭证或配额有效;该供应商的 400 根因仍未验证。+## 已接入-- `capabilities/create/list/get/send/getRun/listRuns/readMessages/cancel`。+- `capabilities/models/create/list/get/setModel/send/getRun/listRuns/readMessages/cancel`。- create 可传 isolatedWorkspace:true,由宿主分配独立空作答目录;返回本任务 workingDir 与 permissionMode,插件不能覆盖权限。- 创建用户可见的普通本地 Session;工作目录及权限来自用户配置,不接受插件传入绕过权限、任意目录或另一插件身份。普通任务创建前复用 Worker 的目录身份判据:配置路径必须仍为原规范路径,改链、缺失或非目录拒绝;异步解析后复核账号、tasks 批准及配置。缺省/isolatedWorkspace 仍由宿主分配目录,旧 errand 路径不变。旧别名配置没有原目标证据,不自动授权当前目标;这不解决校验后的目录置换窗口。- 发送走普通输入协调器,使用持久 requestKey 去重和稳定输入 ID;重复请求不会再次启动模型。@@ -30,10 +161,10 @@## 当前限制与后续工作- 仅本插件创建的本地普通任务;不支持选择既有任务、远端任务或 Bot;自有普通任务可通过 startTeam 成为 Orca Lead。-- 尚未开放修改/归档任务、队列暂停、事件订阅、逐输入费用与用量。usage 明确返回 unavailable。+- 已支持通过 `setModel` 修改任务模型;尚未开放其它配置修改/归档任务、队列暂停、事件订阅、逐输入费用与用量。usage 明确返回 unavailable。- 回执已经持久化,但完整的重启后终态补账、无输入别名的自动续跑归属尚未闭环。缺少原生证据时返回 reconciling,不重放请求、不报告成功;目前不应作为无人值守正式评测的完成依据。- 一旦 Session INSERT 已开始、创建进程中断或回执撤回失败,结果仍可能不明:保留回执,重放只读取已存在任务,不补建,可能返回 TASK_NOT_FOUND。旧孤立回执没有本次失败证据,不自动修复;已删除任务不复活、已撤销任务及旧 key 不接管。此限制与创建前明确失败后的显式重试不同。-- 无推理档位的模型暂不支持;不支持的 route 明确拒绝。+- 无推理档位的模型以空 effort 表示;显式提供不支持的档位仍拒绝。- cancel 的 requestKey 当前不建立独立账本;同一 run 的终态保持幂等,进行中的重复取消仍可能再次请求原生停止。- 评测插件已接入此接口;实际 UI 联调结果另记,未自动启动付费模型。