Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 插件 workspace 槽——为项目目录创建/复用侧边栏会话入口 (#414)
Lizi90244ed6324f
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.tsindex 80e5462d8d..d49276bc79 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts@@ -302,6 +302,20 @@ describe('withCardToken(令牌注入纯函数)', () => {result: [1],});});++ it('inFlightCallInfoOf 只认真正在途:交卷/重开/查无一律 null(workspace 凭证语义)', () => {+ const { svc } = makeService();+ svc.registerCall('c1', { ghostId: 'g1', toolUseId: null, sessionId: 's1' });+ expect(svc.inFlightCallInfoOf('c1')).toEqual({ ghostId: 'g1', sessionId: 's1' });+ // 交卷后:宽限窗内 callInfoOf 仍可查(卡片供片语义),但在途凭证必须失效。+ svc.finalizeCall('c1');+ expect(svc.callInfoOf('c1')).not.toBeNull();+ expect(svc.inFlightCallInfoOf('c1')).toBeNull();+ // 重开态(card-action 换卡窗口)同样不是工具调用在途,不发凭证。+ svc.reopenForAction('c1', { ghostId: 'g1', sessionId: 's1' });+ expect(svc.inFlightCallInfoOf('c1')).toBeNull();+ expect(svc.inFlightCallInfoOf('nope')).toBeNull();+ });});describe('parseCardHeightReport(report-height IPC 校验 + clamp 纯函数)', () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 0a70f4c734..2c4992fe86 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -476,13 +476,19 @@ describe('FORGE_GUIDE', () => {'minimize','最小化为浮动气泡',// 2026-07-25 skill 槽:随包捆绑 Agent Skills,声明一致性 + 全局作用域披露。- '十四个卡槽',+ // 卡槽总数标记随 workspace 槽合入更新为十五个。+ '十五个卡槽','捆绑 Agent Skills(skill 槽)','skill.items','SKILL.md','~/.agents/skills','逐字一致','不受插件沙箱约束',+ // 2026-07-25 工作区会话(workspace 槽):目录亲选/确认卡授权,判重复用,+ // 空会话入口落侧边栏;§2 卡槽清单与 §4.17 章节同步。+ '创建工作区会话(workspace 槽)',+ 'cindy.workspace',+ "kind: 'ensure-session'",]) {expect(FORGE_GUIDE).toContain(marker);}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.tsnew file mode 100644index 0000000000..bb4da7bab9--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts@@ -0,0 +1,381 @@+/** workspaceSlot.test — 工作区会话槽(workspace)的假 deps 单测。 */++import { describe, expect, it, vi } from 'vitest';++import type { InstalledGhost } from '../../../shared/ghost';+import {+ GhostWorkspaceSlot,+ type WorkspaceSessionService,+ type WorkspaceSlotDeps,+} from '../workspaceSlot';++function workspaceGhost(options: { slots?: string[]; enabled?: boolean } = {}): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: 'ws-ghost',+ name: 'Workspace Ghost',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: options.slots ?? ['workspace'],+ },+ dir: '/fake/ws-ghost',+ enabled: options.enabled ?? true,+ } as InstalledGhost;+}++function makeService(overrides: Partial<WorkspaceSessionService> = {}): WorkspaceSessionService {+ return {+ findActiveSessionByWorkdir: vi.fn(async () => null),+ createDraftSession: vi.fn(async () => 'new-session-id'),+ focusSession: vi.fn(),+ ...overrides,+ };+}++function makeSlot(+ overrides: Partial<WorkspaceSlotDeps> = {},+ service: WorkspaceSessionService | null = makeService(),+) {+ let clock = 0;+ const deps: WorkspaceSlotDeps = {+ getGhost: () => workspaceGhost(),+ showDirectoryDialog: vi.fn(async () => '/Users/me/projects/demo'),+ resolveCallContext: vi.fn(() => ({ ghostId: 'ws-ghost', sessionId: 'sess-1' })),+ getSessionDirInfo: vi.fn(async () => ({+ workingDir: '/Users/me/projects/demo',+ remoteHostId: null,+ })),+ statDir: vi.fn(async () => 'ok' as const),+ isInsideWorkdir: vi.fn(() => true),+ confirmDir: vi.fn(async () => ({ ok: true as const })),+ now: () => (clock += 60_000),+ ...overrides,+ };+ const slot = new GhostWorkspaceSlot(deps);+ slot.setSessionService(service);+ return { slot, deps, service };+}++const PICK_REQ = { kind: 'ensure-session', mode: 'pick' } as const;+const DIR_REQ = {+ kind: 'ensure-session',+ mode: 'dir',+ dir: '/Users/me/other/repo',+ callId: 'call-1',+} as const;++describe('workspaceSlot · 资格审与载荷校验', () => {+ it('未声明 workspace 槽 / 未启用 一律 PERMISSION_DENIED', async () => {+ const noSlot = makeSlot({ getGhost: () => workspaceGhost({ slots: ['pick'] }) });+ expect(await noSlot.slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ const disabled = makeSlot({ getGhost: () => workspaceGhost({ enabled: false }) });+ expect(await disabled.slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ });++ it('kind/mode/title/focus 形状不对整单拒', async () => {+ const { slot } = makeSlot();+ expect(await slot.handleRequest('ws-ghost', { kind: 'x', mode: 'pick' })).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(+ await slot.handleRequest('ws-ghost', { kind: 'ensure-session', mode: 'open' }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ expect(await slot.handleRequest('ws-ghost', { ...PICK_REQ, title: 1 })).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(await slot.handleRequest('ws-ghost', { ...PICK_REQ, focus: 'yes' })).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ });++ it('会话服务未注入 = HOST_NOT_READY', async () => {+ const { slot } = makeSlot({}, null);+ expect(await slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({+ ok: false,+ errorCode: 'HOST_NOT_READY',+ });+ });+});++describe('workspaceSlot · pick 流(亲选即授权)', () => {+ it('用户选中 → 判重未命中 → 创建空会话;绝对路径不回沙箱', async () => {+ const { slot, service } = makeSlot();+ const result = await slot.handleRequest('ws-ghost', { ...PICK_REQ, title: '选择项目' });+ expect(result).toMatchObject({ ok: true, sessionId: 'new-session-id', created: true, name: 'demo' });+ expect(service!.createDraftSession).toHaveBeenCalledWith({+ dirAbs: '/Users/me/projects/demo',+ title: '选择项目',+ ghostId: 'ws-ghost',+ });+ expect(JSON.stringify(result)).not.toContain('/Users');+ });++ it('判重命中 → 复用不新建;focus:true 时跳转聚焦', async () => {+ const service = makeService({ findActiveSessionByWorkdir: vi.fn(async () => 'old-session') });+ const { slot } = makeSlot({}, service);+ const result = await slot.handleRequest('ws-ghost', { ...PICK_REQ, focus: true });+ expect(result).toMatchObject({ ok: true, sessionId: 'old-session', created: false });+ expect(service.createDraftSession).not.toHaveBeenCalled();+ expect(service.focusSession).toHaveBeenCalledWith('old-session');+ });++ it('缺省不聚焦(只落侧边栏)', async () => {+ const { slot, service } = makeSlot();+ await slot.handleRequest('ws-ghost', PICK_REQ);+ expect(service!.focusSession).not.toHaveBeenCalled();+ });++ it('用户取消 = CANCELLED', async () => {+ const { slot } = makeSlot({ showDirectoryDialog: vi.fn(async () => null) });+ expect(await slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({+ ok: false,+ errorCode: 'CANCELLED',+ });+ });++ it('对话框打不开(无宿主窗口)= INTERNAL,失败关闭', async () => {+ const { slot } = makeSlot({+ showDirectoryDialog: vi.fn(async () => {+ throw new Error('no window');+ }),+ });+ expect(await slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({+ ok: false,+ errorCode: 'INTERNAL',+ });+ });+});++describe('workspaceSlot · dir 流(callId 上下文凭证 + 两档钳制)', () => {+ it('缺 dir / 缺 callId / 相对路径 整单拒', async () => {+ const { slot } = makeSlot();+ expect(+ await slot.handleRequest('ws-ghost', { kind: 'ensure-session', mode: 'dir', callId: 'c' }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ expect(+ await slot.handleRequest('ws-ghost', { kind: 'ensure-session', mode: 'dir', dir: '/a' }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ expect(+ await slot.handleRequest('ws-ghost', {+ kind: 'ensure-session',+ mode: 'dir',+ dir: 'relative/path',+ callId: 'c',+ }),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });+ });++ it('callId 查无 / 不属于本插件 = PERMISSION_DENIED(冒名即拒)', async () => {+ const missing = makeSlot({ resolveCallContext: vi.fn(() => null) });+ expect(await missing.slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ const foreign = makeSlot({+ resolveCallContext: vi.fn(() => ({ ghostId: 'other-ghost', sessionId: 'sess-1' })),+ });+ expect(await foreign.slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ });+ });++ it('无会话语境无法弹卡 = INVALID_REQUEST(引导改用 pick)', async () => {+ const { slot } = makeSlot({+ resolveCallContext: vi.fn(() => ({ ghostId: 'ws-ghost', sessionId: null })),+ });+ expect(await slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ });++ it('目录不存在 / 不是目录 分别报 DIR_NOT_FOUND / NOT_DIRECTORY', async () => {+ const missing = makeSlot({ statDir: vi.fn(async () => 'not-found' as const) });+ expect(await missing.slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'DIR_NOT_FOUND',+ });+ const file = makeSlot({ statDir: vi.fn(async () => 'not-directory' as const) });+ expect(await file.slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'NOT_DIRECTORY',+ });+ });++ it('目录在会话 workdir 内 → 免确认直通', async () => {+ const { slot, deps } = makeSlot({ isInsideWorkdir: vi.fn(() => true) });+ const result = await slot.handleRequest('ws-ghost', DIR_REQ);+ expect(result).toMatchObject({ ok: true, created: true, name: 'repo' });+ expect(deps.confirmDir).not.toHaveBeenCalled();+ });++ it('目录在 workdir 外 → 弹确认卡;拒绝/超时 = CANCELLED', async () => {+ const allowed = makeSlot({ isInsideWorkdir: vi.fn(() => false) });+ expect(await allowed.slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: true,+ created: true,+ });+ expect(allowed.deps.confirmDir).toHaveBeenCalledWith({+ ghostId: 'ws-ghost',+ sessionId: 'sess-1',+ dirAbs: '/Users/me/other/repo',+ });++ const denied = makeSlot({+ isInsideWorkdir: vi.fn(() => false),+ confirmDir: vi.fn(async () => ({ ok: false as const, message: '用户拒绝' })),+ });+ expect(await denied.slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'CANCELLED',+ });+ });++ it('会话快照读不到(查无/读失败)→ 同样硬拒,不落确认卡路径(fail closed)', async () => {+ const service = makeService();+ const { slot, deps } = makeSlot(+ { getSessionDirInfo: vi.fn(async () => null), isInsideWorkdir: vi.fn(() => true) },+ service,+ );+ expect(await slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(deps.confirmDir).not.toHaveBeenCalled();+ expect(service.createDraftSession).not.toHaveBeenCalled();+ });++ it('发起会话是远程工作区(remoteHostId 非空)→ 硬拒(fail closed),不弹卡不创建', async () => {+ const service = makeService();+ const { slot, deps } = makeSlot(+ {+ getSessionDirInfo: vi.fn(async () => ({+ workingDir: '/remote/proj',+ remoteHostId: 'ssh-host',+ })),+ isInsideWorkdir: vi.fn(() => true),+ },+ service,+ );+ expect(await slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(deps.confirmDir).not.toHaveBeenCalled();+ expect(deps.isInsideWorkdir).not.toHaveBeenCalled();+ expect(service.createDraftSession).not.toHaveBeenCalled();+ });++ it('并发 ensure 串行化:第二单等第一单建完,命中复用不双建', async () => {+ let created: string | null = null;+ let releaseCreate: (v: string) => void = () => {};+ const createGate = new Promise<string>((resolve) => {+ releaseCreate = resolve;+ });+ const service = makeService({+ findActiveSessionByWorkdir: vi.fn(async () => created),+ createDraftSession: vi.fn(async () => {+ const id = await createGate;+ created = id;+ return id;+ }),+ });+ // 两个不同插件(各自频控互不影响),同目录、workdir 内免确认路径。+ const { slot } = makeSlot(+ {+ getGhost: (id) =>+ ({ ...workspaceGhost(), manifest: { ...workspaceGhost().manifest, id } }) as never,+ isInsideWorkdir: vi.fn(() => true),+ resolveCallContext: vi.fn((callId: string) =>+ callId === 'call-a'+ ? { ghostId: 'ghost-a', sessionId: 'sess-1' }+ : { ghostId: 'ghost-b', sessionId: 'sess-1' },+ ),+ },+ service,+ );+ const first = slot.handleRequest('ghost-a', {+ kind: 'ensure-session',+ mode: 'dir',+ dir: '/Users/me/other/repo',+ callId: 'call-a',+ });+ const second = slot.handleRequest('ghost-b', {+ kind: 'ensure-session',+ mode: 'dir',+ dir: '/Users/me/other/repo',+ callId: 'call-b',+ });+ releaseCreate('sess-new');+ const [r1, r2] = await Promise.all([first, second]);+ expect(r1).toMatchObject({ ok: true, sessionId: 'sess-new', created: true });+ expect(r2).toMatchObject({ ok: true, sessionId: 'sess-new', created: false });+ expect(service.createDraftSession).toHaveBeenCalledTimes(1);+ });+});++describe('workspaceSlot · 骚扰钳制与失败面', () => {+ it('同插件两次请求间隔不足 = RATE_LIMITED(按尝试记账)', async () => {+ let clock = 0;+ const { slot } = makeSlot({ now: () => (clock += 1000) });+ expect((await slot.handleRequest('ws-ghost', PICK_REQ)).ok).toBe(true);+ expect(await slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({+ ok: false,+ errorCode: 'RATE_LIMITED',+ });+ });++ it('已有选择框在场 = BUSY,不排队', async () => {+ let release: (value: string | null) => void = () => {};+ const gate = new Promise<string | null>((resolve) => {+ release = resolve;+ });+ const { slot } = makeSlot({ showDirectoryDialog: vi.fn(() => gate) });+ const first = slot.handleRequest('ws-ghost', PICK_REQ);+ const second = await slot.handleRequest('ws-ghost', PICK_REQ);+ expect(second).toMatchObject({ ok: false, errorCode: 'BUSY' });+ release('/tmp/dir');+ expect((await first).ok).toBe(true);+ });++ it('确认通道 reject(桥未就绪/通道异常)折叠成 INTERNAL,并释放在场标记', async () => {+ const { slot } = makeSlot({+ isInsideWorkdir: vi.fn(() => false),+ confirmDir: vi.fn(async () => {+ throw new Error('bridge down');+ }),+ });+ expect(await slot.handleRequest('ws-ghost', DIR_REQ)).toMatchObject({+ ok: false,+ errorCode: 'INTERNAL',+ });+ // 在场标记已释放:下一单(过频控后)不会被误判 BUSY。+ let clock = 10 * 60_000;+ const next = makeSlot({ now: () => (clock += 60_000) });+ expect((await next.slot.handleRequest('ws-ghost', PICK_REQ)).ok).toBe(true);+ });++ it('创建失败折叠成 INTERNAL,不泄漏内部错误细节', async () => {+ const service = makeService({+ createDraftSession: vi.fn(async () => {+ throw new Error('db exploded at C:\\secret\\path');+ }),+ });+ const { slot } = makeSlot({}, service);+ const result = await slot.handleRequest('ws-ghost', PICK_REQ);+ expect(result).toMatchObject({ ok: false, errorCode: 'INTERNAL' });+ expect(JSON.stringify(result)).not.toContain('secret');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/cardService.ts b/apps/desktop/src/main/cindy-brain/cardService.tsindex b885a0232f..ddc1e63479 100644--- a/apps/desktop/src/main/cindy-brain/cardService.ts+++ b/apps/desktop/src/main/cindy-brain/cardService.ts@@ -250,6 +250,18 @@ export class GhostCardService {return e ? { ghostId: e.ghostId, sessionId: e.sessionId } : null;}+ /**+ * 严格在途查询(workspace 槽的上下文凭证用):仅当该单已登记、未交卷+ * (settledAt 为 null)且非重开态时返回归属。宽限窗/重开窗/working 窗都是+ * 卡片供片语义,不能让 callId 在工具调用结束后继续充当"目录授权上下文"+ * ——否则插件记住一个旧 callId 就能跨调用复用当时会话的 workdir 自动放行。+ */+ inFlightCallInfoOf(callId: string): { ghostId: string; sessionId: string | null } | null {+ const e = this.calls.get(callId);+ if (!e || e.settledAt !== null || e.reopenedAt !== null) return null;+ return { ghostId: e.ghostId, sessionId: e.sessionId };+ }+/*** 交互卡按钮被点后重开卡片更新窗口(card-action 派发前调,由 dispatcher 接线)。* 让意识在卡片结算很久后 / 重启后仍能 card-update 换新卡:diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 16f17d7d1f..4b28708f96 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -820,7 +820,7 @@ key、未知字段、原清单没有的条目、类型或长度不合格、文不一致、无效 JSON 或单文件超过 64KB 都会在 Forge 打包期、内置播种期与安装期拒绝。清单列表、详情页、Panel 标题、安装/配置提示和 Agent 工具目录都消费同一份本地化结果。-十四个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图)、\`agent\`(让+十五个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图)、\`agent\`(让当前 Agent 开始一个普通用户回合,见 §4.11)、\`panel\`(常驻面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话事件 + 拦截用户消息,见 §4.6)、\`network\`(访问自带服务的域名白名单 HTTP,主机代发,@@ -830,7 +830,8 @@ Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机可信 session_id / workdir / 只读状态注入 args,见 §4.13)、\`pick\`(请主机弹系统选文件夹窗口,用户亲选即授权,见 §4.14)、\`preview\`(请主机在右侧栏内置浏览器打开白名单网站的预览标签,见 §4.15)、\`skill\`(捆绑 Agent Skills:随包 SKILL.md 技能,启用后-Claude Code 与 Codex 都能发现,见 §4.16)。+Claude Code 与 Codex 都能发现,见 §4.16)、\`workspace\`(请主机为项目目录在+侧边栏创建/复用会话入口,见 §4.17)。**agent 能力详单**:在 \`slots\` 加 \`"agent"\`,默认只允许在用户真实点击你的聊天卡片后发起一次 Agent 回合;这一档不写配套字段。若确实需要没有当次点击也能@@ -2315,12 +2316,60 @@ SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):信任与作用域(如实告知用户,也请作者自重):- 技能指令由**主 Agent 以用户全部权限执行**,对所有项目、所有会话生效,- **不受插件沙箱约束**——这是十四个卡槽里信任面最高的能力,装入确认框会把+ **不受插件沙箱约束**——这是十五个卡槽里信任面最高的能力,装入确认框会把每个技能置顶逐条列出;- 技能跟随插件的**全局**启用状态:仅在某个工作目录停用插件**不会**隐藏技能,只有全局停用或卸载才撤链(本期只有全局作用域);- \`skill.items\` 的字段不参与 locales 本地化(必须与 SKILL.md 逐字一致,而SKILL.md 只有一份)。+## 4.17 创建工作区会话(workspace 槽)++需要把某个项目目录变成侧边栏里的会话入口("打开项目"/仓库列表这类场景)时,+声明 \`workspace\` 槽,经管子请主机**确保**该目录下存在一个会话:目录下已有+active 会话直接复用(created:false),没有才创建一个空会话,创建/命中后显示在+侧边栏对应工作区分组里。++面板里由用户点击发起(推荐,用户在系统窗口亲选目录即授权):++\`\`\`js+const ensured = await cindy.workspace({+ kind: 'ensure-session',+ mode: 'pick', // 主机弹系统选文件夹窗口+ title: '选择要打开的项目目录', // 用途说明(≤100 字),也用作新会话标题+ focus: true // 可选:创建/命中后跳转聚焦到该会话,缺省只落侧边栏+});+if (ensured.ok) {+ // ensured.sessionId —— 会话 id+ // ensured.created —— true = 新建;false = 命中已有会话复用+ // ensured.name —— 目录名(展示用;绝对路径不会给你)+}+\`\`\`++处理 ghost_call 工具调用期间已经拿到目录路径时,可改用 dir 模式,带上本单 callId:++\`\`\`js+// main.js 的 tool-call 处理器里(msg.callId 是主机随单下发的)+const ensured = await cindy.workspace({+ kind: 'ensure-session',+ mode: 'dir',+ dir: '/Users/me/projects/demo', // 本机绝对路径+ callId: msg.callId // 主机铸造的上下文凭证,只在本单在途期间有效+});+\`\`\`++规则与红线:++- \`mode:'pick'\` 的授权动作是用户亲手选中,取消回 CANCELLED——**尊重取消,不要+ 循环重弹**;绝对路径不回沙箱,你只拿到目录名与会话 id;+- \`mode:'dir'\` 只能在处理 ghost_call 期间用:callId 配对失败回 PERMISSION_DENIED;+ 目录在发起会话的工作目录内自动放行,之外弹确认卡由用户决定(拒绝/超时回+ CANCELLED,不要重试,如确有需要先与用户沟通);目录必须真实存在+ (DIR_NOT_FOUND / NOT_DIRECTORY);+- 只支持本机目录,远程(SSH)工作区一律拒;+- 同一插件两次请求最小间隔 3 秒、全局同时只有一个窗口/确认卡在场(RATE_LIMITED /+ BUSY);+- 创建的是**空会话**:不拉起 agent、不发消息、不自动开始任何任务;要让 Agent+ 立即干活请配合 agent 槽(§4.11)。## 5. 面板(panel.html/css/js)diff --git a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.tsindex 954f0687bd..b7abbda0f1 100644--- a/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts+++ b/apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts@@ -25,9 +25,11 @@ import { MAKER_PUSH } from '../maker-ipc/channels';/*** 过户通道:attachments = 媒体文件进总仓;dir = 上行读票据;save_dir = 下行* 写票据;fs_write = fs 槽写 workdir 文件(会话 permission 为逐条确认档时,- * 意识每次写入前弹卡;同目录本会话批一次,记忆在 fsSlot)。+ * 意识每次写入前弹卡;同目录本会话批一次,记忆在 fsSlot);workspace =+ * workspace 槽在会话 workdir 外的目录下创建/复用会话入口(2026-07-25,+ * 不过户字节,只授权"以此目录为工作区建会话")。*/-export type GhostGrantLane = 'attachments' | 'dir' | 'save_dir' | 'fs_write';+export type GhostGrantLane = 'attachments' | 'dir' | 'save_dir' | 'fs_write' | 'workspace';/** 确认卡上逐条展示的过户对象(路径/大小让用户看清自己在授权什么)。 */export interface GhostGrantFileItem {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex f73659c22c..0ee76b11d2 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -133,13 +133,14 @@ import { GhostAgentSlot, type GhostAgentTurnRunner } from './agentSlot.js';import { GhostNodeRuntimeBroker } from './nodeRuntimeBroker.js';import { GhostPickSlot } from './pickSlot.js';import { GhostPreviewSlot } from './previewSlot.js';+import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';import type { GhostTrustRegistry } from './ghostSignature.js';import { GhostNotifySlot, sanitizeGhostNoticeText } from './notifySlot.js';import { GhostNetworkSlot } from './networkSlot.js';import { GhostFsSlot } from './fsSlot.js';import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';-import { getDirDepositVault, getSaveDepositVault } from './dirDeposit.js';+import { getDirDepositVault, getSaveDepositVault, isPathInsideDir } from './dirDeposit.js';import {GhostSubscriptionGateway,GhostTurnTranslator,@@ -1282,6 +1283,88 @@ export function getGhostPickSlot(): GhostPickSlot {return pickSlotSingleton;}+let workspaceSlotSingleton: GhostWorkspaceSlot | null = null;++/**+ * 工作区会话槽单例(workspace):资格审/限速/目录授权/判重在 GhostWorkspaceSlot,+ * 这里只组装 Electron 系统对话框、确认卡桥(lane='workspace')、在途 callId+ * 反查(cardService)与会话目录快照;真实的判重/创建/聚焦服务由 maker-ipc+ * 初始化完成后经 setGhostWorkspaceSessionService 注入(保持 cindy-brain 不+ * 反向依赖 maker-ipc)。+ */+export function getGhostWorkspaceSlot(): GhostWorkspaceSlot {+ if (!workspaceSlotSingleton) {+ workspaceSlotSingleton = new GhostWorkspaceSlot({+ getGhost: findAvailableGhost,+ showDirectoryDialog: async ({ ghostName, purpose }) => {+ const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];+ if (!win || win.isDestroyed()) throw new Error('没有可挂靠的宿主窗口');+ // main 侧 t() 只插值 {{appName}},插件名在调用点替换(与 pick 槽同做法)。+ const message = t('settings.ghosts.workspace.dialogMessage').replaceAll('{{name}}', ghostName);+ const result = await dialog.showOpenDialog(win, {+ title: t('settings.ghosts.workspace.dialogTitle'),+ message: purpose ? `${message}\n${purpose}` : message,+ properties: ['openDirectory', 'createDirectory'],+ });+ if (result.canceled || result.filePaths.length === 0) return null;+ return result.filePaths[0];+ },+ // 严格在途:交卷/重开后的 callId 不再是有效的目录授权上下文凭证。+ resolveCallContext: (callId) => getGhostCardService().inFlightCallInfoOf(callId),+ getSessionDirInfo: async (sessionId) => {+ const snapshot = await getSessionFsSnapshot(sessionId);+ if (!snapshot) return null;+ return { workingDir: snapshot.workingDir, remoteHostId: snapshot.remoteHostId };+ },+ statDir: async (dirAbs) => {+ try {+ const stat = await fs.promises.stat(dirAbs);+ return stat.isDirectory() ? 'ok' : 'not-directory';+ } catch (error) {+ // ENOTDIR = 路径中间某段不是目录,语义上更接近"不是目录"而非"不存在"。+ return (error as NodeJS.ErrnoException)?.code === 'ENOTDIR'+ ? 'not-directory'+ : 'not-found';+ }+ },+ isInsideWorkdir: (dirAbs, workdirAbs) => {+ try {+ return isPathInsideDir(fs.realpathSync.native(workdirAbs), fs.realpathSync.native(dirAbs));+ } catch {+ return false;+ }+ },+ confirmDir: async ({ ghostId, sessionId, dirAbs }) => {+ const bridge = getGhostGrantConfirmBridge();+ if (!bridge) {+ throw new Error('确认通道未就绪');+ }+ const decision = await bridge.request(sessionId, {+ ghostId,+ ghostName: findAvailableGhost(ghostId)?.manifest.name ?? ghostId,+ lane: 'workspace',+ items: [{ name: path.basename(dirAbs), absPath: dirAbs, size: 0, isDirectory: true }],+ });+ if (decision.confirmed) return { ok: true };+ return {+ ok: false,+ message:+ decision.reason === 'timeout'+ ? '确认超时:用户未在时限内响应,本次工作区会话请求已取消'+ : '用户拒绝了本次工作区会话请求,不要重试;如确有需要请先与用户沟通',+ };+ },+ log,+ });+ }+ return workspaceSlotSingleton;+}++/** maker-ipc 完成初始化后注入判重/创建/聚焦服务;保持 cindy-brain 不反向依赖它。 */+export function setGhostWorkspaceSessionService(service: WorkspaceSessionService | null): void {+ getGhostWorkspaceSlot().setSessionService(service);+}+let previewSlotSingleton: GhostPreviewSlot | null = null;/** 插件预览开页通道(main → 全窗口 renderer;右侧栏开 web-browser 标签)。 */@@ -2666,7 +2749,8 @@ export function registerGhostIpc(): void {// fsSlot 三档守门)/ agent-request(Agent 新回合,一次性用户票或后台权限// 守门)/ node-request(随包 Node JSON-RPC/MCP stdio 中继)/ pick-request// (系统级选文件夹,用户亲选即授权)/ preview-request(右侧栏开预览标签,- // preview.hosts 白名单守门)。其它类型一律拒。+ // preview.hosts 白名单守门)/ workspace-request(工作区会话入口,亲选或+ // 确认卡授权,判重/创建在 workspaceSlot)。其它类型一律拒。ipcMain.handle('ghost-pipe:ping', (event) => {const id = ghostIdForLogicWebContents(event.sender.id);if (!id) throwIpcError('PERMISSION_DENIED', '非意识电子脑上下文');@@ -2726,6 +2810,11 @@ export function registerGhostIpc(): void {if (type === 'pick-request') {return getGhostPickSlot().handleRequest(id, payload);}+ // workspace-request = 工作区会话入口(workspace 槽):目录亲选或确认卡+ // 授权,已有 active 会话复用;限速/判重/创建守门在 workspaceSlot。+ if (type === 'workspace-request') {+ return getGhostWorkspaceSlot().handleRequest(id, payload);+ }// preview-request = 右侧栏开预览标签(preview 槽):URL 必须命中身份卡// preview.hosts 白名单;守门/限速在 previewSlot,落地在 renderer。if (type === 'preview-request') {diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.tsindex 309ccb4368..aaeca07e8a 100644--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts@@ -446,7 +446,9 @@ export function isGhostEligibleSessionRow(row: {orcaRole: string | null | undefined;}): boolean {// orcaRole 宽松判空:worker-thread 代理序列化可能把 NULL 列变 undefined。- return (row.source === 'desktop' || row.source === 'shared') && row.orcaRole == null;+ // plugin 来源:workspace 槽创建的项目会话,用户打开后正常交互,应享有完整的+ // ghost 事件(turn/hook/session-switched 等),与 desktop/shared 同等待遇。+ return (row.source === 'desktop' || row.source === 'shared' || row.source === 'plugin') && row.orcaRole == null;}/**diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.tsnew file mode 100644index 0000000000..331e9faae6--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts@@ -0,0 +1,275 @@+/**+ * workspaceSlot.ts — 工作区会话槽(workspace,2026-07-25)。+ * ---------------------------------------------------------------------------+ * 插件经管子上行 `{type:'workspace-request', kind:'ensure-session', mode, …}`,+ * 请主机在指定本机项目目录下**确保**存在一个会话入口(侧边栏可见):+ * 目录下已有 active 会话即复用(created:false),没有才创建 plugin 来源的空+ * draft 会话(不拉起 agent 进程)。安全模型:+ *+ * - 资格审:已装、启用、声明 workspace 槽;+ * - 目录授权两条路,决定权都在用户的真实动作上:+ * · mode:'pick':主机弹系统级选文件夹窗口,用户亲手选中即授权(与 pick+ * 槽同一哲学);绝对路径不回沙箱,结果只带目录 basename;+ * · mode:'dir':绝对路径 + 当前在途 ghost_call 的 callId(主机铸造、不可+ * 伪造的上下文凭证,反查发起会话)。目录在该会话 workdir 内自动放行,+ * workdir 外弹确认卡(GrantConfirmBridge lane='workspace')——两档钳制+ * 对齐 attachments/dir 过户的 2026-07-14 政策;+ * - 骚扰钳制:同一插件两次请求最小间隔 GHOST_WORKSPACE_MIN_INTERVAL_MS+ * (按尝试记账),全局同时只允许一个对话框/确认卡在场(BUSY;dir 模式在+ * 授权 await 之后、弹卡之前同步 check-and-set,防并发双卡);+ * - 判重+创建整段经全局串行链执行:并发 ensure(跨插件/同目录)在无锁下会+ * "都查无 → 都创建"打破 ensure 语义;流量极低,全局串行即可;+ * - 远程工作区(SSH)v1 不支持:发起会话是远程会话时 mode:'dir' 一律硬拒+ * (fail closed),引导改用 pick 模式由用户亲选本机目录。+ *+ * 纯逻辑 + 依赖注入(规则 14):Electron dialog / 确认卡桥 / localDb 会话服务+ * 在 cindy-brain/index.ts 与 maker-ipc register 装配时注入,单测喂假 deps 直测。+ */++import path from 'node:path';++import {+ GHOST_WORKSPACE_MIN_INTERVAL_MS,+ GHOST_WORKSPACE_TITLE_MAX_CHARS,+ type GhostPipeWorkspaceResult,+ type InstalledGhost,+} from '../../shared/ghost.js';+import { sanitizeGhostNoticeText } from './notifySlot.js';++/** 会话判重/创建/聚焦服务(maker-ipc 初始化完成后经 setter 注入)。 */+export interface WorkspaceSessionService {+ /**+ * 按目录判重:命中返回已有 active 会话 id(口径 = 侧边栏"同一工作区",+ * 归一化与 worktree 折叠在实现侧),查无返回 null。+ */+ findActiveSessionByWorkdir(dirAbs: string): Promise<string | null>;+ /** 创建 plugin 来源的空 draft 会话(不拉起 agent 进程),返回会话 id。 */+ createDraftSession(params: {+ dirAbs: string;+ title: string | null;+ ghostId: string;+ }): Promise<string>;+ /** focus:true 时跳转聚焦到该会话(deep-link navigate 通道;尽力而为)。 */+ focusSession(sessionId: string): void;+}++export interface WorkspaceSlotDeps {+ getGhost(id: string): InstalledGhost | null;+ /**+ * 弹系统级选文件夹窗口;返回所选绝对路径,取消返回 null。+ * 找不到可挂靠的 Cindy 窗口时应 reject(失败关闭,不弹无主对话框)。+ */+ showDirectoryDialog(params: { ghostName: string; purpose: string | null }): Promise<string | null>;+ /** 在途 ghost_call 反查(cardService.callInfoOf):查无/过期返回 null。 */+ resolveCallContext(callId: string): { ghostId: string; sessionId: string | null } | null;+ /** 会话目录快照(localDb);查无会话返回 null。 */+ getSessionDirInfo(+ sessionId: string,+ ): Promise<{ workingDir: string | null; remoteHostId: string | null } | null>;+ /** 目录存在性校验(host 侧 fs.stat)。 */+ statDir(dirAbs: string): Promise<'ok' | 'not-found' | 'not-directory'>;+ /** 目标目录是否位于会话 workdir 内(realpath 归一化,口径同 dirDeposit)。 */+ isInsideWorkdir(dirAbs: string, workdirAbs: string): boolean;+ /** workdir 外目录的确认卡(GrantConfirmBridge lane='workspace')。 */+ confirmDir(params: {+ ghostId: string;+ sessionId: string;+ dirAbs: string;+ }): Promise<{ ok: true } | { ok: false; message: string }>;+ now?(): number;+ log?: {+ info: (msg: string, meta?: Record<string, unknown>) => void;+ warn: (msg: string, meta?: Record<string, unknown>) => void;+ };+}++function fail(+ errorCode: Extract<GhostPipeWorkspaceResult, { ok: false }>['errorCode'],+ message: string,+): GhostPipeWorkspaceResult {+ return { ok: false, errorCode, message };+}++/** 工作区会话槽:资格审 → 载荷校验 → 限速/单发 → 目录授权 → 判重 → 创建。 */+export class GhostWorkspaceSlot {+ /** 意识 id → 上次尝试时刻(按尝试记账;体量 = 已装意识数,无需清理)。 */+ private readonly lastAttemptAt = new Map<string, number>();+ /** 全局在场标记(系统对话框/确认卡一次一个,不排队——排队就是骚扰队列)。 */+ private consentInFlight = false;+ /**+ * 判重+创建的全局串行链:并发 ensure 在"查无 → 创建"之间没有原子性,+ * 两个请求会各建一个空会话、都报 created:true。按目录分键收益有限+ * (还得处理归一化),流量极低直接全局串行。链上错误已被消化,不会把+ * 上一单的失败漏给下一单。+ */+ private ensureChain: Promise<unknown> = Promise.resolve();+ private sessionService: WorkspaceSessionService | null = null;++ constructor(private readonly deps: WorkspaceSlotDeps) {}++ /** maker-ipc 初始化完成后注入真实会话服务;传 null 用于退出清理。 */+ setSessionService(service: WorkspaceSessionService | null): void {+ this.sessionService = service;+ }++ async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeWorkspaceResult> {+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost?.enabled || !ghost.manifest.slots.includes('workspace')) {+ return fail('PERMISSION_DENIED', '插件未申请工作区会话权限(workspace 槽),或当前未启用');+ }+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {+ return fail('INVALID_REQUEST', 'workspace-request 载荷必须是对象');+ }+ const request = payload as Record<string, unknown>;+ if (request.kind !== 'ensure-session') {+ return fail('INVALID_REQUEST', 'kind 目前只支持 "ensure-session"');+ }+ if (request.mode !== 'pick' && request.mode !== 'dir') {+ return fail('INVALID_REQUEST', 'mode 必须是 "pick" 或 "dir"');+ }+ if (request.title !== undefined && typeof request.title !== 'string') {+ return fail('INVALID_REQUEST', 'title 必须是字符串');+ }+ if (request.focus !== undefined && typeof request.focus !== 'boolean') {+ return fail('INVALID_REQUEST', 'focus 必须是布尔值');+ }+ const service = this.sessionService;+ if (!service) {+ return fail('HOST_NOT_READY', '会话服务尚未准备好,请稍后再试');+ }++ // 骚扰钳制:限速按尝试记账(spam 顺延窗口),再看全局在场标记。+ const now = this.deps.now?.() ?? Date.now();+ const last = this.lastAttemptAt.get(ghostId);+ this.lastAttemptAt.set(ghostId, now);+ if (last !== undefined && now - last < GHOST_WORKSPACE_MIN_INTERVAL_MS) {+ return fail('RATE_LIMITED', '工作区会话请求太频繁,稍后再试');+ }+ if (this.consentInFlight) {+ return fail('BUSY', '已有一个选择窗口或确认卡在等用户操作');+ }++ const titleRaw = typeof request.title === 'string' ? sanitizeGhostNoticeText(request.title) : '';+ const title = titleRaw ? titleRaw.slice(0, GHOST_WORKSPACE_TITLE_MAX_CHARS) : null;++ // ── 目录授权 ────────────────────────────────────────────────────────+ let dirAbs: string;+ if (request.mode === 'pick') {+ this.consentInFlight = true;+ let picked: string | null;+ try {+ picked = await this.deps.showDirectoryDialog({+ ghostName: ghost.manifest.name,+ purpose: title,+ });+ } catch (error) {+ this.deps.log?.warn('ghost workspace pick dialog failed', {+ ghostId,+ err: error instanceof Error ? error.message : String(error),+ });+ return fail('INTERNAL', '选择窗口无法打开');+ } finally {+ this.consentInFlight = false;+ }+ if (picked === null) {+ return fail('CANCELLED', '用户取消了选择');+ }+ dirAbs = picked;+ } else {+ if (typeof request.dir !== 'string' || request.dir.length === 0 || request.dir.length > 1024) {+ return fail('INVALID_REQUEST', 'mode:"dir" 必须携带 1–1024 字符的 dir 绝对路径');+ }+ if (typeof request.callId !== 'string' || request.callId.length === 0 || request.callId.length > 128) {+ return fail('INVALID_REQUEST', 'mode:"dir" 必须携带当前在途 ghost_call 的 callId');+ }+ if (!path.isAbsolute(request.dir)) {+ return fail('INVALID_REQUEST', 'dir 必须是绝对路径');+ }+ // callId 是主机铸造的上下文凭证:反查归属与发起会话,冒名/过期直接拒。+ const ctx = this.deps.resolveCallContext(request.callId);+ if (!ctx || ctx.ghostId !== ghostId) {+ return fail('PERMISSION_DENIED', 'callId 无效或不属于这个插件(只能在处理 ghost_call 期间使用)');+ }+ if (!ctx.sessionId) {+ return fail(+ 'INVALID_REQUEST',+ '本次调用没有会话语境,无法向用户弹确认卡;请改用 mode:"pick" 让用户亲自选目录',+ );+ }+ const stat = await this.deps.statDir(request.dir);+ if (stat === 'not-found') return fail('DIR_NOT_FOUND', '目录不存在(只支持本机已存在的目录)');+ if (stat === 'not-directory') return fail('NOT_DIRECTORY', '该路径不是目录');+ const dirInfo = await this.deps.getSessionDirInfo(ctx.sessionId);+ // fail closed:快照读不到(查无会话/读失败)或远程(SSH)会话一律硬拒+ // ——证明不了"本机工作区语境"就连确认卡也不发,防快照失败把远程会话+ // 漏进确认卡路径(与管子契约"远程一律拒"一致)。+ if (dirInfo === null || dirInfo.remoteHostId !== null) {+ return fail(+ 'INVALID_REQUEST',+ '无法确认发起会话的本机工作区语境(远程 SSH 会话或会话信息不可用),workspace v1 不支持;请改用 mode:"pick" 让用户亲自选本机目录',+ );+ }+ // 两档钳制:目录在发起会话的 workdir 内 → 自动放行;workdir 外一律+ // 确认卡,证明不了"在内"就弹卡。+ const insideWorkdir =+ dirInfo.workingDir !== null && this.deps.isInsideWorkdir(request.dir, dirInfo.workingDir);+ if (!insideWorkdir) {+ // 前面的 statDir/getSessionDirInfo await 期间可能有并发请求闯进来,+ // 弹卡前同步 check-and-set,保证确认卡全局一次一张。+ if (this.consentInFlight) {+ return fail('BUSY', '已有一个选择窗口或确认卡在等用户操作');+ }+ this.consentInFlight = true;+ let confirmed: { ok: true } | { ok: false; message: string };+ try {+ confirmed = await this.deps.confirmDir({+ ghostId,+ sessionId: ctx.sessionId,+ dirAbs: request.dir,+ });+ } catch (error) {+ // 桥未就绪/renderer 通道异常等 reject 折叠成结构化 INTERNAL,+ // 不把裸异常漏给沙箱(与 pick 对话框同纪律)。+ this.deps.log?.warn('ghost workspace confirm failed', {+ ghostId,+ err: error instanceof Error ? error.message : String(error),+ });+ return fail('INTERNAL', '确认通道异常,请稍后再试');+ } finally {+ this.consentInFlight = false;+ }+ if (!confirmed.ok) {+ return fail('CANCELLED', confirmed.message);+ }+ }+ dirAbs = request.dir;+ }++ // ── 判重 → 创建(ensure 语义,授权后统一走这段;全局串行防双建)──────+ const name = path.basename(dirAbs) || dirAbs;+ const ensure = async (): Promise<GhostPipeWorkspaceResult> => {+ try {+ const existing = await service.findActiveSessionByWorkdir(dirAbs);+ if (existing) {+ if (request.focus === true) service.focusSession(existing);+ this.deps.log?.info('ghost workspace ensured (reused)', { ghostId, sessionId: existing });+ return { ok: true, sessionId: existing, created: false, name };+ }+ const sessionId = await service.createDraftSession({ dirAbs, title, ghostId });+ if (request.focus === true) service.focusSession(sessionId);+ this.deps.log?.info('ghost workspace ensured (created)', { ghostId, sessionId });+ return { ok: true, sessionId, created: true, name };+ } catch (error) {+ this.deps.log?.warn('ghost workspace ensure failed', {+ ghostId,+ err: error instanceof Error ? error.message : String(error),+ });+ return fail('INTERNAL', '会话创建失败,请稍后再试');+ }+ };+ // ensure 自身把异常折叠成 INTERNAL,链尾兜底只为极端情况下不断链。+ const resultPromise = this.ensureChain.then(ensure, ensure);+ this.ensureChain = resultPromise.catch(() => undefined);+ return resultPromise;+ }+}diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.tsindex a5e7d968d4..1266f1cf77 100644--- a/apps/desktop/src/main/deepLink.ts+++ b/apps/desktop/src/main/deepLink.ts@@ -310,6 +310,14 @@ export function openMainWindowVoiceSettings(tab: 'voice-input' | 'providers'): vdispatchDeepLink({ type: 'settings', tab });}+/**+ * 主进程内部发起的会话聚焦(workspace 槽 focus:true)。复用 deep link 的+ * 前台 + renderer dispatch 通道,行为与用户点 cindy://session/<id> 一致。+ */+export function openMainWindowSession(sessionId: string): void {+ dispatchDeepLink({ type: 'session', id: sessionId });+}+function dispatchDeepLink(payload: DeepLinkPayload): void {// 纯前台意图:main 进程内消化。冷启动时窗口还没建,app 启动流程本身会前台,直接丢弃。if (payload.type === 'focus') {diff --git a/apps/desktop/src/main/localDb/__tests__/pluginWorkspaceDedupe.test.ts b/apps/desktop/src/main/localDb/__tests__/pluginWorkspaceDedupe.test.tsnew file mode 100644index 0000000000..ecaea1ce64--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/pluginWorkspaceDedupe.test.ts@@ -0,0 +1,50 @@+/** pluginWorkspaceDedupe.test — workspace 槽判重纯函数单测。 */++import { describe, expect, it } from 'vitest';++import { pickSessionForWorkdir } from '../pluginWorkspaceDedupe';++const row = (id: string, workingDir: string | null, updatedAt = 1000) => ({+ id,+ workingDir,+ updatedAt,+});++describe('pickSessionForWorkdir', () => {+ it('精确命中同目录的会话;查无返回 null', () => {+ const rows = [row('a', '/Users/me/proj'), row('b', '/Users/me/other')];+ expect(pickSessionForWorkdir(rows, '/Users/me/proj')).toBe('a');+ expect(pickSessionForWorkdir(rows, '/Users/me/nowhere')).toBeNull();+ });++ it('目标路径经存储归一化再比较(反斜杠/尾斜杠/长路径前缀)', () => {+ const rows = [row('a', 'C:/work/app')];+ expect(pickSessionForWorkdir(rows, 'C:\\work\\app\\')).toBe('a');+ expect(pickSessionForWorkdir(rows, '\\\\?\\C:\\work\\app')).toBe('a');+ });++ it('worktree 子目录折叠到主仓(与侧边栏"同一工作区"口径一致)', () => {+ const rows = [row('a', '/Users/me/proj')];+ expect(pickSessionForWorkdir(rows, '/Users/me/proj/.worktrees/feat-x')).toBe('a');+ expect(pickSessionForWorkdir(rows, '/Users/me/proj/.claude/worktrees/feat-y')).toBe('a');+ });++ it('多条命中取 updatedAt 最新;null workingDir 行被跳过', () => {+ const rows = [+ row('old', '/p/app', 1000),+ row('new', '/p/app', 2000),+ row('none', null, 9000),+ ];+ expect(pickSessionForWorkdir(rows, '/p/app')).toBe('new');+ });++ it('与全仓现状一致:比较不做大小写折叠(大小写不同 = 不同工作区)', () => {+ const rows = [row('a', 'C:/Work/App')];+ expect(pickSessionForWorkdir(rows, 'c:/work/app')).toBeNull();+ });++ it('空白/空目标返回 null,不误配', () => {+ expect(pickSessionForWorkdir([row('a', '/p')], '')).toBeNull();+ expect(pickSessionForWorkdir([row('a', '/p')], ' ')).toBeNull();+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.tsnew file mode 100644index 0000000000..a360f87eba--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/pluginWorkspaceSessions.ts@@ -0,0 +1,148 @@+/**+ * pluginWorkspaceSessions —— workspace 槽的会话判重与创建(main 侧服务)。+ *+ * 服务 cindy-brain/workspaceSlot(经 maker-ipc register 注入),两个入口:+ * - findActiveSessionByWorkdir:按"侧边栏同一工作区"口径判重——+ * normalizeWorkingDirForGrouping 比较(worktree 折叠到主仓,与+ * renderer projectGrouping 的 projectIdentityKey 同源),只看本机+ * (remoteHostId 为空)、project 工作区、非 Orca worker 的 active 会话。+ * 注意:与全仓现状一致,比较**不做大小写折叠**——大小写不同的路径视为+ * 不同工作区(改口径要连 projectGrouping 一起改,不在本模块单点偏离)。+ * - createPluginDraftSession:插入 source='plugin' 的空 draft 行(不拉起+ * agent 进程),流程对齐 `local-db:sessions:create`(git bootstrap →+ * insert → recent-workdirs → 意识旁听通知);广播与意识旁听通知都由+ * 注入方(register.ts)提供——main 禁止运行时动态 import+ * (docs/dev-rules/architecture-invariants.md §2),这里不直接触碰+ * cindy-brain 与窗口。+ *+ * source='plugin' 的语义:projectGrouping 对零消息的 plugin 会话豁免草稿+ * 判定(否则空会话会掉「未分类」,插件"落到已有工作区分组"的目的不成立)。+ */++import { randomUUID } from 'node:crypto';++import { and, eq, isNull, isNotNull, ne, or } from 'drizzle-orm';++import { getDbClient } from '../client/current';+import { sessions } from '../schema';+import { sessionCreateToRow } from '../mapper';+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';+import { normalizeWorkingDirForStorage } from '../../../shared/workingDir.js';++const log = createLogger('plugin-workspace-sessions');++/**+ * 按目录找可复用的 active 会话:命中返回最近活跃的一条 id,查无返回 null。+ * 排除 Orca worker(侧边栏不可见,复用它等于把用户带进隐藏会话)与+ * dialogue 工作区(app-managed 临时 cwd,不是项目)。+ */+export async function findActiveSessionByWorkdir(dirAbs: string): Promise<string | null> {+ const db = getDbClient().drizzle;+ const rows = await db+ .select({ id: sessions.id, workingDir: sessions.workingDir, updatedAt: sessions.updatedAt })+ .from(sessions)+ .where(+ and(+ eq(sessions.status, 'active'),+ eq(sessions.workspaceKind, 'project'),+ isNotNull(sessions.workingDir),+ isNull(sessions.remoteHostId),+ // Orca worker 不进侧边栏,复用它等于把用户带进隐藏会话;NULL != 'worker'+ // 在 SQLite 里是 NULL(falsy),必须显式放行 NULL 行。+ or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker')),+ ),+ );+ return pickSessionForWorkdir(rows, dirAbs);+}++/**+ * 创建 plugin 来源的空 draft 会话,返回会话 id。调用方(workspaceSlot)已+ * 完成目录授权与存在性校验;这里只负责落库与既有 create 流程的副作用对齐。+ * Orca 字段这里显式排除:插件会话永远是普通 project 会话。+ */+export async function createPluginDraftSession(params: {+ dirAbs: string;+ title: string | null;+ ghostId: string;+ /**+ * 会话默认值(register 侧从 New Maker 面板缓存解析;缓存未就绪时为空,+ * 由 mapper 兜底)——让插件建的 draft 跟随用户当前的模型/强度选择。+ */+ defaults?: {+ agentKind?: 'cc' | 'codex';+ model?: string;+ effort?: string;+ fastMode?: boolean;+ providerId?: string | null;+ };+ /**+ * 意识旁听通知(cindy-brain notifyGhostSessionEvent,由 register 静态注入;+ * fire-and-forget,失败不阻断创建)。+ */+ notifySessionCreated?: (info: { sessionId: string; workdir?: string }) => void;+}): Promise<string> {+ 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,+ // 非空目录/未开快照原样跳过(projectGitBootstrap 自带守卫)。+ await ensureProjectGitInitialized({+ workingDir: insertRow.workingDir,+ workspaceKind: insertRow.workspaceKind,+ remoteHostId: insertRow.remoteHostId,+ sessionId: id,+ autoSnapshotEnabled: readGitSafetySettings().autoSnapshotEnabled,+ source: 'plugin-workspace-session',+ });+ await db.insert(sessions).values(insertRow);+ if (insertRow.workingDir) {+ // 用户刚为这个目录做过授权动作(亲选/确认卡),进"最近项目"列表合理;+ // 失败仅日志,不阻断创建流程(与既有 create 同纪律)。+ void upsertRecentWorkdir(insertRow.workingDir, now);+ }+ // 订阅槽①旁路通知(意识旁听会话创建):经注入回调触达 cindy-brain,+ // 失败仅日志——旁听是 best-effort,不阻断创建。+ try {+ params.notifySessionCreated?.({+ sessionId: id,+ ...(insertRow.workingDir ? { workdir: insertRow.workingDir } : {}),+ });+ } catch (error) {+ log.warn('[plugin-workspace] notifySessionCreated failed', {+ sessionId: id,+ err: error instanceof Error ? error.message : String(error),+ });+ }+ log.info('[plugin-workspace] draft session created', {+ sessionId: id,+ ghostId: params.ghostId,+ workingDir: insertRow.workingDir,+ });+ return id;+}diff --git a/apps/desktop/src/main/localDb/pluginWorkspaceDedupe.ts b/apps/desktop/src/main/localDb/pluginWorkspaceDedupe.tsnew file mode 100644index 0000000000..9589c50603--- /dev/null+++ b/apps/desktop/src/main/localDb/pluginWorkspaceDedupe.ts@@ -0,0 +1,27 @@+/**+ * workspace 槽判重的纯比较逻辑(零重依赖,单测直测)。+ *+ * 口径 = normalizeWorkingDirForGrouping:与 renderer projectGrouping 的+ * "同一工作区"同源(存储归一化 + worktree 折叠到主仓)。与全仓现状一致,+ * **不做大小写折叠**——大小写不同的路径视为不同工作区;改口径要连+ * projectGrouping 一起改,不在本模块单点偏离。+ */++import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';++/** 从候选会话行里挑与目标目录同工作区的最近活跃一条;查无返回 null。 */+export function pickSessionForWorkdir(+ rows: ReadonlyArray<{ id: string; workingDir: string | null; updatedAt: number }>,+ dirAbs: string,+): string | null {+ const targetKey = normalizeWorkingDirForGrouping(dirAbs);+ if (targetKey == null) return null;+ let best: { id: string; updatedAt: number } | null = null;+ for (const row of rows) {+ if (normalizeWorkingDirForGrouping(row.workingDir) !== targetKey) continue;+ if (best === null || row.updatedAt > best.updatedAt) {+ best = { id: row.id, updatedAt: row.updatedAt };+ }+ }+ return best?.id ?? null;+}diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex e11e767659..e4d263b026 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -29,6 +29,7 @@ const SESSION_SOURCES = ['scheduler','learn','shared',+ 'plugin',] as const satisfies readonly SessionSource[];export const sessions = sqliteTable(diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.tsindex ed25425259..4a359d5ca0 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts@@ -176,20 +176,6 @@ describe('XD 网关权威模型清单重建', () => {id: 'missing-output',inputCostPerToken: 0.000012,},- {- id: 'cached-half-price',- costDiscount: 0.5,- inputCostPerToken: 0.000012,- outputCostPerToken: 0.000036,- cacheReadInputTokenCost: 0.000012,- cacheCreationInputTokenCost: 0.000036,- },- {- id: 'cache-only-priced',- inputCostPerToken: 0,- outputCostPerToken: 0,- cacheReadInputTokenCost: 0.000012,- },]);const cc = xdModels('claude-code');@@ -214,19 +200,6 @@ describe('XD 网关权威模型清单重建', () => {output: 36,});expect(cc.find((m) => m.id === 'missing-output')?.cost).toBeUndefined();- // 缓存维度随折扣一起投影;只免标准价、缓存带价的模型 cost 会暴露缓存价,- // 供展示层拒绝「免费」误标。- expect(cc.find((m) => m.id === 'cached-half-price')?.cost).toEqual({- input: 6,- output: 18,- cacheRead: 6,- cacheWrite: 18,- });- expect(cc.find((m) => m.id === 'cache-only-priced')?.cost).toEqual({- input: 0,- output: 0,- cacheRead: 12,- });});it('非法 effort 档位被白名单过滤;defaultEffort 不在档位集内时回落 high 规则', () => {diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 007c6df673..ec697fb302 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -58,7 +58,7 @@ export interface XdGatewayAgentOverride {defaultEnabled?: boolean;}-/** 服务端下发的 XD 网关聊天模型条目(shared/modelAccess ModelAccessGatewayModel 同形)。 */+/** 服务端下发的 XD 网关聊天模型条目(shared/modelAccess ModelAccessGatewayModel 的子集)。 */export interface XdGatewayModelInfo {id: string;/** AIGateway 折扣比例(0..1),折后价 = 原价 × (1 - costDiscount)。 */@@ -66,7 +66,7 @@ export interface XdGatewayModelInfo {/** AIGateway 标准 token 单价(per token)。 */inputCostPerToken?: number;outputCostPerToken?: number;- /** AIGateway 缓存 token 单价(per token);参与「免费」判定,防止只免标准价的模型误标免费。 */+ /** AIGateway 缓存 token 单价(per token);参与「免费」判定与价格展示。 */cacheReadInputTokenCost?: number;cacheCreationInputTokenCost?: number;/** 进哪些 runtime tab;缺省 = 仅 claude-code 兜底。 */diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex f335e83a1c..09b085b792 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -461,7 +461,14 @@ import {runGhostAssistantReplyHook,screenGhostUserMessage,setGhostAgentTurnRunner,+ setGhostWorkspaceSessionService,+ notifyGhostSessionEvent,} from '../cindy-brain/index.js';+import {+ createPluginDraftSession,+ findActiveSessionByWorkdir,+} from '../localDb/ipc/pluginWorkspaceSessions.js';+import { openMainWindowSession } from '../deepLink.js';const log = createLogger('maker-ipc');@@ -4919,6 +4926,46 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions};});+ // Ghost 的 workspace 槽:判重/创建走 localDb 服务,创建后广播与 scheduler+ // 同一条 `local-db:sessions:created` 通道让侧边栏刷新;focus 复用 deep link+ // 的会话聚焦通道。注入方式与 setGhostAgentTurnRunner 同款倒置,避免+ // cindy-brain 反向依赖 maker-ipc / localDb 形成模块环。+ setGhostWorkspaceSessionService({+ findActiveSessionByWorkdir,+ createDraftSession: async (params) => {+ // draft 跟随用户在 New Maker 面板的当前选择,与用户手建草稿的默认体验+ // 一致。main 侧缓存没有"当前激活 vendor"信号,取有选择记录的一档:+ // cc 有记录用 cc;cc 无记录而 codex 有则整套跟 codex(agentKind 一起切,+ // 避免给 codex-only 用户建出带 Claude 默认值的 cc 会话);都没有走+ // mapper 兜底。+ const ccDefaults = getWorkerDefaultsFromNewMaker('claude-code');+ const codexDefaults = ccDefaults.model ? null : getWorkerDefaultsFromNewMaker('codex');+ const picked = ccDefaults.model+ ? { agentKind: 'cc' as const, d: ccDefaults }+ : codexDefaults?.model+ ? { agentKind: 'codex' as const, d: codexDefaults }+ : null;+ 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 } : {}),+ },+ }+ : {}),+ notifySessionCreated: (info) => notifyGhostSessionEvent('created', info),+ });+ broadcastSessionCreated(sessionId);+ return sessionId;+ },+ focusSession: (sessionId) => openMainWindowSession(sessionId),+ });+// 排队项会进 pendingQueue projection, 经 Electron IPC 结构化克隆发给 renderer,// vendorOptions 里只能保留原始值条目 —— buildCreateOptsWithStderr 注入的// onStderrLine 函数、orca rehydrate 塞的运行时对象都克隆不了, 不剥掉diff --git a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts b/apps/desktop/src/main/usage/__tests__/modelPricing.test.tsindex 8cc35b7fa1..e75814400b 100644--- a/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts+++ b/apps/desktop/src/main/usage/__tests__/modelPricing.test.ts@@ -156,76 +156,6 @@ describe('gateway model pricing projection', () => {expect(mocks.send).toHaveBeenCalledWith(MODEL_PRICING_CHANGED_CHANNEL, pricing);});- it('applies gateway costDiscount to quotes and keeps originals for display', async () => {- const pricing = replaceGatewayModelPricing([- {- id: 'half-price',- costDiscount: 0.5,- inputCostPerToken: 0.000012,- outputCostPerToken: 0.000036,- cacheReadInputTokenCost: 0.000012,- },- {- id: 'invalid-discount',- costDiscount: 1.2,- inputCostPerToken: 0.000012,- outputCostPerToken: 0.000036,- },- {- // codex/ 折扣路由的 0.15 乘数是客户端权威,不与服务端 costDiscount 叠加。- id: 'codex/gpt-5.5',- costDiscount: 0.5,- inputCostPerToken: 0.00002,- outputCostPerToken: 0.00004,- },- ]);-- expect(pricing).toEqual({- xd: {- 'half-price': {- providerId: 'xd',- modelId: 'half-price',- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),- source: 'gateway',- approximate: false,- inputPerMtok: 6,- outputPerMtok: 18,- cacheReadPerMtok: 6,- discount: 0.5,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,- originalCacheReadPerMtok: 12,- },- 'invalid-discount': {- providerId: 'xd',- modelId: 'invalid-discount',- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),- source: 'gateway',- approximate: false,- inputPerMtok: 12,- outputPerMtok: 36,- },- 'codex/gpt-5.5': {- providerId: 'xd',- modelId: 'codex/gpt-5.5',- currency: gatewayCurrencyForRegion(CURRENT_CINDY_REGION),- source: 'gateway',- approximate: false,- inputPerMtok: 3,- outputPerMtok: 6,- },- },- });-- // 折扣元数据经磁盘缓存整组存活,冷启动记账与展示口径不回退到原价。- await vi.waitFor(async () => {- const raw = JSON.parse(await readFile(userDataPath('cache', 'model-pricing.json'), 'utf8'));- expect(raw.pricing).toEqual(pricing);- });- __resetModelPricingCacheForTesting();- await expect(getModelPricing()).resolves.toEqual(pricing);- });-it('keeps legal zero tiers but drops missing, invalid and 0/0 standard prices', () => {const pricing = replaceGatewayModelPricing([{diff --git a/apps/desktop/src/main/usage/modelPricing.ts b/apps/desktop/src/main/usage/modelPricing.tsindex 031cfd3362..652c35587d 100644--- a/apps/desktop/src/main/usage/modelPricing.ts+++ b/apps/desktop/src/main/usage/modelPricing.ts@@ -114,26 +114,6 @@ function validateQuote(if (isNonNegativeFinite(quote.cacheCreatePerMtok)) {next.cacheCreatePerMtok = quote.cacheCreatePerMtok;}- // 折扣元数据整组透传:discount 合法且带完整 input/output 原价才保留,避免残缺- // 缓存数据让展示层重建出错误的划线原价。- if (- typeof quote.discount === 'number' &&- Number.isFinite(quote.discount) &&- quote.discount > 0 &&- quote.discount <= 1 &&- isNonNegativeFinite(quote.originalInputPerMtok) &&- isNonNegativeFinite(quote.originalOutputPerMtok)- ) {- next.discount = quote.discount;- next.originalInputPerMtok = quote.originalInputPerMtok;- next.originalOutputPerMtok = quote.originalOutputPerMtok;- if (isNonNegativeFinite(quote.originalCacheReadPerMtok)) {- next.originalCacheReadPerMtok = quote.originalCacheReadPerMtok;- }- if (isNonNegativeFinite(quote.originalCacheCreatePerMtok)) {- next.originalCacheCreatePerMtok = quote.originalCacheCreatePerMtok;- }- }return next;}diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex be605faecc..3ba1e46238 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -27,6 +27,8 @@ import { contextBridge, ipcRenderer } from 'electron';* 系统选文件夹窗口由主机弹,用户亲选即授权,守门全在主机侧 pickSlot。* - preview(req):preview 槽的便捷口——send({type:'preview-request', …req})* 的语法糖;URL 白名单守门在主机侧 previewSlot。+ * - workspace(req):workspace 槽的便捷口——send({type:'workspace-request',+ * …req}) 的语法糖;目录授权与会话创建守门全在主机侧 workspaceSlot。*/type HostMessageListener = (payload: unknown) => void;@@ -60,4 +62,6 @@ contextBridge.exposeInMainWorld('cindy', {ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'pick-request' }),preview: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'preview-request' }),+ workspace: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'workspace-request' }),});diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.tsindex a11d69fd9a..3b9d146555 100644--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts@@ -112,10 +112,12 @@ describe('automation-generated sessions', () => {'scheduler','learn','shared',+ 'plugin',]);expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('feishu');expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('telegram');expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('discord');+ expect(DESKTOP_VISIBLE_SESSION_SOURCES).toContain('plugin');expect(normalizeSessionSource('desktop')).toBe('desktop');expect(normalizeSessionSource('scheduler')).toBe('scheduler');@@ -123,6 +125,7 @@ describe('automation-generated sessions', () => {expect(normalizeSessionSource('feishu')).toBe('feishu');expect(normalizeSessionSource('telegram')).toBe('telegram');expect(normalizeSessionSource('discord')).toBe('discord');+ expect(normalizeSessionSource('plugin')).toBe('plugin');expect(normalizeSessionSource(null)).toBe('desktop');expect(normalizeSessionSource('unknown')).toBe('desktop');});diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.tsindex 94c5fcb8b8..f00e148f66 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts@@ -503,11 +503,8 @@ describe('ModelSelector trigger variants', () => {currency: 'CNY',source: 'gateway',approximate: false,- inputPerMtok: 6,- outputPerMtok: 18,- discount: 0.5,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,+ inputPerMtok: 12,+ outputPerMtok: 36,},},};@@ -582,11 +579,8 @@ describe('ModelSelector trigger variants', () => {currency: 'CNY',source: 'gateway',approximate: false,- inputPerMtok: 6,- outputPerMtok: 18,- discount: 0.5,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,+ inputPerMtok: 12,+ outputPerMtok: 36,},},};@@ -834,11 +828,8 @@ describe('ModelSelector trigger variants', () => {currency: 'CNY',source: 'gateway',approximate: false,- inputPerMtok: 6,- outputPerMtok: 18,- discount: 0.5,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,+ inputPerMtok: 12,+ outputPerMtok: 36,},},};diff --git a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts b/apps/desktop/src/renderer/__tests__/projectGrouping.test.tsindex 8a964c2a5c..eb1034d524 100644--- a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts+++ b/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts@@ -46,6 +46,7 @@ function s(partial: Partial<Session>): Session {userSendAt,status: partial.status ?? 'active',agentKind: partial.agentKind ?? 'cc',+ source: partial.source,remoteHostId: partial.remoteHostId ?? null,deviceLinkDeviceId: partial.deviceLinkDeviceId,deviceLinkDeviceName: partial.deviceLinkDeviceName,@@ -493,6 +494,18 @@ describe('groupSessions', () => {expect(r.projects[0].sessions[0]).toBe(orphan);});+ // scheduler / plugin 来源豁免草稿判定:零消息也落项目分组。scheduler 由+ // 自动化任务显式绑定目录;plugin 是 workspace 槽建的空会话入口——零消息+ // 落在项目分组正是功能本身,掉未分类则功能不成立。+ it('keeps zero-message scheduler/plugin sessions in their project group (draft exemption)', () => {+ const scheduler = s({ workingDir: '/p/auto', userSendAt: null, source: 'scheduler' });+ const plugin = s({ workingDir: '/p/auto', userSendAt: null, source: 'plugin' });+ const r = groupSessions([scheduler, plugin]);+ expect(r.unclassified).toHaveLength(0);+ expect(r.projects).toHaveLength(1);+ expect(r.projects[0].sessions).toHaveLength(2);+ });+it('allows manually imported external sessions to create standalone projects', () => {const importedCodex = s({id: 'codex-019dcd5a-6e54-7960-95e0-aa68117a28d1',diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex 240d80a756..41a01a7c17 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -16,6 +16,7 @@ import {FileCode2,FilePen,FolderOpen,+ FolderPlus,Globe,GraduationCap,KeyRound,@@ -58,6 +59,7 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {pick: FolderOpen,preview: AppWindow,skill: GraduationCap,+ workspace: FolderPlus,};function itemIcon(item: GhostPermissionItem): LucideIcon {diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex 377bfed079..d9ab791db4 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -648,9 +648,8 @@ function ModelSelectorContentView({// ── 模型单价 ─────────────────────────────────────────────────────────────// providerId 是价格索引的一部分。同模型经 XD / OpenAI / Anthropic 等来源出现时,- // 必须按实际行来源查价,不能退化为 pricing[modelId]。XD Gateway quote 本身即- // 折后实付口径(原价在 quote.original*),CatalogModel.cost 只作「明确全零 →- // 免费」的证据;其它来源保持价格源自带的币种。+ // 必须按实际行来源查价,不能退化为 pricing[modelId]。只有 XD Gateway 目录价会+ // 叠加 CatalogModel.cost 作为折后展示价;其它来源保持价格源自带的币种。const pricePresentationOf = (providerId: string | null, id: string) => {// device-link 只同步被控端 provider 目录,不同步价格快照;不能把控制端价格与// 被控端 CatalogModel.cost 拼成一个展示结果。在协议补齐前远程选择器不展示价格。diff --git a/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx b/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsxindex 473a811215..ea6b71b9f8 100644--- a/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/GhostGrantConfirmCard.tsx@@ -68,7 +68,9 @@ export function GhostGrantConfirmCard({ pending, onRespond }: GhostGrantConfirmC? 'ghostGrant.confirm.descriptionDir': pending.lane === 'fs_write'? 'ghostGrant.confirm.descriptionFsWrite'- : 'ghostGrant.confirm.descriptionSaveDir';+ : pending.lane === 'workspace'+ ? 'ghostGrant.confirm.descriptionWorkspace'+ : 'ghostGrant.confirm.descriptionSaveDir';return (<divdiff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.tsindex 5ab5a78c9b..7999dd9124 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts@@ -368,9 +368,11 @@ export function pinnedSessionIdsInDisplayOrder(sessions: readonly Session[]): st* - projects 按 latestActivityAt desc;组内 sessions 按 status → sortTime desc** 草稿判定:workingDir 缺失 OR- * (非 scheduler / 非 Orca lead 且 userSendAt == null AND _count.messages === 0)+ * (非 scheduler / 非 plugin / 非 Orca lead 且 userSendAt == null AND _count.messages === 0)* → 归未分类。scheduler session 的归属由自动化任务配置决定,刚绑定时可能- * 还没落 user prompt/message count,不能按用户手动草稿处理。+ * 还没落 user prompt/message count,不能按用户手动草稿处理。plugin session+ * 是插件经 workspace 槽为指定目录创建的空会话入口——"零消息落在项目分组"+ * 正是它的产品目的,套草稿规则会让它掉未分类、功能不成立。** 异常输入:* - 空数组 / 全 null → 各段返回空数组@@ -402,6 +404,8 @@ export function groupSessions(// 可靠的"非空"证据,避免把这类孤儿错判成草稿堆到未分类。// scheduler 会话不套这条草稿规则:它由自动化任务显式绑定 workingDir,且// session-bound 事件可能早于 user prompt/message count 落库。+ // plugin 会话(workspace 槽)同样豁免:它就是插件为目录准备的零消息会话+ // 入口,创建时目录已经过用户授权,落项目分组是功能本身。const unclassified: Session[] = [];const dialogues: Session[] = [];const groups = new Map<string, Session[]>();@@ -414,10 +418,10 @@ export function groupSessions(const dir = normalizeWorkingDir(s.workingDir);const noPhysicalMessages = (s._count?.messages ?? 0) === 0;const isOrcaLead = isOrcaLeadSession(s);- const isSchedulerSession = s.source === 'scheduler';+ const isAutoPlacedSession = s.source === 'scheduler' || s.source === 'plugin';if (dir == null ||- (!isSchedulerSession && !isOrcaLead && s.userSendAt == null && noPhysicalMessages)+ (!isAutoPlacedSession && !isOrcaLead && s.userSendAt == null && noPhysicalMessages)) {unclassified.push(s);} else {diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 13cbf4f748..31f04be562 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -18,6 +18,7 @@ import {FileCode2,FilePen,FolderOpen,+ FolderPlus,Globe,GraduationCap,KeyRound,@@ -88,6 +89,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {pick: FolderOpen,preview: AppWindow,skill: GraduationCap,+ workspace: FolderPlus,};/** Chooses a visual affordance without changing the host-owned permission title or meaning. */diff --git a/apps/desktop/src/renderer/hooks/useModelPricing.ts b/apps/desktop/src/renderer/hooks/useModelPricing.tsindex 86dd86eb51..1e4bc98f1f 100644--- a/apps/desktop/src/renderer/hooks/useModelPricing.ts+++ b/apps/desktop/src/renderer/hooks/useModelPricing.ts@@ -2,7 +2,10 @@import { useEffect, useState } from 'react';-import type { ModelPriceQuote, ModelPricingCatalog } from '../../shared/regionalMoney';+import type {+ ModelPriceQuote,+ ModelPricingCatalog,+} from '../../shared/regionalMoney';let cache: ModelPricingCatalog | null = null;let cacheLoaded = false;@@ -27,23 +30,10 @@ function isValidQuote(quote.approximate === false &&isNonNegativeFinite(quote.inputPerMtok) &&isNonNegativeFinite(quote.outputPerMtok) &&- (quote.cacheReadPerMtok === undefined || isNonNegativeFinite(quote.cacheReadPerMtok)) &&- (quote.cacheCreatePerMtok === undefined || isNonNegativeFinite(quote.cacheCreatePerMtok)) &&- // 折扣元数据可选;discount 存在时必须合法且带完整 input/output 原价。- (quote.discount === undefined ||- (typeof quote.discount === 'number' &&- Number.isFinite(quote.discount) &&- quote.discount > 0 &&- quote.discount <= 1 &&- isNonNegativeFinite(quote.originalInputPerMtok) &&- isNonNegativeFinite(quote.originalOutputPerMtok))) &&- (quote.originalInputPerMtok === undefined || isNonNegativeFinite(quote.originalInputPerMtok)) &&- (quote.originalOutputPerMtok === undefined ||- isNonNegativeFinite(quote.originalOutputPerMtok)) &&- (quote.originalCacheReadPerMtok === undefined ||- isNonNegativeFinite(quote.originalCacheReadPerMtok)) &&- (quote.originalCacheCreatePerMtok === undefined ||- isNonNegativeFinite(quote.originalCacheCreatePerMtok))+ (quote.cacheReadPerMtok === undefined ||+ isNonNegativeFinite(quote.cacheReadPerMtok)) &&+ (quote.cacheCreatePerMtok === undefined ||+ isNonNegativeFinite(quote.cacheCreatePerMtok)));}@@ -55,8 +45,8 @@ function isValidCatalog(v: unknown): v is ModelPricingCatalog {!!rawModels &&typeof rawModels === 'object' &&!Array.isArray(rawModels) &&- Object.entries(rawModels as Record<string, unknown>).every(([modelId, quote]) =>- isValidQuote(quote, providerId, modelId),+ Object.entries(rawModels as Record<string, unknown>).every(+ ([modelId, quote]) => isValidQuote(quote, providerId, modelId),),);}@@ -88,11 +78,12 @@ export function useModelPricing(): ModelPricingCatalog | null {useEffect(() => {let active = true;- const unsubscribe = window.electronAPI.maker.usage.onModelPricingChanged((next) => {- cacheLoaded = true;- cache = isValidCatalog(next) ? next : null;- if (active) setPricing(cache);- });+ const unsubscribe =+ window.electronAPI.maker.usage.onModelPricingChanged((next) => {+ cacheLoaded = true;+ cache = isValidCatalog(next) ? next : null;+ if (active) setPricing(cache);+ });void load().then((res) => {if (active) setPricing(res);});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 8bc6238133..daa808064e 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2427,6 +2427,8 @@"noChange": "No permission changes.","pick": "Can ask you to pick a folder for it","pickDetail": "When it asks, Cindy shows the system folder picker; you decide what to share, and cancelling gives it nothing.",+ "workspace": "Can ask to create a session entry for a project folder in the sidebar",+ "workspaceDetail": "When it asks, you either pick the folder yourself or see the full path on a confirmation card before deciding; while it is handling a call you started, subfolders inside the current session's working directory are used directly without an extra prompt. Folders that already have a session are reused, and what gets created is an empty session — nothing starts running on its own.","sessionContext": "Can learn which project folder the current session is working in","sessionContextDetail": "Shares only location facts (session ID and project folder path) while it works for the current session — no file contents, and no file access is granted.","preview": "Can open preview pages from the sites below in the sidebar browser",@@ -2522,7 +2524,8 @@"slotNetwork": "Network access","slotNotify": "System tips","slotFs": "File writing",- "slotSkill": "Agent skills"+ "slotSkill": "Agent skills",+ "slotWorkspace": "Workspace sessions"},"commandPaletteTag": "Plugin command","updateConfirm": {@@ -2534,6 +2537,10 @@"pick": {"dialogTitle": "Choose a folder","dialogMessage": "Plugin “{{name}}” is asking you to choose a folder"+ },+ "workspace": {+ "dialogTitle": "Choose a project folder",+ "dialogMessage": "Plugin “{{name}}” is asking you to choose a project folder to create a session in the sidebar"}},"mcp": {@@ -6169,6 +6176,7 @@"descriptionDir": "The directory/file below is outside this session's working directory. If you allow, its files will be handed to this plugin for upload (it only receives a one-time ticket, never paths).","descriptionSaveDir": "The directory below is outside this session's working directory. If you allow, this plugin can save downloaded files into it (existing files are never overwritten).","descriptionFsWrite": "This plugin requests to write the files below into the current session's working directory. If you allow, further writes to the same directory in this session won't ask again.",+ "descriptionWorkspace": "This folder is outside this session's working directory. If you allow, Cindy creates an empty session for it in the sidebar (an existing session is reused) without reading any files inside.","dirMeta": "{{count}} files · {{size}}","directory": "Directory","allowDirs": "Also allow their folders (media files in the same folders won't ask again this session)",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 5eceb28f17..060d22759c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2426,6 +2426,8 @@"noChange": "権限に変更はありません。","pick": "フォルダの選択をあなたに依頼できます","pickDetail": "依頼があると、Cindy がシステムのフォルダ選択ウィンドウを表示します。どのフォルダを渡すかはあなたが直接決め、キャンセルすれば何も渡りません。",+ "workspace": "プロジェクトフォルダのセッション入口をサイドバーに作成するよう依頼できます",+ "workspaceDetail": "依頼があると、あなたが直接フォルダを選ぶか、確認カードでフルパスを見てから許可を決めます。あなたが開始した呼び出しの処理中は、現在のセッションの作業ディレクトリ内のサブフォルダは追加確認なしで使用されます。既にセッションがあるフォルダは再利用され、重複作成はされません。作成されるのは空のセッションだけで、勝手にタスクが始まることはありません。","sessionContext": "現在のセッションが使用中のプロジェクトフォルダの場所を知ることができます","sessionContextDetail": "現在のセッションのために動作するときだけ、場所の情報(セッション ID とプロジェクトフォルダのパス)を伝えます。ファイルの内容は含まれず、ファイルへのアクセス権も与えられません。","preview": "以下のサイトのプレビューページをサイドバーのブラウザで開けます",@@ -2521,7 +2523,8 @@"slotNetwork": "ネットワークアクセス","slotNotify": "システム通知","slotFs": "ファイル書き込み",- "slotSkill": "エージェントスキル"+ "slotSkill": "エージェントスキル",+ "slotWorkspace": "ワークスペースセッション"},"commandPaletteTag": "プラグインコマンド","updateConfirm": {@@ -2533,6 +2536,10 @@"pick": {"dialogTitle": "フォルダを選択","dialogMessage": "プラグイン「{{name}}」がフォルダの選択を求めています"+ },+ "workspace": {+ "dialogTitle": "プロジェクトフォルダを選択",+ "dialogMessage": "プラグイン「{{name}}」がサイドバーにセッションを作成するため、プロジェクトフォルダの選択を求めています"}},"mcp": {@@ -6159,6 +6166,7 @@"descriptionDir": "以下のディレクトリ/ファイルは現在のセッションの作業ディレクトリの外にあります。許可すると、その中のファイルがアップロード用にこのプラグインへ渡されます(渡されるのはワンタイムチケットのみで、パスは渡されません)。","descriptionSaveDir": "以下のディレクトリは現在のセッションの作業ディレクトリの外にあります。許可すると、このプラグインがダウンロードしたファイルをここに保存できます(既存ファイルは上書きされません)。","descriptionFsWrite": "このプラグインは現在のセッションの作業ディレクトリに以下のファイルを書き込もうとしています。許可すると、このセッション中は同じディレクトリへの書き込みは再確認されません。",+ "descriptionWorkspace": "このフォルダは現在のセッションの作業ディレクトリの外にあります。許可すると、Cindy がこのフォルダを作業ディレクトリとする空のセッションをサイドバーに作成します(既にセッションがある場合は再利用)。中のファイルは読み取りません。","dirMeta": "{{count}} 個のファイル · {{size}}","directory": "ディレクトリ","allowDirs": "これらのファイルのフォルダーも許可(このセッション中、同じフォルダーのメディアファイルは再確認しません)",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 468a913bc0..b9cf8235ef 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2426,6 +2426,8 @@"noChange": "권한 변경이 없습니다.","pick": "폴더 선택을 요청할 수 있습니다","pickDetail": "요청 시 Cindy가 시스템 폴더 선택 창을 띄웁니다. 어떤 폴더를 넘길지는 직접 결정하며, 취소하면 아무것도 전달되지 않습니다.",+ "workspace": "프로젝트 폴더의 세션 항목을 사이드바에 만들도록 요청할 수 있습니다",+ "workspaceDetail": "요청 시 직접 폴더를 선택하거나 확인 카드에서 전체 경로를 본 뒤 허용 여부를 결정합니다. 사용자가 시작한 호출을 처리하는 동안에는 현재 세션 작업 디렉터리 안의 하위 폴더는 추가 확인 없이 사용됩니다. 이미 세션이 있는 폴더는 재사용되어 중복 생성되지 않습니다. 만들어지는 것은 빈 세션뿐이며 스스로 작업을 시작하지 않습니다.","sessionContext": "현재 세션이 사용 중인 프로젝트 폴더 위치를 알 수 있습니다","sessionContextDetail": "현재 세션을 위해 작동할 때만 위치 정보(세션 ID와 프로젝트 폴더 경로)를 전달합니다. 파일 내용은 포함되지 않으며 파일 접근 권한도 부여되지 않습니다.","preview": "아래 사이트의 미리보기 페이지를 사이드바 브라우저에서 열 수 있습니다",@@ -2521,7 +2523,8 @@"slotNetwork": "네트워크 접근","slotNotify": "시스템 알림","slotFs": "파일 쓰기",- "slotSkill": "에이전트 스킬"+ "slotSkill": "에이전트 스킬",+ "slotWorkspace": "워크스페이스 세션"},"commandPaletteTag": "플러그인 명령","updateConfirm": {@@ -2533,6 +2536,10 @@"pick": {"dialogTitle": "폴더 선택","dialogMessage": "플러그인 \"{{name}}\"이(가) 폴더 선택을 요청합니다"+ },+ "workspace": {+ "dialogTitle": "프로젝트 폴더 선택",+ "dialogMessage": "플러그인 \"{{name}}\"이(가) 사이드바에 세션을 만들기 위해 프로젝트 폴더 선택을 요청합니다"}},"mcp": {@@ -6159,6 +6166,7 @@"descriptionDir": "아래 디렉터리/파일은 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 그 안의 파일이 업로드를 위해 이 플러그인에 전달됩니다(일회용 티켓만 전달되며 경로는 전달되지 않습니다).","descriptionSaveDir": "아래 디렉터리는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 이 플러그인이 다운로드한 파일을 여기에 저장할 수 있습니다(기존 파일은 덮어쓰지 않습니다).","descriptionFsWrite": "이 플러그인이 현재 세션의 작업 디렉터리에 아래 파일을 쓰려고 합니다. 허용하면 이 세션 동안 같은 디렉터리에 대한 이후 쓰기는 다시 묻지 않습니다.",+ "descriptionWorkspace": "이 폴더는 현재 세션의 작업 디렉터리 밖에 있습니다. 허용하면 Cindy가 이 폴더를 작업 디렉터리로 하는 빈 세션을 사이드바에 만듭니다(이미 세션이 있으면 재사용). 폴더 안의 파일은 읽지 않습니다.","dirMeta": "파일 {{count}}개 · {{size}}","directory": "디렉터리","allowDirs": "이 파일들의 폴더도 허용(이 세션에서 같은 폴더의 미디어 파일은 다시 묻지 않습니다)",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex ac30aa50db..eefa9a3d16 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2426,6 +2426,8 @@"noChange": "权限无变化。","pick": "可请求你选择一个文件夹交给它","pickDetail": "它发起请求时,Cindy 会弹出系统的选择文件夹窗口;选哪个、给不给,都由你亲手决定,取消则它什么都拿不到。",+ "workspace": "可请求为项目文件夹在侧边栏创建会话入口",+ "workspaceDetail": "它发起请求时,由你亲手选择文件夹,或在确认卡上看到完整路径后再决定;它正在处理你发起的调用时,当前会话工作目录内的子文件夹可直接使用,不再单独确认。文件夹已有会话时直接复用,不重复创建。创建的只是空会话,不会自动开始任何任务。","sessionContext": "可获知当前会话正在使用的项目文件夹位置","sessionContextDetail": "只在它为当前会话干活时告知位置信息(会话编号与项目文件夹路径),不包含文件内容,也不因此获得文件访问权。","preview": "可在右侧栏浏览器中打开以下网站的预览页面",@@ -2521,7 +2523,8 @@"slotNetwork": "网络访问","slotNotify": "系统提示","slotFs": "写文件",- "slotSkill": "Agent 技能"+ "slotSkill": "Agent 技能",+ "slotWorkspace": "工作区会话"},"commandPaletteTag": "插件指令","updateConfirm": {@@ -2533,6 +2536,10 @@"pick": {"dialogTitle": "选择文件夹","dialogMessage": "插件「{{name}}」请求你选择一个文件夹"+ },+ "workspace": {+ "dialogTitle": "选择项目文件夹",+ "dialogMessage": "插件「{{name}}」请求你选择一个项目文件夹,用于在侧边栏创建会话"}},"mcp": {@@ -6159,6 +6166,7 @@"descriptionDir": "以下目录/文件在当前会话的工作目录之外。允许后,其中的文件会交给该插件上传(它只拿到一次性票据,拿不到路径)。","descriptionSaveDir": "以下目录在当前会话的工作目录之外。允许后,该插件可以把下载的文件存入其中(不会覆盖已有文件)。","descriptionFsWrite": "该插件请求在当前会话的工作目录写入以下文件。允许后,本会话内它写同一目录不再询问。",+ "descriptionWorkspace": "该文件夹在当前会话的工作目录之外。允许后,Cindy 会以它为工作目录在侧边栏创建一个空会话(已有会话时直接复用),不会读取其中的文件。","dirMeta": "{{count}} 个文件 · {{size}}","directory": "目录","allowDirs": "同时允许这些文件所在目录(本会话内同目录媒体文件不再询问)",diff --git a/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts b/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.tsindex edebb303af..4053f9016e 100644--- a/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/modelPriceFormat.test.ts@@ -50,20 +50,12 @@ describe('modelPriceFormat', () => {]);});- it('presents a discounted quote with its carried originals and badge values', () => {- const discounted = quote({- inputPerMtok: 6,- outputPerMtok: 18,- cacheReadPerMtok: 0.15,- discount: 0.5,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,- originalCacheReadPerMtok: 0.3,- });- expect(modelPricePresentation(discounted, { input: 6, output: 18 })).toEqual({+ it('uses the effective price while retaining the original for a 50% discount', () => {+ const original = quote({ inputPerMtok: 12, outputPerMtok: 36 });+ expect(modelPricePresentation(original, { input: 6, output: 18 })).toEqual({kind: 'priced',- current: quote({ inputPerMtok: 6, outputPerMtok: 18, cacheReadPerMtok: 0.15 }),- original: quote({ inputPerMtok: 12, outputPerMtok: 36, cacheReadPerMtok: 0.3 }),+ current: quote({ inputPerMtok: 6, outputPerMtok: 18 }),+ original,discount: 0.5,});expect(modelPriceDiscountLabelValues(0.5)).toEqual({@@ -76,46 +68,34 @@ describe('modelPriceFormat', () => {});expect(modelPriceDetailRows(- quote({ inputPerMtok: 6, outputPerMtok: 18, cacheReadPerMtok: 0.15 }),- quote({ inputPerMtok: 12, outputPerMtok: 36, cacheReadPerMtok: 0.3 }),+ quote({ inputPerMtok: 6, outputPerMtok: 18, cacheReadPerMtok: 0.3 }),+ original,),).toEqual([{ kind: 'input', value: '¥6', originalValue: '¥12' },{ kind: 'output', value: '¥18', originalValue: '¥36' },- { kind: 'cacheRead', value: '¥0.15', originalValue: '¥0.3' },+ { kind: 'cacheRead', value: '¥0.3' },]);});- it('marks only an all-zero cost with a confirmed missing quote as free', () => {+ it('marks only an explicit double-zero model price with a confirmed missing quote as free', () => {expect(modelPricePresentation(null, { input: 0, output: 0 })).toEqual({kind: 'free',});- expect(- modelPricePresentation(null, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }),- ).toEqual({ kind: 'free' });expect(modelPricePresentation(undefined, { input: 0, output: 0 })).toBeNull();- // 缓存维度带价 ⇒ 不是免费模型;标准报价被 0/0 规则丢弃后宁可不展示价格。- expect(modelPricePresentation(null, { input: 0, output: 0, cacheRead: 8.4 })).toBeNull();- expect(modelPricePresentation(null, { input: 0, output: 0, cacheWrite: 15 })).toBeNull();});- it('keeps a 100% discounted quote as a discount, never as free', () => {- const fullDiscount = quote({- inputPerMtok: 0,- outputPerMtok: 0,- discount: 1,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,- });- expect(modelPricePresentation(fullDiscount, { input: 0, output: 0 })).toEqual({+ it('keeps double-zero effective prices as a 100% discount when the quote is nonzero', () => {+ const original = quote({ inputPerMtok: 12, outputPerMtok: 36 });+ expect(modelPricePresentation(original, { input: 0, output: 0 })).toEqual({kind: 'priced',current: quote({ inputPerMtok: 0, outputPerMtok: 0 }),- original: quote({ inputPerMtok: 12, outputPerMtok: 36 }),+ original,discount: 1,});});- it('preserves the standard price when the quote carries no discount', () => {+ it('preserves the standard price when there is no discount', () => {const standard = quote({ inputPerMtok: 12, outputPerMtok: 36 });expect(modelPricePresentation(standard, { input: 12, output: 36 })).toEqual({kind: 'priced',@@ -123,30 +103,29 @@ describe('modelPriceFormat', () => {});});- it('ignores sub-threshold discounts on the quote', () => {- const noisy = quote({- inputPerMtok: 12,- outputPerMtok: 36,- discount: 1e-12,- originalInputPerMtok: 12,- originalOutputPerMtok: 36,- });- expect(modelPricePresentation(noisy, { input: 12, output: 36 })).toEqual({+ it('ignores sub-threshold floating-point discount noise', () => {+ const standard = quote({ inputPerMtok: 12, outputPerMtok: 36 });+ expect(+ modelPricePresentation(standard, {+ input: 12 * (1 - 1e-12),+ output: 36 * (1 - 1e-12),+ }),+ ).toEqual({kind: 'priced',- current: noisy,+ current: standard,});});- it('never derives a discount from catalog costs alone', () => {+ it('keeps missing or inconsistent display costs on the existing fallback path', () => {const standard = quote({ inputPerMtok: 12, outputPerMtok: 36 });- expect(modelPricePresentation(standard, { input: 6, output: 18 })).toEqual({+ expect(modelPricePresentation(standard, { input: 6 })).toEqual({kind: 'priced',current: standard,});- expect(modelPricePresentation(standard, { input: 6 })).toEqual({+ expect(modelPricePresentation(undefined, { input: 0 })).toBeNull();+ expect(modelPricePresentation(standard, { input: 6, output: 30 })).toEqual({kind: 'priced',current: standard,});- expect(modelPricePresentation(undefined, { input: 0 })).toBeNull();});});diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 90da3b9a5a..72a2f823d7 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -586,9 +586,10 @@ export interface PendingGhostGrantConfirm {/*** attachments = 媒体文件交给意识;dir = 上传目录/文件;save_dir = 允许意识* 往目录里存文件;fs_write = 意识申请写工作目录文件(会话 permission 为- * 逐条确认档时逐次弹,同目录本会话批一次)。+ * 逐条确认档时逐次弹,同目录本会话批一次);workspace = 意识申请以该目录+ * 为工作区在侧边栏创建/复用会话入口(不过户字节)。*/- lane: 'attachments' | 'dir' | 'save_dir' | 'fs_write';+ lane: 'attachments' | 'dir' | 'save_dir' | 'fs_write' | 'workspace';items: Array<{name: string;absPath: string;@@ -7110,7 +7111,13 @@ function parseGhostGrantConfirmRequest(request: {[k: string]: unknown;}): PendingGhostGrantConfirm | null {const lane = request.lane;- if (lane !== 'attachments' && lane !== 'dir' && lane !== 'save_dir' && lane !== 'fs_write')+ if (+ lane !== 'attachments' &&+ lane !== 'dir' &&+ lane !== 'save_dir' &&+ lane !== 'fs_write' &&+ lane !== 'workspace'+ )return null;if (typeof request.ghostId !== 'string' || typeof request.ghostName !== 'string') return null;const rawItems = Array.isArray(request.items) ? request.items : null;diff --git a/apps/desktop/src/renderer/lib/modelPriceFormat.ts b/apps/desktop/src/renderer/lib/modelPriceFormat.tsindex 3857bef7e4..ef8977567a 100644--- a/apps/desktop/src/renderer/lib/modelPriceFormat.ts+++ b/apps/desktop/src/renderer/lib/modelPriceFormat.ts@@ -3,8 +3,6 @@ import type { ModelPriceQuote, MoneyCurrency } from '../../shared/regionalMoney'interface EffectiveModelCost {input?: number;output?: number;- cacheRead?: number;- cacheWrite?: number;}const MIN_DISPLAY_DISCOUNT = 0.0005;@@ -49,11 +47,39 @@ function isNonNegativeFinite(value: unknown): value is number {return typeof value === 'number' && Number.isFinite(value) && value >= 0;}+function inferDiscount(+ quote: ModelPriceQuote,+ cost: Required<EffectiveModelCost>,+): number | undefined {+ // effectiveCost 无法提供缓存维度;若 quote 含非零缓存价,无法验证缓存折扣+ // 是否一致,不推断折扣以避免 badge 与缓存行价格不一致。+ if ((quote.cacheReadPerMtok && quote.cacheReadPerMtok > 0) ||+ (quote.cacheCreatePerMtok && quote.cacheCreatePerMtok > 0)) {+ return undefined;+ }+ const candidates: number[] = [];+ for (const [original, current] of [+ [quote.inputPerMtok, cost.input],+ [quote.outputPerMtok, cost.output],+ ] as const) {+ if (original === 0) {+ if (current !== 0) return undefined;+ continue;+ }+ const candidate = 1 - current / original;+ if (candidate < MIN_DISPLAY_DISCOUNT || candidate > 1) return undefined;+ candidates.push(candidate);+ }+ if (candidates.length === 0) return undefined;+ const discount = candidates[0];+ return candidates.every((candidate) => Math.abs(candidate - discount) < 1e-9)+ ? discount+ : undefined;+}+/**- * 构建模型选择器的展示价格。quote 即实付口径——Gateway costDiscount 已在构建- * quote 时套用(shared/modelPriceQuote.ts),用量记账与展示同价;折扣前原价由- * quote.original* 承载。CatalogModel.cost 只作为「明确全零 → 免费」的证据- * (含缓存维度),不再参与折扣推断。+ * 构建模型选择器的展示价格。quote 继续保留用量估算所需的标准价;+ * CatalogModel.cost 只承载 XD 模型的折后展示价。*/export function modelPricePresentation(quote: ModelPriceQuote | null | undefined,@@ -61,49 +87,38 @@ export function modelPricePresentation(): ModelPricePresentation | null {if (quote === undefined) return null;- if (quote === null) {- // 免费证据链:价格快照已成功加载但确认无该模型报价(quote === null),且目录- // cost 的所有计费维度(含缓存)都明确为 0。任何维度带价都不许出免费标签。- const input = effectiveCost?.input;- const output = effectiveCost?.output;- const allDimensionsZero =- isNonNegativeFinite(input) &&- input === 0 &&- isNonNegativeFinite(output) &&- output === 0 &&- (effectiveCost?.cacheRead === undefined || effectiveCost.cacheRead === 0) &&- (effectiveCost?.cacheWrite === undefined || effectiveCost.cacheWrite === 0);- return allDimensionsZero ? { kind: 'free' } : null;- }+ const input = effectiveCost?.input;+ const output = effectiveCost?.output;+ const hasEffectiveCost = isNonNegativeFinite(input) && isNonNegativeFinite(output);if (- quote.discount !== undefined &&- quote.discount >= MIN_DISPLAY_DISCOUNT &&- quote.originalInputPerMtok !== undefined &&- quote.originalOutputPerMtok !== undefined+ hasEffectiveCost &&+ input === 0 &&+ output === 0 &&+ (quote === null || (+ quote.inputPerMtok === 0 &&+ quote.outputPerMtok === 0 &&+ (!quote.cacheReadPerMtok || quote.cacheReadPerMtok === 0) &&+ (!quote.cacheCreatePerMtok || quote.cacheCreatePerMtok === 0)+ ))) {- const {- discount,- originalInputPerMtok,- originalOutputPerMtok,- originalCacheReadPerMtok,- originalCacheCreatePerMtok,- ...current- } = quote;- const original: ModelPriceQuote = {- ...current,- inputPerMtok: originalInputPerMtok,- outputPerMtok: originalOutputPerMtok,- ...(originalCacheReadPerMtok !== undefined- ? { cacheReadPerMtok: originalCacheReadPerMtok }- : {}),- ...(originalCacheCreatePerMtok !== undefined- ? { cacheCreatePerMtok: originalCacheCreatePerMtok }- : {}),- };- return { kind: 'priced', current, original, discount };+ return { kind: 'free' };}- return { kind: 'priced', current: quote };+ if (quote === null) return null;+ if (!hasEffectiveCost) return { kind: 'priced', current: quote };++ const discount = inferDiscount(quote, { input, output });+ if (discount === undefined) return { kind: 'priced', current: quote };+ return {+ kind: 'priced',+ current: {+ ...quote,+ inputPerMtok: input,+ outputPerMtok: output,+ },+ original: quote,+ discount,+ };}export function modelPriceDetailRows(@@ -145,14 +160,6 @@ export function modelPriceDetailRows({kind: 'cacheRead' as const,value: formatModelPriceAmount(quote.cacheReadPerMtok, quote.currency),- ...(originalQuote?.cacheReadPerMtok !== undefined- ? {- originalValue: formatModelPriceAmount(- originalQuote.cacheReadPerMtok,- originalQuote.currency,- ),- }- : {}),},]),...(quote.cacheCreatePerMtok === undefined@@ -161,14 +168,6 @@ export function modelPriceDetailRows({kind: 'cacheCreate' as const,value: formatModelPriceAmount(quote.cacheCreatePerMtok, quote.currency),- ...(originalQuote?.cacheCreatePerMtok !== undefined- ? {- originalValue: formatModelPriceAmount(- originalQuote.cacheCreatePerMtok,- originalQuote.currency,- ),- }- : {}),},]),];diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex cff7447e2e..62a287ee1f 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -2328,14 +2328,15 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / preexpect(withPreview({ hosts: ['a.example.com'], extra: 1 }).ok).toBe(false);});- it('session-context / pick 槽:纯槽声明即可装入,并生成对应权限项', () => {+ it('session-context / pick / workspace 槽:纯槽声明即可装入,并生成对应权限项', () => {const r = validateGhostManifest({...goodChipManifest(),- slots: ['panel', 'session-context', 'pick', 'preview'],+ slots: ['panel', 'session-context', 'pick', 'preview', 'workspace'],preview: { hosts: ['example.com'] },});expect(r.ok).toBe(true);if (!r.ok) return;+ expect(ghostContentKeys(r.manifest)).toContain('slotWorkspace');const items = ghostPermissionItems(r.manifest);expect(items).toEqual(expect.arrayContaining([@@ -2351,6 +2352,12 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / prelabelKey: 'preview',detail: 'example.com',}),+ expect.objectContaining({+ key: 'workspace',+ kind: 'workspace',+ labelKey: 'workspace',+ detailKey: 'workspaceDetail',+ }),]),);});diff --git a/apps/desktop/src/shared/billing.ts b/apps/desktop/src/shared/billing.tsindex 22367250ae..af58ce4f36 100644--- a/apps/desktop/src/shared/billing.ts+++ b/apps/desktop/src/shared/billing.ts@@ -88,10 +88,8 @@ export type BillingPaymentOrder = {status: BillingPaymentOrderStatus;paymentAction: BillingPaymentAction | null;/**- * Added by the fulfillment projection; informational only. Since PR #401 the- * checkout UX treats payment status SUCCEEDED as terminal (COMPLETED) and no- * longer keys any phase, recovery or polling behavior off this field —- * crediting is reconciled server-side for every SUCCEEDED order.+ * Added by the fulfillment projection. Older servers may omit it; checkout+ * currently infers COMPLETED from payment status alone (server reconciles).*/fulfillmentStatus?: BillingFulfillmentStatus;createdAt: string;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex e594c1e367..fb18fc9469 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -90,6 +90,12 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此* manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字* 一致,打包与装入双侧强制),装入确认框逐条列出并置于清单最上部。+ * 'workspace' = 工作区会话(2026-07-25):插件请主机在指定本机项目目录下确保+ * 存在一个会话入口并显示在侧边栏——目录下已有 active 会话即复用,没有才创建+ * 空 draft 会话(不拉起 agent 进程)。目录授权两条路:系统选文件夹窗口亲选+ * 即授权(pick 模式,路径不回沙箱),或 tool-call 语境下带在途 callId + 绝对+ * 路径(目录在该会话 workdir 内自动放行,workdir 外弹确认卡)。远程工作区+ * v1 一律拒(fail closed)。*/export const GHOST_SLOTS = ['subscribe',@@ -106,6 +112,7 @@ export const GHOST_SLOTS = ['pick','preview','skill',+ 'workspace',] as const;export type GhostSlot = (typeof GHOST_SLOTS)[number];@@ -1283,6 +1290,7 @@ export function ghostContentKeys(manifest: GhostManifest): string[] {else if (slot === 'fs') keys.push('slotFs');// skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。else if (slot === 'skill') keys.push('slotSkill');+ else if (slot === 'workspace') keys.push('slotWorkspace');// 'panel' 槽已由 manifest.panel 覆盖,不重复}return keys;@@ -1344,7 +1352,7 @@ export interface GhostPermissionItem {/** 稳定键:更新 diff 按它对齐(内容变化视为移除+新增,如面板换边)。 */key: string;/** 图标分组(renderer 按 kind 选图标)。 */- kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill';+ kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill' | 'workspace';/** i18n key 后缀,消费方拼 `settings.ghosts.perm.<labelKey>`。 */labelKey: string;/** i18n 插值参数(工具名、指令名、面板标题等)。 */@@ -1521,6 +1529,16 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItif (manifest.slots.includes('pick')) {items.push({ key: 'pick', kind: 'pick', labelKey: 'pick', detailKey: 'pickDetail' });}+ // workspace 槽:能为指定项目目录创建/复用侧边栏会话入口。授权动作是用户+ // 亲选目录或点确认卡,装入时只告知"它会来要"。+ if (manifest.slots.includes('workspace')) {+ items.push({+ key: 'workspace',+ kind: 'workspace',+ labelKey: 'workspace',+ detailKey: 'workspaceDetail',+ });+ }// session-context 槽:派活时可获知当前会话的项目目录位置(路径信息,// 非文件访问权;node 槽的执行权另行单列)。if (manifest.slots.includes('session-context')) {@@ -2250,7 +2268,7 @@ export function resolveGhostManifestLocale(? {secrets: manifest.network.secrets.map((secret) => ({...secret,- ...resource.network!.secrets![secret.key],+ ...(resource.network!.secrets![secret.key] ?? {}),})),}: {}),@@ -2258,7 +2276,7 @@ export function resolveGhostManifestLocale(? {connections: manifest.network.connections.map((connection) => ({...connection,- ...resource.network!.connections![connection.key],+ ...(resource.network!.connections![connection.key] ?? {}),})),}: {}),@@ -2271,7 +2289,7 @@ export function resolveGhostManifestLocale(...manifest.node,secretBindings: manifest.node.secretBindings?.map((binding) => ({...binding,- ...resource.node!.secretBindings![binding.key],+ ...(resource.node!.secretBindings![binding.key] ?? {}),})),},}@@ -4223,6 +4241,71 @@ export interface DirDepositReceiptShape {rel_paths: string[];}+/** workspace 槽:用途说明/新会话标题长度上限。 */+export const GHOST_WORKSPACE_TITLE_MAX_CHARS = 100;+/** workspace 槽:同一插件两次请求的最小间隔 ms(防确认卡/对话框骚扰)。 */+export const GHOST_WORKSPACE_MIN_INTERVAL_MS = 3000;++/**+ * 上行:workspace 槽——请主机在指定本机项目目录下确保存在一个会话入口+ * (侧边栏可见)。目录下已有 active 会话时复用(created:false),没有才创建+ * 空 draft 会话(不拉起 agent 进程)。目录授权两条路:+ * - mode:'pick':主机弹系统级选文件夹窗口,用户亲手选中即授权,绝对路径+ * 不回沙箱(与 pick 槽同一哲学);+ * - mode:'dir':传绝对路径 + 当前在途 ghost_call 的 callId(主机签发的上下文+ * 凭证,反查发起会话)。目录在该会话 workdir 内自动放行,workdir 外弹+ * 确认卡由用户决定(对齐 attachments/dir 过户的两档钳制)。+ * 远程工作区(SSH)v1 不支持,一律拒(fail closed)。+ */+export type GhostPipeWorkspaceRequest =+ | {+ type: 'workspace-request';+ kind: 'ensure-session';+ mode: 'pick';+ /** pick 模式选择框里的用途说明(净化后随插件名展示);也用作新会话标题。 */+ title?: string;+ /** 建成/命中后是否跳转聚焦到该会话(缺省 false,只落侧边栏)。 */+ focus?: boolean;+ }+ | {+ type: 'workspace-request';+ kind: 'ensure-session';+ mode: 'dir';+ /** 目标项目目录的本机绝对路径。 */+ dir: string;+ /** 当前在途 ghost_call 的 callId。 */+ callId: string;+ /** 用作新会话标题(净化后展示)。 */+ title?: string;+ /** 建成/命中后是否跳转聚焦到该会话(缺省 false,只落侧边栏)。 */+ focus?: boolean;+ };++/** workspace 槽结构化返回。绝对路径不回沙箱,只给目录 basename。 */+export type GhostPipeWorkspaceResult =+ | {+ ok: true;+ sessionId: string;+ /** true = 本次新建;false = 命中已有会话复用。 */+ created: boolean;+ /** 目录名(展示用,不含上级路径)。 */+ name: string;+ }+ | {+ ok: false;+ errorCode:+ | 'PERMISSION_DENIED'+ | 'INVALID_REQUEST'+ | 'CANCELLED'+ | 'RATE_LIMITED'+ | 'BUSY'+ | 'DIR_NOT_FOUND'+ | 'NOT_DIRECTORY'+ | 'HOST_NOT_READY'+ | 'INTERNAL';+ message: string;+ };+/*** 上行:preview 槽——请主机在右侧栏内置浏览器打开一个预览标签页。* url 必须命中身份卡 preview.hosts 白名单(ghostPreviewUrlAllowed);diff --git a/apps/desktop/src/shared/modelPriceQuote.ts b/apps/desktop/src/shared/modelPriceQuote.tsindex 32b667d29d..5f93a8319b 100644--- a/apps/desktop/src/shared/modelPriceQuote.ts+++ b/apps/desktop/src/shared/modelPriceQuote.ts@@ -51,45 +51,6 @@ function applyCodexBudgetDiscount(quote: ModelPriceQuote): ModelPriceQuote {};}-function normalizedCostDiscount(value: unknown): number | undefined {- return typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 1- ? value- : undefined;-}--/**- * 把 Gateway costDiscount 落到报价上:各单价 ×(1-discount) 变为实付口径,原价挪进- * original* 字段供划线展示。codex/ 折扣路由跳过——其 0.15 乘数由- * applyCodexBudgetDiscount 作为客户端权威,不与服务端 costDiscount 叠加双重打折。- */-function applyGatewayCostDiscount(- quote: ModelPriceQuote,- discount: number | undefined,-): ModelPriceQuote {- if (discount === undefined || quote.modelId.startsWith('codex/')) return quote;- const multiplier = 1 - discount;- return {- ...quote,- inputPerMtok: quote.inputPerMtok * multiplier,- outputPerMtok: quote.outputPerMtok * multiplier,- ...(quote.cacheReadPerMtok !== undefined- ? { cacheReadPerMtok: quote.cacheReadPerMtok * multiplier }- : {}),- ...(quote.cacheCreatePerMtok !== undefined- ? { cacheCreatePerMtok: quote.cacheCreatePerMtok * multiplier }- : {}),- discount,- originalInputPerMtok: quote.inputPerMtok,- originalOutputPerMtok: quote.outputPerMtok,- ...(quote.cacheReadPerMtok !== undefined- ? { originalCacheReadPerMtok: quote.cacheReadPerMtok }- : {}),- ...(quote.cacheCreatePerMtok !== undefined- ? { originalCacheCreatePerMtok: quote.cacheCreatePerMtok }- : {}),- };-}-export function gatewayModelPriceQuote(model: ModelAccessGatewayModel,region: CindyRegion,@@ -100,26 +61,29 @@ export function gatewayModelPriceQuote(if (!modelId || inputPerMtok === undefined || outputPerMtok === undefined) {return undefined;}- // 0/0 判定用折扣前原价:100% 折扣(原价非零)仍是有效报价,展示为立省 100% 而非免费。- if (inputPerMtok === 0 && outputPerMtok === 0) return undefined;const cacheReadPerMtok = perMtok(model.cacheReadInputTokenCost);const cacheCreatePerMtok = perMtok(model.cacheCreationInputTokenCost);- return applyCodexBudgetDiscount(- applyGatewayCostDiscount(- {- providerId: 'xd',- modelId,- currency: gatewayCurrencyForRegion(region),- source: 'gateway',- approximate: false,- inputPerMtok,- outputPerMtok,- ...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),- ...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),- },- normalizedCostDiscount(model.costDiscount),- ),- );+ if (+ inputPerMtok === 0 &&+ outputPerMtok === 0 &&+ (cacheReadPerMtok === undefined || cacheReadPerMtok === 0) &&+ (cacheCreatePerMtok === undefined || cacheCreatePerMtok === 0)+ ) {+ return undefined;+ }+ // quote 保留未折扣的标准价:UI 通过对比 quote(原价) vs CatalogModel.cost(折后价)+ // 推断折扣 badge;costDiscount 仅在 effectiveGatewayModelCost 侧应用到 cost。+ return applyCodexBudgetDiscount({+ providerId: 'xd',+ modelId,+ currency: gatewayCurrencyForRegion(region),+ source: 'gateway',+ approximate: false,+ inputPerMtok,+ outputPerMtok,+ ...(cacheReadPerMtok !== undefined ? { cacheReadPerMtok } : {}),+ ...(cacheCreatePerMtok !== undefined ? { cacheCreatePerMtok } : {}),+ });}export function gatewayPricingCatalog(@@ -213,7 +177,9 @@ export function getModelPriceQuote();}-export function subscriptionDirectPriceQuote(modelId: string): ModelPriceQuote | undefined {+export function subscriptionDirectPriceQuote(+ modelId: string,+): ModelPriceQuote | undefined {if (modelId.startsWith(CHATGPT_MODEL_PREFIX)) {return providerReferencePriceQuote('openai', modelId);}@@ -236,25 +202,15 @@ export function regionalizeModelPriceQuote(outputPerMtok: quote.outputPerMtok * USD_TO_CNY_FIXED_RATE,...(quote.cacheReadPerMtok !== undefined? {- cacheReadPerMtok: quote.cacheReadPerMtok * USD_TO_CNY_FIXED_RATE,+ cacheReadPerMtok:+ quote.cacheReadPerMtok * USD_TO_CNY_FIXED_RATE,}: {}),...(quote.cacheCreatePerMtok !== undefined? {- cacheCreatePerMtok: quote.cacheCreatePerMtok * USD_TO_CNY_FIXED_RATE,+ cacheCreatePerMtok:+ quote.cacheCreatePerMtok * USD_TO_CNY_FIXED_RATE,}: {}),- ...(quote.originalInputPerMtok !== undefined- ? { originalInputPerMtok: quote.originalInputPerMtok * USD_TO_CNY_FIXED_RATE }- : {}),- ...(quote.originalOutputPerMtok !== undefined- ? { originalOutputPerMtok: quote.originalOutputPerMtok * USD_TO_CNY_FIXED_RATE }- : {}),- ...(quote.originalCacheReadPerMtok !== undefined- ? { originalCacheReadPerMtok: quote.originalCacheReadPerMtok * USD_TO_CNY_FIXED_RATE }- : {}),- ...(quote.originalCacheCreatePerMtok !== undefined- ? { originalCacheCreatePerMtok: quote.originalCacheCreatePerMtok * USD_TO_CNY_FIXED_RATE }- : {}),};}diff --git a/apps/desktop/src/shared/regionalMoney.ts b/apps/desktop/src/shared/regionalMoney.tsindex d42b745f42..8b5e0d987d 100644--- a/apps/desktop/src/shared/regionalMoney.ts+++ b/apps/desktop/src/shared/regionalMoney.ts@@ -23,15 +23,6 @@ export interface ModelPriceQuote {outputPerMtok: number;cacheReadPerMtok?: number;cacheCreatePerMtok?: number;- /**- * Gateway 促销折扣(0..1]。存在时本报价的各单价**已是折后实付价**——用量记账与- * 选择器展示共用同一口径;折扣前原价由 original* 字段承载,仅供划线展示。- */- discount?: number;- originalInputPerMtok?: number;- originalOutputPerMtok?: number;- originalCacheReadPerMtok?: number;- originalCacheCreatePerMtok?: number;}export type ModelPricingCatalog = Record<string, Record<string, ModelPriceQuote>>;diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.tsindex 7f4cb3e903..fbbe788834 100644--- a/apps/desktop/src/shared/sessionSource.ts+++ b/apps/desktop/src/shared/sessionSource.ts@@ -7,6 +7,7 @@ export const SESSION_SOURCES = ['scheduler','learn','shared',+ 'plugin',] as const;export type SessionSource = (typeof SESSION_SOURCES)[number];@@ -20,6 +21,8 @@ export type SessionSource = (typeof SESSION_SOURCES)[number];// 这次带 dialogue 归组,不再以 im-working-dir 聚成假项目组。)// scheduler / learn: 本机自动化会话,可见可点开看过程。// shared: .xdtshare 导入的分享会话,按 workingDir 归组。+// plugin: 插件经 workspace 槽创建的工作区会话入口(空 draft,用户确认后建;+// projectGrouping 对零消息的 plugin 会话豁免草稿判定,直接落项目分组)。export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = ['desktop','feishu',@@ -29,6 +32,7 @@ export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = ['scheduler','learn','shared',+ 'plugin',];export function normalizeSessionSource(source: unknown): SessionSource {@@ -38,7 +42,8 @@ export function normalizeSessionSource(source: unknown): SessionSource {source === 'discord' ||source === 'scheduler' ||source === 'learn' ||- source === 'shared'+ source === 'shared' ||+ source === 'plugin'? source: 'desktop';}