Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mail): 补齐权限投影并解除附件服务循环依赖
Dash23985dd6e336
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex af62289111..cdd335b760 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1124,6 +1124,8 @@ import {} from './cindy-brain/index.js';import { installedGhostStoragePart } from '../shared/pluginIdentity.js';import { setCodexImageAuthBinding } from './cindy-brain/codexImageAuthBinding.js';+import { configureMailAttachmentHost } from './cindy-brain/mailAttachmentUpload.js';+import { writeTempFile, materializeDirectSendOssAttachments } from './maker-ipc/normalizeAttachments.js';import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-session-background-activity.js';import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';@@ -2470,6 +2472,7 @@ setCodexImageAuthBinding({getAuth: getChatgptBridgeAuth,onAuthFailure: invalidateChatgptBridgeAuth,});+configureMailAttachmentHost({ writeTempFile, materializeDirectSendOssAttachments });registerGhostIpc();registerPluginMarketIpc();registerPluginPublisherIpc();diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.tsindex a3e116a6bd..d62ad568c2 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts@@ -7,13 +7,12 @@ import { isDataOwnerBroadcastScopeCurrent, tapWindowBroadcast } from '../../deviimport { buildAttachmentOssRef } from '@cindy/device-link';import { renderMailCard } from '../mailCards';import { parseMailAttachmentUpload } from '../mailAttachmentUpload';-import { prepareMailAttachmentUpload } from '../mailAttachmentUpload';+import { configureMailAttachmentHost, prepareMailAttachmentUpload } from '../mailAttachmentUpload';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import { createHash } from 'node:crypto';const uploadFixture = vi.hoisted(() => ({ materialize: vi.fn() }));-vi.mock('../../maker-ipc/normalizeAttachments.js', () => ({ materializeDirectSendOssAttachments: uploadFixture.materialize }));const image = `cindy-media://blobs/${'b'.repeat(64)}.png`;const audio = `cindy-media://blobs/${'c'.repeat(64)}.mp3`;const request = { ref: { collectionId: 'plugin-results', kind: 'card', id: JSON.stringify(['s', 'c']) }, client: { protocolVersion: 1, primitives: [] } };@@ -28,6 +27,7 @@ it('mail imports reuse task attachment cleanup and verify downloaded bytes beforuploadFixture.materialize.mockResolvedValue({ message: { content: [{ type: 'file', path: file }] },cleanupAfterAcceptance: accepted, cleanupBeforeAcceptance: discard });const upload = { name: 'plan.pdf', url: buildAttachmentOssRef({ ossKey: 'fixture', size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }) };+ configureMailAttachmentHost({ writeTempFile: vi.fn(), materializeDirectSendOssAttachments: uploadFixture.materialize });const result = await prepareMailAttachmentUpload(upload, 'task');expect(uploadFixture.materialize).toHaveBeenCalledWith('task', expect.objectContaining({ type: 'user' }), {});expect(result.attachment).toMatchObject({ path: file, filename: 'plan.pdf', bytes: bytes.length });diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 02fe8d308b..499bd7bb29 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -335,7 +335,6 @@ import { GhostPipeDispatcher } from './pipeDispatcher.js';import { GhostCardService, parseCardHeightReport } from './cardService.js';import { MailCardService } from './mailCards.js';import { prepareMailAttachmentSelection, prepareMailAttachmentUpload } from './mailAttachmentUpload.js';-import { writeTempFile } from '../maker-ipc/normalizeAttachments.js';import { GhostCardActionDispatcher } from './cardActionDispatch.js';import { GhostSessionActivityTracker } from './ghostSessionActivity.js';import { sanitizeGhostCardHtml } from './cardSanitizer.js';@@ -2359,7 +2358,7 @@ export function getGhostCardActionDispatcher(): GhostCardActionDispatcher {const result = await dialog.showOpenDialog({ properties: ['openFile'],...(inline ? { filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] }] } : {}) });if (result.canceled || !result.filePaths[0]) return null;- return prepareMailAttachmentSelection(result.filePaths[0], sessionId, inline, writeTempFile);+ return prepareMailAttachmentSelection(result.filePaths[0], sessionId, inline);},prepareMailUpload: prepareMailAttachmentUpload,// 呼吸起点:点击成功投递即把该会话标为"意识活动中"(结束由 card-updatediff --git a/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts b/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.tsindex 44673a012c..f0eb2d4efb 100644--- a/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts+++ b/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts@@ -3,7 +3,19 @@ import { constants } from 'node:fs';import path from 'node:path';import { createHash, randomUUID } from 'node:crypto';import { parseAttachmentOssRef, parsePeerAttachmentRef } from '@cindy/device-link';-import type { writeTempFile } from '../maker-ipc/normalizeAttachments.js';+import type { writeTempFile, materializeDirectSendOssAttachments } from '../maker-ipc/normalizeAttachments.js';++interface MailAttachmentHost {+ writeTempFile: typeof writeTempFile;+ materializeDirectSendOssAttachments: typeof materializeDirectSendOssAttachments;+}+let attachmentHost: MailAttachmentHost | undefined;+/** Main bootstrap owns assembly; importing the plugin runtime must not load maker-ipc. */+export function configureMailAttachmentHost(host: MailAttachmentHost): void { attachmentHost = host; }+function requireAttachmentHost(): MailAttachmentHost {+ if (!attachmentHost) throw new Error('MAIL_ATTACHMENT_HOST_NOT_READY');+ return attachmentHost;+}const parseUploadRef = (url: string) => parsePeerAttachmentRef(url) || parseAttachmentOssRef(url);@@ -17,7 +29,7 @@ export interface PreparedMailAttachment {/** Snapshot the selected bytes into the existing session-owned temporary store.* The sandbox/Node adapter never receives the user's source path or rereads it. */-export async function prepareMailAttachmentSelection(filePath: string, sessionId: string, inline: boolean, writeSnapshot: typeof writeTempFile): Promise<PreparedMailAttachment> {+export async function prepareMailAttachmentSelection(filePath: string, sessionId: string, inline: boolean, writeSnapshot = requireAttachmentHost().writeTempFile): Promise<PreparedMailAttachment> {const handle = await fs.open(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));let bytes: Buffer;try {@@ -48,12 +60,11 @@ export function parseMailAttachmentUpload(value: unknown): MailAttachmentUpload/** Reuse task attachment materialization and its owner/session cleanup. Never* accept a phone-supplied desktop path, or create a second upload store. */-export async function prepareMailAttachmentUpload(input: MailAttachmentUpload, sessionId: string): Promise<PreparedMailAttachment> {+export async function prepareMailAttachmentUpload(input: MailAttachmentUpload, sessionId: string, materialize = requireAttachmentHost().materializeDirectSendOssAttachments): Promise<PreparedMailAttachment> {const upload = parseMailAttachmentUpload(input);if (!upload) throw new Error('INVALID_MAIL_ATTACHMENT');const ref = parseUploadRef(upload.url)!;- const { materializeDirectSendOssAttachments } = await import('../maker-ipc/normalizeAttachments.js');- const staged = await materializeDirectSendOssAttachments(sessionId, {+ const staged = await materialize(sessionId, {type: 'user', content: [{ type: 'file', path: upload.url, name: upload.name, mimeType: ref.mimeType }],}, {});const discard = async () => { await staged.cleanupBeforeAcceptance?.(); };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.tsindex ef2569466e..960a699285 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts@@ -44,7 +44,7 @@ import * as cindyMediaBlobStore from '../../cindy-media/blobStore.js';import { ingestMedia } from '../../cindy-media/ingest.js';import { downloadToFile, removeRemote } from '../../device-link/mediaTransfer.js';import { buildAttachmentOssRef } from '../../../shared/attachmentOssRef.js';-import { prepareMailAttachmentSelection } from '../../cindy-brain/mailAttachmentUpload.js';+import { configureMailAttachmentHost, prepareMailAttachmentSelection } from '../../cindy-brain/mailAttachmentUpload.js';const tempDirs: string[] = [];@@ -52,6 +52,7 @@ beforeEach(async () => {vi.clearAllMocks();tempRoot.value = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-review-inline-test-'));tempDirs.push(tempRoot.value);+ configureMailAttachmentHost({ writeTempFile, materializeDirectSendOssAttachments });configureTempAttachmentOwner({instanceId: 'normalize-attachments-test-owner',processId: process.pid,@@ -71,7 +72,7 @@ describe('inline attachment temporary files', () => {const source = path.join(tempRoot.value, 'personal-name.txt');for (const inline of [false, true]) {await fs.writeFile(source, 'selected');- const staged = await prepareMailAttachmentSelection(source, 'mail-selection', inline, writeTempFile);+ const staged = await prepareMailAttachmentSelection(source, 'mail-selection', inline);expect(staged.attachment.filename).toBe('personal-name.txt');expect(staged.attachment.path).not.toBe(source);expect(staged.attachment.path).not.toContain('personal-name');diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 30b0661185..7ae33a63f3 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6565,6 +6565,11 @@"unknownReviewerDetail": "The package claims a review, but this Cindy version does not recognize the reviewer key, so it is not shown as reviewed."},"perm": {+ "mail": "Use mail drafts and send cards",+ "mailDetail": "Edit and sync drafts in a card, with confirmation and an undo countdown before sending.",+ "mailReader": "View mail in the app",+ "mailReaderHost": "Open mail links from {{host}} in the app",+ "mailMarkRead": "Mark messages as read when opened","grantsTitle": "After installing it will have:","toolsGroup": "Registered Tools","toolsDiffGroup": "Registered Tool Changes",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 65ae147c94..201f0360e1 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6534,6 +6534,11 @@"unknownReviewerDetail": "審査情報はありますが、現在の Cindy は審査キーを認識していないため、審査済みとは表示しません。"},"perm": {+ "mail": "メールの下書き・送信カードを使用",+ "mailDetail": "カードで下書きを編集・同期し、送信前に確認と取り消しカウントダウンを表示します。",+ "mailReader": "アプリ内でメールを表示",+ "mailReaderHost": "{{host}} のメールリンクをアプリ内で開く",+ "mailMarkRead": "開いたメールを既読にする","grantsTitle": "インストール後に持つ権限:","toolsGroup": "登録ツール","toolsDiffGroup": "登録ツールの変更",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 26905236f3..26114e50db 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6534,6 +6534,11 @@"unknownReviewerDetail": "검토 정보가 있지만 현재 Cindy가 검토 키를 알지 못하므로 검토 완료로 표시하지 않습니다."},"perm": {+ "mail": "메일 초안 및 전송 카드 사용",+ "mailDetail": "카드에서 초안을 편집하고 동기화하며, 전송 전에 확인 및 실행 취소 카운트다운을 표시합니다.",+ "mailReader": "앱에서 메일 보기",+ "mailReaderHost": "{{host}}의 메일 링크를 앱에서 열기",+ "mailMarkRead": "메일을 열면 읽음으로 표시","grantsTitle": "설치 후 갖게 되는 권한:","toolsGroup": "등록 도구","toolsDiffGroup": "등록 도구 변경",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 6b3f83983c..715c9edcff 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6534,6 +6534,11 @@"unknownReviewerDetail": "包里带有审核声明,但当前 Cindy 不认识这把审核公钥,因此不会显示为已审核。"},"perm": {+ "mail": "使用邮件草稿与发送卡片",+ "mailDetail": "可在卡片中编辑和同步草稿,并在发送前提供确认和撤销倒计时。",+ "mailReader": "在应用内查看邮件",+ "mailReaderHost": "在应用内打开 {{host}} 的邮件链接",+ "mailMarkRead": "打开邮件时可将其标记为已读","grantsTitle": "安装后它将拥有:","toolsGroup": "注册工具","toolsDiffGroup": "注册工具变化",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex d5d69516d0..d4e029da1a 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6534,6 +6534,11 @@"unknownReviewerDetail": "包裡帶有稽核宣告,但當前 Cindy 不認識這把稽核公鑰,因此不會顯示為已稽核。"},"perm": {+ "mail": "使用郵件草稿與傳送卡片",+ "mailDetail": "可在卡片中編輯和同步草稿,並在傳送前提供確認與撤銷倒數。",+ "mailReader": "在應用程式內查看郵件",+ "mailReaderHost": "在應用程式內開啟 {{host}} 的郵件連結",+ "mailMarkRead": "開啟郵件時可將其標記為已讀","grantsTitle": "安裝後它將擁有:","toolsGroup": "註冊工具","toolsDiffGroup": "註冊工具變化",diff --git a/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.ts b/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.tsindex fa95160c45..92874bf987 100644--- a/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.ts+++ b/apps/desktop/src/shared/__tests__/ghostInstallConsent.test.ts@@ -51,6 +51,40 @@ describe('plugin install consent', () => {expect(ghostUpdateNeedsConsent(current, manifest({ version: '1.1.0' }))).toBe(false);});+ // Unit regression for #6404: an existing tool must not hide new mailbox+ // capabilities from the production install/update consent boundary.+ it('projects mail, reader hosts and read-state writes into install and update consent', () => {+ const base = manifest();+ const compose = manifest({ mail: true });+ const reader = manifest({ mail: true, mailReader: { tool: 'forecast', hosts: ['mail.example.test'] } });+ const full = manifest({ mail: true, mailReader: { tool: 'forecast', hosts: ['mail.example.test'], markRead: true } });+ const additions = (previous: GhostManifest, next: GhostManifest) => {+ const facts = evaluateGhostInstallConsent(installed(previous), next);+ expect(facts?.kind).toBe('update');+ if (facts?.kind !== 'update') throw new Error('expected update facts');+ return facts.added.map(item => item.key);+ };+ expect(additions(base, compose)).toEqual(['mail']);+ expect(additions(compose, reader)).toEqual(['mail-reader:forecast', 'mail-reader:host:mail.example.test']);+ expect(additions(reader, full)).toEqual(['mail-reader:mark-read']);+ expect(additions(reader, manifest({ mail: true,+ tools: [{ name: 'forecast', description: 'Read the forecast' }, { name: 'reader', description: 'Read mail' }],+ mailReader: { tool: 'reader', hosts: ['mail.example.test'] },+ }))).toEqual(['mail-reader:reader']);+ const facts = evaluateGhostInstallConsent(null, full);+ if (facts?.kind !== 'install') throw new Error('expected install facts');+ expect(facts.permissions.map(item => item.key)).toEqual(expect.arrayContaining([+ 'mail', 'mail-reader:forecast', 'mail-reader:host:mail.example.test', 'mail-reader:mark-read',+ ]));+ const reordered = manifest({ mail: true, mailReader: { tool: 'forecast', hosts: ['other.example.test', 'mail.example.test'] } });+ expect(additions(reader, reordered)).toEqual(['mail-reader:host:other.example.test']);+ expect(evaluateGhostInstallConsent(installed(reordered), manifest({ mail: true,+ mailReader: { tool: 'forecast', hosts: ['mail.example.test', 'other.example.test', 'mail.example.test'] },+ }))).toBeNull();+ expect(evaluateGhostInstallConsent(installed(full), reader)).toBeNull();+ expect(evaluateGhostInstallConsent(installed(full), base)).toBeNull();+ });+it('keeps an update silent when it only removes permissions or changes tools', () => {const current = installed(manifest({ network: { hosts: ['api.weather.test', 'maps.weather.test'] } }));expect(evaluateGhostInstallConsent(current, manifest({ version: '1.1.0' }))).toBeNull();diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 41726db29f..976e898873 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -2329,6 +2329,20 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt});}}+ if (manifest.mail === true) {+ items.push({ key: 'mail', kind: 'card', labelKey: 'mail', detailKey: 'mailDetail' });+ const reader = parseMailReader(manifest.mailReader);+ if (reader) {+ items.push({ key: `mail-reader:${reader.tool}`, kind: 'card', labelKey: 'mailReader' });+ for (const host of reader.hosts) {+ items.push({ key: `mail-reader:host:${host}`, kind: 'preview',+ labelKey: 'mailReaderHost', labelArgs: { host } });+ }+ if (reader.markRead === true) {+ items.push({ key: 'mail-reader:mark-read', kind: 'card', labelKey: 'mailMarkRead' });+ }+ }+ }if (manifest.notify === true) {items.push({ key: 'notify', kind: 'notify', labelKey: 'notify', detailKey: 'notifyDetail' });}diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 430e9d2218..1107ddaec8 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -223,6 +223,9 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开全部条目。首次安装展示全部权限并确认;更新相对当前已装版本按 `diffInstalledGhostPermissionItems`比较,新增条目、同 key 条目内容变化或内置 OAuth 客户端变化才算权限变多,只删除不算;已装版本没有有效批准基线时按全部权限新增处理。+ 邮件的 `mail`、`mailReader.tool`、逐个 reader host 和 `markRead: true` 分别进入权限投影;+ 复用既有工具也不能隐藏新增邮件能力。域名重排/去重不算扩权,只移除邮件能力不要求确认。+ 同一投影用于插件详情、首装与更新确认;不新增批准记录或要求存量插件重新配置。- 入口与确认界面:插件页、拖入、双击 `.cindy` 与设置页导入由发起窗口弹确认框(`GhostInstallConsentWindowBridge` → `GhostInstallConsentHost`,只投给、也只接受发起安装的那个 webContents);Agent 调用 `ghost_market_install`/`ghost_forge_install` 不论任务权限档diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex dbde9e6609..fc068146da 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -2448,6 +2448,10 @@ Mail providers may declare `mailReader: { tool, hosts }` alongside `mail: true`.reject a reader without `mail: true` or without its matching tool in `tools`.Desktop and plugin-protocol validate this known declaration and retain futureextension data; malformed declarations cannot survive as unknown top-level fields.+Install/detail permission projection includes `mail`, the reader tool, individual+reader hosts and optional read-state writes; adding any of them requires the existing+update consent even when the tool was already registered. Reordering/deduplicating+hosts or removing capabilities does not expand permissions.The tool must be declared and read-only by default. Cindy matches exact HTTPS hostsand calls it with `{ url }`; the provider resolves the account and message withoutmarking read or mutating drafts. Providers may opt in with `mailReader.markRead: true`