Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugin): 开放目标选择、投递方式与图片消息接口
liugaowei5d05509e4b13
diff --git a/apps/desktop/scripts/fixtures/plugin-target-picker/picker-fixture.tsx b/apps/desktop/scripts/fixtures/plugin-target-picker/picker-fixture.tsxnew file mode 100644index 0000000000..cf011bc5a6--- /dev/null+++ b/apps/desktop/scripts/fixtures/plugin-target-picker/picker-fixture.tsx@@ -0,0 +1,24 @@+import { mountPage, subscription } from '../../ui-page/harness';+import { PluginTargetPickerHost } from '../../../src/renderer/cindy-brain/PluginTargetPickerHost';+import { setDataOwnerGeneration } from '../../../src/renderer/contexts/dataOwnerGeneration';+import type { PluginTargetPickerPush } from '../../../src/shared/pluginTargets';++const ownerStamp = { dataOwnerId: 'fixture-owner', ownerGeneration: 1 };+setDataOwnerGeneration(ownerStamp.dataOwnerId, ownerStamp.ownerGeneration);++void mountPage({+ host: (ctx) => ({+ onAuthStateChange: subscription('authState'),+ ghosts: {+ onTargetPicker: (listener: (payload: PluginTargetPickerPush, stamp: typeof ownerStamp) => void) => {+ queueMicrotask(() => listener({ requestId: 'fixture-picker', pluginName: 'Example Plugin',+ kind: ctx.data.kind as PluginTargetPickerPush['kind'], persistent: ctx.data.persistent === true,+ candidates: ctx.data.candidates as PluginTargetPickerPush['candidates'] }, ownerStamp));+ return () => {};+ },+ onTargetPickerDismiss: subscription('pickerDismiss'),+ resolveTargetPicker: async () => ({ handled: true }),+ },+ }),+ render: () => <PluginTargetPickerHost />,+});diff --git a/apps/desktop/scripts/fixtures/plugin-target-picker/ui-page.mjs b/apps/desktop/scripts/fixtures/plugin-target-picker/ui-page.mjsnew file mode 100644index 0000000000..5901c95c23--- /dev/null+++ b/apps/desktop/scripts/fixtures/plugin-target-picker/ui-page.mjs@@ -0,0 +1,40 @@+import assert from 'node:assert/strict';++const candidates = [+ { id: 'first', label: 'Website redesign', detail: '/workspace/website' },+ { id: 'second', label: 'Review release notes', detail: '/workspace/release-notes' },+ { id: 'third', label: 'Documentation', detail: '/workspace/documentation' },+];++export default {+ name: 'plugin-target-picker',+ entry: './picker-fixture.tsx',+ viewport: { width: 760, height: 600 },+ real: 'PluginTargetPickerHost, ConfirmDialog, Input, owner push checks, translations and theme',+ notCovered: 'Real IPC, target discovery, persistent bindings, account changes, AI dispatch and attachments',+ cases: {+ default: { about: 'Choose an existing task for one delivery', data: { kind: 'task', candidates } },+ project: { about: 'Bind a project for future deliveries', data: { kind: 'project', persistent: true, candidates } },+ bot: { about: 'Choose a companion for one delivery', data: { kind: 'bot', candidates: [+ { id: 'first', label: 'Cindy', detail: 'Research and development' },+ { id: 'second', label: 'Editor', detail: 'Writing and proofreading' },+ ] } },+ empty: { about: 'No eligible local targets', data: { kind: 'task', candidates: [] } },+ },+ async ready(page) {+ await page.getByRole('alertdialog').waitFor();+ },+ async check(page, ui) {+ const dialog = page.getByRole('alertdialog');+ const action = dialog.getByRole('button', { name: await ui.t(+ ui.data.persistent ? 'pluginTargetPicker.bind' : 'pluginTargetPicker.choose'), exact: true });+ assert.equal(await action.isDisabled(), true);+ if (!ui.data.candidates.length) return;+ const rows = dialog.getByRole('group').getByRole('button');+ await rows.first().click();+ assert.equal(await action.isEnabled(), true);+ assert.equal(await rows.first().getAttribute('aria-pressed'), 'true');+ await dialog.getByRole('textbox').fill(ui.data.candidates[0].label);+ assert.equal(await rows.count(), 1);+ },+};diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.tsnew file mode 100644index 0000000000..51c3da9c1f--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts@@ -0,0 +1,200 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { PluginTargetPickerPush } from '../../../shared/pluginTargets.js';++const state = vi.hoisted(() => ({ bindings: {} as Record<string, unknown> }));+vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => 'owner',+ ownerScopedUserDataPath: () => '/not-written.json',+ getActiveDataOwnerPushStamp: () => ({ ownerGeneration: 1 }),+}));+vi.mock('../../maker-host/logger-adapter.js', () => ({+ desktopMakerLogger: { child: () => ({}) },+}));+vi.mock('../../maker-host/override-settings-file.js', () => ({+ createOverrideSettingsFile: () => ({+ invalidateIfChanged: () => {},+ read: () => state,+ updateAtomic: async (update: (input: { value: typeof state }) => Partial<typeof state>) =>+ Object.assign(state, update({ value: state })),+ }),+}));+import { PluginTargetSlot, type PluginTargetAdapter } from '../pluginTargetSlot.js';++describe('user-selected plugin destinations', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ state.bindings = {};+ });+ afterEach(() => {+ vi.useRealTimers();+ });+ function fixture() {+ let push: PluginTargetPickerPush | null = null;+ const slot = new PluginTargetSlot({+ name: () => 'Example plugin',+ revision: () => 'approved-install',+ open: (value) => {+ push = value;+ return { senderId: 7, close: vi.fn() };+ },+ });+ const send = vi.fn<PluginTargetAdapter['send']>(async () => 'queue');+ const create = vi.fn(async () => {});+ const withdraw = vi.fn(async () => {});+ slot.adapter = {+ candidates: async () => [{ id: 'chosen', label: 'Chosen task', detail: '' }],+ session: async () => 'chosen',+ send,+ create,+ withdraw,+ };+ const guard = vi.fn();+ const call = (payload: unknown, plugin = 'plugin') => slot.handle(plugin, payload, guard);+ const pick = async (persistent = false, targetKind = 'task') => {+ const result = call({ kind: 'pick', requestKey: 'select', targetKind, persistent });+ await vi.advanceTimersByTimeAsync(0);+ const request = push!;+ expect(slot.resolve(request.requestId, 99, 'chosen')).toBe(false);+ expect(slot.resolve(request.requestId, 7, 'chosen')).toBe(true);+ return (await result) as { bindingId: string };+ };+ return { slot, call, pick, send, create, withdraw, getPush: () => push };+ }+ // Production entry: PluginTargetSlot.handle. Protects targets.send's delivery/default+ // and idempotency contract; existing ownership cases do not cover this field. In-memory unit tier.+ it('carries screenshot bytes once and rejects a changed attachment on the same receipt', async () => {+ const f = fixture(), picked = await f.pick();+ const base64 = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString('base64');+ const request = { kind: 'send', bindingId: picked.bindingId, requestKey: 'image', text: 'context',+ attachments: [{ base64, name: 'window.png' }] };+ await f.call(request);+ await f.call(structuredClone(request));+ expect(f.send).toHaveBeenCalledOnce();+ expect(f.send.mock.calls[0]?.[7]?.[0]).toMatchObject({ mimeType: 'image/png', name: 'window.png' });+ await expect(f.call({ ...request, attachments: [{ base64, name: 'other.png' }] }))+ .rejects.toMatchObject({ code: 'REQUEST_KEY_CONFLICT' });+ });+ it('rejects a forged media URL before creating or sending a target task', async () => {+ const f = fixture(), picked = await f.pick(false, 'project');+ await expect(f.call({ kind: 'send', bindingId: picked.bindingId, requestKey: 'image', text: 'context',+ attachments: [{ url: 'cindy-media://blobs/foreign.png' }] })).rejects.toMatchObject({ code: 'INVALID_ATTACHMENTS' });+ expect(f.create).not.toHaveBeenCalled();+ expect(f.send).not.toHaveBeenCalled();+ });+ it.each([undefined, 'queue', 'steer'] as const)('preserves requested delivery %s and reports actual delivery', async (delivery) => {+ const f = fixture(), picked = await f.pick();+ const request = { kind: 'send', bindingId: picked.bindingId, requestKey: 'send', text: 'context', delivery };+ expect(await f.call(request)).toMatchObject({ accepted: true, delivery: 'queue' });+ expect(f.send.mock.calls[0]?.[6]).toBe(delivery ?? 'queue');+ // A mode change cannot reuse an accepted request to inject the same content twice.+ await expect(f.call({ ...request, delivery: delivery === 'steer' ? 'queue' : 'steer' }))+ .rejects.toMatchObject({ code: 'REQUEST_KEY_CONFLICT' });+ expect(f.send).toHaveBeenCalledOnce();+ });+ it('reports successful steering and treats omitted delivery as an explicit queue retry', async () => {+ const f = fixture(), picked = await f.pick();+ f.send.mockResolvedValueOnce('steer');+ expect(await f.call({ kind: 'send', bindingId: picked.bindingId, requestKey: 'steer', text: 'context', delivery: 'steer' }))+ .toMatchObject({ accepted: true, delivery: 'steer' });+ const other = await f.pick();+ const request = { kind: 'send', bindingId: other.bindingId, requestKey: 'queue', text: 'context' };+ await f.call(request);+ expect(await f.call({ ...request, delivery: 'queue' })).toMatchObject({ delivery: 'queue' });+ expect(f.send).toHaveBeenCalledTimes(2);+ });+ it.each(['invalid', 'project-steer'])('rejects %s before any target mutation', async (mode) => {+ const f = fixture(), picked = await f.pick(false, mode === 'project-steer' ? 'project' : 'task');+ await expect(f.call({ kind: 'send', bindingId: picked.bindingId, requestKey: 'send', text: 'context',+ delivery: mode === 'project-steer' ? 'steer' : 'interrupt' }))+ .rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ expect(f.send).not.toHaveBeenCalled();+ expect(f.create).not.toHaveBeenCalled();+ });+ it('rejects a plugin-supplied task ID and does not expose a candidate list to the plugin', async () => {+ const f = fixture();+ await expect(+ f.call({ kind: 'send', bindingId: 'chosen', requestKey: 'a', text: 'context' }),+ ).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });+ const picked = await f.pick();+ expect(picked).not.toHaveProperty('candidates');+ expect(picked).not.toHaveProperty('targetId');+ expect(f.send).not.toHaveBeenCalled();+ });+ it('cannot turn a one-time selection into a persistent binding or use it from another plugin', async () => {+ const f = fixture(),+ picked = await f.pick();+ await expect(f.call({ kind: 'get', bindingId: picked.bindingId })).rejects.toMatchObject({+ code: 'TARGET_UNAVAILABLE',+ });+ await expect(+ f.call(+ { kind: 'send', bindingId: picked.bindingId, requestKey: 'a', text: 'context' },+ 'another',+ ),+ ).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });+ });+ it('requires fixed bindings to be resolved and rejects replay with a new key or changed text', async () => {+ const f = fixture(),+ saved = await f.pick(true);+ await expect(+ f.call({ kind: 'send', bindingId: saved.bindingId, requestKey: 'a', text: 'context' }),+ ).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });+ const handle = (await f.call({ kind: 'get', bindingId: saved.bindingId })) as {+ bindingId: string;+ };+ const request = { kind: 'send', bindingId: handle.bindingId, requestKey: 'a', text: 'context' };+ await Promise.all([f.call(request), f.call(request)]);+ expect(f.send).toHaveBeenCalledTimes(1);+ await expect(f.call({ ...request, requestKey: 'b', text: 'changed' })).rejects.toMatchObject({+ code: 'DELIVERY_UNCERTAIN',+ });+ expect(f.create).not.toHaveBeenCalled();+ });+ it('cancels a picker and rejects its late selection without delivering anything', async () => {+ const f = fixture();+ const selection = f.call({ kind: 'pick', requestKey: 'old', targetKind: 'task' });+ const settled = expect(selection).rejects.toMatchObject({ code: 'SUPERSEDED' });+ await vi.advanceTimersByTimeAsync(0);+ const requestId = f.getPush()!.requestId;+ await f.call({ kind: 'cancel', requestKey: 'old' });+ expect(f.slot.resolve(requestId, 7, 'chosen')).toBe(false);+ await settled;+ expect(f.send).not.toHaveBeenCalled();+ });+ it('fails closed when a fixed target disappears and does not choose a substitute', async () => {+ const f = fixture(),+ saved = await f.pick(true);+ f.slot.adapter!.candidates = async () => [+ { id: 'different', label: 'Another task', detail: '' },+ ];+ await expect(f.call({ kind: 'get', bindingId: saved.bindingId })).rejects.toMatchObject({+ code: 'TARGET_UNAVAILABLE',+ });+ expect(f.send).not.toHaveBeenCalled();+ expect(f.create).not.toHaveBeenCalled();+ });+ it('does not reopen an older picker after a slow candidate query finishes', async () => {+ const f = fixture();+ let releaseOld!: (value: Array<{ id: string; label: string; detail: string }>) => void;+ f.slot.adapter!.candidates = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseOld = resolve;+ }),+ )+ .mockResolvedValue([{ id: 'chosen', label: 'Chosen task', detail: '' }]);+ const old = f.call({ kind: 'pick', requestKey: 'slow', targetKind: 'task' });+ const rejected = expect(old).rejects.toMatchObject({ code: 'SUPERSEDED' });+ const current = f.call({ kind: 'pick', requestKey: 'current', targetKind: 'task' });+ await vi.advanceTimersByTimeAsync(0);+ const requestId = f.getPush()!.requestId;+ releaseOld([{ id: 'chosen', label: 'Chosen task', detail: '' }]);+ await rejected;+ expect(f.getPush()!.requestId).toBe(requestId);+ f.slot.resolve(requestId, 7, 'chosen');+ await current;+ expect(f.send).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 84b0fc8da1..eec364eb35 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3995,7 +3995,18 @@ const r = await cindy.agent.requestSchedule({用户拒绝或确认界面不可用时返回 \`PERMISSION_DENIED\`,不影响插件其它功能;不得自动循环重试确认。面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。-先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:+用户要把内容交给自己选定的项目、已有任务或伙伴时,使用独立的 \`cindy.targets\`(仅本机 Desktop 逻辑页,同样需要已批准的 \`agent.tasks\`)。先检查 \`typeof cindy.targets?.pick === 'function'\`;旧客户端没有此入口,不调用私有 IPC 或自动改投别处。++- \`pick({requestKey,targetKind:'project'|'task'|'bot',persistent?:boolean})\`:由 Cindy 展示目标列表、搜索和插件身份。用户取消返回 \`{cancelled:true}\`;成功返回 \`{bindingId,kind,label}\`,不向插件返回整份候选或消息历史。+- 默认只用于本次:返回的 bindingId 是 5 分钟有效、只可用于一次投递的句柄。+- \`persistent:true\` 明确让用户绑定今后可直接投递的固定目标。把 bindingId 存入插件配置;该 ID 不能直接 send。每次触发先 \`get({bindingId})\` 复核目标并换取本次临时句柄,再 send;临时选择不改写固定绑定。+- \`send({bindingId,requestKey,text,title?,route?,delivery?,attachments?})\`:仅接受本次临时句柄。project 在选定目录中新建普通任务,可传统一目录的 route;task/bot 沿用接收方模型和权限,不接受 route。\`delivery\` 可选 \`queue | steer\`,缺省 queue;project 不接受 steer。steer 尝试同轮注入,不停止当前轮,空闲或插话暂不可用时入队。返回 \`{taskId,accepted:true,delivery:"queue"|"steer"}\` 表示实际接受路径,不表示执行完成。筛查拒绝返回 DELIVERY_REJECTED,不入队重试;ACK 未知返回 DELIVERY_UNCERTAIN,宿主保留保护性暂停队列,不能重发。不开放读取任意任务历史或改模。+- \`tasks.send\` 和 \`targets.send\` 均支持可选 \`attachments:[{base64,name?}]\`:只接收插件提供的图片字节,不接受本机路径、URL、媒体 URI 或自报 MIME。Host 检测 PNG/JPEG/WebP,最多 4 张、合计 20 MiB。先检查 \`tasks.capabilities().messageAttachments.kinds\` 包含 image;旧客户端不支持时停止,不静默丢图或改投临时路径。截图进既有 cindy-media,作为消息附件展示并进入模型输入;不需要额外声明 media.deposit。附件内容及名称参与幂等签名,更换附件不能复用同键。+- 同一次 send 重试沿用相同 requestKey、句柄、内容和 delivery(缺省与 queue 等价);主机运行期间共享原投递结果。句柄用后不能换键再发;Host 重启后旧临时句柄失效。结果未知不得重新 get/pick 绕过后重发,应先让用户在 Cindy 检查。+- \`cancel({requestKey})\`:关闭该请求的选择器、使迟到选择失效,并仅撤回本插件尚未执行的输入;不会停止接收方其他输入,也不保证撤销已经开始的工作。+- 候选只包含本机可见、可用的项目、普通任务或有唯一 canonical 对话的活跃伙伴。最近活动只排序,不替用户选中;固定目标失效返回 TARGET_UNAVAILABLE,不自动降级。项目使用 Cindy 已有目录分组,不伪造 projectId。++原有 \`cindy.tasks\` 的归属限制不变。先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:\`models\`、\`create\`、\`get\`、\`setModel\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`、\`setHidden\`。可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,调用方已无正在执行的输入或已接受新真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限,自动回报和插件输入重试不构成真人接管。这不恢复插件控制权,也不保证停止已接受执行,不构成通用执行沙箱。diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 626540ad18..818a3ddb49 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -72,6 +72,8 @@ import { getDesktopProviderService } from '../maker-host/createDesktopProviderSeimport { PluginDownloadSlot } from './downloadSlot.js';import { createDownloader } from '../downloader/index.js';import { handlePluginTaskRequest, type PluginTaskHandler } from './taskSlot.js';+import { PluginTargetSlot, type PluginTargetAdapter } from './pluginTargetSlot.js';+import type { PluginTargetPickerPush } from '../../shared/pluginTargets.js';import { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate } from './taskCapability.js';import {registerGhostCardRemoteProvider,@@ -2092,6 +2094,22 @@ export function setGhostSessionRevealer(reveal: ((sessionId: string) => void) |getGhostErrandSlot().setRevealSession(reveal);}+const pluginTargetSlot = new PluginTargetSlot({+ name: id => findGhostForInstanceId(id)?.manifest.name ?? id,+ revision: getPluginTaskInstallRevision,+ open: (payload: PluginTargetPickerPush) => {+ const window = getDeepLinkMainWindow();+ if (!window || window.isDestroyed() || !isTrustedAppRendererWindow(window)) throw new Error('HOST_NOT_READY');+ const owner = getActiveDataOwnerPushStamp();+ window.show(); window.focus();+ sendGhostWindowPush(window, 'ghosts:target-picker', payload, owner);+ return { senderId: window.webContents.id, close: () => {+ if (!window.isDestroyed()) sendGhostWindowPush(window, 'ghosts:target-picker-dismiss', { requestId: payload.requestId }, owner);+ } };+ },+});+export function setPluginTargetAdapter(adapter: PluginTargetAdapter): void { pluginTargetSlot.adapter = adapter; }+let pluginTaskHandler: PluginTaskHandler | null = null;export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }let pluginTaskUninstaller: ((pluginId: string, remove: () => Promise<void>) => Promise<void>) | null = null;@@ -8608,7 +8626,7 @@ export function registerGhostIpc(): void {// 专属 errand 会话跑一轮,最终回复文字取回给插件;任务文本同样只进// 普通 user 消息。资格审/频控/任务表在 errandSlot,会话与收口在注入// 的 runner(maker-ipc)。- if (type === 'tasks-request') {+ if (type === 'tasks-request' || type === 'targets-request') {const owner = getActiveDataOwnerPushStamp();const pageId = (payload as { mobilePageId?: unknown }).mobilePageId;const pageCurrent = pageId === undefined ? undefined : mobilePluginPages?.captureSource(pageId, id);@@ -8618,7 +8636,8 @@ export function registerGhostIpc(): void {return owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&!event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id && (!pageCurrent || pageCurrent());};- return handlePluginTaskRequest(id, payload, {+ if (type === 'targets-request' && pageId !== undefined) throw new Error('UNSUPPORTED_CAPABILITY');+ const result = await handlePluginTaskRequest(id, type === 'targets-request' ? { type: 'tasks-request', kind: 'capabilities' } : payload, {getGhost: findGhostForInstanceId, handler: pluginTaskHandler,isCurrent,ensureAuthorized: () => requestPluginTaskApproval(id, isCurrent, facts => {@@ -8637,6 +8656,18 @@ export function registerGhostIpc(): void {return createWindowGhostInstallConsentPrompt(window.webContents)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts });}),});+ if (type !== 'targets-request' || !result.ok) return result;+ const revision = pluginTaskAuthorizationRevision(id);+ const assertAuthorized = () => {+ if (!isCurrent() || !revision || pluginTaskAuthorizationRevision(id) !== revision || !isPluginTaskAuthorized(id))+ throw Object.assign(new Error('PERMISSION_DENIED'), { code: 'PERMISSION_DENIED' });+ };+ try { return { ok: true, data: await pluginTargetSlot.handle(id, payload, assertAuthorized) }; }+ catch (error) {+ const rawCode = (error as { code?: unknown })?.code ?? (error instanceof Error ? error.message : '');+ const code = ['PERMISSION_DENIED', 'HOST_NOT_READY', 'INVALID_PARAMS', 'INVALID_ATTACHMENTS', 'TARGET_UNAVAILABLE', 'SUPERSEDED', 'REQUEST_KEY_CONFLICT', 'DELIVERY_UNCERTAIN', 'DELIVERY_REJECTED', 'STALE_REVISION', 'ROUTE_UNAVAILABLE'].includes(String(rawCode)) ? String(rawCode) : 'HOST_NOT_READY';+ return { ok: false, error: { code, message: code, retryable: false } };+ }}if (type === 'agent-errand-request') {return getGhostErrandSlot().handleRequest(id, payload);@@ -8723,6 +8754,13 @@ export function registerGhostIpc(): void {throwIpcError('INVALID_PARAMS', '未知的管子消息类型');});+ // User-selected destination replies are accepted only from the trusted receiving window.+ ipcMain.handle('ghosts:target-picker:resolve', (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ const value = raw as { requestId?: unknown; targetId?: unknown } | null;+ return { handled: typeof value?.requestId === 'string' && pluginTargetSlot.resolve(value.requestId, event.sender.id, value.targetId) };+ });+// ── 确认弹窗回包(confirm 槽)────────────────────────────────────────// renderer 上的确认框被用户点掉之后,把答案送回 main 结算那条挂起的管子请求。// 不校验 sender 归属:requestId 是 main 自己铸的 randomUUID,只在本机 rendererdiff --git a/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.tsnew file mode 100644index 0000000000..573c1b668f--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts@@ -0,0 +1,381 @@+import { createHash, randomUUID } from 'node:crypto';+import type {+ PluginTargetCandidate,+ PluginTargetDelivery,+ PluginTargetKind,+ PluginTargetPickerPush,+ PluginTargetRequest,+ PluginTargetView,+} from '../../shared/pluginTargets.js';+import type { PluginTaskRoute } from '../../shared/pluginTasks.js';+import {+ getActiveDataOwnerPushStamp,+ ownerScopedUserDataPath,+ activeOwnerScopeKey,+} from '../appSessionState.js';+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';+import { parsePluginMessageAttachments, type PluginMessageImage } from '../cindy-media/pluginMessageAttachments.js';++interface Binding extends PluginTargetView {+ pluginId: string;+ targetId: string;+}+interface Receipt {+ pluginId: string;+ requestKey: string;+ hash: string;+ clientId: string;+ taskId?: string;+ status: 'pending' | 'accepted' | 'cancelled';+}+interface Ledger {+ bindings: Record<string, Binding>;+}+export interface PluginTargetAdapter {+ candidates(kind: PluginTargetKind): Promise<PluginTargetCandidate[]>;+ create(+ pluginId: string,+ project: string,+ taskId: string,+ title: string,+ route: PluginTaskRoute | undefined,+ guard: () => void,+ ): Promise<void>;+ session(kind: 'task' | 'bot', id: string): Promise<string>;+ send(+ pluginId: string,+ taskId: string,+ clientId: string,+ text: string,+ guard: () => void,+ validateTarget: () => Promise<void>,+ delivery: PluginTargetDelivery,+ images?: PluginMessageImage[],+ ): Promise<PluginTargetDelivery>;+ withdraw(taskId: string, clientId: string, guard: () => void): Promise<void>;+}+const fail = (code: string): never => {+ throw Object.assign(new Error(code), { code });+};+const keyString = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0 && value.length <= 200 && !value.includes('\0');+const kinds = ['project', 'task', 'bot'];+const ledger = createOverrideSettingsFile<Ledger>({+ filePath: () => ownerScopedUserDataPath('plugin-targets.json'),+ scopeKey: activeOwnerScopeKey,+ defaults: { bindings: {} },+ normalize: (raw) => {+ const value = raw as Ledger | null;+ return {+ bindings: value?.bindings && typeof value.bindings === 'object' ? value.bindings : {},+ };+ },+ log: desktopMakerLogger.child('plugin-targets'),+ label: 'plugin-targets',+ preserveUnreadableFile: true,+ logLoadedValue: false,+ logReadErrorDetails: false,+});+/** User selection is the grant. No plugin-supplied task ID or project path is accepted. */+export class PluginTargetSlot {+ adapter: PluginTargetAdapter | null = null;+ private temporary = new Map<string, Binding & { expiresAt: number; consumedBy?: string }>();+ private receipts = new Map<string, Receipt & { result?: Promise<unknown> }>();+ private operations = new Map<string, { cancelled: boolean; expiresAt: number }>();+ private activePicker = new Map<string, object>();+ private picks = new Map<+ string,+ {+ operation: string;+ pluginId: string;+ senderId: number;+ options: PluginTargetCandidate[];+ resolve: (id: string | null) => void;+ close: () => void;+ }+ >();+ constructor(+ private readonly ui: {+ open(payload: PluginTargetPickerPush): { senderId: number; close: () => void };+ name(pluginId: string): string;+ revision(pluginId: string): string | null;+ },+ ) {}+ private scope(pluginId: string, key: string) {+ return JSON.stringify([+ activeOwnerScopeKey(),+ getActiveDataOwnerPushStamp().ownerGeneration,+ pluginId,+ this.ui.revision(pluginId),+ key,+ ]);+ }+ private read() {+ ledger.invalidateIfChanged();+ return ledger.read();+ }+ private binding(pluginId: string, id: string): Binding {+ const binding = this.read().bindings[id];+ if (!binding || binding.pluginId !== pluginId || !kinds.includes(binding.kind))+ return fail('TARGET_UNAVAILABLE');+ return binding;+ }+ resolve(requestId: string, senderId: number, id: unknown): boolean {+ const pending = this.picks.get(requestId);+ if (!pending || pending.senderId !== senderId) return false;+ pending.resolve(+ typeof id === 'string' && pending.options.some((item) => item.id === id) ? id : null,+ );+ return true;+ }+ private cancelPick(operation: string) {+ for (const pending of this.picks.values())+ if (pending.operation === operation) pending.resolve(null);+ }+ async handle(pluginId: string, raw: unknown, authorized: () => void): Promise<unknown> {+ authorized();+ for (const [key, binding] of this.temporary)+ if (binding.expiresAt < Date.now()) this.temporary.delete(key);+ for (const [key, operation] of this.operations)+ if (operation.expiresAt < Date.now() && !this.receipts.has(key)) {+ this.operations.delete(key);+ this.receipts.delete(key);+ }+ if (!this.adapter) return fail('HOST_NOT_READY');+ const adapter = this.adapter;+ const request = raw as PluginTargetRequest;+ if (!request || !['pick', 'get', 'send', 'cancel'].includes(request.kind))+ return fail('INVALID_PARAMS');+ if (request.kind === 'get') {+ if (!keyString(request.bindingId)) return fail('INVALID_PARAMS');+ const binding = this.binding(pluginId, request.bindingId);+ const candidates = await adapter.candidates(binding.kind);+ authorized();+ const fresh = candidates.find((item) => item.id === binding.targetId);+ if (!fresh) return fail('TARGET_UNAVAILABLE');+ // Exchange a saved binding for a short-lived, one-use delivery handle.+ // A Host restart loses handles, so an uncertain send cannot replay after restart.+ const handle = {+ ...binding,+ bindingId: randomUUID(),+ label: fresh.label.slice(0, 200),+ expiresAt: Date.now() + 300000,+ };+ this.temporary.set(this.scope(pluginId, handle.bindingId), handle);+ return { bindingId: handle.bindingId, kind: handle.kind, label: handle.label };+ }+ if (!keyString(request.requestKey)) return fail('INVALID_PARAMS');+ const operationKey = this.scope(pluginId, request.requestKey);+ if (request.kind === 'cancel') {+ const operation = this.operations.get(operationKey) ?? {+ cancelled: true,+ expiresAt: Date.now() + 600000,+ };+ operation.cancelled = true;+ this.operations.set(operationKey, operation);+ this.cancelPick(operationKey);+ const receipt = this.receipts.get(operationKey);+ if (receipt?.taskId) {+ // Withdraw only this plugin input. Never stop another user's running turn.+ await adapter.withdraw(receipt.taskId, receipt.clientId, authorized);+ authorized();+ }+ this.receipts.delete(operationKey);+ return { cancelled: true, runningWorkMayHaveStarted: receipt?.status === 'accepted' };+ }+ let operation = this.operations.get(operationKey);+ if (!operation) {+ operation = { cancelled: false, expiresAt: Date.now() + 600000 };+ this.operations.set(operationKey, operation);+ }+ const guard = () => {+ authorized();+ if (operation!.cancelled) fail('SUPERSEDED');+ };+ guard();+ if (request.kind === 'pick') {+ if (+ !kinds.includes(request.targetKind) ||+ (request.persistent !== undefined && typeof request.persistent !== 'boolean')+ )+ return fail('INVALID_PARAMS');+ const marker = {};+ this.activePicker.set(pluginId, marker);+ const guardPicker = () => {+ guard();+ if (this.activePicker.get(pluginId) !== marker) fail('SUPERSEDED');+ };+ // A plugin gets at most one live picker; replacement also settles the old IPC.+ for (const pending of this.picks.values())+ if (pending.pluginId === pluginId) pending.resolve(null);+ const candidates = await adapter.candidates(request.targetKind);+ guardPicker();+ const requestId = randomUUID();+ const selected = await new Promise<string | null>((resolve, reject) => {+ let ui: { senderId: number; close: () => void };+ let timer: ReturnType<typeof setTimeout>;+ let boundaryTimer: ReturnType<typeof setInterval>;+ const finish = (id: string | null) => {+ clearTimeout(timer);+ clearInterval(boundaryTimer);+ this.picks.delete(requestId);+ ui?.close();+ resolve(id);+ };+ try {+ ui = this.ui.open({+ requestId,+ pluginName: this.ui.name(pluginId),+ kind: request.targetKind,+ persistent: request.persistent === true,+ candidates,+ });+ this.picks.set(requestId, {+ operation: operationKey,+ pluginId,+ senderId: ui.senderId,+ options: candidates,+ resolve: finish,+ close: ui.close,+ });+ timer = setTimeout(() => finish(null), 120000);+ boundaryTimer = setInterval(() => {+ try {+ guardPicker();+ } catch {+ finish(null);+ }+ }, 500);+ } catch (error) {+ reject(error);+ }+ });+ guardPicker();+ if (!selected) return { cancelled: true };+ const candidate = candidates.find((item) => item.id === selected)!;+ const binding: Binding = {+ pluginId,+ bindingId: randomUUID(),+ kind: request.targetKind,+ targetId: candidate.id,+ label: candidate.label.slice(0, 200),+ };+ if (request.persistent) {+ await ledger.updateAtomic(({ value }) => {+ guardPicker();+ return { bindings: { ...value.bindings, [binding.bindingId]: binding } };+ });+ guardPicker();+ } else+ this.temporary.set(this.scope(pluginId, binding.bindingId), {+ ...binding,+ expiresAt: Date.now() + 300000,+ });+ return { bindingId: binding.bindingId, kind: binding.kind, label: binding.label };+ }+ if (+ !keyString(request.bindingId) ||+ typeof request.text !== 'string' ||+ !request.text.trim() ||+ request.text.length > 64000 ||+ (request.delivery !== undefined && !['queue', 'steer'].includes(request.delivery)) ||+ (request.title !== undefined &&+ (typeof request.title !== 'string' || request.title.length > 200))+ )+ return fail('INVALID_PARAMS');+ // Saved IDs authorize resolution, not sending. Only a host-minted live handle sends.+ const binding = this.temporary.get(this.scope(pluginId, request.bindingId));+ if (!binding || binding.pluginId !== pluginId) return fail('TARGET_UNAVAILABLE');+ const delivery = request.delivery ?? 'queue';+ if (binding.kind === 'project' && delivery === 'steer') return fail('INVALID_PARAMS');+ if (request.route !== undefined) {+ const route = request.route;+ if (+ !route ||+ !['cc', 'codex', 'pi'].includes(route.agentKind) ||+ !keyString(route.providerId) ||+ typeof route.model !== 'string' ||+ !route.model.trim() ||+ route.model.length > 256 ||+ typeof route.effort !== 'string' ||+ route.effort.length > 32 ||+ typeof route.fastMode !== 'boolean'+ )+ return fail('INVALID_PARAMS');+ }+ if (binding.kind !== 'project' && request.route !== undefined) return fail('INVALID_PARAMS');+ const images = parsePluginMessageAttachments(request.attachments);+ const candidates = await adapter.candidates(binding.kind);+ guard();+ if (!candidates.some((item) => item.id === binding.targetId)) return fail('TARGET_UNAVAILABLE');+ const hash = createHash('sha256')+ .update(JSON.stringify([binding.bindingId, request.text, request.title, request.route, delivery,+ images.map(({ hash, name }) => [hash, name])]))+ .digest('hex');+ const receipt: Receipt = {+ pluginId,+ requestKey: request.requestKey,+ hash,+ clientId: randomUUID(),+ status: 'pending',+ };+ const previous = this.receipts.get(operationKey);+ if (previous) {+ if (previous.hash !== hash) return fail('REQUEST_KEY_CONFLICT');+ if (previous.result) return previous.result;+ return fail('DELIVERY_UNCERTAIN');+ }+ // A one-use handle cannot become a second delivery by changing text or requestKey.+ if (binding.consumedBy && binding.consumedBy !== operationKey)+ return fail('DELIVERY_UNCERTAIN');+ binding.consumedBy = operationKey;+ const saved: Receipt & { result?: Promise<unknown> } = receipt;+ this.receipts.set(operationKey, saved);+ const deliver = async () => {+ receipt.taskId =+ binding.kind === 'project'+ ? randomUUID()+ : await adapter.session(binding.kind, binding.targetId);+ guard();+ if (binding.kind === 'project')+ await adapter.create(+ pluginId,+ binding.targetId,+ receipt.taskId,+ request.title || binding.label,+ request.route,+ guard,+ );+ guard();+ const actualDelivery = await adapter.send(+ pluginId,+ receipt.taskId,+ receipt.clientId,+ request.text,+ guard,+ async () => {+ const fresh = await adapter.candidates(binding.kind);+ guard();+ if (!fresh.some((item) => item.id === binding.targetId)) fail('TARGET_UNAVAILABLE');+ if (+ binding.kind !== 'project' &&+ (await adapter.session(binding.kind, binding.targetId)) !== receipt.taskId+ )+ fail('TARGET_UNAVAILABLE');+ guard();+ },+ delivery,+ images,+ );+ receipt.status = 'accepted';+ authorized();+ if (operation.cancelled) await adapter.withdraw(receipt.taskId, receipt.clientId, authorized);+ return { taskId: receipt.taskId, accepted: true, delivery: actualDelivery };+ };+ saved.result = deliver().finally(() => {+ if (operation!.cancelled) this.receipts.delete(operationKey);+ });+ return saved.result;+ }+}diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.tsindex b06f12d76f..292a8c0f51 100644--- a/apps/desktop/src/main/cindy-brain/taskSlot.ts+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts@@ -2,6 +2,7 @@ import { ghostDeclaresHiddenTasks, type InstalledGhost } from '../../shared/ghosimport type { PluginTaskRequest, PluginTaskResult } from '../../shared/pluginTasks.js';import { isPluginTeamPlanWithinBudget } from '../../shared/pluginTasks.js';import { hasPluginTaskApproval } from './taskCapability.js';+import { PLUGIN_ATTACHMENT_MAX_BYTES, validPluginMessageAttachments } from '../../shared/pluginAttachments.js';export const PLUGIN_TASK_OPERATIONS = ['capabilities',@@ -41,7 +42,7 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskRequegetTeam: ['taskId'],setTeamPlan: ['taskId', 'plan'],releaseWorker: ['taskId', 'workerId', 'completedAt'],- send: ['taskId', 'requestKey', 'expectedRevision', 'text'],+ send: ['taskId', 'requestKey', 'expectedRevision', 'text', 'attachments'],getRun: ['runId'],listRuns: ['taskId', 'after', 'limit'],readMessages: ['taskId', 'after', 'limit'],@@ -68,7 +69,7 @@ export function validPluginTaskRequest(value: unknown): value is PluginTaskRequeif (value.kind === 'create' && !text(value.title, 100)) return false;if (value.kind === 'send' &&- (!text(value.text, 32768) ||+ (!text(value.text, 32768) || !validPluginMessageAttachments(value.attachments) ||!Number.isSafeInteger(value.expectedRevision) ||(value.expectedRevision as number) < 0))@@ -157,6 +158,7 @@ export async function handlePluginTaskRequest(exactRoute: true,pluginDefaultModel: true,sourceCallContext: true,+ messageAttachments: { kinds: ['image'], maxCount: 4, maxBytes: PLUGIN_ATTACHMENT_MAX_BYTES },hiddenTasks: declaresHiddenTasks(),},};diff --git a/apps/desktop/src/main/cindy-media/__tests__/pluginMessageAttachments.test.ts b/apps/desktop/src/main/cindy-media/__tests__/pluginMessageAttachments.test.tsnew file mode 100644index 0000000000..9fa3ec696d--- /dev/null+++ b/apps/desktop/src/main/cindy-media/__tests__/pluginMessageAttachments.test.ts@@ -0,0 +1,74 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createHash } from 'node:crypto';+import { PLUGIN_ATTACHMENT_MAX_BYTES } from '../../../shared/pluginAttachments.js';++const state = vi.hoisted(() => ({ owner: { client: { drizzle: {} } }, ingest: vi.fn() }));+vi.mock('../../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => state.owner }));+vi.mock('../blobStore.js', () => ({+ extForMime: (mime: string) => ({ 'image/png': '.png', 'image/jpeg': '.jpg' } as Record<string, string>)[mime],+ blobUrl: (hash: string, ext: string) => `cindy-media://blobs/${hash}${ext}`,+}));+vi.mock('../ingest.js', () => ({ ingestMedia: state.ingest }));+import { collectPluginAttachmentPayloadTexts, parsePluginMessageAttachments, withPluginMessageAttachments } from '../pluginMessageAttachments.js';++const bytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);+const base64 = bytes.toString('base64');+const hash = createHash('sha256').update(bytes).digest('hex');+const url = `cindy-media://blobs/${hash}.png`;+const images = () => parsePluginMessageAttachments([{ base64, name: 'window.png' }]);+afterEach(() => { state.ingest.mockReset(); expect(collectPluginAttachmentPayloadTexts()).toEqual([]); });++describe('plugin message image delivery', () => {+ // Production boundary: parsePluginMessageAttachments. No URL/path reads or caller MIME trust.+ it.each([+ [{ url }], [{ path: '/private/window.png', base64 }], [{ base64, mimeType: 'image/png' }],+ [{ base64: 'not image===' }], [{ base64: Buffer.from('plain text').toString('base64') }],+ [{ base64, name: '../window.png' }], Array.from({ length: 5 }, () => ({ base64 })),+ [{ base64: 'A'.repeat(Math.ceil(PLUGIN_ATTACHMENT_MAX_BYTES / 3) * 4 + 4) }],+ ].map(value => ({ value })))('rejects invalid or oversized attachments before ingestion', ({ value }) => {+ expect(() => parsePluginMessageAttachments(value)).toThrow('INVALID_ATTACHMENTS');+ expect(state.ingest).not.toHaveBeenCalled();+ });+ it('detects the image from bytes and protects it through the durable handoff', async () => {+ state.ingest.mockImplementation(async (input: { assertStillValid: () => void }, db: unknown) => {+ input.assertStillValid();+ expect(db).toBe(state.owner.client.drizzle);+ expect(collectPluginAttachmentPayloadTexts().join('')).toContain(url);+ return { url, mimeType: 'image/png', ext: '.png', bytes: bytes.length };+ });+ const result = await withPluginMessageAttachments(images(), () => {}, async files => {+ expect(files).toMatchObject([{ url, category: 'image', mimeType: 'image/png', path: '', originalName: 'window.png' }]);+ expect(files[0]).not.toHaveProperty('base64');+ expect(collectPluginAttachmentPayloadTexts().join('')).toContain(url);+ return 'persisted';+ });+ expect(result).toBe('persisted');+ expect(state.ingest).toHaveBeenCalledWith(expect.objectContaining({ refs: [], isCache: false }), state.owner.client.drizzle);+ });+ it.each(['SUPERSEDED', 'DELIVERY_REJECTED', 'DELIVERY_UNCERTAIN'])('releases only in-flight protection after %s without replaying', async code => {+ state.ingest.mockResolvedValue({ url, mimeType: 'image/png', ext: '.png', bytes: bytes.length });+ const deliver = vi.fn(async () => { throw new Error(code); });+ await expect(withPluginMessageAttachments(images(), () => {}, deliver)).rejects.toThrow(code);+ expect(deliver).toHaveBeenCalledOnce();+ // Any adopted queue/message is protected by the existing queue and chat ref owners.+ expect(collectPluginAttachmentPayloadTexts()).toEqual([]);+ });+ it('rejects a stale owner after ingestion and never submits to the new account', async () => {+ state.ingest.mockImplementation(async () => {+ state.owner = { client: { drizzle: {} } };+ return { url, mimeType: 'image/png', ext: '.png', bytes: bytes.length };+ });+ const deliver = vi.fn();+ await expect(withPluginMessageAttachments(images(), () => {}, deliver)).rejects.toThrow('PERMISSION_DENIED');+ expect(deliver).not.toHaveBeenCalled();+ });+ it('does not deliver after an import failure; a retry imports the same content safely', async () => {+ const deliver = vi.fn(async () => 'accepted');+ state.ingest.mockRejectedValueOnce(new Error('write failed'))+ .mockResolvedValueOnce({ url, mimeType: 'image/png', ext: '.png', bytes: bytes.length });+ await expect(withPluginMessageAttachments(images(), () => {}, deliver)).rejects.toThrow('write failed');+ expect(deliver).not.toHaveBeenCalled();+ expect(await withPluginMessageAttachments(images(), () => {}, deliver)).toBe('accepted');+ expect(deliver).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/cindy-media/pluginMessageAttachments.ts b/apps/desktop/src/main/cindy-media/pluginMessageAttachments.tsnew file mode 100644index 0000000000..071a33b20a--- /dev/null+++ b/apps/desktop/src/main/cindy-media/pluginMessageAttachments.ts@@ -0,0 +1,65 @@+import { createHash, randomUUID } from 'node:crypto';+import type { AgentInputSerializedFile } from '../../shared/agentInputQueue.js';+import { validPluginMessageAttachments } from '../../shared/pluginAttachments.js';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { blobUrl, extForMime } from './blobStore.js';+import { ingestMedia } from './ingest.js';+import { sniffMediaMime } from './sniffMediaMime.js';++export interface PluginMessageImage {+ buffer: Buffer;+ mimeType: string;+ hash: string;+ name: string;+}+export function parsePluginMessageAttachments(value: unknown): PluginMessageImage[] {+ const invalid = () => Object.assign(new Error('INVALID_ATTACHMENTS'), { code: 'INVALID_ATTACHMENTS' });+ if (!validPluginMessageAttachments(value)) throw invalid();+ return (value ?? []).map(item => {+ const buffer = Buffer.from(item.base64, 'base64');+ const mimeType = sniffMediaMime(buffer);+ if (!mimeType || !['image/png', 'image/jpeg', 'image/webp'].includes(mimeType)+ || buffer.toString('base64') !== item.base64) throw invalid();+ return { buffer, mimeType, hash: createHash('sha256').update(buffer).digest('hex'),+ name: item.name ?? `image${extForMime(mimeType)}` };+ });+}++// Extend the existing draft/queued-message live set across import → durable queue.+// Register before the first await, including deduplicated blobs older than the GC buffer.+const inFlight = new Set<string[]>();+export function collectPluginAttachmentPayloadTexts(): string[] {+ return [...inFlight].map(urls => JSON.stringify(urls));+}+export async function withPluginMessageAttachments<T>(+ images: PluginMessageImage[],+ assertCurrent: () => void,+ deliver: (files: AgentInputSerializedFile[]) => Promise<T>,+): Promise<T> {+ assertCurrent();+ if (!images.length) return deliver([]);+ const snapshot = getCurrentDbClientSnapshot();+ if (!snapshot) throw Object.assign(new Error('HOST_NOT_READY'), { code: 'HOST_NOT_READY' });+ const guard = () => {+ assertCurrent();+ if (snapshot !== getCurrentDbClientSnapshot())+ throw Object.assign(new Error('PERMISSION_DENIED'), { code: 'PERMISSION_DENIED' });+ };+ const urls = images.map(image => blobUrl(image.hash, extForMime(image.mimeType) ?? '.png'));+ inFlight.add(urls);+ try {+ const files = [];+ for (const image of images) {+ const media = await ingestMedia({ buffer: image.buffer, mimeType: image.mimeType,+ isCache: false, refs: [], assertStillValid: guard }, snapshot.client.drizzle);+ guard();+ files.push({ id: randomUUID(), name: image.name, originalName: image.name, category: 'image' as const,+ path: '', ext: media.ext, size: media.bytes, mimeType: media.mimeType, url: media.url });+ }+ // Caller awaits the existing durable queue write, or same-turn message persistence.+ // Those existing owners protect the URL after this in-flight scope is released.+ return await deliver(files);+ } finally {+ inFlight.delete(urls);+ }+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 3dfbcec720..70060098d8 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -1558,6 +1558,27 @@ describe('agent-chosen control steering', () => {function expected(h: ReturnType<typeof createHarness>) {return { session: h.getTurnSessionIdentity(), turnGeneration: 0 };}+ // Production entry: steerControlInput. Plugin target grants must survive screening+ // and provider preparation; existing turn-boundary cases do not revoke grants. In-memory unit tier.+ it.each(['screening', 'provider-preparation'])('does not queue or accept input revoked during %s', async (stage) => {+ const h = createHarness();+ h.setRunning(true);+ let revoked = false;+ const beforeMutation = async () => { if (revoked) throw new Error('PERMISSION_DENIED'); };+ if (stage === 'screening') h.setScreenUserMessage(async () => {+ revoked = true;+ return { action: 'allow' };+ });+ else h.steerToAgent.mockImplementationOnce(async (_id, _message, sendOpts) => {+ revoked = true;+ await sendOpts.beforeProviderStart?.();+ });+ await expect(h.coordinator.steerControlInput(sid, { item: makeItem('report', 'context') },+ { ...expected(h), beforeMutation })).rejects.toThrow('PERMISSION_DENIED');+ expect(h.coordinator.hasPendingQueueItem(sid, 'report')).toBe(false);+ expect(h.onSteerAccepted).not.toHaveBeenCalled();+ expect(h.sendToAgent).not.toHaveBeenCalled();+ });it('joins a running turn even though ordinary new turns must queue', async () => {const h = createHarness();h.setRunning(true);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.tsindex 964b6403fa..924a3424b5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageSourceNote.test.ts@@ -157,7 +157,7 @@ describe('delivery-path wiring (source contract)', () => {it('plugin task dispatch stamps the plugin identity without an origin kind', () => {const pluginDispatch = between(register,- 'dispatch: async (pluginId, taskId, clientId, text) => {',+ 'dispatch: async (pluginId, taskId, clientId, text','inspect: async taskId =>',);expect(pluginDispatch).toContain(diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.tsindex c1e2a8880e..8dda3db472 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts@@ -166,6 +166,20 @@ function fixture() {};}+it('includes message images in owned-task replay identity without persisting screenshot bytes', async () => {+ const f = fixture(), task = await f.create();+ const base64 = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString('base64');+ const request = { taskId: task.taskId, requestKey: 'image', expectedRevision: task.revision,+ text: 'context', attachments: [{ base64, name: 'window.png' }] };+ await f.service.send('p', request);+ await f.service.send('p', structuredClone(request));+ expect(f.deps.dispatch).toHaveBeenCalledOnce();+ expect(vi.mocked(f.deps.dispatch).mock.calls[0]?.[4]?.[0]).toMatchObject({ mimeType: 'image/png' });+ expect(JSON.stringify([...f.rows.values()])).not.toContain(base64);+ await expect(f.service.send('p', { ...request, attachments: [{ base64, name: 'other.png' }] }))+ .rejects.toMatchObject({ code: 'IDEMPOTENCY_CONFLICT' });+});+describe('plugin dispatch uses live Plan execution authority', () => {it.each(['send', 'accept'] as const)('%s rejects consumed Pi intent while execution is active, unknown or switching', async entry => {const f = fixture(), task = await f.create();diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 3abbeaca6b..10a5871095 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -206,6 +206,8 @@ function hasRetryableQueuedContent(item: AgentInputQueuedMessage): boolean {}export interface AgentInputSendOpts {+ /** Main-only authorization recheck after async steer preparation, before provider dispatch. */+ beforeProviderStart?: () => Promise<void>;/** Main-only App grant, checked by the send/steer transaction at dispatch. */readonly [MCP_APP_MESSAGE_GUARD]?: McpAppMessageGuard;readonly [AUTO_REVIEW_DELEGATED_CONTINUATION]?: true;@@ -2208,7 +2210,7 @@ export class AgentInputCoordinator {async steerControlInput(sessionId: string,target: { item: AgentInputQueuedMessage } | { queuedClientId: string },- expectedTurn: { session: object; turnGeneration: number },+ expectedTurn: { session: object; turnGeneration: number; beforeMutation?: () => Promise<void> },): Promise<ControlSteerOutcome> {await this.ensureQueueRestored(sessionId).catch(() => undefined);const state = this.getState(sessionId);@@ -2229,6 +2231,7 @@ export class AgentInputCoordinator {controlInput: { fromQueue },expectedTurnSession: expectedTurn.session,expectedTurnGeneration: expectedTurn.turnGeneration,+ beforeMutation: expectedTurn.beforeMutation,});if (observed.providerAccepted) return 'steered';// Input screening discarded the content: a definitive refusal, never a retry candidate.@@ -2552,6 +2555,10 @@ export class AgentInputCoordinator {);const appMessageGuard = queuedAppMessageGuard(item);await this.deps.steerToAgent(sessionId, buildMakerUserMessage(item, referenceContexts), {+ ...(opts?.beforeMutation ? { beforeProviderStart: async () => {+ try { await opts.beforeMutation!(); }+ catch (error) { authorizationFailed = true; throw error; }+ } } : {}),...(appMessageGuard ? { [MCP_APP_MESSAGE_GUARD]: appMessageGuard } : {}),...(item.sharedTaskAuthor ? { sharedTaskAuthor: item.sharedTaskAuthor } : {}),[AUTO_REVIEW_SOURCE_CONTENT]: queuedAutoReviewText(item),diff --git a/apps/desktop/src/main/maker-ipc/pluginTargetCandidates.ts b/apps/desktop/src/main/maker-ipc/pluginTargetCandidates.tsnew file mode 100644index 0000000000..af0b0f7a82--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/pluginTargetCandidates.ts@@ -0,0 +1,87 @@+import { and, desc, eq, isNull, ne, or } from 'drizzle-orm';+import path from 'node:path';+import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { botProfiles, botSessionLinks, sessions } from '../localDb/schema.js';+import { listRecentWorkdirs } from '../localDb/ipc/recentWorkdirs.js';+import { resolveBotCanonicalSession } from './botCanonicalSessionRegistry.js';+import type { PluginTargetCandidate, PluginTargetKind } from '../../shared/pluginTargets.js';++export async function listPluginTargetCandidates(+ kind: PluginTargetKind,+): Promise<PluginTargetCandidate[]> {+ const snapshot = getCurrentDbClientSnapshot();+ if (!snapshot) throw new Error('HOST_NOT_READY');+ const db = snapshot.client.drizzle;+ let result: PluginTargetCandidate[];+ if (kind === 'project') {+ result = (await listRecentWorkdirs(snapshot.client))+ .filter((row) => row.exists)+ .map((row) => ({+ id: row.path,+ label: path.basename(row.path) || row.path,+ detail: row.path,+ }));+ } else if (kind === 'bot') {+ const rows = await db+ .select({+ id: botProfiles.id,+ label: botProfiles.displayName,+ detail: botProfiles.description,+ })+ .from(botProfiles)+ .innerJoin(+ botSessionLinks,+ and(+ eq(botSessionLinks.botId, botProfiles.id),+ eq(botSessionLinks.role, 'canonical'),+ isNull(botSessionLinks.archivedAt),+ ),+ )+ .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))+ .where(+ and(+ eq(botProfiles.status, 'active'),+ isNull(botProfiles.hiddenAt),+ eq(sessions.status, 'active'),+ isNull(sessions.remoteHostId),+ isNull(sessions.agentDeviceId),+ ),+ )+ .orderBy(desc(sessions.userSendAt), desc(sessions.updatedAt));+ const counts = new Map<string, number>();+ for (const row of rows) counts.set(row.id, (counts.get(row.id) ?? 0) + 1);+ result = rows.filter((row) => counts.get(row.id) === 1);+ } else {+ const rows = await db+ .select({ id: sessions.id, label: sessions.title, detail: sessions.workingDir })+ .from(sessions)+ .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))+ .where(+ and(+ eq(sessions.status, 'active'),+ isNull(sessions.remoteHostId),+ isNull(sessions.agentDeviceId),+ isNull(sessions.hiddenAt),+ isNull(botSessionLinks.id),+ ne(sessions.source, 'bot'),+ ne(sessions.source, 'review'),+ or(isNull(sessions.orcaRole), ne(sessions.orcaRole, 'worker')),+ ),+ )+ .orderBy(desc(sessions.userSendAt), desc(sessions.updatedAt));+ result = rows.map((row) => ({ ...row, detail: row.detail || '' }));+ }+ if (getCurrentDbClientSnapshot() !== snapshot) throw new Error('PERMISSION_DENIED');+ return result;+}+export async function resolvePluginTargetSession(+ kind: 'task' | 'bot',+ id: string,+): Promise<string> {+ if (!(await listPluginTargetCandidates(kind)).some((row) => row.id === id))+ throw new Error('TARGET_UNAVAILABLE');+ if (kind === 'task') return id;+ const canonical = await resolveBotCanonicalSession(id);+ if (canonical.status !== 'resolved') throw new Error('TARGET_UNAVAILABLE');+ return canonical.sessionId;+}diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.tsindex cdc1cf1a3f..c578a97c1f 100644--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts@@ -2,6 +2,8 @@ import { createHash, randomUUID } from 'node:crypto';import type { Session } from '@cindy/maker-core';import type { PluginTaskRoute, PluginTaskRun, PluginTaskView, PluginTeamPlan } from '../../shared/pluginTasks.js';import { isPluginTeamPlanWithinBudget, PLUGIN_TASK_RECEIPT_MAX_JSON_CHARS } from '../../shared/pluginTasks.js';+import type { PluginMessageAttachment } from '../../shared/pluginAttachments.js';+import { parsePluginMessageAttachments, type PluginMessageImage } from '../cindy-media/pluginMessageAttachments.js';import {isSameSessionExecution,queuedInputBelongsTo,@@ -135,6 +137,7 @@ export interface PluginTaskServiceDeps {taskId: string,clientId: string,text: string,+ images?: PluginMessageImage[],): Promise<{ ok: boolean; message?: string }>;inspect(taskId: string,@@ -437,11 +440,16 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {}),send: async (pluginId: string,- request: { taskId: string; requestKey: string; expectedRevision: number; text: string },+ request: { taskId: string; requestKey: string; expectedRevision: number; text: string; attachments?: PluginMessageAttachment[] },): Promise<PluginTaskRun> => completeOperation(async () => {+ let images: PluginMessageImage[];+ try { images = parsePluginMessageAttachments(request.attachments); }+ catch { throw new PluginTaskError('INVALID_ATTACHMENTS', 'Invalid message images'); }const prepared = await exclusive(async () => {const view = await ownTask(pluginId, request.taskId);- const fingerprint = hash([request.text, request.expectedRevision]);+ const fingerprint = hash(images.length+ ? [request.text, request.expectedRevision, images.map(({ hash, name }) => [hash, name])]+ : [request.text, request.expectedRevision]);const previous = replay(await deps.store.find(pluginId, 'send', request.taskId, request.requestKey),fingerprint,@@ -487,6 +495,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {prepared.run.taskId,prepared.run.inputMessageId,request.text,+ images,);if (!outcome.ok) failure = 'failed';} catch {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 82c56bbf41..93125e3ee5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -15,7 +15,9 @@ import { isSessionHiddenSync } from '../localDb/hiddenSessionRegistry.js';import { ghostDeclaresHiddenTasks } from '../../shared/ghost.js';import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';-import { showMobilePluginTaskPermission, setPluginTaskHandler, getPluginTaskSourceSessionId, setPluginTaskUninstaller, setPluginTaskRelocator, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';+import { showMobilePluginTaskPermission, setPluginTaskHandler, setPluginTargetAdapter, getPluginTaskSourceSessionId, setPluginTaskUninstaller, setPluginTaskRelocator, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';+import { listPluginTargetCandidates, resolvePluginTargetSession } from './pluginTargetCandidates.js';+import { collectPluginAttachmentPayloadTexts, withPluginMessageAttachments } from '../cindy-media/pluginMessageAttachments.js';import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';import { createHash as pluginTaskConfigHash } from 'node:crypto';import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';@@ -4322,7 +4324,7 @@ export async function withSessionInputStoppedForRewind<T>(* 内存队列,空集合语义正确。*/export function collectAgentInputQueueScanTexts(): string[] {- return agentInputCoordinatorHolder?.collectQueuedPayloadTexts() ?? [];+ return [...collectPluginAttachmentPayloadTexts(), ...(agentInputCoordinatorHolder?.collectQueuedPayloadTexts() ?? [])];}export interface AutomationUserTurnGitBaselineHooks {@@ -10811,6 +10813,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)targetSessionId?: string;message: string;persistedContent?: string;+ /** Host-managed images; attachment callers always use the durable queue. */+ files?: AgentInputQueuedMessage['files'];clientId?: string;dispatcherSessionId?: string;title?: string;@@ -11245,7 +11249,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Pending selections also need the canonical send transaction: it consumes the intent,// then refreshes queued createOpts from DB before starting the target harness.// enqueue does not await dispatch, so the drain can acquire this lock after we return.- if (params.forceQueue || explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith(BOT_GROUP_CLIENT_ID_PREFIX) || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId) || agentSwitchPending.get(targetSessionId)) {+ if (params.files?.length || params.forceQueue || explicitClientId?.startsWith('bot-dm:') || explicitClientId?.startsWith(BOT_GROUP_CLIENT_ID_PREFIX) || explicitClientId?.startsWith('bot-authorization-resume:') || inputCoordinator.shouldQueueNewTurn(targetSessionId) || agentSwitchPending.get(targetSessionId)) {lockStage = 'enqueue-queued-message';const qClientId = explicitClientId ?? createId();await enqueueSendToSessionMessage({@@ -11263,6 +11267,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)autoReviewUserText: params.autoReviewUserText,botTaskCoordination: params.botTaskCoordination,authorizationGuard: params.authorizationGuard,+ files: params.files,});return {ok: true as const,@@ -12841,14 +12846,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const revision = Number.parseInt(pluginTaskConfigHash('sha256').update(JSON.stringify([resolvedConfig, row.permissionMode, row.planModeEnabled, row.workingDir, row.status, row.orcaRole])).digest('hex').slice(0, 12), 16);return { taskId, title: row.title, status: row.status, revision, resolvedConfig, workingDir: row.workingDir ?? undefined, permissionMode: row.permissionMode, planModeEnabled: !!row.planModeEnabled, hidden: row.hiddenAt != null };},- dispatch: async (pluginId, taskId, clientId, text) => {+ dispatch: async (pluginId, taskId, clientId, text, images = []) => {assertPlugin(pluginId);// 插件来源只用于标签与 `[消息来源]` 说明;不新增 origin 类型,也不是权限判据。const pluginName = sanitizeSourceName(getInstalledGhostName(pluginId));- const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true, sourcePlugin: { pluginId, ...(pluginName ? { name: pluginName } : {}) }, onAccepted: async () => { assertPlugin(pluginId); await pluginTaskServiceForCurrentOwner!().assertDispatch(pluginId, taskId); assertPlugin(pluginId); } });- await awaitAgentInputQueueSnapshotPersistence(taskId);- assertCurrent();- return outcome;+ const validate = async () => { assertPlugin(pluginId); await pluginTaskServiceForCurrentOwner!().assertDispatch(pluginId, taskId); assertPlugin(pluginId); };+ return withPluginMessageAttachments(images, () => assertPlugin(pluginId), async files => {+ await validate();+ const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, files,+ autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true,+ sourcePlugin: { pluginId, ...(pluginName ? { name: pluginName } : {}) },+ authorizationGuard: { validate, assertCurrent: () => assertPlugin(pluginId) }, onAccepted: validate });+ await awaitAgentInputQueueSnapshotPersistence(taskId);+ assertCurrent();+ return outcome;+ });},inspect: async taskId => {assertCurrent(); await inputCoordinator.ensureQueueRestored(taskId); assertCurrent();@@ -13203,6 +13215,89 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}};setPluginTaskHandler(handlePluginTask);+ setPluginTargetAdapter({+ candidates: listPluginTargetCandidates,+ session: resolvePluginTargetSession,+ create: async (pluginId, project, taskId, title, route, guard) => {+ guard();+ const snapshot = getCurrentDbClientSnapshot();+ const config = readPluginTaskConfig(pluginId);+ const configSnapshot = JSON.stringify(config);+ const guardCreate = () => { guard(); if (JSON.stringify(readPluginTaskConfig(pluginId)) !== configSnapshot) throw new Error('STALE_REVISION'); };+ const execution = await resolveSessionExecution({ ...config, ...route });+ guardCreate();+ await createPluginTaskSession({ ghostId: pluginId, sessionId: taskId, title,+ ...execution, agentKind: execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind,+ permissionMode: clampPluginTaskPermissionMode(config.permissionMode), workingDir: project,+ shouldContinue: () => { guardCreate(); return getCurrentDbClientSnapshot() === snapshot; },+ notifySessionCreated: ({ sessionId, workdir }) => {+ notifyGhostSessionEvent('created', { sessionId, workdir }); broadcastSessionCreated(sessionId);+ },+ });+ },+ send: async (pluginId, taskId, clientId, text, guard, validateTarget, delivery, images = []) => {+ guard();+ const snapshot = getCurrentDbClientSnapshot();+ const assertCurrent = () => { guard(); if (snapshot !== getCurrentDbClientSnapshot()) throw new Error('PERMISSION_DENIED'); };+ const name = sanitizeSourceName(getInstalledGhostName(pluginId));+ const sourcePlugin = { pluginId, ...(name ? { name } : {}) };+ const validate = async () => { assertCurrent(); await validateTarget(); assertCurrent(); };+ await validate();+ return withPluginMessageAttachments(images, assertCurrent, async files => {+ if (delivery === 'steer') {+ const outcome = await withSendToSessionLock(taskId, async () => {+ await validate();+ await assertReviewExternalInputAllowed(taskId);+ const session = maker.getSession(taskId);+ if (!session?.isTurnRunning() || !session.capabilities.sameTurnSteer.supported) return 'not-attempted';+ const turnGeneration = session.getTurnGeneration();+ const meta = await maker.getSessionMeta(taskId);+ await validate();+ if (!meta) throw new Error('TARGET_UNAVAILABLE');+ const item = await buildSessionControlInputItem({ targetSessionId: taskId, clientId,+ message: text, persistedContent: text, meta, sourcePlugin, files,+ autoReviewUserText: { kind: 'delegated-continuation' },+ });+ await validate();+ return inputCoordinator.steerControlInput(taskId, { item }, {+ session, turnGeneration, beforeMutation: validate,+ });+ });+ if (outcome === 'steered') {+ await awaitAgentInputQueueSnapshotPersistence(taskId);+ return 'steer';+ }+ if (outcome === 'rejected') throw new Error('DELIVERY_REJECTED');+ // The coordinator owns ACK-uncertain input in a paused queue. Never enqueue a copy.+ if (outcome === 'queued') {+ await awaitAgentInputQueueSnapshotPersistence(taskId);+ throw new Error('DELIVERY_UNCERTAIN');+ }+ }+ const result = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, files,+ autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true,+ resumeWithStoredPermissionMode: true,+ sourcePlugin,+ authorizationGuard: { validate, assertCurrent },+ onAccepted: validate,+ });+ if (!result.ok) throw Object.assign(new Error(result.message), { code: result.errorCode });+ await awaitAgentInputQueueSnapshotPersistence(taskId);+ return 'queue';+ });+ },+ withdraw: async (taskId, clientId, guard) => {+ guard();+ await withdrawOwnedSessionInputs({ sessionId: taskId,+ queue: {+ ensureQueueRestored: async id => { await inputCoordinator.ensureQueueRestored(id); guard(); },+ getQueueControlSnapshot: id => inputCoordinator.getQueueControlSnapshot(id),+ remove: (id, inputId) => inputCoordinator.remove(id, inputId),+ },+ owns: id => { guard(); return id === clientId; }, flush: awaitAgentInputQueueSnapshotPersistence,+ });+ },+ });setPluginTaskUninstaller((pluginId, remove) => pluginTaskServiceForCurrentOwner!().withUninstall(pluginId, remove));setPluginTaskRelocator((from, to) => pluginTaskServiceForCurrentOwner!().relocatePlugin(from, to));@@ -13474,6 +13569,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)inheritTargetPlanMode?: boolean;message: string;persistedContent: string;+ files?: AgentInputQueuedMessage['files'];clientId: string;meta: NonNullable<Awaited<ReturnType<typeof maker.getSessionMeta>>>;dbRow: NonNullable<Awaited<ReturnType<typeof getSessionRowSnapshot>>>;@@ -16944,6 +17040,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)messageUuid?: string;userName?: string;signal?: AbortSignal;+ beforeProviderStart?: () => Promise<void>;/** coordinator 从队列项透传的手机来源(main 构造,非 wire 输入)。 */fromMobileClient?: boolean;uiLanguage?: string;@@ -17087,6 +17184,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}assertCurrentInputGeneration(sessionId, readExpectedInputGeneration(sendOpts));if (so[MCP_APP_MESSAGE_GUARD]) await so[MCP_APP_MESSAGE_GUARD]!();+ await so.beforeProviderStart?.();sess = readCurrentSteerSession();// 同轮插话也属于新输入。必须在 vendor await 前通知,旧轮可能先于 steer ack 结束。// 共用入口同时覆盖 INPUT_STEER、队列提升和旧 STEER IPC。@@ -17094,10 +17192,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// A channel route vouches only for its triggering sender; steered input ends that.noteInteractionRouteSteer(sess);await sess.steer(steerPayload as never, {- ...(so[MCP_APP_MESSAGE_GUARD] || appContext?.text ? {+ ...(so[MCP_APP_MESSAGE_GUARD] || so.beforeProviderStart || appContext?.text ? {beforeProviderStart: async () => {await so[MCP_APP_MESSAGE_GUARD]?.();await appContext?.assertCurrent();+ await so.beforeProviderStart?.();},} : {}),logTitle: meta?.title,diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex e36e5e462c..47cfbd28c5 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -67,6 +67,13 @@ contextBridge.exposeInMainWorld('cindy', {ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fs-request' }),library: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),+ targets: Object.fromEntries(['pick', 'get', 'send', 'cancel'].map(kind => [kind,+ async (req: Record<string, unknown> = {}): Promise<unknown> => {+ const result = await ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'targets-request', kind });+ if (result?.ok === true) return result.data;+ throw Object.assign(new Error(result?.error?.message ?? 'Target request failed'), { code: result?.error?.code ?? 'HOST_NOT_READY' });+ },+ ])),tasks: Object.fromEntries(['capabilities', 'models', 'setModel', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages', 'setHidden'].map(kind => [kind, async (req: Record<string, unknown> = {}): Promise<unknown> => {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex d63781eace..76a6e5ad02 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -726,6 +726,8 @@ const fanOutGhostBadge = createIpcFanOut('ghosts:badge');const fanOutGhostUnreadSnapshot = createIpcFanOut('ghosts:unread-snapshot');// 意识确认弹窗(confirm 槽:renderer 用主机同款 ConfirmDialog 弹,答案回 main)。// main 只投单个窗口(不广播),所以这里落地的窗口就是该弹框的唯一归属。+const fanOutGhostTargetPicker = createIpcFanOut('ghosts:target-picker');+const fanOutGhostTargetPickerDismiss = createIpcFanOut('ghosts:target-picker-dismiss');const fanOutGhostConfirmRequest = createIpcFanOut('ghosts:confirm-request');const fanOutForgeOidcInstallConfirmRequest = createIpcFanOut('forge-oidc-install:confirm-request');// 插件安装/更新确认(main 只投给发起安装的那个窗口;超时或取消时再发 dismissed 收起)。@@ -1425,6 +1427,10 @@ contextBridge.exposeInMainWorld('electronAPI', {onNotify: fanOutGhostNotify,onBadge: fanOutGhostBadge,onUnreadSnapshot: fanOutGhostUnreadSnapshot,+ onTargetPicker: fanOutGhostTargetPicker,+ onTargetPickerDismiss: fanOutGhostTargetPickerDismiss,+ resolveTargetPicker: (requestId: string, targetId: string | null): Promise<{ handled: boolean }> =>+ ipcRenderer.invoke('ghosts:target-picker:resolve', { requestId, targetId }),onConfirmRequest: fanOutGhostConfirmRequest,// 确认弹窗回包(confirm 槽):renderer 把用户的点击送回 main 结算那条挂起的// 管子请求。requestId 是 main 铸的,陌生/重复 id 由桥忽略。diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 60e68f5dcc..d4ce48d844 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -32,6 +32,7 @@ import { Tooltip } from '@/components/ui/tooltip';import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';+import { PluginTargetPickerHost } from '@/cindy-brain/PluginTargetPickerHost';import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';import { ForgeOidcInstallConfirmHost } from '@/cindy-brain/ForgeOidcInstallConfirmHost';import { GhostInstallConsentHost } from '@/cindy-brain/GhostInstallConsentHost';@@ -440,6 +441,7 @@ export function App() {内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口都挂、谁收到谁弹,不按窗口类型 gate。 */}<GhostConfirmDialogHost />+ <PluginTargetPickerHost /><ForgeOidcInstallConfirmHost /><GhostInstallConsentHost /><PluginPublisherConfirmHost />diff --git a/apps/desktop/src/renderer/cindy-brain/PluginTargetPickerHost.tsx b/apps/desktop/src/renderer/cindy-brain/PluginTargetPickerHost.tsxnew file mode 100644index 0000000000..985c5674e2--- /dev/null+++ b/apps/desktop/src/renderer/cindy-brain/PluginTargetPickerHost.tsx@@ -0,0 +1,119 @@+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';+import { Input } from '@/components/ui/input';+import type { PluginTargetPickerPush } from '../../shared/pluginTargets';++/** The host owns the list and selection; a plugin cannot impersonate this dialog. */+export function PluginTargetPickerHost() {+ const { t } = useTranslation();+ const [request, setRequest] = useState<+ (PluginTargetPickerPush & { ownerStamp: DataOwnerPushStamp }) | null+ >(null);+ const [query, setQuery] = useState('');+ const [selected, setSelected] = useState<string | null>(null);+ useEffect(() => {+ const off = window.electronAPI.ghosts.onTargetPicker((payload, ownerStamp) => {+ if (!isDataOwnerPushStampCurrent(ownerStamp)) return;+ setQuery('');+ setSelected(null);+ setRequest({ ...payload, ownerStamp });+ });+ const dismiss = window.electronAPI.ghosts.onTargetPickerDismiss((payload) => {+ setRequest((current) => (current?.requestId === payload.requestId ? null : current));+ });+ const auth = window.electronAPI.onAuthStateChange((state) => {+ setRequest((current) =>+ current &&+ state.dataOwnerId === current.ownerStamp.dataOwnerId &&+ state.ownerGeneration === current.ownerStamp.ownerGeneration+ ? current+ : null,+ );+ });+ return () => {+ off();+ dismiss();+ auth();+ };+ }, []);+ if (!request) return null;+ const finish = (id: string | null) => {+ // Hide before notifying main: subsequent desktop capture must not contain the picker.+ setRequest(null);+ if (!isDataOwnerPushStampCurrent(request.ownerStamp)) return;+ requestAnimationFrame(() =>+ requestAnimationFrame(() => {+ void window.electronAPI.ghosts.resolveTargetPicker(request.requestId, id).catch(() => {});+ }),+ );+ };+ const items = request.candidates.filter((item) =>+ `${item.label} ${item.detail}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()),+ );+ return (+ <ConfirmDialog+ open+ presentation="standard"+ cancelFirst+ maxWidth={520}+ title={t(`pluginTargetPicker.${request.kind}`)}+ description={t(+ request.persistent+ ? 'pluginTargetPicker.bindDescription'+ : 'pluginTargetPicker.onceDescription',+ { name: request.pluginName },+ )}+ confirmText={t(request.persistent ? 'pluginTargetPicker.bind' : 'pluginTargetPicker.choose')}+ cancelText={t('pluginTargetPicker.cancel')}+ confirmDisabled={!selected}+ onConfirm={() => finish(selected)}+ onCancel={() => finish(null)}+ onOpenChange={(open) => {+ if (!open) finish(null);+ }}+ content={+ <div className="flex min-w-0 flex-col gap-2">+ <Input+ autoFocus+ size="md"+ value={query}+ onChange={setQuery}+ placeholder={t('pluginTargetPicker.search')}+ aria-label={t('pluginTargetPicker.search')}+ />+ <div+ role="group"+ aria-label={t(`pluginTargetPicker.${request.kind}`)}+ className="flex flex-col gap-1"+ >+ {items.map((item) => (+ <button+ key={item.id}+ aria-pressed={selected === item.id}+ onClick={() => setSelected(item.id)}+ className={`min-w-0 rounded-lg border px-3 py-2 text-left ${selected === item.id ? 'border-[var(--text-secondary)] bg-[var(--surface-hover)]' : 'border-transparent hover:bg-[var(--surface-hover)]'}`}+ >+ <span className="block truncate text-13 font-medium text-[var(--text-primary)]">+ {item.label}+ </span>+ {item.detail && (+ <span className="block truncate text-12 text-[var(--text-tertiary)]">+ {item.detail}+ </span>+ )}+ </button>+ ))}+ {!items.length && (+ <p className="py-6 text-center text-13 text-[var(--text-tertiary)]">+ {t('pluginTargetPicker.empty')}+ </p>+ )}+ </div>+ </div>+ }+ />+ );+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex bb4d4f6553..3a22215864 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,4 +1,16 @@{+ "pluginTargetPicker": {+ "project": "Choose a project",+ "task": "Choose a task",+ "bot": "Choose a companion",+ "bindDescription": "Allow {{name}} to send to this fixed target in future.",+ "onceDescription": "Choose where {{name}} sends this time. This does not change its fixed binding.",+ "bind": "Use this target",+ "choose": "Choose Target",+ "cancel": "Cancel",+ "search": "Search by name or project",+ "empty": "No available targets"+ },"logSupport": {"title": "Logs and Feedback","localFiles": "Choose logs from the day of the problem. Review unredacted files before sharing.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 976fd8a1f7..36ce2a5029 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,4 +1,16 @@{+ "pluginTargetPicker": {+ "project": "プロジェクトを選択",+ "task": "タスクを選択",+ "bot": "パートナーを選択",+ "bindDescription": "{{name}} が今後この固定先に送信することを許可します。",+ "onceDescription": "{{name}} の今回の送信先を選択します。固定先は変更しません。",+ "bind": "この送信先に固定",+ "choose": "送信先を選択",+ "cancel": "キャンセル",+ "search": "名前やプロジェクトで検索",+ "empty": "利用可能な送信先がありません"+ },"logSupport": {"title": "ログとフィードバック","localFiles": "問題が発生した日のログを選択してください。未マスキングのため、共有前に内容を確認してください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 835180123e..26cf032887 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,4 +1,16 @@{+ "pluginTargetPicker": {+ "project": "프로젝트 선택",+ "task": "작업 선택",+ "bot": "파트너 선택",+ "bindDescription": "{{name}}이(가) 앞으로 이 고정 대상으로 전송하도록 허용합니다.",+ "onceDescription": "{{name}}의 이번 전송 대상을 선택합니다. 고정 대상은 변경되지 않습니다.",+ "bind": "이 대상으로 고정",+ "choose": "대상 선택",+ "cancel": "취소",+ "search": "이름 또는 프로젝트 검색",+ "empty": "사용 가능한 대상이 없습니다"+ },"logSupport": {"title": "로그 및 피드백","localFiles": "문제가 발생한 날짜의 로그를 선택하세요. 민감 정보가 가려지지 않았으므로 공유 전에 확인하세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 0d7485d008..6a31862489 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,4 +1,16 @@{+ "pluginTargetPicker": {+ "project": "选择项目",+ "task": "选择任务",+ "bot": "选择伙伴",+ "bindDescription": "允许 {{name}} 今后直接向这个固定目标投递。",+ "onceDescription": "选择 {{name}} 本次投递的位置,不会改写固定绑定。",+ "bind": "固定到这里",+ "choose": "选择目标",+ "cancel": "取消",+ "search": "搜索名称或项目",+ "empty": "没有可用目标"+ },"logSupport": {"title": "日志与反馈","localFiles": "选择问题当天的日志。文件未脱敏,请先检查。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex ecd0813bac..cda258fbe5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,4 +1,16 @@{+ "pluginTargetPicker": {+ "project": "選擇專案",+ "task": "選擇任務",+ "bot": "選擇夥伴",+ "bindDescription": "允許 {{name}} 今後直接向這個固定目標傳送。",+ "onceDescription": "選擇 {{name}} 本次傳送的位置,不會改寫固定綁定。",+ "bind": "固定到這裡",+ "choose": "選擇目標",+ "cancel": "取消",+ "search": "搜尋名稱或專案",+ "empty": "沒有可用目標"+ },"logSupport": {"title": "日誌與回饋","localFiles": "選擇問題當天的日誌。檔案未經去識別化處理,請先檢查。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex f62088b116..27231eca39 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1560,6 +1560,9 @@ interface ElectronAPI {/** confirm 槽:插件请求弹主机同款确认框(main 已资格审+净化+限速+单飞)。* main 只投单个窗口,所以收到即本窗口负责弹;答案用 resolveConfirm 回包。* confirmText/cancelText 为 null 时用 renderer 自己的缺省文案(跟语言走)。 */+ onTargetPicker: (callback: (payload: import('../shared/pluginTargets').PluginTargetPickerPush, ownerStamp: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void) => () => void;+ onTargetPickerDismiss: (callback: (payload: { requestId: string }) => void) => () => void;+ resolveTargetPicker: (requestId: string, targetId: string | null) => Promise<{ handled: boolean }>;onConfirmRequest: (callback: (payload: {requestId: string;diff --git a/apps/desktop/src/shared/pluginAttachments.ts b/apps/desktop/src/shared/pluginAttachments.tsnew file mode 100644index 0000000000..ff7ac013b4--- /dev/null+++ b/apps/desktop/src/shared/pluginAttachments.ts@@ -0,0 +1,25 @@+/** Images supplied by the plugin itself, never a Host path or an existing media URL. */+export interface PluginMessageAttachment {+ base64: string;+ name?: string;+}+export const PLUGIN_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024;+export function validPluginMessageAttachments(value: unknown): value is PluginMessageAttachment[] | undefined {+ if (value === undefined) return true;+ if (!Array.isArray(value) || value.length > 4) return false;+ let bytes = 0;+ for (const item of value) {+ if (!item || typeof item !== 'object' || Array.isArray(item)+ || Object.keys(item).some(key => !['base64', 'name'].includes(key))+ || typeof item.base64 !== 'string' || !item.base64.length+ || item.base64.length > Math.ceil(PLUGIN_ATTACHMENT_MAX_BYTES / 3) * 4+ || item.base64.length % 4 !== 0+ || !/^[A-Za-z0-9+/]*={0,2}$/.test(item.base64)+ || (item.name !== undefined && (typeof item.name !== 'string' || !item.name.trim()+ || item.name.length > 200 || item.name.includes('/') || item.name.includes('\\')+ || Array.from(item.name as string).some(char => char.charCodeAt(0) < 32)))) return false;+ bytes += item.base64.length / 4 * 3 - (item.base64.endsWith('==') ? 2 : item.base64.endsWith('=') ? 1 : 0);+ if (bytes > PLUGIN_ATTACHMENT_MAX_BYTES) return false;+ }+ return true;+}diff --git a/apps/desktop/src/shared/pluginTargets.ts b/apps/desktop/src/shared/pluginTargets.tsnew file mode 100644index 0000000000..6c9a239141--- /dev/null+++ b/apps/desktop/src/shared/pluginTargets.ts@@ -0,0 +1,37 @@+import type { PluginTaskRoute } from './pluginTasks.js';+import type { PluginMessageAttachment } from './pluginAttachments.js';++export type PluginTargetKind = 'project' | 'task' | 'bot';+export type PluginTargetDelivery = 'queue' | 'steer';+export interface PluginTargetView {+ bindingId: string;+ kind: PluginTargetKind;+ label: string;+}+/** Only sent to Cindy's trusted desktop renderer, never to a plugin. */+export interface PluginTargetCandidate {+ id: string;+ label: string;+ detail: string;+}+export interface PluginTargetPickerPush {+ requestId: string;+ pluginName: string;+ kind: PluginTargetKind;+ persistent: boolean;+ candidates: PluginTargetCandidate[];+}+export type PluginTargetRequest =+ | { kind: 'pick'; requestKey: string; targetKind: PluginTargetKind; persistent?: boolean }+ | { kind: 'get'; bindingId: string }+ | {+ kind: 'send';+ requestKey: string;+ bindingId: string;+ text: string;+ attachments?: PluginMessageAttachment[];+ title?: string;+ route?: PluginTaskRoute;+ delivery?: PluginTargetDelivery;+ }+ | { kind: 'cancel'; requestKey: string };diff --git a/apps/desktop/src/shared/pluginTasks.ts b/apps/desktop/src/shared/pluginTasks.tsindex ea42d51185..fb1b35b7a9 100644--- a/apps/desktop/src/shared/pluginTasks.ts+++ b/apps/desktop/src/shared/pluginTasks.ts@@ -1,3 +1,4 @@+import type { PluginMessageAttachment } from './pluginAttachments.js';/** Ordinary local Session API. No Bot/Orca identity or permission override is accepted. */export interface PluginTaskRoute {agentKind: 'cc' | 'codex' | 'pi';@@ -103,6 +104,7 @@ export type PluginTaskRequest = (requestKey: string;expectedRevision: number;text: string;+ attachments?: PluginMessageAttachment[];}| { type: 'tasks-request'; kind: 'getRun'; runId: string }| { type: 'tasks-request'; kind: 'listRuns'; taskId: string; after?: string; limit?: number }diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.mdindex 410441d498..51b84d4caf 100644--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@ -328,3 +328,38 @@ Pi 子代理未成功投递的自动 allow 再次投递前重走现有核验,`auto-review-context.test.ts`、Pi/Claude Code 审批接线回归以及 `eval-auto-approval.mts` 的`delegated-*` 正反对照(后者需要真实审阅模型,当前拆分 PR 未运行付费验证)。主机身份校验是确定性边界,动作与任务是否相符仍由 Auto 审阅,不宣称题目目录是系统沙箱。++## 用户选择的投递目标(增量接口,尚未发布)++`cindy.targets` 的作者契约见 `FORGE_GUIDE`,实现位于 `pluginTargetSlot.ts`、+`pluginTargetCandidates.ts` 和 `PluginTargetPickerHost.tsx`。保留 `cindy.tasks` 自有任务边界,+不把它的 get/list/send 放宽成任意任务权限。新入口复用 `agent.tasks` 的启用、批准和逻辑页身份校验,+还必须取得用户在宿主选择器里的具体目标选择;插件不能直接提交 taskId、botId 或项目路径作为授权。+不改变现存插件、旧任务 API、默认设置卡或 manifest 字段。++- 每次选择只产生临时句柄;固定选择落入 owner-scoped `plugin-targets.json`,只保存插件、目标标识和名称,不保存桌面内容或消息。+- `get` 将固定绑定换成本次短期句柄。发送消费临时句柄,相同请求共享同一 Promise,不能更换 requestKey 或正文使同一句柄重复创建/投递;Host 重启后句柄失效。未知结果由调用方保留为待检查,不自动重放。+- Picker 只投主窗口,绑定 webContents;回包必须来自受信宿主 Renderer。Owner stamp 在接收端校验,换账号清 UI;等待中还会复核原插件逻辑页、批准 revision 和 owner generation。+- 新项目任务沿用插件模型选择和受限的动手权限,使用现有 `createPluginTaskSession`;目录来自宿主已有项目列表。存量任务和伙伴保留其模型、权限、目录;伙伴只通过唯一 canonical 注册解析,不使用兼容镜像或伪造伙伴身份。+- `send` 的可选 `delivery` 为 `queue | steer`,缺省为 `queue`;project 仅接受 queue,新建任务不需要插话。delivery 参与请求幂等签名,缺省与显式 queue 等价,同键更换投递方式返回 REQUEST_KEY_CONFLICT。+- queue 走 `sendToSessionInternal` 与既有输入队列;steer 复用 `steerControlInput` 同轮注入,不停止或重启当前轮。空闲、框架不支持或当前输入边界不允许插话时走普通队列,保留 Stop/pause 边界。返回 `{taskId,accepted:true,delivery:'queue'|'steer'}`,delivery 表示实际接受路径,不表示 AI 已执行完成。+- main 盖 sourcePlugin 和 delegated-continuation 来源,沿用目标模型及权限。接受前、异步筛查后及 provider 派发前复核插件批准与目标。筛查拒绝返回 DELIVERY_REJECTED,不改走队列;ACK 未知保留宿主保护性暂停队列并返回 DELIVERY_UNCERTAIN,不再次排队。取消只按本插件 host-generated clientId 撤回排队输入,不停止整个会话或撤回已经接受的插话。+- 仅本机 Desktop,不新增 Mobile/device-link 透传,也不承诺跨平台原生触发。++此能力供声明了 `agent.tasks` 的插件使用;目标由用户选择,投递沿用既有插件授权和目标任务权限。+静态检查不等于设置 UI、取材、伙伴实际执行的联调验收;不得把 accepted 当成完成。++### 消息图片附件++`tasks.send` 与 `targets.send` 支持 `attachments?: Array<{base64:string,name?:string}>`。+插件先核对 `tasks.capabilities().messageAttachments`,无此能力时停止发送截图,不能静默丢图或回退文件路径。+只接受插件自己提供的字节;不接受 Host 路径、URL、其他会话的媒体 URI 或自报 MIME。+Host 校验规范 base64,嗅探 PNG/JPEG/WebP,最多 4 张、合计 20 MiB;附件字节指纹和名称参与幂等签名,回执不保存 base64。++`pluginMessageAttachments.ts` 复用 `ingestMedia` 和草稿/排队消息提交链路。入库前同步登记内容地址到现有回收器的活引用集合,+覆盖去重旧 blob 的入库、取消和派发在途窗口。调用方等待既有持久队列写入或插话落库后释放在途保护;+之后由内存队列、恢复快照和 `createMessage → commitMessageMediaRefs` 的会话附件引用保护。+失败或取消且未采用的图片不保留永久引用,由既有零引用缓冲与手动回收处理。无新目录、数据表、媒体协议或 media.deposit 授权。++queue 与 steer 都把托管 URL 写入 files、chatMessage.images 和持久消息信封;模型输入由既有附件装配器生成。+正文/附件来源仍是插件续行,不把截图变为新用户授权;目标、批准、owner 和取消闸保持不变。