Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mail): enforce native read intent and validate embedded image URLs

Dash1084336035ae
diff --cc apps/desktop/scripts/mailComposeRuntime.test.mjs
index d2df277082,0000000000..407c5f72d1
mode 100644,000000..100644
--- a/apps/desktop/scripts/mailComposeRuntime.test.mjs
+++ b/apps/desktop/scripts/mailComposeRuntime.test.mjs
@@@ -1,892 -1,0 +1,927 @@@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import { URL } from "node:url";
+import { webcrypto } from "node:crypto";
+import { createContext, runInContext } from "node:vm";
+import { test } from "vitest";
+import { JSDOM } from 'jsdom';
+import { isSyntheticTriggerText, syntheticTriggerKind } from "@cindy/maker-shared/synthetic-trigger";
+
+const source = fs.readFileSync(new URL("../src/main/cindy-brain/runtime/mailComposeRuntime.js", import.meta.url), "utf8");
+const copy = (value) => JSON.parse(JSON.stringify(value));
+const { DOMParser } = new JSDOM('').window;
+
+// Behavioral adapter contract, not real-provider integration. Exercise three
+// different identity/receipt shapes through the same production flow.
+function fixture({
+ providerName = "QQ 邮箱",
+ draftStorage = "server",
+ shape = "imap",
+ write,
+ read,
+ remove,
+ supportsDelete = true,
+ autoSend = true,
+ acceptCard = true,
+ richText = false,
+ allowCardRead = true,
+} = {}) {
+ let kv = {},
+ revision = 1,
+ timerId = 0,
+ clock = 100000,
+ flow;
+ const cards = [],
+ continuations = [],
+ writes = [],
+ reads = [],
+ deletes = [],
+ timers = new Map(),
+ locks = new Map();
+ let current = {
+ status: "read_back",
+ draftId: "logical-draft",
+ fingerprint: "revision-1",
+ locator:
+ shape === "imap"
+ ? { folder: "草稿箱", uid: 42, uidValidity: "700" }
+ : { id: "native-draft" },
+ headers: {
+ from: "[email protected]",
+ to: "David <[email protected]>",
+ cc: "",
+ bcc: "",
+ subject: "Meeting",
+ },
+ editor: { editable: true, body: "Original", quote: "", ...(richText ? { format: 'html', bodyHtml: '<p style="color:red">Original</p>', quoteHtml: '' } : {}) },
+ attachments: [],
+ };
+ const account = {
+ ok: true,
+ accountId: "account-a",
+ accountEmail: "[email protected]",
+ };
+ const context = createContext({
+ DOMParser,
+ crypto: webcrypto,
+ TextEncoder,
+ Date: class extends Date { static now() { return clock; } },
+ setTimeout(fn, delay) {
+ const id = ++timerId;
+ if (delay === 10000 && autoSend) queueMicrotask(fn);
+ else timers.set(id, { fn, at: clock + delay });
+ return id;
+ },
+ clearTimeout(id) {
+ timers.delete(id);
+ },
+ navigator: {
+ locks: {
+ request(name, fn) {
+ const next = (locks.get(name) || Promise.resolve()).then(fn);
+ locks.set(
+ name,
+ next.catch(() => {}),
+ );
+ return next;
+ },
+ },
+ },
+ async fetch(url, options = {}) {
+ if (url === "/app-context")
+ return {
+ ok: true,
+ json: async () => ({ context: { locale: "zh-CN" } }),
+ };
+ assert.equal(url, "/kv");
+ if (options.method === "PUT") kv = JSON.parse(options.body);
+ return { ok: true, json: async () => copy(kv) };
+ },
+ cindy: {
+ onHostMessage() {},
+ async send(card) {
+ if (card.type === 'mail-draft-read') {
+ const stored = cards.findLast(c => c.draft && c.callId === card.callId);
+ if (!stored || !allowCardRead) return { ok: false };
+ const draft = copy(stored.draft);
+ // Host persists status-only patches as part of the same card.
+ for (const update of cards.slice(cards.indexOf(stored) + 1)) {
+ if (update.callId === card.callId && update.statusOnly) Object.assign(draft, copy(update.statusOnly));
+ }
+ return { ok: true, draft };
+ }
+ cards.push(copy(card));
+ return { ok: acceptCard || !card.statusOnly?.pendingSend };
+ },
+ agent: {
+ async run(event) {
+ continuations.push(copy(event));
+ return { ok: true };
+ },
+ },
+ },
+ });
+ runInContext(source, context);
+ const adapter = {
+ providerName,
+ draftStorage,
+ richText,
+ ...(supportsDelete ? { async deleteDraft(request) {
+ deletes.push(copy(request));
+ assert.deepEqual(copy(request.record.locator), current.locator);
+ return remove ? remove(request) : { ok: true, data: { deleted: true, draftId: current.draftId } };
+ } } : {}),
+ async selectAccount(id) {
+ return id === account.accountId
+ ? account
+ : { ok: false, message: "账号不存在" };
+ },
+ async readDraft({ record, sourceCallId }) {
+ reads.push({ record: copy(record), sourceCallId });
+ if (read) {
+ const result = await read();
+ if (result) return result;
+ }
+ return { ok: true, data: { readBack: copy(current) } };
+ },
+ async writeDraft(request) {
+ writes.push(copy(request));
+ if (write) {
+ const result = await write(request, writes.length);
+ if (result) return result;
+ }
+ if (request.record.fingerprint !== current.fingerprint)
+ return { ok: false, execution: 'not_executed', stale: copy(current), message: 'Changed' };
+ assert.deepEqual(copy(request.record.locator), current.locator);
+ assert.equal(request.record.fingerprint, current.fingerprint);
+ if (request.send)
+ return {
+ ok: true,
+ data: {
+ sent: true,
+ receipt:
+ shape === "graph"
+ ? { accepted: true, delivery_confirmed: false, status: 202 }
+ : {
+ message_id: "<[email protected]>",
+ accepted: ["[email protected]"],
+ rejected: [],
+ },
+ },
+ };
+ current = {
+ ...current,
+ fingerprint: "revision-" + ++revision,
+ locator:
+ shape === "imap"
+ ? { ...current.locator, uid: current.locator.uid + 1 }
+ : current.locator,
+ headers: {
+ ...current.headers,
+ ...Object.fromEntries(
+ ["to", "cc", "bcc", "subject"].map((name) => [
+ name,
+ request.fields[name],
+ ]),
+ ),
+ },
+ editor: {
+ ...current.editor,
+ body: request.fields.body,
+ quote: request.fields.quote,
+ ...(richText ? { bodyHtml: request.fields.bodyHtml, quoteHtml: request.fields.quoteHtml } : {}),
+ },
+ ...(richText ? { attachments: JSON.parse(request.fields.attachmentItems) } : {}),
+ };
+ return { ok: true, data: { readBack: copy(current) } };
+ },
+ };
+ function restart() {
+ timers.clear();
+ flow = context.cindyMail.register(adapter);
+ }
+ restart();
+ const values = () => ({
+ to: current.headers.to,
+ cc: current.headers.cc,
+ bcc: current.headers.bcc,
+ subject: current.headers.subject,
+ body: current.editor.body,
+ quote: current.editor.quote,
+ ...(richText ? { bodyHtml: current.editor.bodyHtml, quoteHtml: current.editor.quoteHtml, attachmentItems: JSON.stringify(current.attachments) } : {}),
+ });
+ const action = (operation) => {
+ const card = cards.findLast((card) => card.draft);
+ return `mail:${operation}:${card.draft.key}`;
+ };
+ return {
+ cards,
+ continuations,
+ writes,
+ reads,
+ deletes,
+ values,
+ action,
+ restart,
+ current: () => copy(current),
+ kv: () => copy(kv),
+ relocate: () => {
+ current.locator = { ...current.locator, uid: current.locator.uid + 10 };
+ },
+ externalEdit: (fields = {}) => {
+ current.fingerprint = 'external-' + ++revision;
+ for (const [name, value] of Object.entries(fields)) {
+ if (name === 'attachments') current.attachments = value;
+ else if (name in current.headers) current.headers[name] = value;
+ else current.editor[name] = value;
+ }
+ },
+ present: () =>
+ flow.present({ callId: "card-call" }, account, copy(current)),
+ tool: (operation, extra = {}) =>
+ flow.beforeTool({
+ operation,
+ account: account.accountId,
+ draftId: current.draftId,
+ readOnly: false,
+ sourceCallId: "agent-call",
+ ...extra,
+ }),
+ resolve: () => flow.resolveDraft(account.accountId, current.draftId),
+ card: (operation, fields = values(), extra = {}) =>
+ flow.handleCard({
+ actionId: action(operation),
+ callId: "card-call",
+ userActionToken: "host-click-token",
+ formChange: operation === "change",
+ formValues: fields,
+ ...extra,
+ }),
+ waitCountdown: async () => {
+ for (let i = 0; i < 300 && ![...timers.values()].some(t => t.at === clock + 10000); i++) await Promise.resolve();
+ assert.ok([...timers.values()].some(t => t.at === clock + 10000), "countdown armed");
+ },
+ advance: async (ms) => {
+ clock += ms;
+ for (const [id, timer] of [...timers]) if (timer.at <= clock) { timers.delete(id); await timer.fn(); }
+ },
+ flush: async () => {
+ for (const [id, timer] of [...timers]) {
+ timers.delete(id);
+ await timer.fn();
+ }
+ },
+ };
+}
+
+// Reading before an AI edit must not publish the old mail at the new tool call.
+// The saved revision is presented only after the provider update completes.
+for (const providerName of ['Gmail', 'QQ 邮箱']) test(providerName + ': unchanged reads keep the existing card until an update is ready', async () => {
+ const f = fixture({ providerName, richText: true });
+ await f.present();
+ const key = f.cards.at(-1).draft.key;
+ const read = await f.tool('get');
+ assert.equal(read.data.readBack.editor.body, 'Original');
+ assert.equal(f.cards.length, 1);
+ assert.equal(await f.tool('update'), null);
+ assert.equal(f.cards.length, 1);
+ f.externalEdit({ body: 'Updated text', bodyHtml: '', format: 'text' });
+ await f.present();
+ assert.equal(f.cards.length, 2);
+ assert.notEqual(f.cards.at(-1).draft.key, key);
+ assert.equal(f.cards.at(-1).draft.fields.find(f => f.name === 'body').value, 'Updated text');
+ assert.equal(f.writes.length, 0);
+});
+test('a draft read in another task still presents its own card', async () => {
+ const f = fixture({ allowCardRead: false });
+ await f.present();
+ await f.tool('get');
+ assert.equal(f.cards.length, 2);
+ assert.equal(f.cards.at(-1).callId, 'agent-call');
+});
+
+// The plain quote editor and HTML MIME alternative must describe the same reply.
+for (const quote of ['Updated <quote>\nSecond line', '']) test('editing the plain quote updates or clears its HTML alternative: ' + JSON.stringify(quote), async () => {
+ const f = fixture({ richText: true });
+ f.externalEdit({ quote: 'Original quote', quoteHtml: '<blockquote><b>Original quote</b></blockquote>' });
+ await f.present();
+ const values = f.values();
+ await f.card('change', { ...values, quote: 'Intermediate' });
+ await f.card('change', { ...values, quote });
+ assert.ok((await f.tool('send')).ok);
+ const sent = f.writes.find(x => x.send).fields;
+ assert.equal(sent.quote, quote);
+ assert.equal(sent.quoteHtml, quote ? '<div>Updated &lt;quote&gt;<br>Second line</div>' : '');
+});
+test('editing other fields preserves authored HTML quotes byte for byte', async () => {
+ const f = fixture({ richText: true });
+ const quoteHtml = '<blockquote style="color:red"><b>Original quote</b></blockquote>';
+ f.externalEdit({ quote: 'Original quote', quoteHtml });
+ await f.present();
+ await f.card('change', { ...f.values(), subject: 'New subject' });
+ assert.ok((await f.tool('send')).ok);
+ assert.equal(f.writes.find(x => x.send).fields.quoteHtml, quoteHtml);
+});
+
+// Regression: the real sent reply nested a full HTML document inside its quote.
+// Existing adapter tests covered edits, not outgoing HTML structure or CID integrity.
+// Unit tier: production present/send entries, fake providers, no network or real sends.
+for (const providerName of ['Gmail', 'QQ 邮箱']) test(providerName + ': shared formatting repairs quoted documents before preview/save/send', async () => {
+ const f = fixture({ providerName, richText: true });
+ f.externalEdit({
+ quote: '\nOriginal message',
+ quoteHtml: '<br><br><div class="gmail_quote"><div>Sender wrote:</div><blockquote><!doctype html><html lang="zh-CN"><head><meta charset="utf-8"></head><body style="font-family:Georgia;background:#eee"><table width="600"><tr><td><img src="cid:card@test" width="544">原文</td></tr></table></body></html></blockquote></div>',
+ attachments: [{ key: 'image-key', filename: 'image-1', mimeType: 'image/png', bytes: 123, contentId: 'card@test' }],
+ });
+ await f.present();
+ const shown = Object.fromEntries(f.cards.findLast(c => c.draft).draft.fields.map(x => [x.name, x.value]));
+ assert.doesNotMatch(shown.quoteHtml, /<!doctype|<\/?(?:html|head|body)\b/i);
+ const doc = new DOMParser().parseFromString(shown.quoteHtml, 'text/html');
+ assert.equal(doc.querySelector('blockquote [style]')?.style.fontFamily, 'Georgia');
+ assert.equal(doc.querySelector('img')?.getAttribute('src'), 'cid:card@test');
+ assert.equal(doc.querySelector('table')?.getAttribute('width'), '600');
+ assert.equal(JSON.parse(shown.attachmentItems)[0].filename, 'image-1.png');
+ assert.ok((await f.tool('send')).ok);
+ assert.equal(f.writes.filter(x => !x.send).length, 1);
+ assert.equal(f.writes.find(x => x.send).fields.quoteHtml, shown.quoteHtml);
+ assert.equal(f.current().editor.quoteHtml, shown.quoteHtml);
+});
+
+test('shared send blocks broken inline images and permits an explicit correction', async () => {
+ const f = fixture({ richText: true });
+ f.externalEdit({ bodyHtml: '<p>Hello<img src="cid:missing@test"></p>' });
+ await f.present();
+ const blocked = await f.tool('send');
+ assert.equal(blocked.ok, false);
+ assert.equal(blocked.execution, 'not_executed');
+ assert.equal(f.writes.length, 0);
+ // The assistant can correct the draft instead of being stuck behind validation.
+ assert.equal(await f.tool('update'), null);
+ await f.card('change', { ...f.values(), bodyHtml: '<p>Hello</p>' });
+ assert.ok((await f.tool('send')).ok);
+});
+
+test('shared formatting derives missing plain text and replaces a preview URL with its attachment CID', async () => {
+ const f = fixture({ richText: true });
+ f.externalEdit({ body: '', bodyHtml: '<html><body style="color:red"><p>Hello</p><p>World<img src="cindy-media://image"></p></body></html>',
+ attachments: [{ key: 'image', filename: 'photo.png', mimeType: 'image/png', bytes: 123, contentId: 'photo@test', previewUrl: 'cindy-media://image' }] });
+ await f.present();
+ assert.ok((await f.tool('send')).ok);
+ const sent = f.writes.find(x => x.send).fields;
+ assert.match(sent.body, /Hello\n+World/);
+ assert.match(sent.bodyHtml, /src="cid:photo@test"/);
+ assert.doesNotMatch(sent.bodyHtml, /cindy-media:/);
+});
+
++// #6404: src/background/inline-style tests missed stylesheet and srcset paths.
++// Production tool/card send entries must inspect body and quote using one policy.
++for (const name of ['bodyHtml', 'quoteHtml']) for (const syntax of ['css', 'srcset'])
++ for (const url of ['cid:missing@test', 'file:///private/image.png'])
++ test(`shared send validates ${name} ${syntax} image ${url}`, async () => {
++ const f = fixture({ richText: true });
++ f.externalEdit({ [name]: syntax === 'css'
++ ? `<style>.photo { background-image:url('${url}') }</style><p class="photo">Photo</p>`
++ : `<picture><source srcset="https://example.test/photo.png 1x, ${url} 2x"><img src="https://example.test/photo.png"></picture>` });
++ await f.present();
++ if (name === 'bodyHtml') {
++ const result = await f.tool('send');
++ assert.equal(result.ok, false);
++ assert.equal(result.execution, 'not_executed');
++ } else await f.card('send', Object.fromEntries(f.cards.findLast(c => c.draft).draft.fields.map(x => [x.name, x.value])));
++ assert.equal(f.writes.length, 0);
++ });
++
++test('shared formatting preserves styles and srcset descriptors while reconnecting image bytes', async () => {
++ const f = fixture({ richText: true });
++ const html = '<style>.photo{background:url("cindy-media://image")}</style><picture><source srcset="data:image/png;base64,AAAA 1x, cindy-media://image 2x"><img src="cid:photo@test"></picture>';
++ f.externalEdit({ bodyHtml: html, quoteHtml: html,
++ attachments: [{ key: 'image', filename: 'photo.png', mimeType: 'image/png', bytes: 123, contentId: 'photo@test', previewUrl: 'cindy-media://image' }] });
++ await f.present();
++ const shown = Object.fromEntries(f.cards.findLast(c => c.draft).draft.fields.map(x => [x.name, x.value]));
++ for (const name of ['bodyHtml', 'quoteHtml']) {
++ assert.doesNotMatch(shown[name], /cindy-media:/);
++ const doc = new DOMParser().parseFromString(shown[name], 'text/html');
++ assert.match(doc.querySelector('style').textContent, /url\("cid:photo@test"\)/);
++ assert.equal(doc.querySelector('source').getAttribute('srcset'), 'data:image/png;base64,AAAA 1x, cid:photo@test 2x');
++ }
++ assert.ok((await f.tool('send')).ok);
++ for (const name of ['bodyHtml', 'quoteHtml']) assert.equal(f.writes.find(x => x.send).fields[name], shown[name]);
++});
++
+test('a provider that reintroduces malformed HTML cannot proceed to sending', async () => {
+ const f = fixture({ richText: true, write: request => {
+ if (request.send) return;
+ return { ok: true, data: { readBack: { ...request.readBack, fingerprint: 'saved-but-unformatted',
+ editor: { ...request.readBack.editor, body: 'Changed', bodyHtml: '<html><body><p>Changed</p></body></html>' } } } };
+ } });
+ await f.present();
+ await f.card('change', { ...f.values(), body: 'Changed', bodyHtml: '<p>Changed</p>' });
+ const result = await f.tool('send');
+ assert.equal(result.ok, false);
+ assert.equal(result.format, true);
+ assert.equal(f.writes.length, 1);
+ assert.equal(f.writes[0].send, false);
+});
+
+test('formatting never restores text intentionally cleared in the plain editor', async () => {
+ const f = fixture({ richText: true });
+ f.externalEdit({ format: 'text' });
+ await f.present();
+ await f.card('change', { ...f.values(), body: '' });
+ await f.flush();
+ assert.equal(f.writes[0].fields.body, '');
+});
+
+for (const [providerName, shape] of [
+ ["Gmail", "api"],
+ ["QQ 邮箱", "imap"],
+ ["163 邮箱", "imap"],
+ ["iCloud Mail", "imap"],
+ ["Yahoo Mail", "imap"],
+ ["Outlook", "graph"],
+]) {
+ test(
+ providerName +
+ " adapter: edits, model read, card/model send race and receipt share one draft",
+ async () => {
+ const f = fixture({ providerName, shape });
+ assert.equal(await f.present(), true);
+ const fields = {
+ ...f.values(),
+ body: "Latest edit",
+ };
+ await f.card("change", fields);
+ assert.equal(f.writes.length, 0);
+ const read = await f.tool("get");
+ assert.equal(read.data.readBack.editor.body, fields.body);
+ assert.equal(read.data.readBack.headers.cc, fields.cc);
+ assert.equal(f.writes.length, 1);
+ assert.equal((await f.resolve()).draftId, "logical-draft");
+ if (shape === "imap") assert.equal((await f.resolve()).locator.uid, 43);
+ await Promise.all([f.tool("send"), f.card("send", fields)]);
+ assert.equal(f.writes.filter((request) => request.send).length, 1);
+ const repeated = await f.tool("send");
+ assert.equal(repeated.data.alreadySent, true);
+ if (shape === "graph")
+ assert.deepEqual(copy(repeated.data.receipt), {
+ accepted: true,
+ delivery_confirmed: false,
+ status: 202,
+ });
+ else
+ assert.deepEqual(copy(repeated.data.receipt.accepted), [
+ ]);
+ assert.doesNotMatch(JSON.stringify(f.kv()), /Latest edit|copy@example/);
+ assert.ok(
+ f.cards.some((card) => card.draft?.status.includes("已同步到 " + providerName)),
+ );
+ },
+ );
+}
+
+test("an external locator change with identical content is adopted on read", async () => {
+ const f = fixture();
+ await f.present();
+ f.relocate();
+ await f.tool("get");
+ assert.equal((await f.resolve()).locator.uid, 52);
+ assert.equal((await f.tool("send")).ok, true);
+ assert.equal(f.writes[0].record.locator.uid, 52);
+});
+
+test("card send alone continues with the provider receipt; model send does not start another turn", async () => {
+ for (const entry of ["card", "model"]) {
+ const f = fixture({ providerName: "Outlook", shape: "graph" });
+ await f.present();
+ if (entry === "card") await f.card("send");
+ else await f.tool("send");
+ assert.equal(f.continuations.length, entry === "card" ? 1 : 0);
+ if (entry === "card") {
+ assert.equal(f.continuations[0].userActionToken, "host-click-token");
+ assert.equal(f.continuations[0].event.provider, "Outlook");
+ assert.equal(f.continuations[0].event.receipt.delivery_confirmed, false);
+ // Regression: the internal send receipt appeared as a user bubble. Use
+ // the shared desktop/mobile visibility rule while retaining Agent input.
+ const request = f.continuations[0];
+ const prompt = request.promptTemplate.replace(/\{\{user_message\}\}|\{\{event_json\}\}/g,
+ key => key === "{{user_message}}" ? request.userMessage : JSON.stringify(request.event));
+ assert.equal(isSyntheticTriggerText(prompt), true);
+ assert.equal(syntheticTriggerKind(prompt), "generic");
+ assert.ok(prompt.includes(JSON.stringify(request.event)));
+ assert.ok(prompt.includes("不要重复发送"));
+ }
+ }
+});
+
+test("local storage is labeled honestly and still flushes edits before send", async () => {
+ const f = fixture({
+ providerName: "SMTP",
+ draftStorage: "local",
+ shape: "local",
+ });
+ await f.present();
+ await f.card("change", { ...f.values(), body: "Local edit" });
+ await f.flush();
+ assert.ok(f.cards.at(-1).draft.status.includes("已保存到本地草稿"));
+ assert.equal(
+ f.cards.some((card) => /已同步到|正在同步到/.test(card.draft?.status)),
+ false,
+ );
+ await f.tool("send");
+ assert.equal(f.writes.at(-1).fields.body, "Local edit");
+});
+
+test("a newer edit during IMAP save is saved to the replacement UID before send", async () => {
+ let release, started;
+ const ready = new Promise((resolve) => {
+ started = resolve;
+ });
+ const wait = new Promise((resolve) => {
+ release = resolve;
+ });
+ const f = fixture({
+ write: async (_, number) => {
+ if (number === 1) {
+ started();
+ await wait;
+ }
+ },
+ });
+ await f.present();
+ await f.card("change", { ...f.values(), body: "First" });
+ const saving = f.flush();
+ await ready;
+ await f.card("change", { ...f.values(), body: "Newest" });
+ const sending = f.tool("send");
+ release();
+ await saving;
+ assert.equal((await sending).ok, true);
+ assert.deepEqual(
+ f.writes.map((request) => request.record.locator.uid),
+ [42, 43, 44],
+ );
+ assert.equal(f.writes.at(-1).fields.body, "Newest");
+});
+
+test("unknown/malformed send receipts never retry, including after a plugin restart", async () => {
+ for (const write of [
+ async () => {
+ throw new Error("lost transport");
+ },
+ async () => ({ ok: true, data: {} }),
+ ]) {
+ const f = fixture({ write });
+ await f.present();
+ assert.equal((await f.tool("send")).execution, "unknown");
+ f.restart();
+ assert.equal((await f.tool("send")).execution, "unknown");
+ assert.equal(f.writes.length, 1);
+ }
+});
+
+test("read-only and wrong-card events cannot flush edits or send; restart reconnects the original draft", async () => {
+ const f = fixture();
+ await f.present();
+ await f.card("send", f.values(), { callId: "other-call" });
+ assert.equal(f.writes.length, 0);
+ await f.card("change", { ...f.values(), body: "Pending edit" });
+ assert.equal(
+ (await f.tool("get", { readOnly: true })).execution,
+ "not_executed",
+ );
+ assert.equal(
+ (await f.tool("send", { readOnly: true })).execution,
+ "not_executed",
+ );
+ assert.equal(f.writes.length, 0);
+ await f.flush();
+ f.restart();
+ assert.equal((await f.tool("send")).ok, true);
+ assert.equal(f.reads.length, 1);
+ assert.equal(f.writes.at(-1).fields.body, 'Pending edit');
+});
+
+test('old cards reconnect after restart, keep the latest keystroke and save through the original identity', async () => {
+ const f = fixture(); await f.present();
+ const key = f.cards.at(-1).draft.key;
+ f.restart(); f.relocate();
+ await Promise.all([
+ f.card('change', { ...f.values(), body: 'First' }),
+ f.card('change', { ...f.values(), body: 'Latest typing' }),
+ ]);
+ await f.flush();
+ assert.equal(f.reads.length, 1);
+ assert.equal(f.current().editor.body, 'Latest typing');
+ assert.equal(f.cards.at(-1).draft.key, key);
+ assert.equal(f.writes.some(w => w.send), false);
+});
+
+test('restart with an external change preserves local typing and never overwrites or sends', async () => {
+ const f = fixture(); await f.present(); const original = f.values();
+ f.restart(); f.externalEdit({ body: 'Remote replacement' });
+ await f.card('change', { ...original, body: 'Keep my unsynced edit' });
+ await f.flush();
+ assert.equal(f.writes.length, 0);
+ assert.equal(f.cards.at(-1).draft.fields.find(f => f.name === 'body').value, 'Keep my unsynced edit');
+ assert.equal(f.cards.at(-1).draft.state, 'error');
+ assert.equal((await f.tool('send')).stale, true);
+ assert.equal(f.writes.length, 0);
+ const viewCount = f.cards.length;
+ const read = await f.tool('get');
+ assert.equal(read.data.cardEdits.body, 'Keep my unsynced edit');
+ assert.equal(read.data.readBack.editor.body, 'Remote replacement');
+ assert.equal(f.cards.length, viewCount);
+ assert.match(f.cards.at(-1).draft.status, /正文/);
+});
+
+// Regression: restore/save treated every changed provider fingerprint as a
+// conflict. Exercise actual card/model entry points, including restart (unit).
+test('revision-only changes and one-sided edits reconnect without conflicts', async () => {
+ for (const change of [{}, { subject: 'Remote subject' }]) {
+ const f = fixture(); await f.present(); const original = f.values();
+ f.restart(); f.externalEdit(change);
+ await f.card('change', { ...original, body: 'Local typing' });
+ await f.flush();
+ assert.equal(f.current().editor.body, 'Local typing');
+ assert.equal(f.current().headers.subject, change.subject || original.subject);
+ assert.equal(f.cards.at(-1).draft.state, 'draft');
+ }
+});
+
+test('restart restores unsynced card edits for model send and merges separate text ranges', async () => {
+ const f = fixture(); await f.present();
+ await f.card('change', { ...f.values(), body: 'Dear Original' });
+ f.restart(); f.externalEdit({ body: 'Original wishes', cc: '[email protected]' });
+ assert.equal((await f.tool('send')).ok, true);
+ assert.equal(f.writes.at(-1).fields.body, 'Dear Original wishes');
+ assert.equal(f.writes.at(-1).fields.cc, '[email protected]');
+ assert.equal(f.writes.filter(w => w.send).length, 1);
+});
+
+test('a rejected stale save merges the latest typing and retries only a proven non-execution', async () => {
+ const f = fixture(); await f.present();
+ await f.card('change', { ...f.values(), body: 'Local typing' });
+ f.externalEdit({ subject: 'Remote subject' });
+ await f.flush();
+ assert.equal(f.current().editor.body, 'Local typing');
+ assert.equal(f.current().headers.subject, 'Remote subject');
+ assert.equal(f.cards.at(-1).draft.state, 'draft');
+ assert.equal(f.writes.length, 2);
+});
+
+test('mailbox changes during countdown get a fresh preview and full undo period', async () => {
+ const f = fixture({ autoSend: false }); await f.present();
+ const pending = f.tool('send'); await f.waitCountdown();
+ f.externalEdit({ subject: 'Updated while waiting' });
+ await f.advance(10000); await f.waitCountdown();
+ assert.equal(f.writes.length, 1); // Rejected precondition; no mail sent.
+ assert.equal(f.cards.findLast(c => c.draft).draft.fields.find(f => f.name === 'subject').value, 'Updated while waiting');
+ await f.card('cancel');
+ assert.equal((await pending).cancelled, true);
+ await f.advance(10000);
+ assert.equal(f.writes.length, 1);
+});
+
+test('model send after restart previews remote-only changes before starting its countdown', async () => {
+ const f = fixture({ autoSend: false }); await f.present(); f.restart();
+ f.externalEdit({ subject: 'Latest remote subject' });
+ const pending = f.tool('send'); await f.waitCountdown();
+ assert.equal(f.writes.length, 0);
+ assert.equal(f.cards.findLast(c => c.draft).draft.fields.find(f => f.name === 'subject').value, 'Latest remote subject');
+ await f.card('cancel'); assert.equal((await pending).cancelled, true);
+});
+
+test('identical concurrent edits converge without rewriting; overlapping replacements remain a conflict', async () => {
+ for (const remote of ['Same change', 'Other change']) {
+ const f = fixture(); await f.present();
+ await f.card('change', { ...f.values(), body: 'Same change' });
+ f.externalEdit({ body: remote }); await f.flush();
+ assert.equal(f.writes.length, 1);
+ assert.equal(f.cards.at(-1).draft.state, remote === 'Same change' ? 'draft' : 'error');
+ }
+});
+
+test('HTML style and typing changes merge while preview-only attachment changes do not conflict', async () => {
+ const f = fixture({ richText: true });
+ const file = { key: 'image', filename: 'image.png', mimeType: 'image/png', bytes: 20, contentId: '[email protected]', previewUrl: 'cindy-media://blobs/' + 'a'.repeat(64) + '.png' };
+ f.externalEdit({ attachments: [file] }); await f.present();
+ const values = f.values();
+ f.restart();
+ f.externalEdit({ bodyHtml: '<p style="color:blue">Original</p>', attachments: [{ ...file, contentId: '<[email protected]>', previewUrl: 'cindy-media://blobs/' + 'b'.repeat(64) + '.png' }] });
+ await f.card('change', { ...values, body: 'Dear Original', bodyHtml: '<p style="color:red">Dear Original</p>' });
+ await f.flush();
+ assert.equal(f.current().editor.bodyHtml, '<p style="color:blue">Dear Original</p>');
+ assert.equal(f.current().editor.body, 'Dear Original');
+ assert.equal(f.current().attachments.length, 1);
+ assert.equal(f.cards.at(-1).draft.state, 'draft');
+});
+
+
+test('unknown writes allow inspecting the mailbox without unlocking or repeating the write', async () => {
+ const f = fixture({ write: async () => { throw new Error('lost response'); } });
+ await f.present();
+ assert.equal((await f.tool('send')).execution, 'unknown');
+ const unknownCardCount = f.cards.length;
+ await f.card('cancel', undefined, { formValues: undefined });
+ await f.card('now', undefined, { formValues: undefined });
+ assert.equal(f.cards.length, unknownCardCount);
+ f.restart();
+ assert.equal((await f.tool('get')).ok, true);
+ assert.equal(f.cards.at(-1).draft.state, 'unconfirmed');
+ assert.equal((await f.tool('send')).execution, 'unknown');
+ assert.equal(f.writes.length, 1);
+});
+
+// Regression: both entry points must expose a real undo interval, not send first.
+test("send waits ten seconds; cancel retains draft; send-now and concurrent requests send once", async () => {
+ for (const entry of ["card", "model"]) {
+ const f = fixture({ autoSend: false });
+ await f.present();
+ const pending = entry === "card" ? f.card("send") : f.tool("send");
+ await f.waitCountdown();
+ assert.equal(f.writes.length, 0);
+ await f.advance(9999);
+ assert.equal(f.writes.length, 0);
+ await f.card("cancel", undefined, { formValues: undefined });
+ await pending;
+ await f.advance(1);
+ assert.equal(f.writes.length, 0);
+ assert.equal(f.cards.at(-1).draft.state, "draft");
+ assert.equal(f.continuations.length, 0);
+
+ const retry = entry === "card" ? f.card("send") : f.tool("send");
+ await f.waitCountdown();
+ const duplicate = f.tool("send");
+ await f.card("now", undefined, { formValues: undefined });
+ await Promise.all([retry, duplicate]);
+ await f.advance(10000);
+ assert.equal(f.writes.filter(w => w.send).length, 1);
+ assert.equal(f.continuations.length, entry === "card" ? 1 : 0);
+ }
+});
+test("expiry sends exactly once and restart never resumes a waiting send", async () => {
+ const f = fixture({ autoSend: false });
+ await f.present();
+ const pending = f.tool("send");
+ await f.waitCountdown();
+ await f.advance(9999);
+ assert.equal(f.writes.length, 0);
+ await f.advance(1);
+ assert.equal((await pending).data.sent, true);
+ assert.equal(f.writes.length, 1);
+ const sentCardCount = f.cards.length;
+ await f.card('cancel', undefined, { formValues: undefined });
+ await f.card('now', undefined, { formValues: undefined });
+ assert.equal(f.cards.length, sentCardCount);
+ assert.equal(f.writes.length, 1);
+
+ const restarted = fixture({ autoSend: false });
+ await restarted.present();
+ void restarted.tool("send");
+ await restarted.waitCountdown();
+ restarted.restart();
+ await restarted.advance(10000);
+ assert.equal(restarted.writes.length, 0);
+ const freshSend = restarted.tool('send');
+ await restarted.waitCountdown();
+ assert.equal(restarted.writes.length, 0);
+ await restarted.card('cancel');
+ assert.equal((await freshSend).execution, 'not_executed');
+ assert.equal(restarted.writes.length, 0);
+});
+for (const action of ['cancel', 'now']) test(`stale countdown ${action} restores the draft after restart without sending`, async () => {
+ const f = fixture({ autoSend: false });
+ await f.present();
+ void f.tool('send');
+ await f.waitCountdown();
+ assert.equal(f.cards.at(-1).statusOnly.state, 'sending');
+ f.restart();
+ await f.card(action, undefined, { formValues: undefined });
+ assert.equal(f.reads.length, 1);
+ assert.equal(f.cards.at(-1).draft.state, 'draft');
+ assert.equal(f.cards.at(-1).draft.pendingSend, undefined);
+ await f.advance(10000);
+ assert.equal(f.writes.length, 0);
+ const fresh = f.tool('send');
+ await f.waitCountdown();
+ await f.card('cancel', undefined, { formValues: undefined });
+ assert.equal((await fresh).execution, 'not_executed');
+ assert.equal(f.writes.length, 0);
+});
+test("a rejected countdown card or a draft without a presented card cannot send", async () => {
+ const f = fixture({ acceptCard: false });
+ assert.equal((await f.tool("send")).execution, "not_executed");
+ await f.present();
+ assert.equal((await f.tool("send")).execution, "not_executed");
+ assert.equal(f.writes.length, 0);
+});
+
+test('card/model deletion discards unsaved edits once and stays terminal after restart', async () => {
+ const f = fixture();
+ await f.present();
+ assert.equal(f.cards.at(-1).draft.deleteLabel, '删除草稿');
+ await f.card('change', { ...f.values(), body: 'Discard this edit' });
+ await Promise.all([f.card('delete'), f.tool('delete')]);
+ await f.flush();
+ assert.equal(f.writes.length, 0);
+ assert.equal(f.deletes.length, 1);
+ assert.equal(f.cards.at(-1).statusOnly.state, 'deleted');
+ await f.card('change', { ...f.values(), body: 'Late change' });
+ f.restart();
+ assert.equal((await f.tool('delete')).data.alreadyDeleted, true);
+ assert.equal((await f.tool('send')).execution, 'not_executed');
+ assert.equal(f.deletes.length, 1);
+ assert.equal(f.continuations.length, 0);
+});
+
+test('delete cancels the send countdown and no expiry can send the draft', async () => {
+ const f = fixture({ autoSend: false });
+ await f.present();
+ const sending = f.tool('send');
+ await f.waitCountdown();
+ assert.equal((await f.tool('delete')).data.deleted, true);
+ assert.equal((await sending).cancelled, true);
+ await f.advance(10000);
+ assert.equal(f.writes.length, 0);
+ assert.equal(f.deletes.length, 1);
+});
+
+test('delete waits for an in-flight save and uses its replacement IMAP UID', async () => {
+ let release, started;
+ const ready = new Promise(resolve => { started = resolve; });
+ const wait = new Promise(resolve => { release = resolve; });
+ const f = fixture({ write: async () => { started(); await wait; } });
+ await f.present();
+ await f.card('change', { ...f.values(), body: 'Saving' });
+ const saving = f.flush();
+ await ready;
+ const deleting = f.tool('delete');
+ release();
+ await saving;
+ assert.equal((await deleting).ok, true);
+ assert.equal(f.deletes[0].record.locator.uid, 43);
+ assert.equal(f.cards.at(-1).statusOnly.state, 'deleted');
+});
+
+// Regression: an old card silently refused deletion on any provider revision
+// change. Discard targets the logical draft, including newer content (unit tier).
+test('old cards delete the latest draft after restart, without saving or sending edits', async () => {
+ for (const fields of [{}, { bodyHtml: '<p>Updated</p>', attachments: [{ key: 'image', filename: 'card.png', bytes: 42 }] }]) {
+ const f = fixture({ richText: true });
+ await f.present();
+ f.externalEdit(fields);
+ f.relocate();
+ f.restart();
+ await f.card('delete');
+ assert.equal(f.deletes.length, 1);
+ assert.equal(f.deletes[0].record.fingerprint, f.current().fingerprint);
+ assert.equal(f.cards.at(-1).statusOnly.state, 'deleted');
+ assert.equal(f.writes.length, 0);
+ }
+});
+
+test('delete reports progress before slow reads and failed preparation stays retryable', async () => {
+ let fail = true;
+ const f = fixture({ read: async () => {
+ assert.equal(f.cards.at(-1).statusOnly.state, 'deleting');
+ if (fail) throw new Error('Read failed');
+ } });
+ await f.present();
+ await f.card('delete');
+ assert.equal(f.deletes.length, 0);
+ assert.equal(f.cards.at(-1).statusOnly.state, 'error');
+ assert.equal(Object.values(f.kv().mailDraftCards)[0].state, 'draft');
+ fail = false;
+ await f.card('delete');
+ assert.equal(f.deletes.length, 1);
+ assert.equal(f.cards.at(-1).statusOnly.state, 'deleted');
+});
+
+test('readonly or mismatched drafts are not deleted; unknown deletion is never replayed', async () => {
+ const readonly = fixture();
+ await readonly.present();
+ assert.equal((await readonly.tool('delete', { readOnly: true })).execution, 'not_executed');
+ assert.equal(readonly.deletes.length, 0);
+ const mismatch = fixture({ read: async () => ({ ok: true, data: { readBack: { status: 'read_back', draftId: 'another-draft' } } }) });
+ await mismatch.present();
+ await mismatch.card('delete');
+ assert.equal(mismatch.deletes.length, 0);
+ assert.equal(mismatch.cards.at(-1).statusOnly.state, 'error');
+ for (const remove of [async () => { throw new Error('lost response'); }, async () => ({ ok: true, data: {} })]) {
+ const f = fixture({ remove });
+ await f.present();
+ assert.equal((await f.tool('delete')).execution, 'unknown');
+ assert.equal(f.cards.at(-1).statusOnly.state, 'unconfirmed');
+ f.restart();
+ assert.equal((await f.tool('delete')).execution, 'unknown');
+ assert.equal((await f.tool('send')).execution, 'unknown');
+ assert.equal(f.deletes.length, 1);
+ assert.equal(f.writes.length, 0);
+ }
+ const legacy = fixture({ supportsDelete: false });
+ await legacy.present();
+ assert.equal(legacy.cards.at(-1).draft.deleteLabel, undefined);
+ assert.equal(await legacy.tool('delete'), null);
+});
diff --cc apps/desktop/src/main/bootstrap-electron.ts
index cdd335b760,192923c4da..4896499fba
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@@ -2472,7 -2473,21 +2475,22 @@@ setCodexImageAuthBinding(
getAuth: getChatgptBridgeAuth,
onAuthFailure: invalidateChatgptBridgeAuth,
});
+configureMailAttachmentHost({ writeTempFile, materializeDirectSendOssAttachments });
+ setRemotePluginManagementServices({
+ isRelayOnline: () => getDeviceLinkStatus() === 'online',
+ listProjects: listRecentWorkdirs,
+ sidebar: {
+ read: id => !loadSidebarSettingsSnapshot().hiddenMainViewGhostIds.includes(id),
+ write: async (id, visible, assertCurrent) => { await setLocalMainViewHidden(id, !visible, assertCurrent); },
+ },
+ market: {
+ snapshot: () => getPluginMarketService().snapshot({ discoveryOnly: true }),
+ detail: id => getPluginMarketService().detail(id),
+ install: async (id, options, prompt, assertCurrent, assertScope) => {
+ await getPluginMarketService().install(id, options, { consent: { prompt, initiator: 'user' }, assertCurrent, assertScope });
+ },
+ },
+ });
registerGhostIpc();
registerPluginMarketIpc();
registerPluginPublisherIpc();
diff --cc apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts
index 42ca52f2e7,42ca52f2e7..c074248f09
--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts
@@@ -82,6 -82,6 +82,30 @@@ function makeHarness(opts:
const CALL = { ghostId: 'art', tool: 'gen_image', args: { prompt: '一只猫' } };
++// #6404: wrapper-only tests did not exercise ordinary ghost_call arguments.
++// Unit: dispatch real tool payloads; only Host opening + literal opt-in may mark read.
++describe('mail reader opening intent', () => {
++ it.each([
++ { opened: undefined, optIn: true, tool: 'read_mail', expected: false },
++ { opened: true, optIn: true, tool: 'read_mail', expected: true },
++ { opened: true, optIn: undefined, tool: 'read_mail', expected: false },
++ { opened: true, optIn: 'true', tool: 'read_mail', expected: false },
++ { opened: true, optIn: false, tool: 'read_mail', expected: false },
++ { opened: undefined, optIn: true, tool: 'set_read', expected: true },
++ ] as const)('dispatches $tool with opening=$opened, opt-in=$optIn', async ({ opened, optIn, tool, expected }) => {
++ const ghost = fakeGhost();
++ Object.assign(ghost.manifest, { mail: true, mailReader: { tool: 'read_mail', hosts: ['mail.example.test'], markRead: optIn } });
++ ghost.manifest.tools = ['read_mail', 'set_read'].map(name => ({ name, description: name }));
++ const h = makeHarness({ ghost });
++ const args = { url: 'https://mail.example.test/message/one', markRead: !opened, mailReaderOpened: true };
++ const pending = h.dispatcher.callGhostTool({ ghostId: 'art', tool, args, ...(opened ? { mailReaderOpened: true as const } : {}) });
++ expect(h.sent[0].args).toEqual(expected ? { ...args, markRead: true } : { url: args.url, mailReaderOpened: true });
++ expect(args.markRead).toBe(!opened); // Never mutate the caller's data.
++ h.dispatcher.handleToolResult('art', { callId: h.sent[0].callId, ok: true, result: 'mail' });
++ expect(await pending).toEqual({ ok: true, result: 'mail' });
++ });
++});
++
describe('caller cancellation', () => {
it('Host Stop affects only opted-in calls in that session, preserving legacy calls', async () => {
const h = makeHarness();
diff --cc apps/desktop/src/main/cindy-brain/forge.ts
index eadb73a46e,84b0fc8da1..b560c1b4c6
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@@ -1851,25 -1851,6 +1851,26 @@@ v3 直接用顶层字段声明插件贡
\`agent\`、\`panel\`、\`mainView\`、\`card\`、\`subscribe\`、\`network\`、\`node\`、\`preview\`、
\`skill\`;布尔能力写成字面量 \`true\`:\`notify\`、\`badge\`、\`confirm\`、\`fs\`、
\`library\`、\`sessionContext\`、\`pick\`、\`workspace\`。不用的字段直接省略,
+邮件插件声明 \`mail: true\`,调用 Cindy 内置 \`cindyMail.register(adapter)\`
+(version 1),不生成卡片 HTML、不打包公共流程;纯邮件插件不需要 \`card\`。
+阅读邮件可声明 \`mailReader:{tool,hosts}\`,工具接收 \`{url}\` 并返回 MailMessage,默认只读。
+\`mail\` 只能省略或写字面量 \`true\`;声明 \`mailReader\` 时必须同时有 \`mail: true\`,
+且 \`tool\` 必须指向本清单 \`tools\` 中的工具。协议校验与桌面安装校验都会拒绝不完整组合。
+支持打开即已读时增加 \`mailReader.markRead:true\`,读取工具接受可选 \`markRead:true\`;
+声明中的 \`markRead\` 只能省略或为字面量 \`true\`,\`false\`、字符串等其它值不合法。
+仅用户主动打开时传入,AI 读取和邻近预加载不传。成功读取后只标记当前邮件,不标记整个会话或草稿。
++Host 派发器会移除普通工具参数中的此标记,仅可信阅读器打开请求可注入;其它明确授权的已读操作工具不受影响。
+标记失败仍返回正文和 \`markReadFailed:true\`,由 Cindy 显示提示;新增 OAuth scope 不阻断已有授权的操作。
+适配器提供 providerName、draftStorage(server/local)、selectAccount、readDraft、writeDraft。
+通过 present 展示读回草稿,beforeTool 统一 get/send/update/delete,resolveDraft 获取最新位置。
+Host 负责样式、编辑同步、发送和任务续接;同一任务同一封邮件只显示最新卡片,旧快照保留但不重复展示。插件保留凭据、MIME 和服务商请求。
+插件重启后,下一次卡片编辑或工具操作会自动读回原草稿,使用 Host 卡片中上次同步的内容、卡片编辑和邮箱最新内容做三方合并;单边变化、相同变化和不重叠的文字修改自动合并,只有无法合并的修改才保留两边内容并提示具体字段。版本标记或预览地址变化本身不算冲突。适配器返回 execution:not_executed 和 stale 读回快照时可合并后重试一次,未知操作结果不能重试。发送倒计时结束时若发现实际内容变化,展示合并稿并重新倒计时。
+图文适配器的 attachmentItems 可为已有图片 key 添加 contentId,表示将同一附件插入 HTML 正文;必须核验实际图片字节、保留 MIME 引用,不能重复上传或把预览 URL 写入邮件。
+工具说明应要求默认展示草稿卡等用户确认;只有用户已明确确认该邮件,或有效的用户/任务指令明确授权该范围内直接发送,才不再询问。写信/回复请求、编辑及自动审批本身不代表确认。
+UI 和 Agent 发送都先进入 10 秒倒计时,卡片可撤销或立即发送;beforeTool(send) 等待最终回执。
+撤销后保留草稿且不得自动重试。所有发送先创建并展示草稿,再走 beforeTool(send),不得保留直发旁路。
+缺少 SDK 时只读可用,编辑/发送需更新 Cindy;不要绕开公共流程直接发送已展示草稿。
+
不能写 \`false\`。\`card: {}\` 与 \`agent: {}\` 分别表示基础聊天卡片能力和用户点击后
发起 Agent 回合;其它对象型能力必须包含该能力真正需要的详单。
diff --cc apps/desktop/src/main/cindy-brain/index.ts
index 499bd7bb29,626540ad18..3da5cdf73b
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@@ -1,8 -1,12 +1,15 @@@
+ import { RemotePluginPreferences } from './remotePluginPreferences.js';
+ import { readDeviceLinkSettings } from '../device-link/settings-store.js';
+ import { isSharedTaskPeer, isProviderSharePeer } from '@cindy/device-link';
+ import { RemotePluginManagement, type RemotePluginManagementDeps } from './remotePluginManagement.js';
+ import { projectPluginWorkdir, resolvePluginWorkdir } from './remotePluginProjects.js';
+ import { takePeerAttachment } from '../device-link/peerAttachmentStore.js';
+ import { parsePeerAttachmentRef } from '@cindy/device-link';
import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';
import { readMobilePreview } from './mobilePreview.js';
+import { createMailReader, mailReaderRemoteProvider } from './mailReader.js';
+import { assertRemoteBotInvocationAllowed } from '../device-link/remoteBotSessionBoundary.js';
+import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
import { MobileTaskSettings } from './mobileTaskSettings.js';
import { MobilePluginPages } from './mobilePageService.js';
import { listMobilePageFiles, readMobilePageChunk } from './mobilePageAssets.js';
@@@ -7880,27 -7941,63 +7961,81 @@@ export function registerGhostIpc(): voi
});
if (ipcRegistered) return;
ipcRegistered = true;
+ const readMail = createMailReader({
+ plugins: () => availableGhosts().flatMap(g => g.enabled && g.approval.state === 'approved' && g.manifest.mail === true && g.manifest.mailReader &&
+ g.manifest.tools?.some(t => t.name === g.manifest.mailReader!.tool)
+ ? [{ id: g.instanceKey || g.manifest.id, namespace: g.instanceKey ? undefined : g.namespace, enabled: true, reader: g.manifest.mailReader }] : []),
+ authorize: async sessionId => {
+ // A shared task does not grant access to the owner's mailbox.
+ if (getDeviceLinkInvokeContext()?.sharedTask || !await getSessionRowSnapshot(sessionId))
+ throwIpcError('NOT_FOUND', 'Mail preview unavailable');
+ await assertRemoteBotInvocationAllowed([sessionId]);
+ },
+ captureScope: () => { const scope = captureDataOwnerBroadcastScope(); return () => isDataOwnerBroadcastScopeCurrent(scope); },
- call: (plugin, sessionId, url, markRead) => getGhostPipeDispatcher().callGhostTool({ ghostId: plugin.id, namespace: plugin.namespace, tool: plugin.reader.tool, args: { url, ...(markRead ? { markRead: true } : {}) }, sessionId }),
++ call: (plugin, sessionId, url, markRead) => getGhostPipeDispatcher().callGhostTool({ ghostId: plugin.id, namespace: plugin.namespace, tool: plugin.reader.tool, args: { url }, sessionId, ...(markRead ? { mailReaderOpened: true as const } : {}) }),
+ });
+ remoteResourceRegistry.register(mailReaderRemoteProvider(readMail));
+ ipcMain.handle('ghosts:mail-preview', (event, sessionId: unknown, url: unknown, read: unknown, opened: unknown = false) => {
+ assertTrustedAppRendererEvent(event);
+ return readMail(sessionId, url, read, opened);
+ });
const manager = getGhostManager();
const runtime = getGhostRuntime();
+ const taskSettings = new MobileTaskSettings({
+ read: readPluginTaskConfig, write: writePluginTaskConfig, validate: validatePluginTaskConfig,
+ providers: () => getDesktopProviderService({ allowSideEffects: false }).listProviders({ allowSideEffects: false, snapshotOnly: true }),
+ agents: async () => { const { getMakerIfReady } = await import('../maker-host/index.js'); return getMakerIfReady()?.listAvailableAgents() ?? []; },
+ });
+ remotePluginManagement = new RemotePluginManagement({
+ list: availableGhosts,
+ settingsPage: true,
+ preferences: new RemotePluginPreferences({
+ auxiliaryModelLabel: () => {
+ const ref = getEffectiveAuxiliaryModelChain().refs[0] ?? null;
+ return ref === null ? null : formatAuxiliaryModelRefLabel(ref);
+ },
+ tasks: taskSettings,
+ sidebar: {
+ read: id => requireRemotePluginManagementServices().sidebar.read(id),
+ write: (id, visible, assertCurrent) => requireRemotePluginManagementServices().sidebar.write(id, visible, assertCurrent),
+ },
+ }),
+ projects: {
+ list: async () => {
+ const entries = await requireRemotePluginManagementServices().listProjects();
+ return [...new Map(entries.map((entry) => {
+ const project = projectPluginWorkdir(entry.path);
+ return [project.id, project] as const;
+ })).values()];
+ },
+ resolve: resolvePluginWorkdir,
+ disabled: listDisabledGhostIdsForWorkdir,
+ setDisabled: (workdir, instance, disabled, assertCurrent) => {
+ assertCurrent();
+ setGhostWorkdirDisabledAndNotify(workdir, instance, disabled);
+ },
+ },
+ capture: peer => {
+ const scope = captureDataOwnerBroadcastScope(), checkPeer = capturePluginOauthPeer(peer);
+ return () => { try { checkPeer(); const settings = readDeviceLinkSettings(); return !isSharedTaskPeer(peer) && !isProviderSharePeer(peer) && remotePluginManagementServices?.isRelayOnline() === true && settings.remoteControlEnabled && !settings.revokedControllers.includes(peer) && isDataOwnerBroadcastScopeCurrent(scope); } catch { return false; } };
+ },
+ captureReceipt: peer => {
+ const scope = captureDataOwnerBroadcastScope();
+ return () => { const settings = readDeviceLinkSettings(); return !isSharedTaskPeer(peer) && !isProviderSharePeer(peer) && settings.remoteControlEnabled && !settings.revokedControllers.includes(peer) && isDataOwnerBroadcastScopeCurrent(scope); };
+ },
+ market: {
+ snapshot: () => requireRemotePluginManagementServices().market.snapshot(),
+ detail: id => requireRemotePluginManagementServices().market.detail(id),
+ install: async (id, options, prompt, assertCurrent, assertScope) => {
+ await requireRemotePluginManagementServices().market.install(id, options, prompt, assertCurrent, assertScope);
+ },
+ },
+ setEnabled: async (id, enabled, approval, assertCurrent) => { await setGhostEnabledForUser(id, enabled, approval, assertCurrent); },
+ uninstall: async (id, _approval, assertCurrent) => { assertCurrent(); await uninstallGhostAndCleanup(id, { assertCurrent }); },
+ installFile: installRemoteGhostFile,
+ });
mobilePluginPages = new MobilePluginPages({
+ management: remotePluginManagement,
list: availableGhosts,
listOrder: () => {
const order = new Map<string, { addedAt?: number; recentIndex?: number }>();
diff --cc apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
index fece50e297,fece50e297..8c39898f16
--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
@@@ -200,6 -200,6 +200,8 @@@ export class GhostPipeDispatcher
sessionId?: string;
/** Host debug actions are explicitly excluded. Never exposed in plugin payloads. */
recordUsage?: false;
++ /** Native reader's explicit opening intent. Never sourced from tool args. */
++ mailReaderOpened?: true;
}): Promise<GhostToolCallResult> {
const { ghostId, namespace, tool, args } = request;
@@@ -239,7 -239,7 +241,14 @@@
// ── 派发 + 配对等待 ────────────────────────────────────────────────
const callId = request.callId && request.callId.length > 0 ? request.callId : randomUUID();
-- const payload: GhostPipeToolCall = { type: 'tool-call', callId, tool, args };
++ let toolArgs = args;
++ if (ghost.manifest.mail === true && ghost.manifest.mailReader?.tool === tool) {
++ toolArgs = { ...args };
++ delete toolArgs.markRead;
++ if (request.mailReaderOpened === true && ghost.manifest.mailReader.markRead === true)
++ toolArgs.markRead = true;
++ }
++ const payload: GhostPipeToolCall = { type: 'tool-call', callId, tool, args: toolArgs };
return new Promise<GhostToolCallResult>((resolve) => {
const startedAt = Date.now();
diff --cc apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
index 2195a74d60,0000000000..cf418ea1ea
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
+++ b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
@@@ -1,1134 -1,0 +1,1172 @@@
+/* Cindy-owned mail SDK. Served by the Host before provider entry points.
+ * Providers supply only account/read/write adapters; no HTML or card handlers.
+ * State is scoped to the provider sandbox and uses its existing routing KV. */
+var cindyMail = (function () {
+ "use strict";
+ // Outgoing content policy belongs to Cindy, not individual provider adapters.
+ // Parse in an inert document; never mount incoming mail in the plugin page.
+ // Leave ordinary fragments byte-for-byte intact to avoid spurious sync edits.
+ function formatMailFields(input, additions, format) {
+ const fields = { ...input };
+ if (typeof fields.bodyHtml !== 'string') return { fields };
+ const items = JSON.parse(fields.attachmentItems || '[]');
+ const files = [...items, ...(additions || [])];
+ const cid = value => (value || '').replace(/^<|>$/g, '');
+ const ids = files.map(f => cid(f.contentId)).filter(Boolean);
+ let issue = new Set(ids).size !== ids.length ? 'duplicateImage' : undefined;
+ const extensions = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif',
+ 'image/webp': 'webp', 'image/svg+xml': 'svg', 'application/pdf': 'pdf', 'text/plain': 'txt' };
+ let renamed = false;
+ for (const file of items) {
+ const extension = extensions[(file.mimeType || '').toLowerCase()];
+ if (extension && !/\.[^./\\]+$/.test(file.filename || '')) {
+ file.filename = (file.filename || 'attachment') + '.' + extension;
+ renamed = true;
+ }
+ }
+ if (renamed) fields.attachmentItems = JSON.stringify(items);
+ for (const name of ['bodyHtml', 'quoteHtml']) {
+ const source = fields[name] || '';
+ if (!source) continue;
+ const doc = new DOMParser().parseFromString(source, 'text/html');
+ const fullDocument = /<!doctype\s|<\/?(?:html|head|body)(?:\s|>)/i.test(source);
+ let changed = fullDocument;
+ if (fullDocument) {
+ // Browsers adopt a nested <body>'s attributes onto the document body.
+ // Restore those attributes on the quoted content, not on the reply or
+ // attribution. Keep tables, inline styles and Outlook comments intact.
+ const container = name === 'quoteHtml' ? doc.body.querySelector('blockquote') || doc.body : doc.body;
+ const wrapper = doc.createElement('div');
+ for (const element of [doc.documentElement, doc.body])
+ for (const attr of element.attributes) {
+ if (attr.name === 'style') wrapper.style.cssText += ';' + attr.value;
+ else wrapper.setAttribute(attr.name, attr.value);
+ }
+ // Legacy HTML body colours/backgrounds also need to survive extraction.
+ for (const [attr, prop] of [['bgcolor', 'background-color'], ['text', 'color']])
+ if (doc.body.hasAttribute(attr) && !wrapper.style.getPropertyValue(prop))
+ wrapper.style.setProperty(prop, doc.body.getAttribute(attr));
+ if (doc.body.hasAttribute('background') && !wrapper.style.backgroundImage)
+ wrapper.style.backgroundImage = 'url(' + JSON.stringify(doc.body.getAttribute('background')) + ')';
+ doc.querySelectorAll('meta, base, title').forEach(node => node.remove());
+ while (container.firstChild) wrapper.appendChild(container.firstChild);
+ for (const node of [...doc.head.childNodes].reverse())
+ if (node.nodeType === 8 || node.nodeName === 'STYLE') wrapper.prepend(node);
+ container.appendChild(wrapper);
+ }
+ // Preview URLs are Host-local. Reconnect to the same MIME image instead of
+ // leaking a local address or sending a broken picture to the recipient.
+ const checkImage = value => {
++ value = value.trim();
+ const match = files.find(f => f.previewUrl === value && cid(f.contentId));
+ if (match) return 'cid:' + cid(match.contentId);
+ if (/^cid:/i.test(value)) {
+ let id = value.slice(4);
+ try { id = decodeURIComponent(id); } catch (_) { /* Literal CID. */ }
+ if (!ids.includes(cid(id))) issue ||= 'missingImage';
+ } else if (/^(?:cindy-media|xdt-image|blob|file):/i.test(value)) issue ||= 'localImage';
+ return value;
+ };
- for (const element of doc.body.querySelectorAll('[src], [background], [style]')) {
++ const checkCss = value => value.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/gi,
++ (all, doubleQuoted, singleQuoted, bare) => {
++ const url = doubleQuoted ?? singleQuoted ?? bare, next = checkImage(url);
++ return next === url.trim() ? all : 'url("' + next + '")';
++ });
++ const checkSrcset = value => {
++ // URLs end at ASCII whitespace, not commas (data URLs contain commas).
++ // Keep descriptors and separators verbatim; inspect every candidate.
++ let position = 0, copied = 0, output = '';
++ while (position < value.length) {
++ while (/[\t\n\f\r ,]/.test(value[position] || '') && position < value.length) position++;
++ const start = position;
++ while (position < value.length && !/[\t\n\f\r ]/.test(value[position])) position++;
++ const token = value.slice(start, position), url = token.replace(/,+$/, '');
++ if (!url) break;
++ output += value.slice(copied, start) + checkImage(url);
++ copied = start + url.length;
++ if (token.endsWith(',')) continue;
++ let depth = 0;
++ while (position < value.length) {
++ const char = value[position++];
++ if (char === '(') depth++;
++ else if (char === ')') depth = Math.max(0, depth - 1);
++ else if (char === ',' && !depth) break;
++ }
++ }
++ return output + value.slice(copied);
++ };
++ for (const element of doc.querySelectorAll('[src], [srcset], [background], [style], style')) {
+ for (const attr of ['src', 'background']) if (element.hasAttribute(attr)) {
+ const before = element.getAttribute(attr), after = checkImage(before);
+ if (before !== after) { element.setAttribute(attr, after); changed = true; }
+ }
- if (element.hasAttribute('style')) {
- const before = element.getAttribute('style');
- const after = before.replace(/url\(\s*(["']?)([^"')]+)\1\s*\)/gi,
- (all, quote, value) => { const next = checkImage(value.trim()); return next === value.trim() ? all : 'url("' + next + '")'; });
- if (before !== after) { element.setAttribute('style', after); changed = true; }
++ for (const attr of ['style', 'srcset']) if (element.hasAttribute(attr)) {
++ const before = element.getAttribute(attr);
++ const after = attr === 'style' ? checkCss(before) : checkSrcset(before);
++ if (before !== after) { element.setAttribute(attr, after); changed = true; }
+ }
++ if (element.nodeName === 'STYLE') {
++ const before = element.textContent, after = checkCss(before);
++ if (before !== after) { element.textContent = after; changed = true; }
++ }
++ }
++ if (changed) {
++ // A fragment starting with <style> is parsed into head. Retain it when
++ // serializing a repaired image URL instead of dropping authored CSS.
++ for (const node of [...doc.head.childNodes].reverse())
++ if (node.nodeType === 8 || node.nodeName === 'STYLE') doc.body.prepend(node);
++ fields[name] = doc.body.innerHTML;
+ }
- if (changed) fields[name] = doc.body.innerHTML;
+ const plain = name === 'bodyHtml' ? 'body' : 'quote';
+ if (format !== 'text' && !fields[plain]?.trim()) {
+ // Only supply an absent fallback; never overwrite an authored text part.
+ const textRoot = doc.body.cloneNode(true);
+ textRoot.querySelectorAll('style, script, title').forEach(n => n.remove());
+ textRoot.querySelectorAll('br').forEach(n => n.replaceWith('\n'));
+ textRoot.querySelectorAll('p, div, tr, li, blockquote, h1, h2, h3, h4').forEach(n => n.append('\n'));
+ fields[plain] = (plain === 'quote' ? '\n\n' : '') + textRoot.textContent.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
+ }
+ }
+ if (Object.entries(fields).some(([name, value]) => typeof value !== 'string' || value.length > (name.endsWith('Html') ? 64000 : 16000))) issue ||= 'formatTooLarge';
+ return { fields, issue };
+ }
+ function create(adapter) {
+ if (
+ !adapter ||
+ typeof adapter.providerName !== "string" ||
+ !adapter.providerName ||
+ !["server", "local"].includes(adapter.draftStorage) ||
+ ["selectAccount", "readDraft", "writeDraft"].some(
+ (name) => typeof adapter[name] !== "function",
+ )
+ ) {
+ throw new Error(
+ "Mail compose requires an account/read/write adapter and explicit draft storage.",
+ );
+ }
+ // Card records contain routing/receipts only. The adapter owns draft storage;
+ // credentials and mail bodies never enter these records.
+ async function mailCopy() {
+ var provider = adapter.providerName;
+ var locale = "en";
+ try {
+ var response = await fetch("/app-context");
+ var data = await response.json();
+ locale = data.context.locale;
+ } catch (_) {
+ /* English fallback. */
+ }
+ return locale === "zh-CN"
+ ? {
+ from: "发件人",
+ to: "收件人",
+ cc: "抄送",
+ bcc: "密送",
+ subject: "主题",
+ body: "正文",
+ quote: "引用内容",
+ attachmentItems: "附件",
+ send: "发送",
+ delete: "删除草稿",
+ deleting: "正在删除草稿…",
+ deleted: "草稿已删除",
+ deleteFailed: "未能删除草稿,请重试。",
+ countdown: "{seconds} 秒后发送",
+ cancel: "撤销",
+ sendNow: "立即发送",
+ cancelled: "已撤销发送,草稿已保留。",
+ saved:
+ adapter.draftStorage === "server"
+ ? "已同步到 " + provider
+ : "已保存到本地草稿",
+ syncing:
+ adapter.draftStorage === "server"
+ ? "正在同步到 " + provider + "…"
+ : "正在保存本地草稿…",
+ sent: "邮件已发送",
+ busy: "正在处理…",
+ failed: "未能完成,请先核对邮箱中的草稿和已发送邮件。",
+ unavailable:
+ "此草稿无法在卡片中完整编辑,请通过邮箱插件重新读取并核对。",
+ missing: "草稿卡片已失效,请让助手重新读取这份草稿。",
+ recoveryConflict: "{fields}有两处修改无法自动合并。卡片上的编辑已保留,请核对后再发送。",
+ continued: "已交给助手继续处理",
+ continue: "继续处理",
+ continueFailed: "邮件已发送,但未能继续任务。可点击“继续处理”。",
+ review: "草稿已更新,请检查后再发送。",
+ duplicateImage: "正文图片引用重复,请让助手重新关联图片后再发送。",
+ missingImage: "正文中的图片缺少对应附件,请补上图片或删除该图片后再发送。",
+ localImage: "正文图片仍使用本地地址,请将图片作为内嵌附件插入后再发送。",
+ formatTooLarge: "整理后的邮件超过编辑大小上限,请让助手缩减内容后再发送。",
+ formatNotRetained: "邮箱插件未保留整理后的邮件格式,草稿已保留,请让助手检查插件后再发送。",
+ }
+ : {
+ from: "From",
+ to: "To",
+ cc: "Cc",
+ bcc: "Bcc",
+ subject: "Subject",
+ body: "Message",
+ quote: "Quoted message",
+ attachmentItems: "Attachments",
+ send: "Send",
+ delete: "Delete draft",
+ deleting: "Deleting draft…",
+ deleted: "Draft deleted",
+ deleteFailed: "Could not delete the draft. Please try again.",
+ countdown: "Sending in {seconds}s",
+ cancel: "Undo",
+ sendNow: "Send now",
+ cancelled: "Send cancelled. Draft retained.",
+ saved:
+ adapter.draftStorage === "server"
+ ? "Synced to " + provider
+ : "Saved to local draft",
+ syncing:
+ adapter.draftStorage === "server"
+ ? "Syncing to " + provider + "…"
+ : "Saving local draft…",
+ sent: "Message sent",
+ busy: "Working…",
+ failed:
+ "Unable to complete. Check the draft and Sent folder in your mailbox before taking further action.",
+ unavailable:
+ "This draft cannot be edited in full here. Read and review it through the mail plugin.",
+ missing:
+ "This draft card is no longer available. Ask the assistant to read the saved draft again.",
+ recoveryConflict: "Conflicting edits in {fields}. Your card edits are retained; review them before sending.",
+ continued: "Handed back to the assistant",
+ continue: "Continue",
+ continueFailed:
+ "Message sent, but the task could not continue. Select Continue.",
+ review: "Draft updated. Review it before sending.",
+ duplicateImage: "Inline images have duplicate references. Ask the assistant to reconnect them before sending.",
+ missingImage: "An inline image has no matching attachment. Add the image or remove it before sending.",
+ localImage: "An image still uses a local address. Insert it as an inline attachment before sending.",
+ formatTooLarge: "The formatted message exceeds the editor size limit. Ask the assistant to shorten it before sending.",
+ formatNotRetained: "The mail plugin did not retain the formatted content. The draft is saved; ask the assistant to check the plugin before sending.",
+ };
+ }
+ async function mailRecords(change) {
+ return navigator.locks.request(
+ adapter.storageLock || "mail-compose-records",
+ async function () {
+ var response = await fetch("/kv");
+ if (!response.ok)
+ throw new Error("草稿卡片状态无法读取,请检查邮箱。");
+ var data = await response.json();
+ var records = data.mailDraftCards || {};
+ if (!change) return records;
+ var result = change(records);
+ data.mailDraftCards = records;
+ var saved = await fetch("/kv", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(data),
+ });
+ if (!saved.ok)
+ throw new Error(
+ "草稿卡片状态无法保存,邮件未再次发送,请先检查邮箱。",
+ );
+ return result;
+ },
+ );
+ }
+ async function mailStatus(callId, text, action, working, sourceCallId, state, pendingSend) {
+ return cindy.send({ type: "mail-draft-update", callId,
+ ...(sourceCallId ? { sourceCallId } : {}),
+ statusOnly: { status: text, state: state || (working ? "sending" : "error"), pendingSend,
+ ...(action ? { continueLabel: action } : {}) } });
+ }
+ const mailEdits = new Map();
+ function draftValues(readBack) {
+ const values = Object.fromEntries(['to', 'cc', 'bcc', 'subject'].map(name => [name, readBack.headers[name] || '']));
+ Object.assign(values, { body: readBack.editor.body || '', quote: readBack.editor.quote || '' });
+ if (adapter.richText) Object.assign(values, {
+ bodyHtml: readBack.editor.bodyHtml || '<div>' + values.body.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>') + '</div>',
+ quoteHtml: readBack.editor.quoteHtml || '',
+ attachmentItems: JSON.stringify(readBack.attachments.map(a => ({ key: a.key, filename: a.filename, bytes: a.bytes, contentId: a.contentId || '', mimeType: a.mimeType, previewUrl: a.previewUrl }))),
+ });
+ return values;
+ }
+ function comparable(name, value) {
+ if (name !== 'attachmentItems') return (value || '').replace(/\r\n/g, '\n');
+ // Managed preview addresses are not mailbox content.
+ return JSON.stringify(JSON.parse(value || '[]').map(a =>
+ [a.key, (a.contentId || '').replace(/^<|>$/g, ''), a.filename, a.bytes]).sort());
+ }
+ function sameFields(a, b) {
+ return Object.keys(b).every(name => comparable(name, a[name]) === comparable(name, b[name]));
+ }
+ // A conservative three-way text merge: identical edits converge; independent
+ // replacement ranges combine. Overlapping replacements remain for review.
+ function mergeText(base, local, remote) {
+ function range(next) {
+ let start = 0, end = base.length, last = next.length;
+ while (start < end && start < last && base[start] === next[start]) start++;
+ while (end > start && last > start && base[end - 1] === next[last - 1]) { end--; last--; }
+ return { start, end, text: next.slice(start, last) };
+ }
+ const a = range(local), b = range(remote);
+ if ((a.start === b.start && (a.start === a.end || b.start === b.end)) ||
+ !(a.end <= b.start || b.end <= a.start)) return undefined;
+ let result = base;
+ for (const edit of [a, b].sort((x, y) => y.start - x.start))
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
+ return result;
+ }
+ function mergeFields(base, local, remote) {
+ const fields = { ...remote }, conflicts = [];
+ for (const name of Object.keys(remote)) {
+ const l = local[name] ?? '', r = remote[name], b = base?.[name];
+ if (comparable(name, l) === comparable(name, r)) continue;
+ if (b !== undefined && comparable(name, l) === comparable(name, b)) continue;
+ if (b !== undefined && comparable(name, r) === comparable(name, b)) { fields[name] = l; continue; }
+ let merged;
+ if (b !== undefined && ['body', 'quote', 'bodyHtml', 'quoteHtml'].includes(name))
+ merged = mergeText(b.replace(/\r\n/g, '\n'), l.replace(/\r\n/g, '\n'), r.replace(/\r\n/g, '\n'));
+ if (merged !== undefined && merged.length <= (name.endsWith('Html') ? 64000 : 16000)) fields[name] = merged;
+ else { fields[name] = l; conflicts.push(name); }
+ }
+ return { fields, conflicts };
+ }
+ async function conflictError(conflicts) {
+ if (!conflicts.length) return undefined;
+ const copy = await mailCopy();
+ const labels = [...new Set(conflicts.map(n => copy[n.replace(/Html$/, '')] || n))];
+ return { ok: false, execution: 'not_executed', stale: true, conflicts,
+ message: copy.recoveryConflict.replace('{fields}', labels.join(' / ')) };
+ }
+ // Rebuild volatile editor state from the provider's saved draft, using only
+ // the persisted routing identity. Concurrent keystrokes share this read.
+ async function restoreMailDraft(key, callId, sourceCallId) {
+ return navigator.locks.request('mail-restore:' + key, async function () {
+ if (mailEdits.has(key)) return true;
+ const record = (await mailRecords())[key];
+ if (!record || record.callId !== callId || record.state !== 'draft') return false;
+ const saved = await cindy.send({ type: 'mail-draft-read', callId, ...(sourceCallId ? { sourceCallId } : {}) });
+ const card = saved?.ok && saved.draft;
+ if (!card || card.key !== key || card.accountId !== record.account || card.draftId !== record.draftId) return false;
+ const account = await adapter.selectAccount(record.account);
+ if (!account.ok) throw new Error('Mail account unavailable');
+ const result = await adapter.readDraft({ record: { ...record }, sourceCallId });
+ const readBack = result?.ok && result.data?.readBack;
+ if (!readBack || readBack.status !== 'read_back' || readBack.draftId !== record.draftId || !readBack.editor) throw new Error('Mail draft unavailable');
+ const remote = draftValues(readBack);
+ const local = { ...remote, ...Object.fromEntries(card.fields.map(f => [f.name, f.value])) };
+ // Legacy clean cards are their own last synchronized snapshot. A legacy
+ // error without a base can still converge when both contents are equal.
+ const base = card.baseValues || (card.state === 'draft' ? local :
+ ['syncing', 'sending'].includes(card.state) && readBack.fingerprint === record.fingerprint ? remote : undefined);
+ const merged = mergeFields(base, local, remote);
+ const active = await mailRecords(records => {
+ const current = records[key];
+ if (!current || current.callId !== callId || current.state !== 'draft' || current.fingerprint !== record.fingerprint) return false;
+ current.locator = readBack.locator;
+ current.fingerprint = readBack.fingerprint;
+ return true;
+ });
+ if (!active) return false;
+ mailEdits.set(key, { fields: merged.fields, revision: sameFields(merged.fields, remote) ? 0 : 1,
+ savedRevision: 0, callId, readBack, error: await conflictError(merged.conflicts),
+ inputFields: local, conflictBase: merged.conflicts.length ? base : undefined });
+ return true;
+ });
+ }
+ async function showMailDraft(
+ message,
+ account,
+ readBack,
+ note,
+ settledKey,
+ edits,
+ renderOnly,
+ unconfirmed,
+ ) {
+ var copy = await mailCopy();
+ if (!readBack || readBack.status !== "read_back") return false;
+ var editor = readBack.editor;
+ const originalValues = editor ? draftValues(readBack) : {};
+ const formatted = editor && adapter.richText && !renderOnly ? formatMailFields(edits || originalValues, undefined, editor.format) : undefined;
+ if (formatted) {
+ edits = formatted.fields;
+ if (formatted.issue) note = copy[formatted.issue];
+ else if (!sameFields(edits, originalValues)) note ||= copy.syncing;
+ }
+ var fields = ["to", "cc", "bcc", "subject", "body", "quote"].map(
+ function (name) {
+ return {
+ name: name,
+ label: copy[name],
+ value: originalValues[name] || '',
+ ...(name === "body" || name === "quote" ? { multiline: true } : {}),
+ ...(name === "to" || name === "cc" ? { row: "recipients" } : {}),
+ ...(["to", "cc", "bcc"].includes(name)
+ ? { kind: "recipients" }
+ : {}),
+ ...(name === "quote" || (name === "bcc" && !readBack.headers.bcc)
+ ? { collapsed: true }
+ : {}),
+ };
+ },
+ );
+ if (adapter.richText === true && editor) {
+ if (editor.format !== 'text') fields.find(f => f.name === 'body').kind = 'hidden';
+ fields.push({ name: 'bodyHtml', label: copy.body, kind: editor.format === 'text' ? 'hidden' : 'mail-html', value: originalValues.bodyHtml });
+ fields.push({ name: 'quoteHtml', label: copy.quote, kind: 'hidden', value: originalValues.quoteHtml });
+ fields.push({ name: 'attachmentItems', label: 'Attachments', kind: 'mail-attachments', value: originalValues.attachmentItems });
+ }
+ if (edits)
+ fields.forEach(function (field) {
+ field.value = edits[field.name];
+ });
+ // New messages have no quote section. Keep the complete value set internally
+ // so hiding an empty quote never changes the draft sent to the worker.
+ var values = Object.fromEntries(fields.map((f) => [f.name, f.value]));
+ fields = fields.filter(function (field) {
+ return field.name !== "quote" || field.value;
+ });
+ var key = renderOnly ? settledKey : crypto.randomUUID();
+ if (!editor || (!editor.editable && !adapter.richText) || fields.some(f => typeof f.value !== 'string' || f.value.length > (f.name.endsWith('Html') ? 64000 : 16000))) return false;
+ const activeEdit = mailEdits.get(key);
+ var draft = { accountId: account.accountId, draftId: readBack.draftId, key,
+ ...(activeEdit?.error?.stale && !activeEdit.conflictBase ? {} : { baseValues: activeEdit?.conflictBase || originalValues }),
+ from: readBack.headers.from || account.accountEmail, fields,
+ attachments: readBack.attachments.map(a => a.filename || a.mimeType || ""),
+ ...(readBack.images ? { images: readBack.images } : {}),
+ state: unconfirmed ? "unconfirmed" : note === copy.syncing ? "syncing" : note ? "error" : "draft",
+ status: note || copy.saved, sendLabel: copy.send, fromLabel: copy.from,
+ ...(typeof adapter.deleteDraft === "function" ? { deleteLabel: copy.delete } : {}) };
+ if (!renderOnly)
+ await mailRecords(function (records) {
+ if (
+ Object.keys(records).some(function (id) {
+ return (
+ id !== settledKey &&
+ records[id].account === account.accountId &&
+ records[id].draftId === readBack.draftId &&
+ records[id].state !== "draft"
+ );
+ })
+ ) {
+ throw new Error("此草稿有待核对的操作,请先检查邮箱。");
+ }
+ // A newly read version supersedes older buttons for this saved draft.
+ Object.keys(records).forEach(function (id) {
+ if (
+ records[id].account === account.accountId &&
+ records[id].draftId === readBack.draftId
+ ) {
+ cancelMailSend(id);
+ clearTimeout(mailEdits.get(id)?.timer);
+ mailEdits.delete(id);
+ delete records[id];
+ }
+ });
+ records[key] = {
+ account: account.accountId,
+ draftId: readBack.draftId,
+ fingerprint: readBack.fingerprint,
+ locator: readBack.locator,
+ callId: message.callId,
+ state: "draft",
+ };
+ });
+ if (!renderOnly)
+ mailEdits.set(key, {
+ fields: values,
+ revision: sameFields(values, originalValues) ? 0 : 1,
+ savedRevision: 0,
+ callId: message.callId,
+ readBack: readBack,
+ ...(formatted?.issue ? { error: { ok: false, execution: 'not_executed', format: true, message: copy[formatted.issue] } } : {}),
+ });
+ const presented = await cindy.send({ type: "mail-draft-update", callId: message.callId,
+ ...(message.sourceCallId ? { sourceCallId: message.sourceCallId } : {}), draft });
+ const created = !renderOnly && mailEdits.get(key);
+ if (presented?.ok && created && !created.error && created.revision !== created.savedRevision)
+ created.timer = setTimeout(() => runMailDraft(key, false).catch(() => mailStatus(message.callId, copy.failed)), 1100);
+ return presented?.ok === true;
+ }
+ async function continueMailTask(message, record, copy, key) {
+ var result;
+ try {
+ if (
+ message.userActionToken &&
+ cindy.agent &&
+ typeof cindy.agent.run === "function"
+ )
+ result = await cindy.agent.run({
+ mode: "continue",
+ userActionToken: message.userActionToken,
+ // The card already shows the outcome. Reuse the shared synthetic
+ // input marker so desktop/mobile hide this internal continuation.
+ promptTemplate: "[UI_ACTION_TRIGGER]{{user_message}}\n{{event_json}}",
+ userMessage:
+ "用户已在邮件草稿卡片点击发送,邮箱服务已接受发送请求。请根据回执继续原任务,不要重复发送,也不要把接受请求说成已送达。用户可能修改过草稿;需要描述实际邮件内容时,通过此邮箱插件读取已发送邮件,不沿用之前的草稿。",
+ event: {
+ provider: adapter.providerName,
+ account: record.account,
+ draftId: record.draftId,
+ receipt: record.receipt,
+ },
+ });
+ } catch (_) {
+ /* Sending already succeeded; never turn this into a send retry. */
+ }
+ await mailStatus(
+ message.callId,
+ result && result.ok
+ ? copy.sent + " · " + copy.continued
+ : copy.continueFailed,
+ result && result.ok
+ ? ""
+ : copy.continue,
+ false, undefined, "sent",
+ );
+ }
+ // Both UI sends and Agent draft sends enter this same per-draft operation.
+ // Change events capture text immediately; only adapter writes are debounced.
+ async function runMailDraft(key, send, sourceCallId) {
+ return navigator.locks.request("mail-compose:" + key, async function () {
+ var record = (await mailRecords())[key];
+ if (!record)
+ return {
+ ok: false,
+ execution: "not_executed",
+ message: "草稿卡片已失效,请重新读取。",
+ };
+ if (record.state === "deleted" || mailEdits.get(key)?.deleting)
+ return { ok: false, execution: "not_executed", message: "草稿已删除或正在删除,不能保存或发送。" };
+ if (record.state === "sent")
+ return {
+ ok: true,
+ data: {
+ ...record.receipt,
+ receipt: record.receipt,
+ sent: true,
+ alreadySent: true,
+ draftId: record.draftId,
+ },
+ };
+ if (record.state !== "draft")
+ return {
+ ok: false,
+ execution: "unknown",
+ message: "之前操作的结果尚未确认,请先检查邮箱,未再次发送。",
+ };
+ var selected = await adapter.selectAccount(record.account);
+ if (!selected.ok)
+ return {
+ ok: false,
+ execution: "not_executed",
+ message: selected.message,
+ };
+ var edit = mailEdits.get(key);
+ if (!edit)
+ return {
+ ok: false,
+ execution: "not_executed",
+ message: "请重新读取草稿后再操作。",
+ };
+ clearTimeout(edit.timer);
+ edit.timer = undefined;
+ if (edit.error) return edit.error;
+ var result;
+ var rebased = false;
+ do {
+ if (adapter.richText) {
+ const formatted = formatMailFields(edit.fields, edit.additions, edit.readBack.editor.format);
+ if (!sameFields(formatted.fields, edit.fields)) { edit.fields = formatted.fields; edit.revision++; }
+ if (formatted.issue) {
+ edit.error = { ok: false, execution: 'not_executed', format: true, message: (await mailCopy())[formatted.issue] };
+ await showMailDraft({ callId: record.callId, sourceCallId }, selected, edit.readBack, edit.error.message, key, edit.fields, true);
+ return edit.error;
+ }
+ }
+ var revision = edit.revision;
+ var fields = { ...edit.fields };
+ var additions = (edit.additions || []).slice();
+ var sending = send && revision === edit.savedRevision;
+ if (!send && revision === edit.savedRevision)
+ return {
+ ok: true,
+ data: { draftId: record.draftId, readBack: edit.readBack },
+ };
+ if (sending) edit.sending = true;
+ record.state = "pending";
+ await mailRecords(function (records) {
+ records[key] = record;
+ });
+ if (sending) {
+ await showMailDraft({ callId: record.callId, sourceCallId }, selected, edit.readBack, undefined, key, fields, true);
+ await mailStatus(
+ record.callId,
+ (await mailCopy()).busy,
+ "",
+ true,
+ sourceCallId,
+ );
+ }
+ var response = undefined;
+ try {
+ response = await adapter.writeDraft({
+ record: { ...record },
+ account: selected,
+ fields: fields,
+ attachments: additions,
+ readBack: edit.readBack,
+ send: sending,
+ sourceCallId: sourceCallId,
+ });
+ } catch (_) {
+ /* Unknown write: keep pending and never replay it. */
+ }
+ result = response || {
+ ok: false,
+ execution: "unknown",
+ message: "无法确认邮箱操作结果,请先检查邮箱,未再次发送。",
+ };
+ if (
+ result.ok &&
+ (sending
+ ? result.data?.sent !== true ||
+ !result.data.receipt ||
+ typeof result.data.receipt !== "object" ||
+ Array.isArray(result.data.receipt)
+ : result.data?.readBack?.status !== "read_back" ||
+ result.data.readBack.draftId !== record.draftId)
+ ) {
+ result = {
+ ok: false,
+ execution: "unknown",
+ message: "邮箱返回的操作回执不完整,请核对邮箱,未再次发送。",
+ };
+ }
+ if (!result.ok) {
+ edit.sending = false;
+ // Retry only a provider-confirmed non-execution. Unknown writes and
+ // sends retain the existing terminal protection; never replay them.
+ if (!rebased && result.execution === 'not_executed' && result.stale) {
+ let latest = typeof result.stale === 'object' ? result.stale : undefined;
+ if (!latest) {
+ const fetched = await adapter.readDraft({ record: { ...record }, sourceCallId });
+ latest = fetched?.ok && fetched.data?.readBack;
+ }
+ if (latest?.status === 'read_back' && latest.draftId === record.draftId && latest.editor) {
+ const base = draftValues(edit.readBack), remote = draftValues(latest);
+ const merged = mergeFields(base, edit.fields, remote);
+ edit.inputFields = { ...edit.fields };
+ edit.fields = merged.fields;
+ edit.conflictBase = merged.conflicts.length ? base : undefined;
+ edit.readBack = latest;
+ edit.revision++;
+ edit.savedRevision = sameFields(merged.fields, remote) ? edit.revision : edit.revision - 1;
+ record.fingerprint = latest.fingerprint;
+ record.locator = latest.locator;
+ record.state = 'draft';
+ await mailRecords(records => { records[key] = record; });
+ edit.error = await conflictError(merged.conflicts);
+ if (!edit.error) {
+ rebased = true;
+ // Content learned after the countdown must be shown for a new
+ // full grace period; a metadata-only change can proceed.
+ if (sending && !sameFields(fields, merged.fields)) {
+ await showMailDraft({ callId: record.callId, sourceCallId }, selected, latest, undefined, key, edit.fields, true);
+ return { ok: true, restartCountdown: true };
+ }
+ result = { ok: true, data: { draftId: record.draftId, readBack: latest } };
+ continue;
+ }
+ result = edit.error;
+ }
+ }
+ edit.error = result;
+ if (result.execution === "not_executed") {
+ if (additions.length && !result.stale) {
+ edit.additions = (edit.additions || []).filter(a => !additions.includes(a));
+ for (const file of additions) if (file.contentId) {
+ edit.fields.bodyHtml = edit.fields.bodyHtml.replace(new RegExp('<p><img src="cid:' + file.contentId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '"[^>]*></p>', 'g'), '');
+ }
+ }
+ record.state = "draft";
+ await mailRecords(function (records) {
+ records[key] = record;
+ });
+ }
+ await showMailDraft(
+ { callId: record.callId, sourceCallId: sourceCallId },
+ selected,
+ edit.readBack,
+ result.message,
+ key,
+ edit.fields,
+ true,
+ );
+ return result;
+ }
+ if (result.data.sent) {
+ record.state = "sent";
+ record.receipt = result.data.receipt;
+ try {
+ await mailRecords(function (records) {
+ records[key] = record;
+ });
+ } catch (_) {
+ /* A known send is never retried. */
+ }
+ edit.sent = true;
+ if (sourceCallId)
+ await mailStatus(
+ record.callId,
+ (await mailCopy()).sent,
+ "",
+ false,
+ sourceCallId, "sent",
+ );
+ return result;
+ }
+ edit.readBack = result.data.readBack;
+ edit.conflictBase = undefined;
+ if (adapter.richText) {
+ edit.additions = (edit.additions || []).filter(a => !additions.includes(a));
+ if (edit.fields.attachmentItems === fields.attachmentItems) edit.fields.attachmentItems = draftValues(edit.readBack).attachmentItems;
+ if (edit.fields.bodyHtml === fields.bodyHtml) edit.fields.bodyHtml = edit.readBack.editor.bodyHtml || '';
+ if (edit.fields.quote === fields.quote) edit.fields.quoteHtml = edit.readBack.editor.quoteHtml || '';
+ }
+ edit.savedRevision = revision;
+ record.fingerprint = edit.readBack.fingerprint;
+ record.locator = edit.readBack.locator;
+ record.state = "draft";
+ await mailRecords(function (records) {
+ records[key] = record;
+ });
+ if (adapter.richText) {
+ const actual = draftValues(edit.readBack), verified = formatMailFields(actual, undefined, edit.readBack.editor.format);
+ if (verified.issue || !sameFields(verified.fields, actual)) {
+ edit.error = { ok: false, execution: 'not_executed', format: true, message: (await mailCopy()).formatNotRetained };
+ await showMailDraft({ callId: record.callId, sourceCallId }, selected, edit.readBack, edit.error.message, key, edit.fields, true);
+ return edit.error;
+ }
+ }
+ } while (send || edit.savedRevision !== edit.revision);
+ await showMailDraft(
+ { callId: record.callId, sourceCallId: sourceCallId },
+ selected,
+ edit.readBack,
+ undefined,
+ key,
+ edit.fields,
+ true,
+ );
+ return result;
+ });
+ }
+ // Deletion shares the save/send lock and uses the latest provider locator.
+ // Discard pending edits instead of writing them back before deleting.
+ async function deleteMailDraft(key, sourceCallId) {
+ if (typeof adapter.deleteDraft !== "function")
+ return { ok: false, execution: "not_executed", message: "此邮箱插件尚不支持删除草稿。" };
+ const edit = mailEdits.get(key);
+ if (edit?.sending)
+ return { ok: false, execution: "not_executed", message: "邮件正在发送,不能删除草稿。" };
+ cancelMailSend(key, { ok: false, execution: "not_executed", cancelled: true,
+ message: "用户已删除草稿,发送已取消。不要自动重新创建或发送。" });
+ if (edit) { edit.deleting = true; clearTimeout(edit.timer); edit.timer = undefined; }
+ return navigator.locks.request("mail-compose:" + key, async function () {
+ const record = (await mailRecords())[key], copy = await mailCopy();
+ if (!record || record.state === "sent") {
+ if (edit) edit.deleting = false;
+ return { ok: false, execution: "not_executed", message: "草稿不存在或已发送,不能删除。" };
+ }
+ if (record.state === "deleted")
+ return { ok: true, data: { deleted: true, alreadyDeleted: true, draftId: record.draftId } };
+ if (record.state !== "draft")
+ return { ok: false, execution: "unknown", message: "之前操作结果尚未确认,请先检查邮箱,未执行删除。" };
+ let result, deleteStarted = false;
+ try {
+ // Show progress before account refresh/read-back (which may fetch large
+ // attachments). A delete discards this logical draft, not one revision.
+ await mailStatus(record.callId, copy.deleting, "", true, sourceCallId, "deleting");
+ const account = await adapter.selectAccount(record.account);
+ if (!account.ok) result = { ...account, execution: "not_executed" };
+ else {
+ const latest = await adapter.readDraft({ record: { ...record }, sourceCallId });
+ if (!latest?.ok || latest.data?.readBack?.status !== "read_back" ||
+ latest.data.readBack.draftId !== record.draftId)
+ result = { ok: false, execution: "not_executed", message: latest?.message || copy.deleteFailed };
+ else {
+ record.locator = latest.data.readBack.locator;
+ record.fingerprint = latest.data.readBack.fingerprint;
+ record.state = "pending";
+ await mailRecords(records => { records[key] = record; });
+ deleteStarted = true;
+ result = await adapter.deleteDraft({ record: { ...record }, account, sourceCallId });
+ if (result?.ok && result.data?.deleted !== true) result = undefined;
+ }
+ }
+ } catch (_) {
+ // Failed preparation made no destructive request and can be retried.
+ // Once handed to the provider, an uncertain delete is never replayed.
+ if (!deleteStarted) result = { ok: false, execution: "not_executed", message: copy.deleteFailed };
+ }
+ result ||= { ok: false, execution: "unknown", message: "无法确认草稿是否已删除,请先检查邮箱,不要重复操作。" };
+ record.state = result.ok ? "deleted" : result.execution === "not_executed" ? "draft" : "pending";
+ if (edit) {
+ edit.deleting = record.state !== "draft";
+ if (!result.ok) edit.error = result;
+ if (result.ok) edit.additions = [];
+ }
+ await mailRecords(records => { records[key] = record; });
+ await mailStatus(record.callId, result.ok ? copy.deleted : result.message || copy.failed,
+ "", false, sourceCallId, result.ok ? "deleted" : record.state === "draft" ? "error" : "unconfirmed");
+ return result;
+ });
+ }
+ // The provider is never called with send=true until this in-memory grace
+ // period settles. Restarting the sandbox cannot resume an unattended send.
+ function cancelMailSend(key, result) {
+ const edit = mailEdits.get(key), pending = edit?.pendingSend;
+ if (!pending || pending.phase === "sending") return false;
+ pending.phase = "cancelled";
+ clearTimeout(pending.timer);
+ edit.pendingSend = undefined;
+ pending.resolve(result || { ok: false, execution: "not_executed", cancelled: true,
+ message: "用户已撤销发送,草稿已保留。不要自动重试发送,等待用户新的指示。" });
+ return true;
+ }
+ function requestMailSend(key, sourceCallId) {
+ const edit = mailEdits.get(key);
+ if (!edit || edit.sent) return runMailDraft(key, true, sourceCallId);
+ if (edit.pendingSend) return edit.pendingSend.promise.then(result =>
+ result.ok && result.data?.sent ? { ...result, data: { ...result.data, alreadySent: true } } : result);
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ const pending = { promise, resolve, phase: "preparing", sourceCallId };
+ edit.pendingSend = pending;
+ pending.finish = async function () {
+ if (edit.pendingSend !== pending || pending.phase !== "waiting") return;
+ pending.phase = "sending";
+ edit.sending = true;
+ clearTimeout(pending.timer);
+ try {
+ const result = await runMailDraft(key, true, sourceCallId);
+ if (result.restartCountdown) {
+ edit.sending = false;
+ pending.phase = 'preparing';
+ await prepare();
+ return;
+ }
+ resolve(result);
+ }
+ catch (_) {
+ resolve({ ok: false, execution: "unknown", message: "无法确认发送结果,请核对邮箱,不要重复发送。" });
+ } finally {
+ if (edit.pendingSend === pending && pending.phase === 'sending') edit.pendingSend = undefined;
+ }
+ };
+ async function prepare() {
+ try {
+ const saved = await runMailDraft(key, false, sourceCallId);
+ if (edit.pendingSend !== pending) return;
+ if (!saved.ok || saved.data?.sent) { edit.pendingSend = undefined; resolve(saved); return; }
+ // Restoration may adopt remote-only changes without any write. Show
+ // that exact content before starting the grace period, including AI sends.
+ const record = (await mailRecords())[key];
+ const account = record && await adapter.selectAccount(record.account);
+ if (!account?.ok || !await showMailDraft({ callId: edit.callId, sourceCallId }, account,
+ edit.readBack, undefined, key, edit.fields, true)) throw new Error('Draft preview unavailable');
+ const copy = await mailCopy();
+ if (edit.pendingSend !== pending) return;
+ const deadline = Date.now() + 10000;
+ const shown = await mailStatus(edit.callId, copy.countdown.replace("{seconds}", "10"), "", true,
+ sourceCallId, "sending", { deadline, label: copy.countdown, cancelLabel: copy.cancel, sendNowLabel: copy.sendNow });
+ if (edit.pendingSend !== pending) return;
+ if (!shown?.ok) throw new Error("Countdown card unavailable");
+ pending.phase = "waiting";
+ // Give the user the full grace period after the card was accepted.
+ pending.timer = setTimeout(pending.finish, 10000);
+ } catch (_) {
+ if (edit.pendingSend === pending) {
+ cancelMailSend(key, { ok: false, execution: "not_executed", message: "无法展示发送倒计时,邮件未发送。请重新读取草稿。" });
+ await mailStatus(edit.callId, (await mailCopy()).failed, "", false, sourceCallId, "error");
+ }
+ }
+ }
+ void prepare();
+ return promise;
+ }
+ async function handleMailCard(message) {
+ var match = /^mail:(change|send|continue|cancel|now|attach|image|delete):([a-f0-9-]{36})$/.exec(
+ message.actionId || "",
+ );
+ if (!match || (message.formChange === true) !== (match[1] === "change"))
+ return;
+ var key = match[2];
+ var edit = mailEdits.get(key);
+ if (!edit && ['change', 'send', 'attach', 'image', 'cancel', 'now'].includes(match[1])) {
+ await restoreMailDraft(key, message.callId);
+ edit = mailEdits.get(key);
+ }
+ if (edit?.deleting && match[1] !== "delete") return;
+ if (
+ ["change", "send", "attach", "image"].includes(match[1]) &&
+ edit &&
+ edit.callId === message.callId &&
+ (!message.formValues ||
+ ["to", "cc", "bcc", "subject", "body"].some(
+ (name) => typeof message.formValues[name] !== "string",
+ ) ||
+ (edit.fields.quote && typeof message.formValues.quote !== "string"))
+ ) {
+ await mailStatus(message.callId, (await mailCopy()).unavailable);
+ return;
+ }
+ // Capture before the first await so a following model tool sees the keystroke.
+ if (
+ ["change", "send", "attach", "image"].includes(match[1]) &&
+ edit &&
+ edit.callId === message.callId &&
+ !edit.sent &&
+ !edit.sending &&
+ message.formValues &&
+ Object.keys(message.formValues).some(
+ (name) => message.formValues[name] !== edit.fields[name],
+ )
+ ) {
+ cancelMailSend(key);
+ const incoming = { ...edit.fields, ...message.formValues };
+ const base = edit.error?.stale ? edit.conflictBase : edit.inputFields || edit.fields;
+ const merged = mergeFields(base, incoming, edit.error?.stale ? draftValues(edit.readBack) : edit.fields);
+ // The quote text field edits the outgoing quote too. Preserve authored
+ // HTML unless that text changed, including an explicit deletion.
+ if (adapter.richText && incoming.quote !== base?.quote && incoming.quoteHtml === base?.quoteHtml) {
+ merged.fields.quoteHtml = merged.fields.quote
+ ? '<div>' + merged.fields.quote.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r\n?|\n/g, '<br>') + '</div>'
+ : '';
+ }
+ edit.conflictBase = merged.conflicts.length ? base : undefined;
+ edit.fields = merged.fields;
+ edit.inputFields = incoming;
+ edit.revision++;
+ if (!edit.error || edit.error.execution === 'not_executed') edit.error = await conflictError(merged.conflicts);
+ }
+ if (['attach', 'image'].includes(match[1]) && adapter.richText && edit && !edit.sent && !edit.sending && message.mailAttachment) {
+ cancelMailSend(key);
+ if (edit.error?.execution === 'not_executed' && !edit.error.stale) edit.error = undefined;
+ edit.additions = [...(edit.additions || []), message.mailAttachment];
+ if (message.mailAttachment.contentId) {
+ const alt = message.mailAttachment.filename.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
+ edit.fields.bodyHtml += '<p><img src="cid:' + message.mailAttachment.contentId + '" alt="' + alt + '" style="max-width:100%"></p>';
+ }
+ edit.revision++;
+ }
+ var record = (await mailRecords())[key];
+ if (!record || record.callId !== message.callId) return;
+ if (match[1] === "delete") { await deleteMailDraft(key); return; }
+ if (record.state === "deleted") return;
+ var copy = await mailCopy();
+ if (match[1] === "continue" && record.state === "sent") {
+ await continueMailTask(message, record, copy, key);
+ return;
+ }
+ if (!edit) {
+ await mailStatus(record.callId, copy.missing);
+ return;
+ }
+ if (edit.error?.stale) {
+ const selected = await adapter.selectAccount(record.account);
+ if (selected.ok) await showMailDraft({ callId: record.callId }, selected, edit.readBack, edit.error.message, key, edit.fields, true);
+ return;
+ }
+ if (
+ match[1] === "change" &&
+ (record.state === "sent" || edit.sent || edit.sending)
+ )
+ return;
+ if (match[1] === "cancel" || match[1] === "now") {
+ if (record.state !== "draft" || edit.sent || edit.sending) return;
+ if (match[1] === "now" && edit.pendingSend) {
+ await edit.pendingSend.finish();
+ } else if (cancelMailSend(key) || !edit.pendingSend) {
+ // After restart the persisted countdown has no live send behind it.
+ // Restore a draft; a new send request must start a fresh grace period.
+ const selected = await adapter.selectAccount(record.account);
+ if (selected.ok) await showMailDraft({ callId: record.callId },
+ selected, edit.readBack, undefined, key, edit.fields, true);
+ }
+ return;
+ }
+ clearTimeout(edit.timer);
+ if (["change", "attach", "image"].includes(match[1])) {
+ if (!edit.timer) {
+ var selected = await adapter.selectAccount(record.account);
+ if (selected.ok)
+ await showMailDraft(
+ { callId: record.callId },
+ selected,
+ edit.readBack,
+ copy.syncing,
+ key,
+ edit.fields,
+ true,
+ );
+ }
+ edit.timer = setTimeout(
+ () =>
+ runMailDraft(key, false).catch(() =>
+ mailStatus(record.callId, copy.failed),
+ ),
+ 1100,
+ );
+ return;
+ }
+ var result = await requestMailSend(key);
+ if (result.ok && result.data.sent && !result.data.alreadySent) {
+ record = { ...record, state: "sent", receipt: result.data.receipt };
+ await continueMailTask(message, record, copy, key);
+ }
+ }
+ // Provider tool names and argument schemas stay in the adapter. null means the
+ // caller can proceed with its ordinary operation after pending edits are saved.
+ async function beforeTool(args) {
+ var { operation, account, draftId, sourceCallId, readOnly } = args;
+ if (!["get", "send", "update", "delete"].includes(operation))
+ throw new Error("Unsupported draft operation");
+ var records = await mailRecords();
+ var key = Object.keys(records).find(
+ (id) =>
+ records[id].account === account && records[id].draftId === draftId,
+ );
+ if (!key) return operation === "send" ? { ok: false, execution: "not_executed",
+ message: "请先读取草稿并展示卡片,再通过公共邮件流程发送。" } : null;
+ // Uncertain writes must block repeat writes, not the read needed to inspect
+ // the mailbox. Keep the receipt record intact and expose a read-only view.
+ if (operation === "get" && records[key].state === "pending") {
+ const latest = await adapter.readDraft({ record: { ...records[key] }, sourceCallId });
+ if (latest?.ok && latest.data?.readBack?.status === "read_back" && sourceCallId && readOnly === false) {
+ const selected = await adapter.selectAccount(account);
+ if (selected.ok) latest.data.draftCard = await showMailDraft(
+ { callId: sourceCallId }, selected, latest.data.readBack,
+ (await mailCopy()).failed, key, undefined, true, true,
+ );
+ }
+ return latest || { ok: false, execution: "not_executed", message: "无法读取当前草稿,请稍后再试。" };
+ }
+ if (readOnly !== false) {
+ if (
+ operation !== "get" ||
+ mailEdits.get(key)?.revision !== mailEdits.get(key)?.savedRevision
+ )
+ return {
+ ok: false,
+ execution: "not_executed",
+ message: "只读任务不能同步或发送草稿。",
+ };
+ return null;
+ }
+ if (operation === "delete" && typeof adapter.deleteDraft === "function")
+ return deleteMailDraft(key, sourceCallId);
+ if (records[key].state === "deleted")
+ return { ok: false, execution: "not_executed", message: "草稿已删除,不能继续操作。" };
+ if (!mailEdits.has(key)) {
+ const record = records[key];
+ if (record.state === "sent" || record.state === "pending")
+ return runMailDraft(key, operation === "send", sourceCallId);
+ if (!await restoreMailDraft(key, record.callId, sourceCallId)) {
+ // A different task can read the provider draft without taking over an
+ // old task's card. Sending still requires a current, owned card.
+ if (operation === 'get') return null;
+ return { ok: false, execution: 'not_executed', message: '暂时无法连接原草稿,请稍后再试。' };
+ }
+ }
+ if (operation !== "send") cancelMailSend(key);
+ // An explicit model update can resolve a conflict using the latest provider
+ // version. Reads below expose both versions; automatic sends remain blocked.
+ if (operation === 'update' && (mailEdits.get(key)?.error?.stale || mailEdits.get(key)?.error?.format)) return null;
+ var result = operation === "send" ? await requestMailSend(key, sourceCallId) :
+ operation === "get" &&
+ mailEdits.get(key)?.error?.execution === "not_executed"
+ ? { ok: true }
+ : await runMailDraft(key, operation === "send", sourceCallId);
+ if (operation === "get" && result.ok) {
+ // Saving can change an IMAP locator; read the latest record, not the old UID.
+ var record = (await mailRecords())[key];
+ var latest = await adapter.readDraft({
+ record: { ...record },
+ sourceCallId,
+ });
+ if (!latest)
+ return {
+ ok: false,
+ execution: "not_executed",
+ message: "无法读取当前草稿,请稍后再试。",
+ };
+ // Reading a conflict must expose both versions to the assistant without
+ // replacing the card and silently discarding the user's local edits.
+ const edit = mailEdits.get(key);
+ if (edit?.error?.stale && latest.ok) return { ...latest, data: { ...latest.data,
+ cardEdits: { ...edit.fields }, conflicts: edit.error.conflicts || [] } };
+ if (
+ latest.ok &&
+ latest.data.readBack?.status === "read_back" &&
+ sourceCallId
+ ) {
+ // Inspecting a draft before editing it must not move an unchanged
+ // snapshot to the latest turn. Verify its task ownership with the host;
+ // another task still gets its own card. Adopt fresh provider locators
+ // even when the visible document did not change.
+ const saved = await cindy.send({ type: 'mail-draft-read', callId: record.callId, sourceCallId });
+ const currentEdit = mailEdits.get(key);
+ if (saved?.ok && saved.draft?.key === key && currentEdit &&
+ currentEdit.revision === currentEdit.savedRevision &&
+ currentEdit.readBack.editor?.format === latest.data.readBack.editor?.format &&
+ sameFields(currentEdit.fields, draftValues(latest.data.readBack))) {
+ currentEdit.readBack = latest.data.readBack;
+ await mailRecords(records => {
+ if (records[key]?.fingerprint !== record.fingerprint) return;
+ records[key].fingerprint = latest.data.readBack.fingerprint;
+ records[key].locator = latest.data.readBack.locator;
+ });
+ return latest;
+ }
+ var selected = await adapter.selectAccount(account);
+ if (selected.ok)
+ await showMailDraft(
+ { callId: sourceCallId }, selected, latest.data.readBack,
+ );
+ }
+ return latest;
+ }
+ return operation === "send" || !result.ok ? result : null;
+ }
+ cindy.onHostMessage(async function (message) {
+ if (message?.type !== "event" || message.name !== "card-action" || !message.actionId?.startsWith("mail:")) return;
+ try { await handleMailCard(message); }
+ catch (_) { await mailStatus(message.callId, (await mailCopy()).failed); }
+ });
+ return {
+ present: (message, account, snapshot) =>
+ showMailDraft(message, account, snapshot),
+ beforeTool,
+ // IMAP save can replace a UID. Adapters performing update/delete after
+ // beforeTool must resolve the current locator rather than use an older UID.
+ resolveDraft: async function (account, draftId) {
+ return (
+ Object.values(await mailRecords()).find(
+ (record) =>
+ record.account === account && record.draftId === draftId,
+ ) || null
+ );
+ },
+ handleCard: async function (message) {
+ try {
+ await handleMailCard(message);
+ } catch (_) {
+ await mailStatus(message.callId, (await mailCopy()).failed);
+ }
+ },
+ };
+ }
+ return { version: 1, sendGraceMs: 10000, register: create };
+})();
diff --cc apps/desktop/src/preload/preload.ts
index dced5b1a95,d63781eace..0de43cffec
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@@ -1252,7 -1253,12 +1253,13 @@@ contextBridge.exposeInMainWorld('electr
// 意识仓库 (shared/ghost.ts)。listSync 走 sendSync:意识面板要与内置
// 面板同帧注册进布局引擎(规则 7 无跳变);目录扫描极小,同步读不卡启动。
ghosts: {
+ mailPreview: (sessionId: string, url: string, read: boolean, opened = false) => ipcRenderer.invoke('ghosts:mail-preview', sessionId, url, read, opened),
+ openRemoteSettings: (target: import('../shared/remotePluginSettings').RemotePluginSettingsTarget): Promise<import('../shared/remotePluginSettings').RemotePluginSettingsView> =>
+ ipcRenderer.invoke('device-link:plugin-settings:open', target),
+ closeRemoteSettings: (id: string): Promise<void> => ipcRenderer.invoke('device-link:plugin-settings:close', id),
+ onRemoteSettingsDirectory: fanOutRemoteSettingsDirectory,
+ answerRemoteSettingsDirectory: (answer: import('../shared/remotePluginSettings').RemotePluginSettingsDirectoryAnswer): Promise<void> =>
+ ipcRenderer.invoke('device-link:plugin-settings:answer-directory', answer),
recommendationsSync:
(): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>
ipcRenderer.sendSync('ghosts:recommendations'),
diff --cc apps/desktop/src/renderer/vite-env.d.ts
index f9c92eed1a,f62088b116..8974d53558
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@@ -1275,7 -1275,10 +1275,11 @@@ interface ElectronAPI
/** 意识仓库 —— 数据模型与校验见 shared/ghost.ts,main 端见 main/cindy-brain/。 */
ghosts: {
+ mailPreview: (sessionId: string, url: string, read: boolean, opened?: boolean) => Promise<{ supported: boolean; message?: import('@cindy/maker-shared/mail-message').MailMessage; error?: string }>;
+ openRemoteSettings: (target: import('../shared/remotePluginSettings').RemotePluginSettingsTarget) => Promise<import('../shared/remotePluginSettings').RemotePluginSettingsView>;
+ closeRemoteSettings: (id: string) => Promise<void>;
+ onRemoteSettingsDirectory: (callback: (value: import('../shared/remotePluginSettings').RemotePluginSettingsDirectory) => void) => () => void;
+ answerRemoteSettingsDirectory: (answer: import('../shared/remotePluginSettings').RemotePluginSettingsDirectoryAnswer) => Promise<void>;
recommendationsSync: () => import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot;
/** 首帧同步拉取已装清单(规则 7:意识面板与内置面板同帧注册,无跳变)。 */
listSync: () => { ghosts: import('../shared/ghost').InstalledGhost[] };
diff --cc docs/design-rules/design-inventory.md
index ed9255abbf,aeef2e8e54..fc677a1076
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@@ -37,11 -37,11 +37,11 @@@
| `desktop.overlay.splash` | desktop | 启动遮罩 | App → SplashScreen;同源 gating 下并挂 LoginBrandStage(z-9980 品牌画布,启动期即可见、Splash(z-9999) 之下) | LoginBrandStage, SplashScreen | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/splash/SplashScreen.tsx | 3 | 0 | 5 |
| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx, apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
- | `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 27 | 0 | 48 |
+ | `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginActions, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginDevicePicker, PluginManagementLayout, PluginProjectMenu, RemotePluginConfiguration, RemotePluginPage, RemotePluginReadOnlyDetail, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 28 | 0 | 47 |
| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 136 | 95 | 542 |
-| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 143 | 46 | 196 |
+| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 144 | 46 | 198 |
- | `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 35 | 0 | 43 |
- | `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 43 | 0 | 37 |
+ | `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginDevicePicker, PluginManagementLayout, RemoteSkillsPage, SkillCategoryFilterBar, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/skillhub-home.css | 39 | 0 | 45 |
+ | `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 42 | 0 | 35 |
| `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |
| `desktop.window.ghost-panel` | desktop | 插件面板独立窗口 | `?ghostPanelWindow=<id>` → renderer/ghost-panel-window-entry.tsx;hash `/ghost-panel-window` | GhostPanelWindowLayout | apps/desktop/src/main/ghost-panel-window/controller.ts, apps/desktop/src/main/ghost-panel-window/ipc.ts, apps/desktop/src/main/ghost-panel-window/registry.ts, apps/desktop/src/main/ghost-panel-window/settings-store.ts, apps/desktop/src/main/ghost-panel-window/window.ts, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/ghost-panel-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 77 | 38 | 15 |
| `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | Button, ConfirmDialog, FormField, Popover, RemoteDesktopViewerWindow, Select, Switch, Tip | apps/desktop/src/main/remote-desktop-viewer/connection.ts, apps/desktop/src/main/remote-desktop-viewer/credentials.ts, apps/desktop/src/main/remote-desktop-viewer/preferences.ts, apps/desktop/src/main/remote-desktop-viewer/registry.ts, apps/desktop/src/main/remote-desktop-viewer/resolutionMemory.ts, apps/desktop/src/main/remote-desktop-viewer/safety.ts, apps/desktop/src/main/remote-desktop-viewer/windows.ts, apps/desktop/src/renderer/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/popover.tsx, apps/desktop/src/renderer/components/ui/select-parts.tsx, apps/desktop/src/renderer/components/ui/select.css, apps/desktop/src/renderer/components/ui/select.tsx, apps/desktop/src/renderer/components/ui/switch.tsx, apps/desktop/src/renderer/components/ui/tooltip.tsx, apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx, apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css, apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 132 | 36 | 29 |
diff --cc docs/dev-rules/protocol-compatibility.md
index fc068146da,6eec8ce389..a868d630ce
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@@ -2307,191 -2339,6 +2387,196 @@@ Claude 原生 `user` 范围投影为 `g
伙伴资料快照 `companion.profile.v1` 新增可选的 `templateId`;新增偏好键 `companion.todo.v1:<id>`、`companion.routine.v1:<id>`、`companion.workbench.v1`,
旧客户端不认识这些键,接管时忽略。镜像上传的房间消息可带 `media` 块;旧客户端按文件名显示。手机端同样不改原生指纹。
+## Host-owned mail cards
+
+Manifest v3 adds optional `mail: true`. Cindy serves the versioned `cindyMail` SDK
+inside the provider sandbox before its entry point. Providers register mailbox
+adapters; they do not need `card` or generate HTML. The local pipe accepts validated
+`mail-draft-update` only from enabled mail providers with a live task-owned call.
+Cindy renders and persists the existing `ghost_cards` row; no database migration
+or relay version change. Old hosts lack the SDK: providers retain read-only tools
+and require a Cindy update before draft editing/sending, without a direct-send fallback.
+
+The host-only `data-cindy-mail` marker records account/draft identity, state and
+`supersededBy`. Ordinary plugin HTML cannot retain it. Autosave replaces one view;
+subsequent tool reads supersede matching provider/account/draft views in that task.
+Obsolete or legacy mail actions are rejected on the Host. Historical snapshots remain stored.
+The `plugin-card-actions` resource carries optional `mail` / `legacyMail` metadata;
+desktop and mobile clients hide superseded mail cards and their plugin labels, leaving
+only the latest card per provider/account/draft in that task, including sent/deleted
+states. Legacy cards without this metadata retain their read-only fallback.
+Old clients keep static fallback text
+and receive no obsolete actions. Existing form capability negotiation and task/owner
+checks still apply. Sent cards expose only optional task continuation, never send.
+Mail receipt continuations use the existing `[UI_ACTION_TRIGGER]` prefix: the
+Agent receives the complete receipt, while both clients hide the internal prompt
+from chat and session previews. The original mail card remains the visible result.
+
+Optional adapter `deleteDraft` adds a `deleteLabel` and `mail:delete:<key>` action
+to active drafts only. It requires no form values because pending edits are
+discarded. Deletion shares the per-draft save/send lock and cancels queued saves
+and send countdowns. It discards the logical draft even if its content/revision
+has changed, verifies the draft identity and refreshes the provider locator;
+save/send conflict checks do not apply to explicit discard. Progress is shown
+before provider read-back. Failed preparation remains retryable; a deletion
+with an unknown provider outcome is never replayed.
+Both clients treat `deleting` and terminal `deleted` as
+read-only; the Host rejects late edits/sends and cannot restore a deleted card.
+Unknown deletes stay locked until the mailbox is checked. Older adapters omit
+the button; older clients fall back to inert text for the new states. Existing
+remote action ownership/revision checks and the same card row carry this change.
+
+Oversized tool results retain validated top-level `xdt_card_id` and
+`xdt_anchor_card_id` in bounded valid JSON during persistence/import and remote
+history compaction. The card content remains in the existing card store; no new
+wire fields or schema are required. Uncorrelated live cards may only match calls
+in the latest visible user turn, so incomplete older history cannot steal them.
+
+Rich mail adapters opt in with `richText: true`; old adapters keep the existing
+plain-text contract. Host fields add `mail-html`, `mail-attachments` and `hidden`
+kinds, with `bodyHtml` / `quoteHtml` (64k characters) and `attachmentItems` (bounded
+JSON metadata). Ordinary text remains 16k. Only Host mail gets the 1 MiB card
+budget; arbitrary plugin HTML remains limited to 32 KiB. HTML previews are inert,
+sandboxed documents, not markup mounted in Cindy's privileged renderer DOM.
+Both clients block remote image sources and CSS fetches in mail previews; CSP
+permits only data and managed CID substitutions. Original outgoing HTML remains
+unchanged by this preview policy; remote images can be viewed in the mailbox.
+HTML supports typing directly into rendered text in both clients and the enlarged
+view, without an edit-mode button, formatting toolbar or source editor. Edits patch source text
+only, preserving styles, links and CID image references, and synchronize the
+plain-text alternative through the existing form autosave path. Sent/history
+cards stay read-only. `editor.format: 'text'` retains
+the existing compact plain-text input.
+
+The Host mail SDK owns outgoing formatting for all rich adapters. Before preview,
+autosave and send it extracts document wrappers into fragments, retains body
+attributes on a content container, derives absent text alternatives, supplies
+missing filename extensions from known MIME types, and reconnects managed preview
+URLs to their attachment CIDs. Missing/duplicate inline references stop sending.
++The same URL policy covers `src`, `background`, every `srcset` candidate, inline
++CSS and stylesheet `url(...)` in both the body and the quoted content.
+Normalized content is saved and read back before the existing countdown; adapter
+read-back must retain the normalized structure. Adapters honor supplied filenames,
+preserve MIME bytes/reply headers and verify the provider result. No new wire fields
+or SDK version are required; plain-text-only adapters retain their existing path.
+This is structural protection, not a guarantee of identical CSS rendering across
+email clients. Ordinary fragments and explicitly authored plain text are retained.
+
+Desktop attachment actions `mail:attach` / `mail:image` are native Host gestures,
+not plugin HTML controls. The dispatcher verifies current view, owner, mail
+capability and draft state before and after the native picker, and passes one
+transient hash/size-bound file descriptor to the provider event. No arbitrary
+path comes from form text. Selected desktop bytes are copied into the existing
+session-owned temporary attachment store; only the staged descriptor crosses
+the plugin boundary, never the user's original path. Source replacement after
+selection cannot change the staged bytes. Failed/stale delivery discards the
+copy; accepted files retain normal session/orphan cleanup. Pending or sent mail cannot open the picker. Mobile
+resource metadata adds optional `mailUpload`; old hosts omit it and new phones
+hide the upload button. Supporting hosts accept `mail:attach:<key>` with optional
+`input.mailAttachment: {url,name}` and the complete form. Only existing OSS/peer
+upload references with size and SHA-256 are accepted (16 MiB/file), never local
+paths. The existing task materializer owns downloads and session cleanup; owner,
+interaction lease and current draft state are checked before delivery. No new
+relay channel, native dependency, database or runtime fingerprint is introduced.
+Ordinary attachment removal retains the existing remote form delivery gate.
+Optional `mail.images` contains validated managed preview URLs keyed by CID;
+these URLs never replace CID references in the saved/sent message. The existing
+media-deposit ledger owns these image bytes; no new file store or database exists.
+Mobile resolves CID previews with the existing remote-media queue into data URLs
+inside a sanitized mail WebView whose CSP blocks all page scripts. Host-injected
+editing listeners send only a document revision, known text-run index and plain
+text; the native side validates those before applying source patches. Desktop
+uses parent-owned listeners in an iframe without script permission. Autosave
+echoes do not reload either editing surface. CID substitutions never enter form
+edits; missing images leave the rest of the email readable.
+Attachment items optionally carry `mimeType` and `previewUrl` (validated managed
+image URLs only). Both clients show file identity and size; image clicks use
+their existing viewers. Removing a CID image removes its part and image nodes,
+preserving the rest of the authored document. "Insert into message" assigns an
+available `[email protected]` CID to an existing image key and inserts an HTML
+image before the closing body tag. Adapters validate the actual bytes and write
+that existing part as inline without uploading a duplicate. Compare part keys
+and normalized Content-IDs, ignoring preview-only metadata when detecting edits.
+After sandbox restart, the next card edit/send (including model send) restores
+volatile state using the persisted account/draft/locator. It retains incoming
+form edits and the same card key. Optional `baseValues` in the existing host card
+retains the last synchronized values (not in plugin KV). The SDK's internal
+`mail-draft-read` uses the same plugin/call/session ownership as publication.
+It compares base, card edits and provider values: identical/one-sided changes and
+independent text ranges merge automatically, ignoring preview-only metadata.
+Unmergeable overlapping edits retain both versions and name the conflicting fields.
+Legacy clean cards supply their own base; legacy errors without a base converge
+only when contents agree. Pending/unknown/sent records never become drafts.
+Adapters may return `execution:not_executed` with `stale` read-back; the SDK can
+merge and retry once. Unknown writes never retry. Changed content discovered at
+send time is shown before a fresh countdown; metadata-only drift needs no prompt.
+Old clients ignore optional baseline values; existing remote form actions carry
+no new required fields. The host SDK, not mailbox plugins, owns recovery/merging.
+Recovery never resumes a previous countdown; a new send gets the full grace period.
+Reading an unchanged draft in the same task reuses its existing card without
+publishing another snapshot. The host verifies task ownership through
+`mail-draft-read`; a different task still receives its own card. Fresh provider
+fingerprints/locators are adopted even if visible content is unchanged. Desktop
+mail cards require an exact tool ID or settled result to anchor them; the generic
+same-plugin in-flight heuristic must not show old mail beneath a schema/read call.
+Desktop HTML previews retain head styles, class selectors and body presentation
+inside their inert sandbox. External CSS resources, scripts and navigation remain
+blocked; preview sanitization never mutates the saved HTML.
+
+### Read-only mail preview
+
+Mail providers may declare `mailReader: { tool, hosts }` alongside `mail: true`.
+`mail` accepts only omission or literal `true` in both v2 and v3; both validators
+reject a reader without `mail: true` or without its matching tool in `tools`.
+Desktop and plugin-protocol validate this known declaration and retain future
+extension 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 hosts
+and calls it with `{ url }`; the provider resolves the account and message without
+marking read or mutating drafts. Providers may opt in with `mailReader.markRead: true`
+and accept optional `markRead:true` on that same tool. The declaration permits only
+omission or literal `true`; `false`, strings, null and other values are invalid in
+both manifest validators. Runtime dispatch also requires literal `true`, including
+for declarations retained by older validators. Future unknown metadata remains
+preserved by manifest normalization and never grants permission. Only an explicit user opening
- passes it; AI reads, probes and neighboring preloads remain read-only. Restored
- inactive tabs and a hidden sidebar must not mark mail read merely by mounting.
++passes it; AI reads, probes and neighboring preloads remain read-only.
++The dispatcher strips `markRead` from ordinary tool arguments for the declared
++reader; only the trusted native-reader request may inject it after literal opt-in.
++Other explicitly authorized read-state tools retain their normal Agent path.
++Restored inactive tabs and a hidden sidebar must not mark mail read merely by mounting.
+Mark only the successfully resolved, visibly opened message, never the whole thread or drafts. A failed
+mark must retain the body and return `markReadFailed:true` for a non-blocking notice.
+It returns `MailMessage` (maker-shared/mail-message).
+Credentials and MIME parsing remain with the provider. Cindy validates the data
+and reuses its inert HTML/CID/recipient renderers, never compose actions. Multiple
+matching providers/accounts cannot silently select the first. Unknown providers or
+older hosts keep normal browser opening. Attachments use managed image previews;
+other file types retain their metadata and the mailbox opening fallback.
+
+Desktop uses a session-scoped sidebar tab. Mobile/same-account remote clients use
+the existing `mail-messages/message` remote resource, ID `[sessionId,url,read]`,
+primitive `mail-message`.
+Explicit opening adds optional `query:"open"` to resource get, or optional fourth
+`opened:true` to `ghosts:mail-preview`; resource IDs and default read behavior stay
+unchanged. Old hosts ignore the new optional values; old providers still receive
+only `{url}`. No new channel, storage or native changes. Plugins adding an OAuth
+scope must keep existing granted operations usable; missing new scopes may fail
+marking read, not prevent viewing or composing.
+Existing 256-character resource ID bounds still apply; overlong remote links fall back to browser opening. Shared-task access does not
+grant mailbox access. Scope checks run before and after reads; clients bind display
+to account/device/session/URL and ignore stale responses. No mail content is stored
+in sidebar state or added to the chat by opening a link.
+
+Desktop native mail cards also open this tab through `open-mail-card` with
+`sessionId` and `callId`. The tab stores only the card ID and uses the existing
+card editor/actions; session-scoped lookup and supersession select the current
+view. This is a local desktop trial, not a new plugin or device-link capability.
+Older URL-based reader tabs remain valid. Draft edits, deletion and delayed send
+still use the same host-owned mail workflow as the chat card.
+
## 伙伴导入的消息机器人分类
`companion-import` Remote Resource 的 client primitives 可追加 `companion-import-bots-v1`。只有声明它的控制端