Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 补齐远程新建菜单的附件、计划模式和插件 (#5570)
DavidShenXDd3873e96e2e9
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.tsnew file mode 100644index 0000000000..0607c7886f--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostComposerIpc.test.ts@@ -0,0 +1,142 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { IpcMainInvokeEvent } from 'electron';+import type { InstalledGhost } from '../../../shared/ghost';+import {+ createGhostComposerListHandler,+ MAX_REMOTE_COMPOSER_CATALOG_BYTES,+} from '../ghostComposerIpc';+import { ghostComposerListSchema } from '../../../shared/ghostComposer';+import { expandGhostCommand } from '../../../renderer/cindy-brain/ghostCommand';++const mocks = vi.hoisted(() => ({ context: vi.fn(), trusted: vi.fn() }));+vi.mock('../../device-link/invoke-context', () => ({ getDeviceLinkInvokeContext: mocks.context }));+vi.mock('../../security/trustedAppRenderer', () => ({+ assertTrustedAppRendererEvent: mocks.trusted,+}));++const ghost = (id: string): InstalledGhost => ({+ manifest: {+ schemaVersion: 2,+ id,+ name: id,+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ command: id,+ tools: [{ name: 'draw', description: 'Draw', parameters: { type: 'object' } }],+ },+ dir: '/private/install/path',+ enabled: true,+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+});+const event = {} as IpcMainInvokeEvent;+beforeEach(() => {+ vi.clearAllMocks();+ mocks.context.mockReturnValue(null);+});++describe('remote composer catalog boundary', () => {+ it('projects public command data with host-side directory disablement', () => {+ const list = vi.fn(() => [ghost('art'), ghost('cindy-mivo'), ghost('xd-mivo')]);+ const disabledIds = vi.fn(() => ['art']);+ mocks.context.mockReturnValue({ channel: 'ghosts:composer-list' });+ const result = createGhostComposerListHandler({ list, disabledIds })(event, '/host/project');+ expect(result.map((item) => item.manifest.id)).toEqual(['art', 'xd-mivo']);+ expect(result[0].enabled).toBe(false);+ expect(disabledIds).toHaveBeenCalledWith('/host/project');+ expect(ghostComposerListSchema.safeParse(result).success).toBe(true);+ expect(JSON.stringify(result)).not.toMatch(/private|approval|revision|main.js/);+ const received = ghostComposerListSchema.parse(JSON.parse(JSON.stringify(result)));+ expect(expandGhostCommand('$xd-mivo draw', received)).toContain('ghost_call');+ expect(expandGhostCommand('$art draw', received)).toBe('$art draw');+ expect(mocks.trusted).not.toHaveBeenCalled();+ });++ it('validates local senders and rejects shared-task or mismatched invoke contexts', () => {+ const list = vi.fn(() => [ghost('art')]);+ const handler = createGhostComposerListHandler({ list, disabledIds: () => [] });+ handler(event);+ expect(mocks.trusted).toHaveBeenCalledWith(event);+ list.mockClear();+ for (const context of [+ { channel: 'wrong' },+ { channel: 'ghosts:composer-list', sharedTask: {} },+ ]) {+ mocks.context.mockReturnValue(context);+ expect(() => handler(event)).toThrow();+ }+ expect(list).not.toHaveBeenCalled();+ });++ it('bounds large remote icons without losing menu entries or changing local data', () => {+ const ghosts = Array.from({ length: 9 }, (_, i) => ({+ ...ghost(`art-${i}`),+ iconDataUrl: `data:image/png;base64,${'A'.repeat(512 * 1024)}`,+ }));+ const handler = createGhostComposerListHandler({ list: () => ghosts, disabledIds: () => [] });+ const local = handler(event);+ expect(Buffer.byteLength(JSON.stringify(local), 'utf8')).toBeGreaterThan(4 * 1024 * 1024);+ mocks.context.mockReturnValue({ channel: 'ghosts:composer-list' });+ const remote = handler(event);+ expect(Buffer.byteLength(JSON.stringify(remote), 'utf8'))+ .toBeLessThanOrEqual(MAX_REMOTE_COMPOSER_CATALOG_BYTES);+ expect(remote.map((entry) => entry.manifest.id))+ .toEqual(ghosts.map((entry) => entry.manifest.id));+ expect(remote.every((entry) => entry.manifest.tools?.[0].name === 'draw')).toBe(true);+ expect(remote.some((entry) => entry.iconDataUrl)).toBe(true);+ expect(remote.some((entry) => !entry.iconDataUrl)).toBe(true);+ expect(local.every((entry) => entry.iconDataUrl === ghosts[0].iconDataUrl)).toBe(true);+ expect(ghostComposerListSchema.safeParse(remote).success).toBe(true);+ });++ it('counts UTF-8 and JSON escapes and falls back to discovery for oversized schemas', () => {+ const large = ghost('large');+ large.manifest.tools![0].parameters = { description: '中文"\\'.repeat(150_000) };+ const small = { ...ghost('small'), iconDataUrl: 'data:image/png;base64,AA==' };+ mocks.context.mockReturnValue({ channel: 'ghosts:composer-list' });+ const remote = createGhostComposerListHandler({+ list: () => [large, small], disabledIds: () => [],+ })(event);+ expect(Buffer.byteLength(JSON.stringify(remote), 'utf8'))+ .toBeLessThanOrEqual(MAX_REMOTE_COMPOSER_CATALOG_BYTES);+ expect(remote[0].manifest.tools).toBeUndefined();+ expect(remote[1].manifest.tools).toEqual(small.manifest.tools);+ expect(remote[1].iconDataUrl).toBe(small.iconDataUrl);+ expect(expandGhostCommand('$large draw', remote)).toContain('ghost_list');+ expect(expandGhostCommand('$small draw', remote)).toContain('ghost_call');+ expect(large.manifest.tools![0].parameters).toBeDefined();+ });++ it('accepts an exact UTF-8 budget and omits the optional field once it exceeds it', () => {+ const item = ghost('boundary');+ delete item.manifest.tools;+ mocks.context.mockReturnValue({ channel: 'ghosts:composer-list' });+ const handler = createGhostComposerListHandler({ list: () => [item], disabledIds: () => [] });+ const baseBytes = Buffer.byteLength(JSON.stringify(handler(event)), 'utf8');+ const fieldBytes = Buffer.byteLength(JSON.stringify({ iconDataUrl: '' }), 'utf8') - 1;+ const remaining = MAX_REMOTE_COMPOSER_CATALOG_BYTES - baseBytes - fieldBytes;+ item.iconDataUrl = '中'.repeat(Math.floor(remaining / 3)) + 'A'.repeat(remaining % 3);+ expect(Buffer.byteLength(JSON.stringify(handler(event)), 'utf8'))+ .toBe(MAX_REMOTE_COMPOSER_CATALOG_BYTES);+ item.iconDataUrl += '\\';+ expect(handler(event)[0].iconDataUrl).toBeUndefined();+ });++ it('rejects oversized required metadata instead of silently dropping plugins', () => {+ const large = ghost('large');+ large.manifest.name = '中'.repeat(MAX_REMOTE_COMPOSER_CATALOG_BYTES / 2);+ mocks.context.mockReturnValue({ channel: 'ghosts:composer-list' });+ expect(() => createGhostComposerListHandler({ list: () => [large], disabledIds: () => [] })(event))+ .toThrow('Plugin catalog metadata exceeds the response size limit');+ });++ it.each([null, {}, 42, 'bad\0path', 'x'.repeat(32_769)])(+ 'rejects invalid directory arguments',+ (workingDir) => {+ const list = vi.fn(() => []);+ const handler = createGhostComposerListHandler({ list, disabledIds: () => [] });+ expect(() => handler(event, workingDir)).toThrow();+ expect(list).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/desktop/src/main/cindy-brain/ghostComposerIpc.ts b/apps/desktop/src/main/cindy-brain/ghostComposerIpc.tsnew file mode 100644index 0000000000..feb6d712da--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostComposerIpc.ts@@ -0,0 +1,71 @@+import type { IpcMainInvokeEvent } from 'electron';+import type { InstalledGhost } from '../../shared/ghost';+import {+ GHOST_COMPOSER_LIST_CHANNEL,+ projectGhostComposerEntries,+ type GhostComposerEntry,+} from '../../shared/ghostComposer';+import { getDeviceLinkInvokeContext } from '../device-link/invoke-context';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer';+import { throwIpcError } from '../utils/ipcValidate';++// Leave room for the invoke envelope below the transport's 4 MiB message limit.+export const MAX_REMOTE_COMPOSER_CATALOG_BYTES = 1024 * 1024;++function boundRemoteCatalog(entries: GhostComposerEntry[]): GhostComposerEntry[] {+ const result = entries.map<GhostComposerEntry>(+ ({ manifest: { tools: _tools, ...manifest }, iconDataUrl: _icon, ...entry }) => ({+ ...entry,+ manifest,+ }),+ );+ let bytes = Buffer.byteLength(JSON.stringify(result), 'utf8');+ if (bytes > MAX_REMOTE_COMPOSER_CATALOG_BYTES) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin catalog metadata exceeds the response size limit');+ }++ // Keep every menu entry. Optional schemas and icons fall back to discovery and+ // the generic icon when they do not fit; never truncate a tool declaration.+ for (const field of ['tools', 'iconDataUrl'] as const) {+ entries.forEach((entry, index) => {+ const value = field === 'tools' ? entry.manifest.tools : entry.iconDataUrl;+ if (value === undefined) return;+ // Both destination objects already have fields, so account for the comma+ // plus the JSON-escaped key/value, measured in UTF-8 bytes.+ const addedBytes = Buffer.byteLength(JSON.stringify({ [field]: value }), 'utf8') - 1;+ if (bytes + addedBytes > MAX_REMOTE_COMPOSER_CATALOG_BYTES) return;+ if (field === 'tools') result[index].manifest.tools = entry.manifest.tools;+ else result[index].iconDataUrl = entry.iconDataUrl;+ bytes += addedBytes;+ });+ }+ return result;+}++/** Read-only projection for same-account controllers and trusted local UI. */+export function createGhostComposerListHandler(deps: {+ list: () => InstalledGhost[];+ disabledIds: (workingDir: string) => string[];+}) {+ return (event: IpcMainInvokeEvent, workingDir?: unknown) => {+ const context = getDeviceLinkInvokeContext();+ if (context) {+ if (context.channel !== GHOST_COMPOSER_LIST_CHANNEL || context.sharedTask) {+ throwIpcError('PERMISSION_DENIED', 'Plugin catalog requires a same-account controller');+ }+ } else {+ assertTrustedAppRendererEvent(event);+ }+ if (+ workingDir !== undefined &&+ (typeof workingDir !== 'string' || workingDir.length > 32_768 || workingDir.includes('\0'))+ ) {+ throwIpcError('INVALID_PARAMS', 'Invalid working directory');+ }+ const entries = projectGhostComposerEntries(+ deps.list(),+ typeof workingDir === 'string' && workingDir.trim() ? deps.disabledIds(workingDir) : [],+ );+ return context ? boundRemoteCatalog(entries) : entries;+ };+}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 67d140bd0a..79826b290f 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -482,6 +482,8 @@ import {type CindyCapabilityKey,} from './cindyPrefsStore.js';import { isCindyOverrideModelAllowed } from './cindyOverrideWhitelist.js';+import { createGhostComposerListHandler } from './ghostComposerIpc.js';+import { GHOST_COMPOSER_LIST_CHANNEL } from '../../shared/ghostComposer.js';import {isGhostDisabledForWorkdir,listDisabledGhostIdsForWorkdir,@@ -7606,6 +7608,10 @@ export function registerGhostIpc(): void {ipcMain.on('ghosts:list', (event) => {event.returnValue = { ghosts: availableGhosts().map(projectGhostForRenderer) };});+ ipcMain.handle(GHOST_COMPOSER_LIST_CHANNEL, createGhostComposerListHandler({+ list: availableGhosts,+ disabledIds: listDisabledGhostIdsForWorkdir,+ }));// Author tasks may contain private context: local trusted application UI only.ipcMain.on('ghosts:recommendations', (event) => {const empty = { ownerId: null, sources: [], recentIds: [], newlyInstalledId: null };diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.tsindex d1ea78a8d8..6cf17c108b 100644--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts@@ -344,6 +344,29 @@ describe('rewriteOutboundMedia — send/steer content-block 形态', () => {});describe('rewriteOutboundMedia — enqueue files 形态', () => {+ it.each([+ ['report.pdf', 'pdf', 'application/pdf'],+ ['demo.mp4', 'file', 'video/mp4'],+ ['audio.mp3', 'file', 'audio/mpeg'],+ ] as const)('uploads new remote-draft %s attachments before removing controller paths', async (name, category, mimeType) => {+ const localPath = path.resolve('controller-files', name);+ const payload = buildUserMessageAttachmentPayload([{+ id: name, name, path: localPath, size: 42, ext: path.extname(name), category, mimeType,+ }]);+ const item = {+ clientId: 'new-remote-draft', files: payload.serializedFiles,+ persistedContent: JSON.stringify({ text: 'read this', files: payload.persistFileRefs }),+ };+ uploadLocalFile.mockResolvedValue({ key: `cindy/device-link/u/${name}`, size: 42, contentType: mimeType, sha256: SHA256 });+ const out = await rewriteOutboundMedia('maker:input:enqueue', ['sess', item]);+ const rewritten = out[1] as typeof item;+ expect(uploadLocalFile).toHaveBeenCalledExactlyOnceWith(localPath, { contentType: mimeType });+ expect(parseAttachmentOssRef(rewritten.files![0].path)).toMatchObject({ originalName: name, mimeType });+ expect(JSON.stringify(out)).not.toContain(JSON.stringify(localPath).slice(1, -1));+ expect(item.files![0].path).toBe(localPath);+ uploadLocalFile.mockRejectedValueOnce(new Error('upload failed'));+ await expect(rewriteOutboundMedia('maker:input:enqueue', ['sess', item])).rejects.toThrow('upload failed');+ });it.each([['maker:input:enqueue', undefined],['maker:input:steer', { touchUserSend: true }],diff --git a/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts b/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.tsindex 1337eaaf37..866fabd507 100644--- a/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/sessionStorageRemoteHostId.test.ts@@ -156,6 +156,22 @@ describe('DesktopSessionStorage.create remoteHostId 规范化', () => {});});+describe('DesktopSessionStorage.create initial plan mode', () => {+ beforeEach(() => {+ h.captured = null;+ h.rows.clear();+ });++ it.each([true, false, undefined])('persists %s in the task insert', async (planMode) => {+ const storage = new DesktopSessionStorage();+ await storage.create({+ id: 'plan-session', title: 'Plan', workDir: '/repo', model: 'm', agentKind: 'codex', planMode,+ });+ expect(h.rows.size).toBe(1);+ expect(h.rows.get('plan-session')).toMatchObject({ planModeEnabled: planMode ?? false });+ });+});+describe('DesktopSessionStorage.create workspaceKind', () => {beforeEach(() => {h.captured = null;diff --git a/apps/desktop/src/main/maker-host/session-storage.ts b/apps/desktop/src/main/maker-host/session-storage.tsindex e811ccbe7b..66161a1708 100644--- a/apps/desktop/src/main/maker-host/session-storage.ts+++ b/apps/desktop/src/main/maker-host/session-storage.ts@@ -57,6 +57,7 @@ function rowToMeta(row: SessionRow): SessionMeta {effort: row.effort,permissionMode: row.permissionMode,fastMode: row.fastMode,+ planMode: row.planModeEnabled,...(row.source === 'review' ? { reviewMode: true as const } : {}),sdkSessionId: row.sdkSessionId ?? undefined,parentSessionId: row.parentSessionId ?? undefined,@@ -81,6 +82,7 @@ export class DesktopSessionStorage implements SessionStorage {effort: meta.effort ?? 'high',permissionMode: meta.permissionMode ?? 'ask',fastMode: meta.fastMode ?? false,+ planModeEnabled: meta.planMode ?? false,status: 'active',sdkSessionId: meta.sdkSessionId ?? null,agentKind: toDbKind(meta.agentKind),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionCreateHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionCreateHandler.test.tsindex 81145fcc4c..ede9b2a91b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionCreateHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionCreateHandler.test.ts@@ -33,6 +33,33 @@ function createDeps(overrides: Record<string, unknown> = {}) {}describe('maker session CREATE_SESSION IPC handler', () => {+ it.each([true, false])('passes initial plan mode %s to the creation transaction', async (planMode) => {+ const harness = new IpcHarness();+ const deps = createDeps();+ registerMakerSessionCreateHandler(harness, deps);+ await harness.invoke(MAKER_INVOKE.CREATE_SESSION, {+ agentKind: 'codex', workingDir: 'C:\\repo', model: 'gpt-5.4', planMode,+ });+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ planMode }));+ expect(deps.bootstrapSession.mock.invocationCallOrder[0]).toBeLessThan(+ deps.broadcastSessionCreated.mock.invocationCallOrder[0],+ );+ });++ it('rejects invalid plan flags before creation and propagates persistence failures', async () => {+ const harness = new IpcHarness();+ const deps = createDeps();+ registerMakerSessionCreateHandler(harness, deps);+ const args = { agentKind: 'codex', workingDir: 'C:\\repo', model: 'gpt-5.4' };+ await expect(harness.invoke(MAKER_INVOKE.CREATE_SESSION, { ...args, planMode: 'true' }))+ .rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ expect(deps.bootstrapSession).not.toHaveBeenCalled();+ deps.bootstrapSession.mockRejectedValue(new Error('storage unavailable'));+ await expect(harness.invoke(MAKER_INVOKE.CREATE_SESSION, { ...args, planMode: true }))+ .rejects.toThrow('storage unavailable');+ expect(deps.broadcastSessionCreated).not.toHaveBeenCalled();+ });+it('bootstraps a session and returns the public create-session payload', async () => {const harness = new IpcHarness();const deps = createDeps();diff --git a/apps/desktop/src/main/maker-ipc/sessionRequest.ts b/apps/desktop/src/main/maker-ipc/sessionRequest.tsindex 4a020942bd..593e123650 100644--- a/apps/desktop/src/main/maker-ipc/sessionRequest.ts+++ b/apps/desktop/src/main/maker-ipc/sessionRequest.ts@@ -113,6 +113,9 @@ export function readCreateSessionOpts(throwIpcError('INVALID_PARAMS', 'createSession opts must be an object');}const body = requireObject(input, 'createSession opts');+ if (body.planMode !== undefined && typeof body.planMode !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'planMode must be a boolean');+ }if (Array.isArray(body.extraDirs) && body.extraDirs.some((dir) =>typeof dir === 'string' && isLibraryExtraDirSlot(dir.trim()))) {throwIpcError('INVALID_PARAMS', 'extraDirs must not contain Host-owned library slots');diff --git a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.tsindex 6ee48f1dac..bc4209afe4 100644--- a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts@@ -14,7 +14,7 @@ describe('ChatInput Ghost snapshot contract', () => {it('derives the $ palette from the workdir-filtered installed snapshot', () => {expect(source).toContain(- 'const ghostsForCommand = useMemo(\n () => filterGhostsForWorkdir(installedGhosts, workingDir),',+ 'const ghostsForCommand = pluginsForMenu;',);expect(source).toContain('const ghostCommandItems = useMemo(() => {\n if (!isGhostSigil) return [];\n return ghostsForCommand',@@ -26,12 +26,13 @@ describe('ChatInput Ghost snapshot contract', () => {expect(source).toContain('const installedGhostsRef = useRef(installedGhosts);');expect(source).toContain('installedGhostsRef.current = installedGhosts;');expect(source).toMatch(- /const eligibleGhosts\s*=\s*filterGhostsForWorkdir\(\s*installedGhostsRef\.current,\s*workingDirRef\.current,\s*\);[\s\S]*?expandGhostCommand\(text,\s*eligibleGhosts\)/,+ /const eligibleGhosts: GhostCommandSource\[\]\s*=\s*sourceRemoteGhosts \?\? filterGhostsForWorkdir\(\s*installedGhostsRef\.current,\s*workingDirRef\.current,\s*\);[\s\S]*?expandGhostCommand\(text,\s*eligibleGhosts\)/,);});it('does not expose controller-local plugin rows in device-link sessions', () => {- expect(source).toContain('if (deviceLinkDeviceId !== null) return [];');+ expect(source).toContain('useInstalledGhosts(deviceLinkDeviceId === null)');+ expect(source).toContain('? remoteComposerGhosts.ghosts');expect(source).toContain('[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t]',);diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsindex 084bcded3c..ad7b930eae 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -180,15 +180,16 @@ describe('ChatInput session switch focus contract', () => {).toHaveLength(1);expect(chatInputSource.match(- /placeGhostAtComposerStart\(editor, ghost, installedGhostsRef\.current\)/g,+ /placeGhostAtComposerStart\(editor, ghost, composerGhostsRef\.current\)/g,),).toHaveLength(1);expect(chatInputSource).toContain('pendingGhostId: undefined');expect(capabilitySelectionBlock).toContain("selectedItem.type === 'plugin-command'");-expect(capabilitySelectionBlock).toContain('!ghost?.enabled');+ expect(capabilitySelectionBlock).toContain('!ghost?.enabled');+ expect(capabilitySelectionBlock).toContain('composerGhostsRef.current.find(');expect(capabilitySelectionBlock).toContain(- 'placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);',+ 'placeGhostAtComposerStart(editor, ghost, composerGhostsRef.current);',);expect(capabilitySelectionBlock).toContain('closeAtPanel();');expect(capabilitySelectionBlock).not.toContain('focusIOSSimulatorPanel');diff --git a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.tsindex 1d21100ca7..ff7e4c7fe6 100644--- a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts@@ -25,7 +25,7 @@ describe('composer quote palette boundary wiring', () => {);expect(source).toContain("type: 'plugin-command'");- expect(source).toContain('placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current)');+ expect(source).toContain('placeGhostAtComposerStart(editor, ghost, composerGhostsRef.current)');expect(source).not.toContain('scanPluginAtResources');});diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkCreateArgs.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkCreateArgs.test.tsindex 418f7380c6..8a2bbcbd7f 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkCreateArgs.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkCreateArgs.test.ts@@ -50,6 +50,17 @@ function deviceProvider(id: string, connected: boolean, modelIds: string[]): Pro}describe('buildDeviceLinkCreateArgs', () => {+ it.each([undefined, '/remote/project'])('carries initial plan mode through creation and provisional UI (%s)', (workingDir) => {+ const args = resolveDeviceLinkSubmission({+ agentKind: 'codex', workingDir, capabilityAgentKind: 'codex', deviceProviders: [],+ candidate: { model: 'gpt-5.4', effort: 'high', permissionMode: 'auto', fastMode: false, planModeEnabled: true },+ });+ expect(args.planMode).toBe(true);+ expect(args).not.toHaveProperty('planModeEnabled');+ const row = buildProvisionalRemoteSession({ sessionId: 'remote', workDir: workingDir ?? '/dialogue/remote', args, nowIso: '2026-10-08T00:00:00Z' });+ expect(row.planModeEnabled).toBe(true);+ });+it('归属一致核心:workspaceKind 恒为 project(被控端据此挂到项目下,不独立)', () => {const args = buildDeviceLinkCreateArgs({agentKind: 'cc',diff --git a/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.ts b/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.tsindex 1c1c7f5526..7a6aafff82 100644--- a/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/localAttachmentPicker.test.ts@@ -25,7 +25,7 @@ describe('canUseLocalAttachmentPicker', () => {).toBe(true);});- it('rejects SSH and device-link execution contexts', () => {+ it('keeps SSH excluded and allows device-link uploads', () => {expect(canUseLocalAttachmentPicker({sessionId: 'session-ssh',@@ -38,6 +38,6 @@ describe('canUseLocalAttachmentPicker', () => {runtimeAgentKind: 'codex',deviceLinkDeviceId: 'remote-device',}),- ).toBe(false);+ ).toBe(true);});});diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.tsindex 8b06f3dc38..90e6fae072 100644--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts@@ -161,7 +161,7 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {'vendorKey={normalizeDbAgentKind(draft.vendor)}',// #807 第二十二轮:仍然由调用方显式持有(ChatInput 不 fallback 内部一份),但远程草稿下// 包了一层闸门 —— 拒绝路径型附件,因为那是控制端绝对路径,发到对端读不到或读到无关文件。- 'attachmentState={guardedAttachmentState}',+ 'attachmentState={attachmentState}','draftKey={NEW_MAKER_DRAFT_KEY}','extraDirs={effectiveExtraDirs}',// #807 第二十二轮**刻意收窄**原来「+ 始终能加引用目录」这条:远程草稿不下传 onChange,diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex 1ef06c41ce..92062a3ce5 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -426,6 +426,18 @@ describe('Shared create project picker', () => {expect(branchHandler).toContain('setWtBranchPreferenceError(true);');});+ it('refreshes both creation callbacks when the remote plan selection changes', () => {+ for (const handler of ['handleSend', 'handleCreateGoal']) {+ const start = newMakerDraftRouteSource.indexOf(`const ${handler} = useCallback(`);+ expect(start).toBeGreaterThan(-1);+ const end = newMakerDraftRouteSource.indexOf('\n );', start);+ const callback = newMakerDraftRouteSource.slice(start, end);+ const dependencies = callback.slice(callback.lastIndexOf('\n ['));+ expect(callback).toContain('planModeEnabled: effectivePlanMode');+ expect(dependencies).toMatch(/\beffectivePlanMode\s*,/);+ }+ });+it('creates managed worktrees before starting either local or device-link goals', () => {const goal = newMakerDraftRouteSource.slice(newMakerDraftRouteSource.indexOf('const handleCreateGoal = useCallback('),@@ -891,11 +903,11 @@ describe('Shared create project picker', () => {expect(action).toContain('if (deviceChanged || workingDirChanged) stripProjectRelativeMentions();',);- // 附件是另一个条件 —— 别再把这两件事合回一个 gate。- expect(action).toContain('if (deviceChanged) dropPathBackedAttachments();');- // 拆分后的两个函数各自绑住自己的解析基准,注释里写明了理由。+ // 附件由出站上传层搬运,无需随引用一起删除。+ expect(action).not.toContain('dropPathBackedAttachments');+ // 项目引用仍随目标目录清理,附件保留。expect(newMakerDraftRouteSource).toContain('const stripProjectRelativeMentions = useCallback(');- expect(newMakerDraftRouteSource).toContain('const dropPathBackedAttachments = useCallback(');+ expect(newMakerDraftRouteSource).not.toContain('const dropPathBackedAttachments = useCallback(');// 旧的合并式 helper 必须消失,否则又会有人按单一条件调它。断言声明与调用两种形态,// 而不是裸名字 —— 拆分后的函数注释里会提到这个旧名作为历史记录。expect(newMakerDraftRouteSource).not.toContain('const cleanupCrossFilesystemDraftContext');@@ -1242,30 +1254,15 @@ describe('Shared create project picker', () => {);});- // #807 review 第十七轮:换设备要一并丢掉**路径型**附件。attachment-path-passthrough 之后非图片- // 附件只把 path 透传给模型,而 rehomeDraftAttachments 只重整图片 —— 上一台机器的路径会随首条- // 消息发到新设备,读不到、或读到同路径下一个毫不相关的文件。- it('drops path-backed attachments on every device switch', () => {- const helper = newMakerDraftRouteSource.slice(- newMakerDraftRouteSource.indexOf('const dropPathBackedAttachments = useCallback('),- );- const body = helper.slice(0, helper.indexOf('}, ['));- expect(body).toContain(".filter((f) => f.category !== 'image')");- expect(body).toContain('attachmentState.removeFile(f.id)');- // 图片不动:它们走 xdt-image:// 缓存,不依赖对端文件系统。- expect(body).toContain("t('newChat.deviceSwitcher.attachmentsDropped'");- // chip 剥离在**另一个**函数里(不同的解析基准,不同的触发条件)。- expect(body).not.toContain('stripLocalMentionChips');- expect(newMakerDraftRouteSource).toContain(- 'const stripProjectRelativeMentions = useCallback(() => {',+ // Device-link uploads controller-owned files before dispatch; see outboundMedia.test.ts.+ it('keeps transferable attachments when switching device', () => {+ const action = newMakerDraftRouteSource.slice(+ newMakerDraftRouteSource.indexOf('const applyDraftTarget = useCallback('),+ newMakerDraftRouteSource.indexOf('const applyDraftTarget = useCallback(') + 6000,);- // 全文恰好两处非图片过滤,各有明确分工:① 这个换设备时的同步清理;② 第二十四轮加的不变量- // 收敛 effect(兜住在途摄入等所有入口)。出现第三处就说明又有人在某条路径上手写了一份。- expect(- (newMakerDraftRouteSource.match(/\.filter\(\(f\) => f\.category !== 'image'\)/g) ?? [])- .length,- ).toBe(2);- expect(newMakerDraftRouteSource).toContain('「远程草稿绝不携带控制端路径附件」的**收敛器**');+ expect(action).not.toContain('attachmentState.removeFile');+ expect(newMakerDraftRouteSource).not.toContain('dropPathBackedAttachments');+ expect(action).toContain('stripProjectRelativeMentions();');});/**@@ -1317,8 +1314,8 @@ describe('Shared create project picker', () => {expect(body).toContain('if (deviceChanged || workingDirChanged) stripProjectRelativeMentions();',);- // 路径型附件存**绝对**路径 → 只有换设备才失效,同机换项目不该丢用户的附件。- expect(body).toContain('if (deviceChanged) dropPathBackedAttachments();');+ // 附件始终属于控制端,换目标设备不丢弃;发送时由上传层转成远端引用。+ expect(body).not.toContain('dropPathBackedAttachments');// 三个无 TTL 快照:绑「指向一台**新**设备」或「用户主动重新验证了这台设备」,// **不是**「指向设备就作废」—— 详见下面 does not evict… 那条用例的机制说明。expect(body).toContain('if (req.deviceId && (deviceChanged || req.remoteSnapshot)) {');@@ -1474,40 +1471,11 @@ describe('Shared create project picker', () => {expect(remoteSessionHandoffSource).toContain('args: p.createArgs,');});- // #807 review 第二十二轮:换设备时的清理只管「切换那一刻已在托盘里」的附件,**先选设备、之后- // 再拖进来**的路径型附件照样会把控制端绝对路径发到对端。两者一起才是「远程草稿绝不携带控制端- // 路径附件」这条不变量。- it('refuses path-backed attachments added after a remote device is selected', () => {- const guard = newMakerDraftRouteSource.slice(- newMakerDraftRouteSource.indexOf('const guardedAttachmentState = useMemo('),- );- const body = guard.slice(0, guard.indexOf('}, ['));- // 本机草稿零开销:直接返回原对象,不包装。- expect(body).toContain('if (!isDeviceLinkDraft) return attachmentState;');- // 判据必须与下游**同口径**(第 29 轮 P1):useAttachments 的分类完全不看 MIME —— 先按扩展名- // categorizeFile,认不出来才 peekFileHeader 按魔数推断。原来这里用 `f.type.startsWith('image/')`,- // 于是 Electron 给空 / 通用 File.type 时(某些平台与拖拽源如此,重命名过的图片更是必然),- // 一张下游明明能识别的图片会被拦掉,而且只在远程草稿下如此,用户切回本机就能加。- // 断言旧代码形态而非裸片段 —— 上面那段注释里会逐字提到它作为历史记录。- expect(body).not.toContain("incoming.filter((f) => f.type.startsWith('image/'))");- expect(body).toContain('const ext = extractExt(f.name);');- expect(body).toContain(- 'const category = ext ? categorizeFile(ext) : categorizeByFilename(f.name);',- );- // 认不出类别时**放行**,交给下游的文件头推断 + 收敛器兜底 —— 闸门宁可放过,绝不误拒。- expect(body).toContain('if (!category) return false;');- expect(body).toContain("return category !== 'image';");- expect(body).toContain("t('newChat.deviceSwitcher.attachmentsRemoteUnsupported'");- // 三个入口(ChatInput + 本路由的拖拽 + 延迟分类的拖拽)都必须走闸门,不能有一个直连原对象。- expect(newMakerDraftRouteSource).toContain('attachmentState={guardedAttachmentState}');- expect(- (newMakerDraftRouteSource.match(/guardedAttachmentState\.addFiles\(/g) ?? []).length,- ).toBe(2);- // 唯一一处直连原对象的 addFiles 必须是闸门内部那次(放行的那批);此外一处都不许有。- expect(- (newMakerDraftRouteSource.match(/(?<!guarded)attachmentState\.addFiles\(/g) ?? []).length,- ).toBe(1);- expect(body).toContain('await attachmentState.addFiles(passed);');+ // Device-link uploads controller-owned files before dispatch; see outboundMedia.test.ts.+ it('accepts files from the picker and both drop entry points for remote drafts', () => {+ expect(newMakerDraftRouteSource).toContain('attachmentState={attachmentState}');+ expect(newMakerDraftRouteSource).not.toContain('guardedAttachmentState');+ expect((newMakerDraftRouteSource.match(/attachmentState\.addFiles\(/g) ?? []).length).toBe(2);});// #807 review 第二十二轮:ExtraDirsButton 开的是控制端原生目录对话框,选出来的本机路径发到对端@@ -1555,21 +1523,10 @@ describe('Shared create project picker', () => {);});- // #807 review 第二十四轮:`useAttachments.addFiles` 对未知扩展名要先 await peekFileHeader,附件是- // IPC 回来后才进 state 的 —— 本机草稿下拖入 → 期间切到远程 → 切换清理找不到它 → IPC 回来后被追加,- // 且那次调用握的是切换前的真 addFiles,绕过闸门。按入口逐个堵已经漏了三次,改成维护不变量。- it('converges the no-controller-path invariant regardless of which entry added the file', () => {- const effect = newMakerDraftRouteSource.slice(- newMakerDraftRouteSource.indexOf('「远程草稿绝不携带控制端路径附件」的**收敛器**'),- );- const body = effect.slice(0, effect.indexOf('}, ['));- expect(body).toContain('if (!isDeviceLinkDraft) return;');- expect(body).toContain(".filter((f) => f.category !== 'image')");- expect(body).toContain('attachmentState.removeFile(f.id)');- // 依赖 attachments 本身(而非整个 attachmentState 对象)才能在附件晚到时重跑。- expect(effect.slice(effect.indexOf('}, ['), effect.indexOf('}, [') + 160)).toContain(- 'attachmentState.attachments',- );+ // Device-link uploads controller-owned files before dispatch; see outboundMedia.test.ts.+ it('preserves in-flight attachment ingestion for the remote upload pipeline', () => {+ expect(newMakerDraftRouteSource).not.toContain('attachmentState.removeFile(f.id)');+ expect(newMakerDraftRouteSource).toContain('rehomeDraftAttachments(files, remoteSessionId)');});// #807 review 第二十四轮:handleCreateGoal 必须整段持在途锁。上一轮我以为「模态遮罩挡住 pill」就diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsxindex 62780ad74e..bbf72cca1e 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx@@ -9,7 +9,7 @@* 2. 所有消费者读到同一引用(getSnapshot 引用稳定);* 3. ghosts:changed 推送后全体刷新,仍不重扫(payload 自带全量清单)。*/-import { act, cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, renderHook, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { InstalledGhost } from '../../../shared/ghost';@@ -68,6 +68,18 @@ function Probe({ label }: { label: string }) {}describe('useInstalledGhosts(窗口级共享缓存)', () => {+ it('remote composers can opt out of local synchronous IPC and subscriptions', () => {+ const { result, rerender } = renderHook(({ enabled }) => useInstalledGhosts(enabled), {+ initialProps: { enabled: false },+ });+ expect(result.current).toEqual([]);+ expect(listSync).not.toHaveBeenCalled();+ expect(onChanged).not.toHaveBeenCalled();+ rerender({ enabled: true });+ expect(result.current[0].manifest.id).toBe('cindy-art');+ rerender({ enabled: false });+ expect(result.current).toEqual([]);+ });it('多个消费者只触发一次 listSync,清单一致', () => {render(<>diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/useRemoteComposerGhosts.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/useRemoteComposerGhosts.test.tsxnew file mode 100644index 0000000000..33fc81db7c--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/useRemoteComposerGhosts.test.tsx@@ -0,0 +1,107 @@+// @vitest-environment jsdom+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useRemoteComposerGhosts } from '../useRemoteComposerGhosts';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { sharedTaskHostPeer } from '@cindy/device-link';++const invoke = vi.fn();+const catalog = (id: string) => [{ manifest: { id, name: id, command: id }, enabled: true }];+function deferred() {+ let resolve!: (value: unknown) => void;+ const promise = new Promise<unknown>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}+beforeEach(() => {+ invoke.mockReset();+ setDataOwnerGeneration('owner');+ Object.assign(window, { electronAPI: { deviceLink: { invoke } } });+});+afterEach(cleanup);++describe('remote composer plugins', () => {+ it('omits directory arguments for a folderless remote draft', async () => {+ invoke.mockResolvedValue(catalog('remote'));+ const { result } = renderHook(() => useRemoteComposerGhosts('a', undefined, true, 0));+ await waitFor(() => expect(result.current.ghosts[0]?.manifest.id).toBe('remote'));+ // JSON transport would turn [undefined] into [null], which the host rejects.+ expect(invoke).toHaveBeenCalledExactlyOnceWith('a', 'ghosts:composer-list', []);+ });+ it('renders immediately and drops late responses after switching device or directory', async () => {+ const old = deferred();+ const next = deferred();+ invoke+ .mockReturnValueOnce(old.promise)+ .mockReturnValueOnce(next.promise)+ .mockResolvedValue(catalog('project'));+ const { result, rerender } = renderHook(+ ({ device, dir }) => useRemoteComposerGhosts(device, dir, false, 0),+ { initialProps: { device: 'a', dir: '/a' } },+ );+ expect(result.current.ghosts).toEqual([]);+ rerender({ device: 'b', dir: '/b' });+ await act(async () => {+ next.resolve(catalog('b'));+ });+ expect(result.current.ghosts[0]?.manifest.id).toBe('b');+ await act(async () => {+ old.resolve(catalog('a'));+ });+ expect(result.current.ghosts[0]?.manifest.id).toBe('b');+ rerender({ device: 'b', dir: '/project' });+ expect(result.current.ghosts).toEqual([]);+ await waitFor(() => expect(result.current.ghosts[0]?.manifest.id).toBe('project'));+ expect(invoke).toHaveBeenLastCalledWith('b', 'ghosts:composer-list', ['/project']);+ });++ it('retries failed/old-host responses, refreshes on open/reconnect, and does not fetch on close', async () => {+ invoke+ .mockRejectedValueOnce(new Error('CHANNEL_NOT_ALLOWED'))+ .mockResolvedValue(catalog('remote'));+ const { result, rerender } = renderHook(+ ({ open, epoch }) => useRemoteComposerGhosts('a', undefined, open, epoch),+ { initialProps: { open: false, epoch: 0 } },+ );+ await waitFor(() => expect(result.current.failed).toBe(true));+ expect(result.current.ghosts).toEqual([]);+ act(() => result.current.reload());+ await waitFor(() => expect(result.current.ghosts[0]?.manifest.id).toBe('remote'));+ rerender({ open: true, epoch: 0 });+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(3));+ rerender({ open: false, epoch: 0 });+ expect(invoke).toHaveBeenCalledTimes(3);+ rerender({ open: false, epoch: 1 });+ await waitFor(() => expect(invoke).toHaveBeenCalledTimes(4));+ });++ it('rejects malformed payloads and does not fall back to local plugins', async () => {+ invoke.mockResolvedValue({ ghosts: catalog('local') });+ const { result } = renderHook(() => useRemoteComposerGhosts('a', '/a', false, 0));+ await waitFor(() => expect(result.current.failed).toBe(true));+ expect(result.current.ghosts).toEqual([]);+ });++ it('ignores an in-flight response after the account changes', async () => {+ const pending = deferred();+ invoke.mockReturnValue(pending.promise);+ const { result } = renderHook(() => useRemoteComposerGhosts('a', '/a', false, 0));+ setDataOwnerGeneration('another-owner');+ await act(async () => {+ pending.resolve(catalog('private'));+ });+ expect(result.current.ghosts).toEqual([]);+ });++ it('does not request a local or unresolved device catalog', () => {+ const { rerender } = renderHook(+ ({ device }: { device: string | null | undefined }) =>+ useRemoteComposerGhosts(device, '/a', true, 0),+ { initialProps: { device: null as string | null | undefined } },+ );+ rerender({ device: undefined });+ rerender({ device: sharedTaskHostPeer('task', 'host') });+ expect(invoke).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostCommand.ts b/apps/desktop/src/renderer/cindy-brain/ghostCommand.tsindex a1ef3d281e..0e5c6313f4 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostCommand.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostCommand.ts@@ -19,7 +19,8 @@* 追加文本对用户可见(气泡里如实显示),不做暗改。*/-import type { GhostToolDecl, InstalledGhost } from '../../shared/ghost';+import type { GhostToolDecl } from '../../shared/ghost';+import type { GhostCommandSource } from '../../shared/ghostComposer';/*** `$` 后紧跟指令词(与 ghost.json command 约束同宽:无空白,≤32 字符)。@@ -36,10 +37,10 @@ export function parseGhostCommandWord(text: string): string | null {}/** 按指令词(大小写折叠)找已唤醒的意识;找不到 → null(消息原样发送)。 */-export function findGhostByCommand(- ghosts: InstalledGhost[],+export function findGhostByCommand<T extends GhostCommandSource>(+ ghosts: T[],word: string,-): InstalledGhost | null {+): T | null {const fold = word.toLowerCase();return (ghosts.find(@@ -54,10 +55,10 @@ export function findGhostByCommand(* 仅用于编辑器内替换旧 `$command` 的结构识别;真正发送仍必须走* findGhostByCommand,所以停用 Plugin 不会因此被误调用。*/-export function findGhostByCommandIncludingDisabled(- ghosts: InstalledGhost[],+export function findGhostByCommandIncludingDisabled<T extends GhostCommandSource>(+ ghosts: T[],word: string,-): InstalledGhost | null {+): T | null {const fold = word.toLowerCase();return (ghosts.find(@@ -286,7 +287,7 @@ const buildMentionDirective = (roster: string): string => `${MENTION_HEAD}${rost* (agent 免 ghost_list 直接调),超体积闸回落"先 ghost_list"旧形态;* - 未命中(没这个指令 / 意识沉睡 / 非 `$` 开头)原样返回——绝不吞掉用户的字。*/-export function expandGhostCommand(text: string, ghosts: InstalledGhost[]): string {+export function expandGhostCommand(text: string, ghosts: GhostCommandSource[]): string {const word = parseGhostCommandWord(text);if (!word) return text;const ghost = findGhostByCommand(ghosts, word);diff --git a/apps/desktop/src/renderer/cindy-brain/useInstalledGhosts.ts b/apps/desktop/src/renderer/cindy-brain/useInstalledGhosts.tsindex 8e5ed9de9c..4052ebc94d 100644--- a/apps/desktop/src/renderer/cindy-brain/useInstalledGhosts.ts+++ b/apps/desktop/src/renderer/cindy-brain/useInstalledGhosts.ts@@ -81,8 +81,15 @@ export function __resetInstalledGhostsStoreForTest(): void {* 已装意识清单:设置页导航子项 / 意识总览 / 单意识页 / 聊天动作行共用,* 所有消费者永远看到同一份清单(同一引用)。*/-export function useInstalledGhosts(): InstalledGhost[] {- return useSyncExternalStore(subscribeInstalledGhosts, getInstalledGhostsSnapshot);+const EMPTY_GHOSTS: InstalledGhost[] = [];+const emptySnapshot = () => EMPTY_GHOSTS;+const noSubscription = () => () => {};++export function useInstalledGhosts(enabled = true): InstalledGhost[] {+ return useSyncExternalStore(+ enabled ? subscribeInstalledGhosts : noSubscription,+ enabled ? getInstalledGhostsSnapshot : emptySnapshot,+ );}/**diff --git a/apps/desktop/src/renderer/cindy-brain/useRemoteComposerGhosts.ts b/apps/desktop/src/renderer/cindy-brain/useRemoteComposerGhosts.tsnew file mode 100644index 0000000000..f44ef5de76--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/useRemoteComposerGhosts.ts@@ -0,0 +1,67 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import {+ GHOST_COMPOSER_LIST_CHANNEL,+ ghostComposerListSchema,+ type GhostComposerEntry,+} from '../../shared/ghostComposer';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';+import { isSharedTaskPeer } from '@cindy/device-link';++const EMPTY: GhostComposerEntry[] = [];++/** Async device/workdir-scoped catalog; opening the menu never awaits this read. */+export function useRemoteComposerGhosts(+ deviceId: string | null | undefined,+ workingDir: string | null | undefined,+ menuOpen: boolean,+ reconnectEpoch: number,+) {+ const owner = getDataOwnerGeneration();+ const key = JSON.stringify([owner.dataOwnerId, owner.generation, deviceId, workingDir ?? '']);+ const currentKey = useRef(key);+ currentKey.current = key;+ const [snapshot, setSnapshot] = useState<{+ key: string;+ ghosts: GhostComposerEntry[];+ failed: boolean;+ }>();+ const [retry, setRetry] = useState(0);+ const reload = useCallback(() => setRetry((value) => value + 1), []);++ const wasMenuOpen = useRef(menuOpen);+ useEffect(() => {+ if (menuOpen && !wasMenuOpen.current) reload();+ wasMenuOpen.current = menuOpen;+ }, [menuOpen, reload]);++ useEffect(() => {+ if (!deviceId || isSharedTaskPeer(deviceId)) return;+ let cancelled = false;+ const capturedOwner = getDataOwnerGeneration();+ const current = () =>+ !cancelled && currentKey.current === key && isDataOwnerGenerationCurrent(capturedOwner);+ void window.electronAPI.deviceLink+ .invoke(deviceId, GHOST_COMPOSER_LIST_CHANNEL, workingDir ? [workingDir] : [])+ .then((raw) => {+ const result = ghostComposerListSchema.safeParse(raw);+ if (!result.success) throw new Error('Invalid remote plugin catalog');+ if (current()) setSnapshot({ key, ghosts: result.data, failed: false });+ })+ .catch(() => {+ // Old hosts may reject the channel. Never substitute the controller's catalog.+ if (current()) setSnapshot({ key, ghosts: EMPTY, failed: true });+ });+ return () => {+ cancelled = true;+ };+ }, [deviceId, workingDir, key, reconnectEpoch, retry]);++ return {+ ghosts: snapshot?.key === key ? snapshot.ghosts : EMPTY,+ failed: snapshot?.key === key && snapshot.failed,+ reload,+ };+}diff --git a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsxindex 3f154d6dfb..3627c59e01 100644--- a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx@@ -47,6 +47,7 @@ import {Monitor,Paperclip,Plug,+ RotateCw,Sparkles,Target,UsersRound,@@ -118,6 +119,7 @@ interface AtMentionPanelProps {}const ACTION_ICONS: Record<ComposerSuggestionAction['id'], typeof Paperclip> = {+ 'retry-plugins': RotateCw,'attach-files': Paperclip,'new-goal': Target,'plan-mode': ClipboardList,diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 64b1a073f1..39d4e13799 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -191,8 +191,10 @@ import {findGhostByCommand,parseGhostCommandWord,} from '@/cindy-brain/ghostCommand';-import { filterGhostsForWorkdir } from '@/cindy-brain/ghostWorkdirFilter';+import { filterGhostsForWorkdir, getWorkdirDisabledGhostIds } from '@/cindy-brain/ghostWorkdirFilter';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';+import { useRemoteComposerGhosts } from '@/cindy-brain/useRemoteComposerGhosts';+import { projectGhostComposerEntries, type GhostCommandSource } from '../../../shared/ghostComposer';import {attachGhostMediaToSession,getGhostMediaUriFromDataTransfer,@@ -3006,23 +3008,29 @@ export function ChatInput({// 反映;plugin 不自己查 listSync,同步 IPC 不进 keystroke 热路径)。// 目录级禁用同判(ghostWorkdirFilter):被禁用的意识胶囊不亮——渲染层// 绝不比发送层乐观;禁用变更会广播 ghosts:changed,清单引用变化时重滤。- const installedGhosts = useInstalledGhosts();+ const installedGhosts = useInstalledGhosts(deviceLinkDeviceId === null);const installedGhostsRef = useRef(installedGhosts);installedGhostsRef.current = installedGhosts;- const pluginsForMenu = useMemo(- () =>- installedGhosts.filter(- (ghost) =>- !ghost.retirement &&- (ghost.manifest.id !== 'cindy-mivo' ||- !installedGhosts.some((candidate) => candidate.manifest.id === 'xd-mivo')),- ),- [installedGhosts],+ const trigger: TriggerState = editor ? detectTrigger(editor) : { kind: 'none' };+ const remoteComposerGhosts = useRemoteComposerGhosts(+ deviceLinkDeviceId,+ workingDir,+ syntheticAtAnchor !== null ||+ trigger.kind === 'at' ||+ (trigger.kind === 'slash' && trigger.sigil === '$'),+ remoteReconnectEpoch,);- const ghostsForCommand = useMemo(- () => filterGhostsForWorkdir(installedGhosts, workingDir),- [installedGhosts, workingDir],+ const pluginsForMenu = useMemo(+ () => deviceLinkDeviceId+ ? remoteComposerGhosts.ghosts+ : deviceLinkDeviceId === null+ ? projectGhostComposerEntries(installedGhosts, [...getWorkdirDisabledGhostIds(workingDir)])+ : [],+ [deviceLinkDeviceId, remoteComposerGhosts.ghosts, installedGhosts, workingDir],);+ const composerGhostsRef = useRef(pluginsForMenu);+ composerGhostsRef.current = pluginsForMenu;+ const ghostsForCommand = pluginsForMenu;const pluginAvailableIds = useMemo(() =>new Set(ghostsForCommand.filter((ghost) => ghost.enabled).map((ghost) => ghost.manifest.id)),@@ -3031,12 +3039,6 @@ export function ChatInput({// 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或// Host 入口或未生效项保留展示但置灰(entry 级 disabled + 原因)。const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(() => {- // device-link 会话的插件运行在被控端;控制端清单既不代表远端已安装- // 状态,选择后也无法用本地 InstalledGhost 解析并插入命令。fail-closed:- // 仅 deviceLinkDeviceId === null(已确认本机)才展示;undefined(所有权- // 尚未解析)与 string(远程)一律隐藏,避免 bootstrap/重连窗口期把控制端- // 本地插件项泄漏进可能落为远程的会话。- if (deviceLinkDeviceId !== null) return [];return pluginsForMenu.map((ghost) => {const hasCommand = !!ghost.manifest.command;const hasComposerEntry = hasCommand;@@ -3062,7 +3064,7 @@ export function ChatInput({disabledReason: t(!pluginAvailableIds.has(ghost.manifest.id)? 'extraDirs.pluginDisabled'- : ghost.manifest.skill+ : ghost.hasSkill? 'extraDirs.pluginAgentInvoked': 'extraDirs.pluginNoCommand',),@@ -4206,7 +4208,6 @@ export function ChatInput({);// ── Slash / At panel state ─────────────────────────────────────────- const trigger: TriggerState = editor ? detectTrigger(editor) : { kind: 'none' };// Slash commands — palette refactor 后改成 loadAllCommands 一次性拉三源(desktop +// agent-builtin + agent-skill); 内部并发, mergeCommands 按优先级合并去重。@@ -4606,6 +4607,13 @@ export function ChatInput({},});}+ if (remoteComposerGhosts.failed) {+ actions.push({+ id: 'retry-plugins',+ label: t('extraDirs.retryRemotePlugins'),+ run: remoteComposerGhosts.reload,+ });+ }return actions;}, [collaboration,@@ -4620,6 +4628,8 @@ export function ChatInput({planModeEntry,remoteHostId,runNewGoalAction,+ remoteComposerGhosts.failed,+ remoteComposerGhosts.reload,t,deviceLinkDeviceId,writableDirs,@@ -4991,7 +5001,7 @@ export function ChatInput({if (selectedItem.type === 'file-picker') return;if (selectedItem.type === 'plugin-command') {if (!selectedItem.pluginId) return;- const ghost = installedGhostsRef.current.find(+ const ghost = composerGhostsRef.current.find((candidate) => candidate.manifest.id === selectedItem.pluginId,);if (!ghost?.enabled) return;@@ -5006,7 +5016,7 @@ export function ChatInput({.run();if (ghost.manifest.command) {- placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);+ placeGhostAtComposerStart(editor, ghost, composerGhostsRef.current);}closeAtPanel();@@ -5131,6 +5141,7 @@ export function ChatInput({// 语音发送等所有入口,确保 host 已登记切换意图后才允许 maker:send。if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;const sourceSessionId = sessionId;+ const sourceRemoteGhosts = deviceLinkDeviceId ? composerGhostsRef.current : null;const sourceStorageKey = storageKey;const sendInFlightKey = sourceStorageKey ?? sourceSessionId ?? '__draft__';if (dispatchSendInFlightKeysRef.current.has(sendInFlightKey)) return;@@ -5492,9 +5503,8 @@ export function ChatInput({const mentionsToSend = mentions.length > 0 ? mentions : undefined;// 意识 $指令展开(C3d 双触发):`$画图 ...` 开头且命中已唤醒意识时,// 追加"必须走 cindy 总机"的机器指令;未命中原样发送。- // 读取 useInstalledGhosts 的最新窗口级快照。ghosts:changed 会原子更新- // 该快照;发送路径无需同步 IPC,仍按当前工作目录执行同一禁用判定。- const eligibleGhosts = filterGhostsForWorkdir(+ // 远控沿用发送开始时的目标设备快照;本机仍读取最新窗口清单并检查目录禁用。+ const eligibleGhosts: GhostCommandSource[] = sourceRemoteGhosts ?? filterGhostsForWorkdir(installedGhostsRef.current,workingDirRef.current,);@@ -5526,7 +5536,7 @@ export function ChatInput({}let recentUsageMarked = false;const markRecentPluginUsage = () => {- if (!usedGhost || recentUsageMarked) return;+ if (!usedGhost || recentUsageMarked || sourceRemoteGhosts) return;recentUsageMarked = true;void window.electronAPI.ghosts.markUsed(usedGhost.manifest.id).catch((error) => {log.warn(diff --git a/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts b/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.tsindex 969dff5fb8..f604f40043 100644--- a/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts+++ b/apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts@@ -17,7 +17,7 @@* hardBreak / 段落边界(序列化为 `\n`),紧贴 chip 视为 run 未断,不亮。** 意识清单不在 plugin 里查(listSync 是同步 IPC,不进 keystroke 热路径):- * ChatInput 经 useInstalledGhosts 订阅,变更时用 setGhostCommandRoster 推进来。+ * ChatInput 读取当前设备的插件清单,变更时用 setGhostCommandRoster 推进来。*/import { Extension, type Editor } from '@tiptap/core';import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';@@ -28,13 +28,13 @@ import {findGhostByCommand,findGhostByCommandIncludingDisabled,} from '@/cindy-brain/ghostCommand';-import type { InstalledGhost } from '../../../shared/ghost';+import type { GhostCommandSource } from '../../../shared/ghostComposer';const PLUGIN_KEY = new PluginKey<GhostCommandPluginState>('ghostCommandDecoration');const META_KEY = 'ghostCommandDecoration';interface GhostCommandPluginState {- ghosts: InstalledGhost[];+ ghosts: GhostCommandSource[];decorations: DecorationSet;}@@ -56,7 +56,7 @@ export interface GhostCommandMatch {from: number;/** 指令词结束后的 doc 位置(decoration 区间 [from, to))。 */to: number;- ghost: InstalledGhost;+ ghost: GhostCommandSource;}/**@@ -66,7 +66,7 @@ export interface GhostCommandMatch {*/export function findGhostCommandMatch(doc: PMNode,- ghosts: InstalledGhost[],+ ghosts: GhostCommandSource[],options: { includeDisabled?: boolean } = {},): GhostCommandMatch | null {if (ghosts.length === 0) return null;@@ -125,7 +125,7 @@ export function findGhostCommandMatch(* 胶囊 span 的渲染属性(导出供测试锁契约):头像 data URL 过白名单才注入* `--ghost-cmd-icon`(globals.css 据此换掉默认幽灵图标),异形值静默回退。*/-export function ghostPillAttrs(ghost: InstalledGhost): Record<string, string> {+export function ghostPillAttrs(ghost: GhostCommandSource): Record<string, string> {const attrs: Record<string, string> = {class: 'ghost-cmd-pill','data-ghost-cmd': ghost.manifest.id,@@ -141,7 +141,7 @@ export function ghostPillAttrs(ghost: InstalledGhost): Record<string, string> {}/** 由匹配结果构建胶囊 decoration(未命中 → 空集)。 */-function buildDecorations(doc: PMNode, ghosts: InstalledGhost[]): DecorationSet {+function buildDecorations(doc: PMNode, ghosts: GhostCommandSource[]): DecorationSet {const match = findGhostCommandMatch(doc, ghosts);if (!match) return DecorationSet.empty;return DecorationSet.create(doc, [@@ -192,9 +192,9 @@ export function applyGhostCommandBackspace(view: EditorView): boolean {/*** 推送最新意识清单(装/卸/唤醒/沉睡即时反映)。同引用去重——- * useInstalledGhosts 的 state 引用只在真变更时更新。+ * 清单的 state 引用只在数据更新时变化。*/-export function setGhostCommandRoster(editor: Editor | null, ghosts: InstalledGhost[]): void {+export function setGhostCommandRoster(editor: Editor | null, ghosts: GhostCommandSource[]): void {if (!editor || editor.isDestroyed) return;const current = PLUGIN_KEY.getState(editor.state);if (current && current.ghosts === ghosts) return;@@ -211,7 +211,7 @@ export function createGhostCommandPlugin(): Plugin<GhostCommandPluginState> {return { ghosts: [], decorations: buildDecorations(state.doc, []) };},apply(tr: Transaction, old: GhostCommandPluginState): GhostCommandPluginState {- const roster = tr.getMeta(META_KEY) as InstalledGhost[] | undefined;+ const roster = tr.getMeta(META_KEY) as GhostCommandSource[] | undefined;if (roster) return { ghosts: roster, decorations: buildDecorations(tr.doc, roster) };if (!tr.docChanged) return old;// 只扫消息头部的指令 run,输入量级下全量重算成本可忽略(同 CjkPunct)。diff --git a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.tsindex b6751d8c3a..fb235e5d80 100644--- a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts+++ b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts@@ -10,7 +10,7 @@import type { Editor } from '@tiptap/core';-import type { InstalledGhost } from '../../../shared/ghost';+import type { GhostCommandSource } from '../../../shared/ghostComposer';import { findGhostCommandMatch } from './GhostCommandDecoration';/** Match popover selection timing: close first, then focus the final editable position. */@@ -22,8 +22,8 @@ export function focusComposerEndNextFrame(editor: Editor): void {export function placeGhostAtComposerStart(editor: Editor,- ghost: InstalledGhost,- installedRoster: readonly InstalledGhost[],+ ghost: GhostCommandSource,+ installedRoster: readonly GhostCommandSource[],): boolean {const command = ghost.manifest.command;if (!command || editor.isDestroyed || !editor.isEditable) return false;diff --git a/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts b/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.tsindex ad8520a565..5e4dba8289 100644--- a/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts+++ b/apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts@@ -6,10 +6,10 @@ interface LocalAttachmentPickerContext {}/**- * 本机文件选择器只能在本机执行语境已经确认后开放。+ * 本机及 device-link 均从控制端选文件;device-link 出站层上传字节后替换路径。*- * 新建草稿没有 sessionId,可直接按远程标记判定;已建会话则必须等 runtime- * 身份回流,避免 SSH / device-link 冷启动首帧把控制端路径摄入附件状态。+ * device-link 身份明确后即可上传;其它已建会话须等 runtime 身份回流。+ * SSH 没有这条上传链路,仍不提供本机选择器。*/export function canUseLocalAttachmentPicker({sessionId,@@ -17,7 +17,8 @@ export function canUseLocalAttachmentPicker({remoteHostId,deviceLinkDeviceId,}: LocalAttachmentPickerContext): boolean {- if (remoteHostId || deviceLinkDeviceId) return false;+ if (remoteHostId) return false;+ if (deviceLinkDeviceId) return true;if (sessionId && !runtimeAgentKind) return false;return true;}diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex 75752d87d7..0ff4a1bdf3 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -195,9 +195,6 @@ import {import { filterGhostsForWorkdir } from '@/cindy-brain/ghostWorkdirFilter';import type { Effort, PermissionMode } from '@/lib/userPreferences.types';import {- categorizeByFilename,- categorizeFile,- extractExt,type AttachedFile,type MentionedResource,} from '@/lib/fileTypes';@@ -878,26 +875,6 @@ export function NewMakerDraftRoute() {text: stripLocalMentionChips(composerDraft.text),});}, []);- /**- * 丢掉路径型(非图片)附件 —— 触发条件是**文件系统变了**,即换设备。- *- * 与 chip 相反,附件存的是**绝对**路径(useAttachments 落 `raw.path`)。所以同一台机器上换项目- * 它们仍然有效,不该丢;只有跨设备(远程→远程、远程→本机,方向无关)那条绝对路径才会失效 ——- * attachment-path-passthrough 之后非图片附件只把 path 透传给模型(agent 自己用 Read 读),- * 而 rehomeDraftAttachments 只重整图片、非图片原样返回,于是要么读不到,要么读到同路径下一个- * 毫不相关的文件(后者更糟,用户不会发现)。图片走 xdt-image:// 缓存、不依赖对端文件系统,不受影响。- *- * 这两件事原先合在一个 cleanupCrossFilesystemDraftContext 里、由同一个条件驱动,于是必然有一边- * 是错的:按设备触发就漏掉同机换项目的 chip(上面那条 P1),按项目触发又会在同机换项目时误丢- * 用户的附件。拆开之后各自绑住自己真正的解析基准。- */- const dropPathBackedAttachments = useCallback(() => {- const stranded = attachmentState.attachments.filter((f) => f.category !== 'image');- if (stranded.length === 0) return;- for (const f of stranded) attachmentState.removeFile(f.id);- // 只有附件给 toast:chip 是可见的文字、重打一次就有,附件从托盘里无声消失只会被当成 bug。- toast.info(t('newChat.deviceSwitcher.attachmentsDropped', { count: stranded.length }));- }, [attachmentState, t]);const effectiveWorkingDir = draft.workingDir;const effectiveRemoteHostId = draft.remoteHostId;const isRemoteProjectDraft = effectiveWorkingDir != null && effectiveRemoteHostId != null;@@ -1044,85 +1021,6 @@ export function NewMakerDraftRoute() {wtBranchPreferenceErrorRef.current = false;setWtBranchPreferenceError(false);}, []);- /**- * 远程草稿的附件闸门:**先选设备、之后再拖进来的**路径型附件同样进不了对端(Codex review P1)。- *- * 换设备时的 cleanupCrossFilesystemDraftContext 只能清掉「切换那一刻已经在托盘里」的,管不到- * 之后新加的;而 rehomeDraftAttachments 只重整图片、非图片原样返回,于是那条**控制端**绝对路径- * 会随首条消息发到对端 —— 要么读不到,要么读到同路径下一个毫不相关的文件。两者一起才构成- * 「远程草稿绝不携带控制端路径附件」这条不变量,少一半就等于留着一条口子。- *- * 为什么是拒绝而不是「传上去」:把文件送到对端需要一个能在对端写字节的通道,而 device-link- * 的 invoke allowlist 里没有、也不该为此加一个写通道 —— 那是权限边界变更,不属于本 PR。- * 所以在用户动作发生的那一刻就明确拒绝并说明,而不是等发送时静默丢掉(那才像 bug)。- * 图片不受影响:它们走 xdt-image:// 缓存,由 rehomeDraftAttachments 正常搬运。- *- * 包一层而不是改 useAttachments:这条限制只属于「创建页 + 远程草稿」这个语境,- * 会话中途与本机草稿都不该被它影响。ChatInput 与本路由自己的拖拽 / 粘贴入口共用这一份,- * 免得又出现「只堵了一半」。- */- const guardedAttachmentState = useMemo(() => {- if (!isDeviceLinkDraft) return attachmentState;- return {- ...attachmentState,- addFiles: async (fileList: FileList | readonly File[]) => {- const incoming = Array.from(fileList);- // 判据必须与下游**同口径**(Codex review 第 29 轮 P1)。原来这里用 `f.type.startsWith('image/')`,- // 而 useAttachments 的分类**完全不看 MIME** —— 它先 extractExt(name) → categorizeFile,- // 扩展名认不出来才 peekFileHeader 按魔数推断。于是 Electron 给空 / 通用 `File.type` 时- // (某些平台与拖拽源就是如此,重命名过的图片更是必然),一张 useAttachments 明明能正确识别的- // 图片会被这道闸门拦掉,而且**只在远程草稿下**如此:用户切回本机就能加,现象极难理解。- //- // 所以改成「只拒绝**明确**是非图片的」:- // · 分类为 image → 放行;- // · 扩展名 / 文件名认不出类别(category 为 null)→ 也放行 —— 交给 useAttachments 的文件头- // 推断,推断出非图片会被下方的收敛式不变量 effect 移除并 toast;- // · 分类为明确的非图片(pdf / text / …)→ 就地拒绝并说明。- //- // 这也让两道防线的分工彻底清楚:闸门是 **best-effort 的即时反馈**(用户动作那一刻就知道为什么),- // 收敛器才是**权威不变量**(不论从哪条路进来,远程草稿里绝不留下路径型附件)。闸门宁可放过、- // 绝不误拒;真正的兜底不靠它。- const definitelyNonImage = (f: File): boolean => {- const ext = extractExt(f.name);- const category = ext ? categorizeFile(ext) : categorizeByFilename(f.name);- if (!category) return false; // 未知 → 不在这里下结论- return category !== 'image';- };- const rejected = incoming.filter(definitelyNonImage);- const passed = incoming.filter((f) => !definitelyNonImage(f));- if (rejected.length > 0) {- toast.warning(- t('newChat.deviceSwitcher.attachmentsRemoteUnsupported', { count: rejected.length }),- );- }- if (passed.length > 0) await attachmentState.addFiles(passed);- },- };- }, [isDeviceLinkDraft, attachmentState, t]);- /**- * 「远程草稿绝不携带控制端路径附件」的**收敛器** —— 兜住所有按路径逐个堵会漏掉的入口。- *- * 为什么单靠上面那个 addFiles 闸门不够(Codex review P1):`useAttachments.addFiles` 对未知扩展名- * 的文件要先 await `peekFileHeader` 猜类型,附件是在那次 IPC 回来之后才进 state 的。于是存在这条- * 时序 —— 本机草稿下拖入一个未知扩展名文件 → 在 IPC 往返期间切到远程设备 → 切换时的清理找不到它- * (还没进 state)→ IPC 回来后它被追加进去,而那次调用握的是**切换前**取到的真 addFiles,绕过了- * 闸门。下一次发送就把控制端绝对路径发给对端。- *- * 这个 hook 在本 PR 的 review 里已经按「入口」被抓漏三次(切换时清理 → 加时闸门 → 这条在途摄入),- * 所以这次不再补第四个入口,改成维护**不变量**:只要远程草稿里出现了非图片附件,不论它从哪条路- * 进来的,都移除并说明。之后任何新入口都自动被覆盖。- *- * 与另两处的关系(别当成重复删掉任何一个):闸门让用户在动作发生那一刻就得到明确拒绝、文件根本- * 不进 state;切换时的同步清理让附件在下一帧之前就消失、且顺带处理 mention chip;这条是最后一道- * 网,只在前两者都没拦住时才动。- */- useEffect(() => {- if (!isDeviceLinkDraft) return;- const stranded = attachmentState.attachments.filter((f) => f.category !== 'image');- if (stranded.length === 0) return;- for (const f of stranded) attachmentState.removeFile(f.id);- toast.info(t('newChat.deviceSwitcher.attachmentsDropped', { count: stranded.length }));- }, [isDeviceLinkDraft, attachmentState.attachments, attachmentState.removeFile, t]);// 零可用模型引导卡:device-link 草稿不出(连接态在被控端,本机替它连不上)。const providerOnboarding = useProviderOnboarding();const showProviderOnboardingCard = providerOnboarding.visible && !isDeviceLinkDraft;@@ -2077,9 +1975,12 @@ export function NewMakerDraftRoute() {: supportsFastMode? resolveDraftFast(calibratedDraftModel): false;- // 计划模式草稿态:仅本地草稿支持(device-link 远程草稿 v1 不透传,入口也不显示;- // 创建后进会话仍可经运行时隧道切换)。- const effectivePlanMode = isDeviceLinkDraft ? false : chatPrefs.planMode === true;+ // 远程开关仅属于这台设备的当前引擎,不读写控制端的本机偏好。+ const remotePlanKey = `${effectiveDeviceLinkDeviceId ?? ''}:${capabilityAgentKind}`;+ const [remoteDraftPlan, setRemoteDraftPlan] = useState<{ key: string; enabled: boolean } | null>(null);+ const effectivePlanMode = isDeviceLinkDraft+ ? capabilities?.planMode?.supported === true && remoteDraftPlan?.key === remotePlanKey && remoteDraftPlan.enabled+ : chatPrefs.planMode === true;// 选中模型 + effort:device-link 用镜像 holder(deviceLinkInitial,被控端草稿值已按 capabilities// 校准);本地草稿用 chatPrefs(逐字节不变)。device-link 在 holder seed 完成前(等隧道 / 能力)@@ -2219,9 +2120,8 @@ export function NewMakerDraftRoute() {});const workingDirChanged = req.workingDir !== draft.workingDir;- // chip 绑 workingDir;附件绑设备。两者条件不同,见各自函数的注释。+ // 引用绑定目标目录;控制端附件由出站上传层搬运,切换设备时保留。if (deviceChanged || workingDirChanged) stripProjectRelativeMentions();- if (deviceChanged) dropPathBackedAttachments();// 作废那三个无 TTL 快照 —— 但**不是**「指向设备就做」(Codex review 第 30 轮 P1,我上一轮// 收敛时写错的条件)。evict 不是幂等清理,而是一次**有副作用的状态转移**:它 notify@@ -2344,7 +2244,6 @@ export function NewMakerDraftRoute() {draft.workingDir,capabilityAgentKind,stripProjectRelativeMentions,- dropPathBackedAttachments,],);@@ -2726,13 +2625,16 @@ export function NewMakerDraftRoute() {[isDeviceLinkDraft, patchActivePrefs],);// 计划模式草稿开关:写当前 vendor prefs(发送建会话时经 planModeEnabled 落库)。- // device-link 远程草稿不显示入口(onPlanModeChange 不下发),这里只处理本地。+ // 远程草稿随创建参数提交,不修改被控端的新建默认值。const handlePlanModeChange = useCallback((enabled: boolean) => {- if (isDeviceLinkDraft) return;+ if (isDeviceLinkDraft) {+ setRemoteDraftPlan({ key: remotePlanKey, enabled });+ return;+ }patchActivePrefs({ planMode: enabled });},- [isDeviceLinkDraft, patchActivePrefs],+ [isDeviceLinkDraft, remotePlanKey, patchActivePrefs],);// 用户在草稿里切来源 → 记进当前 vendor 的 prefs(切 vendor / 重启后由 initialProviderId 回填,// 发送时也以此为准)。null = 清除显式选择,回落默认路由。与 model/effort 同口径。@@ -3761,6 +3663,7 @@ export function NewMakerDraftRoute() {effort,permissionMode,fastMode: effectiveFastMode,+ planModeEnabled: effectivePlanMode,providerId,},deviceProviders,@@ -3883,6 +3786,7 @@ export function NewMakerDraftRoute() {makerChatStore.setSessionRuntime(remoteSessionId, {agentKind: createArgs.agentKind,fastMode: createArgs.fastMode,+ planModeEnabled: createArgs.planMode ?? false,sessionProviderId: createArgs.providerId ?? null,});const preNavDraft = getComposerDraft(NEW_MAKER_DRAFT_KEY);@@ -4845,6 +4749,7 @@ export function NewMakerDraftRoute() {effort: draftInitialEffort,permissionMode: chatInitialPermissionMode,fastMode: effectiveFastMode,+ planModeEnabled: effectivePlanMode,providerId: chatInitialProviderId,},deviceProviders,@@ -5217,6 +5122,7 @@ export function NewMakerDraftRoute() {draftInitialEffort,chatInitialPermissionMode,effectiveFastMode,+ effectivePlanMode,effectiveRemoteHostId,effectiveExtraDirs,chatInitialProviderId,@@ -5266,15 +5172,15 @@ export function NewMakerDraftRoute() {// 点击后走安装引导、不会立即填入,只显示建议本身。插件清单变化时随之重算。// 可用插件表按插件清单与工作目录缓存:filterGhostsForWorkdir 会同步查询目录禁用表,// 不能在每次渲染 / 每条建议上重复调用。- const installedGhosts = useInstalledGhosts();+ const installedGhosts = useInstalledGhosts(!isDeviceLinkDraft);const usableSuggestionGhosts = useMemo(() =>new Map(- filterGhostsForWorkdir(installedGhosts, effectiveWorkingDir)+ (isDeviceLinkDraft ? [] : filterGhostsForWorkdir(installedGhosts, effectiveWorkingDir)).filter((g) => g.enabled).map((g) => [g.manifest.id, g]),),- [effectiveWorkingDir, installedGhosts],+ [isDeviceLinkDraft, effectiveWorkingDir, installedGhosts],);const suggestionComposerText = useCallback((suggestion: HomeTaskSuggestion) => {@@ -5482,7 +5388,7 @@ export function NewMakerDraftRoute() {if (droppedItems.files.length > 0) {e.preventDefault();e.stopPropagation();- guardedAttachmentState.addFiles(droppedItems.files);+ attachmentState.addFiles(droppedItems.files);}if (droppedItems.unclassified.length > 0) {// Do not synchronously consume item-less entries: a single@@ -5493,7 +5399,7 @@ export function NewMakerDraftRoute() {classifyPath: (path) =>window.electronAPI.localDb.sessionShare.classifyPath({ path }),}).then(({ files }) => {- if (files.length > 0) guardedAttachmentState.addFiles(files);+ if (files.length > 0) attachmentState.addFiles(files);});}}}@@ -5674,7 +5580,7 @@ export function NewMakerDraftRoute() {initialPermissionMode={chatInitialPermissionMode}initialProviderId={chatInitialProviderId}planModeEnabled={effectivePlanMode}- onPlanModeChange={isDeviceLinkDraft ? undefined : handlePlanModeChange}+ onPlanModeChange={handlePlanModeChange}fastMode={effectiveFastMode}onFastModeChange={handleFastModeChange}onWorkingDirChange={handleWorkingDirChange}@@ -5761,7 +5667,7 @@ export function NewMakerDraftRoute() {}narrowToolbar={isDraftToolbarNarrow}paletteMaxHeight={240}- attachmentState={guardedAttachmentState}+ attachmentState={attachmentState}draftKey={NEW_MAKER_DRAFT_KEY}focusOnStorageKeyChange// 「+」始终显示(与对话界面一致):无项目裸态也可加引用目录,作为本次对话的上下文。diff --git a/apps/desktop/src/renderer/features/cc-agent/deviceLinkCreateArgs.ts b/apps/desktop/src/renderer/features/cc-agent/deviceLinkCreateArgs.tsindex f2a35741b3..fd75691ed6 100644--- a/apps/desktop/src/renderer/features/cc-agent/deviceLinkCreateArgs.ts+++ b/apps/desktop/src/renderer/features/cc-agent/deviceLinkCreateArgs.ts@@ -41,6 +41,7 @@ export interface DeviceLinkCreateParams {effort: Effort;permissionMode: PermissionMode;fastMode: boolean;+ planModeEnabled?: boolean;/*** 附加只读引用目录(草稿期用户选的)。控制端选的是**本机路径**(extraDirs picker 走本机* 原生目录对话框),随 create 透传到被控端后,被控端 create 落地在 bootstrapSession 里按@@ -68,6 +69,7 @@ export interface DeviceLinkCreateArgs {effort: Effort;permissionMode: PermissionMode;fastMode: boolean;+ planMode?: boolean;/** 仅当草稿有非空 extraDirs 时出现;被控端 bootstrapSession 再校验(单一真相源)。 */extraDirs?: string[];writableDirs?: string[];@@ -90,6 +92,7 @@ export function buildDeviceLinkCreateArgs(p: DeviceLinkCreateParams): DeviceLinkeffort: p.effort,permissionMode: p.permissionMode,fastMode: p.fastMode,+ ...(p.planModeEnabled ? { planMode: true } : {}),// 空 / 缺省不放进 args:payload 干净,且被控端 bootstrapSession 也只在非空时才校验。...(p.extraDirs && p.extraDirs.length > 0 ? { extraDirs: p.extraDirs } : {}),...(p.writableDirs && p.writableDirs.length > 0 ? { writableDirs: p.writableDirs } : {}),@@ -109,6 +112,7 @@ export interface DeviceLinkSubmissionCandidate {effort: Effort;permissionMode: PermissionMode;fastMode: boolean;+ planModeEnabled?: boolean;/** 用户显式选中的被控端来源;null / 省略 = 跟随被控端默认路由。 */providerId?: string | null;}@@ -160,6 +164,7 @@ export function resolveDeviceLinkSubmission(p: DeviceLinkSubmissionParams): Devieffort: p.candidate.effort,permissionMode: p.candidate.permissionMode,fastMode: p.candidate.fastMode,+ planModeEnabled: p.candidate.planModeEnabled,extraDirs: p.extraDirs,writableDirs: p.writableDirs,providerId,@@ -215,6 +220,7 @@ export function buildProvisionalRemoteSession(p: ProvisionalRemoteSessionParams)contextTokens: 0,contextWindow: 0,fastMode: p.args.fastMode,+ planModeEnabled: p.args.planMode ?? false,clearedAt: null,pinnedAt: null,// 与被控端刚建出的行一致:首条还没被收下,userSendAt 为空。「用户正在发第一条」由diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 06180b8b3e..a862db804f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -13445,6 +13445,7 @@"addUnavailable": "This session can’t be opened in the current split. Open a session in the main area and try again."},"extraDirs": {+ "retryRemotePlugins": "Remote plugins failed to load. Retry","menuAria": "Composer actions","tooltipEmpty": "More actions","tooltipCount": "{{count}} additional directories",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7e07d71813..d4fc064494 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -13415,6 +13415,7 @@"addUnavailable": "このセッションは現在の分割で開けません。メイン領域でセッションを開いてから、もう一度お試しください。"},"extraDirs": {+ "retryRemotePlugins": "リモートプラグインを読み込めませんでした。再試行","menuAria": "操作メニュー","tooltipEmpty": "その他の操作","tooltipCount": "追加ディレクトリ {{count}} 件",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 48ce96566d..e751b9145e 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -13415,6 +13415,7 @@"addUnavailable": "현재 분할 창에서 이 세션을 열 수 없습니다. 기본 영역에서 세션을 연 후 다시 시도하세요."},"extraDirs": {+ "retryRemotePlugins": "원격 플러그인을 불러오지 못했습니다. 다시 시도","menuAria": "작업 메뉴","tooltipEmpty": "더 많은 작업","tooltipCount": "추가 디렉터리 {{count}}개",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 5b1788f443..55ed4b62a8 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -13415,6 +13415,7 @@"addUnavailable": "当前无法在分栏中打开该任务,请先在主区域打开一个任务再重试"},"extraDirs": {+ "retryRemotePlugins": "远程插件加载失败,点击重试","menuAria": "操作菜单","tooltipEmpty": "更多操作","tooltipCount": "{{count}} 个附加目录",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex b1db4777bf..09127ec1c4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -13415,6 +13415,7 @@"addUnavailable": "當前無法在分欄中開啟該任務,請先在主區域開啟一個任務再重試"},"extraDirs": {+ "retryRemotePlugins": "遠端插件載入失敗,點擊重試","menuAria": "操作選單","tooltipEmpty": "更多操作","tooltipCount": "{{count}} 個附加目錄",diff --git a/apps/desktop/src/renderer/lib/composerSuggestion.ts b/apps/desktop/src/renderer/lib/composerSuggestion.tsindex 827b4320ee..7d84d8c2de 100644--- a/apps/desktop/src/renderer/lib/composerSuggestion.ts+++ b/apps/desktop/src/renderer/lib/composerSuggestion.ts@@ -19,6 +19,7 @@ import {*/export type ComposerSuggestionActionId =+ | 'retry-plugins'| 'attach-files'| 'new-goal'| 'plan-mode'diff --git a/apps/desktop/src/shared/ghostComposer.ts b/apps/desktop/src/shared/ghostComposer.tsnew file mode 100644index 0000000000..1a04636747--- /dev/null+++ b/apps/desktop/src/shared/ghostComposer.ts@@ -0,0 +1,64 @@+import { z } from 'zod';+import type { InstalledGhost } from './ghost';++export const GHOST_COMPOSER_LIST_CHANNEL = 'ghosts:composer-list';++/** Only public command metadata crosses devices; never installation paths or credentials. */+const ghostComposerEntrySchema = z.object({+ manifest: z.object({+ id: z.string().min(1),+ name: z.string().min(1),+ command: z.string().min(1).max(32).regex(/^\S+$/u).optional(),+ tools: z+ .array(+ z.object({+ name: z.string(),+ description: z.string(),+ parameters: z.record(z.string(), z.unknown()).optional(),+ }),+ )+ .optional(),+ }),+ enabled: z.boolean(),+ hasSkill: z.boolean().optional(),+ iconDataUrl: z.string().optional(),+});++export const ghostComposerListSchema = z.array(ghostComposerEntrySchema);+export type GhostComposerEntry = z.infer<typeof ghostComposerEntrySchema>;++/** Shared structural input for command placement, decoration and send-time expansion. */+export type GhostCommandSource = Pick<GhostComposerEntry, 'manifest' | 'enabled' | 'iconDataUrl'>;++export function projectGhostComposerEntries(+ ghosts: readonly InstalledGhost[],+ disabledIds: readonly string[] = [],+): GhostComposerEntry[] {+ const disabled = new Set(disabledIds);+ return ghosts+ .filter(+ (ghost) =>+ !ghost.retirement &&+ (ghost.manifest.id !== 'cindy-mivo' ||+ !ghosts.some((item) => item.manifest.id === 'xd-mivo')),+ )+ .map(({ manifest, enabled, iconDataUrl }) => ({+ manifest: {+ id: manifest.id,+ name: manifest.name,+ ...(manifest.command ? { command: manifest.command } : {}),+ ...(manifest.tools+ ? {+ tools: manifest.tools.map(({ name, description, parameters }) => ({+ name,+ description,+ ...(parameters ? { parameters } : {}),+ })),+ }+ : {}),+ },+ enabled: enabled && !disabled.has(manifest.id),+ hasSkill: !!manifest.skill,+ ...(iconDataUrl ? { iconDataUrl } : {}),+ }));+}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 4acc868416..ee87357cba 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -11,6 +11,25 @@> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。+## Desktop 远程新建菜单++同账号控制端通过新增只读 `ghosts:composer-list(workingDir?)` 异步取得执行主机的插件菜单。+响应仅含名称、ID、指令、工具声明、图标、Skill 存在标记与目录过滤后的启用状态,不传安装路径、+批准记录、配置或凭证。无项目时不传参数;共享任务访客不开放此通道。+远程清单按序列化后的 UTF-8 字节限制为 1 MiB,为传输封装预留空间;保留所有插件的基础信息,+先容纳工具声明、再容纳图标。超出剩余预算的可选字段整项省略,工具声明缺失时复用现有+`ghost_list` 按需查询,图标缺失时显示通用图标。基础信息本身超限则明确失败,不截断插件列表;+本机清单不受此远程预算影响。+切换设备、目录或账号后丢弃旧响应;打开菜单、重连或点击重试时重读,不阻塞菜单展开。+旧主机拒绝未知通道时显示读取失败与重试入口,不用控制端清单替代;插件入口需要执行主机支持此通道。++计划模式复用 `maker:create-session` 的既有可选 `planMode` 参数;新主机创建任务记录时将显式值+与任务元数据一次写入既有 `planModeEnabled` 字段,写入失败复用创建清理路径,不在创建后另行补写。+控制端临时镜像与首条消息采用同一选择。未携带参数的旧控制端+保持原行为;旧主机虽接受启动参数,但不保证持久化初始选择,完整行为需更新执行主机。+附件复用现有出站上传与接收落盘协议,上传完成后才发送远端引用;移除新建页的旧图片限定,+不增加媒体协议字段、数据库迁移、服务端能力或 Mobile 原生改动。SSH 的附件限制保持原行为。+## 账号用量上限的自动继续输入投影 `AgentInputProjection` 新增可选字段 `usageLimitWait: { resumeAt } | null`,与 `error`diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex 03b1b77d01..1fbe5182f3 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -27,6 +27,10 @@ import {} from '../remoteResources.js';describe('REMOTE_INVOKE_ALLOWLIST', () => {+ it('allows the public composer projection without exposing the full installed plugin records', () => {+ expect(REMOTE_INVOKE_ALLOWLIST.has('ghosts:composer-list')).toBe(true);+ expect(REMOTE_INVOKE_ALLOWLIST.has('ghosts:list')).toBe(false);+ });it('allows Review start to run on the data-owning Desktop', () => {expect(REMOTE_INVOKE_ALLOWLIST.has('maker:review:start')).toBe(true);});diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 873235cc50..48f70b939d 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -522,6 +522,8 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = ['maker:list-customizations','maker:scan-at-resources',// —— 插件列表(只读)——+ // Public composer metadata only; no paths, secrets, lifecycle writes or shared guests.+ 'ghosts:composer-list','maker:plugins:list',// 单个插件的启停状态(只读)。与 maker:plugins:list 同类,差别只在它不跳过// HOSTED_ELSEWHERE 插件、且按 id 精确查。准入三条:handler 只读 settings + 项目diff --git a/packages/maker-core/src/interfaces/session-storage.ts b/packages/maker-core/src/interfaces/session-storage.tsindex 2a594fe684..7738b0abed 100644--- a/packages/maker-core/src/interfaces/session-storage.ts+++ b/packages/maker-core/src/interfaces/session-storage.ts@@ -17,6 +17,8 @@ export interface SessionMeta {effort?: Effort;permissionMode?: PermissionMode;fastMode?: boolean;+ /** Initial plan selection, persisted with the task rather than after creation. */+ planMode?: boolean;/** Persist the host-owned Review purpose atomically with session creation. */reviewMode?: true;createdAt: number;diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 42007452b5..a6c929af98 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -561,6 +561,57 @@ describe('Maker local Pi package generation fence', () => {});});+describe('Maker initial plan persistence', () => {+ it.each([true, false, undefined])('stores initial plan mode %s with the new task', async (planMode) => {+ const storage = createStorage();+ const create = vi.spyOn(storage, 'create');+ const update = vi.spyOn(storage, 'update');+ const maker = new Maker({+ agents: { codex: createAgent(async () => createHandle({ id: 'plan-handle' })) },+ storage,+ logger: createLogger(),+ });+ try {+ const session = await maker.createSession({+ agentKind: 'codex', workingDir: '/repo', model: 'm', planMode,+ });+ expect(create).toHaveBeenCalledTimes(1);+ expect(create.mock.calls[0][0].planMode).toBe(planMode);+ expect((await storage.get(session.id))?.planMode).toBe(planMode);+ expect(update).not.toHaveBeenCalled();+ } finally {+ await maker.shutdown();+ }+ });++ it.each(['codex', 'claude-code', 'pi'] as const)(+ 'cleans up %s after a failed plan-bearing insert and permits retry without an orphan',+ async (agentKind) => {+ const close = vi.fn(async () => undefined);+ const start = vi.fn(async () => ({ ...createHandle({ id: 'plan-handle', agentKind }), close }));+ const storage = createStorage();+ const create = storage.create.bind(storage);+ const insert = vi.spyOn(storage, 'create')+ .mockRejectedValueOnce(new Error('storage unavailable'))+ .mockImplementation(create);+ const maker = new Maker({ agents: { [agentKind]: createAgent(start, agentKind) }, storage, logger: createLogger() });+ const opts: CreateSessionOptions = { agentKind, workingDir: '/repo', model: 'm', planMode: true };+ try {+ await expect(maker.createSession(opts)).rejects.toThrow('storage unavailable');+ expect(insert.mock.calls[0][0].planMode).toBe(true);+ expect(close).toHaveBeenCalledTimes(1);+ expect(maker.listActiveSessions()).toEqual([]);+ expect(await storage.list()).toEqual([]);+ const session = await maker.createSession(opts);+ expect(await storage.list()).toEqual([expect.objectContaining({ id: session.id, planMode: true })]);+ expect(maker.listActiveSessions()).toHaveLength(1);+ } finally {+ await maker.shutdown();+ }+ },+ );+});+describe('Maker session creation singleflight', () => {it('persists the durable resume id while exposing a distinct transient request id', async () => {const storage = createStorage();diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex 458d8a9ee1..2eb8cf35a5 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -908,6 +908,7 @@ export class Maker {effort: opts.effort,permissionMode: opts.permissionMode,fastMode: opts.fastMode,+ ...(typeof opts.planMode === 'boolean' ? { planMode: opts.planMode } : {}),reviewMode: opts.reviewMode,parentSessionId: opts.parentSessionId,// remoteHostId: 远端 session 把目标机器持久化, 之后 resume / list 都能识别。