Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mail): 统一邮件卡片、草稿发送与会话阅读
Dasha8ee93b307b8
diff --git a/apps/desktop/scripts/mailComposeRuntime.test.mjs b/apps/desktop/scripts/mailComposeRuntime.test.mjsnew file mode 100644index 0000000000..9560e3cb5d--- /dev/null+++ b/apps/desktop/scripts/mailComposeRuntime.test.mjs@@ -0,0 +1,835 @@+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);+ return stored && allowCardRead ? { ok: true, draft: copy(stored.draft) } : { ok: false };+ }+ 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');+});++// 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:/);+});++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",+ cc: "[email protected]",+ };+ 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), [+ "[email protected]",+ ]);+ 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');+ 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 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);+});+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 --git a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.tsindex 18bc8c7542..7f9dcca6d1 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts@@ -44,6 +44,27 @@ function makeDispatcher(overrides: Partial<CardActionDispatchDeps> = {}) {}describe('cardActionDispatch owner boundary', () => {+ it('delivers passive edits without minting a send/Agent ticket or starting activity', async () => {+ const issueUserActionToken = vi.fn(() => 'ticket'), onActivityStart = vi.fn();+ const { dispatcher, sendToGhost, reopenForAction } = makeDispatcher({+ resolveLiveInfo: () => ({ ghostId: 'cindy-mivo', sessionId: 's' }), issueUserActionToken, onActivityStart,+ });+ expect(await dispatcher.dispatch('c', 'change', undefined, undefined, { body: 'latest' }, true)).toEqual({ ok: true });+ expect(sendToGhost.mock.calls[0][1]).toMatchObject({ formChange: true, formValues: { body: 'latest' }, spawnCallId: 'c' });+ expect(sendToGhost.mock.calls[0][1]).not.toHaveProperty('userActionToken');+ expect(issueUserActionToken).not.toHaveBeenCalled();+ expect(onActivityStart).not.toHaveBeenCalled();+ expect(reopenForAction).toHaveBeenCalledTimes(1);+ });+ it('validates form fields and settles form activity on the original card', async () => {+ const onActivityStart = vi.fn();+ const { dispatcher, sendToGhost } = makeDispatcher({ resolveLiveInfo: () => ({ ghostId: 'cindy-mivo', sessionId: 'session' }), onActivityStart });+ expect(await dispatcher.dispatch('call', 'save', undefined, undefined, { body: ' exact\n' })).toEqual({ ok: true });+ expect(sendToGhost.mock.calls[0][1].formValues).toEqual({ body: ' exact\n' });+ expect(onActivityStart).toHaveBeenCalledWith('call', 'session');+ expect(await dispatcher.dispatch('call', 'save', undefined, undefined, { body: 'x'.repeat(16001) })).toEqual({ ok: false, reason: 'bad-form-values' });+ expect(sendToGhost).toHaveBeenCalledTimes(1);+ });it('rechecks the owner after wake and never sends to a stale Ghost', async () => {let releaseWake!: () => void;let ownerValid = true;@@ -273,3 +294,107 @@ describe('cardActionDispatch · 资格审 + 投递', () => {expect(onActivityStart).not.toHaveBeenCalled();});});++it('mail sends need the current host-owned view and complete fields, without a generic card slot', async () => {+ const { renderMailCard } = await import('../mailCards');+ const ghost = fakeGhost({ card: false }); ghost.manifest.mail = true;+ const mail = { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name })), attachments: [], state: 'draft' as const,+ status: 'Synced', sendLabel: 'Send', fromLabel: 'From' };+ let html = renderMailCard(mail);+ const f = makeDispatcher({ getGhost: () => ghost,+ resolvePersistedCard: async () => ({ ghostId: 'cindy-mivo', sessionId: null, html }) });+ const values = Object.fromEntries(mail.fields.map(f => [f.name, f.value]));+ const send = () => f.dispatcher.dispatch('call', `mail:send:${mail.key}`, undefined, undefined, values);+ expect(await send()).toEqual({ ok: true });+ expect(f.sendToGhost.mock.calls[0][1].spawnCallId).toBe('call');+ expect((await f.dispatcher.dispatch('call', `mail:send:${mail.key}`)).ok).toBe(false);+ expect((await f.dispatcher.dispatch('call', `mail:now:${mail.key}`)).ok).toBe(false);+ html = renderMailCard({ ...mail, state: 'sending', pendingSend: { deadline: Date.now() + 10000, label: '{seconds}s', cancelLabel: 'Undo', sendNowLabel: 'Send now' } });+ expect((await send()).ok).toBe(false);+ expect((await f.dispatcher.dispatch('call', `mail:cancel:${mail.key}`)).ok).toBe(true);+ expect((await f.dispatcher.dispatch('call', `mail:now:${mail.key}`)).ok).toBe(true);+ html = renderMailCard({ ...mail, state: 'sending' });+ expect((await f.dispatcher.dispatch('call', `mail:cancel:${mail.key}`)).ok).toBe(false);+ html = renderMailCard({ ...mail, supersededBy: 'new' });+ expect(await send()).toEqual({ ok: false, reason: 'mail-view-expired' });+ html = renderMailCard({ ...mail, state: 'sent' });+ expect(await send()).toEqual({ ok: false, reason: 'mail-view-readonly' });+ html = '<p>Legacy card</p>';+ expect(await send()).toEqual({ ok: false, reason: 'mail-view-expired' });+ expect(f.sendToGhost).toHaveBeenCalledTimes(3);+});++it('deletion requires an active host draft with provider support and rejects all terminal edits', async () => {+ const { renderMailCard } = await import('../mailCards');+ const ghost = fakeGhost({ card: false }); ghost.manifest.mail = true;+ const mail = { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name })), attachments: [], state: 'draft' as const,+ status: 'Synced', sendLabel: 'Send', fromLabel: 'From', deleteLabel: 'Delete draft' };+ let html = renderMailCard(mail);+ const f = makeDispatcher({ getGhost: () => ghost,+ resolvePersistedCard: async () => ({ ghostId: 'cindy-mivo', sessionId: null, html }) });+ const remove = () => f.dispatcher.dispatch('call', `mail:delete:${mail.key}`);+ expect((await remove()).ok).toBe(true);+ for (const state of ['sent', 'deleted', 'deleting', 'unconfirmed', 'sending'] as const) {+ html = renderMailCard({ ...mail, state });+ expect((await remove()).ok).toBe(false);+ const values = Object.fromEntries(mail.fields.map(f => [f.name, f.value]));+ expect((await f.dispatcher.dispatch('call', `mail:send:${mail.key}`, undefined, undefined, values)).ok).toBe(false);+ }+ html = renderMailCard({ ...mail, deleteLabel: undefined });+ expect((await remove()).ok).toBe(false);+ html = renderMailCard({ ...mail, supersededBy: 'new' });+ expect((await remove()).ok).toBe(false);+ expect(f.sendToGhost).toHaveBeenCalledTimes(1);+});++it('only a live draft can open the host file picker, and a superseded view cannot deliver its selected file', async () => {+ const { renderMailCard } = await import('../mailCards');+ const ghost = fakeGhost({ card: false }); ghost.manifest.mail = true;+ const mail = { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]',+ fields: [...['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name })),+ { name: 'attachmentItems', label: 'Attachments', value: '[]', kind: 'mail-attachments' as const }], attachments: [], state: 'draft' as const,+ status: 'Synced', sendLabel: 'Send', fromLabel: 'From' };+ let html = renderMailCard(mail);+ const chosen = { path: '/selected/file.pdf', filename: 'file.pdf', bytes: 12, sha256: 'a'.repeat(64) };+ const pickMailAttachment = vi.fn(async () => chosen);+ const f = makeDispatcher({ getGhost: () => ghost, pickMailAttachment,+ resolvePersistedCard: async () => ({ ghostId: 'cindy-mivo', sessionId: null, html }) });+ const values = Object.fromEntries(mail.fields.map(f => [f.name, f.value]));+ const attach = () => f.dispatcher.dispatch('call', `mail:attach:${mail.key}`, undefined, undefined, values);+ expect(await attach()).toEqual({ ok: true });+ expect(f.sendToGhost.mock.calls[0][1].mailAttachment).toEqual(chosen);+ html = renderMailCard({ ...mail, state: 'sent', continueLabel: 'Continue' });+ expect((await attach()).ok).toBe(false); expect(pickMailAttachment).toHaveBeenCalledTimes(1);+ html = renderMailCard(mail);+ pickMailAttachment.mockImplementation(async () => { html = renderMailCard({ ...mail, supersededBy: 'new' }); return chosen; });+ expect((await attach()).ok).toBe(false); expect(f.sendToGhost).toHaveBeenCalledTimes(1);+});++it('phone uploads use the task materializer and discard late files when the draft becomes readonly', async () => {+ const { renderMailCard } = await import('../mailCards');+ const ghost = fakeGhost({ card: false }); ghost.manifest.mail = true;+ const mail = { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]',+ fields: [...['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name })),+ { name: 'attachmentItems', label: 'Files', value: '[]', kind: 'mail-attachments' as const }], attachments: [], state: 'draft' as const,+ status: 'Synced', sendLabel: 'Send', fromLabel: 'From' };+ let html = renderMailCard(mail);+ const staged = { attachment: { path: '/host/cache/upload.pdf', filename: 'plan.pdf', bytes: 10, sha256: 'a'.repeat(64) },+ accepted: vi.fn(), discard: vi.fn(async () => {}) };+ const prepareMailUpload = vi.fn(async () => staged);+ const f = makeDispatcher({ getGhost: () => ghost, prepareMailUpload,+ resolveLiveInfo: () => ({ ghostId: 'cindy-mivo', sessionId: 's' }),+ resolvePersistedCard: async () => ({ ghostId: 'cindy-mivo', sessionId: 's', html }) });+ const values = Object.fromEntries(mail.fields.map(f => [f.name, f.value]));+ const upload = { url: 'provider-validated-reference', name: 'plan.pdf' };+ const attach = () => f.dispatcher.dispatch('call', `mail:attach:${mail.key}`, undefined, 'phone-page', values, false, upload);+ expect((await attach()).ok).toBe(true);+ expect(prepareMailUpload).toHaveBeenCalledWith(upload, 's');+ expect(f.sendToGhost.mock.calls[0][1]).toMatchObject({ mailAttachment: staged.attachment, mobilePageId: 'phone-page' });+ expect(staged.accepted).toHaveBeenCalledTimes(1);+ prepareMailUpload.mockImplementation(async () => { html = renderMailCard({ ...mail, state: 'sent' }); return staged; });+ expect((await attach()).ok).toBe(false);+ expect(staged.discard).toHaveBeenCalledTimes(1);+ expect(f.sendToGhost).toHaveBeenCalledTimes(1);+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.tsindex 90874a5474..a3e116a6bd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardRemoteResource.test.ts@@ -4,12 +4,106 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({ captureDataOwnerBroadcastimport { createPluginIdentityRemoteProvider, createGhostCardRemoteProvider, projectGhostCardBlocks, projectGhostCardActions, persistGhostCardWithRemoteChange, findGhostForRemotePluginIdentity } from '../cardRemoteResource.js';import { upsertGhostCard } from '../cardStoreDb.js';import { isDataOwnerBroadcastScopeCurrent, tapWindowBroadcast } from '../../device-link/broadcast-tap.js';+import { buildAttachmentOssRef } from '@cindy/device-link';+import { renderMailCard } from '../mailCards';+import { parseMailAttachmentUpload } from '../mailAttachmentUpload';+import { prepareMailAttachmentUpload } from '../mailAttachmentUpload';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { createHash } from 'node:crypto';+const uploadFixture = vi.hoisted(() => ({ materialize: vi.fn() }));+vi.mock('../../maker-ipc/normalizeAttachments.js', () => ({ materializeDirectSendOssAttachments: uploadFixture.materialize }));const image = `cindy-media://blobs/${'b'.repeat(64)}.png`;const audio = `cindy-media://blobs/${'c'.repeat(64)}.mp3`;const request = { ref: { collectionId: 'plugin-results', kind: 'card', id: JSON.stringify(['s', 'c']) }, client: { protocolVersion: 1, primitives: [] } };const context = { controllerDeviceId: 'phone' };+it('mail imports reuse task attachment cleanup and verify downloaded bytes before provider delivery', async () => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'mail-upload-test-'));+ try {+ const file = path.join(dir, 'plan.pdf'), bytes = Buffer.from('test attachment');+ await fs.writeFile(file, bytes);+ const accepted = vi.fn(), discard = vi.fn(async () => {});+ uploadFixture.materialize.mockResolvedValue({ message: { content: [{ type: 'file', path: file }] },+ cleanupAfterAcceptance: accepted, cleanupBeforeAcceptance: discard });+ const upload = { name: 'plan.pdf', url: buildAttachmentOssRef({ ossKey: 'fixture', size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }) };+ const result = await prepareMailAttachmentUpload(upload, 'task');+ expect(uploadFixture.materialize).toHaveBeenCalledWith('task', expect.objectContaining({ type: 'user' }), {});+ expect(result.attachment).toMatchObject({ path: file, filename: 'plan.pdf', bytes: bytes.length });+ result.accepted(); expect(accepted).toHaveBeenCalledOnce(); expect(discard).not.toHaveBeenCalled();+ await fs.writeFile(file, 'wrong bytes');+ await expect(prepareMailAttachmentUpload(upload, 'task')).rejects.toThrow('MAIL_ATTACHMENT_INTEGRITY');+ expect(discard).toHaveBeenCalledOnce();+ } finally { await fs.rm(dir, { recursive: true, force: true }); }+});++it('projects phone attachment support and rejects local paths, oversized uploads and terminal drafts', async () => {+ const mail = { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]',+ state: 'draft' as const, status: 'Ready', sendLabel: 'Send', fromLabel: 'From', attachments: [],+ fields: [...['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name })),+ { name: 'attachmentItems', label: 'Files', value: '[]', kind: 'mail-attachments' as const }] };+ let html = renderMailCard(mail);+ const dispatch = vi.fn(async () => true);+ const provider = createGhostCardRemoteProvider({+ readCard: async () => ({ sessionId: 's', callId: 'c', ghostId: 'mail', html, v: 2, height: 100 }),+ authorize: async () => {}, captureScope: () => () => true, interactions: { externalLinks: () => false, dispatch },+ });+ const resource = await provider.get!(context, { ...request, client: { protocolVersion: 1, primitives: ['plugin-card-actions', 'plugin-card-forms'] } });+ expect(resource.blocks?.[0].data).toHaveProperty('mailUpload', true);+ const upload = { name: 'plan.pdf', url: buildAttachmentOssRef({ ossKey: 'fixture', size: 100, sha256: 'a'.repeat(64), mimeType: 'application/pdf' }) };+ const values = Object.fromEntries(mail.fields.map(f => [f.name, f.value]));+ const base = { client: request.client, collectionId: 'plugin-results', resourceRef: request.ref, actionId: `mail:attach:${mail.key}`,+ input: { revision: resource.revision, pageId: 'page', mailAttachment: upload, formValues: values } };+ await provider.invoke!(context, base);+ expect(dispatch).toHaveBeenLastCalledWith('c', base.actionId, undefined, 'page', 'mail', 'phone', values, false, upload);+ for (const invalid of [{ ...upload, url: '/private/mail.pdf' }, { ...upload, name: '../secret' },+ { ...upload, url: buildAttachmentOssRef({ ossKey: 'large', size: 17 * 1024 * 1024, sha256: 'a'.repeat(64) }) }]) {+ expect(parseMailAttachmentUpload(invalid)).toBeNull();+ await expect(provider.invoke!(context, { ...base, input: { ...base.input, mailAttachment: invalid } })).rejects.toThrow();+ }+ html = renderMailCard({ ...mail, state: 'deleted' });+ await expect(provider.invoke!(context, base)).rejects.toThrow();+ expect(dispatch).toHaveBeenCalledTimes(1);+});+describe('native mobile card actions', () => {+ it('accepts edits across autosave revisions but rejects replaced form identities and forged actions', async () => {+ const fields = JSON.stringify([{ name: 'body', label: 'Message', value: 'Saved' }]).replace(/"/g, '"');+ let html = `<div data-ghost-form="${fields}" data-ghost-change="change:one">Saved</div><button data-ghost-action="send:one" data-ghost-submit="true">Send</button>`;+ const dispatch = vi.fn(async () => true);+ const provider = createGhostCardRemoteProvider({ readCard: async () => ({ sessionId: 's', callId: 'c', ghostId: 'mail', html, v: 2, height: 100 }),+ authorize: async () => {}, captureScope: () => () => true, interactions: { externalLinks: () => false, dispatch } });+ const base = { client: request.client, collectionId: 'plugin-results', resourceRef: request.ref, actionId: 'change:one',+ input: { revision: 'earlier-save', pageId: 'page', formChange: true, formValues: { body: 'Latest' } } };+ await provider.invoke!(context, base);+ expect(dispatch).toHaveBeenLastCalledWith('c', 'change:one', undefined, 'page', 'mail', 'phone', { body: 'Latest' }, true);+ await provider.invoke!(context, { ...base, actionId: 'send:one', input: { ...base.input, formChange: false, formKey: 'change:one' } });+ await expect(provider.invoke!(context, { ...base, actionId: 'forged' })).rejects.toThrow();+ html = html.replaceAll(':one', ':two');+ await expect(provider.invoke!(context, base)).rejects.toThrow();+ expect(dispatch).toHaveBeenCalledTimes(2);+ });+ it('projects editable fields and rejects old-client, partial and stale submissions', async () => {+ const form = [{ name: 'body', label: 'Message', value: 'Original', multiline: true }];+ const html = `<div data-ghost-form="${JSON.stringify(form).replace(/"/g, '"')}">Original</div><button data-ghost-action="send" data-ghost-submit="true">Send</button>`;+ const dispatch = vi.fn(async () => true);+ const provider = createGhostCardRemoteProvider({ readCard: async () => ({ sessionId: 's', callId: 'c', ghostId: 'mail', html, v: 2, height: 160 }),+ authorize: async () => {}, captureScope: () => () => true, interactions: { externalLinks: () => false, dispatch } });+ const legacy = await provider.get!(context, { ...request, client: { protocolVersion: 1, primitives: ['plugin-card-actions'] } });+ expect(legacy.blocks?.find(block => block.id === 'text')?.fallbackMarkdown).toContain('Original');+ expect(legacy.blocks?.find(block => block.id === 'actions')?.data).toEqual(expect.objectContaining({ items: [expect.objectContaining({ disabled: true })] }));+ const resource = await provider.get!(context, { ...request, client: { protocolVersion: 1, primitives: ['plugin-card-actions', 'plugin-card-forms'] } });+ expect(resource.blocks?.find(block => block.id === 'actions')?.data).toEqual(expect.objectContaining({ form }));+ expect(resource.blocks?.find(block => block.id === 'text')?.fallbackMarkdown).not.toContain('Original');+ const base = { client: request.client, collectionId: 'plugin-results', resourceRef: request.ref, actionId: 'send', input: { revision: resource.revision, pageId: 'page' } };+ for (const values of [undefined, {}, { extra: 'text' }, { body: 'x'.repeat(16001) }])+ await expect(provider.invoke!(context, { ...base, input: { ...base.input, formValues: values } })).rejects.toThrow();+ await provider.invoke!(context, { ...base, input: { ...base.input, formValues: { body: 'Edited' } } });+ expect(dispatch).toHaveBeenCalledWith('c', 'send', undefined, 'page', 'mail', 'phone', { body: 'Edited' });+ await expect(provider.invoke!(context, { ...base, input: { ...base.input, revision: 'old', formValues: { body: 'Edited' } } })).rejects.toThrow();+ expect(dispatch).toHaveBeenCalledTimes(1);+ });it('projects declared buttons and approved links, preserving required text input and disabled state', () => {const html = '<button data-ghost-action="edit" data-ghost-prompt="Describe & edit">Edit <b>image</b></button><button data-ghost-action="delete" disabled>Delete</button><a data-ghost-link="https://example.com/?a=1&b=2">Visit</a>';expect(projectGhostCardActions(html, false)).toEqual([@@ -33,7 +127,7 @@ describe('native mobile card actions', () => {await expect(provider.invoke!(context, { ...base, actionId: 'forged' })).rejects.toThrow();await expect(provider.invoke!(context, { ...base, input: { ...base.input, prompt: '' } })).rejects.toThrow();await provider.invoke!(context, base);- expect(dispatch).toHaveBeenCalledWith('c', 'edit', 'Change it', 'page', 'art', 'phone');+ expect(dispatch).toHaveBeenCalledWith('c', 'edit', 'Change it', 'page', 'art', 'phone', undefined);html = '<p>Changed</p>';await expect(provider.invoke!(context, base)).rejects.toThrow();expect(dispatch).toHaveBeenCalledTimes(1);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardSanitizer.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardSanitizer.test.tsindex 050b195189..e582485dcd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardSanitizer.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardSanitizer.test.ts@@ -9,6 +9,7 @@ import { describe, expect, it } from 'vitest';import { sanitizeGhostCardHtml } from '../cardSanitizer';import { GHOST_CARD_HTML_MAX_BYTES } from '../../../shared/ghost';+import { readGhostCardForm } from '@cindy/maker-shared/ghost-card-form';const HASH = 'a'.repeat(64);const GOOD_IMG = `cindy-media://blobs/${HASH}.png`;@@ -20,6 +21,15 @@ function ok(html: string): string {}describe('sanitizeGhostCardHtml', () => {+ it('permits inert form declarations without enabling native forms, scripts or navigation', () => {+ const fields = [{ name: 'body', label: 'Message', value: '<script>"&', multiline: true }];+ const encoded = JSON.stringify(fields).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');+ const html = ok(`<div data-ghost-form="${encoded}" onclick="bad()">Preview</div><button data-ghost-action="save" data-ghost-submit="true" formaction="https://example.test">Save</button><input value="secret"><script>bad()</script>`);+ expect(readGhostCardForm(html)).toEqual(fields);+ expect(html).toContain('data-ghost-submit="true"');+ expect(html).not.toMatch(/onclick|formaction|<input|<script/);+ expect(ok('<div data-ghost-form="bad">Preview</div>')).not.toContain('data-ghost-form');+ });it('保留白名单结构与文本', () => {const out = ok('<div><p>你好 <strong>世界</strong></p></div>');expect(out).toBe('<div><p>你好 <strong>世界</strong></p></div>');@@ -97,6 +107,15 @@ describe('sanitizeGhostCardHtml', () => {expect(() => sanitizeGhostCardHtml('<<<><//>< p <div')).not.toThrow();});+ it('preserves escaped mail text without turning encoded markup into elements', () => {+ const html = '<p>Dash <[email protected]> & "team" ' 😀 &lt;script&gt;</p>';+ expect(ok(html)).toBe(html);+ expect(ok(ok(html))).toBe(html);+ const encodedAttack = '<p><img src=x onerror=alert(1)> <script>bad()</script></p>';+ expect(ok(encodedAttack)).toBe(encodedAttack);+ expect(ok(encodedAttack)).not.toMatch(/<img|<script/);+ });+it('plaintext 吞掉余下输入', () => {const out = ok('<p>前</p><plaintext><script>x</script>');expect(out).toBe('<p>前</p>');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.tsindex ef4108a7e4..3d64ac1661 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardService.test.ts@@ -61,6 +61,22 @@ function deferredWrite() {}describe('GhostCardService relocation', () => {+ it('lets an active tool refresh its earlier task card, rejecting other owners/tasks and settled sources', () => {+ const { svc, advance, broadcast } = makeService();+ const target = { ghostId: 'mail', sessionId: 's' };+ svc.registerCall('old', { ...target, toolUseId: null });+ svc.handleCardUpdate('mail', update('old'));+ svc.finalizeCall('old');+ advance(300_000);+ svc.registerCall('tool', { ...target, toolUseId: null });+ expect(svc.reopenForTool('other', 'old', 'tool', target)).toBe(false);+ expect(svc.reopenForTool('mail', 'old', 'tool', { ...target, sessionId: 'other' })).toBe(false);+ expect(svc.reopenForTool('mail', 'old', 'tool', target)).toBe(true);+ expect(svc.handleCardUpdate('mail', update('old', 'Sent')).accepted).toBe(true);+ expect(broadcast).toHaveBeenCalledTimes(2);+ svc.finalizeCall('tool');+ expect(svc.reopenForTool('mail', 'old', 'tool', target)).toBe(false);+ });it('drains every accepted source write even after its call was swept, without waiting for other plugins', async () => {const pending = [deferredWrite(), deferredWrite(), deferredWrite()];const persist = vi.fn()@@ -151,6 +167,7 @@ describe('GhostCardService', () => {expect(svc.hasCard('c1')).toBe(true);expect(broadcast).toHaveBeenCalledWith({callId: 'c1',+ sessionId: 's1',ghostId: 'g1',toolUseId: 'tu1',html: 'S:<p>a</p>',@@ -250,6 +267,16 @@ describe('GhostCardService', () => {expect(svc.handleCardUpdate('g1', update('c1')).accepted).toBe(true);});+ it('accepts an immediate result after a new user action while retaining per-action rate limits', () => {+ const { svc, advance } = makeService();+ svc.registerCall('c1', { ghostId: 'g1', toolUseId: null, sessionId: 's1' });+ expect(svc.handleCardUpdate('g1', update('c1')).accepted).toBe(true);+ advance(50);+ svc.reopenForAction('c1', { ghostId: 'g1', sessionId: 's1' });+ expect(svc.handleCardUpdate('g1', update('c1', '<p>Saved</p>')).accepted).toBe(true);+ expect(svc.handleCardUpdate('g1', update('c1')).reason).toBe('rate-limited');+ });+it('reopenForAction 重建被清扫条目:用持久归属续会话,落该 sessionId', async () => {const { svc, persist } = makeService();// 从未 registerCall(模拟 settle 久 / 重启后内存条目已被清扫)diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mailCards.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mailCards.test.tsnew file mode 100644index 0000000000..59b519fcd2--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mailCards.test.ts@@ -0,0 +1,131 @@+import { expect, it, vi } from 'vitest';+import { MailCardService, renderMailCard } from '../mailCards';+import { GhostCardService, type GhostCardRow } from '../cardService';+import { readMailCard, type MailCardData } from '@cindy/maker-shared/ghost-card-form';+import { sanitizeGhostCardHtml } from '../cardSanitizer';++const snapshot = (extra: Partial<MailCardData> = {}): MailCardData => ({+ accountId: 'account', draftId: 'draft', key: '12345678-1234-1234-1234-123456789abc',+ from: 'Dash <[email protected]>', attachments: [], state: 'draft', status: 'Synced', sendLabel: 'Send', fromLabel: 'From',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name === 'subject' ? 'Same subject' : name === 'body' ? 'Original' : '' })), ...extra,+});+function fixture() {+ const rows = new Map<string, GhostCardRow>();+ const persist = vi.fn(async (row: GhostCardRow) => { rows.set(row.callId, row); });+ const broadcast = vi.fn();+ const cards = new GhostCardService({ hasCardSlot: () => false, sanitize: sanitizeGhostCardHtml, persist, broadcast });+ const service = new MailCardService({ cards, read: async id => rows.get(id) ?? null,+ list: async session => [...rows.values()].filter(r => r.sessionId === session), persist, broadcast });+ const register = (id: string, ghostId = 'gmail', sessionId = 'session') => cards.registerCall(id, { ghostId, sessionId, toolUseId: null });+ const publish = (id: string, draft = snapshot(), sender = 'gmail') => service.handle(sender, { callId: id, draft }, () => true);+ return { rows, cards, service, register, publish, broadcast };+}+it('updates autosaves in place; a new view collapses old snapshots and rejects late updates', async () => {+ const f = fixture(); f.register('old'); f.register('new');+ expect(await f.publish('old')).toEqual({ ok: true });+ const edited = snapshot(); edited.fields[4].value = 'Edited';+ expect(await f.publish('old', edited)).toEqual({ ok: true });+ expect(f.rows.size).toBe(1);+ expect(await f.publish('new', snapshot())).toEqual({ ok: true });+ const old = f.rows.get('old')!;+ expect(readMailCard(old.html)?.supersededBy).toBe('new');+ expect(readMailCard(old.html)?.fields[4].value).toBe('Edited');+ expect(old.html).not.toContain('data-ghost-action');+ expect(old.html).not.toContain('data-ghost-change');+ expect(await f.publish('old', edited)).toEqual({ ok: false });+ expect(readMailCard(f.rows.get('new')!.html)?.supersededBy).toBeUndefined();+});+it('does not conflate equal subjects across drafts, accounts, plugins or tasks', async () => {+ const f = fixture();+ const cases = [['a', 'gmail', 'session', snapshot()], ['b', 'gmail', 'session', snapshot({ accountId: 'other' })],+ ['c', 'gmail', 'session', snapshot({ draftId: 'other' })], ['d', 'qq', 'session', snapshot()], ['e', 'gmail', 'other', snapshot()]] as const;+ for (const [id, ghost, session, draft] of cases) { f.register(id, ghost, session); expect((await f.publish(id, draft, ghost)).ok).toBe(true); }+ expect([...f.rows.values()].every(r => !readMailCard(r.html)?.supersededBy)).toBe(true);+});+it('rejects unknown/foreign calls and stale owners; a real tool can reopen its persisted view', async () => {+ const f = fixture();+ expect((await f.publish('unknown')).ok).toBe(false);+ f.register('old'); await f.publish('old');+ expect((await f.publish('old', snapshot(), 'qq')).ok).toBe(false);+ f.register('source');+ expect((await f.service.handle('gmail', { callId: 'old', sourceCallId: 'source', draft: snapshot() }, () => false)).ok).toBe(false);+ expect((await f.service.handle('gmail', { callId: 'old', sourceCallId: 'source', draft: snapshot() }, () => true)).ok).toBe(true);+});+it('sent is terminal and cannot restore editing or a second send', async () => {+ const f = fixture(); f.register('old'); await f.publish('old');+ expect((await f.service.handle('gmail', { callId: 'old', statusOnly: { state: 'sent', status: 'Sent', continueLabel: 'Continue' } }, () => true)).ok).toBe(true);+ expect(f.rows.get('old')!.html).not.toContain('mail:send:');+ expect(f.rows.get('old')!.html).toContain('mail:continue:');+ expect((await f.publish('old')).ok).toBe(false);+});+// Restore must retain the last synchronized baseline and unsaved view without+// granting another plugin/task access. Existing tests only covered publication.+it('restores both versions only for the active owning call and keeps old cards readable', async () => {+ const f = fixture(); f.register('card'); f.register('source');+ const draft = snapshot();+ draft.baseValues = Object.fromEntries(draft.fields.map(field => [field.name, field.value]));+ draft.fields[4].value = 'Unsaved typing'; draft.state = 'syncing';+ await f.publish('card', draft);+ expect(await f.service.restore('gmail', { callId: 'card', sourceCallId: 'source' }, () => true))+ .toEqual({ ok: true, draft });+ expect((await f.service.restore('qq', { callId: 'card' }, () => true)).ok).toBe(false);+ expect((await f.service.restore('gmail', { callId: 'card' }, () => false)).ok).toBe(false);+ f.register('foreign-task', 'gmail', 'other');+ expect((await f.service.restore('gmail', { callId: 'card', sourceCallId: 'foreign-task' }, () => true)).ok).toBe(false);+ expect((await f.publish('card', { ...draft, baseValues: { ...draft.baseValues, body: 'x'.repeat(16001) } })).ok).toBe(false);+ await f.publish('card', snapshot());+ expect((await f.service.restore('gmail', { callId: 'card' }, () => true)).draft?.baseValues).toBeUndefined();+ await f.publish('card', snapshot({ state: 'sent' }));+ expect((await f.service.restore('gmail', { callId: 'card' }, () => true)).ok).toBe(false);+});+it('keeps sender and body literal; ordinary plugin HTML cannot forge host mail metadata', () => {+ const mail = snapshot({ from: '<img src=x onerror=alert(1)>' });+ mail.fields[4].value = 'Text <img> <script>evil</script> "quoted"';+ const html = renderMailCard(mail);+ expect(html).not.toContain('<script>');+ expect(html).not.toContain('<img');+ expect(readMailCard(html)).toEqual(mail);+ const sanitized = sanitizeGhostCardHtml(html);+ expect(sanitized.ok).toBe(true);+ if (sanitized.ok) expect(readMailCard(sanitized.html)).toBeNull();+});++it('only drafts with delete support show the button; deleted cards cannot become editable again', async () => {+ const f = fixture(); f.register('draft');+ expect(renderMailCard(snapshot())).not.toContain('mail:delete:');+ await f.publish('draft', snapshot({ deleteLabel: 'Delete draft' }));+ expect(f.rows.get('draft')!.html).toContain('mail:delete:');+ for (const state of ['deleting', 'deleted'] as const) {+ expect((await f.service.handle('gmail', { callId: 'draft', statusOnly: { state, status: state } }, () => true)).ok).toBe(true);+ expect(f.rows.get('draft')!.html).not.toContain('data-ghost-action');+ expect(f.rows.get('draft')!.html).not.toContain('data-ghost-change');+ }+ expect((await f.publish('draft')).ok).toBe(false);+ expect((await f.publish('draft', snapshot({ state: 'sent' }))).ok).toBe(false);+});++it('persists larger HTML drafts as inert metadata without rendering source in the card footer', async () => {+ const f = fixture(); f.register('rich');+ const mail = snapshot();+ mail.fields.push({ name: 'bodyHtml', kind: 'mail-html', label: 'Body', value: '<p>' + 'Long formatted message '.repeat(1800) + '</p>' },+ { name: 'attachmentItems', kind: 'mail-attachments', label: 'Files', value: '[]' });+ expect((await f.publish('rich', mail)).ok).toBe(true);+ expect(readMailCard(f.rows.get('rich')!.html)?.fields.at(-2)?.value).toBe(mail.fields.at(-2)?.value);+ expect(f.rows.get('rich')!.html).not.toContain('<p>Long formatted');+ mail.fields.at(-1)!.value = '{"path":"/private"}';+ expect((await f.publish('rich', mail)).ok).toBe(false);+});+it('publishes undo/send-now only while waiting and removes the deadline after cancellation', async () => {+ const f = fixture(); f.register('card'); await f.publish('card');+ const pendingSend = { deadline: Date.now() + 10000, label: '{seconds}s', cancelLabel: 'Undo', sendNowLabel: 'Send now' };+ expect((await f.service.handle('gmail', { callId: 'card', statusOnly: { state: 'sending', status: 'Waiting', pendingSend } }, () => true)).ok).toBe(true);+ const html = f.rows.get('card')!.html;+ expect(readMailCard(html)?.pendingSend).toEqual(pendingSend);+ expect(html).toContain('mail:cancel:');+ expect(html).toContain('mail:now:');+ expect(html).not.toContain('mail:send:');+ expect(html).not.toContain('data-ghost-change');+ expect((await f.service.handle('gmail', { callId: 'card', statusOnly: { state: 'draft', status: 'Cancelled' } }, () => true)).ok).toBe(true);+ expect(readMailCard(f.rows.get('card')!.html)?.pendingSend).toBeUndefined();+ expect(f.rows.get('card')!.html).not.toContain('mail:now:');+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.tsnew file mode 100644index 0000000000..18a6ee9d31--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest';+import { createMailReader, mailReaderRemoteProvider } from '../mailReader.js';++const message = { accountId: 'a', messageId: 'm', from: '[email protected]', to: '[email protected]', cc: '', bcc: '', subject: 'Subject', date: '', bodyText: 'Hello', bodyHtml: '<p>Hello</p>', attachments: [] };+const plugin = { id: 'test-mail', namespace: null, enabled: true, reader: { tool: 'read_mail', hosts: ['mail.example.com'] } };+function setup(markRead = false) {+ const call = vi.fn<Parameters<typeof createMailReader>[0]['call']>(async () => ({ ok: true, result: message }));+ const authorize = vi.fn(async () => {});+ let current = true;+ const reader = createMailReader({ plugins: () => [{ ...plugin, reader: { ...plugin.reader, ...(markRead ? { markRead: true as const } : {}) } }], call, authorize, captureScope: () => () => current });+ return { reader, call, authorize, expire: () => { current = false; } };+}+describe('common mailbox reader', () => {+ // Opening may mark read; probing, AI reads and neighboring preloads must not.+ it('passes read intent only for an authorized opening with an opted-in provider', async () => {+ const f = setup(true), url = 'https://mail.example.com/m';+ await f.reader('session', url, false, true);+ expect(f.call).not.toHaveBeenCalled();+ await f.reader('session', url, true);+ expect(f.call.mock.calls.at(-1)).toHaveLength(3);+ await f.reader('session', url, true, true);+ expect(f.call.mock.calls.at(-1)?.[3]).toBe(true);+ const legacy = setup();+ await legacy.reader('session', url, true, true);+ expect(legacy.call.mock.calls.at(-1)).toHaveLength(3);+ await expect(f.reader('session', url, true, 'true')).rejects.toThrow();+ });+ it('carries explicit remote opening intent without changing legacy resource IDs', async () => {+ const f = setup(true), provider = mailReaderRemoteProvider(f.reader);+ const request = { client: { protocolVersion: 1, primitives: ['mail-message'] }, ref: { collectionId: 'mail-messages', kind: 'message', id: JSON.stringify(['session', 'https://mail.example.com/m', true]) } };+ await provider.get!({ controllerDeviceId: 'controller' }, request);+ expect(f.call.mock.calls.at(-1)).toHaveLength(3);+ const result = await provider.get!({ controllerDeviceId: 'controller' }, { ...request, query: 'open' });+ expect(f.call.mock.calls.at(-1)?.[3]).toBe(true);+ expect(result.ref).toEqual(request.ref);+ f.authorize.mockRejectedValue(new Error('Forbidden'));+ f.call.mockClear();+ await expect(f.reader('session', 'https://mail.example.com/m', true, true)).rejects.toThrow('Forbidden');+ expect(f.call).not.toHaveBeenCalled();+ });+ // New optional history must survive IPC without trusting a plugin's foreign-host URL.+ it('validates conversation links while retaining a readable selected message', async () => {+ const f = setup();+ const summary = { messageId: 'm', from: 'A', date: '', subject: 'S', snippet: 'Hi', url: 'https://mail.example.com/message/m' };+ f.call.mockResolvedValue({ ok: true, result: { ...message, conversation: { threadId: 'thread', messages: [summary] } } } as never);+ expect((await f.reader('session', summary.url, true)).message?.conversation?.messages).toEqual([summary]);+ f.call.mockResolvedValue({ ok: true, result: { ...message, conversation: { threadId: 'thread', messages: [{ ...summary, url: 'https://foreign.example.com/m' }] } } } as never);+ const result = await f.reader('session', summary.url, true);+ expect(result.message?.bodyText).toBe('Hello');+ expect(result.message?.conversation).toBeUndefined();+ expect(result.message?.conversationUnavailable).toBe(true);+ });+ it('resolves only exact HTTPS provider hosts without invoking a tool', async () => {+ const f = setup();+ expect(await f.reader('session', 'https://mail.example.com/mail/#inbox/id', false)).toEqual({ supported: true });+ for (const url of ['https://mail.example.com.evil.com/a', 'http://mail.example.com/a', 'https://[email protected]/a', 'https://mail.example.com:444/a'])+ expect(await f.reader('session', url, false)).toEqual({ supported: false });+ expect(f.call).not.toHaveBeenCalled();+ });+ it('uses only the declared read tool and returns validated data without publishing a card', async () => {+ const f = setup();+ expect(await f.reader('session', 'https://mail.example.com/mail/#id', true)).toEqual({ supported: true, message });+ expect(f.call).toHaveBeenCalledWith(plugin, 'session', 'https://mail.example.com/mail/#id');+ });+ it('does not return mail after account/owner changes', async () => {+ const f = setup();+ f.call.mockImplementation(async () => { f.expire(); return { ok: true, result: message }; });+ await expect(f.reader('session', 'https://mail.example.com/a', true)).rejects.toThrow();+ });+ it('does not read before session authorization', async () => {+ const f = setup(); f.authorize.mockRejectedValue(new Error('Forbidden'));+ await expect(f.reader('session', 'https://mail.example.com/a', true)).rejects.toThrow('Forbidden');+ expect(f.call).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts b/apps/desktop/src/main/cindy-brain/cardActionDispatch.tsindex b700dbfcbf..3608bd0422 100644--- a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts+++ b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts@@ -17,6 +17,8 @@* 依赖注入(规则 14):归属查询 / 唤醒 / 投递全经 deps,单测直测零 Electron。*/+import { parseGhostCardFormValues, readMailCard } from '@cindy/maker-shared/ghost-card-form';+import type { MailAttachmentUpload, prepareMailAttachmentUpload } from './mailAttachmentUpload.js';import {GHOST_CARD_ACTION_ID_RE,GHOST_CARD_ACTION_PROMPT_MAX_LEN,@@ -31,7 +33,7 @@ export interface CardActionDispatchDeps {/** 内存卡片服务:in-flight + 宽限窗内的条目(归属 + 会话;命中最快)。 */resolveLiveInfo(callId: string): { ghostId: string; sessionId: string | null } | null;/** 持久卡库兜底:settle 后 / 重启后仍能查到卡的归属 + 会话(内存查无时用)。 */- resolvePersistedCard(callId: string): Promise<{ ghostId: string; sessionId: string | null } | null>;+ resolvePersistedCard(callId: string): Promise<{ ghostId: string; sessionId: string | null; html?: string } | null>;/*** 重开卡片更新窗口:让意识在结算很久后 / 重启后仍能 card-update 换新卡* (cardService.reopenForAction)。sessionId 仅在内存条目已被清扫、需重建时用。@@ -59,6 +61,8 @@ export interface CardActionDispatchDeps {onActivityStart?(key: string, sessionId: string): void;ownerScope?: GhostOwnerScope;now?(): number;+ pickMailAttachment?(inline: boolean): Promise<{ path: string; filename: string; bytes: number; sha256: string; contentId?: string } | null>;+ prepareMailUpload?: typeof prepareMailAttachmentUpload;log?: {info: (msg: string, meta?: Record<string, unknown>) => void;warn: (msg: string, meta?: Record<string, unknown>) => void;@@ -84,7 +88,9 @@ export class GhostCardActionDispatcher {* (IPC 层对 renderer 恒可回,reason 仅诊断)。prompt 仅 data-ghost-prompt* 类动作有(宿主输入框收集的用户文字),可选;非法形状整次拒。*/- async dispatch(callId: unknown, actionId: unknown, prompt?: unknown, mobilePageId?: string): Promise<CardActionResult> {+ async dispatch(callId: unknown, actionId: unknown, prompt?: unknown, mobilePageId?: string, formValues?: unknown, change = false, upload?: MailAttachmentUpload): Promise<CardActionResult> {+ const fields = formValues === undefined ? undefined : parseGhostCardFormValues(formValues);+ if (fields === null || (change && !fields)) return { ok: false, reason: 'bad-form-values' };if (typeof callId !== 'string' || callId.length === 0 || callId.length > MAX_CALL_ID_LEN) {return { ok: false, reason: 'bad-call-id' };}@@ -137,7 +143,45 @@ export class GhostCardActionDispatcher {this.deps.log?.warn('card-action rejected: ghost unavailable', { ghostId, callId });return { ok: false, reason: 'ghost-unavailable' };}- if (!ghost.manifest.card) {+ let mailAction = false;+ let mailAttachment: Awaited<ReturnType<NonNullable<CardActionDispatchDeps['pickMailAttachment']>>> = null;+ let staged: Awaited<ReturnType<typeof prepareMailAttachmentUpload>> | undefined;+ if (upload && (!mobilePageId || change || !actionId.startsWith('mail:attach:'))) return { ok: false, reason: 'bad-mail-upload' };+ if (actionId.startsWith('mail:')) {+ const stored = await this.deps.resolvePersistedCard(callId);+ if (!ownerUsable()) return rejectStaleOwner(ghostId);+ const mail = stored?.html ? readMailCard(stored.html) : null;+ if (ghost.manifest.mail !== true) return { ok: false, reason: 'no-mail-slot' };+ if (!mail || mail.supersededBy || stored?.ghostId !== ghostId) return { ok: false, reason: 'mail-view-expired' };+ const countdownAction = !change && !!mail.pendingSend &&+ (actionId === `mail:cancel:${mail.key}` || actionId === `mail:now:${mail.key}`);+ const expected = change ? 'change' : mail.state === 'sent' && mail.continueLabel ? 'continue' : 'send';+ const attachmentAction = !change && mail.fields.some(f => f.kind === 'mail-attachments') &&+ (actionId === `mail:attach:${mail.key}` || actionId === `mail:image:${mail.key}`);+ const deleteAction = !change && !!mail.deleteLabel && actionId === `mail:delete:${mail.key}`;+ if (deleteAction && !['draft', 'syncing', 'error'].includes(mail.state)) return { ok: false, reason: 'mail-view-readonly' };+ if (attachmentAction && !['draft', 'syncing', 'error'].includes(mail.state)) return { ok: false, reason: 'mail-view-readonly' };+ if (!countdownAction && ((!attachmentAction && !deleteAction && actionId !== `mail:${expected}:${mail.key}`) || ['sending', 'unconfirmed', 'deleting', 'deleted'].includes(mail.state) ||+ (mail.state === 'sent' && expected !== 'continue'))) return { ok: false, reason: 'mail-view-readonly' };+ if (!countdownAction && !deleteAction && expected !== 'continue' && (!fields || Object.keys(fields).length !== mail.fields.length || mail.fields.some(f => !(f.name in fields)))) return { ok: false, reason: 'bad-mail-fields' };+ if (attachmentAction) {+ if (mobilePageId ? (!upload || !sessionId || !this.deps.prepareMailUpload) : !this.deps.pickMailAttachment) return { ok: false, reason: 'mail-attachment-picker-unavailable' };+ try {+ if (mobilePageId) {+ staged = await this.deps.prepareMailUpload!(upload!, sessionId!);+ mailAttachment = staged.attachment;+ } else mailAttachment = await this.deps.pickMailAttachment!(actionId.startsWith('mail:image:'));+ }+ catch { return { ok: false, reason: 'mail-attachment-read-failed' }; }+ if (!ownerUsable()) { await staged?.discard(); return rejectStaleOwner(ghostId); }+ if (!mailAttachment) return { ok: true };+ const latest = await this.deps.resolvePersistedCard(callId);+ const current = latest?.html ? readMailCard(latest.html) : null;+ if (!current || current.key !== mail.key || current.supersededBy || !['draft', 'syncing', 'error'].includes(current.state)) { await staged?.discard(); return { ok: false, reason: 'mail-view-expired' }; }+ }+ mailAction = ghost.manifest.mail === true;+ }+ if (!ghost.manifest.card && !mailAction) {// 卡片是它发的却没声明 card 能力 = 不该发生;保险起见拒。this.deps.log?.warn('card-action rejected: no card capability', { ghostId, callId });return { ok: false, reason: 'no-card-slot' };@@ -151,32 +195,38 @@ export class GhostCardActionDispatcher {const root = ghostCardRootCallId(callId);let spawnCallId = `${root}${GHOST_CARD_SPAWN_SEP}${this.now().toString(36)}`;if (spawnCallId.length > MAX_CALL_ID_LEN) spawnCallId = callId;+ if (change || mailAction) spawnCallId = callId;if (spawnCallId !== callId) {this.deps.reopenForAction(spawnCallId, { ghostId, sessionId });}try {- if (!ownerUsable()) return rejectStaleOwner(ghostId);+ if (!ownerUsable()) { await staged?.discard(); return rejectStaleOwner(ghostId); }if (!this.deps.isRunning(ghostId)) {await this.deps.wake(ghost);- if (!ownerUsable()) return rejectStaleOwner(ghostId);+ if (!ownerUsable()) { await staged?.discard(); return rejectStaleOwner(ghostId); }}// 卡片路径只发这一张一次性票;不另记面板手势,避免一次点击两份凭据。- const userActionToken = this.deps.issueUserActionToken?.(ghostId, sessionId) ?? null;- if (!ownerUsable()) return rejectStaleOwner(ghostId);+ const userActionToken = change ? null : this.deps.issueUserActionToken?.(ghostId, sessionId) ?? null;+ if (!ownerUsable()) { await staged?.discard(); return rejectStaleOwner(ghostId); }this.deps.sendToGhost(ghostId, {type: 'event',name: 'card-action',+ ...(change ? { formChange: true } : {}),...(mobilePageId ? { mobilePageId } : {}),callId,actionId,...(sessionId ? { sessionId } : {}),...(userActionToken ? { userActionToken } : {}),...(promptText !== undefined ? { prompt: promptText } : {}),+ ...(fields ? { formValues: fields } : {}),+ ...(mailAttachment ? { mailAttachment } : {}),spawnCallId,ts: this.now(),});+ try { staged?.accepted(); } catch { /* Delivered files must stay available to the adapter. */ }} catch (err) {+ await staged?.discard();this.deps.log?.warn('card-action deliver failed', {ghostId,callId,@@ -187,9 +237,9 @@ export class GhostCardActionDispatcher {// 呼吸起点:投递成功即亮(意识后台干活从这一刻开始;结束/兜底由// 活动跟踪器按 card-update state / TTL 收口)。- if (sessionId) this.deps.onActivityStart?.(spawnCallId, sessionId);+ if (sessionId && !change) this.deps.onActivityStart?.(fields ? callId : spawnCallId, sessionId);- this.deps.log?.info('card-action delivered', { ghostId, callId, actionId, spawnCallId });+ if (!change) this.deps.log?.info('card-action delivered', { ghostId, callId, actionId, spawnCallId });return { ok: true };}}diff --git a/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts b/apps/desktop/src/main/cindy-brain/cardRemoteResource.tsindex ad776d1974..32d3406a7a 100644--- a/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts+++ b/apps/desktop/src/main/cindy-brain/cardRemoteResource.ts@@ -1,4 +1,5 @@import { GHOST_CARD_ACTION_ID_RE, isGhostCardLinkAllowed } from '../../shared/ghost.js';+import { readMailCard, isLegacyMailCard, readGhostCardFormChange, readGhostCardForm, parseGhostCardFormValues, omitGhostCardFormPreview } from '@cindy/maker-shared/ghost-card-form';import type { GhostCardRow } from './cardService.js';import { createHash } from 'node:crypto';import { REMOTE_RESOURCE_CHANGED_CHANNEL, type RemoteResourceBlock } from '@cindy/device-link';@@ -9,6 +10,7 @@ import { remoteResourceRegistry, RemoteResourceRegistryError, type RemoteResourcimport { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent, tapWindowBroadcast, getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap.js';import { isValidGhostId } from '../../shared/ghost.js';import { createPluginLogicalIdentity, findInstalledGhostByIdentity, findInstalledGhostByInstanceId, isGhostInstanceId } from '../../shared/pluginIdentity.js';+import { parseMailAttachmentUpload, type MailAttachmentUpload } from './mailAttachmentUpload.js';const COLLECTION = 'plugin-results';const KIND = 'card';@@ -69,7 +71,7 @@ export function projectGhostCardBlocks(html: string): RemoteResourceBlock[] {}export interface RemotePluginCardAction {- id: string; label: string; prompt?: string; url?: string; disabled: boolean;+ id: string; label: string; prompt?: string; url?: string; disabled: boolean; submit?: boolean;}/** Input is already sanitizer-owned HTML. Only declared inert controls are projected. */export function projectGhostCardActions(html: string, externalLinks: boolean): RemotePluginCardAction[] {@@ -83,6 +85,7 @@ export function projectGhostCardActions(html: string, externalLinks: boolean): Rconst after = source.slice(match.index! + match[0].length);const label = read('aria-label') ?? decodeText(after.slice(0, after.indexOf(`</${match[1]}>`) < 0 ? 256 : after.indexOf(`</${match[1]}>`)).replace(/<[^>]+>/g, '')).trim().slice(0, 512);items.push({ id: action ?? `link:${items.length}`, label: label || action || url!,+ ...(read('data-ghost-submit') === 'true' ? { submit: true } : {}),...(action && read('data-ghost-prompt') !== undefined ? { prompt: read('data-ghost-prompt') } : {}),...(!action && url ? { url } : {}), disabled: /(?:^|\s)disabled(?:\s|$|=)/.test(attrs) });if (items.length >= 64) break;@@ -91,7 +94,12 @@ export function projectGhostCardActions(html: string, externalLinks: boolean): R}interface CardInteractions {externalLinks(ghostId: string): boolean;- dispatch(callId: string, actionId: string, prompt: string | undefined, pageId: string, ghostId: string, controllerId: string): Promise<boolean>;+ dispatch(callId: string, actionId: string, prompt: string | undefined, pageId: string, ghostId: string, controllerId: string, formValues?: Record<string, string>, formChange?: boolean, upload?: MailAttachmentUpload): Promise<boolean>;+}+function mailUploadAction(html: string): RemotePluginCardAction | undefined {+ const mail = readMailCard(html);+ return mail && !mail.supersededBy && ['draft', 'syncing', 'error'].includes(mail.state) && mail.fields.some(f => f.kind === 'mail-attachments')+ ? { id: `mail:attach:${mail.key}`, label: 'Attach', disabled: false, submit: true } : undefined;}/** Task-scoped native controls. No plugin scripts or arbitrary host bridge. */export function createGhostCardRemoteProvider(deps: {@@ -119,23 +127,41 @@ export function createGhostCardRemoteProvider(deps: {async list() { return { collectionId: COLLECTION, revision: '1', items: [] }; },async get(_context, request) {const { card, revision } = await read(request.ref.id);- const blocks = projectGhostCardBlocks(card.html);+ const supportsForms = Boolean(deps.interactions) && request.client.primitives.includes('plugin-card-actions') && request.client.primitives.includes('plugin-card-forms');+ const mail = readMailCard(card.html), legacyMail = isLegacyMailCard(card.html);+ const obsolete = !!mail?.supersededBy || legacyMail;+ const blocks = supportsForms && (mail || legacyMail) ? [] : projectGhostCardBlocks(supportsForms ? omitGhostCardFormPreview(card.html) : card.html);if (deps.interactions && request.client.primitives.includes('plugin-card-actions')) blocks.push({id: 'actions', primitive: 'plugin-card-actions', fallbackMarkdown: '',- data: { pluginId: card.ghostId, revision, items: projectGhostCardActions(card.html, deps.interactions.externalLinks(card.ghostId)) },+ data: { pluginId: card.ghostId, revision, mail, legacyMail, mailUpload: supportsForms && !!mailUploadAction(card.html), changeAction: supportsForms && !obsolete ? readGhostCardFormChange(card.html) : undefined, form: supportsForms ? readGhostCardForm(card.html) : null,+ items: obsolete ? [] : projectGhostCardActions(card.html, deps.interactions.externalLinks(card.ghostId)).map(action => action.submit && !supportsForms ? { ...action, disabled: true } : action) },});return { ref: request.ref, display: { title: card.ghostId }, links: [], revision, blocks };},async invoke(context, request) {if (!deps.interactions || !request.resourceRef) throw new RemoteResourceRegistryError('UNSUPPORTED_CAPABILITY', 'Card actions unavailable');const { card, callId, valid, revision } = await read(request.resourceRef.id);- const action = projectGhostCardActions(card.html, false).find(item => item.id === request.actionId && !item.url);+ if (isLegacyMailCard(card.html) || readMailCard(card.html)?.supersededBy) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Mail view has been replaced');+ const change = request.input?.formChange === true;+ const uploadAction = !change ? mailUploadAction(card.html) : undefined;+ const attaching = uploadAction?.id === request.actionId;+ const upload = parseMailAttachmentUpload(request.input?.mailAttachment);+ if (attaching ? !upload : request.input?.mailAttachment !== undefined)+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Invalid mail attachment');+ const action = change && readGhostCardFormChange(card.html) === request.actionId+ ? { id: request.actionId, submit: true, disabled: false, prompt: undefined }+ : change ? undefined : attaching ? uploadAction : projectGhostCardActions(card.html, false).find(item => item.id === request.actionId && !item.url);const input = request.input ?? {};- if (!action || action.disabled || input.revision !== revision || typeof input.pageId !== 'string'+ const form = readGhostCardForm(card.html);+ const values = input.formValues === undefined ? null : parseGhostCardFormValues(input.formValues);+ if (action?.submit ? (!form || !values || Object.keys(values).length !== form.length || form.some(field => !(field.name in values))) : input.formValues !== undefined)+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Card form is unavailable or incomplete');+ if (!action || action.disabled || (!change && input.revision !== revision && !(action?.submit && input.formKey && input.formKey === readGhostCardFormChange(card.html))) || typeof input.pageId !== 'string'|| (action.prompt !== undefined && (typeof input.prompt !== 'string' || !input.prompt.trim() || input.prompt.length > 2000))|| (action.prompt === undefined && input.prompt !== undefined) || !valid())throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Card action is no longer available');- const delivered = await deps.interactions.dispatch(callId, action.id, input.prompt as string | undefined, input.pageId, card.ghostId, context.controllerDeviceId);+ const extra: [boolean?, MailAttachmentUpload?] = upload ? [false, upload] : change ? [true] : [];+ const delivered = await deps.interactions.dispatch(callId, action.id, input.prompt as string | undefined, input.pageId, card.ghostId, context.controllerDeviceId, values ?? undefined, ...extra);if (!valid() || !delivered) throw new RemoteResourceRegistryError('INTERNAL', 'Card action could not be delivered');return { effects: [] };},diff --git a/apps/desktop/src/main/cindy-brain/cardSanitizer.ts b/apps/desktop/src/main/cindy-brain/cardSanitizer.tsindex 732ef0a2f2..51362a442f 100644--- a/apps/desktop/src/main/cindy-brain/cardSanitizer.ts+++ b/apps/desktop/src/main/cindy-brain/cardSanitizer.ts@@ -13,6 +13,7 @@* (后者仅 devDependencies),故手写小型 tokenizer(规则 9:代码确定性)。*/+import { parseGhostCardForm } from '@cindy/maker-shared/ghost-card-form';import {GHOST_CARD_ACTION_ID_RE,GHOST_CARD_HTML_MAX_BYTES,@@ -134,7 +135,10 @@ function validateKeyframes(css: string, violated: { v: boolean }): void {}function escapeText(s: string): string {- return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ // Preserve character references in text tokens. Never decode them before+ // tokenization: encoded markup must remain inert text, including on re-sanitize.+ return s.replace(/&(?!(?:#[0-9]+|#x[0-9a-f]+|[a-z][a-z0-9]*);)/gi, '&')+ .replace(/</g, '<').replace(/>/g, '>');}function escapeAttr(s: string): string {@@ -233,6 +237,10 @@ function parseAttrs(raw: string): ParsedAttrs {/** 按标签挑出允许的属性并净化值;返回可直接拼接的属性串(含前导空格)或空串。 */function sanitizeAttrs(tag: string, attrs: ParsedAttrs, opts: CssOpts): string | null {const parts: string[] = [];+ if (tag === 'div' && parseGhostCardForm(attrs['data-ghost-form'])) {+ parts.push(` data-ghost-form="${escapeAttr(attrs['data-ghost-form'])}"`);+ if (GHOST_CARD_ACTION_ID_RE.test(attrs['data-ghost-change'] || '')) parts.push(` data-ghost-change="${escapeAttr(attrs['data-ghost-change'])}"`);+ }const style = attrs['style'];if (typeof style === 'string' && style.length > 0) {const clean = sanitizeCss(style, opts);@@ -280,6 +288,7 @@ function sanitizeAttrs(tag: string, attrs: ParsedAttrs, opts: CssOpts): string |const actionValid = GHOST_CARD_ACTION_ID_RE.test(action);if (actionValid) {parts.push(` data-ghost-action="${escapeAttr(action)}"`);+ if (attrs['data-ghost-submit'] === 'true') parts.push(' data-ghost-submit="true"');// data-ghost-prompt:该动作需要用户输入文字(宿主点击时弹输入框收集,// 文字随 card-action 的 prompt 字段回传)。属性值 = 输入框占位文案// (可空;超限整属性丢)。只在动作合法时放行——无动作的输入声明无意义。diff --git a/apps/desktop/src/main/cindy-brain/cardService.ts b/apps/desktop/src/main/cindy-brain/cardService.tsindex 03d5be1bbb..87621dddae 100644--- a/apps/desktop/src/main/cindy-brain/cardService.ts+++ b/apps/desktop/src/main/cindy-brain/cardService.ts@@ -97,6 +97,8 @@ export interface GhostCardRow {/** 推送给 renderer 的载荷(带 html,免回查)。 */export interface GhostCardPush {callId: string;+ /** Host-owned task scope; older senders may omit it. */+ sessionId?: string | null;ghostId: string;/** 物理键与逻辑身份不同时,供进行中调用按 namespace 精确配对。 */logicalGhostId?: string;@@ -290,6 +292,8 @@ export class GhostCardService {return this.calls.get(callId)?.hasCard ?? false;}+ async flushWrites(): Promise<void> { await Promise.all(this.pendingWrites.keys()); }+/*** 内存归属查询(in-flight + 宽限窗内):callId → ghostId,查无 null。* 交互卡 card-action 派发用它快查;窗口外(settle 久 / 重启后)由持久卡库@@ -333,6 +337,15 @@ export class GhostCardService {return { ghostId: e.ghostId, sessionId: e.sessionId, ...(e.sessionInstanceId ? { sessionInstanceId: e.sessionInstanceId } : {}), remoteHostId: e.remoteHostId, scriptWorkdir: e.scriptWorkdir, scriptWritePath: e.scriptWritePath, channel: e.channel };}+ /** An active tool may update its own earlier card in the same task. */+ reopenForTool(sender: string, callId: string, sourceCallId: string, target: { ghostId: string; sessionId: string | null }): boolean {+ const source = this.inFlightCallInfoOf(sourceCallId);+ if (!source || source.ghostId !== sender || target.ghostId !== sender ||+ source.channel !== 'session' || !source.sessionId || source.sessionId !== target.sessionId) return false;+ this.reopenForAction(callId, target);+ return true;+ }+/*** 交互卡按钮被点后重开卡片更新窗口(card-action 派发前调,由 dispatcher 接线)。* 让意识在卡片结算很久后 / 重启后仍能 card-update 换新卡:@@ -348,6 +361,9 @@ export class GhostCardService {if (existing) {existing.settledAt = null;existing.reopenedAt = now;+ // A trusted click starts a new operation. Its immediate result must not+ // be discarded by the previous operation's update interval.+ existing.lastAcceptedAt = null;return;}this.calls.set(callId, {@@ -374,6 +390,7 @@ export class GhostCardService {handleCardUpdate(senderGhostId: string,payload: unknown,+ hostMail = false,): { accepted: boolean; reason?: string } {this.sweep();const reject = (reason: string, meta?: Record<string, unknown>) => {@@ -411,7 +428,7 @@ export class GhostCardService {// 出去是孤儿卡——供片语义不成立,直接拒(fs 落盘反查不受影响)。判据用显式// channel 字段:workingDir 空白(scriptWorkdir null)的脚本条目同样拒。if (entry.channel === 'script') return reject('script-call-no-card', { callId: p.callId });- if (!this.deps.hasCardSlot(senderGhostId)) return reject('no-card-slot');+ if (!hostMail && !this.deps.hasCardSlot(senderGhostId)) return reject('no-card-slot');const now = this.now();// working 跨调用窗口内豁免 too-late(生成类流程:提交调用的卡位由后续@@ -425,7 +442,7 @@ export class GhostCardService {}if (entry.lastAcceptedAt !== null &&- now - entry.lastAcceptedAt < GHOST_CARD_MIN_INTERVAL_MS+ now - entry.lastAcceptedAt < GHOST_CARD_MIN_INTERVAL_MS && !hostMail) {// 限速静默丢(首版免罚):意识狂刷不惊动 UI,也不给它节奏反馈。return reject('rate-limited', { callId: p.callId });@@ -436,7 +453,9 @@ export class GhostCardService {: GHOST_CARD_HEIGHT_DEFAULT;const height = Math.min(GHOST_CARD_HEIGHT_MAX, Math.max(GHOST_CARD_HEIGHT_MIN, heightRaw));- const sanitized = this.deps.sanitize(p.html);+ // Host mail HTML is rendered only from validated structured data. Preserve+ // its private identity marker; plugin-authored HTML never gets this path.+ const sanitized = hostMail ? { ok: true as const, html: p.html, animatedHtml: undefined } : this.deps.sanitize(p.html);if (!sanitized.ok) return reject(`sanitize:${sanitized.reason}`, { callId: p.callId });entry.hasCard = true;@@ -468,6 +487,7 @@ export class GhostCardService {this.pendingWrites.set(pending, senderGhostId);this.deps.broadcast({callId: p.callId,+ sessionId: entry.sessionId,ghostId: senderGhostId,...(entry.logicalGhostId !== undefined ? { logicalGhostId: entry.logicalGhostId } : {}),toolUseId: entry.toolUseId,diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 84b0fc8da1..b7b89bafd1 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1851,6 +1851,22 @@ v3 直接用顶层字段声明插件贡献项与自主 Host 能力,不再有 \\`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,默认只读。+支持打开即已读时增加 \`mailReader.markRead:true\`,读取工具接受可选 \`markRead:true\`;+仅用户主动打开时传入,AI 读取和邻近预加载不传。成功读取后只标记当前邮件,不标记整个会话或草稿。+标记失败仍返回正文和 \`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 回合;其它对象型能力必须包含该能力真正需要的详单。@@ -2772,7 +2788,20 @@ cindy.onHostMessage(async function (msg) {- **需要用户输入文字的动作**(如"按提示词改写这张图"):按钮上再加\`data-ghost-prompt="占位文案"\`(≤128 字,可空串)。用户点击时主机弹标准输入框收集文字(textarea,回车发送/Esc 取消),card-action 事件多带 \`prompt\` 字段- (≤2000 字)——你不用也画不了卡内输入框,输入交互由主机代管;+ (≤2000 字)——输入交互由主机代管;+- **可编辑文本表单**:一张卡至多声明一个 div,其 \`data-ghost-form\` 属性为经 HTML 属性转义的+ JSON 字段数组,每项 \`{name,label,value,multiline?,row?,collapsed?,kind?}\`;1–16 项、字段名唯一、label ≤128 字、value ≤16000 字。+ div 内保留纯文本预览供旧客户端使用。宿主在卡片顶部用标准控件渲染;卡内仍零脚本,禁止用它收集凭证。+ 按钮加 \`data-ghost-submit="true"\`,真实点击后事件带 \`formValues: Record<string,string>\`;+ 不与 prompt 混用。插件必须校验字段和业务对象,缺少 formValues 不得执行提交(旧客户端不会发送)。+ 桌面和手机共用字段合同,手机继续校验卡片 revision;原卡收到更新后结束提交状态。+ row 为同一行的分组名,collapsed 默认折叠字段。kind:"recipients" 将地址显示成姓名,+ 同一 row 按实际宽度折叠溢出人数,展开直接替换摘要;原字符串仍是编辑和提交的值。旧端忽略 kind。+ div 可声明 \`data-ghost-change="change-action-id"\`:编辑即时回传 card-action + formChange:true + formValues;+ 此事件没有 userActionToken,不触发 Agent 或活动呼吸。动作 ID 标识当前编辑版本,自动保存回执保持同一 ID,+ 替换草稿/重置编辑时必须换 ID。插件合并频繁编辑,自行保存到业务系统;模型的读取和提交也必须先同步同一份编辑。+ 模型工具更新本任务旧卡时,card-update 可带 sourceCallId(当前尚未结束的工具调用 ID);Host 核对同插件、同任务后重开旧卡。+ 表单动作活动归原 callId,完成后原地更新;不用额外画空的 spawnCallId 卡片。- **可放外部链接**(外链 v3,经宿主确认):写 \`<a href="https://…">官网</a>\`,或在任意可用标签上挂 \`data-ghost-link="https://…"\`(整块可点)。仅收**整串**http/https URL(≤2048 字,不合法只丢属性——文字保留、点不动)。用户点击时主机@@ -2782,7 +2811,7 @@ cindy.onHostMessage(async function (msg) {一个元素只有一种点击行为;别拿链接文案冒充按钮语义,去向和文案不符只会让用户在确认框里看穿;- 不带 \`data-ghost-action\` 的图片仍是"点开看大图":用户点卡内图片主机自动弹 lightbox- (大图/标注/另存),零代码;复杂交互(多字段表单等)仍去你的面板做;+ (大图/标注/另存),零代码;超出上述文本字段的复杂交互仍去你的面板做;- **3D 预览图**:img 再加 \`data-ghost-model="cindy-media://blobs/<指纹>.glb"\`(你名下已落库的 GLB 地址,整串精确匹配才生效),用户点击该图 = 应用内 3D 查看器直接加载这个模型(可旋转/缩放),不再是普通看大图。适合"3D 生成完成卡":预览 + 模型一次diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 6f3aef29d1..7beefdcfd0 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,5 +1,8 @@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';@@ -330,6 +333,8 @@ import {import { GHOST_SCHEME, ghostExternalLinkUrls } from '../../shared/ghost.js';import { GhostPipeDispatcher } from './pipeDispatcher.js';import { GhostCardService, parseCardHeightReport } from './cardService.js';+import { MailCardService } from './mailCards.js';+import { prepareMailAttachmentUpload } from './mailAttachmentUpload.js';import { GhostCardActionDispatcher } from './cardActionDispatch.js';import { GhostSessionActivityTracker } from './ghostSessionActivity.js';import { sanitizeGhostCardHtml } from './cardSanitizer.js';@@ -2312,6 +2317,14 @@ export function getGhostCardService(): GhostCardService {}let cardActionDispatcherSingleton: GhostCardActionDispatcher | null = null;+let mailCardServiceSingleton: MailCardService | null = null;+function getMailCardService(): MailCardService {+ return mailCardServiceSingleton ??= new MailCardService({+ cards: getGhostCardService(), read: getGhostCard, list: listGhostCardsBySession,+ persist: persistGhostCardWithRemoteChange,+ broadcast: payload => broadcastGhostWindowPush(GHOST_CARD_UPDATED_CHANNEL, payload),+ });+}/** 交互卡(v2)按钮点击派发器单例:归属查证(内存卡服务→持久卡库兜底)+* 唤醒 + 管子下发 card-action。wake/sendToGhost/isRunning 与订阅网关同源。 */@@ -2321,7 +2334,7 @@ export function getGhostCardActionDispatcher(): GhostCardActionDispatcher {resolveLiveInfo: (callId) => getGhostCardService().callInfoOf(callId),resolvePersistedCard: async (callId) => {const c = await getGhostCard(callId);- return c ? { ghostId: c.ghostId, sessionId: c.sessionId ?? null } : null;+ return c ? { ghostId: c.ghostId, sessionId: c.sessionId ?? null, html: c.html } : null;},reopenForAction: (callId, info) => getGhostCardService().reopenForAction(callId, info),getGhost: findGhostForPhysicalStoragePart,@@ -2341,6 +2354,22 @@ export function getGhostCardActionDispatcher(): GhostCardActionDispatcher {},issueUserActionToken: (ghostId, sessionId) =>getGhostAgentSlot().issueUserActionToken(ghostId, sessionId),+ pickMailAttachment: async inline => {+ const result = await dialog.showOpenDialog({ properties: ['openFile'],+ ...(inline ? { filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] }] } : {}) });+ if (result.canceled || !result.filePaths[0]) return null;+ const filePath = result.filePaths[0];+ const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);+ try {+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error('attachment-too-large');+ const bytes = await handle.readFile();+ return { path: filePath, filename: path.basename(filePath), bytes: bytes.length,+ sha256: createHash('sha256').update(bytes).digest('hex'),+ ...(inline ? { contentId: randomUUID() + '@cindy.local' } : {}) };+ } finally { await handle.close(); }+ },+ prepareMailUpload: prepareMailAttachmentUpload,// 呼吸起点:点击成功投递即把该会话标为"意识活动中"(结束由 card-update// state / TTL 收口)。onActivityStart: (key, sessionId) => getGhostSessionActivityTracker().begin(key, sessionId),@@ -7852,14 +7881,32 @@ export function registerGhostIpc(): void {return ghost ? { name: ghost.manifest.name, iconDataUrl: ghost.iconDataUrl } : undefined;}, {externalLinks: id => findGhostForPhysicalStoragePart(id)?.manifest.card?.externalLinks === true,- dispatch: async (callId, actionId, prompt, pageId, ghostId, controllerId) => {+ dispatch: async (callId, actionId, prompt, pageId, ghostId, controllerId, formValues, formChange, mailUpload) => {if (!mobilePluginPages) return false;mobilePluginPages.assertInteraction(pageId, ghostId, controllerId);- return (await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt, pageId)).ok;+ return (await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt, pageId, formValues, formChange, mailUpload)).ok;},});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 }),+ });+ 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();mobilePluginPages = new MobilePluginPages({@@ -8551,9 +8598,25 @@ export function registerGhostIpc(): void {if (type === 'schedule-request') {return getGhostScheduleSlot().handleRequest(id, payload);}+ if (type === 'mail-draft-update' || type === 'mail-draft-read') {+ const scope = captureDataOwnerBroadcastScope();+ const current = () => isDataOwnerBroadcastScopeCurrent(scope) && ghostIdForLogicWebContents(event.sender.id) === id;+ const ghost = findGhostForInstanceId(id);+ if (!ghost?.enabled || (ghost.manifest as { mail?: unknown }).mail !== true) return { ok: false };+ return type === 'mail-draft-read' ? getMailCardService().restore(id, payload, current) : getMailCardService().handle(id, payload, current);+ }if (type === 'card-update') {// 卡槽③供片:校验链(归属/卡槽/限速/净化)在 cardService,拒绝原因// 只进日志,恒回 { ok: true }(与 tool-result 同纪律,不给沙箱探测面)。+ const card = payload as { callId?: unknown; sourceCallId?: unknown };+ if (card.sourceCallId !== undefined) {+ if (typeof card.sourceCallId !== 'string' || typeof card.callId !== 'string') return { ok: true };+ const scope = captureDataOwnerBroadcastScope();+ const service = getGhostCardService();+ const target = service.callInfoOf(card.callId) ?? await getGhostCard(card.callId);+ if (!target || !isDataOwnerBroadcastScopeCurrent(scope) || ghostIdForLogicWebContents(event.sender.id) !== id ||+ !service.reopenForTool(id, card.callId, card.sourceCallId, { ghostId: target.ghostId, sessionId: target.sessionId ?? null })) return { ok: true };+ }getGhostCardService().handleCardUpdate(id, payload);return { ok: true };}@@ -8706,9 +8769,9 @@ export function registerGhostIpc(): void {// 派发器内部永不抛;意识随后自绘 card-update 换新卡走既有回放路径。ipcMain.handle('ghosts:card:action',- async (event, callId: unknown, actionId: unknown, prompt?: unknown) => {+ async (event, callId: unknown, actionId: unknown, prompt?: unknown, formValues?: unknown, formChange?: unknown) => {assertTrustedAppRendererEvent(event);- const r = await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt);+ const r = await getGhostCardActionDispatcher().dispatch(callId, actionId, prompt, undefined, formValues, formChange === true);return { ok: r.ok };},);diff --git a/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts b/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.tsnew file mode 100644index 0000000000..106c3e345e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mailAttachmentUpload.ts@@ -0,0 +1,42 @@+import fs from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { parseAttachmentOssRef, parsePeerAttachmentRef } from '@cindy/device-link';++const parseUploadRef = (url: string) => parsePeerAttachmentRef(url) || parseAttachmentOssRef(url);++export interface MailAttachmentUpload { url: string; name: string }+export function parseMailAttachmentUpload(value: unknown): MailAttachmentUpload | null {+ if (!value || typeof value !== 'object') return null;+ const p = value as Record<string, unknown>;+ if (typeof p.url !== 'string' || p.url.length > 8192 || typeof p.name !== 'string' ||+ !p.name.trim() || p.name.length > 255 || /[\\/\x00-\x1f]/.test(p.name)) return null;+ const ref = parseUploadRef(p.url);+ if (!ref || !Number.isSafeInteger(ref.size) || ref.size! < 0 || ref.size! > 16 * 1024 * 1024 ||+ !ref.sha256 || !/^[a-f0-9]{64}$/.test(ref.sha256)) return null;+ return { url: p.url, name: p.name };+}++/** Reuse task attachment materialization and its owner/session cleanup. Never+ * accept a phone-supplied desktop path, or create a second upload store. */+export async function prepareMailAttachmentUpload(input: MailAttachmentUpload, sessionId: string) {+ const upload = parseMailAttachmentUpload(input);+ if (!upload) throw new Error('INVALID_MAIL_ATTACHMENT');+ const ref = parseUploadRef(upload.url)!;+ const { materializeDirectSendOssAttachments } = await import('../maker-ipc/normalizeAttachments.js');+ const staged = await materializeDirectSendOssAttachments(sessionId, {+ type: 'user', content: [{ type: 'file', path: upload.url, name: upload.name, mimeType: ref.mimeType }],+ }, {});+ const discard = async () => { await staged.cleanupBeforeAcceptance?.(); };+ try {+ const file = (staged.message as { content: { path: string }[] }).content[0].path;+ if (file === upload.url) throw new Error('MAIL_ATTACHMENT_NOT_MATERIALIZED');+ const bytes = await fs.readFile(file);+ if (bytes.length !== ref.size || createHash('sha256').update(bytes).digest('hex') !== ref.sha256)+ throw new Error('MAIL_ATTACHMENT_INTEGRITY');+ return {+ attachment: { path: file, filename: upload.name, bytes: bytes.length, sha256: ref.sha256 },+ accepted: () => staged.cleanupAfterAcceptance?.(),+ discard,+ };+ } catch (error) { await discard(); throw error; }+}diff --git a/apps/desktop/src/main/cindy-brain/mailCards.ts b/apps/desktop/src/main/cindy-brain/mailCards.tsnew file mode 100644index 0000000000..818607e1f1--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mailCards.ts@@ -0,0 +1,104 @@+import { parseMailCard, readMailCard, mailCardStatus, mailSendRemainingFraction, MAIL_CARD_MAX_BYTES, type MailCardData } from '@cindy/maker-shared/ghost-card-form';+import type { GhostCardRecord } from './cardStoreDb';+import type { GhostCardService, GhostCardPush, GhostCardRow } from './cardService';++const escape = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');++/** Only the host creates this marker. Plugin HTML cannot retain data-cindy-mail. */+export function renderMailCard(mail: MailCardData): string {+ const active = !mail.supersededBy && ['draft', 'syncing', 'error'].includes(mail.state);+ const button = (action: string, label: string, submit = false) =>+ `<button data-ghost-action="mail:${action}:${escape(mail.key)}"${submit ? ' data-ghost-submit="true"' : ''} style="position:relative;overflow:hidden;min-height:36px;padding:7px 16px;border:1px solid var(--border-default);border-radius:999px;font:inherit;cursor:pointer;background:${action === 'cancel' || action === 'delete' ? 'transparent' : action === 'now' ? 'var(--surface)' : 'var(--text-primary)'};color:${action === 'cancel' || action === 'delete' || action === 'now' ? 'var(--text-primary)' : 'var(--surface)'}">` ++ (action === 'now' ? `<span data-mail-progress="true" aria-hidden="true" style="position:absolute;inset:0;pointer-events:none"><span style="display:block;height:100%;background:var(--text-primary);opacity:0.14;transform-origin:left;transform:scaleX(${1 - mailSendRemainingFraction(mail)})"></span></span>` : '') ++ `<span style="position:relative">${escape(label)}</span></button>`;+ return `<div data-cindy-mail="${escape(JSON.stringify(mail))}"></div>` ++ `<div data-ghost-form="${escape(JSON.stringify(mail.fields))}"${active ? ` data-ghost-change="mail:change:${escape(mail.key)}"` : ''}>` ++ mail.fields.filter(f => (f.kind !== 'hidden' || f.name === 'body') && f.kind !== 'mail-html' && f.kind !== 'mail-attachments').map(f => `<p style="white-space:pre-wrap"><b>${escape(f.label)}</b><br>${escape(f.value)}</p>`).join('') + '</div>' ++ '<div style="padding:10px 12px;font-size:12px;line-height:1.5;color:var(--text-secondary);overflow-wrap:anywhere">' ++ `<div>${escape(mail.fromLabel)}: ${escape(mail.from)}</div>` ++ (mail.attachments.length && !mail.fields.some(f => f.kind === 'mail-attachments') ? `<div style="margin-top:4px">${mail.attachments.map(escape).join(' · ')}</div>` : '') ++ '<div style="display:flex;align-items:center;gap:12px;justify-content:space-between;margin-top:8px">' ++ `<span>${escape(mailCardStatus(mail))}</span><div style="display:flex;align-items:flex-end;gap:8px;flex-shrink:0;font-size:14px;color:var(--text-primary)">` ++ (active && mail.deleteLabel ? button('delete', mail.deleteLabel) : '') ++ (active ? button('send', mail.sendLabel, true) : '') ++ (!mail.supersededBy && mail.pendingSend ? button('cancel', mail.pendingSend.cancelLabel) + button('now', mail.pendingSend.sendNowLabel) : '') ++ (!mail.supersededBy && mail.state === 'sent' && mail.continueLabel ? button('continue', mail.continueLabel) : '') + '</div></div></div>';+}++export class MailCardService {+ // Publication is ordered; autosaves update one call, subsequent reads create a+ // new view. Reuse card persistence, ownership and transport, no parallel DB.+ private pending: Promise<unknown> = Promise.resolve();+ constructor(private readonly deps: {+ cards: GhostCardService;+ read(callId: string): Promise<GhostCardRecord | null>;+ list(sessionId: string): Promise<GhostCardRecord[]>;+ persist(row: GhostCardRow): Promise<void>;+ broadcast(payload: GhostCardPush): void;+ }) {}++ handle(sender: string, payload: unknown, current: () => boolean): Promise<{ ok: boolean }> {+ const task = this.pending.catch(() => {}).then(() => this.publish(sender, payload, current));+ this.pending = task;+ return task;+ }+ /** Recovery reads the existing host-owned row, under the same call/owner scope+ * as updates. No mailbox bodies are copied into the plugin's small routing KV. */+ async restore(sender: string, payload: unknown, current: () => boolean): Promise<{ ok: boolean; draft?: MailCardData }> {+ if (!payload || typeof payload !== 'object') return { ok: false };+ const p = payload as Record<string, unknown>;+ if (typeof p.callId !== 'string' || p.callId.length > 128) return { ok: false };+ await this.pending.catch(() => {});+ const row = await this.deps.read(p.callId);+ const mail = row && readMailCard(row.html);+ if (!row || row.ghostId !== sender || !mail || mail.supersededBy || !current()) return { ok: false };+ if (p.sourceCallId !== undefined && (typeof p.sourceCallId !== 'string' ||+ !this.deps.cards.reopenForTool(sender, p.callId, p.sourceCallId, row))) return { ok: false };+ const info = this.deps.cards.callInfoOf(p.callId);+ if (!info || info.ghostId !== sender || !info.sessionId || info.sessionId !== row.sessionId ||+ !['draft', 'syncing', 'error', 'sending'].includes(mail.state) || !current()) return { ok: false };+ return { ok: true, draft: mail };+ }+ private async publish(sender: string, payload: unknown, current: () => boolean): Promise<{ ok: boolean }> {+ if (!payload || typeof payload !== 'object') return { ok: false };+ const p = payload as Record<string, unknown>;+ if (typeof p.callId !== 'string' || p.callId.length > 128) return { ok: false };+ const previous = await this.deps.read(p.callId);+ const priorMail = previous && readMailCard(previous.html);+ if (priorMail?.supersededBy || (previous && previous.ghostId !== sender)) return { ok: false };+ if (p.sourceCallId !== undefined) {+ if (typeof p.sourceCallId !== 'string' || !previous || !this.deps.cards.reopenForTool(sender, p.callId, p.sourceCallId, previous)) return { ok: false };+ }+ const info = this.deps.cards.callInfoOf(p.callId);+ if (!info || info.ghostId !== sender || !info.sessionId || !current()) return { ok: false };+ let mail = parseMailCard(p.draft);+ if (!mail && priorMail && p.statusOnly && typeof p.statusOnly === 'object') {+ const status = p.statusOnly as Record<string, unknown>;+ mail = parseMailCard({ ...priorMail, status: status.status, state: status.state,+ continueLabel: status.continueLabel, pendingSend: status.pendingSend });+ }+ if (!mail || mail.supersededBy || (priorMail && (priorMail.accountId !== mail.accountId || priorMail.draftId !== mail.draftId))) return { ok: false };+ if (priorMail && ['sent', 'deleted'].includes(priorMail.state) && mail.state !== priorMail.state) return { ok: false };+ const rows = await this.deps.list(info.sessionId);+ if (!current()) return { ok: false };+ const html = renderMailCard(mail);+ if (Buffer.byteLength(html) > MAIL_CARD_MAX_BYTES) return { ok: false };+ const result = this.deps.cards.handleCardUpdate(sender, {+ type: 'card-update', callId: p.callId, html, height: 100, v: 2,+ state: ['syncing', 'sending', 'deleting'].includes(mail.state) ? 'working' : 'done',+ }, true);+ if (!result.accepted) return { ok: false };+ await this.deps.cards.flushWrites();+ for (const row of rows) {+ if (!current()) return { ok: false };+ if (row.callId === p.callId || row.ghostId !== sender) continue;+ const old = readMailCard(row.html);+ if (!old || old.accountId !== mail.accountId || old.draftId !== mail.draftId) continue;+ // Snapshot stays intact, but can no longer submit. Always point at newest.+ const html = renderMailCard({ ...old, supersededBy: p.callId });+ await this.deps.persist({ ...row, html, updatedAt: Date.now() });+ if (current()) this.deps.broadcast({ ...row, html, toolUseId: null, animatedHtml: null, state: 'done' });+ }+ return { ok: current() };+ }+}diff --git a/apps/desktop/src/main/cindy-brain/mailReader.ts b/apps/desktop/src/main/cindy-brain/mailReader.tsnew file mode 100644index 0000000000..ff1f9b776e--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/mailReader.ts@@ -0,0 +1,53 @@+import { mailReaderMatches, parseMailMessage, type MailReaderDeclaration, type MailMessage } from '@cindy/maker-shared/mail-message';+import { RemoteResourceRegistryError, type RemoteResourceProvider } from '../device-link/remoteResourceRegistry.js';++export interface MailReaderPlugin { id: string; namespace?: string | null; enabled: boolean; reader: MailReaderDeclaration }+export interface MailPreviewResult { supported: boolean; message?: MailMessage; error?: string }+export function createMailReader(deps: {+ plugins(): MailReaderPlugin[];+ authorize(sessionId: string): Promise<void>;+ captureScope(): () => boolean;+ call(plugin: MailReaderPlugin, sessionId: string, url: string, markRead?: true): Promise<{ ok: boolean; result?: unknown; message?: string }>;+}) {+ return async (sessionId: unknown, url: unknown, read: unknown, opened: unknown = false): Promise<MailPreviewResult> => {+ if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 128 || typeof url !== 'string' || url.length > 2048 || typeof read !== 'boolean' || typeof opened !== 'boolean')+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Invalid mail link');+ const valid = deps.captureScope();+ await deps.authorize(sessionId);+ const check = () => { if (!valid()) throw new RemoteResourceRegistryError('NOT_FOUND', 'Mail unavailable'); };+ check();+ const candidates = deps.plugins().filter(p => p.enabled && mailReaderMatches(p.reader, url));+ if (!candidates.length) return { supported: false };+ if (!read) return { supported: true };+ if (candidates.length !== 1) return { supported: true, error: 'MAIL_PROVIDER_AMBIGUOUS' };+ const provider = candidates[0];+ const result = opened && provider.reader.markRead+ ? await deps.call(provider, sessionId, url, true)+ : await deps.call(provider, sessionId, url);+ check();+ await deps.authorize(sessionId); check();+ const message = result.ok ? parseMailMessage(result.result) : null;+ if (message?.conversation?.messages.some(m => !mailReaderMatches(candidates[0].reader, m.url))) {+ delete message.conversation;+ message.conversationUnavailable = true;+ }+ return message ? { supported: true, message } : { supported: true, error: 'MAIL_READ_FAILED' };+ };+}++/** Existing device-link resource transport, scoped exactly like plugin cards. */+export function mailReaderRemoteProvider(read: ReturnType<typeof createMailReader>): RemoteResourceProvider {+ const collectionId = 'mail-messages';+ return {+ collection: { id: collectionId, resourceKind: 'message', title: 'Mail' },+ async list() { return { collectionId, revision: '1', items: [] }; },+ async get(_context, request) {+ let args: unknown; try { args = JSON.parse(request.ref.id); } catch { /* validated below */ }+ if (!Array.isArray(args) || args.length !== 3) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Invalid mail link');+ // query is optional and ignored by older hosts; the existing read-only ID stays compatible.+ const result = await read(args[0], args[1], args[2], request.query === 'open');+ return { ref: request.ref, revision: '1', display: { title: result.message?.subject || 'Mail' }, links: [],+ blocks: [{ id: 'message', primitive: 'mail-message', fallbackMarkdown: result.message?.bodyText.slice(0, 16000) || '', data: result }] };+ },+ };+}diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex e4acfb861a..e90dbe77a5 100644--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@ -18,7 +18,8 @@ import {import { getActiveAppSession, type ActiveAppSession } from '../../appSessionState.js';import { ownerScopedGhostPartition, ownerScopedGhostPartitionForInstalledGhost } from '../ghostWebviewPartition.js';import { installedGhostStoragePart } from '../../../shared/pluginIdentity.js';-import { GHOST_BOOT_PATH, ghostBootHtml, ghostFileMime, resolveGhostFilePath } from './ghostFiles.js';+import { GHOST_BOOT_PATH, GHOST_MAIL_SDK_PATH, ghostBootHtml, ghostFileMime, resolveGhostFilePath } from './ghostFiles.js';+import mailComposeRuntimeSource from './mailComposeRuntime.js?raw';import { handleGhostKvRequest, readBoundedBodyText } from './ghostKvEndpoint.js';import { resolveHashRef as resolveBlobHashRef } from '../../cindy-media/blobStore.js';import { buildRangedMediaResponse } from '../../cindy-media/rangeResponse.js';@@ -634,6 +635,11 @@ function registerGhostProtocol(},});}+ if (url.pathname === GHOST_MAIL_SDK_PATH) {+ return new Response(mailComposeRuntimeSource, { status: 200, headers: {+ 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-cache',+ } });+ }if (url.pathname === GHOST_BOOT_PATH || url.pathname === '/') {const entry = binding.entry;if (!entry) return new Response(null, { status: 404 });diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.tsindex ca82e03356..f15c22504d 100644--- a/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostFiles.ts@@ -14,6 +14,7 @@ import { isSafeGhostRelativePath } from '../../../shared/ghost.js';/** 合成启动文档的保留路径(不对应磁盘文件)。 */export const GHOST_BOOT_PATH = '/__boot__';+export const GHOST_MAIL_SDK_PATH = '/__cindy_mail__.js';/*** 把请求 pathname 解析为安装目录内的绝对文件路径;任何越界 / 非法形态返回 null。@@ -72,6 +73,7 @@ export function ghostBootHtml(entry: string): string {// HTTPS;不在这里继承响应头已有的 data:/blob:/media 放行。`<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' https:">`,'</head><body>',+ `<script src="${GHOST_MAIL_SDK_PATH}"></script>`,`<script src="${src}"></script>`,'</body></html>',].join('');diff --git a/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.jsnew file mode 100644index 0000000000..ef8b721eba--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js@@ -0,0 +1,1126 @@+/* 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 => {+ 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]')) {+ 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; }+ }+ }+ 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, '&').replace(/</g, '<').replace(/>/g, '>').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'].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);+ 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, '&').replace(/"/g, '"').replace(/</g, '<');+ 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") {+ if (cancelMailSend(key)) {+ const selected = await adapter.selectAccount(record.account);+ if (selected.ok) await showMailDraft({ callId: record.callId },+ selected, edit.readBack, undefined, key, edit.fields, true);+ }+ return;+ }+ if (match[1] === "now") {+ await edit.pendingSend?.finish();+ 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 --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex 781b11a8d5..7d2f40ce6e 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -428,6 +428,18 @@ describe('[14] sendInvokeResultSafe — 结果超限兜底', () => {expect(second[2].result[0].content.length).toBeLessThan(bigContent.length);});+ it('keeps a long HTML draft card reference in the compact phone history response', () => {+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => { throw tooLarge(); });+ const client = mkClient({ sendInvokeResult });+ const content = JSON.stringify({ ok: true, result: { bodyHtml: '你好'.repeat(16000) }, xdt_card_id: 'draft-card' });+ __testing.sendInvokeResultSafe(client as never, 'ctrl', 'req', {+ ok: true, result: [{ id: 'card-result', role: 'tool_result', content }],+ }, 'local-db:messages:list');+ const stored = sendInvokeResult.mock.calls[1][2].result[0].content;+ expect(JSON.parse(stored)).toMatchObject({ xdt_card_id: 'draft-card' });+ expect(Buffer.byteLength(stored)).toBeLessThanOrEqual(8192);+ });+it('消息页非字符串 content 超限 → 用占位文本替代,不返回半截 JSON', () => {const sendInvokeResult = vi.fn().mockImplementationOnce(() => {throw tooLarge();diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex db76d308ef..3b70434dc7 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -23,6 +23,7 @@ import {import { requestFilePeer, stopFilePeers } from './filePeer';import { requestTaskMigration } from '../task-migration/service';import { normalizeProviderOrder } from "../../shared/providerOrder.js";+import { compactToolCardResult } from '../../shared/toolResultPersistCap.js';/*** dispatch —— device-link 被控端隧道层。*@@ -3813,7 +3814,10 @@ function compactRemoteMessageForDeviceLink(message: unknown): unknown {const contentLimit = record.role === 'tool_result'? REMOTE_TOOL_RESULT_CONTENT_LIMIT: REMOTE_MESSAGE_CONTENT_LIMIT;- const compactContent = compactRemoteMessageContent(record.content, contentLimit);+ const compactContent = record.role === 'tool_result' && typeof record.content === 'string'+ && encodedByteLength(record.content) > contentLimit+ ? compactToolCardResult(record.content, contentLimit) ?? compactRemoteMessageContent(record.content, contentLimit)+ : compactRemoteMessageContent(record.content, contentLimit);if (compactContent === record.content) {return sanitizeRemoteMessage(record);}diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 55658c3b72..29ce37b3b8 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -6,6 +6,7 @@ import { CLOSE_SHARED_TASKS_FOR_SESSION_SQL } from '../sharedTaskClosureSql.js';import fs from 'node:fs';import path from 'node:path';import { Worker } from 'node:worker_threads';+import { capToolResultTextForPersist, compactToolCardResult, TOOL_RESULT_PERSIST_CONTENT_LIMIT, TOOL_RESULT_PERSIST_TRUNCATION_SUFFIX } from '../../../shared/toolResultPersistCap.js';import {createDbTransportError,@@ -21,6 +22,10 @@ import {import { isBackgroundDbRpc } from './rpcAdmission.js';const WORKER_CODE = `+const TOOL_RESULT_PERSIST_CONTENT_LIMIT = ${TOOL_RESULT_PERSIST_CONTENT_LIMIT};+const TOOL_RESULT_PERSIST_TRUNCATION_SUFFIX = ${JSON.stringify(TOOL_RESULT_PERSIST_TRUNCATION_SUFFIX)};+const compactToolCardResult = ${compactToolCardResult.toString()};+const capToolResultTextForPersist = ${capToolResultTextForPersist.toString()};const createAutoReviewIntentProjection = ${createAutoReviewIntentProjection.toString()};const readAutoReviewProjection = ${readAutoReviewProjection.toString()};const batchAutoReviewProjection = ${batchAutoReviewProjection.toString()};@@ -2459,16 +2464,6 @@ function stringifyContent(value) {return json === undefined ? 'null' : json;}-function capToolResultTextForPersist(text) {- var limit = 8 * 1024;- var suffix = '\\n\\n[tool result truncated: stored first 8KB]';- if (text.length <= limit) return text;- var cut = Math.max(0, limit - suffix.length);- var lastKept = text.charCodeAt(cut - 1);- if (cut > 0 && lastKept >= 0xd800 && lastKept <= 0xdbff) cut -= 1;- return text.slice(0, cut) + suffix;-}-function stringifyImportedContent(role, content) {if (role === 'tool_result' && typeof content === 'string') {return stringifyContent(capToolResultTextForPersist(content));diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 1e4a7f1a21..261544898e 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -887,7 +887,7 @@ describe('db worker tx handlers', () => {},);- it('claude.importMessages caps oversized tool_result content at the persistence limit', async () => {+ it.each([false, true])('claude.importMessages caps oversized results and preserves card references (inline=%s)', async (useInlineWorker) => {await withClient(async (client) => {await seedSession(client, 's1');const cap = 8 * 1024;@@ -905,6 +905,15 @@ describe('db worker tx handlers', () => {agentMeta: null,createdAt: 3100,},+ {+ lineNo: 10,+ partIndex: 0,+ role: 'tool_result',+ content: JSON.stringify({ ok: true, result: { bodyHtml: '邮件'.repeat(cap) }, xdt_card_id: 'draft-card' }),+ toolUseId: 'tool-card',+ agentMeta: null,+ createdAt: 3300,+ },{lineNo: 9,partIndex: 0,@@ -917,7 +926,7 @@ describe('db worker tx handlers', () => {],});- expect(result).toEqual({ changed: 2 });+ expect(result).toEqual({ changed: 3 });const toolResult = (await client.queryOne('SELECT content FROM messages WHERE client_id = ?',['claude-import:8-0'],@@ -930,7 +939,9 @@ describe('db worker tx handlers', () => {['claude-import:9-0'],)) as { content: string };expect((JSON.parse(assistant.content) as { text: string }).text.length).toBe(cap * 2);- });+ const card = await client.queryOne<{ content: string }>('SELECT content FROM messages WHERE client_id = ?', ['claude-import:10-0']);+ expect(JSON.parse(JSON.parse(card!.content))).toMatchObject({ xdt_card_id: 'draft-card' });+ }, { useInlineWorker });});it('claude.importMessages does not rewrite rewound imported messages', async () => {diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.tsindex e7c3d69489..74d2b70f7e 100644--- a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts@@ -70,6 +70,15 @@ beforeEach(() => {});describe('right-sidebar-window IPC', () => {+ // The mail card gesture must survive detached-window routing without mail content.+ it('routes a mail card by ID and rejects malformed card references', async () => {+ const controller = makeController();+ const { handler, mainWebContents } = registerController(controller);+ const command = { type: 'open-mail-card', sessionId: 's1', callId: 'card-1' };+ await handler({ sender: mainWebContents }, { command, allowOpen: true });+ expect(controller.routeCommand).toHaveBeenCalledWith({ command, allowOpen: true });+ await expect(handler({ sender: mainWebContents }, { command: { ...command, callId: '' }, allowOpen: true })).rejects.toThrow(/callId/);+ });it('preserves workbench click intent, keeps legacy commands passive, and rejects invalid intent', async () => {const controller = makeController();const { handler, mainWebContents } = registerController(controller);diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.tsindex 135678d187..764efec8d5 100644--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts@@ -97,11 +97,17 @@ function parseCommand(raw: unknown): RsbWindowCommand {if (r.type === 'toggle-review-tab') {return { type: 'toggle-review-tab', sessionId: r.sessionId };}- if (r.type === 'open-web-browser') {+ if (r.type === 'open-web-browser' || r.type === 'open-mail-preview') {if (typeof r.url !== 'string' || r.url.length === 0) {throwIpcError('INVALID_PARAMS', 'command.url required');}- return { type: 'open-web-browser', sessionId: r.sessionId, url: r.url };+ return { type: r.type, sessionId: r.sessionId, url: r.url };+ }+ if (r.type === 'open-mail-card') {+ if (typeof r.callId !== 'string' || !r.callId || r.callId.length > 128) {+ throwIpcError('INVALID_PARAMS', 'command.callId must be a 1–128 character string');+ }+ return { type: r.type, sessionId: r.sessionId, callId: r.callId };}if (r.type === 'ensure-orca-workers-tab') {const hasFocusWorkerSessionId =diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 5b4bc9b023..553cedcc1e 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1251,6 +1251,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// 意识仓库 (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),recommendationsSync:(): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>ipcRenderer.sendSync('ghosts:recommendations'),@@ -1457,8 +1458,10 @@ contextBridge.exposeInMainWorld('electronAPI', {callId: string,actionId: string,prompt?: string,+ formValues?: Record<string, string>,+ formChange?: boolean,): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('ghosts:card:action', callId, actionId, prompt),+ ipcRenderer.invoke('ghosts:card:action', callId, actionId, prompt, formValues, formChange),resolvePanelMedia: (uri: string,purpose?: 'attach' | 'menu',diff --git a/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.tsindex 396bb8e651..6162bd79c4 100644--- a/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostCardRenderItems.test.ts@@ -10,7 +10,7 @@*/import { describe, it, expect } from 'vitest';-import { buildRenderItems, type RenderItem } from '../components/chat/MessageStream';+import { buildRenderItems, buildCachedRenderItems, type RenderItem } from '../components/chat/MessageStream';import type { ChatMessage } from '@/lib/makerChatStore';import { makerChatStore } from '@/lib/makerChatStore';import type { GhostCardSnapshot, GhostCardEntry, GhostLiveCard } from '@/cindy-brain/ghostCardStore';@@ -42,18 +42,54 @@ function snapshot(return { version: 1, byCallId: new Map(Object.entries(cards)), liveCards };}-const readyEntry = (ghostId = 'cindy-art'): GhostCardEntry => ({+const readyEntry = (ghostId = 'cindy-art'): Extract<GhostCardEntry, { status: 'ready' }> => ({status: 'ready',ghostId,html: '<p>card</p>',height: 240,});-function itemsOf(messages: ChatMessage[], snap?: GhostCardSnapshot): RenderItem[] {- return buildRenderItems(messages, undefined, snap).items;+function itemsOf(messages: ChatMessage[], snap?: GhostCardSnapshot, sessionId = 'session-a'): RenderItem[] {+ return buildRenderItems(messages, undefined, snap, { sessionId }).items;}describe('ghost_card · settled 配对', () => {+ // An unanchored mail push used to flash under an unrelated Gmail schema/read+ // call. Mail waits for its exact tool identity/result, unlike progress cards.+ it('does not guess which in-flight mailbox call owns a mail card', () => {+ const entry = { ...readyEntry('gmail'), html: `<div data-cindy-mail="${JSON.stringify({+ accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: '' })),+ attachments: [], state: 'draft', status: 'Saved', sendLabel: 'Send', fromLabel: 'From',+ }).replace(/"/g, '"')}"></div>` };+ const call = mkGhostCall('schema', 'gmail', 'gmail_schema');+ const snap = snapshot({ mail: entry }, [{ callId: 'mail', ghostId: 'gmail', sessionId: 'session-a', toolUseId: null, receivedAt: 1 }]);+ expect(itemsOf([call], snap).some(i => i.type === 'ghost_card')).toBe(false);+ expect(itemsOf([call, mkResult('result', 'tu-schema', { xdt_card_id: 'mail' })], snap)+ .filter(i => i.type === 'ghost_card')).toHaveLength(1);+ expect(itemsOf([call], { ...snap, liveCards: [{ ...snap.liveCards[0], toolUseId: 'tu-schema' }] })+ .filter(i => i.type === 'ghost_card')).toHaveLength(1);+ });+ // Same-draft reads used to accumulate "draft updated" rows. Only the latest+ // view belongs in the transcript; unrelated mail and ordinary cards remain.+ it('omits superseded mail cards and their tool/media fallback in live and persisted history', () => {+ const mailEntry = (supersededBy?: string): GhostCardEntry => ({ ...readyEntry('gmail'), html:+ `<div data-cindy-mail="${JSON.stringify({ accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc',+ from: '', fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: '' })),+ attachments: [], state: 'draft', status: 'Saved', sendLabel: 'Send', fromLabel: 'From', supersededBy,+ }).replace(/"/g, '"')}"></div>` });+ const messages = [mkGhostCall('old', 'gmail'), mkResult('r-old', 'tu-old', { xdt_card_id: 'old', xdt_image_urls: [IMG] }),+ mkGhostCall('new', 'gmail'), mkResult('r-new', 'tu-new', { xdt_card_id: 'new' }),+ mkGhostCall('other'), mkResult('r-other', 'tu-other', { xdt_card_id: 'other' })];+ const cards = { old: mailEntry('new'), new: mailEntry(), other: readyEntry() };+ const items = itemsOf(messages, snapshot(cards));+ expect(items.filter(i => i.type === 'ghost_card').map(i => i.callId)).toEqual(['new', 'other']);+ expect(items.some(i => i.type === 'tool_media' || i.type === 'tool_segment')).toBe(false);+ const live = itemsOf([mkGhostCall('old', 'gmail')], snapshot(cards, [+ { callId: 'old', ghostId: 'gmail', sessionId: 'session-a', toolUseId: 'tu-old', receivedAt: 1 },+ ]));+ expect(live.some(i => i.type === 'ghost_card' || i.type === 'tool_segment')).toBe(false);+ });it('keeps the card store physical id for a namespaced settled call', () => {const call = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };const cards = itemsOf([call, mkResult('result-org', 'tu-org', { xdt_card_id: 'org-card' })],@@ -146,12 +182,38 @@ describe('ghost_card · settled 配对', () => {describe('ghost_card · in-flight 锚定', () => {const live = (callId: string, over: Partial<GhostLiveCard> = {}): GhostLiveCard => ({callId,+ sessionId: 'session-a',ghostId: 'cindy-art',toolUseId: null,receivedAt: 1,...over,});+ // Regression: the global live pool let a second conversation borrow the first+ // conversation's mail before its own result arrived. Existing tests had one+ // session only. Exercise real render projection with interleaved pushes (unit).+ it.each([null, 'tu-mail'])('isolates concurrent conversations before tool results (%s)', (toolUseId) => {+ const call = mkGhostCall('mail');+ const first = live('card-a', { toolUseId });+ const second = live('card-b', { sessionId: 'session-b', toolUseId });+ const ready = { 'card-a': readyEntry(), 'card-b': readyEntry() };+ expect(itemsOf([call], snapshot(ready, [first]), 'session-b').some(i => i.type === 'ghost_card')).toBe(false);+ const both = snapshot(ready, [first, second]);+ const messages = [call];+ for (const [sessionId, callId] of [['session-a', 'card-a'], ['session-b', 'card-b']]) {+ expect(buildCachedRenderItems(messages, undefined, both, { sessionId }).items+ .filter(i => i.type === 'ghost_card').map(i => i.callId)).toEqual([callId]);+ }+ });++ it('waits for an explicit result when a live card has no trusted session', () => {+ const call = mkGhostCall('mail');+ const snap = snapshot({ legacy: readyEntry() }, [live('legacy', { sessionId: undefined })]);+ expect(itemsOf([call], snap).some(i => i.type === 'ghost_card')).toBe(false);+ expect(itemsOf([call, mkResult('result', 'tu-mail', { xdt_card_id: 'legacy' })], snap)+ .find(i => i.type === 'ghost_card')).toMatchObject({ callId: 'legacy', settled: true });+ });+it('does not claim a root card for an enterprise call sharing its ghost id', () => {const call = { ...mkGhostCall('org', 'helper'), toolInput: { ghost_id: 'helper', namespace: 'acme', tool: 'run' } };const cards = itemsOf([call], snapshot({ 'root-card': readyEntry('helper') }, [@@ -268,6 +330,17 @@ describe('ghost_card · in-flight 锚定', () => {expect(items.some((it) => it.type === 'ghost_card')).toBe(false);});+ it('does not attach a new live card to an unfinished call from an older user turn', () => {+ const items = itemsOf([+ mkGhostCall('old'),+ { clientId: 'new-user', role: 'user', content: 'Create another draft' },+ mkGhostCall('new'),+ ], snapshot({ 'new-card': readyEntry() }, [live('new-card')]));+ expect(items.filter(item => item.type === 'ghost_card')).toEqual([+ expect.objectContaining({ key: 'ghostcard-new', callId: 'new-card' }),+ ]);+ });+it('已被 tool_result 认领(settled)的卡不再被活卡锚定', () => {const items = itemsOf([@@ -423,7 +496,7 @@ describe('ghost_card · 媒体回锚(xdt_anchor_card_id)', () => {mkResult('r2', 'tu-g2', { ok: true, xdt_anchor_card_id: 'call-1', xdt_video_urls: [VIDEO] }),],snapshot({ 'call-1': readyEntry('xd-mivo') }, [- { callId: 'call-1', ghostId: 'xd-mivo', toolUseId: 'tu-g1', receivedAt: 1 },+ { callId: 'call-1', ghostId: 'xd-mivo', sessionId: 'session-a', toolUseId: 'tu-g1', receivedAt: 1 },]),);const card = items.find((it) => it.type === 'ghost_card');diff --git a/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts b/apps/desktop/src/renderer/__tests__/ghostCardStore.test.tsindex 7ab26e51c7..5d8a39a6a5 100644--- a/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostCardStore.test.ts@@ -49,9 +49,9 @@ const push = (callId: string, over: Partial<Parameters<typeof ingestCardPush>[0]describe('ghostCardStore', () => {it('preserves the logical identity of an in-place plugin on its live card', () => {- ingestCardPush(push('org', { ghostId: 'helper', logicalGhostId: '_ns__acme__helper' }));+ ingestCardPush(push('org', { ghostId: 'helper', logicalGhostId: '_ns__acme__helper', sessionId: 'session-a' }));expect(getGhostCardSnapshot().liveCards[0]).toMatchObject({- ghostId: 'helper', logicalGhostId: '_ns__acme__helper',+ ghostId: 'helper', logicalGhostId: '_ns__acme__helper', sessionId: 'session-a',});});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts b/apps/desktop/src/renderer/cindy-brain/ghostCardStore.tsindex fa7724f9be..28633e768e 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostCardStore.ts@@ -38,6 +38,7 @@ export type GhostCardEntry =export interface GhostLiveCard {callId: string;+ sessionId?: string | null;ghostId: string;logicalGhostId?: string;/** agent 侧 tool_use id(claude 路径推送里带;codex 为 null → 启发式锚定)。 */@@ -79,6 +80,7 @@ function sweepLive(now: number): void {/** 推送入口(preload onCardUpdated 消费;导出供单测直喂)。 */export function ingestCardPush(payload: {callId: string;+ sessionId?: string | null;ghostId: string;logicalGhostId?: string;toolUseId: string | null;@@ -116,13 +118,14 @@ export function ingestCardPush(payload: {if (existing >= 0) {// 换海报:锚定信息不变,只刷新鲜度。liveCards = liveCards.map((c, i) =>- i === existing ? { ...c, receivedAt: now } : c,+ i === existing ? { ...c, ...(payload.sessionId !== undefined ? { sessionId: payload.sessionId } : {}), receivedAt: now } : c,);} else {liveCards = [...liveCards,{callId: payload.callId,+ sessionId: payload.sessionId,ghostId: payload.ghostId,...(payload.logicalGhostId !== undefined ? { logicalGhostId: payload.logicalGhostId } : {}),toolUseId: payload.toolUseId,diff --git a/apps/desktop/src/renderer/components/chat/GhostCardForm.tsx b/apps/desktop/src/renderer/components/chat/GhostCardForm.tsxnew file mode 100644index 0000000000..dfc4e97106--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/GhostCardForm.tsx@@ -0,0 +1,189 @@+import { useLayoutEffect, useRef, useState } from 'react';+import { Input, Textarea, type TextareaProps } from '@/components/ui/input';+import {+ GHOST_CARD_FORM_MAX_VALUE,+ mergeGhostCardFormValues,+ visibleMailAttachments,+ removeMailAttachment,+ canInsertMailImage,+ insertMailImage,+ mailPreviewImages,+ type GhostCardFormField,+} from '@cindy/maker-shared/ghost-card-form';+import { GhostCardRecipients } from './GhostCardRecipients';+import { MailHtmlPreview } from './MailHtmlPreview';+import { Maximize2, Paperclip, X } from 'lucide-react';+import { FileTypeIcon } from '@/components/ui/file-type-icon';+import { formatByteSize } from '@cindy/maker-shared/file-preview';+import { ImageLightbox } from './ImageLightbox';+import { useTranslation } from 'react-i18next';++/** Native card editor; autosaves never replace newer local edits. */+export function GhostCardForm({+ fields,+ disabled,+ readOnly = false,+ onChange,+ onAttach,+ images,+ expanded = false,+ onEnlarge,+}: {+ fields: GhostCardFormField[];+ disabled: boolean;+ readOnly?: boolean;+ onChange: (values: Record<string, string>) => void;+ onAttach?: (inline: boolean) => void;+ images?: { cid: string; url: string }[];+ expanded?: boolean;+ onEnlarge?: () => void;+}) {+ const { t } = useTranslation();+ const incoming = Object.fromEntries(fields.map((field) => [field.name, field.value]));+ const [base, setBase] = useState(incoming);+ const [values, setValues] = useState(incoming);+ const [preview, setPreview] = useState<string>();+ if (JSON.stringify(base) !== JSON.stringify(incoming)) {+ setBase(incoming);+ setValues(mergeGhostCardFormValues(values, base, incoming));+ }+ const change = (name: string, value: string) => {+ const next = { ...values, [name]: value };+ setValues(next);+ onChange(next);+ };+ return (+ <div className="flex flex-wrap gap-x-2 p-3">+ {fields.map((field) => {+ if (field.kind === 'hidden') return null;+ if (field.kind === 'mail-html') return <MailHtmlPreview key={field.name} value={values[field.name]} images={mailPreviewImages(values, images)} disabled={disabled} reading={expanded} onEnlarge={onEnlarge}+ onChange={readOnly ? undefined : (html, text) => {+ const plain = field.name === 'quoteHtml' ? 'quote' : 'body';+ const next = { ...values, [field.name]: html, ...(plain in values ? { [plain]: text } : {}) };+ setValues(next); onChange(next);+ }} />;+ if (field.kind === 'mail-attachments') {+ const files = visibleMailAttachments(values, field.name);+ if (!files.length && (readOnly || !onAttach)) return null;+ return <div key={field.name} className="flex w-full flex-wrap gap-2 py-2">+ {!readOnly && onAttach && <button type="button" disabled={disabled} onClick={() => onAttach(false)}+ aria-label={t('chat.ghostCall.mailAttach')} title={t('chat.ghostCall.mailAttach')}+ className="rounded p-1 text-muted-foreground hover:bg-[var(--surface-hover)] disabled:opacity-40"><Paperclip className="h-4 w-4" /></button>}+ {files.map(file => <div key={file.key} className="inline-flex max-w-full items-center gap-1 rounded-lg border border-border bg-[var(--surface)] text-12">+ <button type="button" disabled={!file.previewUrl} onClick={() => setPreview(file.previewUrl)} title={file.filename}+ className="flex min-w-0 items-center gap-2 rounded-lg px-3 py-2 text-left enabled:hover:bg-[var(--surface-hover)]">+ {file.previewUrl ? <img src={file.previewUrl} alt="" className="h-9 w-9 shrink-0 rounded object-cover" /> : <FileTypeIcon name={file.filename} mimeType={file.mimeType} size={20} />}+ <span className="min-w-0"><span className="block truncate">{file.filename}</span><span className="block text-muted-foreground">{file.filename.split('.').pop()?.toUpperCase()}{file.bytes !== undefined ? ' · ' + formatByteSize(file.bytes) : ''}</span></span>+ </button>+ {!readOnly && canInsertMailImage(values, file) && <button type="button" disabled={disabled}+ className="shrink-0 rounded px-2 py-2 text-muted-foreground hover:bg-[var(--surface-hover)] disabled:opacity-40"+ onClick={() => { const next = insertMailImage(values, field.name, file.key); setValues(next); onChange(next); }}>+ {t('chat.ghostCall.mailInsertImage')}+ </button>}+ {!readOnly && <button type="button" disabled={disabled} className="mr-1 rounded p-2 text-muted-foreground hover:bg-[var(--surface-hover)] disabled:opacity-40"+ title={t('chat.ghostCall.mailRemoveAttachment', { name: file.filename })} aria-label={t('chat.ghostCall.mailRemoveAttachment', { name: file.filename })} onClick={() => {+ const next = removeMailAttachment(values, field.name, file.key);+ setValues(next); onChange(next);+ }}><X className="h-3.5 w-3.5" /></button>}+ </div>)}+ </div>;+ }+ if (field.kind === 'recipients') {+ const group = fields.filter(+ (f) => f.kind === 'recipients' && (!readOnly || values[f.name]?.trim()),+ );+ if (group[0] !== field) return null;+ return (+ <GhostCardRecipients+ key={field.name}+ fields={group.map((f) => ({ ...f, value: values[f.name] }))}+ disabled={disabled || readOnly}+ readOnly={readOnly}+ onChange={change}+ />+ );+ }+ const control = readOnly ? <div className="whitespace-pre-wrap break-words p-1 text-13 text-foreground">{values[field.name]}</div> : field.multiline ? (+ <CardTextarea+ expanded={expanded}+ aria-label={field.label}+ disabled={disabled || readOnly}+ value={values[field.name]}+ maxLength={GHOST_CARD_FORM_MAX_VALUE}+ rows={field.collapsed ? 4 : 3}+ className="min-h-0 border-transparent bg-transparent p-1 shadow-none"+ onChange={(value) => change(field.name, value)}+ />+ ) : (+ <Input+ aria-label={field.label}+ disabled={disabled || readOnly}+ value={values[field.name]}+ maxLength={GHOST_CARD_FORM_MAX_VALUE}+ size="sm"+ inputClassName="border-transparent bg-transparent shadow-none"+ onChange={(value) => change(field.name, value)}+ />+ );+ if (field.collapsed)+ return (+ <details key={field.name} className="w-full text-12 text-muted-foreground">+ <summary className="cursor-pointer py-2">{field.label}</summary>+ {control}+ </details>+ );+ return (+ <div+ key={field.name}+ className={+ (field.row ? 'min-w-0 flex-[1_1_220px] ' : 'w-full ') ++ (field.multiline+ ? 'py-2'+ : 'flex min-w-0 items-center gap-2 border-b border-border py-1')+ }+ >+ {!field.multiline && (+ <span aria-hidden className="shrink-0 text-12 text-muted-foreground">+ {field.label}+ </span>+ )}+ <div className="min-w-0 flex-1">+ {field.name === 'body' && onEnlarge && !expanded && <div className="flex justify-end">+ <button type="button" onClick={onEnlarge} title={t('chat.ghostCall.mailEnlarge')} aria-label={t('chat.ghostCall.mailEnlarge')}+ className="rounded p-1 text-muted-foreground hover:bg-[var(--surface-hover)]"><Maximize2 className="h-3.5 w-3.5" /></button>+ </div>}+ {control}+ </div>+ </div>+ );+ })}+ {preview && <ImageLightbox src={preview} onClose={() => setPreview(undefined)} />}+ </div>+ );+}++/** Grow with the draft and card width so signatures are visible during review. */+function CardTextarea({ expanded = false, ...props }: TextareaProps & { expanded?: boolean }) {+ const ref = useRef<HTMLTextAreaElement>(null);+ useLayoutEffect(() => {+ const input = ref.current;+ if (!input) return;+ const fit = () => {+ if (!input.clientWidth) return;+ input.style.height = 'auto';+ input.style.height = `${Math.min(input.scrollHeight + 2, expanded ? Infinity : 440)}px`;+ };+ fit();+ if (typeof ResizeObserver === 'undefined') return;+ let width = input.clientWidth;+ const observer = new ResizeObserver(() => {+ if (input.clientWidth !== width) {+ width = input.clientWidth;+ fit();+ }+ });+ observer.observe(input);+ return () => observer.disconnect();+ }, [props.value, expanded]);+ return <Textarea {...props} textareaRef={ref} />;+}diff --git a/apps/desktop/src/renderer/components/chat/GhostCardRecipients.tsx b/apps/desktop/src/renderer/components/chat/GhostCardRecipients.tsxnew file mode 100644index 0000000000..c3742c8ac8--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/GhostCardRecipients.tsx@@ -0,0 +1,209 @@+import { useLayoutEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import {+ fitGhostCardRecipients,+ ghostCardRecipients,+ GHOST_CARD_FORM_MAX_VALUE,+ type GhostCardFormField,+} from '@cindy/maker-shared/ghost-card-form';+import { Textarea } from '@/components/ui/input';++const chipClass =+ 'inline-block max-w-40 shrink-0 truncate rounded-full bg-muted px-2 py-1 text-12 focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]';+const moreClass =+ 'inline-block shrink-0 rounded-full px-1 py-1 text-12 text-muted-foreground focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]';++/** Measure real names and card width; expanding replaces the summary. */+export function GhostCardRecipients({+ fields,+ disabled,+ readOnly = false,+ onChange,+}: {+ fields: GhostCardFormField[];+ disabled: boolean;+ readOnly?: boolean;+ onChange: (name: string, value: string) => void;+}) {+ const { t } = useTranslation();+ const [expanded, setExpanded] = useState(false);+ const [counts, setCounts] = useState<number[]>([]);+ const [needsExpansion, setNeedsExpansion] = useState(false);+ const canExpand = !readOnly || needsExpansion;+ const root = useRef<HTMLDivElement>(null),+ measure = useRef<HTMLDivElement>(null);+ const summaryFields = fields.filter((field) => field.name !== 'bcc' && !field.collapsed);+ const entries = summaryFields.map((field) => ghostCardRecipients(field.value));+ const signature = JSON.stringify(fields);+ useLayoutEffect(() => {+ const node = root.current,+ probe = measure.current;+ if (!node) return;+ if (expanded) {+ const fit = () =>+ node.querySelectorAll('textarea').forEach((input) => {+ input.style.height = 'auto';+ input.style.height = `${input.scrollHeight + 2}px`;+ });+ fit();+ let width = node.clientWidth;+ const observer = new ResizeObserver(() => {+ if (node.clientWidth !== width) {+ width = node.clientWidth;+ fit();+ }+ });+ observer.observe(node);+ return () => observer.disconnect();+ }+ if (!probe) return;+ const layout = () => {+ const width = (key: string) =>+ probe.querySelector<HTMLElement>(`[data-measure="${key}"]`)?.getBoundingClientRect()+ .width ?? 0;+ const groups = entries.map((items, i) => ({+ label: width(`label-${i}`),+ chips: items.map((_, j) => width(`chip-${i}-${j}`)),+ more: Array.from({ length: items.length + 1 }, (_, j) => width(`more-${i}-${j}`)),+ }));+ const available = node.clientWidth - summaryFields.length * 12;+ const fullCounts = fitGhostCardRecipients(available, groups);+ const hidden =+ fields.some((f) => (f.name === 'bcc' || f.collapsed) && f.value.trim()) ||+ entries.some(+ (items, i) =>+ fullCounts[i] < items.length ||+ items.some((entry, j) => {+ const chip = probe.querySelector<HTMLElement>(`[data-measure="chip-${i}-${j}"]`);+ return (+ entry.label !== entry.address || (!!chip && chip.scrollWidth > chip.clientWidth)+ );+ }),+ );+ const next =+ !readOnly || hidden+ ? fitGhostCardRecipients(available - width('toggle'), groups)+ : fullCounts;+ setNeedsExpansion(hidden);+ setCounts((old) => (JSON.stringify(old) === JSON.stringify(next) ? old : next));+ };+ layout();+ const observer = new ResizeObserver(layout);+ observer.observe(node);+ observer.observe(probe);+ return () => observer.disconnect();+ }, [signature, expanded, readOnly, t]);+ const expand = t('chat.ghostCall.expandFields'),+ collapse = t('chat.ghostCall.collapseFields');+ const more = (count: number) => (count ? `+${count}` : '+');+ return (+ <div ref={root} className="relative w-full min-w-0 overflow-hidden border-b border-border py-1">+ {expanded ? (+ fields.map((field, i) => (+ <div key={field.name} className="flex items-start gap-2 py-1">+ <span aria-hidden className="shrink-0 pt-1 text-12 text-muted-foreground">+ {field.label}+ </span>+ <Textarea+ disabled={disabled}+ aria-label={field.label}+ value={field.value}+ rows={1}+ maxLength={GHOST_CARD_FORM_MAX_VALUE}+ className="min-h-0 flex-1 resize-none overflow-hidden border-transparent bg-transparent p-1 leading-5 shadow-none"+ onChange={(value) => onChange(field.name, value)}+ />+ {i === 0 && (+ <button+ type="button"+ aria-expanded="true"+ className={moreClass}+ onClick={() => setExpanded(false)}+ >+ {collapse}+ </button>+ )}+ </div>+ ))+ ) : (+ <>+ <div className="flex min-h-8 items-center gap-3 overflow-hidden">+ {summaryFields.map((field, i) => {+ const count = counts[i] ?? 0,+ remaining = entries[i].length - count;+ return (+ <div key={field.name} className="flex shrink-0 items-center gap-1">+ <span className="text-12 text-muted-foreground">{field.label}</span>+ {entries[i].slice(0, count).map((entry, j) =>+ canExpand ? (+ <button+ key={j}+ type="button"+ className={chipClass}+ title={entry.address}+ aria-label={`${field.label}: ${entry.address}`}+ onClick={() => setExpanded(true)}+ >+ {entry.label}+ </button>+ ) : (+ <span key={j} className={chipClass} title={entry.address}>+ {entry.label}+ </span>+ ),+ )}+ {(remaining > 0 || !entries[i].length) && (+ <button+ type="button"+ className={moreClass}+ aria-label={`${field.label}: ${expand} (${entries[i].length})`}+ onClick={() => setExpanded(true)}+ >+ {more(remaining)}+ </button>+ )}+ </div>+ );+ })}+ {canExpand && (+ <button+ type="button"+ aria-expanded="false"+ className={`${moreClass} ml-auto`}+ onClick={() => setExpanded(true)}+ >+ {expand}+ </button>+ )}+ </div>+ <div+ ref={measure}+ aria-hidden+ className="pointer-events-none invisible absolute left-0 top-0 flex w-max items-center gap-0"+ >+ <span data-measure="toggle" className={moreClass}>+ {expand}+ </span>+ {summaryFields.map((field, i) => (+ <div key={field.name} className="flex w-max items-center">+ <span data-measure={`label-${i}`} className="text-12">+ {field.label}+ </span>+ {entries[i].map((entry, j) => (+ <span key={j} data-measure={`chip-${i}-${j}`} className={chipClass}>+ {entry.label}+ </span>+ ))}+ {Array.from({ length: entries[i].length + 1 }, (_, j) => (+ <span key={`more-${j}`} data-measure={`more-${i}-${j}`} className={moreClass}>+ {more(j)}+ </span>+ ))}+ </div>+ ))}+ </div>+ </>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/GhostMailHistory.tsx b/apps/desktop/src/renderer/components/chat/GhostMailHistory.tsxnew file mode 100644index 0000000000..307cc9ce2c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/GhostMailHistory.tsx@@ -0,0 +1,21 @@+import { useTranslation } from 'react-i18next';+import { visibleMailAttachments, mailPreviewImages, type GhostCardFormField } from '@cindy/maker-shared/ghost-card-form';+import { MailHtmlPreview } from './MailHtmlPreview';++/** Historical snapshots are readable text, never a second composer. */+export function GhostMailHistory({ fields, legacy = false }: { fields: GhostCardFormField[]; legacy?: boolean }) {+ const { t } = useTranslation();+ const values = Object.fromEntries(fields.map(field => [field.name, field.value]));+ return <details className="rounded-xl border border-border bg-[var(--surface-elevated)] text-sm">+ <summary className="cursor-pointer px-3 py-2 text-muted-foreground">+ {t(legacy ? 'chat.ghostCall.mailLegacy' : 'chat.ghostCall.mailUpdated')}+ {' · '}{fields.find(f => f.name === 'subject')?.value}+ </summary>+ <dl className="space-y-3 border-t border-border px-3 py-3">+ {fields.filter(f => f.value && f.kind !== 'hidden' && (f.kind !== 'mail-attachments' || visibleMailAttachments(values, f.name).length)).map(field => <div key={field.name}>+ <dt className="text-12 text-muted-foreground">{field.label}</dt>+ <dd className="whitespace-pre-wrap break-words">{field.kind === 'mail-html' ? <MailHtmlPreview value={field.value} images={mailPreviewImages(values)} /> : field.kind === 'mail-attachments' ? visibleMailAttachments(values, field.name).map(a => a.filename).join(' · ') : field.value}</dd>+ </div>)}+ </dl>+ </details>;+}diff --git a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsxindex 876737c585..0cca8f9cbc 100644--- a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx+++ b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx@@ -1,5 +1,9 @@import { createRoot } from 'react-dom/client';import { MediaScrubber } from '@/components/ui/media-scrubber';+import { GhostMailHistory } from './GhostMailHistory';+import { GhostCardForm } from './GhostCardForm';+import { readGhostCardForm, readMailCard, mailCardStatus, mailSendRemainingFraction, isLegacyMailCard, readGhostCardFormChange, mergeGhostCardFormValues, trackGhostCardFormDelivery, pendingGhostCardFormDelivery } from '@cindy/maker-shared/ghost-card-form';+import { openMailCard } from '@/features/right-sidebar/lib/mailPreview';import sliderCss from '@/components/ui/slider.css?inline';/*** GhostToolCard — 消息流「意识卡片」(卡槽③海报模式)。@@ -32,7 +36,7 @@ import sliderCss from '@/components/ui/slider.css?inline';* 历史卡片纯静态(净化器已剥 CSS 动画之外的一切动源,iframe 无脚本)。*/-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';+import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import { Check, ChevronDown, Copy, FolderOpen, Ghost, Loader2 } from 'lucide-react';@@ -130,6 +134,16 @@ function buildCardSrcDoc(sanitizedHtml: string, themeVars: string): string {// var(--xxx) 供其按需取用;themeVars 为空(极端:store 未就绪)时不注空标签// ——正常路径下它恒含 color-scheme 声明,不会为空。themeVars ? `<style>${themeVars}</style>` : '',+ readGhostCardForm(sanitizedHtml) ? '<style>[data-ghost-form]{display:none}</style>' : '',+ // The host owns mail layout, including cards saved before this renderer version.+ readMailCard(sanitizedHtml) ? `<style>+ body > div:last-child{display:grid!important;grid-template-columns:minmax(0,1fr) auto;gap:2px 12px;padding:8px 12px!important;align-items:center}+ body > div:last-child > div:first-child{grid-column:1;grid-row:1;overflow-wrap:anywhere}+ body > div:last-child > div:last-child{display:contents!important}+ body > div:last-child > div:last-child > span{grid-column:1;grid-row:2;overflow-wrap:anywhere}+ body > div:last-child > div:last-child > div{grid-column:2;grid-row:1 / span 2}+ body > div:last-child > div:not(:first-child):not(:last-child){grid-column:1 / -1;grid-row:3;margin-top:0!important;overflow-wrap:anywhere}+ </style>` : '',// reduced-motion 门控是宿主强制(规则 7),不靠意识作者自觉:系统开了// 减弱动效时,动画版卡片的意识自绘动画一律停播(srcdoc 内 media query// 正常继承系统偏好)。背景仍由意识正文自己决定:透明画布是现行卡片@@ -150,6 +164,15 @@ function buildCardSrcDoc(sanitizedHtml: string, themeVars: string): string {* 跳过贴底自动跟随,让展开区向下铺开,而不是被 pin-to-bottom 把头部顶上去。 */export const CARD_EXPAND_TOGGLE_EVENT = 'xdt-card-expand-toggle';+/** Same native editor and action bridge, with the sidebar owning the scroll area. */+export function MailCardEditor({ callId, html, height, sessionId }: { callId: string; html: string; height: number; sessionId: string }) {+ const themeVars = useGhostCardThemeVars();+ const { t } = useTranslation();+ if (readMailCard(html)?.state === 'deleted') return <div className="p-3 text-13 text-muted-foreground">{mailCardStatus(readMailCard(html)!)}</div>;+ return <GhostCardCanvas callId={callId} html={html} height={height} sessionId={sessionId}+ themeVars={themeVars} ariaTitle={t('mailReader.title')} running={false} mailPanel />;+}+/*** 单块意识画布(母卡与衍生卡共用):沙箱 iframe + 点击桥(lightbox /* card-action / data-ghost-prompt 输入面板)+ 权威量高与写回。自带一层@@ -165,6 +188,7 @@ function GhostCardCanvas({ariaTitle,sessionId,allowExternalLinks,+ mailPanel = false,}: {/** 本画布的卡片键(母卡 = 调用 callId;衍生卡 = spawnCallId)。 */callId: string;@@ -177,10 +201,54 @@ function GhostCardCanvas({sessionId?: string;/** 插件是否声明了 card.externalLinks;未声明则卡内 data-ghost-link 不激活。 */allowExternalLinks?: boolean;+ mailPanel?: boolean;}): ReactNode {const { t } = useTranslation();+ const editorId = useId();const iframeRef = useRef<HTMLIFrameElement | null>(null);const anchorRef = useRef<HTMLDivElement | null>(null);+ const formFields = useMemo(() => readGhostCardForm(html), [html]);+ const mail = useMemo(() => readMailCard(html), [html]);+ useEffect(() => {+ if (!mail?.pendingSend) return;+ let animatedFill: HTMLElement | null = null;+ let animation: Animation | undefined;+ const update = () => {+ const doc = iframeRef.current?.contentDocument;+ const status = doc?.querySelector('body > div:last-child > div:last-child > span');+ if (status) status.textContent = mailCardStatus(mail);+ const track = doc?.querySelector('[data-mail-progress]');+ const fill = track?.firstElementChild as HTMLElement | null;+ if (!track || !fill) return;+ const progress = 1 - mailSendRemainingFraction(mail);+ track.closest('button')?.setAttribute('aria-label', `${mail.pendingSend!.sendNowLabel}, ${mailCardStatus(mail)}`);+ fill.style.transform = `scaleX(${progress})`;+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {+ animation?.cancel();+ animatedFill = null;+ } else if (animatedFill !== fill) {+ animation?.cancel();+ animatedFill = fill;+ animation = fill.animate([{ transform: `scaleX(${progress})` }, { transform: 'scaleX(1)' }],+ { duration: Math.max(0, mail.pendingSend!.deadline - Date.now()), fill: 'forwards' });+ }+ };+ update();+ const timer = window.setInterval(update, 250);+ return () => { window.clearInterval(timer); animation?.cancel(); };+ }, [mail]);+ const changeAction = readGhostCardFormChange(html);+ const formKey = changeAction ?? JSON.stringify(formFields);+ const incoming = Object.fromEntries((formFields ?? []).map(field => [field.name, field.value]));+ const formState = useRef({ key: formKey, values: incoming, base: incoming, busy: false });+ const [formBusy, setFormBusy] = useState(false);+ const formDelivery = useRef(Promise.resolve(true));+ if (formState.current.key !== formKey) {+ formState.current = { key: formKey, values: incoming, base: incoming, busy: false };+ }+ formState.current.values = mergeGhostCardFormValues(formState.current.values, formState.current.base, incoming);+ formState.current.base = incoming;+ useEffect(() => { formState.current.busy = false; setFormBusy(false); }, [html]);const [lightbox, setLightbox] = useState<{ src: string; galleryId: string } | null>(null);// data-ghost-model 声明的 3D 预览:点击开应用内 3D 查看器(GLB 已在媒体// 总仓,blob 来源直读,预览图作 poster)。@@ -236,9 +304,10 @@ function GhostCardCanvas({const doc = iframeRef.current?.contentDocument;const body = doc?.body;if (!doc || !body) return;- const h = Math.ceil(body.scrollHeight);+ // scrollHeight is at least the iframe viewport height, so it cannot shrink a footer.+ const h = Math.ceil(formFields ? body.getBoundingClientRect().height : body.scrollHeight);if (h <= 0) return;- const clamped = Math.min(GHOST_CARD_HEIGHT_MAX, Math.max(GHOST_CARD_HEIGHT_MIN, h));+ const clamped = Math.min(GHOST_CARD_HEIGHT_MAX, Math.max(formFields ? 1 : GHOST_CARD_HEIGHT_MIN, h));const imagesPending = Array.from(doc.images).some((img) => !img.complete);if (imagesPending) {// 图未到齐只涨不缩(相对当前生效高度,含声明值):文档刚换时只有文字,@@ -251,11 +320,11 @@ function GhostCardCanvas({// 权威实测双写回(fire-and-forget):内存卡片库(本次运行内重挂载即// 准确首帧)+ 磁盘(重启后的历史回放)。下次渲染不再经历// "声明值 → 实测值"的可见收敛。- if (Math.abs(clamped - height) > 2) {+ if (!formFields && Math.abs(clamped - height) > 2) {noteCardMeasuredHeight(callId, clamped);window.electronAPI?.ghosts?.reportCardHeight?.(callId, clamped)?.catch(() => {});}- }, [callId, height]);+ }, [callId, height, formFields]);/** data-ghost-audio 插槽装配:注入标准播放器行 + 双向接线(UI → audio 控制,* audio 事件 → UI 刷新)。同 url 复用同一 <audio>(跨文档重载接续播放)。 */@@ -462,6 +531,25 @@ function GhostCardCanvas({e.stopPropagation();// 已锁(点过、等新卡)则忽略连点。if (el.getAttribute('aria-disabled') === 'true' || (el as HTMLButtonElement).disabled) return;+ if (el.dataset.ghostSubmit === 'true') {+ if (!readGhostCardForm(html) || formState.current.busy) return;+ formState.current.busy = true;+ setFormBusy(true);+ lockActionEl(el);+ void formDelivery.current.then(async ok => {+ if (!ok || (sessionId && await pendingGhostCardFormDelivery(sessionId) === false)) return { ok: false };+ // A second view may have delivered edits since this iframe bound its listener.+ const entry = getGhostCardSnapshot().byCallId.get(callId);+ const latest = entry?.status === 'ready' ? readGhostCardForm(entry.html) : null;+ const values = latest && entry?.status === 'ready' && readGhostCardFormChange(entry.html) === formState.current.key+ ? mergeGhostCardFormValues(formState.current.values, formState.current.base, Object.fromEntries(latest.map(f => [f.name, f.value])))+ : formState.current.values;+ return window.electronAPI?.ghosts?.dispatchCardAction?.(callId, actionId, undefined, values) ?? { ok: false };+ }).then(result => {+ if (!result.ok) { formState.current.busy = false; setFormBusy(false); }+ }).catch(() => {});+ return;+ }// data-ghost-prompt 类动作:先弹宿主输入框收集文字,发送时才派发// (与老基座 imgPrompt popover 同体验;零输入直发会被上游拒)。if (el.dataset.ghostPrompt !== undefined) {@@ -518,7 +606,7 @@ function GhostCardCanvas({});});measureHeight();- }, [measureHeight, callId, lockActionEl, bindAudioSlot, allowExternalLinks]);+ }, [measureHeight, callId, lockActionEl, bindAudioSlot, allowExternalLinks, html, sessionId]);useEffect(() => {// srcDoc 更新后 load 事件可能在 effect 前已触发(同进程同步解析),补挂一次。@@ -597,10 +685,34 @@ function GhostCardCanvas({return (// 非裁切 relative 锚容器:输入面板 absolute 于此(画布壳 overflow-hidden// 会裁面板,面板必须挂在裁切层之外)。- <div ref={anchorRef} className="relative">- {/* 画布外壳:只留圆角裁切(全出血海报靠它裁边),无边框/底色/内边距——- 归属由 chip 表达,画布全量归意识,主机不再叠任何主观描边。 */}- <div className="relative overflow-hidden rounded-[10px]">+ <div ref={anchorRef} className={formFields && !mailPanel ? 'relative rounded-xl border border-border bg-[var(--surface-elevated)]' : 'relative'}>+ {formFields ? <GhostCardForm key={formKey} fields={formFields} disabled={formBusy || ['sent', 'sending', 'unconfirmed', 'deleting', 'deleted'].includes(readMailCard(html)?.state ?? '')}+ expanded={mailPanel}+ onEnlarge={mail && sessionId && !mailPanel ? () => { void openMailCard(sessionId, callId).catch(() => toast.error(t('chat.ghostCall.formSyncFailed'))); } : undefined}+ readOnly={['sent', 'deleted'].includes(readMailCard(html)?.state ?? '')}+ images={readMailCard(html)?.images}+ onAttach={readMailCard(html) ? inline => {+ const mail = readMailCard(html)!;+ setFormBusy(true);+ const delivery = formDelivery.current.then(() => window.electronAPI.ghosts.dispatchCardAction(callId,+ `mail:${inline ? 'image' : 'attach'}:${mail.key}`, undefined, formState.current.values).then(r => r.ok).catch(() => false));+ formDelivery.current = delivery;+ if (sessionId) trackGhostCardFormDelivery(sessionId, `${callId}:${editorId}`, delivery);+ void delivery.then(ok => { if (!ok) toast.error('附件未添加,请重新选择文件。'); }).finally(() => setFormBusy(false));+ } : undefined}+ onChange={values => {+ formState.current.values = values;+ if (changeAction) {+ const delivery = formDelivery.current.then(() => window.electronAPI?.ghosts?.dispatchCardAction?.(callId, changeAction, undefined, values, true)+ .then(result => result.ok).catch(() => false) ?? false);+ formDelivery.current = delivery;+ if (sessionId) trackGhostCardFormDelivery(sessionId, `${callId}:${editorId}`, delivery);+ void delivery.then(ok => { if (!ok) toast.error(t('chat.ghostCall.formSyncFailed')); });+ }+ }} /> : null}+ {/* Editable forms share a frame with their plugin-provided footer.+ Ordinary plugin posters keep their original transparent canvas. */}+ <div className={formFields ? 'relative overflow-hidden rounded-b-xl border-t border-border' : 'relative overflow-hidden rounded-[10px]'}><iframeref={iframeRef}sandbox="allow-same-origin"@@ -811,13 +923,20 @@ export function GhostToolCard({const ownWorking = ownEntry?.status === 'ready' && ownEntry.state === 'working';const effectiveRunning = running || ownWorking;+ const mail = readMailCard(html);+ const legacyMail = isLegacyMailCard(html);+ const history = legacyMail;+ const historyFields = mail?.fields ?? readGhostCardForm(html);const ariaTitle = t('chat.ghostCall.cardAria', { name, tool: toolName });+ if (mail?.supersededBy) return null;+return (<div- className="flex flex-col"- style={{ maxWidth: CARD_MAX_WIDTH }}+ className="flex min-w-0 flex-col"+ style={{ maxWidth: mail || legacyMail ? 'min(100%, max(480px, 75%))' : CARD_MAX_WIDTH }}aria-label={ariaTitle}+ data-mail-call-id={mail ? callId : undefined}>{/* ── 归属小 chip(主机唯一主观渲染;意识不可触)──────────────────收敛自旧整宽身份 bar:只留"这块内容由某意识渲染"的信任签名——幽灵@@ -899,7 +1018,16 @@ export function GhostToolCard({) : null}{/* ── 母卡画布 ─────────────────────────────────────────────────── */}- <GhostCardCanvas+ {mail?.state === 'deleted' ? (+ <div role="status" className="flex min-w-0 items-center gap-2 rounded-xl border border-border bg-[var(--surface-elevated)] px-3 py-2 text-sm text-muted-foreground">+ <span className="shrink-0">{mailCardStatus(mail)}</span>+ {mail.fields.find(f => f.name === 'subject')?.value && <span className="truncate" title={mail.fields.find(f => f.name === 'subject')?.value}>+ · {mail.fields.find(f => f.name === 'subject')?.value}+ </span>}+ </div>+ ) : history ? (+ <GhostMailHistory fields={historyFields ?? []} legacy={legacyMail} />+ ) : <GhostCardCanvascallId={callId}html={html}animatedHtml={animatedHtml}@@ -909,7 +1037,7 @@ export function GhostToolCard({ariaTitle={ariaTitle}sessionId={sessionId}allowExternalLinks={ghost?.manifest.card?.externalLinks}- />+ />}{/* ── 衍生卡(card-action 触发的新结果;母卡保留,可反复抽卡)────────每张是视觉独立的新卡片:间距拉开 + 精简归属 chip(无参数展开),diff --git a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsxnew file mode 100644index 0000000000..3cae170a9c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx@@ -0,0 +1,130 @@+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { Maximize2, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { applyMailInlineEdits, mailInlineDocument, safeMailDocument, validMailImageUrl } from '@cindy/maker-shared/mail-text-edit';+import { followMailPreviewTheme } from './mailPreviewAppearance';++export const safeMailHtml = safeMailDocument;+type PreviewProps = { value: string; images?: { cid: string; url: string }[]; disabled?: boolean; reading?: boolean; onEnlarge?: () => void; onChange?: (html: string, text: string) => void };+function PreviewFrame({ value, images = [], enlarged = false, reading = false, disabled, onChange }: PreviewProps & { enlarged?: boolean }) {+ const frame = useRef<HTMLIFrameElement>(null);+ const stopTheme = useRef<(() => void) | undefined>(undefined);+ const bodyResize = useRef<ResizeObserver | undefined>(undefined);+ useEffect(() => () => { stopTheme.current?.(); bodyResize.current?.disconnect(); }, []);+ const model = useRef({ source: value, emitted: value, received: value, edits: {} as Record<string, string>, revision: 0 });+ if (model.current.received !== value) {+ if (value !== model.current.emitted) model.current = { source: value, emitted: value, received: value, edits: {}, revision: model.current.revision + 1 };+ else model.current.received = value;+ }+ const current = useRef({ disabled, onChange, images });+ current.current = { disabled, onChange, images };+ const revision = model.current.revision;+ useLayoutEffect(() => {+ if (!frame.current) return;+ frame.current.style.visibility = 'hidden';+ frame.current.setAttribute('aria-busy', 'true');+ }, [revision]);+ // Echoes from autosave must not reload the document or move the caret/IME.+ const html = useMemo(() => mailInlineDocument(model.current.source, images), [revision]);+ const fit = () => {+ const el = frame.current, doc = el?.contentDocument;+ if (el && doc?.body && !enlarged) {+ el.style.height = '0px';+ const height = Math.ceil(Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight, doc.body.getBoundingClientRect().bottom)) + 12;+ el.style.height = `${Math.max(80, Math.min(reading ? Infinity : 440, height))}px`;+ }+ };+ const refresh = () => {+ const doc = frame.current?.contentDocument;+ if (!doc) return;+ for (const el of doc.querySelectorAll<HTMLElement>('[data-cindy-mail-run]')) {+ el.contentEditable = current.current.onChange && !current.current.disabled ? 'plaintext-only' : 'false';+ el.setAttribute('spellcheck', 'true');+ }+ for (const el of doc.querySelectorAll<HTMLImageElement>('img[data-cindy-mail-cid]')) {+ const image = current.current.images.find(i => i.cid === el.getAttribute('data-cindy-mail-cid'));+ if (image && validMailImageUrl(image.url)) el.src = image.url;+ }+ };+ useEffect(refresh, [disabled, Boolean(onChange), JSON.stringify(images)]);+ useEffect(() => {+ if (!frame.current || typeof ResizeObserver === 'undefined') return;+ let width = -1;+ const observer = new ResizeObserver(entries => {+ const next = entries[0]?.contentRect.width;+ if (next !== width) { width = next; fit(); }+ }); observer.observe(frame.current);+ return () => observer.disconnect();+ }, [enlarged, reading]);+ const { t } = useTranslation();+ return <iframe ref={frame} title={t('chat.ghostCall.mailPreview')} sandbox="allow-same-origin" scrolling={reading ? 'no' : undefined}+ className="block w-full border-0" aria-busy="true"+ style={{ height: enlarged ? '100%' : 120, visibility: 'hidden', backgroundColor: 'transparent' }} srcDoc={html}+ onLoad={() => {+ const doc = frame.current?.contentDocument;+ if (!doc) return;+ stopTheme.current?.();+ stopTheme.current = followMailPreviewTheme(doc, document);+ bodyResize.current?.disconnect();+ // Font reflow and late images can change the document after iframe load.+ // Keep its full height so only the conversation owns vertical scrolling.+ if (!enlarged && typeof ResizeObserver !== 'undefined') {+ bodyResize.current = new ResizeObserver(fit);+ bodyResize.current.observe(doc.body);+ }+ const loaded = model.current;+ let composing = false;+ const update = (event: Event) => {+ if (composing || loaded !== model.current || current.current.disabled || !current.current.onChange) return;+ const el = (event.target as Element).closest<HTMLElement>('[data-cindy-mail-run]');+ if (!el) return;+ const id = el.getAttribute('data-cindy-mail-run')!;+ const edits = { ...loaded.edits, [id]: el.innerText ?? el.textContent ?? '' };+ const next = applyMailInlineEdits(loaded.source, edits);+ if (!next) return;+ loaded.edits = edits; loaded.emitted = next.html;+ current.current.onChange(next.html, next.text); fit();+ };+ doc.addEventListener('compositionstart', () => { composing = true; });+ doc.addEventListener('compositionend', event => { composing = false; update(event); });+ doc.addEventListener('input', update);+ doc.addEventListener('click', event => { if ((event.target as Element).closest('a')) event.preventDefault(); });+ doc.addEventListener('drop', event => event.preventDefault());+ doc.addEventListener('paste', event => {+ if (!current.current.onChange || current.current.disabled) return;+ event.preventDefault(); doc.execCommand('insertText', false, event.clipboardData?.getData('text/plain') || '');+ });+ doc.addEventListener('load', fit, true);+ refresh(); fit();+ // The authored document can paint before iframe load. Reveal only after+ // preview colors are adapted; autosave echoes keep this revision visible.+ frame.current!.style.visibility = 'visible';+ frame.current!.setAttribute('aria-busy', 'false');+ }} />;+}++export function MailHtmlPreview(props: PreviewProps) {+ const [open, setOpen] = useState(false);+ const { t } = useTranslation();+ if (props.reading) return <PreviewFrame {...props} />;+ return <div className="w-full min-w-0 py-2">+ <div className="mb-1 flex justify-end gap-2">+ <button type="button" title={t('chat.ghostCall.mailEnlarge')} aria-label={t('chat.ghostCall.mailEnlarge')}+ className="rounded p-1 text-muted-foreground hover:bg-[var(--surface-hover)]" onClick={props.onEnlarge ?? (() => setOpen(true))}><Maximize2 className="h-3.5 w-3.5" /></button>+ </div>+ <PreviewFrame {...props} />+ <Dialog.Root open={open} onOpenChange={setOpen}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-50 bg-black/40" />+ <Dialog.Content aria-describedby={undefined} className="fixed left-1/2 top-1/2 z-50 flex h-[85vh] w-[min(960px,94vw)] -translate-x-1/2 -translate-y-1/2 flex-col rounded-xl border border-border bg-[var(--surface-elevated)] p-4 shadow-xl">+ <div className="mb-3 flex items-center justify-between">+ <Dialog.Title className="text-sm font-medium">{t('chat.ghostCall.mailPreview')}</Dialog.Title>+ <Dialog.Close aria-label={t('common.close')} className="rounded p-1 text-muted-foreground hover:bg-[var(--surface-hover)]"><X className="h-4 w-4" /></Dialog.Close>+ </div>+ <div className="min-h-0 flex-1"><PreviewFrame {...props} enlarged /></div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ </div>;+}diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex e6e752c53d..5ee255a1ae 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -1,4 +1,5 @@import { scrollRangeIntoView } from '@/lib/scrollRangeIntoView';+import { readMailCard } from '@cindy/maker-shared/ghost-card-form';import { animateFocusScroll } from './animateFocusScroll';import { simplifyBotRenderItems } from '@/features/bots/botConversationPresentation';import { MessageViewport, type MessageViewportApi } from './MessageViewport';@@ -1497,6 +1498,8 @@ export function buildRenderItems(taskUpdates?: ReadonlyMap<string, AgentTaskUpdate>,ghostCards?: GhostCardSnapshot,opts?: {+ /** Live cards must belong to this task; explicit result IDs support history/forks. */+ sessionId?: string;/*** 还有更老的历史页没加载(= `messages` 只是窗口、不是全量)。为真时,凡靠* 「父调用在不在 messages 里」做的归属判定都不可信,必须放宽而不是丢弃。@@ -1773,6 +1776,18 @@ export function buildRenderItems(let pendingSegmentGhostCards: Extract<RenderItem, { type: 'ghost_card' }>[] = [];// 本次 build 内已被认领的活卡(claude 精确锚 / codex 启发式各认领一次)。const claimedLiveCallIds = new Set<string>();+ const sessionLiveCards = opts?.sessionId+ ? ghostCards?.liveCards.filter(lc => lc.sessionId === opts.sessionId) ?? []+ : [];+ // Mail is a finished document, not plugin progress. Without an exact tool ID,+ // wait for its result rather than attach it to a schema/read call by guesswork.+ const guessableLiveCards = sessionLiveCards.filter(lc => {+ const entry = ghostCards?.byCallId.get(lc.callId);+ return !(entry?.status === 'ready' && readMailCard(entry.html));+ });+ // Old partial history may omit a tool result. It cannot claim a new card just+ // because the same plugin was used there. Exact IDs still work across turns.+ const latestTurnStart = messages.findLastIndex(isRenderTurnBoundary);// 媒体回锚:本次 build 已上屏的 ghost_card item 按 callId 索引。后续调用的// tool_result 带 xdt_anchor_card_id 时按此把媒体挂回对应卡下方(item 是引用,// flush 进 items 后追加 media 仍然生效)。@@ -2093,6 +2108,7 @@ export function buildRenderItems(suppressMediaForCard = true;hideRowForCard = true;if (entry?.status === 'ready') {+ if (readMailCard(entry.html)?.supersededBy) return;const cardItem: Extract<RenderItem, { type: 'ghost_card' }> = {type: 'ghost_card',key: `ghostcard-${msg.clientId}`,@@ -2113,7 +2129,7 @@ export function buildRenderItems(}// in-flight:只认已 ready 的活卡(推送带 html 全量到,ready 是常态)。const live =- ghostCards.liveCards.find(+ sessionLiveCards.find((lc) =>!claimedLiveCallIds.has(lc.callId) &&!settledCardIds.has(lc.callId) &&@@ -2121,8 +2137,8 @@ export function buildRenderItems(typeof msg.toolUseId === 'string' &&lc.toolUseId === msg.toolUseId,) ??- (candidateGhostId- ? ghostCards.liveCards.find(+ (candidateGhostId && i >= latestTurnStart+ ? guessableLiveCards.find((lc) =>!claimedLiveCallIds.has(lc.callId) &&!settledCardIds.has(lc.callId) &&@@ -2133,9 +2149,11 @@ export function buildRenderItems(): undefined);if (!live) return;- if (ghostCards.byCallId.get(live.callId)?.status !== 'ready') return;+ const liveEntry = ghostCards.byCallId.get(live.callId);+ if (liveEntry?.status !== 'ready') return;claimedLiveCallIds.add(live.callId);hideRowForCard = true;+ if (readMailCard(liveEntry.html)?.supersededBy) { suppressMediaForCard = true; return; }const liveCardItem: Extract<RenderItem, { type: 'ghost_card' }> = {type: 'ghost_card',key: `ghostcard-${msg.clientId}`,@@ -2405,6 +2423,7 @@ export function buildCachedRenderItems(taskUpdates,ghostCards,ghostCards?.version,+ opts?.sessionId,opts?.historyWindowIncomplete,opts?.turnChangeSets,opts?.workingDir,@@ -3105,6 +3124,7 @@ export function MessageStream({],() =>buildCachedRenderItems(displayMessages, taskUpdates, ghostCardSnapshot, {+ sessionId,historyWindowIncomplete:!historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,turnChangeSets,@@ -3136,6 +3156,7 @@ export function MessageStream({build: (rows, _streaming, historyArtifacts) => {// History chunks are freshly assembled arrays, not reusable source snapshots.const chunk = buildRenderItems([...rows], taskUpdates, ghostCardSnapshot, {+ sessionId,historyWindowIncomplete: true,historyArtifacts,turnChangeSets,@@ -6488,6 +6509,7 @@ export function MessageStream({// 下一次 store 变更自愈。const entry = ghostCardSnapshot.byCallId.get(item.callId);if (!entry || entry.status !== 'ready') return null;+ if (readMailCard(entry.html)?.supersededBy) return null;// 常态包一层 div(结构稳定,回锚媒体到达时卡片 iframe 不重挂);// 回锚媒体(如 mivo 视频)挂卡正下方,与 tool_media 同款间距。return (diff --git a/apps/desktop/src/renderer/components/chat/__tests__/GhostCardForm.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/GhostCardForm.test.tsxnew file mode 100644index 0000000000..398b087a42--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/GhostCardForm.test.tsx@@ -0,0 +1,164 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { GhostCardForm } from '../GhostCardForm';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++afterEach(cleanup);+// Sent mail must lose empty add-recipient affordances, while existing Bcc stays viewable.+it('removes empty recipient fields after sending without hiding existing addresses', () => {+ let width = 500;+ let resize = () => {};+ vi.stubGlobal('ResizeObserver', class {+ constructor(callback: () => void) { resize = callback; }+ observe() {} disconnect() {}+ });+ const size = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width);+ const fields = [+ { name: 'to', label: 'To', value: '[email protected]', kind: 'recipients' as const },+ { name: 'cc', label: 'Cc', value: '', kind: 'recipients' as const },+ { name: 'bcc', label: 'Bcc', value: '[email protected]', kind: 'recipients' as const, collapsed: true },+ ];+ const onChange = vi.fn();+ try {+ const { rerender } = render(<GhostCardForm fields={fields} disabled={false} onChange={onChange} />);+ expect(screen.getByRole('button', { name: 'Cc: chat.ghostCall.expandFields (0)' })).toBeTruthy();+ rerender(<GhostCardForm fields={fields} disabled={false} readOnly onChange={onChange} />);+ expect(screen.queryByText('Cc')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.expandFields' }));+ expect(screen.queryByLabelText('Cc')).toBeNull();+ expect((screen.getByLabelText('To') as HTMLTextAreaElement).disabled).toBe(true);+ expect((screen.getByLabelText('Bcc') as HTMLTextAreaElement).value).toBe('[email protected]');+ expect((screen.getByLabelText('Bcc') as HTMLTextAreaElement).disabled).toBe(true);+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.collapseFields' }));+ rerender(<GhostCardForm fields={fields.map(f => f.name === 'bcc' ? { ...f, value: '' } : f)} disabled={false} readOnly onChange={onChange} />);+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.expandFields' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'To: [email protected]' })).toBeNull();+ width = 1;+ act(() => resize());+ expect(screen.getByRole('button', { name: 'chat.ghostCall.expandFields' })).toBeTruthy();+ width = 500;+ act(() => resize());+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.expandFields' })).toBeNull();+ } finally {+ size.mockRestore();+ vi.unstubAllGlobals();+ }+});++it('keeps recipient and multiline edits through re-renders and disables both while submitting', () => {+ const fields = [+ { name: 'to', label: 'To', value: '[email protected]' },+ { name: 'cc', label: 'Cc', value: '' },+ { name: 'body', label: 'Message', value: 'Original', multiline: true },+ ];+ const changed = vi.fn();+ const { rerender } = render(+ <GhostCardForm fields={fields} disabled={false} onChange={changed} />,+ );+ fireEvent.change(screen.getByLabelText('To'), { target: { value: '[email protected]' } });+ fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Edited\n\nSignature' } });+ expect(changed).toHaveBeenLastCalledWith({+ to: '[email protected]',+ cc: '',+ body: 'Edited\n\nSignature',+ });+ rerender(+ <GhostCardForm+ fields={fields.map((f) => ({+ ...f,+ value: f.name === 'cc' ? '[email protected]' : f.value,+ }))}+ disabled+ onChange={changed}+ />,+ );+ expect((screen.getByLabelText('To') as HTMLInputElement).value).toBe('[email protected]');+ expect((screen.getByLabelText('Cc') as HTMLInputElement).value).toBe('[email protected]');+ expect((screen.getByLabelText('Message') as HTMLTextAreaElement).disabled).toBe(true);+});++// User requirement: names fill the available width, and expanding must replace+// the summary while retaining every address in the editable/submitted value.+it('reflows recipients on resize and edits the full header without duplicate labels', () => {+ let width = 500;+ let resize = () => {};+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(callback: () => void) {+ resize = callback;+ }+ observe() {}+ disconnect() {}+ },+ );+ const size = vi+ .spyOn(HTMLElement.prototype, 'clientWidth', 'get')+ .mockImplementation(() => width);+ const rect = vi+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')+ .mockImplementation(function (this: HTMLElement) {+ return { width: this.dataset.measure?.startsWith('chip') ? 60 : 30 } as DOMRect;+ });+ const changed = vi.fn();+ const fields = [+ {+ name: 'to',+ label: 'To',+ kind: 'recipients' as const,+ row: 'recipients',+ },+ {+ name: 'cc',+ label: 'Cc',+ value: 'Emma <[email protected]>',+ kind: 'recipients' as const,+ row: 'recipients',+ },+ {+ name: 'bcc',+ label: 'Bcc',+ value: 'Hidden <[email protected]>',+ kind: 'recipients' as const,+ collapsed: true,+ },+ ];+ try {+ render(<GhostCardForm fields={fields} disabled={false} onChange={changed} />);+ expect(screen.getByRole('button', { name: 'To: Oliver <[email protected]>' })).toBeTruthy();+ expect(screen.queryByText('Bcc')).toBeNull();+ width = 230;+ act(() => resize());+ expect(screen.queryByRole('button', { name: 'To: Oliver <[email protected]>' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.expandFields' }));+ expect(screen.getAllByText('To')).toHaveLength(1);+ expect(screen.getAllByText('Cc')).toHaveLength(1);+ expect(screen.getAllByText('Bcc')).toHaveLength(1);+ for (const label of ['To', 'Cc', 'Bcc']) {+ expect((screen.getByLabelText(label) as HTMLTextAreaElement).rows).toBe(1);+ }+ fireEvent.change(screen.getByLabelText('Bcc'), {+ target: { value: 'Private <[email protected]>' },+ });+ expect((screen.getByLabelText('To') as HTMLTextAreaElement).value).toBe(fields[0].value);+ fireEvent.change(screen.getByLabelText('Cc'), { target: { value: 'New <[email protected]>' } });+ expect(changed).toHaveBeenLastCalledWith({+ to: fields[0].value,+ cc: 'New <[email protected]>',+ bcc: 'Private <[email protected]>',+ });+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.collapseFields' }));+ expect(screen.queryByText('Bcc')).toBeNull();+ width = 500;+ act(() => resize());+ expect(screen.getByRole('button', { name: 'Cc: New <[email protected]>' })).toBeTruthy();+ } finally {+ size.mockRestore();+ rect.mockRestore();+ vi.unstubAllGlobals();+ }+});diff --git a/apps/desktop/src/renderer/components/chat/__tests__/GhostMailHistory.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/GhostMailHistory.test.tsxnew file mode 100644index 0000000000..ed84e87f3c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/GhostMailHistory.test.tsx@@ -0,0 +1,19 @@+// @vitest-environment jsdom+import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { GhostMailHistory } from '../GhostMailHistory';+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+afterEach(cleanup);+it('starts collapsed and keeps every original recipient and quote readable without editing or sending', () => {+ const { container } = render(<GhostMailHistory fields={[+ { name: 'subject', label: 'Subject', value: 'Meeting' },+ { name: 'to', label: 'To', value: 'Jane <[email protected]>, Tim <[email protected]>' },+ { name: 'quote', label: 'Quote', value: '<img src=x> original' },+ ]} />);+ const details = container.querySelector('details')!;+ expect(details.open).toBe(false);+ details.open = true;+ expect(screen.getByText('Jane <[email protected]>, Tim <[email protected]>')).toBeTruthy();+ expect(screen.getByText('<img src=x> original')).toBeTruthy();+ expect(container.querySelector('input, textarea, button, iframe, img')).toBeNull();+});diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsxnew file mode 100644index 0000000000..161988af5d--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx@@ -0,0 +1,48 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { MailCardEditor } from '../GhostToolCard';+import { renderMailCard } from '../../../../main/cindy-brain/mailCards';+import { ingestCardPush } from '@/cindy-brain/ghostCardStore';+import type { MailCardData } from '@cindy/maker-shared/ghost-card-form';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/cindy-brain/useGhostCardThemeVars', () => ({ useGhostCardThemeVars: () => '' }));+vi.mock('@/features/right-sidebar/lib/mailPreview', () => ({ openMailCard: vi.fn() }));+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++// Regression boundary (unit): two views of one draft. Form-only tests do not+// cover the send bridge: sending from the stale view must use the delivered edit.+it('sends the latest delivered text when the other view has not repainted yet', async () => {+ vi.stubGlobal('matchMedia', () => ({ matches: true }));+ const mail: MailCardData = { accountId: 'account', draftId: 'draft', key: '10000000-0000-0000-0000-000000000000',+ from: 'sender', fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name === 'body' ? 'Original' : '', multiline: name === 'body' })),+ attachments: [], state: 'draft', status: 'Synced', sendLabel: 'Send', fromLabel: 'From' };+ const callId = 'shared-editor-test';+ let complete!: () => void;+ const dispatch = vi.fn((_id: string, action: string, _prompt: unknown, values: Record<string, string>) => {+ if (action.startsWith('mail:change:')) return new Promise<{ ok: boolean }>(resolve => {+ complete = () => {+ ingestCardPush({ callId, sessionId: 'editor-session', ghostId: 'provider', toolUseId: null, height: 80,+ html: renderMailCard({ ...mail, fields: mail.fields.map(f => ({ ...f, value: values[f.name] })) }) });+ resolve({ ok: true });+ };+ });+ return Promise.resolve({ ok: true });+ });+ vi.stubGlobal('electronAPI', { ghosts: { dispatchCardAction: dispatch } });+ const props = { callId, sessionId: 'editor-session', height: 80, html: renderMailCard(mail) };+ render(<><MailCardEditor {...props} /><MailCardEditor {...props} /></>);+ fireEvent.change(screen.getAllByLabelText('body')[0], { target: { value: 'Edited in sidebar' } });+ await act(async () => {});+ const frame = screen.getAllByTitle('mailReader.title')[1] as HTMLIFrameElement;+ frame.contentDocument!.open(); frame.contentDocument!.write(frame.srcdoc); frame.contentDocument!.close();+ fireEvent.load(frame);+ fireEvent.click(frame.contentDocument!.querySelector('[data-ghost-submit]')!);+ await act(async () => {});+ expect(dispatch).toHaveBeenCalledTimes(1);+ await act(async () => complete());+ expect(dispatch).toHaveBeenCalledTimes(2);+ expect(dispatch.mock.calls[1][1]).toBe(`mail:send:${mail.key}`);+ expect(dispatch.mock.calls[1][3].body).toBe('Edited in sidebar');+});diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsxnew file mode 100644index 0000000000..b04bcc349c--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx@@ -0,0 +1,278 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import { MailHtmlPreview, safeMailHtml } from '../MailHtmlPreview';+import { GhostCardForm } from '../GhostCardForm';+import { mailInlineBindingScript, mailInlineRefreshScript } from '@cindy/maker-shared/mail-text-edit';+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../ImageLightbox', () => ({ ImageLightbox: ({ src }: { src: string }) => <img alt="attachment-preview" src={src} /> }));+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+// Opening a draft in the sidebar must not create a second modal editor or save it.+it('routes both HTML and plain-text enlargement to the shared mail panel', () => {+ const enlarge = vi.fn(), change = vi.fn();+ const view = render(<GhostCardForm fields={[{ name: 'bodyHtml', label: 'Body', kind: 'mail-html', value: '<p>Hello</p>' }]}+ disabled={false} onChange={change} onEnlarge={enlarge} />);+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.mailEnlarge' }));+ expect(enlarge).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole('dialog')).toBeNull();+ view.rerender(<GhostCardForm fields={[{ name: 'body', label: 'Body', multiline: true, value: 'Hello' }]}+ disabled={false} onChange={change} onEnlarge={enlarge} />);+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.mailEnlarge' }));+ expect(enlarge).toHaveBeenCalledTimes(2);+ expect(change).not.toHaveBeenCalled();+ view.rerender(<GhostCardForm fields={[{ name: 'body', label: 'Body', multiline: true, value: 'Hello' }]}+ disabled={false} onChange={change} onEnlarge={enlarge} expanded />);+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailEnlarge' })).toBeNull();+});+// The sidebar previously inherited the compose card's 440px cap and left most+// of the reader empty. Body/font reflow and root margins were not covered by+// the image-load test, leaving a second scrolling viewport (unit regression).+it('lets the reader grow with long mail and late images while keeping chat cards compact', () => {+ const observers = new Map<Element, ResizeObserverCallback>();+ vi.stubGlobal('ResizeObserver', class {+ targets: Element[] = [];+ constructor(private callback: ResizeObserverCallback) {}+ observe(target: Element) { this.targets.push(target); observers.set(target, this.callback); }+ disconnect() { this.targets.forEach(target => observers.delete(target)); }+ });+ const view = render(<MailHtmlPreview value="<p>Long mail</p>" reading />);+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;+ const doc = frame.contentDocument!;+ doc.open(); doc.write(frame.srcdoc); doc.close();+ let height = 1500;+ Object.defineProperty(doc.body, 'scrollHeight', { get: () => height });+ Object.defineProperty(doc.documentElement, 'scrollHeight', { get: () => height + 40 });+ fireEvent.load(frame);+ expect(parseInt(frame.style.height)).toBeGreaterThanOrEqual(height + 40);+ height = 2000;+ doc.dispatchEvent(new Event('load'));+ expect(parseInt(frame.style.height)).toBeGreaterThanOrEqual(height + 40);+ height = 2400; // Fonts/reflow do not dispatch an image load event.+ observers.get(doc.body)!([], {} as ResizeObserver);+ expect(parseInt(frame.style.height)).toBeGreaterThanOrEqual(height + 40);+ height = 900;+ observers.get(doc.body)!([], {} as ResizeObserver);+ expect(parseInt(frame.style.height)).toBeLessThan(1000);+ view.unmount();+ expect(observers.has(doc.body)).toBe(false);+ render(<MailHtmlPreview value="<p>Long mail</p>" />);+ const card = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;+ Object.defineProperty(card.contentDocument!.body, 'scrollHeight', { value: height });+ fireEvent.load(card);+ expect(parseInt(card.style.height)).toBeLessThan(height);+});+// Dark neutral backgrounds merge into the reading surface. Light mode keeps+// authored white paper intact so signature images/tables don't acquire seams.+// Theme changes must never reload the preview or save a draft (unit regression).+it('adapts authored mail colors to the app theme and restores them without changing content', async () => {+ const change = vi.fn();+ const original = '<body style="background-color: rgb(240, 235, 220); color: rgb(25, 60, 50)"><div style="background:white;color:black"><p>Hello</p></div><img src="cid:photo"></body>';+ const root = document.documentElement;+ const oldClass = root.className, oldStyle = root.getAttribute('style');+ try {+ root.classList.remove('dark');+ root.style.setProperty('--surface', '#f2f2ee');+ root.style.setProperty('--text-primary', '#262626');+ root.style.setProperty('--border-default', '#444444');+ render(<MailHtmlPreview value={original} onChange={change} />);+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;+ const source = frame.srcdoc, doc = frame.contentDocument!;+ doc.open(); doc.write(source); doc.close(); fireEvent.load(frame);+ const paragraph = doc.querySelector('p'), image = doc.querySelector('img');+ const authored = doc.body.getAttribute('style');+ const neutral = doc.querySelector('div')!;+ expect(neutral.getAttribute('style')).toBe('background:white;color:black');+ expect(neutral.style.color).toBe('black');+ await act(async () => {+ root.classList.add('dark');+ root.style.setProperty('--surface', '#181818');+ root.style.setProperty('--text-primary', '#eeeeee');+ });+ expect(doc.body.style.backgroundColor).not.toBe('rgb(240, 235, 220)');+ expect(doc.body.style.color).not.toBe('rgb(25, 60, 50)');+ expect(neutral.style.backgroundColor).toBe('rgb(24, 24, 24)');+ expect(neutral.style.color).toBe('rgb(238, 238, 238)');+ expect(doc.body.style.backgroundColor).not.toBe(neutral.style.backgroundColor);+ expect(image?.getAttribute('style')).toBeNull();+ expect(frame.srcdoc).toBe(source);+ expect(doc.querySelector('p')).toBe(paragraph);+ await act(async () => {+ root.classList.remove('dark');+ root.style.setProperty('--surface', '#f2f2ee');+ root.style.setProperty('--text-primary', '#262626');+ });+ expect(doc.body.getAttribute('style')).toBe(authored);+ expect(neutral.getAttribute('style')).toBe('background:white;color:black');+ expect(neutral.style.color).toBe('black');+ expect(image?.getAttribute('style')).toBeNull();+ expect(frame.srcdoc).toBe(source);+ cleanup();+ expect(neutral.getAttribute('style')).toBe('background:white;color:black');+ expect(change).not.toHaveBeenCalled();+ } finally {+ root.className = oldClass;+ if (oldStyle === null) root.removeAttribute('style'); else root.setAttribute('style', oldStyle);+ }+});+// A new srcdoc can paint its authored light background before onLoad. Neither+// the reader nor the compose preview should reveal that unthemed document.+it('reveals each new document only after applying the initial dark theme', () => {+ const root = document.documentElement;+ const oldClass = root.className, oldStyle = root.getAttribute('style');+ const change = vi.fn();+ try {+ root.classList.add('dark');+ root.style.setProperty('--surface', '#181818');+ root.style.setProperty('--text-primary', '#eeeeee');+ const view = render(<MailHtmlPreview value='<body style="background:white;color:black"><p>Hello</p></body>' reading onChange={change} />);+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;+ const load = () => {+ const doc = frame.contentDocument!;+ doc.open(); doc.write(frame.srcdoc); doc.close(); fireEvent.load(frame);+ expect(doc.documentElement.style.colorScheme).toBe('dark');+ expect(doc.body.style.backgroundColor).not.toBe('white');+ expect(frame.style.visibility).toBe('visible');+ expect(frame.getAttribute('aria-busy')).toBe('false');+ };+ expect(frame.style.visibility).toBe('hidden');+ load();+ const run = frame.contentDocument!.querySelector<HTMLElement>('[data-cindy-mail-run]')!;+ run.textContent = 'Edited'; fireEvent.input(run);+ view.rerender(<MailHtmlPreview value={change.mock.calls.at(-1)![0]} reading onChange={change} />);+ expect(frame.style.visibility).toBe('visible');+ expect(frame.contentDocument!.querySelector('[data-cindy-mail-run]')).toBe(run);+ view.rerender(<MailHtmlPreview value='<body style="background:white;color:black"><p>AI update</p></body>' reading onChange={change} />);+ expect(frame.style.visibility).toBe('hidden');+ expect(frame.getAttribute('aria-busy')).toBe('true');+ load();+ expect(change).toHaveBeenCalledTimes(1);+ } finally {+ root.className = oldClass;+ if (oldStyle === null) root.removeAttribute('style'); else root.setAttribute('style', oldStyle);+ }+});+it('inserts an existing image part into the HTML and hides its duplicate attachment tile', () => {+ const change = vi.fn(), url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ render(<GhostCardForm disabled={false} onChange={change} fields={[+ { name: 'bodyHtml', label: 'Body', kind: 'mail-html', value: '<html><body><p>Hello</p></body></html>' },+ { name: 'attachmentItems', label: 'Files', kind: 'mail-attachments', value: JSON.stringify([{ key: 'part', filename: 'card.png', mimeType: 'image/png', previewUrl: url }]) },+ ]} />);+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.mailInsertImage' }));+ const values = change.mock.calls.at(-1)![0];+ expect(values.bodyHtml).toContain('src="cid:[email protected]"');+ expect(values.bodyHtml).not.toContain('cindy-media:');+ expect(values.bodyHtml).toMatch(/<\/p><\/body><\/html>$/);+ expect(JSON.parse(values.attachmentItems)).toHaveLength(1);+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailInsertImage' })).toBeNull();+ expect((screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement).srcdoc).toContain(url);+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailRemoveAttachment' })).toBeNull();+ expect(JSON.parse(values.attachmentItems)[0].contentId).toBe('[email protected]');+});+it('keeps formatting and tables but removes executable content and unsafe URLs', () => {+ const safe = safeMailHtml('<p onclick="evil()" style="color:red;background-image:url(https://example.test/track)"><b>Hello</b></p><table><tr><td>Cell</td></tr></table><script>evil()</script><iframe src=x></iframe><a href="javascript:evil()">Link</a><img src="file:///private" onerror="evil()">');+ expect(safe).toContain('<b>Hello</b>'); expect(safe).toContain('<td>Cell</td>');+ expect(safe).not.toMatch(/evil|javascript|file:|url\(|onclick|onerror|iframe/);+});+// Opening preview alone never mutates the draft. Typing happens in the rendered+// text itself; author scripts remain blocked (unit regression).+it('enlarges the read-only preview and reflects later AI updates without changing the draft', () => {+ const fields = [{ name: 'bodyHtml', label: 'Body', kind: 'mail-html' as const, value: '<p>Original</p>' }];+ const change = vi.fn();+ const { rerender } = render(<GhostCardForm fields={fields} disabled={false} onChange={change} />);+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.queryByRole('toolbar')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.mailEnlarge' }));+ expect(screen.getByRole('dialog')).toBeTruthy();+ expect(screen.getAllByTitle('chat.ghostCall.mailPreview')).toHaveLength(2);+ rerender(<GhostCardForm fields={[{ ...fields[0], value: '<p>AI updated</p>' }]} disabled={false} onChange={change} />);+ expect(screen.getAllByTitle('chat.ghostCall.mailPreview').every(frame => frame.getAttribute('srcdoc')?.includes('AI updated'))).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'common.close' }));+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(change).not.toHaveBeenCalled();+});+it('autosaves simple HTML text edits and the plain alternative, keeps the caret through echoes and locks sent mail', () => {+ const original = '<style>p{color:red}</style><p>Hello <b>Cherry</b></p><img src="cid:card">';+ const fields = [+ { name: 'bodyHtml', label: 'Body', kind: 'mail-html' as const, value: original },+ { name: 'body', label: 'Plain', kind: 'hidden' as const, value: 'Hello Cherry' },+ ];+ const change = vi.fn();+ const { rerender } = render(<GhostCardForm fields={fields} disabled={false} onChange={change} />);+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement;+ const src = frame.srcdoc;+ const doc = frame.contentDocument!;+ doc.open(); doc.write(src); doc.close(); fireEvent.load(frame);+ const input = doc.querySelector<HTMLElement>('[data-cindy-mail-run="0"]')!;+ expect(input.contentEditable).toBe('plaintext-only');+ fireEvent.compositionStart(input);+ input.textContent = '你好\n'; fireEvent.input(input);+ expect(change).not.toHaveBeenCalled();+ fireEvent.compositionEnd(input);+ const saved = change.mock.calls.at(-1)![0];+ expect(saved.body).toBe('你好\nCherry');+ expect(saved.bodyHtml).toContain('<p>你好<br><b>Cherry</b></p>');+ expect(saved.bodyHtml).toContain('<style>p{color:red}</style>');+ expect(saved.bodyHtml).toContain('src="cid:card"');+ expect(saved.bodyHtml).not.toContain('cindy-media:');+ rerender(<GhostCardForm fields={fields.map(f => ({ ...f, value: saved[f.name] }))} disabled={false} onChange={change} />);+ expect(frame.srcdoc).toBe(src);+ expect(doc.querySelector('[data-cindy-mail-run="0"]')).toBe(input);+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.queryByRole('toolbar')).toBeNull();+ rerender(<GhostCardForm fields={fields.map(f => ({ ...f, value: saved[f.name] }))} disabled readOnly onChange={change} />);+ expect(input.contentEditable).toBe('false');+ const count = change.mock.calls.length;+ input.textContent = 'Should not save'; fireEvent.input(input);+ expect(change).toHaveBeenCalledTimes(count);+ expect(screen.queryByRole('textbox')).toBeNull();+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailEditText' })).toBeNull();+});+it('native WebView binding emits only composed plain text and respects the read-only switch', () => {+ const doc = document.implementation.createHTMLDocument('mail');+ doc.body.innerHTML = '<p><span data-cindy-mail-run="0">Hello</span></p>';+ const postMessage = vi.fn();+ new Function('document', 'window', mailInlineBindingScript(7))(doc, { ReactNativeWebView: { postMessage } });+ new Function('document', mailInlineRefreshScript(true, []))(doc);+ const text = doc.querySelector('span')!;+ text.dispatchEvent(new Event('compositionstart', { bubbles: true })); text.textContent = '你好'; text.dispatchEvent(new Event('input', { bubbles: true }));+ expect(postMessage).not.toHaveBeenCalled();+ text.dispatchEvent(new Event('compositionend', { bubbles: true }));+ expect(JSON.parse(postMessage.mock.calls[0][0])).toEqual({ type: 'mail-text', documentId: 7, id: '0', text: '你好' });+ new Function('document', mailInlineRefreshScript(false, []))(doc);+ text.dispatchEvent(new Event('input', { bubbles: true }));+ expect(postMessage).toHaveBeenCalledTimes(1);+});+it('keeps the attachment gesture outside the preview and hides it for sent mail', () => {+ const attach = vi.fn(), fields = [{ name: 'attachmentItems', label: 'Files', kind: 'mail-attachments' as const, value: '[]' }];+ const { rerender } = render(<GhostCardForm fields={fields} disabled={false} onChange={() => {}} onAttach={attach} />);+ fireEvent.click(screen.getByRole('button', { name: 'chat.ghostCall.mailAttach' }));+ expect(attach).toHaveBeenLastCalledWith(false);+ rerender(<GhostCardForm fields={fields} disabled readOnly onChange={() => {}} onAttach={attach} />);+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailAttach' })).toBeNull();+});+it('retains a CID image without duplicate attachment controls or hidden metadata', () => {+ const change = vi.fn();+ render(<GhostCardForm fields={[+ { name: 'body', label: 'Plain', value: 'Body', kind: 'hidden' },+ { name: 'bodyHtml', label: 'Body', value: '<p>Body</p><img src="cid:[email protected]">', kind: 'mail-html' },+ { name: 'attachmentItems', label: 'Files', kind: 'mail-attachments', value: JSON.stringify([{ key: 'part', filename: 'photo.png', contentId: '<[email protected]>' }]) },+ ]} disabled={false} onChange={change} />);+ expect(screen.queryByLabelText('Plain')).toBeNull();+ expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailRemoveAttachment' })).toBeNull();+ expect(change).not.toHaveBeenCalled();+});+// Regression: full HTML cards lost head CSS/body background and class selectors.+it('preserves the authored document and opens an image attachment without editing it', () => {+ const html = '<html><head><style>.card{border-radius:12px;background:linear-gradient(white,pink)}@media(max-width:400px){.card{padding:8px}}</style></head><body style="background-color: ivory"><div class="card">Card</div></body></html>';+ const safe = safeMailHtml(html);+ expect(safe).toContain('.card{border-radius:12px');+ expect(safe).toContain('class="card"');+ expect(safe).toContain('background-color: ivory');+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`, change = vi.fn();+ render(<GhostCardForm disabled={false} onChange={change} fields={[+ { name: 'attachmentItems', label: 'Files', kind: 'mail-attachments', value: JSON.stringify([{ key: 'part', filename: 'card.png', mimeType: 'image/png', bytes: 1024, previewUrl: url }]) },+ ]} />);+ fireEvent.click(screen.getByRole('button', { name: /card.png/ }));+ expect(screen.getByAltText('attachment-preview').getAttribute('src')).toBe(url);+ expect(change).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts b/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.tsnew file mode 100644index 0000000000..2422ceb74b--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/mailPreviewAppearance.ts@@ -0,0 +1,66 @@+/** Preview-only paint. Source HTML, CID images and editing spans stay intact. */+export function followMailPreviewTheme(doc: Document, host: Document): () => void {+ let restore = () => {};+ let previous = '';+ const paint = () => {+ const root = host.documentElement;+ const theme = host.defaultView!.getComputedStyle(root);+ const dark = root.classList.contains('dark');+ const surface = theme.getPropertyValue('--surface').trim();+ const text = theme.getPropertyValue('--text-primary').trim();+ const border = theme.getPropertyValue('--border-default').trim();+ const key = JSON.stringify([dark, surface, text, border]);+ if (key === previous) return;+ previous = key;+ restore();+ // Light mode preserves authored paper, colors and decoration. Recoloring+ // white backgrounds there exposes seams around images and signature tables.+ if (!dark || !surface || !text || !doc.defaultView) return;++ // Read all authored colors before changing inheritance. Keep the original+ // inline attributes so theme changes and cleanup are lossless, even after typing.+ const nodes = Array.from(doc.querySelectorAll<HTMLElement>('html, body, body *'))+ .filter(el => el.tagName !== 'IMG');+ const authored = nodes.map(el => {+ const css = doc.defaultView!.getComputedStyle(el);+ return { el, style: el.getAttribute('style'), color: css.color, background: css.backgroundColor,+ image: css.backgroundImage, border: css.borderTopColor };+ });+ restore = () => {+ for (const { el, style } of authored) {+ if (style === null) el.removeAttribute('style'); else el.setAttribute('style', style);+ }+ };+ const colorInfo = (color: string) => {+ const rgb = color.match(/^rgba?\(([^)]+)\)/)?.[1].split(/[, /]+/).map(Number);+ if (!rgb || rgb.length < 3 || rgb[3] === 0) return null;+ return {+ brightness: (rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722) / 255,+ neutral: Math.max(...rgb.slice(0, 3)) - Math.min(...rgb.slice(0, 3)) <= 16,+ };+ };+ for (const entry of authored) {+ const { el } = entry;+ const set = (name: string, value: string) => el.style.setProperty(name, value, 'important');+ const background = colorInfo(entry.background), foreground = colorInfo(entry.color);+ if (background && background.brightness > 0.25) {+ // Ordinary white/gray mail should share the reading canvas. Mixing+ // white into dark surfaces creates a conspicuous gray rectangle.+ set('background-color', background.neutral ? surface : `color-mix(in srgb, ${surface} 92%, ${entry.background})`);+ }+ if (foreground && foreground.brightness < 0.72) {+ set('color', foreground.neutral ? text : `color-mix(in srgb, ${text} 80%, ${entry.color})`);+ }+ if (border && colorInfo(entry.border)) set('border-color', `color-mix(in srgb, ${border} 75%, ${entry.border})`);+ // CSS backgrounds are decoration (remote CSS URLs are already removed by+ // the sanitizer). Photos remain untouched; no inversion filter is used.+ if (entry.image && entry.image !== 'none') set('background-image', 'none');+ }+ doc.documentElement.style.setProperty('color-scheme', 'dark', 'important');+ doc.documentElement.style.setProperty('background-color', surface, 'important');+ };+ paint();+ const observer = new MutationObserver(paint);+ observer.observe(host.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] });+ return () => { observer.disconnect(); restore(); };+}diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsxindex e343c600f0..79b0fb1668 100644--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx@@ -39,6 +39,7 @@ import { getLinkOpenPreference, getLinkOpenPreferenceForUrl } from '@/hooks/useLimport { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';import type { SessionFileOrigin } from '@/lib/sessionFileOrigin';import { isSeparateLinkActivation, linkMenuPosition } from './linkInteraction';+import { readMailPreview, openMailPreview } from '@/features/right-sidebar/lib/mailPreview';/** 左键"按偏好直开"只对浏览器"作为页面渲染"有意义的 html 家族生效;其余本地* 文件保持原有"点击即预览"。右键菜单的 BROWSER_OPENABLE_EXTS 也收敛到@@ -63,6 +64,11 @@ export async function openUrlByPreference(url: string,t: TFunction,): Promise<void> {+ if (url.startsWith('https://')) {+ let supported = false;+ try { supported = (await readMailPreview(sessionId, url, false)).supported; } catch { /* Older hosts retain normal link opening. */ }+ if (supported) { await openMailPreview(sessionId, url); return; }+ }if (getLinkOpenPreferenceForUrl(url) === 'sidebar') {await openInSidebar(sessionId, url, t);return;diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsxindex 228a55e9c1..86dea366cb 100644--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx@@ -115,6 +115,7 @@ interface TabStripProps {const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {'file-browser': FolderTree,'web-browser': Globe,+ 'mail-preview': Globe,'retired-feature': Puzzle,terminal: Terminal,review: GitPullRequestArrow,@@ -130,6 +131,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {'file-browser': 'rightSidebar.tabs.kinds.fileBrowser','web-browser': 'rightSidebar.tabs.kinds.browser',+ 'mail-preview': 'mailReader.title','retired-feature': 'settings.ghosts.retirement.status',terminal: 'rightSidebar.tabs.kinds.terminal',review: 'rightSidebar.tabs.kinds.review',diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.tsindex aa192a27b6..d2ed98657d 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts@@ -1,4 +1,5 @@import { openRoutinesTab } from './openRoutinesTab';+import { openMailPreview, openMailCard } from './mailPreview';import { ensureBotWorkbenchTab, openBotWorkbenchTab } from './openBotWorkbenchTab';/** 执行 main 已裁决并推给当前 renderer host 的 RSB command。 */@@ -20,6 +21,14 @@ import { openUrlInSidebarBrowser } from './openInSidebarBrowser';/** 在 main 已选定的当前 renderer host 中执行命令,不自行选择宿主。 */export async function executeSidebarCommand(command: RsbWindowCommand): Promise<void> {+ if (command.type === 'open-mail-card') {+ await openMailCard(command.sessionId, command.callId);+ return;+ }+ if (command.type === 'open-mail-preview') {+ await openMailPreview(command.sessionId, command.url);+ return;+ }if (command.type === 'open-routines-tab') {await openRoutinesTab(command.sessionId, command.botId);return;diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.tsnew file mode 100644index 0000000000..c10f0ef604--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.ts@@ -0,0 +1,44 @@+import { REMOTE_RESOURCE_GET_CHANNEL, REMOTE_RESOURCE_PROTOCOL_VERSION } from '@cindy/device-link';+import { parseMailMessage } from '@cindy/maker-shared/mail-message';+import { pendingGhostCardFormDelivery } from '@cindy/maker-shared/ghost-card-form';+import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';+import { addOrFocusSingletonTab, ensureHydrated, patchTabState } from '../store';+import { routeSidebarCommand } from './detachedSidebarRouting';+import { requestRightSidebarVisibility } from './sidebarCommands';++export async function readMailPreview(sessionId: string, url: string, read: boolean, deviceId: string | null | undefined = getSessionDeviceId(sessionId), opened = false) {+ const raw = deviceId ? await window.electronAPI.deviceLink.invoke(deviceId, REMOTE_RESOURCE_GET_CHANNEL, [{+ client: { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: ['mail-message'] },+ ref: { collectionId: 'mail-messages', kind: 'message', id: JSON.stringify([sessionId, url, read]) },+ ...(opened ? { query: 'open' } : {}),+ }]) : await window.electronAPI.ghosts.mailPreview(sessionId, url, read, opened);+ const value = deviceId ? (raw as { blocks?: { data?: unknown }[] })?.blocks?.[0]?.data : raw;+ const result = value as { supported?: unknown; message?: unknown; error?: unknown } | undefined;+ return { supported: result?.supported === true, message: parseMailMessage(result?.message), error: typeof result?.error === 'string' ? result.error : undefined };+}+export async function openMailPreview(sessionId: string, url: string): Promise<void> {+ const routed = await routeSidebarCommand({ type: 'open-mail-preview', sessionId, url });+ if (routed !== 'attached') {+ if (routed === 'routed') requestRightSidebarVisibility('open', { sessionId });+ return;+ }+ await ensureHydrated(sessionId);+ const tab = await addOrFocusSingletonTab(sessionId, 'mail-preview', { url });+ await patchTabState(sessionId, tab.id, () => ({ url }));+ requestRightSidebarVisibility('open', { sessionId });+}++/** The sidebar refers to the existing card; it never creates a second draft. */+export async function openMailCard(sessionId: string, callId: string): Promise<void> {+ if (await pendingGhostCardFormDelivery(sessionId) === false) throw new Error('Draft sync failed');+ const routed = await routeSidebarCommand({ type: 'open-mail-card', sessionId, callId });+ if (routed !== 'attached') {+ if (routed === 'routed') requestRightSidebarVisibility('open', { sessionId });+ return;+ }+ await ensureHydrated(sessionId);+ const state = { url: '', callId };+ const tab = await addOrFocusSingletonTab(sessionId, 'mail-preview', state);+ await patchTabState(sessionId, tab.id, () => state);+ requestRightSidebarVisibility('open', { sessionId });+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.tsindex c3df787785..33d61d5a9a 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts@@ -11,6 +11,7 @@import './file-browser';import './web-browser';+import './mail-preview';import './retired-feature';import './terminal';import './review';diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody.tsxnew file mode 100644index 0000000000..dcb1f2bc6b--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody.tsx@@ -0,0 +1,60 @@+import { useEffect, useState, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';+import { readMailCard } from '@cindy/maker-shared/ghost-card-form';+import { getGhostCardSnapshot, subscribeGhostCards } from '@/cindy-brain/ghostCardStore';+import { MailCardEditor } from '@/components/chat/GhostToolCard';+import { ChatSessionFileProvider } from '@/components/chat/ChatSessionFileContext';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import { Button } from '@/components/ui/button';+import type { TabKindBodyProps } from '../../types';++type Card = { callId: string; ghostId: string; html: string; height: number };++/** Resolve only within this task. Persisted tab state contains an ID, never mail text. */+export function MailCardBody({ state, ctx }: TabKindBodyProps<{ callId: string }>) {+ const { t } = useTranslation();+ const snapshot = useSyncExternalStore(subscribeGhostCards, getGhostCardSnapshot);+ const owner = getDataOwnerGeneration();+ const binding = JSON.stringify([owner, ctx.sessionId, ctx.deviceLinkDeviceId, state.callId]);+ const [attempt, setAttempt] = useState(0);+ const [result, setResult] = useState<{ binding: string; cards: Card[]; requested?: string; error?: boolean }>();+ const rows = result?.binding === binding ? result.cards : [];+ let current = rows.find(c => c.callId === state.callId);+ let missing: string | undefined;+ const visited = new Set<string>();+ while (current && !visited.has(current.callId)) {+ visited.add(current.callId);+ const pushed = snapshot.byCallId.get(current.callId);+ if (pushed?.status === 'ready') current = { ...current, ...pushed };+ const mail = readMailCard(current.html);+ if (!mail) { current = undefined; break; }+ if (!mail.supersededBy) break;+ const next = rows.find(c => c.callId === mail.supersededBy);+ if (!next) { missing = mail.supersededBy; current = undefined; break; }+ const nextMail = readMailCard(next.html);+ if (visited.has(next.callId) || next.ghostId !== current.ghostId ||+ nextMail?.accountId !== mail.accountId || nextMail.draftId !== mail.draftId) { current = undefined; break; }+ current = next;+ }+ useEffect(() => {+ let active = true;+ if (ctx.deviceLinkDeviceId === undefined) return;+ // This editor uses local card actions. Never resolve a remote task's ID locally.+ if (ctx.deviceLinkDeviceId) { setResult({ binding, cards: [], error: true }); return; }+ void window.electronAPI.ghosts.listCardsBySession(ctx.sessionId).then(({ cards }) => {+ if (active && isDataOwnerGenerationCurrent(owner)) setResult({ binding, cards, requested: missing });+ }).catch(() => { if (active && isDataOwnerGenerationCurrent(owner)) setResult({ binding, cards: [], requested: missing, error: true }); });+ return () => { active = false; };+ }, [binding, missing, attempt]);+ const failed = result?.binding === binding && !current && (!missing || result.requested === missing);+ return <div className="h-full overflow-auto">+ {current ? <ChatSessionFileProvider value={{ sessionId: ctx.sessionId, workingDir: ctx.workdir, origin: { kind: 'local' } }}>+ <article className="mx-auto max-w-[960px] px-1 py-2" data-mail-panel-call-id={current.callId}>+ <MailCardEditor key={`${binding}:${current.callId}`} callId={current.callId} html={current.html} height={current.height} sessionId={ctx.sessionId} />+ </article>+ </ChatSessionFileProvider> : <div className="p-4 text-13 text-muted-foreground" role="status">+ {t(failed ? 'mailReader.failed' : 'mailReader.loading')}+ {failed && <Button variant="secondary" size="sm" onClick={() => setAttempt(n => n + 1)}>{t('mailReader.retry')}</Button>}+ </div>}+ </div>;+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsxnew file mode 100644index 0000000000..c6d9386af2--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx@@ -0,0 +1,156 @@+import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';+import { ChevronDown, ChevronRight } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { mailMessageFields, type MailMessage, type MailMessageSummary } from '@cindy/maker-shared/mail-message';+import { mailPreviewImages } from '@cindy/maker-shared/ghost-card-form';+import { MAIL_PAPER_COLOR } from '@cindy/maker-shared/mail-text-edit';+import { GhostCardForm } from '@/components/chat/GhostCardForm';+import { MailHtmlPreview } from '@/components/chat/MailHtmlPreview';+import { Button } from '@/components/ui/button';++type Props = {+ mail: MailMessage;+ openMailbox: ReactNode;+ read: (url: string, opened?: boolean) => Promise<{ message: MailMessage | null | undefined }>;+ retry: () => void;+};++function MessageBody({ mail }: { mail: MailMessage }) {+ const { t } = useTranslation();+ const fields = mailMessageFields(mail, key => t(`mailReader.${key}`));+ const values = Object.fromEntries(fields.map(f => [f.name, f.value]));+ return <>+ {mail.markReadFailed && <p role="status" className="mb-2 text-12 text-muted-foreground">{t('mailReader.markReadFailed')}</p>}+ <div className="mb-3 space-y-1 border-b border-border pb-3 text-12 text-muted-foreground">+ {fields.filter(f => f.kind === 'recipients' && f.value.trim()).map(f => <div key={f.name} className="flex gap-2">+ <span className="shrink-0">{f.label}</span><span className="min-w-0 break-words">{f.value}</span>+ </div>)}+ </div>+ {mail.bodyHtml ? <MailHtmlPreview value={mail.bodyHtml} images={mailPreviewImages(values)} reading />+ : <div className="whitespace-pre-wrap break-words p-1 text-14 leading-relaxed text-foreground">{mail.bodyText}</div>}+ <GhostCardForm fields={fields.filter(f => f.kind === 'mail-attachments')} disabled={false} readOnly onChange={() => {}} />+ </>;+}++function MessageRow({ summary, initial, selected, initiallyExpanded, accountId, read }: {+ summary: MailMessageSummary; initial?: MailMessage; selected: boolean; initiallyExpanded: boolean; accountId: string; read: Props['read'];+}) {+ const { t, i18n } = useTranslation();+ const [expanded, setExpanded] = useState(initiallyExpanded);+ const [message, setMessage] = useState(initial);+ const [failed, setFailed] = useState(false);+ const [attempt, setAttempt] = useState(0);+ const [opened, setOpened] = useState(false);+ useEffect(() => {+ if (!expanded || (message && !opened)) return;+ let active = true;+ setFailed(false);+ void read(summary.url, opened).then(result => {+ if (!active) return;+ if (!result.message || result.message.accountId !== accountId || result.message.messageId !== summary.messageId) {+ setFailed(true); return;+ }+ setMessage(result.message);+ setOpened(false);+ }).catch(() => { if (active) setFailed(true); });+ return () => { active = false; };+ }, [expanded, message, opened, attempt, read, summary.url, summary.messageId, accountId]);+ const dateText = message?.date || summary.date;+ const date = new Date(dateText);+ const validDate = !Number.isNaN(date.getTime());+ const formatted = validDate ? new Intl.DateTimeFormat(i18n?.language, { dateStyle: 'medium', timeStyle: 'short' }).format(date) : dateText;+ const from = message?.from || summary.from;+ return <section className="my-3 overflow-hidden rounded-xl border border-border bg-[var(--mail-paper)] dark:bg-[var(--surface)]"+ style={{ '--mail-paper': MAIL_PAPER_COLOR } as CSSProperties} data-mail-message-id={summary.messageId}>+ <button type="button" aria-expanded={expanded} aria-label={t(expanded ? 'mailReader.collapseMessage' : 'mailReader.expandMessage', { from })}+ onClick={() => { if (!expanded) setOpened(true); setExpanded(v => !v); }} className="flex min-h-11 w-full items-start gap-2 rounded-lg px-3 py-3 text-left hover:bg-muted/40 focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring">+ {expanded ? <ChevronDown className="mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <ChevronRight className="mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground" />}+ <span className="min-w-0 flex-1">+ <span className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">+ <span className="min-w-0 break-words text-13 font-medium text-foreground">{from || t('mailReader.title')}</span>+ <span className="flex items-center gap-2 text-12 text-muted-foreground">+ {selected && <span>{t('mailReader.currentMessage')}</span>}+ {dateText && <time dateTime={validDate ? date.toISOString() : undefined} title={dateText}>{formatted}</time>}+ </span>+ </span>+ {!expanded && <span className="mt-0.5 block truncate text-12 text-muted-foreground">{summary.snippet || summary.subject}</span>}+ </span>+ </button>+ {expanded && <div className="px-3 pb-3 pt-1">+ {message ? <MessageBody mail={message} /> : <div className="py-3 text-13 text-muted-foreground" role="status">+ {t(failed ? 'mailReader.failed' : 'mailReader.loading')}+ {failed && <Button className="ml-2" variant="secondary" size="sm" onClick={() => setAttempt(n => n + 1)}>{t('mailReader.retry')}</Button>}+ </div>}+ </div>}+ </section>;+}++/** One chronological reader, no provider-specific UI or eagerly fetched hidden bodies. */+export function MailConversationView({ mail, openMailbox, read, retry }: Props) {+ const { t } = useTranslation();+ const container = useRef<HTMLDivElement>(null);+ const content = useRef<HTMLDivElement>(null);+ const [revealed, setRevealed] = useState<Set<string>>(() => new Set());+ const messages = mail.conversation?.messages ?? [{ messageId: mail.messageId, url: '', from: mail.from, date: mail.date, subject: mail.subject, snippet: mail.bodyText.slice(0, 200) }];+ const selectedIndex = messages.findIndex(m => m.messageId === mail.messageId);+ useLayoutEffect(() => {+ const parent = container.current;+ const selected = parent?.querySelector<HTMLElement>('[data-current-mail]');+ if (!parent || !selected || !content.current) return;+ let position = parent.scrollTop;+ let observer: ResizeObserver | undefined;+ const align = () => {+ // Keep the initial selection in view as neighboring bodies finish loading.+ // Once scrolling moves away from our last position, leave control to the user.+ if (parent.scrollTop !== position) { observer?.disconnect(); return; }+ parent.scrollTop += selected.getBoundingClientRect().top - parent.getBoundingClientRect().top;+ position = parent.scrollTop;+ };+ if (typeof ResizeObserver !== 'undefined') observer = new ResizeObserver(align);+ const onScroll = () => { if (parent.scrollTop !== position) observer?.disconnect(); };+ align();+ observer?.observe(content.current);+ parent.addEventListener('scroll', onScroll, { passive: true });+ return () => { observer?.disconnect(); parent.removeEventListener('scroll', onScroll); };+ }, [mail.messageId]);+ const rows: ReactNode[] = [];+ for (let i = 0; i < messages.length;) {+ const visible = (index: number) => messages.length <= 6 || index === 0 || index >= messages.length - 2 ||+ Math.abs(index - selectedIndex) <= 2 || revealed.has(messages[index].messageId);+ if (!visible(i)) {+ const start = i;+ while (i < messages.length && !visible(i)) i++;+ const hidden = messages.slice(start, i);+ rows.push(<div key={`gap-${hidden[0].messageId}`} className="flex items-center gap-3 py-2">+ <span className="h-px flex-1 bg-border" />+ <Button variant="secondary" size="sm" onClick={() => setRevealed(old => new Set([...old, ...hidden.map(m => m.messageId)]))}>+ {t('mailReader.showMessages', { count: hidden.length })}+ </Button><span className="h-px flex-1 bg-border" />+ </div>);+ } else {+ const index = i++;+ const summary = messages[index];+ const selected = summary.messageId === mail.messageId;+ rows.push(<div key={summary.messageId} {...(selected ? { 'data-current-mail': true } : {})}>+ <MessageRow summary={summary} initial={selected ? mail : undefined} selected={selected}+ initiallyExpanded={messages.length <= 6 || Math.abs(index - selectedIndex) <= 2} accountId={mail.accountId} read={read} />+ </div>);+ }+ }+ return <div className="flex h-full min-h-0 flex-col">+ <header className="flex shrink-0 items-start justify-between gap-2 border-b border-border px-4 py-3">+ <div className="min-w-0">+ <h1 className="break-words pt-0.5 text-16 font-medium leading-snug text-foreground">{mail.subject || t('mailReader.title')}</h1>+ {messages.length > 1 && <p className="mt-1 text-12 text-muted-foreground">{t('mailReader.messageCount', { count: messages.length })}</p>}+ </div>{openMailbox}+ </header>+ <div ref={container} className="relative min-h-0 flex-1 overflow-auto px-4 pb-4">+ <div ref={content}>+ {mail.conversationUnavailable && <div role="status" className="py-2 text-12 text-muted-foreground">+ {t('mailReader.conversationFailed')} <Button tone="quiet" compact size="sm" onClick={retry}>{t('mailReader.retry')}</Button>+ </div>}+ {rows}+ </div>+ </div>+ </div>;+}diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsxnew file mode 100644index 0000000000..47575b4495--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx@@ -0,0 +1,126 @@+// @vitest-environment jsdom+import { cleanup, render, screen, act, fireEvent } from '@testing-library/react';+import { afterEach, expect, it, vi } from 'vitest';+import type { ReactNode } from 'react';+import type { GhostCardFormField } from '@cindy/maker-shared/ghost-card-form';+const h = vi.hoisted(() => ({ read: vi.fn(), owner: 1 }));+vi.mock('../../lib/mailPreview', () => ({ readMailPreview: h.read }));+vi.mock('../../registry', () => ({ registerTabKind: () => {} }));+vi.mock('@/contexts/dataOwnerGeneration', () => ({ getDataOwnerGeneration: () => h.owner, isDataOwnerGenerationCurrent: (o: number) => o === h.owner }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, args?: { from?: string; count?: number }) => args ? key + ' ' + (args.from ?? args.count) : key }) }));+vi.mock('@/components/chat/GhostCardForm', () => ({ GhostCardForm: ({ fields, readOnly }: { fields: GhostCardFormField[]; readOnly?: boolean }) => <div data-testid="body" data-readonly={readOnly}>{fields.find(f => f.name === 'body')?.value}</div> }));+vi.mock('@/components/chat/ChatSessionFileContext', () => ({ ChatSessionFileProvider: ({ children }: { children: ReactNode }) => children }));+vi.mock('@/components/chat/GhostToolCard', () => ({ MailCardEditor: ({ html, callId }: { html: string; callId: string }) => <div data-testid="editor" data-call-id={callId}>{readMailCard(html)?.fields.find(f => f.name === 'body')?.value}</div> }));+import { MailPreviewBody } from './index';+import { MailCardBody } from './MailCardBody';+import { renderMailCard } from '../../../../../main/cindy-brain/mailCards';+import { readMailCard } from '@cindy/maker-shared/ghost-card-form';+import { ingestCardPush } from '@/cindy-brain/ghostCardStore';+const ctx = { tabId: 'tab', sessionId: 'a', workdir: '', remoteHostId: null, deviceLinkDeviceId: null, patchState() {}, onVisibilityChange() {}, setCloseInterceptor: () => () => {} };+const mail = (bodyText: string) => ({ accountId: 'account', messageId: bodyText, from: 'sender', to: 'to', cc: '', bcc: '', subject: 'Subject', date: '', bodyText, bodyHtml: '', attachments: [] });+afterEach(() => { cleanup(); vi.clearAllMocks(); vi.unstubAllGlobals(); h.owner = 1; });++// New sidebar entry: follow host edits/supersession, but never reuse another task's card.+it('shows host edits and the latest card without leaking it when switching tasks', async () => {+ const card = (callId: string, body: string, supersededBy?: string) => ({ callId, ghostId: 'provider', height: 80,+ html: renderMailCard({ accountId: 'account', draftId: 'draft', key: '00000000-0000-0000-0000-000000000000', from: 'sender',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name === 'body' ? body : '' })),+ attachments: [], state: 'draft', status: 'Synced', sendLabel: 'Send', fromLabel: 'From', supersededBy }) });+ const first = card('panel-old', 'First');+ const list = vi.fn().mockResolvedValue({ cards: [first] });+ vi.stubGlobal('electronAPI', undefined);+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { ghosts: { listCardsBySession: list } } });+ const view = render(<MailCardBody ctx={ctx} state={{ callId: first.callId }} />);+ await act(async () => {});+ expect(screen.getByText('First')).toBeTruthy();+ act(() => ingestCardPush({ ...card(first.callId, 'Edited in card'), sessionId: 'a', toolUseId: null }));+ expect(screen.getByText('Edited in card')).toBeTruthy();+ const replacement = card('panel-new', 'AI updated');+ list.mockResolvedValue({ cards: [card(first.callId, 'Edited in card', replacement.callId), replacement] });+ await act(async () => ingestCardPush({ ...card(first.callId, 'Edited in card', replacement.callId), sessionId: 'a', toolUseId: null }));+ expect(screen.getByTestId('editor').getAttribute('data-call-id')).toBe(replacement.callId);+ expect(screen.getByText('AI updated')).toBeTruthy();+ list.mockResolvedValue({ cards: [] });+ view.rerender(<MailCardBody ctx={{ ...ctx, sessionId: 'b' }} state={{ callId: first.callId }} />);+ expect(screen.queryByText('AI updated')).toBeNull();+ await act(async () => {});+ expect(screen.queryByTestId('editor')).toBeNull();+ expect(screen.getByText('mailReader.failed')).toBeTruthy();+});+it('never paints a previous mail while switching tasks, including a late response', async () => {+ let first!: (v: unknown) => void;+ h.read.mockImplementationOnce(() => new Promise(resolve => { first = resolve; })).mockResolvedValue({ message: mail('Mail B') });+ const view = render(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} />);+ view.rerender(<MailPreviewBody state={{ url: 'https://mail.example/b' }} ctx={{ ...ctx, sessionId: 'b' }} />);+ await act(async () => {});+ expect(screen.getByText('Mail B')).toBeTruthy();+ await act(async () => { first({ message: mail('Mail A') }); });+ expect(screen.queryByText('Mail A')).toBeNull();+ expect(screen.getByTestId('body').getAttribute('data-readonly')).toBe('true');+});+it('removes already displayed content immediately when the account changes', async () => {+ h.read.mockResolvedValueOnce({ message: mail('Old account') }).mockImplementation(() => new Promise(() => {}));+ const view = render(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} />);+ await act(async () => {});+ expect(screen.getByText('Old account')).toBeTruthy();+ h.owner = 2;+ view.rerender(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} />);+ expect(screen.queryByText('Old account')).toBeNull();+});++// Right-side conversation reader: previous single-message tests did not cover+// chronological neighbors, collapsed middle history or expansion's account boundary.+// Regression: all neighbors used to be collapsed even beside the selected mail.+it('opens the selected mail and two neighbors each side, leaving distant bodies unloaded', async () => {+ const messages = Array.from({ length: 12 }, (_, i) => ({+ messageId: 'm' + i, url: 'https://mail.example/m' + i, from: 'Sender ' + i, date: '', subject: 'Subject', snippet: 'Snippet ' + i,+ }));+ const selected = { ...mail('Selected body'), messageId: 'm5', from: 'Sender 5', conversation: { threadId: 'thread', messages } };+ h.read.mockResolvedValueOnce({ message: selected }).mockImplementation(async (_session: string, url: string) => ({+ message: { ...mail('Body ' + url.split('/').pop()), messageId: url.split('/').pop(), from: 'Sender ' + url.split('/').pop()!.slice(1) },+ }));+ render(<MailPreviewBody state={{ url: 'https://mail.example/m5' }} ctx={ctx} />);+ await act(async () => {});+ expect(screen.getByText('Selected body')).toBeTruthy();+ expect(screen.getByText('Sender 0')).toBeTruthy();+ expect(screen.getByText('Sender 11')).toBeTruthy();+ expect(screen.queryByText('Sender 2')).toBeNull();+ for (const i of [3, 4, 6, 7]) expect(screen.getByText('Body m' + i)).toBeTruthy();+ expect(screen.queryByText('Body m0')).toBeNull();+ expect(screen.queryByText('Body m11')).toBeNull();+ expect(h.read).toHaveBeenCalledTimes(5);+ expect(h.read).toHaveBeenCalledWith('a', 'https://mail.example/m5', true, null, true);+ for (const i of [3, 4, 6, 7]) expect(h.read).toHaveBeenCalledWith('a', 'https://mail.example/m' + i, true, null, false);+ fireEvent.click(screen.getAllByRole('button', { name: 'mailReader.showMessages 2' })[0]);+ expect(screen.getByText('Sender 2')).toBeTruthy();+ expect(h.read).toHaveBeenCalledTimes(5);+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'mailReader.expandMessage Sender 2' })));+ expect(screen.getByText('Body m2')).toBeTruthy();+ expect(screen.getByText('Selected body')).toBeTruthy();+ expect(h.read).toHaveBeenLastCalledWith('a', 'https://mail.example/m2', true, null, true);+ fireEvent.click(screen.getByRole('button', { name: 'mailReader.collapseMessage Sender 2' }));+ expect(screen.queryByText('Body m2')).toBeNull();+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'mailReader.expandMessage Sender 2' })));+ expect(h.read).toHaveBeenCalledTimes(7);+});+it('rejects a mismatched mailbox on expansion and keeps the selected mail available', async () => {+ const selected = { ...mail('Selected'), conversation: { threadId: 'thread', messages: [+ { messageId: 'Selected', url: 'https://mail.example/a', from: 'Sender', date: '', subject: '', snippet: '' },+ { messageId: 'next', url: 'https://mail.example/next', from: 'Other', date: '', subject: '', snippet: '' },+ ] } };+ h.read.mockResolvedValueOnce({ message: selected }).mockResolvedValueOnce({ message: { ...mail('Wrong account'), accountId: 'other-account', messageId: 'next' } });+ const view = render(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} />);+ await act(async () => {});+ expect(screen.getByRole('button', { name: 'mailReader.collapseMessage Other' }).getAttribute('aria-expanded')).toBe('true');+ expect(screen.queryByText('Wrong account')).toBeNull();+ expect(screen.getByText('mailReader.failed')).toBeTruthy();+ expect(screen.getByText('Selected')).toBeTruthy();+ let late!: (v: unknown) => void;+ h.read.mockImplementationOnce(() => new Promise(resolve => { late = resolve; }));+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'mailReader.retry' })));+ h.read.mockResolvedValueOnce({ message: mail('New task') });+ view.rerender(<MailPreviewBody state={{ url: 'https://mail.example/new' }} ctx={{ ...ctx, sessionId: 'new' }} />);+ await act(async () => late({ message: { ...mail('Late body'), messageId: 'next' } }));+ expect(screen.queryByText('Late body')).toBeNull();+ expect(screen.getByText('New task')).toBeTruthy();+});diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/index.tsxnew file mode 100644index 0000000000..a2e94b6281--- /dev/null+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/index.tsx@@ -0,0 +1,55 @@+import { useCallback, useEffect, useState } from 'react';+import { ExternalLink, Mail } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import { type MailMessage } from '@cindy/maker-shared/mail-message';+import { ChatSessionFileProvider } from '@/components/chat/ChatSessionFileContext';+import { Button } from '@/components/ui/button';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import { registerTabKind } from '../../registry';+import type { TabKindBodyProps, TabKindPlugin } from '../../types';+import { readMailPreview } from '../../lib/mailPreview';+import { MailCardBody } from './MailCardBody';+import { MailConversationView } from './MailConversationView';++type State = { url: string; callId?: string };+export function MailPreviewBody({ state, ctx }: TabKindBodyProps<State>) {+ const { t } = useTranslation();+ const [attempt, setAttempt] = useState(0);+ const [result, setResult] = useState<{ binding: string; message?: MailMessage; error?: boolean }>();+ const owner = getDataOwnerGeneration();+ const binding = JSON.stringify([owner, ctx.sessionId, ctx.deviceLinkDeviceId, state.url, attempt]);+ useEffect(() => {+ let active = true;+ if (ctx.deviceLinkDeviceId === undefined) return;+ void readMailPreview(ctx.sessionId, state.url, true, ctx.deviceLinkDeviceId, true).then(r => {+ if (active && isDataOwnerGenerationCurrent(owner)) setResult({ binding, message: r.message ?? undefined, error: !r.message });+ }).catch(() => { if (active && isDataOwnerGenerationCurrent(owner)) setResult({ binding, error: true }); });+ return () => { active = false; };+ }, [binding]);+ const current = result?.binding === binding ? result : undefined;+ const mail = current?.message;+ const read = useCallback(async (url: string, opened = false) => {+ const response = await readMailPreview(ctx.sessionId, url || state.url, true, ctx.deviceLinkDeviceId, opened);+ return isDataOwnerGenerationCurrent(owner) ? response : { message: null };+ }, [owner, ctx.sessionId, ctx.deviceLinkDeviceId, state.url]);+ const openMailbox = <Button tone="quiet" compact size="sm" aria-label={t('mailReader.openMailbox')} title={t('mailReader.openMailbox')}+ onClick={() => { void window.electronAPI.openExternal(state.url); }}><ExternalLink className="h-4 w-4" /></Button>;+ return <div className="h-full min-h-0">+ {mail ? <ChatSessionFileProvider value={{ sessionId: ctx.sessionId, workingDir: ctx.workdir, origin: ctx.deviceLinkDeviceId ? { kind: 'device', deviceId: ctx.deviceLinkDeviceId } : { kind: 'local' } }}>+ <MailConversationView key={binding} mail={mail} openMailbox={openMailbox} read={read} retry={() => setAttempt(n => n + 1)} />+ </ChatSessionFileProvider> : <div className="p-4 text-13 text-muted-foreground" role="status">+ <div className="mb-3 flex justify-end">{openMailbox}</div>+ {t(current?.error ? 'mailReader.failed' : 'mailReader.loading')}+ {current?.error && <div className="mt-3"><Button variant="secondary" size="sm" onClick={() => setAttempt(n => n + 1)}>{t('mailReader.retry')}</Button></div>}+ </div>}+ </div>;+}+const plugin: TabKindPlugin<State> = {+ kind: 'mail-preview', menu: { kind: 'mail-preview', labelKey: 'mailReader.title', icon: Mail, order: 20, enabled: true, hiddenFromMenu: true, singleton: true },+ TabPillTitle: ({ t }) => <>{t('mailReader.title')}</>, TabPillIcon: () => <Mail size={13} />,+ TabBody: (props: TabKindBodyProps<State>) => props.state.callId ? <MailCardBody {...props} state={{ callId: props.state.callId }} /> : <MailPreviewBody {...props} />,+ defaultState: () => ({ url: '' }),+ hydrateState: raw => ({ url: typeof (raw as State)?.url === 'string' ? (raw as State).url : '',+ ...(typeof (raw as State)?.callId === 'string' && (raw as State).callId!.length <= 128 ? { callId: (raw as State).callId } : {}) }),+};+registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.tsindex 2582da1d9e..e6f894af10 100644--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts@@ -24,6 +24,7 @@ import type { TabCloseInterceptor } from './store';export type BuiltinTabKindId =| 'file-browser'| 'web-browser'+ | 'mail-preview'| 'retired-feature'| 'terminal'| 'review'diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 03925d5681..c9a45f213b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"Could not sync read status. Check mailbox authorization and reopen this email.","title":"Mail","openMailbox":"Open in mailbox","loading":"Loading email…","failed":"Could not load this email. Check the connected mailbox account, retry, or open it in your mailbox.","retry":"Retry","to":"To","cc":"Cc","bcc":"Bcc","subject":"Subject","currentMessage":"Current email","messageCount_other":"{{count}} emails","messageCount_one":"{{count}} email","showMessages_other":"Show {{count}} emails","showMessages_one":"Show {{count}} email","expandMessage":"Expand email from {{from}}","collapseMessage":"Collapse email from {{from}}","conversationFailed":"Other emails in this conversation could not be loaded.","messageCount":"{{count}} emails","showMessages":"Show {{count}} emails"},"logSupport": {"title": "Logs and Feedback","localFiles": "Choose logs from the day of the problem. Review unredacted files before sharing.",@@ -12032,7 +12033,17 @@"linkConfirmHint": "This link is provided by a plugin and will open in your browser:","linkConfirmOpen": "Open","linkConfirmCancel": "Cancel",- "linkOpenFailed": "Failed to open link"+ "expandFields": "Expand",+ "collapseFields": "Collapse",+ "formSyncFailed": "Card edits have not synced. Check the connection and continue editing; the message has not been sent.",+ "linkOpenFailed": "Failed to open link",+ "mailPreview": "Email preview",+ "mailEnlarge": "Enlarge preview",+ "mailInsertImage": "Insert into message",+ "mailAttach": "Add attachment",+ "mailRemoveAttachment": "Remove {{name}}",+ "mailUpdated": "Draft updated (read-only)",+ "mailLegacy": "Draft history (read-only)"},"ghostHook": {"blockedFallback": "Message blocked by a plugin; not sent",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex fa5011e60f..ccfe9df566 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。","title":"メール","openMailbox":"メールボックスで開く","loading":"メールを読み込み中…","failed":"メールを読み込めませんでした。接続したアカウントを確認して再試行するか、メールボックスで開いてください。","retry":"再試行","to":"宛先","cc":"Cc","bcc":"Bcc","subject":"件名","currentMessage":"現在のメール","messageCount_other":"{{count}} 件のメール","messageCount_one":"{{count}} 件のメール","showMessages_other":"{{count}} 件のメールを表示","showMessages_one":"{{count}} 件のメールを表示","expandMessage":"{{from}} からのメールを展開","collapseMessage":"{{from}} からのメールを折りたたむ","conversationFailed":"前後のメールを読み込めませんでした。","messageCount":"{{count}} 件のメール","showMessages":"{{count}} 件のメールを表示"},"logSupport": {"title": "ログとフィードバック","localFiles": "問題が発生した日のログを選択してください。未マスキングのため、共有前に内容を確認してください。",@@ -11972,7 +11973,17 @@"linkConfirmHint": "このリンクはプラグインが提供したもので、ブラウザで開きます:","linkConfirmOpen": "開く","linkConfirmCancel": "キャンセル",- "linkOpenFailed": "リンクを開けませんでした"+ "expandFields": "展開",+ "collapseFields": "折りたたむ",+ "formSyncFailed": "カードの変更を同期できませんでした。接続を確認して編集を続けてください。メッセージは未送信です。",+ "linkOpenFailed": "リンクを開けませんでした",+ "mailPreview": "メールプレビュー",+ "mailEnlarge": "拡大表示",+ "mailInsertImage": "本文に挿入",+ "mailAttach": "添付ファイルを追加",+ "mailRemoveAttachment": "{{name}}を削除",+ "mailUpdated": "更新済みの下書き(読み取り専用)",+ "mailLegacy": "下書きの履歴(読み取り専用)"},"ghostHook": {"blockedFallback": "メッセージはプラグインによりブロックされました(未送信)",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5fc363adb2..4a2a15dd19 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.","title":"메일","openMailbox":"메일함에서 열기","loading":"메일 읽는 중…","failed":"메일을 읽지 못했습니다. 연결된 계정을 확인하고 다시 시도하거나 메일함에서 여세요.","retry":"다시 시도","to":"받는 사람","cc":"참조","bcc":"숨은 참조","subject":"제목","currentMessage":"현재 메일","messageCount_other":"메일 {{count}}개","messageCount_one":"메일 {{count}}개","showMessages_other":"메일 {{count}}개 펼치기","showMessages_one":"메일 {{count}}개 펼치기","expandMessage":"{{from}}의 메일 펼치기","collapseMessage":"{{from}}의 메일 접기","conversationFailed":"앞뒤 메일을 불러오지 못했습니다.","messageCount":"메일 {{count}}개","showMessages":"메일 {{count}}개 펼치기"},"logSupport": {"title": "로그 및 피드백","localFiles": "문제가 발생한 날짜의 로그를 선택하세요. 민감 정보가 가려지지 않았으므로 공유 전에 확인하세요.",@@ -11972,7 +11973,17 @@"linkConfirmHint": "이 링크는 플러그인이 제공한 것으로, 브라우저에서 열립니다:","linkConfirmOpen": "열기","linkConfirmCancel": "취소",- "linkOpenFailed": "링크를 열지 못했습니다"+ "expandFields": "펼치기",+ "collapseFields": "접기",+ "formSyncFailed": "카드 변경 사항이 동기화되지 않았습니다. 연결을 확인한 후 편집을 계속하세요. 메시지는 전송되지 않았습니다.",+ "linkOpenFailed": "링크를 열지 못했습니다",+ "mailPreview": "메일 미리보기",+ "mailEnlarge": "확대 보기",+ "mailInsertImage": "본문에 삽입",+ "mailAttach": "첨부 파일 추가",+ "mailRemoveAttachment": "{{name}} 삭제",+ "mailUpdated": "업데이트된 초안 (읽기 전용)",+ "mailLegacy": "초안 기록 (읽기 전용)"},"ghostHook": {"blockedFallback": "메시지가 플러그인에 의해 차단되어 전송되지 않았습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 4c8dc137fd..d9213bb54c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"未能同步已读状态,请检查邮箱授权后重新打开。","title":"邮件","openMailbox":"在邮箱中打开","loading":"正在读取邮件…","failed":"未能读取这封邮件。请检查连接的邮箱账号后重试,或在邮箱中打开。","retry":"重试","to":"收件人","cc":"抄送","bcc":"密送","subject":"主题","currentMessage":"当前邮件","messageCount_other":"共 {{count}} 封邮件","messageCount_one":"共 {{count}} 封邮件","showMessages_other":"展开 {{count}} 封邮件","showMessages_one":"展开 {{count}} 封邮件","expandMessage":"展开来自 {{from}} 的邮件","collapseMessage":"收起来自 {{from}} 的邮件","conversationFailed":"暂时无法读取前后邮件。","messageCount":"共 {{count}} 封邮件","showMessages":"展开 {{count}} 封邮件"},"logSupport": {"title": "日志与反馈","localFiles": "选择问题当天的日志。文件未脱敏,请先检查。",@@ -11972,7 +11973,17 @@"linkConfirmHint": "该链接由插件提供,将在系统浏览器中打开:","linkConfirmOpen": "打开","linkConfirmCancel": "取消",- "linkOpenFailed": "链接打开失败"+ "expandFields": "展开",+ "collapseFields": "收起",+ "formSyncFailed": "卡片修改尚未同步,请检查连接后继续编辑;消息尚未发送。",+ "linkOpenFailed": "链接打开失败",+ "mailPreview": "邮件预览",+ "mailEnlarge": "放大查看",+ "mailInsertImage": "插入正文",+ "mailAttach": "添加附件",+ "mailRemoveAttachment": "移除 {{name}}",+ "mailUpdated": "草稿已更新(只读)",+ "mailLegacy": "历史草稿(只读)"},"ghostHook": {"blockedFallback": "消息被插件拦下,未发送",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5e082fa921..6a8cd05dd5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"未能同步已讀狀態,請檢查信箱授權後重新開啟。","title":"郵件","openMailbox":"在信箱中開啟","loading":"正在讀取郵件…","failed":"未能讀取這封郵件。請檢查連接的信箱帳號後重試,或在信箱中開啟。","retry":"重試","to":"收件人","cc":"副本","bcc":"密件副本","subject":"主旨","currentMessage":"目前郵件","messageCount_other":"共 {{count}} 封郵件","messageCount_one":"共 {{count}} 封郵件","showMessages_other":"展開 {{count}} 封郵件","showMessages_one":"展開 {{count}} 封郵件","expandMessage":"展開來自 {{from}} 的郵件","collapseMessage":"收起來自 {{from}} 的郵件","conversationFailed":"暫時無法讀取前後郵件。","messageCount":"共 {{count}} 封郵件","showMessages":"展開 {{count}} 封郵件"},"logSupport": {"title": "日誌與回饋","localFiles": "選擇問題當天的日誌。檔案未經去識別化處理,請先檢查。",@@ -11971,7 +11972,17 @@"linkConfirmHint": "該連結由插件提供,將在系統瀏覽器中開啟:","linkConfirmOpen": "開啟","linkConfirmCancel": "取消",- "linkOpenFailed": "連結開啟失敗"+ "expandFields": "展開",+ "collapseFields": "收起",+ "formSyncFailed": "卡片修改尚未同步,請檢查連線後繼續編輯;訊息尚未傳送。",+ "linkOpenFailed": "連結開啟失敗",+ "mailPreview": "郵件預覽",+ "mailEnlarge": "放大檢視",+ "mailInsertImage": "插入內文",+ "mailAttach": "新增附件",+ "mailRemoveAttachment": "移除 {{name}}",+ "mailUpdated": "草稿已更新(唯讀)",+ "mailLegacy": "歷史草稿(唯讀)"},"ghostHook": {"blockedFallback": "訊息被插件攔下,未傳送",diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 007d603952..935be5ff8d 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -1,3 +1,4 @@+import { pendingGhostCardFormDelivery } from '@cindy/maker-shared/ghost-card-form';import { readBotTaskResults } from '@cindy/maker-shared/botCollaboration';import { asyncQuestionNeedsSupplement, formatAsyncQuestionSupplement } from '@cindy/maker-shared/interaction';import { isComposerTypingRecently } from './composerTypingActivity';@@ -14860,6 +14861,11 @@ function sendMessage(if ((!text.trim() && (!files || files.length === 0)) || !workingDir)return Promise.resolve(false);if (isRemoteDeletedSessionSendBlocked(sessionId)) return Promise.resolve(false);+ const formDelivery = pendingGhostCardFormDelivery(sessionId);+ if (formDelivery) {+ const beforeEnqueue = opts?.beforeEnqueue;+ opts = { ...opts, beforeEnqueue: async () => await formDelivery && (beforeEnqueue ? await beforeEnqueue() : true) };+ }const remoteScopeAtStart = captureRemoteOptimisticSendScope(sessionId,opts?.onRemoteOptimisticFailure,diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8cd154f4b8..b49929cac9 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1275,6 +1275,7 @@ 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 }>;recommendationsSync: () => import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot;/** 首帧同步拉取已装清单(规则 7:意识面板与内置面板同帧注册,无跳变)。 */listSync: () => { ghosts: import('../shared/ghost').InstalledGhost[] };@@ -1438,6 +1439,7 @@ interface ElectronAPI {onCardUpdated: (callback: (payload: {callId: string;+ sessionId?: string | null;ghostId: string;logicalGhostId?: string;toolUseId: string | null;@@ -1471,6 +1473,8 @@ interface ElectronAPI {callId: string,actionId: string,prompt?: string,+ formValues?: Record<string, string>,+ formChange?: boolean,) => Promise<{ ok: boolean }>;/** 订阅槽①:用户消息被意识钩子拦下(renderer 把乐观气泡原地降级为被拦态;* 没有既有气泡时用 text 补渲一条——排队消息被拦不无声蒸发)。 */diff --git a/apps/desktop/src/shared/__tests__/mailMessage.test.ts b/apps/desktop/src/shared/__tests__/mailMessage.test.tsnew file mode 100644index 0000000000..bc45850f76--- /dev/null+++ b/apps/desktop/src/shared/__tests__/mailMessage.test.ts@@ -0,0 +1,29 @@+import { expect, it } from 'vitest';+import { parseMailMessage, parseMailReader, mailMessageFields } from '@cindy/maker-shared/mail-message';+import { validateGhostManifest } from '../ghost';+it('preserves a declared reader through manifest normalization', () => {+ const reader = { tool: 'read_mail', hosts: ['mail.example.com'], markRead: true };+ const result = validateGhostManifest({ schemaVersion: 3, minCindyVersion: '0.1.92', id: 'example-mail', name: 'Mail', version: '1.0.0', entry: 'main.js', agent: {}, mail: true, mailReader: reader,+ tools: [{ name: 'read_mail', description: 'Read only', parameters: { type: 'object', properties: {} } }] });+ expect(result.ok, result.ok ? '' : result.reason).toBe(true);+ if (result.ok) expect(result.manifest.mailReader).toEqual(reader);+ expect(parseMailReader({ tool: 'read_mail', hosts: ['*.com'] })).toBeNull();+});+it('accepts large read-only HTML, filters untrusted preview URLs and preserves CID', () => {+ const message = parseMailMessage({ accountId: 'a', messageId: 'm', from: 'A', to: 'B', cc: '', bcc: '', subject: 'Subject', date: '', bodyText: 'text', bodyHtml: '<p>' + 'x'.repeat(70000) + '</p>',+ attachments: [{ key: 'part', filename: 'image.png', contentId: 'photo', previewUrl: 'https://tracker.example/a' }] });+ expect(message).not.toBeNull();+ expect(message!.attachments[0].previewUrl).toBeUndefined();+ expect(message!.attachments[0].contentId).toBe('photo');+ expect(mailMessageFields(message!, k => k).some(f => f.kind === 'mail-html')).toBe(true);+});+it('drops invalid history without losing the selected message or accepting duplicate IDs', () => {+ const mail = { accountId: 'a', messageId: 'm', from: '', to: '', cc: '', bcc: '', subject: '', date: '', bodyText: 'selected', bodyHtml: '', attachments: [] };+ const summary = { messageId: 'm', url: 'https://mail.example.com/m', from: '', date: '', subject: '', snippet: '' };+ for (const messages of [[summary, summary], [{ ...summary, messageId: 'other' }], [{ ...summary, url: 'javascript:alert(1)' }]]) {+ const parsed = parseMailMessage({ ...mail, conversation: { threadId: 'thread', messages } });+ expect(parsed?.bodyText).toBe('selected');+ expect(parsed?.conversation).toBeUndefined();+ expect(parsed?.conversationUnavailable).toBe(true);+ }+});diff --git a/apps/desktop/src/shared/__tests__/toolResultPersistCap.test.ts b/apps/desktop/src/shared/__tests__/toolResultPersistCap.test.tsindex 6398d9afac..177e0c7a18 100644--- a/apps/desktop/src/shared/__tests__/toolResultPersistCap.test.ts+++ b/apps/desktop/src/shared/__tests__/toolResultPersistCap.test.ts@@ -43,6 +43,17 @@ describe('capToolResultTextForPersist', () => {expect(capped.length).toBeLessThanOrEqual(100);expect(capped.endsWith(TOOL_RESULT_PERSIST_TRUNCATION_SUFFIX)).toBe(true);});++ // Long HTML draft read-backs used to lose their trailing card ID at 8KB.+ // Check the actual persistence entry point, including phone byte budgets.+ it('preserves card references as valid bounded JSON when the body is oversized', () => {+ const input = JSON.stringify({ ok: true, result: { bodyHtml: '你好\\"😀'.repeat(4000) },+ xdt_card_id: 'draft-card', xdt_anchor_card_id: 'original-card' });+ const stored = capToolResultTextForPersist(input);+ expect(JSON.parse(stored)).toMatchObject({ ok: true, xdt_card_id: 'draft-card', xdt_anchor_card_id: 'original-card' });+ expect(new TextEncoder().encode(stored).length).toBeLessThanOrEqual(8192);+ expect(capToolResultTextForPersist(stored)).toBe(stored);+ });});describe('capImportedToolResultContent', () => {diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 65f1971664..1cb5b57bc6 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1,4 +1,5 @@import { parseGhostRoutineEvents, type GhostRoutineEvents } from '@cindy/plugin-protocol';+import { parseMailReader } from '@cindy/maker-shared/mail-message';import { parsePluginAuthorizationRequest, type PluginAuthorizationRequest, type PluginAuthorizationResult } from '@cindy/device-link';import {type GhostRecommendation,@@ -1477,6 +1478,10 @@ export interface GhostManifest {* externalLinks: true 时卡片内可声明 data-ghost-link,点击经宿主确认框后打开浏览器。*/card?: GhostCardNeeds;+ /** Host-owned mail editor; providers supply mailbox adapters only. */+ mail?: true;+ /** Fixed read-only tool for native mail previews; URLs must match an exact HTTPS host. */+ mailReader?: import('@cindy/maker-shared/mail-message').MailReaderDeclaration;/** 注册给 agent 的工具声明;字段本身就是能力声明。 */tools?: GhostToolDecl[];/** `@` 面板入口由已安装插件的 command 提供;不支持资源搜索字段。 */@@ -2994,6 +2999,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set(['settingsHeight','slots','card',+ 'mail','tools','cindy','model',@@ -3111,6 +3117,7 @@ function prepareGhostManifestForValidation(}}+ if (value.mail !== undefined && value.mail !== true) return { ok: false, reason: 'mail 出现时必须是 true' };const syntheticSlots: string[] = [];for (const [field, slot] of V3_DECLARATION_TO_LEGACY_SLOT) {if (value[field] !== undefined) syntheticSlots.push(slot);@@ -3708,6 +3715,7 @@ export function validateGhostManifestLocaleResource(...(typeof description === 'string' ? { description } : {}),...(typeof whenToUse === 'string' ? { whenToUse } : {}),...(tools !== undefined ? { tools } : {}),+ ...(raw.mail === true ? { mail: true as const } : {}),...(panel !== undefined ? { panel } : {}),...(mainView !== undefined ? { mainView } : {}),...(network !== undefined ? { network } : {}),@@ -6021,6 +6029,8 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo...(raw.mobile !== undefined ? { mobile: raw.mobile as GhostManifest['mobile'] } : {}),...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),...(tools !== undefined ? { tools } : {}),+ ...(raw.mail === true ? { mail: true as const } : {}),+ ...(parseMailReader(raw.mailReader) ? { mailReader: parseMailReader(raw.mailReader)! } : {}),...(card !== undefined || prepared.v3BaseCard || slots.includes('card')? { card: card ?? {} }: {}),@@ -6902,6 +6912,8 @@ export type GhostMediaModelsResult =*/export interface GhostPipeCardUpdate {type: 'card-update';+ /** Active tool call in the same task, when refreshing an earlier owned card. */+ sourceCallId?: string;/** 归因号:tool-call 下发的 callId 原样带回(主机验"这单是不是派给你的")。 */callId: string;/** 卡片正文(静态 HTML+CSS;≤ GHOST_CARD_HTML_MAX_BYTES,超限整条拒)。 */@@ -8049,6 +8061,12 @@ export type GhostPipeEventPush =* 按钮永远没有此字段。*/prompt?: string;+ /** Text fields collected by the Host from a declarative card form. Never credentials. */+ formValues?: Record<string, string>;+ /** Host-selected single file. Never supplied by plugin HTML or form text. */+ mailAttachment?: { path: string; filename: string; bytes: number; sha256: string; contentId?: string };+ /** Passive editor update: no user-action token, no Agent continuation. */+ formChange?: boolean;/*** 主机铸造的衍生卡位(`<根callId>::sp<序>`,见 GHOST_CARD_SPAWN_SEP)。* 对它 card-update = 原卡下方长出新卡(原卡保留,母卡按钮可反复点);diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.tsindex 64e6e0dd85..f2acf6f2cb 100644--- a/apps/desktop/src/shared/rightSidebarWindow.ts+++ b/apps/desktop/src/shared/rightSidebarWindow.ts@@ -51,6 +51,8 @@ export type RsbWindowCommand =| { type: 'open-terminal'; sessionId: string }| { type: 'toggle-review-tab'; sessionId: string }| { type: 'open-web-browser'; sessionId: string; url: string }+ | { type: 'open-mail-preview'; sessionId: string; url: string }+ | { type: 'open-mail-card'; sessionId: string; callId: string }| {type: 'ensure-orca-workers-tab';sessionId: string;diff --git a/apps/desktop/src/shared/toolResultPersistCap.ts b/apps/desktop/src/shared/toolResultPersistCap.tsindex ea381b441a..f72cba5084 100644--- a/apps/desktop/src/shared/toolResultPersistCap.ts+++ b/apps/desktop/src/shared/toolResultPersistCap.ts@@ -4,7 +4,8 @@* 背景:7GB 级本地库里 tool_result 占了绝对大头(单条可达 MB 级、177 万行里* 4.5GB),而它既不进 FTS、不进嵌入、不做侧栏预览,device-link 同步到手机也早已* 截到 8KB(dispatch.ts REMOTE_TOOL_RESULT_CONTENT_LIMIT)。本地持久化对齐同一- * 阈值:重开任务仍能看到开头 8K 字符,当前 turn 的完整内容继续走内存+ * 阈值:重开任务仍能看到开头 8K 字符;含卡片关联的结果保留关联及短预览的合法 JSON,+ * 避免截断破坏卡片配对。当前 turn 的完整内容继续走内存* resolvedContent,Agent 续跑走 SDK transcript,不依赖这张表。** 媒体挂账契约:截断丢弃的尾部可能含首次出现的 cindy-media blob URL,调用方@@ -21,6 +22,29 @@ export const TOOL_RESULT_PERSIST_CONTENT_LIMIT = 8 * 1024;export const TOOL_RESULT_PERSIST_TRUNCATION_SUFFIX ='\n\n[tool result truncated: stored first 8KB]';+/** Keep presentation references parseable; the full card lives in the card store.+ * Self-contained so the legacy inline DB worker can use the same implementation. */+export function compactToolCardResult(text: string, limit: number): string | null {+ if (!text.includes('"xdt_card_id"') && !text.includes('"xdt_anchor_card_id"')) return null;+ try {+ const payload = JSON.parse(text);+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;+ const references: Record<string, unknown> = {};+ for (const key of ['xdt_card_id', 'xdt_anchor_card_id']) {+ const value = payload[key];+ if (typeof value === 'string' && value.length > 0 && value.length <= 128) references[key] = value;+ }+ if (!Object.keys(references).length) return null;+ if (typeof payload.ok === 'boolean') references.ok = payload.ok;+ const summary = { ...references, truncated: true, preview: '' };+ const overhead = new TextEncoder().encode(JSON.stringify(summary)).length;+ if (overhead > limit) return null;+ // Six bytes per code unit also covers JSON escaping and unpaired surrogates.+ summary.preview = text.slice(0, Math.min(1024, Math.floor((limit - overhead) / 6)));+ return JSON.stringify(summary);+ } catch { return null; }+}+/*** 把 tool_result 正文截到落库上限,超限时带截断后缀。按字符数截(不是字节):* 上限的意义是"有界",不追求与 device-link 的字节口径逐字节一致。切点回退一位@@ -31,6 +55,8 @@ export function capToolResultTextForPersist(limit = TOOL_RESULT_PERSIST_CONTENT_LIMIT,): string {if (text.length <= limit) return text;+ const cardSummary = compactToolCardResult(text, limit);+ if (cardSummary !== null) return cardSummary;let cut = Math.max(0, limit - TOOL_RESULT_PERSIST_TRUNCATION_SUFFIX.length);const lastKept = text.charCodeAt(cut - 1);if (cut > 0 && lastKept >= 0xd800 && lastKept <= 0xdbff) cut -= 1;diff --git a/apps/mobile/app/mail-preview.tsx b/apps/mobile/app/mail-preview.tsxnew file mode 100644index 0000000000..e51e55727e--- /dev/null+++ b/apps/mobile/app/mail-preview.tsx@@ -0,0 +1,73 @@+import { useEffect, useState } from 'react';+import { Linking, ScrollView, StyleSheet, View } from 'react-native';+import { useLocalSearchParams, useRouter } from 'expo-router';+import { SafeAreaView } from 'react-native-safe-area-context';+import { useTranslation } from 'react-i18next';+import { mailMessageFields, parseMailMessage, type MailMessage } from '@cindy/maker-shared/mail-message';+import { mailPreviewImages, visibleMailAttachments } from '@cindy/maker-shared/ghost-card-form';+import { Text } from '@/components/AppText';+import { MainWindowActionButton } from '@/components/MobilePrimitives';+import { useAuth } from '@/auth/AuthContext';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { getRemoteResource } from '@/device-link/remoteResources';+import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome';+import { MobileMailHtmlPreview } from '@/plugins/MobileMailHtmlPreview';+import { PluginCardRecipients } from '@/plugins/PluginCardRecipients';+import { fontWeight, lineHeight, spacing, typeScale, useThemedStyles, type ThemeColors } from '@/theme';+import { goBackGuarded } from '@/utils/backGuard';++export default function MailPreviewScreen() {+ const params = useLocalSearchParams<{ deviceId: string; sessionId: string; url: string }>();+ const deviceId = typeof params.deviceId === 'string' ? params.deviceId : '';+ const sessionId = typeof params.sessionId === 'string' ? params.sessionId : '';+ const url = typeof params.url === 'string' ? params.url : '';+ const { t } = useTranslation(), styles = useThemedStyles(makeStyles), router = useRouter();+ const { invoke, connectionEpoch, status } = useDeviceLink();+ const { accountGeneration } = useAuth();+ const [attempt, setAttempt] = useState(0);+ const [result, setResult] = useState<{ binding: string; message?: MailMessage; error?: boolean }>();+ const binding = JSON.stringify([accountGeneration, connectionEpoch, deviceId, sessionId, url, attempt]);+ useEffect(() => {+ let active = true;+ if (!deviceId || !sessionId || status !== 'online') return;+ void getRemoteResource(invoke, { deviceId, deviceName: deviceId },+ { collectionId: 'mail-messages', kind: 'message', id: JSON.stringify([sessionId, url, true]) }, undefined, ['mail-message'], 'open').then(resource => {+ const message = parseMailMessage((resource.blocks?.[0]?.data as { message?: unknown })?.message);+ if (active) setResult({ binding, message: message || undefined, error: !message });+ }).catch(() => { if (active) setResult({ binding, error: true }); });+ return () => { active = false; };+ }, [binding, invoke, status]);+ const current = result?.binding === binding ? result : undefined, mail = current?.message;+ const fields = mail ? mailMessageFields(mail, key => t(`plugins.mailReader.${key}`)) : [];+ const values = Object.fromEntries(fields.map(f => [f.name, f.value]));+ return <SafeAreaView edges={simpleScreenSafeAreaEdges()} style={styles.root}>+ <SimpleStackHeader title={t('plugins.mailReader.title')} onBack={() => goBackGuarded(router)} />+ <ScrollView contentContainerStyle={styles.content}>+ <MainWindowActionButton action={{ label: t('plugins.mailReader.openMailbox'), onPress: () => { void Linking.openURL(url).catch(() => undefined); } }} />+ {mail ? <>+ {mail.markReadFailed && <Text style={styles.secondary}>{t('plugins.mailReader.markReadFailed')}</Text>}+ <Text selectable style={styles.title}>{mail.subject}</Text>+ <Text selectable style={styles.secondary}>{mail.from}{mail.date ? '\n' + mail.date : ''}</Text>+ <PluginCardRecipients fields={fields.filter(f => f.kind === 'recipients' && f.value.trim())} disabled readOnly onChange={() => {}} />+ {mail.bodyHtml ? <MobileMailHtmlPreview html={mail.bodyHtml} images={mailPreviewImages(values)} deviceId={deviceId} /> : <Text selectable style={styles.body}>{mail.bodyText}</Text>}+ {visibleMailAttachments(values).map(file => <View key={file.key} style={styles.attachment}>+ <Text selectable style={styles.secondary}>{file.filename}</Text>+ <Text style={styles.meta}>{file.mimeType || file.filename.split('.').pop()?.toUpperCase()}{file.bytes !== undefined ? ` · ${Math.ceil(file.bytes / 1024)} KB` : ''}</Text>+ {file.previewUrl && <MobileMailHtmlPreview html={'<img src="cid:attachment">'} images={[{ cid: 'attachment', url: file.previewUrl }]} deviceId={deviceId} />}+ </View>)}+ </> : <>+ <Text style={styles.secondary}>{t(current?.error || status !== 'online' ? 'plugins.mailReader.failed' : 'plugins.mailReader.loading')}</Text>+ {current?.error && <MainWindowActionButton action={{ label: t('plugins.mailReader.retry'), onPress: () => setAttempt(n => n + 1) }} />}+ </>}+ </ScrollView>+ </SafeAreaView>;+}+function makeStyles(colors: ThemeColors) { return StyleSheet.create({+ root: { flex: 1, backgroundColor: colors.surface },+ content: { padding: spacing.lg, gap: spacing.md },+ title: { fontSize: typeScale.title, lineHeight: lineHeight.title, fontWeight: fontWeight.semibold, color: colors.textPrimary },+ body: { fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge, fontWeight: fontWeight.regular, color: colors.textPrimary },+ secondary: { fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall, fontWeight: fontWeight.regular, color: colors.textSecondary },+ meta: { fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: colors.textTertiary },+ attachment: { gap: spacing.sm },+}); }diff --git a/apps/mobile/src/__tests__/mobileMailAttachment.test.ts b/apps/mobile/src/__tests__/mobileMailAttachment.test.tsnew file mode 100644index 0000000000..d57ad53803--- /dev/null+++ b/apps/mobile/src/__tests__/mobileMailAttachment.test.ts@@ -0,0 +1,41 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { pickMobileMailAttachment } from '../plugins/mobileMailAttachment';++// This native picker/upload handoff is separate from the card component: test+// cancellation, size admission and cleanup without loading a renderer or Expo.+const h = vi.hoisted(() => ({ pick: vi.fn(), info: vi.fn(), remove: vi.fn(), upload: vi.fn(), discard: vi.fn() }));+vi.mock('expo-document-picker', () => ({ getDocumentAsync: h.pick }));+vi.mock('expo-file-system/legacy', () => ({ getInfoAsync: h.info, deleteAsync: h.remove }));+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));+vi.mock('../session/mobileAttachmentUpload', () => ({ uploadMobileAttachmentFromFile: h.upload, discardMobileUploadedAttachment: h.discard }));+beforeEach(() => {+ vi.clearAllMocks();+ h.pick.mockResolvedValue({ canceled: false, assets: [{ uri: 'file:///cache/plan.pdf', name: 'plan.pdf', mimeType: 'application/pdf' }] });+ h.info.mockResolvedValue({ exists: true, isDirectory: false, size: 100 });+ h.remove.mockResolvedValue(undefined);+ h.upload.mockResolvedValue({ path: 'uploaded-reference' });+});+const options = (isActive = () => true) => ({ deviceId: 'host', getAccessToken: async () => 'token', signal: new AbortController().signal, isActive });+it('picker cancel performs no upload or file deletion', async () => {+ h.pick.mockResolvedValue({ canceled: true });+ expect(await pickMobileMailAttachment(options())).toBeNull();+ expect(h.upload).not.toHaveBeenCalled(); expect(h.remove).not.toHaveBeenCalled();+});+it('oversized files are rejected before token/upload and the selected cache copy is removed', async () => {+ h.info.mockResolvedValue({ exists: true, isDirectory: false, size: 17 * 1024 * 1024 });+ await expect(pickMobileMailAttachment(options())).rejects.toThrow('plugins.mailAttachTooLarge');+ expect(h.upload).not.toHaveBeenCalled(); expect(h.remove).toHaveBeenCalledOnce();+});+it('passes exact file bytes and host destination to the existing uploader', async () => {+ expect(await pickMobileMailAttachment(options())).toEqual({ url: 'uploaded-reference', name: 'plan.pdf' });+ expect(h.upload).toHaveBeenCalledWith({ name: 'plan.pdf', size: 100, mimeType: 'application/pdf' }, 'file:///cache/plan.pdf',+ expect.objectContaining({ deviceId: 'host', token: 'token' }));+ expect(h.remove).toHaveBeenCalledOnce(); expect(h.discard).not.toHaveBeenCalled();+});+it('leaving the card during upload discards the late result instead of attaching it', async () => {+ let active = true;+ h.upload.mockImplementation(async () => { active = false; return { path: 'uploaded-reference' }; });+ expect(await pickMobileMailAttachment(options(() => active))).toBeNull();+ expect(h.discard).toHaveBeenCalledWith({ path: 'uploaded-reference' }, expect.any(Object));+ expect(h.remove).toHaveBeenCalledOnce();+});diff --git a/apps/mobile/src/__tests__/pluginCardActions.test.tsx b/apps/mobile/src/__tests__/pluginCardActions.test.tsxindex 27dcf2ceff..24bfbf3e57 100644--- a/apps/mobile/src/__tests__/pluginCardActions.test.tsx+++ b/apps/mobile/src/__tests__/pluginCardActions.test.tsx@@ -1,10 +1,22 @@// @vitest-environment jsdom-import { act, createElement, type ReactNode } from "react";+import { act, createElement, forwardRef, useImperativeHandle, type ReactNode } from "react";import { createRoot } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";import { PluginCardActions } from "../plugins/PluginCardActions";+import { pendingGhostCardFormDelivery } from "@cindy/maker-shared/ghost-card-form";+import { MobileMailHtmlPreview } from '../plugins/MobileMailHtmlPreview';-const h = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock('react-native-webview', () => ({ WebView: forwardRef((props: any, ref) => {+ h.web = props;+ useImperativeHandle(ref, () => ({ injectJavaScript: h.inject }));+ return createElement('div', { 'data-testid': 'html-preview', 'data-html': props.source.html });+}) }));+vi.mock("@/auth/AuthContext", () => ({ useAuth: () => ({ getAccessToken: async () => 'test-token' }) }));+vi.mock("../plugins/mobileMailAttachment", () => ({ pickMobileMailAttachment: (...args: unknown[]) => h.pick(...args) }));+vi.mock("@/session/useBotGroupRemoteMedia", () => ({ useBotGroupRemoteMedia: () => h.resolve }));+vi.mock('@/components/FileTypeIcon', () => ({ FileTypeIcon: () => null }));++const h = vi.hoisted(() => ({ invoke: vi.fn(), pick: vi.fn(), resolve: vi.fn(), inject: vi.fn(), web: {} as any }));vi.mock("react-native", () => {const View = ({ children }: { children?: ReactNode }) =>createElement("div", {}, children);@@ -40,9 +52,31 @@ vi.mock("react-native", () => {vi.mock("@/components/AppText", () => ({Text: ({ children }: { children?: ReactNode }) =>createElement("span", {}, children),- TextInput: () => null,+ TextInput: ({+ value,+ onChangeText,+ editable,+ accessibilityLabel,+ }: {+ value: string;+ onChangeText(value: string): void;+ editable?: boolean;+ accessibilityLabel?: string;+ }) =>+ createElement("textarea", {+ value,+ disabled: editable === false,+ "aria-label": accessibilityLabel,+ onInput: (event: React.FormEvent<HTMLTextAreaElement>) =>+ onChangeText(event.currentTarget.value),+ onChange: () => {},+ }),+}));+vi.mock("@/theme", async () => ({+ ...(await import("../theme/tokens")),+ useThemedStyles: () => ({}),+ useTheme: () => ({ colors: { textPrimary: '#111' } }),}));-vi.mock("@/theme", () => ({ useThemedStyles: () => ({}) }));vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));@@ -62,6 +96,356 @@ afterEach(() => {vi.clearAllMocks();});describe("native plugin card deliberate actions", () => {+ // Mobile parity regression: typing must use the real form delivery, update+ // both MIME alternatives and retain the authored HTML/CID bytes (unit).+ it('autosaves direct HTML typing through the shared card without reloading the editing document', async () => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));+ h.invoke.mockImplementation(async (_d: string, _c: string, args: any[]) => {+ if (args[0].collectionId === 'plugin-results') return dispatch(args[0]);+ if (args[0].actionId === 'open-interaction') return { result: { pageId: 'page' } };+ return { result: { confirms: [] } };+ });+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const key = '12345678-1234-1234-1234-123456789abc';+ const html = '<style>p{color:red}</style><p>Hello</p><img src="cid:card">';+ const fields = [...['to','cc','bcc','subject','body'].map(name => ({ name, label: name, value: '', kind: 'hidden' })),+ { name: 'bodyHtml', label: 'HTML', kind: 'mail-html', value: html }];+ await act(async () => root.render(createElement(PluginCardActions, { deviceId: 'device', sessionId: 's', callId: 'text', data: {+ pluginId: 'mail', revision: '1', form: fields, changeAction: `mail:change:${key}`, items: [],+ mail: { key, accountId: 'a', draftId: 'd', from: '', fields, state: 'draft', status: 'Draft', sendLabel: 'Send', fromLabel: 'From', attachments: [] },+ } })));+ const source = h.web.source;+ expect(source.html).toContain("script-src 'none'");+ expect(container.textContent).not.toContain('plugins.mailEditText');+ expect(container.querySelector('textarea')).toBeNull();+ const message = (data: unknown) => h.web.onMessage({ nativeEvent: { data: JSON.stringify(data) } });+ await act(async () => {+ message({ type: 'mail-text', documentId: 99, id: '0', text: 'stale' });+ message({ type: 'mail-text', documentId: 0, id: '99', text: 'forged' });+ });+ expect(dispatch).not.toHaveBeenCalled();+ await act(async () => {+ message({ type: 'mail-text', documentId: 0, id: '0', text: '你好\nCherry' });+ });+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ input: expect.objectContaining({ formValues: expect.objectContaining({+ body: '你好\nCherry', bodyHtml: '<style>p{color:red}</style><p>你好<br>Cherry</p><img src="cid:card">',+ }) }) }));+ expect(h.web.source).toBe(source);+ expect(h.web.source.html).toContain("script-src 'none'");+ });+ // Inline images must not duplicate attachment tiles; ordinary files remain+ // removable. Exercise real form delivery while preserving the inline MIME part.+ it('opens an image and hides its attachment tile after insertion while retaining its MIME part and head styles', async () => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] })), open = vi.fn();+ h.invoke.mockImplementation(async (_d: string, _c: string, args: any[]) => {+ if (args[0].collectionId === 'plugin-results') return dispatch(args[0]);+ if (args[0].actionId === 'open-interaction') return { result: { pageId: 'page' } };+ return { result: { confirms: [] } };+ });+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`, key = '12345678-1234-1234-1234-123456789abc';+ const fields = [...['to','cc','bcc','subject','body'].map(name => ({ name, label: name, value: '' })),+ { name: 'bodyHtml', label: 'HTML', kind: 'hidden', value: '<style>.card{color:red}</style><p>Keep</p>' },+ { name: 'attachmentItems', label: 'Files', kind: 'mail-attachments', value: JSON.stringify([+ { key: 'image', filename: 'photo.png', mimeType: 'image/png', previewUrl: url, bytes: 1000 },+ { key: 'pdf', filename: 'notes.pdf', mimeType: 'application/pdf' },+ ]) }];+ await act(async () => root.render(createElement(PluginCardActions, { deviceId: 'device', sessionId: 's', callId: 'image', onOpenAttachment: open, data: {+ pluginId: 'mail', revision: '1', form: fields, changeAction: `mail:change:${key}`, items: [],+ mail: { key, accountId: 'a', draftId: 'd', from: '', fields, state: 'draft', status: 'Draft', sendLabel: 'Send', fromLabel: 'From', attachments: [] },+ } })));+ await act(async () => [...container.querySelectorAll('button')].find(b => b.textContent?.includes('photo.png'))!.click());+ expect(open).toHaveBeenCalledWith(url, 'photo.png');+ expect(dispatch).not.toHaveBeenCalled();+ await act(async () => [...container.querySelectorAll('button')].find(b => b.textContent === 'plugins.mailInsertImage')!.click());+ const inserted = dispatch.mock.calls.at(-1)![0] as any;+ expect(inserted.input.formValues.bodyHtml).toContain('src="cid:[email protected]"');+ expect(inserted.input.formValues.bodyHtml).not.toContain('cindy-media:');+ expect(JSON.parse(inserted.input.formValues.attachmentItems)).toHaveLength(2);+ expect(container.textContent).not.toContain('plugins.mailInsertImage');+ expect(container.textContent).not.toContain('photo.png');+ expect(container.textContent).toContain('notes.pdf');+ expect(inserted.input.formValues.bodyHtml).toContain('<style>.card{color:red}</style>');+ await act(async () => [...container.querySelectorAll('button')].find(b => b.textContent === '×')!.click());+ const removed = (dispatch.mock.calls.at(-1)![0] as any).input.formValues;+ expect(JSON.parse(removed.attachmentItems).map((file: any) => file.key)).toEqual(['image']);+ expect(removed.bodyHtml).toBe(inserted.input.formValues.bodyHtml);+ expect(container.textContent).not.toContain('notes.pdf');+ });+ it('resolves inline images for an inert phone preview and keeps the saved CID HTML intact', async () => {+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const html = '<p>Hello</p><img src="cid:logo">';+ h.resolve.mockResolvedValue({ url: 'data:image/png;base64,aGVsbG8=', previewable: true });+ await act(async () => root.render(createElement(MobileMailHtmlPreview, {+ html, deviceId: 'device', images: [{ cid: 'logo', url: `cindy-media://blobs/${'a'.repeat(64)}.png` }],+ })));+ const preview = container.querySelector('[data-testid="html-preview"]')!;+ expect(h.inject.mock.calls.some(([script]) => script.includes('data:image/png;base64,aGVsbG8='))).toBe(true);+ expect(preview.getAttribute('data-html')).toContain("script-src 'none'");+ expect(html).toContain('src="cid:logo"');+ expect(h.invoke).not.toHaveBeenCalled();+ });+ it('uploads from the phone then attaches to the same card; cancellation never dispatches', async () => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));+ h.invoke.mockImplementation(async (_device: string, _channel: string, args: any[]) => {+ if (args[0].collectionId === 'plugin-results') return dispatch(args[0]);+ if (args[0].actionId === 'open-interaction') return { result: { pageId: 'page' } };+ return { result: { confirms: [] } };+ });+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const key = '12345678-1234-1234-1234-123456789abc';+ const fields = [...['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name })),+ { name: 'attachmentItems', label: 'Files', value: '[]', kind: 'mail-attachments' }];+ await act(async () => root.render(createElement(PluginCardActions, { deviceId: 'device', sessionId: 's', callId: 'upload', data: {+ pluginId: 'mail', revision: '1', form: fields, mailUpload: true, changeAction: `mail:change:${key}`, items: [],+ mail: { accountId: 'a', draftId: 'd', key, from: '[email protected]', fields, state: 'draft', status: 'Draft',+ sendLabel: 'Send', fromLabel: 'From', attachments: [] },+ } })));+ const button = () => [...container.querySelectorAll('button')].find(b => b.textContent === 'plugins.mailAttach')!;+ h.pick.mockResolvedValueOnce(null);+ await act(async () => button().click());+ expect(dispatch).not.toHaveBeenCalled();+ const upload = { url: 'xdt-attach-oss://test-reference', name: 'plan.pdf' };+ h.pick.mockResolvedValueOnce(upload);+ await act(async () => button().click());+ expect(h.pick).toHaveBeenLastCalledWith(expect.objectContaining({ deviceId: 'device', isActive: expect.any(Function) }));+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ actionId: `mail:attach:${key}`,+ input: expect.objectContaining({ mailAttachment: upload, formValues: expect.objectContaining({ subject: 'subject' }) }) }));+ });+ it('deletes without saving fields and replaces the editor with a compact status and subject', async () => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));+ h.invoke.mockImplementation(async (_device: string, _channel: string, args: any[]) => {+ if (args[0].collectionId === 'plugin-results') return dispatch(args[0]);+ if (args[0].actionId === 'open-interaction') return { result: { pageId: 'page' } };+ return { result: { confirms: [] } };+ });+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const key = '12345678-1234-1234-1234-123456789abc';+ const fields = ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name }));+ const id = `mail:delete:${key}`;+ const render = (state: 'draft' | 'deleted') => root.render(createElement(PluginCardActions, {+ deviceId: 'device', sessionId: 's', callId: 'delete', data: {+ pluginId: 'mail', revision: state, form: fields, items: [{ id, label: 'Delete draft', disabled: false }],+ mail: { accountId: 'a', draftId: 'd', key, from: '[email protected]', fields, state, status: state,+ sendLabel: 'Send', fromLabel: 'From', deleteLabel: 'Delete draft', attachments: [] },+ },+ }));+ await act(async () => render('draft'));+ await act(async () => [...container.querySelectorAll('button')].find(b => b.textContent === 'Delete draft')!.click());+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ actionId: id }));+ expect(dispatch.mock.calls[0][0]).not.toHaveProperty('input.formValues');+ await act(async () => render('deleted'));+ expect(container.querySelectorAll('textarea,button')).toHaveLength(0);+ expect(container.textContent).toContain('deleted');+ expect(container.textContent).toContain('subject');+ expect(container.textContent).not.toContain('body');+ expect(container.textContent).not.toContain('[email protected]');+ expect(dispatch).toHaveBeenCalledTimes(1);+ });+ it.each(['cancel', 'now'])('allows %s during a locked send countdown without resubmitting fields', async (operation) => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));+ h.invoke.mockImplementation(async (_device: string, _channel: string, args: any[]) => {+ if (args[0].collectionId === 'plugin-results') return dispatch(args[0]);+ if (args[0].actionId === 'open-interaction') return { result: { pageId: 'page' } };+ return { result: { confirms: [] } };+ });+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const key = '12345678-1234-1234-1234-123456789abc';+ const fields = ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name }));+ const id = `mail:${operation}:${key}`;+ await act(async () => root.render(createElement(PluginCardActions, { deviceId: 'device', sessionId: 's', callId: 'waiting', data: {+ pluginId: 'mail', revision: '1', form: fields, items: [{ id, label: operation, disabled: false }],+ mail: { accountId: 'a', draftId: 'd', key, from: '[email protected]', fields, state: 'sending', status: 'Waiting',+ sendLabel: 'Send', fromLabel: 'From', attachments: [], pendingSend: { deadline: Date.now() + 10000, label: '{seconds}s', cancelLabel: 'cancel', sendNowLabel: 'now' } },+ } })));+ expect([...container.querySelectorAll('textarea')].every(el => el.disabled)).toBe(true);+ await act(async () => [...container.querySelectorAll('button')].find(b => b.textContent === operation)!.click());+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ actionId: id }));+ expect(dispatch.mock.calls[0][0]).not.toHaveProperty('input.formValues');+ });+ it("publishes edits without a click and keeps newer typing through an autosave card update", async () => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));+ h.invoke.mockImplementation(+ async (_device: string, _channel: string, args: any[]) => {+ if (args[0].collectionId === "plugin-results")+ return dispatch(args[0].input);+ if (args[0].actionId === "open-interaction")+ return { result: { pageId: "page" } };+ return { result: { confirms: [] } };+ },+ );+ const container = document.createElement("div"),+ root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const renderCard = (revision: string, value: string) =>+ root.render(+ createElement(PluginCardActions, {+ deviceId: "device",+ sessionId: "edit-task",+ callId: "card",+ data: {+ pluginId: "practice",+ revision,+ changeAction: "change:one",+ form: [+ {+ name: "to",+ label: "To",+ value: "Jane <[email protected]>, Rigo <[email protected]>",+ kind: "recipients",+ row: "recipients",+ },+ {+ name: "cc",+ label: "Cc",+ value: "Emma <[email protected]>",+ kind: "recipients",+ row: "recipients",+ },+ { name: "bcc", label: "Bcc", value: "Hidden <[email protected]>", kind: "recipients", collapsed: true },+ { name: "body", label: "Message", value, multiline: true },+ ],+ items: [+ { id: "send", label: "Send", submit: true, disabled: false },+ ],+ },+ }),+ );+ await act(async () => renderCard("one", "Initial"));+ expect(container.textContent).not.toContain("Bcc");+ await act(async () =>+ [...container.querySelectorAll("button")]+ .find((b) => b.textContent === "plugins.expandFields")!+ .click(),+ );+ expect(+ [...container.querySelectorAll("span")].filter(+ (el) => el.textContent === "To",+ ),+ ).toHaveLength(1);+ expect(container.querySelector('textarea[aria-label="Bcc"]')).toBeTruthy();+ const cc = container.querySelector<HTMLTextAreaElement>(+ 'textarea[aria-label="Cc"]',+ )!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )!.set!.call(cc, "Latest <[email protected]>");+ cc.dispatchEvent(new Event("input", { bubbles: true }));+ });+ const input = container.querySelector<HTMLTextAreaElement>(+ 'textarea[aria-label="Message"]',+ )!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )!.set!.call(input, "Latest edit");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ const barrier = pendingGhostCardFormDelivery(+ JSON.stringify(["device", "edit-task"]),+ );+ expect(barrier).toBeDefined();+ expect(await barrier).toBe(true);+ });+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ formChange: true,+ formValues: expect.objectContaining({+ body: "Latest edit",+ cc: "Latest <[email protected]>",+ bcc: "Hidden <[email protected]>",+ }),+ }),+ );+ expect(input.disabled).toBe(false);+ await act(async () => renderCard("two", "Older autosave receipt"));+ expect(input.value).toBe("Latest edit");+ await act(async () =>+ [...container.querySelectorAll("button")]+ .find((b) => b.textContent === "Send")!+ .click(),+ );+ expect(dispatch).toHaveBeenLastCalledWith(+ expect.objectContaining({+ formKey: "change:one",+ formValues: expect.objectContaining({+ body: "Latest edit",+ cc: "Latest <[email protected]>",+ bcc: "Hidden <[email protected]>",+ }),+ }),+ );+ });+ it("submits edited text and holds all fields until the card revision changes", async () => {+ const dispatch = vi.fn(async (_input: unknown) => ({ effects: [] }));+ h.invoke.mockImplementation(+ async (_device: string, _channel: string, args: any[]) => {+ if (args[0].collectionId === "plugin-results")+ return dispatch(args[0].input);+ if (args[0].actionId === "open-interaction")+ return { result: { pageId: "page" } };+ if (args[0].actionId === "poll") return { result: { confirms: [] } };+ return { effects: [] };+ },+ );+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ unmount = () => {+ act(() => root.unmount());+ container.remove();+ };+ const renderCard = (revision: string, value: string) =>+ root.render(+ createElement(PluginCardActions, {+ deviceId: "device",+ sessionId: "session",+ callId: "call",+ data: {+ pluginId: "practice",+ revision,+ form: [{ name: "body", label: "Message", value, multiline: true }],+ items: [+ { id: "send", label: "Send", disabled: false, submit: true },+ ],+ },+ }),+ );+ await act(async () => renderCard("one", "Initial"));+ expect(container.textContent).not.toContain("Bcc");+ const input = container.querySelector("textarea")!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(+ HTMLTextAreaElement.prototype,+ "value",+ )!.set!.call(input, "Edited\n\nMessage");+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => renderCard("one", "Initial"));+ expect(container.textContent).not.toContain("Bcc");+ expect(input.value).toBe("Edited\n\nMessage");+ const button = container.querySelector("button")!;+ await act(async () => button.click());+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({ formValues: { body: "Edited\n\nMessage" } }),+ );+ expect(button.disabled).toBe(true);+ expect(input.disabled).toBe(true);+ await act(async () => button.click());+ expect(dispatch).toHaveBeenCalledTimes(1);+ await act(async () => renderCard("two", "Saved reply"));+ expect(input.value).toBe("Saved reply");+ expect(input.disabled).toBe(false);+ expect(button.disabled).toBe(false);+ });it.each([false, true])("releases only a known successful delivery (unknown=%s)",async (unknown) => {@@ -108,3 +492,40 @@ describe("native plugin card deliberate actions", () => {},);});++it('hides empty recipient add controls in sent mail but keeps existing addresses readable', async () => {+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const fields = [+ { name: 'to', label: 'To', value: '[email protected]', kind: 'recipients' as const },+ { name: 'cc', label: 'Cc', value: '', kind: 'recipients' as const },+ { name: 'bcc', label: 'Bcc', value: '[email protected]', kind: 'recipients' as const, collapsed: true },+ { name: 'subject', label: 'Subject', value: 'Sent mail' },+ { name: 'body', label: 'Message', value: 'Sent body', multiline: true },+ ];+ await act(async () => root.render(createElement(PluginCardActions, { deviceId: 'device', sessionId: 's', callId: 'sent', data: {+ pluginId: 'mail', revision: '1', form: fields, items: [],+ mail: { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]', fields,+ state: 'sent', status: 'Sent', sendLabel: 'Send', fromLabel: 'From', attachments: [] },+ } })));+ expect(container.textContent).not.toContain('Cc');+ await act(async () => [...container.querySelectorAll('button')].find(b => b.textContent === 'plugins.expandFields')!.click());+ expect(container.querySelector('textarea[aria-label="Cc"]')).toBeNull();+ const bcc = container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Bcc"]')!;+ expect(bcc.value).toBe('[email protected]');+ expect(bcc.disabled).toBe(true);+ expect(h.invoke).not.toHaveBeenCalled();+});++it('hides superseded mail entirely instead of showing another draft-updated card', async () => {+ const container = document.createElement('div'), root = createRoot(container);+ unmount = () => act(() => root.unmount());+ const fields = ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: name === 'body' ? 'Historical body' : name }));+ await act(async () => root.render(createElement(PluginCardActions, { deviceId: 'device', sessionId: 's', callId: 'old', data: {+ pluginId: 'mail', revision: '1', form: fields, items: [{ id: 'send', label: 'Send', disabled: false }],+ mail: { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]', fields,+ state: 'draft', status: 'Saved', sendLabel: 'Send', fromLabel: 'From', attachments: [], supersededBy: 'new' },+ } })));+ expect(container.innerHTML).toBe('');+ expect(h.invoke).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/__tests__/usePluginResultCard.test.tsx b/apps/mobile/src/__tests__/usePluginResultCard.test.tsxindex 45d27abe9e..c68a9e5c89 100644--- a/apps/mobile/src/__tests__/usePluginResultCard.test.tsx+++ b/apps/mobile/src/__tests__/usePluginResultCard.test.tsx@@ -35,6 +35,24 @@ beforeEach(() => {});afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });describe('plugin card lifecycle on Mobile', () => {+ // A superseded card must disappear with its wrapper, including after an+ // invalidation of an already visible card; keep the stored snapshot intact.+ it('hides a mail card when the host publishes its replacement and restores that state from history', async () => {+ vi.useFakeTimers();+ const mail = { accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: '' })),+ attachments: [], state: 'draft', status: 'Saved', sendLabel: 'Send', fromLabel: 'From' };+ const card = (supersededBy?: string) => ({ display: { title: 'Mail' }, blocks: [+ { id: 'actions', primitive: 'plugin-card-actions', fallbackMarkdown: '', data: { mail: { ...mail, supersededBy } } },+ ] });+ h.get.mockResolvedValue(card()); await render(); expect(current.hidden).toBe(false);+ h.get.mockResolvedValue(card('new'));+ await act(async () => { h.push?.('mac', { collectionId: 'plugin-results' }); await vi.advanceTimersByTimeAsync(250); });+ expect(current.hidden).toBe(true);+ expect(current.blocks).toHaveLength(1);+ await render({ card: 'old-history' }); expect(current.hidden).toBe(true);+ h.get.mockResolvedValue(card()); await render({ card: 'new' }); expect(current.hidden).toBe(false);+ });it('loads history and refreshes on card change, foreground and reconnect', async () => {vi.useFakeTimers(); await render();expect(current.blocks?.[0].fallbackMarkdown).toBe('done');diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex f0cbf71714..f3fc1bcb73 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -1,3 +1,4 @@+import { pendingGhostCardFormDelivery } from '@cindy/maker-shared/ghost-card-form';import {tryMobilePeerFile,peerMediaUri,@@ -1192,6 +1193,8 @@ export function createMobileMakerTransport({aroundMessagesByClientId: (sessionId, clientId, opts) =>call("local-db:messages:around-client-id", [sessionId, clientId, opts]),send: async (sessionId, message, createOpts, sendOpts) => {+ const delivery = pendingGhostCardFormDelivery(JSON.stringify([deviceId, sessionId]));+ if (delivery && !await delivery) throw new Error((await import('@/i18n')).i18n.t('plugins.formSyncFailed'));const content = typeof message === 'string' ? message : message.content;const first = Array.isArray(content) ? content[0] : undefined;const head = typeof content === 'string' ? contentdiff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.tsindex 3d975660e2..c437a0449f 100644--- a/apps/mobile/src/device-link/remoteResources.ts+++ b/apps/mobile/src/device-link/remoteResources.ts@@ -45,6 +45,8 @@ const RICH_REMOTE_RESOURCE_PRIMITIVES: readonly string[] = [BOT_GROUP_CHAT_PRIMITIVE,'plugin-capabilities','plugin-card-actions',+ 'plugin-card-forms',+ 'mail-message','teammate-todos',];diff --git a/apps/mobile/src/i18n/locales/en/plugins.json b/apps/mobile/src/i18n/locales/en/plugins.jsonindex 5699533da4..9f517570c6 100644--- a/apps/mobile/src/i18n/locales/en/plugins.json+++ b/apps/mobile/src/i18n/locales/en/plugins.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"Could not sync read status. Check mailbox authorization and reopen this email.","title":"Mail","openMailbox":"Open in mailbox","loading":"Loading email…","failed":"Could not load this email. Check the connected mailbox account, retry, or open it in your mailbox.","retry":"Retry","to":"To","cc":"Cc","bcc":"Bcc","subject":"Subject"},"title": "Plugins","all": "All","unread": "Unread",@@ -33,6 +34,9 @@"chooseTask": "Existing task","taskHint": "Describe what you need in a task. Cindy will use the appropriate plugin. Existing tasks keep their model and permissions.","noMobilePage": "This plugin has no mobile page yet. Its tools can be used in a task.",+ "expandFields": "Expand",+ "collapseFields": "Collapse",+ "formSyncFailed": "Card edits have not synced. Check the connection and continue editing; the message has not been sent.","pageUnconfirmed": "The connection or page state is unconfirmed. Sent actions will not be replayed. Check the original task or saved content first.","reopen": "Reopen page","loadingPage": "Opening plugin…",@@ -124,5 +128,15 @@},"demo": {"hint": "Demo data · No real configuration is changed"- }+ },+ "mailPreview": "Email preview",+ "mailEnlarge": "Enlarge preview",+ "mailInsertImage": "Insert into message",+ "mailAttach": "Add attachment",+ "mailUpdated": "Draft updated (read-only)",+ "mailLegacy": "Draft history (read-only)",+ "mailAttaching": "Adding attachment…",+ "mailAttachFailed": "Could not add the attachment. Check your connection and try again.",+ "mailAttachTooLarge": "Each email attachment must be 16 MB or smaller.",+ "mailRemoveAttachment": "Remove {{name}}"}diff --git a/apps/mobile/src/i18n/locales/ja/plugins.json b/apps/mobile/src/i18n/locales/ja/plugins.jsonindex 9b2223d8dd..9337b70fe9 100644--- a/apps/mobile/src/i18n/locales/ja/plugins.json+++ b/apps/mobile/src/i18n/locales/ja/plugins.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"既読状態を同期できませんでした。メールボックスの認証を確認して開き直してください。","title":"メール","openMailbox":"メールボックスで開く","loading":"メールを読み込み中…","failed":"メールを読み込めませんでした。接続したアカウントを確認して再試行するか、メールボックスで開いてください。","retry":"再試行","to":"宛先","cc":"Cc","bcc":"Bcc","subject":"件名"},"title": "プラグイン","all": "すべて","unread": "未読",@@ -33,6 +34,9 @@"chooseTask": "既存のタスク","taskHint": "タスクで要望を伝えると、Cindy が適切なプラグインを使用します。既存のタスクのモデルと権限は保持されます。","noMobilePage": "モバイルページはまだありません。ツールはタスクで使用できます。",+ "expandFields": "展開",+ "collapseFields": "折りたたむ",+ "formSyncFailed": "カードの変更を同期できませんでした。接続を確認して編集を続けてください。メッセージは未送信です。","pageUnconfirmed": "接続またはページの状態を確認できません。送信した操作は自動再送されません。元のタスクや保存内容を確認してください。","reopen": "ページを開き直す","loadingPage": "プラグインを開いています…",@@ -124,5 +128,15 @@},"demo": {"hint": "デモデータ · 実際の設定は変更されません"- }+ },+ "mailPreview": "メールプレビュー",+ "mailEnlarge": "拡大表示",+ "mailInsertImage": "本文に挿入",+ "mailAttach": "添付ファイルを追加",+ "mailUpdated": "更新済みの下書き(読み取り専用)",+ "mailLegacy": "下書きの履歴(読み取り専用)",+ "mailAttaching": "添付ファイルを追加中…",+ "mailAttachFailed": "添付ファイルを追加できませんでした。接続を確認して再試行してください。",+ "mailAttachTooLarge": "添付ファイルは1件につき16 MB以下にしてください。",+ "mailRemoveAttachment": "{{name}} を削除"}diff --git a/apps/mobile/src/i18n/locales/ko/plugins.json b/apps/mobile/src/i18n/locales/ko/plugins.jsonindex 005c49b371..60c0265c69 100644--- a/apps/mobile/src/i18n/locales/ko/plugins.json+++ b/apps/mobile/src/i18n/locales/ko/plugins.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"읽음 상태를 동기화하지 못했습니다. 메일함 인증을 확인하고 다시 여세요.","title":"메일","openMailbox":"메일함에서 열기","loading":"메일 읽는 중…","failed":"메일을 읽지 못했습니다. 연결된 계정을 확인하고 다시 시도하거나 메일함에서 여세요.","retry":"다시 시도","to":"받는 사람","cc":"참조","bcc":"숨은 참조","subject":"제목"},"title": "플러그인","all": "전체","unread": "읽지 않음",@@ -33,6 +34,9 @@"chooseTask": "기존 작업","taskHint": "작업에서 요청을 설명하면 Cindy가 적절한 플러그인을 사용합니다. 기존 작업의 모델과 권한은 유지됩니다.","noMobilePage": "아직 모바일 페이지가 없습니다. 도구는 작업에서 사용할 수 있습니다.",+ "expandFields": "펼치기",+ "collapseFields": "접기",+ "formSyncFailed": "카드 변경 사항이 동기화되지 않았습니다. 연결을 확인한 후 편집을 계속하세요. 메시지는 전송되지 않았습니다.","pageUnconfirmed": "연결 또는 페이지 상태가 확인되지 않았습니다. 전송된 작업은 자동으로 다시 보내지 않습니다. 원래 작업이나 저장된 내용을 먼저 확인해 주세요.","reopen": "페이지 다시 열기","loadingPage": "플러그인 여는 중…",@@ -124,5 +128,15 @@},"demo": {"hint": "데모 데이터 · 실제 설정은 변경되지 않습니다"- }+ },+ "mailPreview": "메일 미리보기",+ "mailEnlarge": "확대 보기",+ "mailInsertImage": "본문에 삽입",+ "mailAttach": "첨부 파일 추가",+ "mailUpdated": "업데이트된 초안 (읽기 전용)",+ "mailLegacy": "초안 기록 (읽기 전용)",+ "mailAttaching": "첨부 파일 추가 중…",+ "mailAttachFailed": "첨부 파일을 추가하지 못했습니다. 연결을 확인한 후 다시 시도해 주세요.",+ "mailAttachTooLarge": "메일 첨부 파일 하나의 크기는 16 MB 이하여야 합니다.",+ "mailRemoveAttachment": "{{name}} 삭제"}diff --git a/apps/mobile/src/i18n/locales/zh-CN/plugins.json b/apps/mobile/src/i18n/locales/zh-CN/plugins.jsonindex 0e5e4c019f..e179d405d6 100644--- a/apps/mobile/src/i18n/locales/zh-CN/plugins.json+++ b/apps/mobile/src/i18n/locales/zh-CN/plugins.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"未能同步已读状态,请检查邮箱授权后重新打开。","title":"邮件","openMailbox":"在邮箱中打开","loading":"正在读取邮件…","failed":"未能读取这封邮件。请检查连接的邮箱账号后重试,或在邮箱中打开。","retry":"重试","to":"收件人","cc":"抄送","bcc":"密送","subject":"主题"},"title": "插件","all": "全部","unread": "未读",@@ -33,6 +34,9 @@"chooseTask": "已有任务","taskHint": "在任务中说明你的需求,Cindy 会调用适合的插件。已有任务继续使用原来的模型和权限。","noMobilePage": "此插件尚未提供手机页面,可在任务中使用其工具。",+ "expandFields": "展开",+ "collapseFields": "收起",+ "formSyncFailed": "卡片修改尚未同步,请检查连接后继续编辑;消息尚未发送。","pageUnconfirmed": "连接或页面状态尚未确认。已发出的操作不会自动重发,请先检查原任务或内容是否已保存。","reopen": "重新打开页面","loadingPage": "正在打开插件…",@@ -124,5 +128,15 @@},"demo": {"hint": "演示数据 · 不会修改真实配置"- }+ },+ "mailPreview": "邮件预览",+ "mailEnlarge": "放大查看",+ "mailInsertImage": "插入正文",+ "mailAttach": "添加附件",+ "mailUpdated": "草稿已更新(只读)",+ "mailLegacy": "历史草稿(只读)",+ "mailAttaching": "正在添加附件…",+ "mailAttachFailed": "附件未能添加,请检查连接后重试。",+ "mailAttachTooLarge": "单个邮件附件不能超过 16 MB。",+ "mailRemoveAttachment": "移除 {{name}}"}diff --git a/apps/mobile/src/i18n/locales/zh-TW/plugins.json b/apps/mobile/src/i18n/locales/zh-TW/plugins.jsonindex 78c6bc982a..f235bd43d0 100644--- a/apps/mobile/src/i18n/locales/zh-TW/plugins.json+++ b/apps/mobile/src/i18n/locales/zh-TW/plugins.json@@ -1,4 +1,5 @@{+ "mailReader": {"markReadFailed":"未能同步已讀狀態,請檢查信箱授權後重新開啟。","title":"郵件","openMailbox":"在信箱中開啟","loading":"正在讀取郵件…","failed":"未能讀取這封郵件。請檢查連接的信箱帳號後重試,或在信箱中開啟。","retry":"重試","to":"收件人","cc":"副本","bcc":"密件副本","subject":"主旨"},"title": "插件","all": "全部","unread": "未讀",@@ -33,6 +34,9 @@"chooseTask": "已有任務","taskHint": "在任務中說明需求,Cindy 會使用適合的插件。現有任務保留原有模型與權限。","noMobilePage": "此插件尚未提供手機頁面,可在任務中使用其工具。",+ "expandFields": "展開",+ "collapseFields": "收起",+ "formSyncFailed": "卡片修改尚未同步,請檢查連線後繼續編輯;訊息尚未傳送。","pageUnconfirmed": "連線或頁面狀態尚未確認。已送出的操作不會自動重送,請先檢查原任務或內容是否已儲存。","reopen": "重新開啟頁面","loadingPage": "正在開啟插件…",@@ -124,5 +128,15 @@},"demo": {"hint": "示範資料 · 不會修改真實設定"- }+ },+ "mailPreview": "郵件預覽",+ "mailEnlarge": "放大檢視",+ "mailInsertImage": "插入內文",+ "mailAttach": "新增附件",+ "mailUpdated": "草稿已更新(唯讀)",+ "mailLegacy": "歷史草稿(唯讀)",+ "mailAttaching": "正在新增附件…",+ "mailAttachFailed": "無法新增附件,請檢查連線後重試。",+ "mailAttachTooLarge": "單個郵件附件不能超過 16 MB。",+ "mailRemoveAttachment": "移除 {{name}}"}diff --git a/apps/mobile/src/plugins/MobileMailHtmlPreview.tsx b/apps/mobile/src/plugins/MobileMailHtmlPreview.tsxnew file mode 100644index 0000000000..b819eeaa3c--- /dev/null+++ b/apps/mobile/src/plugins/MobileMailHtmlPreview.tsx@@ -0,0 +1,112 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { Modal, Pressable, StyleSheet, View } from 'react-native';+import { useTranslation } from 'react-i18next';+import { Text } from '@/components/AppText';+import { applyMailInlineEdits, mailInlineDocument, mailInlineBindingScript, mailInlineRefreshScript, type MailInlineImage } from '@cindy/maker-shared/mail-text-edit';+import { WebView } from 'react-native-webview';+import { interceptHtmlNavigation } from '@/session/htmlNavigationPolicy';+import { useBotGroupRemoteMedia } from '@/session/useBotGroupRemoteMedia';+import { useThemedStyles, spacing, typeScale, lineHeight, fontWeight, type ThemeColors } from '@/theme';++/** CID substitution is preview-only. Never pass fetched URLs back into the draft. */+export function MobileMailHtmlPreview({ html, images = [], deviceId, disabled, onChange }: {+ html: string; images?: { cid: string; url: string }[]; deviceId: string;+ disabled?: boolean; onChange?: (html: string, text: string) => void;+}) {+ const { t } = useTranslation(), styles = useThemedStyles(makeStyles);+ const resolve = useBotGroupRemoteMedia(deviceId);+ const [open, setOpen] = useState(false);+ const [resolved, setResolved] = useState<{ binding: string; urls: Record<string, string> }>();+ const binding = JSON.stringify([deviceId, images]);+ useEffect(() => {+ let active = true;+ const urls: Record<string, string> = {};+ let previewBytes = 0;+ void (async () => {+ // Resolve sequentially through the shared media queue; keep all mailbox+ // HTML inert even when one image is unavailable.+ for (const image of images) {+ if (!active || previewBytes > 8 * 1024 * 1024) return;+ try {+ const media = await resolve({ kind: 'image', url: image.url, thumbnail: true, previewable: true });+ if (!active) return;+ if (media.url.startsWith('data:image/')) urls[image.cid] = media.url;+ else {+ const response = await fetch(media.url);+ const blob = await response.blob();+ if (blob.size > 2 * 1024 * 1024) continue;+ urls[image.cid] = await new Promise<string>((done, reject) => {+ const reader = new FileReader();+ reader.onload = () => done(String(reader.result)); reader.onerror = reject;+ reader.readAsDataURL(blob);+ });+ }+ if (active) setResolved({ binding, urls: { ...urls } });+ previewBytes += urls[image.cid]?.length || 0;+ } catch { /* Preserve the remaining preview when an image cannot be fetched. */ }+ }+ })();+ return () => { active = false; };+ }, [binding, resolve]);+ const urls = resolved?.binding === binding ? resolved.urls : {};+ const previewImages = Object.entries(urls).map(([cid, url]) => ({ cid, url }));+ return <View style={styles.root}>+ <View style={styles.controls}>+ <Pressable accessibilityRole="button" accessibilityLabel={t('plugins.mailEnlarge')} style={styles.enlarge} onPress={() => setOpen(true)}>+ <Text style={styles.note}>{t('plugins.mailEnlarge')}</Text>+ </Pressable>+ </View>+ <View style={styles.preview}><MobileMailFrame html={html} images={previewImages} disabled={disabled || open} onChange={onChange} /></View>+ <Modal visible={open} presentationStyle="pageSheet" onRequestClose={() => setOpen(false)}>+ <View style={styles.sheet}>+ <View style={styles.header}><Text style={styles.title}>{t('plugins.mailPreview')}</Text>+ <Pressable accessibilityRole="button" style={styles.enlarge} onPress={() => setOpen(false)}><Text style={styles.note}>{t('common.close')}</Text></Pressable></View>+ <MobileMailFrame html={html} images={previewImages} disabled={disabled} onChange={onChange} />+ </View>+ </Modal>+ </View>;+}+/** This is an email-only bridge; arbitrary HTML file previews keep their existing+ * reader with no message handler. Author scripts are blocked before parsing. */+function MobileMailFrame({ html, images, disabled, onChange }: {+ html: string; images: MailInlineImage[]; disabled?: boolean; onChange?: (html: string, text: string) => void;+}) {+ const web = useRef<WebView>(null);+ const model = useRef({ source: html, emitted: html, received: html, edits: {} as Record<string, string>, revision: 0 });+ if (model.current.received !== html) {+ if (html !== model.current.emitted) model.current = { source: html, emitted: html, received: html, edits: {}, revision: model.current.revision + 1 };+ else model.current.received = html;+ }+ const revision = model.current.revision;+ const source = useMemo(() => ({ baseUrl: 'about:blank', html: mailInlineDocument(model.current.source, images) }), [revision]);+ const settled = useRef(false), lastSource = useRef(source);+ if (lastSource.current !== source) { lastSource.current = source; settled.current = false; }+ const refresh = mailInlineRefreshScript(Boolean(onChange) && !disabled, images);+ useEffect(() => { web.current?.injectJavaScript(refresh); }, [refresh]);+ return <WebView key={revision} ref={web} source={source} javaScriptEnabled+ originWhitelist={['*']} onShouldStartLoadWithRequest={request => interceptHtmlNavigation(request, settled.current)}+ setSupportMultipleWindows={false} allowFileAccess={false} mediaCapturePermissionGrantType="deny"+ keyboardDisplayRequiresUserAction scrollEnabled+ onLoadEnd={() => { settled.current = true; web.current?.injectJavaScript(mailInlineBindingScript(revision) + refresh); }}+ onMessage={event => {+ if (disabled || !onChange || event.nativeEvent.data.length > 100000) return;+ try {+ const data = JSON.parse(event.nativeEvent.data);+ if (data.type !== 'mail-text' || data.documentId !== model.current.revision || typeof data.id !== 'string' || typeof data.text !== 'string') return;+ const edits = { ...model.current.edits, [data.id]: data.text };+ const next = applyMailInlineEdits(model.current.source, edits);+ if (!next) return;+ model.current.edits = edits; model.current.emitted = next.html;+ onChange(next.html, next.text);+ } catch { /* Invalid/stale messages never modify or send a draft. */ }+ }} style={{ flex: 1 }} />;+}+const makeStyles = (c: ThemeColors) => StyleSheet.create({+ root: { width: '100%' }, preview: { height: 280 },+ controls: { flexDirection: 'row', justifyContent: 'flex-end' },+ sheet: { flex: 1, padding: spacing.lg, backgroundColor: c.surface },+ header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },+ enlarge: { minHeight: 44, justifyContent: 'center', alignSelf: 'flex-end', paddingHorizontal: spacing.sm },+ title: { fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.semibold, color: c.textPrimary },+ note: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: c.textSecondary },+});diff --git a/apps/mobile/src/plugins/PluginCardActions.tsx b/apps/mobile/src/plugins/PluginCardActions.tsxindex e5fb79ed0c..64cffafcdb 100644--- a/apps/mobile/src/plugins/PluginCardActions.tsx+++ b/apps/mobile/src/plugins/PluginCardActions.tsx@@ -1,4 +1,20 @@import { useEffect, useRef, useState } from "react";+import {+ parseGhostCardForm,+ parseMailCard,+ mailCardStatus,+ mailSendRemainingFraction,+ type MailCardData,+ mergeGhostCardFormValues,+ trackGhostCardFormDelivery,+ GHOST_CARD_FORM_MAX_VALUE,+ visibleMailAttachments,+ removeMailAttachment,+ canInsertMailImage,+ insertMailImage,+ mailPreviewImages,+ type GhostCardFormField,+} from "@cindy/maker-shared/ghost-card-form";import {Alert,AppState,@@ -32,7 +48,13 @@ import {useThemedStyles,type ThemeColors,} from "@/theme";+import { useAuth } from "@/auth/AuthContext";+import { MobileMailHtmlPreview } from "./MobileMailHtmlPreview";+import { pickMobileMailAttachment } from "./mobileMailAttachment";+import { PluginCardRecipients } from "./PluginCardRecipients";import { invokePlugin } from "./pluginClient";+import { FileTypeIcon } from '@/components/FileTypeIcon';+import { formatByteSize } from '@cindy/maker-shared/file-preview';interface Action {id: string;@@ -40,10 +62,18 @@ interface Action {prompt?: string;url?: string;disabled: boolean;+ submit?: boolean;}-function parse(- value: unknown,-): { pluginId: string; revision: string; items: Action[] } | null {+function parse(value: unknown): {+ pluginId: string;+ revision: string;+ items: Action[];+ form: GhostCardFormField[] | null;+ changeAction?: string;+ mail?: MailCardData | null;+ legacyMail?: boolean;+ mailUpload?: boolean;+} | null {if (!value || typeof value !== "object") return null;const data = value as Record<string, unknown>;if (@@ -62,55 +92,97 @@ function parse(item.label.length <= 2048 &&typeof item.disabled === "boolean" &&(item.prompt === undefined || typeof item.prompt === "string") &&+ (item.submit === undefined || typeof item.submit === "boolean") &&(item.url === undefined || typeof item.url === "string"),);- return { pluginId: data.pluginId, revision: data.revision, items };+ return {+ mail: parseMailCard(data.mail),+ legacyMail: data.legacyMail === true,+ mailUpload: data.mailUpload === true,+ pluginId: data.pluginId,+ revision: data.revision,+ items,+ form: parseGhostCardForm(data.form),+ changeAction:+ typeof data.changeAction === "string" ? data.changeAction : undefined,+ };}export function PluginCardActions({data,deviceId,sessionId,callId,+ onOpenAttachment,}: {data: unknown;deviceId?: string;sessionId: string;callId: string;+ onOpenAttachment?: (url: string, name: string) => void;}) {const parsed = parse(data);- return parsed && deviceId ? (+ return parsed && !parsed.mail?.supersededBy && deviceId ? (<CardControlskey={`${deviceId}:${sessionId}:${callId}:${parsed.pluginId}`}{...parsed}deviceId={deviceId}sessionId={sessionId}callId={callId}+ onOpenAttachment={onOpenAttachment}/>) : null;}function CardControls({+ form,+ changeAction,+ mail,+ legacyMail,+ mailUpload,pluginId,revision,items,deviceId,sessionId,callId,+ onOpenAttachment,}: {+ form: GhostCardFormField[] | null;+ changeAction?: string;+ mail?: MailCardData | null;+ legacyMail?: boolean;+ mailUpload?: boolean;pluginId: string;revision: string;items: Action[];deviceId: string;sessionId: string;callId: string;+ onOpenAttachment?: (url: string, name: string) => void;}) {const { t } = useTranslation(),styles = useThemedStyles(makeStyles);+ const history = !!mail?.supersededBy || !!legacyMail;+ const { getAccessToken } = useAuth();+ const readonly = history || ['sent', 'sending', 'unconfirmed', 'deleting', 'deleted'].includes(mail?.state ?? '');+ const [countdownNow, setCountdownNow] = useState(Date.now);+ useEffect(() => {+ if (!mail?.pendingSend) return;+ setCountdownNow(Date.now());+ const timer = setInterval(() => setCountdownNow(Date.now()), 250);+ return () => clearInterval(timer);+ }, [mail?.pendingSend?.deadline]);+ const [historyExpanded, setHistoryExpanded] = useState(false);const { invoke, status } = useDeviceLink();const focused = useIsFocused(),focusedRef = useRef(focused);focusedRef.current = focused;const lifetime = useRef({ active: true, owner: getMobileAuthOwner() });const sending = useRef(false);+ const uploadAbort = useRef<AbortController | null>(null);+ const [uploading, setUploading] = useState(false);+ const [uploadError, setUploadError] = useState('');+ const mailEditable = useRef(!readonly); mailEditable.current = !readonly;+ useEffect(() => { if (readonly) uploadAbort.current?.abort(); }, [readonly]);const revisionRef = useRef(revision);revisionRef.current = revision;const page = useRef<string | undefined>(undefined);@@ -120,6 +192,28 @@ function CardControls({);const [prompt, setPrompt] = useState<Action>();const [draft, setDraft] = useState("");+ const formKey = changeAction ?? JSON.stringify(form);+ const changeQueue = useRef(Promise.resolve(true));+ const [expanded, setExpanded] = useState<Record<string, boolean>>({});+ const incoming = Object.fromEntries(+ (form ?? []).map((field) => [field.name, field.value]),+ );+ const [formState, setFormState] = useState(() => ({+ key: formKey,+ values: incoming,+ base: incoming,+ }));+ const formValues =+ formState.key === formKey+ ? mergeGhostCardFormValues(formState.values, formState.base, incoming)+ : incoming;+ const latestValues = useRef(formValues); latestValues.current = formValues;+ if (+ formState.key !== formKey ||+ JSON.stringify(formState.base) !== JSON.stringify(incoming)+ ) {+ setFormState({ key: formKey, values: formValues, base: incoming });+ }const [confirm, setConfirm] = useState<PluginPageConfirm>();const [busy, setBusy] = useState(false),[unknown, setUnknown] = useState(false),@@ -140,6 +234,7 @@ function CardControls({});return () => {token.active = false;+ uploadAbort.current?.abort();listener.remove();if (page.current && isMobileAuthOwnerCurrent(lifetime.current.owner))void invokePlugin(invoke, deviceId, pluginId, "close", {@@ -183,26 +278,40 @@ function CardControls({if (timer) clearTimeout(timer);};}, [lease, focused, foreground, status, invoke, deviceId, pluginId]);- const submit = async (action: Action, text?: string) => {+ const submit = async (+ action: Action,+ text?: string,+ edits?: Record<string, string>,+ mailAttachment?: { url: string; name: string },+ ) => {+ const passive = edits !== undefined;if (- sending.current ||- busy ||- unknown ||- action.disabled ||+ (!passive && sending.current) ||+ (!passive && busy) ||+ (!passive && unknown) ||+ action.disabled || (readonly && !(!history && mail && (+ (mail.state === 'sent' && action.id === `mail:continue:${mail.key}`) ||+ (mail.pendingSend && [`mail:cancel:${mail.key}`, `mail:now:${mail.key}`].includes(action.id))+ ))) ||+ (action.submit && !form) ||status !== "online" ||!focusedRef.current ||AppState.currentState !== "active")- return;+ return false;const token = lifetime.current,expectedRevision = revision;const valid = () =>token.active &&lifetime.current === token &&isMobileAuthOwnerCurrent(token.owner);- sending.current = true;- setBusy(true);+ if (!passive) {+ sending.current = true;+ setBusy(true);+ }try {+ if (!passive && action.submit && !(await changeQueue.current))+ throw new Error("CARD_FORM_SYNC_FAILED");if (!page.current) {const opened = await invokePlugin<{ pageId: string }>(invoke,@@ -219,7 +328,7 @@ function CardControls({"close",opened,).catch(() => {});- return;+ return false;}page.current = opened.pageId;setLease(opened.pageId);@@ -229,7 +338,10 @@ function CardControls({REMOTE_RESOURCE_INVOKE_CHANNEL,[{- client: { protocolVersion: 1, primitives: ["plugin-card-actions"] },+ client: {+ protocolVersion: 1,+ primitives: ["plugin-card-actions", "plugin-card-forms"],+ },collectionId: "plugin-results",resourceRef: {collectionId: "plugin-results",@@ -241,6 +353,10 @@ function CardControls({revision,pageId: page.current,...(text !== undefined ? { prompt: text } : {}),+ ...(action.submit ? { formValues: edits ?? latestValues.current } : {}),+ ...(mailAttachment ? { mailAttachment } : {}),+ ...(passive ? { formChange: true } : {}),+ ...(changeAction ? { formKey: changeAction } : {}),},},],@@ -248,9 +364,12 @@ function CardControls({preSend: () => {if (!valid() ||+ (mailAttachment && !mailEditable.current) ||!focusedRef.current ||AppState.currentState !== "active" ||- revisionRef.current !== expectedRevision+ (!passive &&+ !changeAction &&+ revisionRef.current !== expectedRevision))throw new Error("PLUGIN_PAGE_CLOSED");},@@ -259,12 +378,23 @@ function CardControls({if (valid() && revisionRef.current === expectedRevision) {setPrompt(undefined);setDraft("");- sending.current = false;- setBusy(false);+ if (!action.submit) {+ sending.current = false;+ setBusy(false);+ }}+ if (passive && valid()) setUnknown(false);+ return true;// A known delivery permits a new deliberate click, never an automatic replay.} catch {- if (valid() && revisionRef.current === expectedRevision) setUnknown(true);+ if (valid()) {+ setUnknown(true);+ if (!passive) {+ setBusy(false);+ sending.current = false;+ }+ }+ return false;}};const choose = (action: Action) => {@@ -309,20 +439,185 @@ function CardControls({if (current()) setAnswering(false);}};+ const changeField = (name: string, value: string, related?: Record<string, string>) => {+ if (readonly) return;+ const values = { ...formValues, ...related, [name]: value };+ setFormState({ key: formKey, values, base: incoming });+ if (changeAction) {+ changeQueue.current = changeQueue.current.then(() =>+ submit(+ {+ id: changeAction,+ label: "",+ disabled: false,+ submit: true,+ },+ undefined,+ values,+ ),+ );+ trackGhostCardFormDelivery(+ JSON.stringify([deviceId, sessionId]),+ callId,+ changeQueue.current,+ );+ }+ };+ const attach = async () => {+ if (!mail || readonly || busy || unknown || uploadAbort.current || status !== 'online') return;+ const controller = new AbortController(); uploadAbort.current = controller;+ setUploading(true); setUploadError('');+ const isActive = () => current() && !controller.signal.aborted && mailEditable.current;+ try {+ const file = await pickMobileMailAttachment({ deviceId, getAccessToken, signal: controller.signal, isActive });+ if (file && isActive()) await submit({ id: `mail:attach:${mail.key}`, label: '', disabled: false, submit: true }, undefined, undefined, file);+ } catch (error) {+ if (isActive()) setUploadError(error instanceof Error && error.message === t('plugins.mailAttachTooLarge') ? error.message : t('plugins.mailAttachFailed'));+ } finally {+ if (uploadAbort.current === controller) uploadAbort.current = null;+ if (current()) setUploading(false);+ }+ };+ if (mail?.state === 'deleted') {+ const subject = mail.fields.find(f => f.name === 'subject')?.value;+ return <View style={[styles.mailCard, styles.deletedMail]} accessibilityLiveRegion="polite">+ <Text style={styles.note}>{mailCardStatus(mail)}</Text>+ {subject ? <Text numberOfLines={1} style={[styles.note, styles.deletedSubject]}>· {subject}</Text> : null}+ </View>;+ }return (- <View style={styles.root}>- <View style={styles.actions}>- {items.map((action) => (- <Pressable- key={action.id}- accessibilityRole="button"- disabled={action.disabled || busy || unknown || status !== "online"}- style={styles.button}- onPress={() => choose(action)}- >- <Text style={styles.label}>{action.label}</Text>- </Pressable>- ))}+ <View style={[styles.root, mail && !history && styles.mailCard]}>+ {history ? <Pressable accessibilityRole="button" accessibilityState={{ expanded: historyExpanded }} onPress={() => setHistoryExpanded(!historyExpanded)}>+ <Text style={styles.note}>{historyExpanded ? '▾ ' : '▸ '}{t(legacyMail ? 'plugins.mailLegacy' : 'plugins.mailUpdated')}{' · '}{form?.find(f => f.name === 'subject')?.value}</Text>+ </Pressable> : null}+ {history && historyExpanded ? <View style={styles.root}>{form?.filter(f => f.value && f.kind !== 'hidden' && (f.kind !== 'mail-attachments' || visibleMailAttachments(formValues, f.name).length)).map(field =>+ <View key={field.name}><Text style={styles.note}>{field.label}</Text>+ {field.kind === 'mail-html' ? <MobileMailHtmlPreview html={field.value} images={mailPreviewImages(formValues, mail?.images)} deviceId={deviceId} /> :+ <Text style={styles.body}>{field.kind === 'mail-attachments' ? visibleMailAttachments(formValues, field.name).map(file => file.filename).join(' · ') : field.value}</Text>}+ </View>+ )}</View> : null}+ {!history ? <View style={styles.form}>+ {form?.map((field) => {+ if (field.kind === 'hidden') return null;+ if (field.kind === 'mail-html') return <MobileMailHtmlPreview key={field.name} html={formValues[field.name]} images={mailPreviewImages(formValues, mail?.images)} deviceId={deviceId}+ disabled={busy || uploading || unknown || status !== 'online'}+ onChange={readonly ? undefined : (html, text) => {+ const plain = field.name === 'quoteHtml' ? 'quote' : 'body';+ changeField(field.name, html, plain in formValues ? { [plain]: text } : undefined);+ }} />;+ if (field.kind === 'mail-attachments') {+ const files = visibleMailAttachments(formValues, field.name);+ if (!files.length && (readonly || !mailUpload) && !uploadError) return null;+ return <View key={field.name} style={styles.fullField}>+ {mailUpload && !readonly && <Pressable accessibilityRole="button" disabled={busy || uploading || unknown || status !== 'online'} style={styles.attachButton} onPress={() => void attach()}><Text style={styles.note}>{uploading ? t('plugins.mailAttaching') : t('plugins.mailAttach')}</Text></Pressable>}+ {files.map(file => <View key={file.key} style={styles.attachment}>+ <Pressable accessibilityRole="button" accessibilityLabel={file.filename} disabled={!file.previewUrl || !onOpenAttachment} style={styles.attachmentOpen} onPress={() => file.previewUrl && onOpenAttachment?.(file.previewUrl, file.filename)}>+ <FileTypeIcon name={file.filename} mimeType={file.mimeType} />+ <View style={styles.attachmentText}><Text numberOfLines={1} style={styles.note}>{file.filename}</Text><Text style={styles.note}>{file.filename.split('.').pop()?.toUpperCase()}{file.bytes !== undefined ? ' · ' + formatByteSize(file.bytes) : ''}</Text></View>+ </Pressable>+ {!readonly && canInsertMailImage(formValues, file) && <Pressable accessibilityRole="button" disabled={busy || uploading || unknown || status !== 'online'} style={styles.attachButton} onPress={() => {+ const next = insertMailImage(formValues, field.name, file.key);+ changeField(field.name, next[field.name], next);+ }}><Text style={styles.note}>{t('plugins.mailInsertImage')}</Text></Pressable>}+ {!readonly && <Pressable accessibilityRole="button" disabled={busy || uploading} style={styles.attachButton} accessibilityLabel={t('plugins.mailRemoveAttachment', { name: file.filename })} onPress={() => {+ const next = removeMailAttachment(formValues, field.name, file.key);+ changeField(field.name, next[field.name], next);+ }}><Text style={styles.note}>×</Text></Pressable>}+ </View>)}+ {uploadError ? <Text style={styles.note}>{uploadError}</Text> : null}+ </View>;+ }+ if (field.kind === "recipients") {+ const group = form.filter(+ (f) => f.kind === "recipients" && (!['sent', 'deleted'].includes(mail?.state ?? '') || formValues[f.name]?.trim()),+ );+ if (group[0] !== field) return null;+ return (+ <PluginCardRecipients+ key={field.name}+ fields={group.map((f) => ({ ...f, value: formValues[f.name] }))}+ disabled={busy || uploading || readonly}+ readOnly={['sent', 'deleted'].includes(mail?.state ?? '')}+ onChange={changeField}+ />+ );+ }+ return (+ <View+ key={field.name}+ style={[+ styles.root,+ styles.fullField,+ !field.multiline && !field.collapsed && styles.inlineField,+ ]}+ >+ {field.collapsed ? (+ <Pressable+ onPress={() =>+ setExpanded({+ ...expanded,+ [field.name]: !expanded[field.name],+ })+ }+ >+ <Text style={styles.note}>+ {expanded[field.name] ? "▾ " : "▸ "}+ {field.label}+ </Text>+ </Pressable>+ ) : !field.multiline ? (+ <Text style={styles.note}>{field.label}</Text>+ ) : null}+ {(!field.collapsed || expanded[field.name]) && (+ <TextInput+ accessibilityLabel={field.label}+ value={formValues[field.name]}+ multiline={field.multiline}+ editable={!busy && !uploading && !readonly}+ maxLength={GHOST_CARD_FORM_MAX_VALUE}+ onChangeText={(value) => changeField(field.name, value)}+ style={[+ styles.formInput,+ field.multiline && styles.multiline,+ ]}+ />+ )}+ </View>+ );+ })}+ </View> : null}+ <View style={mail && !history ? styles.mailFooter : undefined}>+ {mail && !history ? (+ <View style={styles.mailInfo}>+ <Text style={styles.note}>{mail.fromLabel}: {mail.from}</Text>+ {mail.attachments.length && !form?.some(f => f.kind === 'mail-attachments') ? (+ <Text style={styles.note}>{mail.attachments.join(' · ')}</Text>+ ) : null}+ <Text style={styles.note}>{mailCardStatus(mail, countdownNow)}</Text>+ </View>+ ) : null}+ <View style={styles.actions}>+ {(history ? [] : items).map((action) => {+ const sendNow = !!mail?.pendingSend && action.id === `mail:now:${mail.key}`;+ return (+ <Pressable+ key={action.id}+ accessibilityRole="button"+ accessibilityLabel={sendNow && mail ? `${action.label}, ${mailCardStatus(mail, countdownNow)}` : action.label}+ disabled={action.disabled || busy || uploading || unknown || status !== "online" || (readonly && !mail?.pendingSend && !action.id.startsWith('mail:continue:'))}+ style={[styles.button, mail && action.id === `mail:send:${mail.key}` && styles.sendButton, sendNow && styles.sendNowButton]}+ onPress={() => choose(action)}+ >+ {sendNow && mail ? (+ <View pointerEvents="none" accessible={false} style={StyleSheet.absoluteFill}>+ <View style={[styles.countdownFill, { width: `${(1 - mailSendRemainingFraction(mail, countdownNow)) * 100}%` }]} />+ </View>+ ) : null}+ <Text style={[styles.label, mail && action.id === `mail:send:${mail.key}` && styles.sendLabel]}>{action.label}</Text>+ </Pressable>+ );+ })}+ </View></View>{unknown ? (<Text style={styles.note}>{t("plugins.pageUnconfirmed")}</Text>@@ -391,7 +686,51 @@ function CardControls({const makeStyles = (c: ThemeColors) =>StyleSheet.create({root: { gap: spacing.sm },- actions: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },+ mailCard: { borderWidth: StyleSheet.hairlineWidth, borderColor: c.border, borderRadius: radius.container, padding: spacing.md, backgroundColor: c.surfaceElevated },+ deletedMail: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingVertical: spacing.sm },+ deletedSubject: { flex: 1, minWidth: 0 },+ attachButton: { minHeight: 44, justifyContent: 'center', paddingHorizontal: spacing.sm },+ attachment: { flexDirection: 'row', alignItems: 'center', borderWidth: StyleSheet.hairlineWidth, borderColor: c.border, borderRadius: radius.container, marginBottom: spacing.xs },+ attachmentOpen: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, padding: spacing.sm, minHeight: 44, flex: 1, minWidth: 0 },+ attachmentText: { flex: 1, minWidth: 0 },+ mailFooter: {+ gap: spacing.sm,+ borderTopWidth: StyleSheet.hairlineWidth,+ borderColor: c.border,+ paddingVertical: spacing.sm,+ },+ mailInfo: { minWidth: 0, gap: 0 },+ form: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },+ inlineField: {+ flexDirection: "row",+ alignItems: "center",+ borderBottomWidth: StyleSheet.hairlineWidth,+ borderColor: c.border,+ },+ fullField: { width: "100%" },+ formInput: {+ color: c.textPrimary,+ fontSize: typeScale.body,+ lineHeight: lineHeight.body,+ fontWeight: fontWeight.regular,+ padding: spacing.xs,+ flex: 1,+ minWidth: 0,+ minHeight: 36,+ borderRadius: radius.pill,+ },+ multiline: {+ minHeight: 140,+ width: "100%",+ flex: 0,+ borderRadius: radius.control,+ textAlignVertical: "top",+ },+ actions: { flexDirection: "row", flexWrap: "wrap", justifyContent: 'flex-end', gap: spacing.sm },+ sendButton: { backgroundColor: c.cta },+ sendLabel: { color: c.ctaText },+ countdownFill: { height: "100%", backgroundColor: c.textPrimary, opacity: 0.14 },+ sendNowButton: { backgroundColor: c.surface, overflow: "hidden", borderWidth: StyleSheet.hairlineWidth, borderColor: c.border },button: {minHeight: 44,padding: spacing.md,diff --git a/apps/mobile/src/plugins/PluginCardRecipients.tsx b/apps/mobile/src/plugins/PluginCardRecipients.tsxnew file mode 100644index 0000000000..ffc54075fc--- /dev/null+++ b/apps/mobile/src/plugins/PluginCardRecipients.tsx@@ -0,0 +1,336 @@+import { useState } from "react";+import { Pressable, StyleSheet, View } from "react-native";+import { useTranslation } from "react-i18next";+import { Text, TextInput } from "@/components/AppText";+import {+ fontWeight,+ lineHeight,+ radius,+ spacing,+ typeScale,+ useThemedStyles,+ type ThemeColors,+} from "@/theme";+import {+ fitGhostCardRecipients,+ ghostCardRecipients,+ GHOST_CARD_FORM_MAX_VALUE,+ type GhostCardFormField,+} from "@cindy/maker-shared/ghost-card-form";++type Props = {+ fields: GhostCardFormField[];+ disabled: boolean;+ readOnly?: boolean;+ onChange: (name: string, value: string) => void;+};++/** Mobile uses native text measurement and the same packing rule as Desktop. */+export function PluginCardRecipients({+ fields,+ disabled,+ readOnly = false,+ onChange,+}: Props) {+ const styles = useThemedStyles(makeStyles),+ { t } = useTranslation();+ const [expanded, setExpanded] = useState(false);+ const [inputHeights, setInputHeights] = useState<Record<string, number>>({});+ return expanded ? (+ <View style={styles.root}>+ {fields.map((field, i) => (+ <View key={field.name} style={styles.editRow}>+ <Text style={[styles.label, styles.editLabel]}>{field.label}</Text>+ <TextInput+ accessibilityLabel={field.label}+ value={field.value}+ multiline+ scrollEnabled={false}+ onContentSizeChange={(event) => {+ const height = Math.max(+ 44,+ Math.ceil(event.nativeEvent.contentSize.height),+ );+ setInputHeights((old) =>+ old[field.name] === height+ ? old+ : { ...old, [field.name]: height },+ );+ }}+ editable={!disabled}+ autoCapitalize="none"+ autoCorrect={false}+ maxLength={GHOST_CARD_FORM_MAX_VALUE}+ onChangeText={(value) => onChange(field.name, value)}+ style={[styles.input, { height: inputHeights[field.name] ?? 44 }]}+ />+ {i === 0 && (+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ expanded: true }}+ style={styles.control}+ onPress={() => setExpanded(false)}+ >+ <Text style={styles.note}>{t("plugins.collapseFields")}</Text>+ </Pressable>+ )}+ </View>+ ))}+ </View>+ ) : (+ <RecipientSummary+ key={JSON.stringify(fields)}+ fields={fields.filter(+ (field) => field.name !== "bcc" && !field.collapsed,+ )}+ readOnly={readOnly}+ hasHiddenDetails={fields.some(+ (f) => (f.name === "bcc" || f.collapsed) && f.value.trim(),+ )}+ onExpand={() => setExpanded(true)}+ />+ );+}++function RecipientSummary({+ fields,+ onExpand,+ readOnly,+ hasHiddenDetails,+}: Omit<Props, "onChange" | "disabled"> & {+ onExpand: () => void;+ hasHiddenDetails: boolean;+}) {+ const styles = useThemedStyles(makeStyles),+ { t } = useTranslation();+ const [width, setWidth] = useState(0),+ [metrics, setMetrics] = useState<Record<string, number>>({});+ const entries = fields.map((field) => ghostCardRecipients(field.value));+ const more = (count: number) => (count ? `+${count}` : "+");+ const expand = t("plugins.expandFields");+ const groups = entries.map((items, i) => ({+ label: metrics[`label-${i}`],+ chips: items.map((_, j) => metrics[`chip-${i}-${j}`]),+ more: Array.from(+ { length: items.length + 1 },+ (_, j) => metrics[`more-${i}-${j}`],+ ),+ }));+ const ready =+ width > 0 &&+ metrics.toggle !== undefined &&+ groups.every((g) =>+ [g.label, ...g.chips, ...g.more].every((v) => v !== undefined),+ );+ const available = width - fields.length * spacing.sm;+ const fullCounts = ready+ ? fitGhostCardRecipients(available, groups, spacing.xs)+ : fields.map(() => 0);+ const canExpand =+ !readOnly ||+ hasHiddenDetails ||+ (ready &&+ entries.some(+ (items, i) =>+ fullCounts[i] < items.length ||+ items.some(+ (entry, j) =>+ entry.label !== entry.address || metrics[`chip-${i}-${j}`] >= 160,+ ),+ ));+ const counts =+ ready && canExpand+ ? fitGhostCardRecipients(available - metrics.toggle, groups, spacing.xs)+ : fullCounts;+ const record = (key: string, value: number) =>+ setMetrics((old) => (old[key] === value ? old : { ...old, [key]: value }));+ return (+ <View+ style={styles.root}+ onLayout={(event) => setWidth(event.nativeEvent.layout.width)}+ >+ <View style={styles.summary}>+ {fields.map((field, i) => (+ <View key={field.name} style={styles.group}>+ <Text style={styles.label}>{field.label}</Text>+ {entries[i].slice(0, counts[i]).map((entry, j) =>+ canExpand ? (+ <Pressable+ key={j}+ accessibilityRole="button"+ accessibilityLabel={`${field.label}: ${entry.address}`}+ style={styles.control}+ onPress={onExpand}+ >+ <Text numberOfLines={1} style={styles.chip}>+ {entry.label}+ </Text>+ </Pressable>+ ) : (+ <Text key={j} numberOfLines={1} style={styles.chip}>+ {entry.label}+ </Text>+ ),+ )}+ {(counts[i] < entries[i].length || !entries[i].length) && (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`${field.label}: ${expand} (${entries[i].length})`}+ style={styles.control}+ onPress={onExpand}+ >+ <Text style={styles.more}>+ {more(entries[i].length - counts[i])}+ </Text>+ </Pressable>+ )}+ </View>+ ))}+ {canExpand && (+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ expanded: false }}+ style={[styles.control, styles.toggle]}+ onPress={onExpand}+ >+ <Text style={styles.note}>{expand}</Text>+ </Pressable>+ )}+ </View>+ <View+ pointerEvents="none"+ accessibilityElementsHidden+ importantForAccessibility="no-hide-descendants"+ style={styles.measure}+ >+ <Text+ style={styles.note}+ onLayout={(e) => record("toggle", e.nativeEvent.layout.width)}+ >+ {expand}+ </Text>+ {fields.map((field, i) => (+ <View key={field.name} style={styles.measureGroup}>+ <Text+ style={styles.label}+ onLayout={(e) => record(`label-${i}`, e.nativeEvent.layout.width)}+ >+ {field.label}+ </Text>+ {entries[i].map((entry, j) => (+ <Text+ key={j}+ numberOfLines={1}+ style={styles.chip}+ onLayout={(e) =>+ record(`chip-${i}-${j}`, e.nativeEvent.layout.width)+ }+ >+ {entry.label}+ </Text>+ ))}+ {Array.from({ length: entries[i].length + 1 }, (_, j) => (+ <Text+ key={`more-${j}`}+ style={styles.more}+ onLayout={(e) =>+ record(`more-${i}-${j}`, e.nativeEvent.layout.width)+ }+ >+ {more(j)}+ </Text>+ ))}+ </View>+ ))}+ </View>+ </View>+ );+}++const makeStyles = (c: ThemeColors) =>+ StyleSheet.create({+ root: {+ width: "100%",+ borderBottomWidth: StyleSheet.hairlineWidth,+ borderColor: c.border,+ overflow: "hidden",+ },+ summary: {+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.sm,+ minHeight: 44,+ },+ group: {+ flexDirection: "row",+ alignItems: "center",+ gap: spacing.xs,+ flexShrink: 0,+ },+ control: {+ minHeight: 44,+ justifyContent: "center",+ borderRadius: radius.pill,+ flexShrink: 0,+ },+ toggle: { marginLeft: "auto" },+ label: {+ fontSize: typeScale.caption,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textTertiary,+ },+ note: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textSecondary,+ },+ chip: {+ fontSize: typeScale.footnote,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textPrimary,+ paddingHorizontal: spacing.sm,+ paddingVertical: spacing.xs,+ borderRadius: radius.pill,+ backgroundColor: c.surfaceChip,+ maxWidth: 160,+ },+ more: {+ fontSize: typeScale.caption,+ lineHeight: lineHeight.caption,+ fontWeight: fontWeight.regular,+ color: c.textTertiary,+ paddingHorizontal: spacing.xs,+ },+ editRow: {+ flexDirection: "row",+ alignItems: "flex-start",+ gap: spacing.sm,+ paddingVertical: 0,+ },+ editLabel: { paddingTop: spacing.sm },+ input: {+ flex: 1,+ minWidth: 0,+ minHeight: 44,+ padding: spacing.xs,+ borderRadius: radius.control,+ textAlignVertical: "top",+ fontSize: typeScale.bodySmall,+ lineHeight: lineHeight.bodySmall,+ fontWeight: fontWeight.regular,+ color: c.textPrimary,+ },+ // Keep intrinsic widths unconstrained by the summary; never expose duplicate labels to accessibility.+ measure: {+ position: "absolute",+ top: 0,+ left: 0,+ opacity: 0,+ flexDirection: "row",+ width: 100000,+ },+ measureGroup: { flexDirection: "row", flexShrink: 0, alignItems: "center" },+ });diff --git a/apps/mobile/src/plugins/mobileMailAttachment.ts b/apps/mobile/src/plugins/mobileMailAttachment.tsnew file mode 100644index 0000000000..1ba874f1e1--- /dev/null+++ b/apps/mobile/src/plugins/mobileMailAttachment.ts@@ -0,0 +1,29 @@+import { i18n } from '@/i18n';+import { uploadMobileAttachmentFromFile, discardMobileUploadedAttachment } from '@/session/mobileAttachmentUpload';++/** Uses the existing phone picker/upload path; provider credentials stay on the Host. */+export async function pickMobileMailAttachment(options: {+ deviceId: string; getAccessToken(): Promise<string | null>; signal: AbortSignal; isActive(): boolean;+}) {+ const picker = await import('expo-document-picker');+ const selected = await picker.getDocumentAsync({ multiple: false, copyToCacheDirectory: true });+ if (selected.canceled || !selected.assets[0]) return null;+ const file = selected.assets[0];+ const fs = await import('expo-file-system/legacy');+ try {+ if (!options.isActive()) return null;+ const info = await fs.getInfoAsync(file.uri);+ const size = info.exists && !info.isDirectory ? info.size : undefined;+ if (size === undefined) throw new Error(i18n.t('plugins.mailAttachFailed'));+ if (size > 16 * 1024 * 1024) throw new Error(i18n.t('plugins.mailAttachTooLarge'));+ const token = await options.getAccessToken();+ if (!options.isActive()) return null;+ const uploaded = await uploadMobileAttachmentFromFile({ name: file.name, size, mimeType: file.mimeType }, file.uri,+ { token, deviceId: options.deviceId, signal: options.signal, isActive: options.isActive });+ if (!options.isActive()) {+ discardMobileUploadedAttachment(uploaded, { getToken: () => Promise.resolve(token) });+ return null;+ }+ return { url: uploaded.url || uploaded.path, name: file.name };+ } finally { await fs.deleteAsync(file.uri, { idempotent: true }).catch(() => undefined); }+}diff --git a/apps/mobile/src/session/HtmlFileReader.tsx b/apps/mobile/src/session/HtmlFileReader.tsxindex 6b5b728f1f..a0d9f79f03 100644--- a/apps/mobile/src/session/HtmlFileReader.tsx+++ b/apps/mobile/src/session/HtmlFileReader.tsx@@ -127,7 +127,7 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInset/>{paintedPreview !== preview && loading ? <View style={StyleSheet.absoluteFill} pointerEvents="none">{loading}</View> : null}</View></View>;}-export function HtmlFileReader({ html, testID }: { html: string; testID?: string }) {+export function HtmlFileReader({ html, testID, javaScriptEnabled = true }: { html: string; testID?: string; javaScriptEnabled?: boolean }) {// CSP 注入放在**渲染载体这一层**,而不是取件那一层:任何进到这个 WebView 的// HTML 都必须带策略,不管它有没有同目录资源(见 htmlPreviewCsp 的说明)。const guardedHtml = useMemo(() => withHtmlPreviewCsp(html), [html]);@@ -149,6 +149,7 @@ export function HtmlFileReader({ html, testID }: { html: string; testID?: stringreturn (<View style={styles.fill} testID={testID}><WebView+ javaScriptEnabled={javaScriptEnabled}onShouldStartLoadWithRequest={interceptNavigation}// 首份文档加载完就上闩:此后 about:blank 这类替换文档的导航不再放行。onLoadEnd={() => { documentSettledRef.current = true; }}diff --git a/apps/mobile/src/session/MailLinkSpan.tsx b/apps/mobile/src/session/MailLinkSpan.tsxnew file mode 100644index 0000000000..527f0aa2d2--- /dev/null+++ b/apps/mobile/src/session/MailLinkSpan.tsx@@ -0,0 +1,42 @@+import { useContext, useEffect, useRef } from 'react';+import { Linking, type StyleProp, type TextStyle } from 'react-native';+import { Text } from '@/components/AppText';+import { useRouter } from 'expo-router';+import { useDeviceLink } from '@/device-link/DeviceLinkContext';+import { getRemoteResource } from '@/device-link/remoteResources';+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';+import { ChatFilePathContext } from './chatFilePathContext';++/** All mail providers use Host-declared link recognition; unknown/old hosts keep OS links. */+export function MailLinkSpan({ url, children, style, SpanText }: {+ url: string; children: string; style: StyleProp<TextStyle>; SpanText: typeof Text;+}) {+ const context = useContext(ChatFilePathContext);+ const { invoke } = useDeviceLink();+ const router = useRouter();+ const busy = useRef(false);+ const current = useRef(context); current.current = context;+ useEffect(() => () => { current.current = null; }, []);+ const open = async () => {+ if (busy.current) return;+ busy.current = true;+ const owner = getMobileAuthOwner(), source = context;+ try {+ if (source && url.startsWith('https://')) {+ let supported = false;+ try {+ const resource = await getRemoteResource(invoke, { deviceId: source.deviceId, deviceName: source.deviceId },+ { collectionId: 'mail-messages', kind: 'message', id: JSON.stringify([source.sessionId, url, false]) }, undefined, ['mail-message']);+ supported = (resource.blocks?.[0]?.data as { supported?: unknown })?.supported === true;+ } catch { /* Legacy hosts open the original link. */ }+ if (current.current !== source || !isMobileAuthOwnerCurrent(owner)) return;+ if (supported) {+ router.push({ pathname: '/mail-preview', params: { deviceId: source.deviceId, sessionId: source.sessionId, url } });+ return;+ }+ }+ await Linking.openURL(url);+ } finally { busy.current = false; }+ };+ return <SpanText onPress={() => { void open().catch(() => undefined); }} style={style}>{children}</SpanText>;+}diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex b4118ef1b3..0982747a6e 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -247,6 +247,7 @@ import {type ChatPathCandidate,} from '@/session/chatPathCandidate';import { ChatFilePathContext, type ChatFilePathTarget } from '@/session/chatFilePathContext';+import { MailLinkSpan } from '@/session/MailLinkSpan';import {peekRemotePathVerdict,peekRemotePathVerdictForRender,@@ -6478,13 +6479,14 @@ function renderInline(void Linking.openURL(inline.url).catch(() => undefined);};return (- <SpanText+ <MailLinkSpankey={spanKey(`link:${index}:${inline.url}`)}- onPress={openExternalUrl}+ url={inline.url}+ SpanText={SpanText}style={clickableInlineStyle(styles, openExternalUrl, ctx.baseStyle)}>{inline.text}- </SpanText>+ </MailLinkSpan>);}case 'strong':@@ -6749,13 +6751,15 @@ function ToolMediaBlock({function PluginResultCard({ callId, sessionId, excludedUrls, actions }: {callId: string; sessionId: string; excludedUrls: string[]; actions: MessageActions;}) {- const { blocks, error, retry } = usePluginResultCard(actions.remoteDeviceId, sessionId, callId);+ const { blocks, error, retry, hidden } = usePluginResultCard(actions.remoteDeviceId, sessionId, callId);const layout = buildMessageContentLayout({ screenWidth: actions.screenWidth });const styles = useThemedStyles(makeStyles);const { t } = useTranslation();+ if (hidden) return null;return <View style={styles.toolMediaBlock} testID="message.pluginResultCard">{blocks?.map((block) => {- if (block.primitive === 'plugin-card-actions') return <PluginCardActions key={block.id} data={block.data} deviceId={actions.remoteDeviceId} sessionId={sessionId} callId={callId} />;+ if (block.primitive === 'plugin-card-actions') return <PluginCardActions key={block.id} data={block.data} deviceId={actions.remoteDeviceId} sessionId={sessionId} callId={callId}+ onOpenAttachment={actions.onOpenPayload ? (url, name) => actions.onOpenPayload!(buildMediaPayload({ kind: 'image', url, previewable: true }, name)) : undefined} />;const url = (block.data as { url?: unknown } | undefined)?.url;const kind = managedToolMediaKind(url);if (typeof url === 'string' && excludedUrls.includes(url)) return null;diff --git a/apps/mobile/src/session/usePluginResultCard.ts b/apps/mobile/src/session/usePluginResultCard.tsindex f93cca9bde..013822facd 100644--- a/apps/mobile/src/session/usePluginResultCard.ts+++ b/apps/mobile/src/session/usePluginResultCard.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useId, useRef, useState } from 'react';import { useIsFocused } from 'expo-router';import { AppState } from 'react-native';import type { RemoteResourceBlock } from '@cindy/device-link';+import { parseMailCard } from '@cindy/maker-shared/ghost-card-form';import { useAuth } from '@/auth/AuthContext';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { getRemoteResource } from '@/device-link/remoteResources';@@ -11,7 +12,10 @@ import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscri* Refresh after foreground/reconnect and host invalidation; stale replies cannot* replace a recycled row or another account's card. */export function usePluginResultCard(deviceId: string | undefined, sessionId: string, callId: string) {- return useSessionPluginResource(deviceId, sessionId, callId, 'plugin-results', 'card');+ const resource = useSessionPluginResource(deviceId, sessionId, callId, 'plugin-results', 'card');+ const hidden = resource.blocks?.some(block => block.primitive === 'plugin-card-actions' &&+ !!parseMailCard((block.data as { mail?: unknown } | undefined)?.mail)?.supersededBy) ?? false;+ return { ...resource, hidden };}export function useSessionPluginResource(deviceId: string | undefined, sessionId: string, callId: string, collectionId: string, kind: string) {@@ -35,7 +39,7 @@ export function useSessionPluginResource(deviceId: string | undefined, sessionIdconst expected = ++generation;const valid = () => !disposed && current.current === binding && generation === expected && AppState.currentState === 'active';try {- const resource = await getRemoteResource(invoke, { deviceId, deviceName: deviceId }, { collectionId, kind, id }, undefined, collectionId === 'plugin-results' ? ['plugin-card-actions'] : []);+ const resource = await getRemoteResource(invoke, { deviceId, deviceName: deviceId }, { collectionId, kind, id }, undefined, collectionId === 'plugin-results' ? ['plugin-card-actions', 'plugin-card-forms'] : []);if (valid()) setState({ binding, blocks: resource.blocks ?? [], title: typeof resource.display.title === 'string' ? resource.display.title : resource.display.title.fallback, error: kind === 'card' && !resource.blocks?.length });} catch (error) {const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex e6cc6f49df..aa14fbf8e4 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,52 @@# 跨端协议兼容+## 邮件阅读会话++只读 MailMessage 可选增加 conversation(threadId 和按时间排列的 messages 摘要)。+摘要包含 messageId、url、from、date、subject、snippet,不附带所有正文;当前 messageId 必须在摘要中。+Host 验证摘要唯一性、数量/长度及链接属于同一插件声明域名;展开时复用现有 mailReader,客户端核对返回的账号和邮件 ID。+conversationUnavailable 表示当前邮件可读但周边邮件未能读取,界面提供重试。+桌面右侧阅读器定位当前邮件,长会话折叠中间摘要。旧查看端(含现有手机)忽略新增字段,保留单封阅读;旧插件照常返回单封。+沿用现有 IPC 和 mail-messages 远程资源,无新 channel、数据库迁移、权限或原生变更。++## 插件卡片文本表单++交互卡沿用 v2,在净化后的 div 上可选增加 `data-ghost-form` 字段数组,动作可选增加+`data-ghost-submit="true"`。桌面与手机共用 maker-shared 校验和标准文本控件;+不开放插件脚本、HTML input、文件输入或凭据输入。字段名唯一,最多 16 项,每项值最多 16000 字。+桌面既有 dispatchCardAction IPC 可选追加 formValues;远程 `plugin-card-actions` 投影可选追加+form 和 items[].submit,既有 invoke 的 input 可选追加 formValues。手机声明 `plugin-card-forms`+能力后,Host 才投影表单并省略重复的静态预览;旧手机保留预览、禁用提交按钮。Host 继续校验会话、+设备、页面与 revision,并检查提交字段与当前声明一致;真实点击票和 Agent 续接规则不变。+表单提交活动归原 callId,插件完成后原地更新卡片,不产生新的空操作卡。++新查看端连接旧 Host 时没有 form,维持原卡片行为。旧查看端忽略新字段;旧桌面保留+插件提供的静态预览,新 Host 拒绝缺少字段的表单提交。插件也必须拒绝缺少 formValues+的写入,并说明需更新客户端或通过原工具继续处理。发布时先升级 Host 和查看端,再发布+依赖表单的插件;插件须保留原工具入口,不把卡片不可用误报为业务写入失败。+字段可选 row(同排分组)和 collapsed(默认折叠)。kind:"recipients" 为可选展示提示:+桌面和手机按实测姓名宽度与卡片宽度折叠剩余人数,展开直接替换摘要;完整地址字符串照常编辑与提交。+旧端忽略 kind 并保留原文本编辑框,未知 kind 也退回文本框,不影响已安装插件。div 可选 data-ghost-change 动作 ID,+桌面 IPC 与手机 input 可选 formChange:true,Host 投递无点击票的 card-action 编辑事件;不唤起 Agent。+手机编辑事件校验当前 changeAction、字段和会话归属;同一编辑版本的自动保存回执允许 revision 变化,+发送校验完整 revision,或同一 formKey(即当前 changeAction)与声明动作。插件必须在自动保存期间保持 changeAction,在重新读取/替换草稿时换 ID。+自动保存回执不重建输入框,不覆盖正在输入的文字。插件负责保存、冲突处理及模型读写与卡片提交的一致性。+发送聊天消息前等待该任务已发起的编辑事件送达,避免远程输入被模型工具超越。+card-update 可选 sourceCallId:只接受当前在途、同插件同任务的工具调用,用于更新较早的卡片;+旧调用、跨任务、跨插件和脚本调用不能重开。旧 Host 忽略此字段,可能不更新超出宽限窗的旧卡,业务工具仍返回回执。+没有新 channel、服务端 schema、数据库迁移或 Mobile 原生 fingerprint 变化。++`ghosts:card-updated` 可选携带 Host 注册调用时确定的 `sessionId`,桌面实时卡匹配只使用+当前对话的推送,避免同插件在多个对话同时运行时串卡。旧 Host 缺此字段时不猜测归属,+等待工具结果里的明确卡片 ID;历史与 fork 的明确 ID 引用仍可显示。旧查看端忽略新增字段。+手机沿用按设备、对话和卡片 ID 获取资源的路径;没有新 channel 或插件作者契约。++公共邮件发送沿用 sending 状态,可选 pendingSend(deadline、label、cancelLabel、sendNowLabel)。+Host 仅在此等待阶段接受 mail:cancel / mail:now;动作不提交表单,草稿编辑锁定。+两端只显示倒计时,真正的 10 秒等待和发送由公共邮件 SDK 执行;同草稿重复请求共用一次等待。+撤销、重新读取或修改草稿取消等待,重启不会恢复自动发送。旧端忽略 pendingSend,仍按 sending+锁定编辑;旧手机可能无法操作新增按钮,完整撤销交互需升级查看端。没有新 channel 或原生配置。+## MCP Apps标准 MCP Apps 使用 `io.modelcontextprotocol/ui` 扩展及官方 `2026-01-26` 协议。@@ -2160,3 +2207,168 @@ PC 同源 ghostPermissionItems 声明摘要投影并排除 tool,以请求 loca`:switch-home` / `:home-choices`,并新增 `:attachment`、`:cindy-copies`、`:merge-cindy` 与 `maker:companion-avatar:resolve`,只在同一个 Desktop 内的 preload 与 Main 之间使用。伙伴资料快照 `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.+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.+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. 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`.+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. Only an explicit user opening+passes it; AI reads, probes and neighboring preloads remain read-only. Mark only the+successfully resolved selected 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.diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.tsindex d59c7b6e50..e81af2d8c9 100644--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@ -73,6 +73,8 @@ const D_GHOST_CALL = ["调用某个插件(Ghost)提供的工具。ghost_id 与 tool 来自 ghost_info 或 ghost_list 的返回,","或用户消息[插件指令]附带的工具清单;","args 按该工具声明的参数 schema 传 JSON 对象。",+ "邮件默认先创建并展示 Cindy 草稿卡,供用户核对收件人和内容,等确认后再发送。只有用户已明确确认这封邮件,或有效的用户/任务指令明确授权该范围内直接发送时,才可不再询问;‘帮我写/回一封邮件’、修改草稿、自动审批或完全访问模式本身不等于确认发送。",+ "即使明确授权直接发送,也必须通过同一草稿卡的公共发送流程,使用最新编辑内容,并保留 10 秒倒计时、撤销和立即发送;不能用底层直发、CLI 或其他旁路跳过。卡片发送点击即为确认,不重复询问;等待最终回执才报告已发送,撤销后不得自动重试。","伙伴中需要授权时,Host 发出独立持久卡并立即返回 SETUP_REQUIRED;结束本轮,等 Host 授权成功后自动续接,不要轮询或重复调用。普通任务仍沿用原调用等待。","部分插件(如 cindy-github / cindy-gitlab)采用二级分派:ghost_info / ghost_list 只暴露 list_tools 与","call_tool 两个工具,具体操作(如 create_pull_request_review)不是顶层 tool,必须经 call_tool",diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 6264836188..9d2720a1ba 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -31,6 +31,9 @@"./file-preview": "./src/filePreview.ts","./fixtures": "./src/fixtures.ts","./ghost-command": "./src/ghostCommand.ts",+ "./ghost-card-form": "./src/ghostCardForm.ts",+ "./mail-text-edit": "./src/mailTextEdit.ts",+ "./mail-message": "./src/mailMessage.ts","./goal-command": "./src/goalCommand.ts","./goal-verdict": "./src/goalVerdict.ts","./history-gap": "./src/historyGap.ts",@@ -111,6 +114,9 @@"email": "[email protected]"},"license": "Apache-2.0",+ "dependencies": {+ "parse5": "8.0.1"+ },"devDependencies": {"@eslint/js": "^9.0.0","@types/node": "*",diff --git a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts b/packages/maker-shared/src/__tests__/ghostCardForm.test.tsnew file mode 100644index 0000000000..b0fec2457c--- /dev/null+++ b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts@@ -0,0 +1,186 @@+import { describe, expect, it } from "vitest";+import { applyMailInlineEdits, mailInlineRuns, mailTextParagraphs, safeMailDocument } from '../mailTextEdit';+import {+ parseGhostCardForm,+ parseGhostCardFormValues,+ readGhostCardForm,+ omitGhostCardFormPreview,+ trackGhostCardFormDelivery,+ pendingGhostCardFormDelivery,+ ghostCardRecipients,+ fitGhostCardRecipients,+ mailCardStatus,+ parseMailCard,+ insertMailImage,+ mailPreviewImages,+ visibleMailAttachments,+} from "../ghostCardForm";++describe("declarative card forms", () => {+ // Shared presentation contract: inline images disappear only from the list,+ // never from the outgoing MIME data. Text, comments and CID prefixes do not count.+ it('lists ordinary attachments and restores images when their last HTML reference is removed', () => {+ const files = [+ { key: 'body', filename: 'body.png', contentId: '<body>', mimeType: 'image/png' },+ { key: 'quote', filename: 'quote.jpg', contentId: 'quote', mimeType: 'image/jpeg' },+ { key: 'unused', filename: 'unused.png', contentId: 'unused', mimeType: 'image/png' },+ { key: 'pdf', filename: 'notes.pdf', mimeType: 'application/pdf' },+ ];+ const values = { attachmentItems: JSON.stringify(files), bodyHtml: '<img src="cid:body"><!-- <img src="cid:unused"> --><p>cid:unused</p><img src="cid:unused-extra">', quoteHtml: "<IMG SRC='cid:quote'>" };+ expect(visibleMailAttachments(values).map(f => f.key)).toEqual(['unused', 'pdf']);+ expect(JSON.parse(values.attachmentItems)).toEqual(files);+ expect(visibleMailAttachments({ ...values, bodyHtml: '' }).map(f => f.key)).toEqual(['body', 'unused', 'pdf']);+ expect(visibleMailAttachments({ ...values, bodyHtml: '', quoteHtml: '' })).toEqual(files);+ });+ it('inserts existing image bytes with an unused CID and keeps preview addresses out of the authored HTML', () => {+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;+ const values = { bodyHtml: '<html><head><style>img{width:200px}</style></head><body><p>Hi</p></body></html>', attachmentItems: JSON.stringify([+ { key: 'first', filename: 'first.png', mimeType: 'image/png', contentId: '[email protected]' },+ { key: 'next', filename: '<next>.png', mimeType: 'image/png', previewUrl: url },+ { key: 'pdf', filename: 'notes.pdf', mimeType: 'application/pdf' },+ ]) };+ const next = insertMailImage(values, 'attachmentItems', 'next');+ expect(next.bodyHtml).toContain('src="cid:[email protected]" alt="<next>.png"');+ expect(next.bodyHtml).toContain('<style>img{width:200px}</style>');+ expect(next.bodyHtml).not.toContain('cindy-media:');+ expect(mailPreviewImages(next)).toEqual([{ cid: '[email protected]', url }]);+ expect(visibleMailAttachments(next).map(f => f.key)).toEqual(['first', 'pdf']);+ expect(insertMailImage(next, 'attachmentItems', 'next')).toBe(next);+ expect(insertMailImage(values, 'attachmentItems', 'pdf')).toBe(values);+ });+ // User correction: simple typing must preserve HTML, not flatten it. Unit+ // tests cover the shared production text patcher; previous coverage was preview-only.+ it('edits paragraphs and line breaks while preserving CSS, inline formatting, links and CID images', () => {+ const html = '<!doctype html><html><head><style>p{color:red}</style></head><body><p>Hello <b>Cherry</b> & Dash</p><p><a href="https://example.test">Link</a><br>Next</p><img src="cid:card"></body></html>';+ expect(mailTextParagraphs(html).map(p => p.text)).toEqual(['Hello Cherry & Dash', 'Link\nNext']);+ expect(applyMailInlineEdits(html, {})!.html).toBe(html);+ expect(mailInlineRuns(html).map(r => r.text)).toEqual(['Hello ', 'Cherry', ' & Dash', 'Link', '\n', 'Next']);+ const updated = applyMailInlineEdits(html, { 0: 'Hello Dear ', 5: 'New\nNext' })!;+ expect(updated.html).toContain('<p>Hello Dear <b>Cherry</b> & Dash</p>');+ expect(updated.html).toContain('<a href="https://example.test">Link</a><br>New<br>Next');+ expect(updated.html).toContain('<style>p{color:red}</style>');+ expect(updated.html).toContain('src="cid:card"');+ expect(updated.text).toBe('Hello Dear Cherry & Dash\n\nLink\nNew\nNext');+ expect(applyMailInlineEdits(html, { 1: '' })!.html).toContain('<p>Hello <b></b> & Dash</p>');+ expect(applyMailInlineEdits('<p></p>', { 0: 'New greeting' })!.html).toBe('<p>New greeting</p>');+ const invalid: Record<string, string>[] = [{ '-1': 'x' }, { 999: 'x' }, { 0: 'x'.repeat(16001) }, { 0: '\0' }];+ for (const edits of invalid) expect(applyMailInlineEdits(html, edits)).toBeNull();+ });+ it('treats typed markup as text and allows adding words to an image-only draft', () => {+ const html = '<html><head><title>Not body text</title></head><body><img src="cid:card"></body></html>';+ expect(mailTextParagraphs(html).map(p => p.text)).toEqual(['']);+ const updated = applyMailInlineEdits(html, { 0: 'Hi <script>alert(1)</script>\n你好' })!;+ expect(updated.html).toContain('<img src="cid:card">Hi <script>alert(1)</script><br>你好</body>');+ expect(updated.text).toBe('Hi <script>alert(1)</script>\n你好');+ });+ it('creates editable markers only after stripping authored controls and executable content', () => {+ const safe = safeMailDocument('<p contenteditable="true" data-cindy-mail-run="99" onclick="evil()">Hello</p><script>evil()</script><iframe src="x"></iframe><img src="cid:card">', true);+ expect(safe).toContain('<span data-cindy-mail-run="0">Hello</span>');+ expect(safe).not.toMatch(/evil|contenteditable|iframe|run="99"/);+ expect(safeMailDocument('<p></p>', true)).toContain('<p><span data-cindy-mail-run="0"></span></p>');+ });+ it('round-trips a pending send and derives the displayed time without granting send permission', () => {+ const mail = parseMailCard({ accountId: 'a', draftId: 'd', key: '12345678-1234-1234-1234-123456789abc', from: '[email protected]',+ fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: '' })),+ attachments: [], state: 'sending', status: 'Waiting', sendLabel: 'Send', fromLabel: 'From',+ pendingSend: { deadline: 11000, label: '{seconds} 秒后发送', cancelLabel: '撤销', sendNowLabel: '立即发送' } });+ expect(mail).not.toBeNull();+ expect(mailCardStatus(mail!, 1000)).toBe('10 秒后发送');+ expect(mailCardStatus(mail!, 10001)).toBe('1 秒后发送');+ expect(mailCardStatus(mail!, 12000)).toBe('0 秒后发送');+ expect(parseMailCard({ ...mail, state: 'sent' })).toBeNull();+ expect(parseMailCard({ ...mail, pendingSend: { ...mail!.pendingSend, deadline: 'soon' } })).toBeNull();+ });+ // Width-based overflow must not omit a recipient or split a quoted display+ // name into multiple people. Pure unit coverage shared by both renderers.+ it("packs measured names only when needed and preserves quoted addresses", () => {+ const addresses =+ '"Smith, Jane" <[email protected]>, 李明 <[email protected]>';+ expect(ghostCardRecipients(addresses)).toEqual([+ { address: '"Smith, Jane" <[email protected]>', label: "Smith, Jane" },+ { address: "李明 <[email protected]>", label: "李明" },+ ]);+ const groups = [+ { label: 30, chips: [50, 100, 50], more: [12, 20, 20, 20] },+ { label: 20, chips: [40], more: [12, 20] },+ ];+ expect(fitGhostCardRecipients(500, groups)).toEqual([3, 1]);+ expect(fitGhostCardRecipients(190, groups)).toEqual([1, 1]);+ // If only one name fits, keep the primary recipient rather than a Cc name.+ expect(fitGhostCardRecipients(160, groups)).toEqual([1, 0]);+ expect(fitGhostCardRecipients(100, groups)).toEqual([0, 0]);+ const field = {+ name: "to",+ label: "To",+ value: addresses,+ kind: "recipients",+ };+ expect(parseGhostCardForm([field])?.[0]).toEqual(field);+ expect(+ parseGhostCardForm([{ ...field, kind: "future" }])?.[0].kind,+ ).toBeUndefined();+ });+ it("holds chat behind edits in flight and fails closed until a new delivery succeeds", async () => {+ let resolve!: (ok: boolean) => void;+ trackGhostCardFormDelivery(+ "task",+ "card",+ new Promise((done) => {+ resolve = done;+ }),+ );+ const pending = pendingGhostCardFormDelivery("task")!;+ expect(pendingGhostCardFormDelivery("other")).toBeUndefined();+ resolve(false);+ expect(await pending).toBe(false);+ expect(await pendingGhostCardFormDelivery("task")).toBe(false);+ trackGhostCardFormDelivery("task", "card", Promise.resolve(true));+ expect(await pendingGhostCardFormDelivery("task")).toBe(true);+ expect(pendingGhostCardFormDelivery("task")).toBeUndefined();+ });+ it("round-trips text, quotes, newlines and markup as inert data", () => {+ const fields = [+ {+ name: "body",+ label: "Message",+ value: '<script> & "\n正文',+ multiline: true,+ },+ ];+ const encoded = JSON.stringify(fields)+ .replace(/&/g, "&")+ .replace(/"/g, """)+ .replace(/</g, "<")+ .replace(/>/g, ">");+ expect(+ readGhostCardForm(`<div data-ghost-form="${encoded}">Preview</div>`),+ ).toEqual(fields);+ expect(+ omitGhostCardFormPreview(+ `<div data-ghost-form="${encoded}"><div>Nested preview</div></div><p>Sender</p>`,+ ),+ ).toBe("<p>Sender</p>");+ expect(parseGhostCardFormValues({ body: " exact\n" })).toEqual({+ body: " exact\n",+ });+ });+ it("rejects duplicates, prototype keys, oversized and unsupported fields", () => {+ const field = { name: "body", label: "Message", value: "text" };+ for (const fields of [+ [field, field],+ [{ ...field, name: "__proto__" }],+ [{ ...field, value: "x".repeat(16001) }],+ [{ ...field, multiline: "yes" }],+ ])+ expect(parseGhostCardForm(fields)).toBeNull();+ for (const values of [+ [],+ {},+ { body: 1 },+ { constructor: "x" },+ { body: "x".repeat(16001) },+ ])+ expect(parseGhostCardFormValues(values)).toBeNull();+ expect(readGhostCardForm('<div data-ghost-form="[]"></div>')).toBeNull();+ });+});diff --git a/packages/maker-shared/src/ghostCardForm.ts b/packages/maker-shared/src/ghostCardForm.tsnew file mode 100644index 0000000000..04d044a6b7--- /dev/null+++ b/packages/maker-shared/src/ghostCardForm.ts@@ -0,0 +1,414 @@+import { parse, type DefaultTreeAdapterTypes } from 'parse5';++/** Declarative, non-secret text fields. Plugins never supply executable controls. */+export interface GhostCardFormField {+ name: string;+ label: string;+ value: string;+ multiline?: boolean;+ row?: string;+ collapsed?: boolean;+ kind?: "recipients" | "mail-html" | "mail-attachments" | "hidden";+}+export const GHOST_CARD_FORM_MAX_VALUE = 16000;+export const MAIL_HTML_MAX_VALUE = 64000;+export const MAIL_CARD_MAX_BYTES = 1024 * 1024;+export function ghostCardFieldMaxValue(name: string): number {+ return name === 'bodyHtml' || name === 'quoteHtml' ? MAIL_HTML_MAX_VALUE : GHOST_CARD_FORM_MAX_VALUE;+}+export interface MailAttachmentItem { key: string; filename: string; bytes?: number; contentId?: string; mimeType?: string; previewUrl?: string }+export function parseMailAttachmentItems(value: string): MailAttachmentItem[] | null {+ try {+ const items = JSON.parse(value);+ if (!Array.isArray(items) || items.length > 100 || items.some(i => !i || typeof i.key !== 'string' || !i.key || i.key.length > 256 || typeof i.filename !== 'string' || i.filename.length > 1024 ||+ (i.bytes !== undefined && (!Number.isSafeInteger(i.bytes) || i.bytes < 0)) || (i.contentId !== undefined && (typeof i.contentId !== 'string' || i.contentId.length > 256))) || new Set(items.map(i => i.key)).size !== items.length) return null;+ return items.map(i => ({ key: i.key, filename: i.filename, ...(i.bytes !== undefined ? { bytes: i.bytes } : {}), ...(i.contentId ? { contentId: i.contentId } : {}),+ ...(typeof i.mimeType === 'string' && /^[\w.+-]+\/[\w.+-]+$/.test(i.mimeType) ? { mimeType: i.mimeType } : {}),+ ...(typeof i.previewUrl === 'string' && /^cindy-media:\/\/blobs\/[a-f0-9]{64}\.(png|jpg|jpeg|gif|webp)$/.test(i.previewUrl) ? { previewUrl: i.previewUrl } : {}) }));+ } catch { return null; }+}+/** Presentation only: body images keep their MIME parts and preview URLs, but+ * do not also appear as attachments. Removing the reference reveals them again. */+export function visibleMailAttachments(values: Record<string, string>, field = 'attachmentItems'): MailAttachmentItem[] {+ const files = parseMailAttachmentItems(values[field]) || [];+ if (!files.some(file => file.contentId)) return files;+ const used = new Set<string>();+ const walk = (node: DefaultTreeAdapterTypes.Node) => {+ if ('tagName' in node) {+ if (['head', 'script', 'style', 'template', 'noscript', 'svg', 'math', 'iframe', 'object', 'textarea', 'select'].includes(node.tagName)) return;+ if (node.tagName === 'img') {+ const src = node.attrs.find(attr => attr.name === 'src')?.value;+ if (src?.startsWith('cid:')) used.add(src.slice(4));+ }+ }+ if ('childNodes' in node) for (const child of node.childNodes) walk(child);+ };+ for (const name of ['bodyHtml', 'quoteHtml']) if (values[name]) walk(parse(values[name]));+ return files.filter(file => !file.contentId || !used.has(file.contentId.replace(/^<|>$/g, '')));+}+/** Remove the MIME part and its visible CID image together, preserving the rest+ * of the authored document (including head styles) on both clients. */+export function removeMailAttachment(values: Record<string, string>, field: string, key: string): Record<string, string> {+ const files = parseMailAttachmentItems(values[field]) || [];+ const file = files.find(f => f.key === key);+ const next = { ...values, [field]: JSON.stringify(files.filter(f => f.key !== key)) };+ const cid = file?.contentId?.replace(/^<|>$/g, '');+ if (cid) for (const name of ['bodyHtml', 'quoteHtml']) if (next[name]) {+ next[name] = next[name].replace(/<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi, tag => {+ const src = /\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag);+ return src && (src[1] ?? src[2] ?? src[3]) === 'cid:' + cid ? '' : tag;+ });+ }+ return next;+}+export function canInsertMailImage(values: Record<string, string>, file: MailAttachmentItem): boolean {+ if (typeof values.bodyHtml !== 'string' || !/^image\/(png|jpeg|gif|webp)$/i.test(file.mimeType || '')) return false;+ const cid = file.contentId?.replace(/^<|>$/g, '');+ return !cid || !(values.bodyHtml + (values.quoteHtml || '')).includes('cid:' + cid);+}+/** Reuse an existing MIME part. Only its CID/disposition changes; its bytes+ * remain at the provider. Preview URLs are never written into the HTML. */+export function insertMailImage(values: Record<string, string>, field: string, key: string): Record<string, string> {+ const files = parseMailAttachmentItems(values[field]) || [];+ const file = files.find(f => f.key === key);+ if (!file || !canInsertMailImage(values, file)) return values;+ let cid = file.contentId?.replace(/^<|>$/g, '');+ if (!cid) {+ let n = 1;+ const used = new Set(files.map(f => f.contentId?.replace(/^<|>$/g, '')));+ do { cid = `image-${n++}@cindy.local`; } while (used.has(cid));+ }+ if (!/^[\w.+@-]{1,256}$/.test(cid)) return values;+ const alt = file.filename.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');+ const image = `<p><img src="cid:${cid}" alt="${alt}" style="max-width:100%;height:auto"></p>`;+ const html = values.bodyHtml;+ const end = /<\/body\s*>/i.exec(html);+ const bodyHtml = end ? html.slice(0, end.index) + image + html.slice(end.index) : html + image;+ const attachmentItems = JSON.stringify(files.map(f => f.key === key ? { ...f, contentId: cid } : f));+ if (bodyHtml.length > MAIL_HTML_MAX_VALUE || attachmentItems.length > GHOST_CARD_FORM_MAX_VALUE) return values;+ return { ...values, bodyHtml, [field]: attachmentItems };+}+export function mailPreviewImages(values: Record<string, string>, images: { cid: string; url: string }[] = []): { cid: string; url: string }[] {+ const result = new Map(images.map(i => [i.cid, i.url]));+ for (const file of parseMailAttachmentItems(values.attachmentItems || '[]') || []) {+ if (file.contentId && file.previewUrl) result.set(file.contentId.replace(/^<|>$/g, ''), file.previewUrl);+ }+ return [...result].map(([cid, url]) => ({ cid, url }));+}+/** Cindy-owned mail presentation, transported inside the existing persisted card.+ * Provider instance + account + draft identify the entity; callId identifies a view. */+export interface MailCardData {+ accountId: string;+ draftId: string;+ key: string;+ from: string;+ fields: GhostCardFormField[];+ /** Last verified provider values, used for three-way merging after restart. */+ baseValues?: Record<string, string>;+ attachments: string[];+ images?: { cid: string; url: string }[];+ state: 'draft' | 'syncing' | 'sending' | 'sent' | 'error' | 'unconfirmed' | 'deleting' | 'deleted';+ status: string;+ sendLabel: string;+ fromLabel: string;+ continueLabel?: string;+ deleteLabel?: string;+ supersededBy?: string;+ pendingSend?: { deadline: number; label: string; cancelLabel: string; sendNowLabel: string };+}+export function parseMailCard(value: unknown): MailCardData | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const p = value as Record<string, unknown>;+ const fields = parseGhostCardForm(p.fields);+ if (!fields || !['to', 'cc', 'bcc', 'subject', 'body'].every(n => fields.some(f => f.name === n))) return null;+ const baseValues = p.baseValues === undefined ? undefined : parseGhostCardFormValues(p.baseValues);+ if (baseValues === null || (baseValues && (!['to', 'cc', 'bcc', 'subject', 'body'].every(n => n in baseValues) ||+ (baseValues.attachmentItems !== undefined && !parseMailAttachmentItems(baseValues.attachmentItems))))) return null;+ for (const k of ['accountId', 'draftId', 'key', 'from', 'status', 'sendLabel', 'fromLabel']) {+ if (typeof p[k] !== 'string' || (p[k] as string).length > 2048) return null;+ }+ if (!p.accountId || !p.draftId || !/^[a-f0-9-]{36}$/.test(p.key as string) ||+ !['draft', 'syncing', 'sending', 'sent', 'error', 'unconfirmed', 'deleting', 'deleted'].includes(p.state as string) ||+ !Array.isArray(p.attachments) || p.attachments.length > 100 ||+ p.attachments.some(a => typeof a !== 'string' || a.length > 1024) ||+ (p.continueLabel !== undefined && (typeof p.continueLabel !== 'string' || p.continueLabel.length > 128)) ||+ (p.deleteLabel !== undefined && (typeof p.deleteLabel !== 'string' || p.deleteLabel.length > 128)) ||+ (p.supersededBy !== undefined && (typeof p.supersededBy !== 'string' || p.supersededBy.length > 128))) return null;+ const pending = p.pendingSend as MailCardData['pendingSend'];+ const images = p.images as MailCardData['images'];+ if (images !== undefined && (!Array.isArray(images) || images.length > 100 || images.some(i => !i || typeof i.cid !== 'string' || i.cid.length > 256 || typeof i.url !== 'string' || !/^cindy-media:\/\/blobs\/[a-f0-9]{64}\.(png|jpg|jpeg|gif|webp)$/.test(i.url)))) return null;+ if (pending !== undefined && (!pending || p.state !== 'sending' ||+ !Number.isSafeInteger(pending.deadline) || pending.deadline <= 0 ||+ [pending.label, pending.cancelLabel, pending.sendNowLabel].some(v => typeof v !== 'string' || !v || v.length > 128))) return null;+ return { accountId: p.accountId as string, draftId: p.draftId as string, key: p.key as string,+ from: p.from as string, fields, attachments: p.attachments as string[], state: p.state as MailCardData['state'],+ ...(baseValues ? { baseValues } : {}),+ status: p.status as string, sendLabel: p.sendLabel as string, fromLabel: p.fromLabel as string,+ ...(images ? { images: images.map(i => ({ cid: i.cid, url: i.url })) } : {}),+ ...(p.continueLabel ? { continueLabel: p.continueLabel as string } : {}),+ ...(p.deleteLabel ? { deleteLabel: p.deleteLabel as string } : {}),+ ...(pending ? { pendingSend: { deadline: pending.deadline, label: pending.label, cancelLabel: pending.cancelLabel, sendNowLabel: pending.sendNowLabel } } : {}),+ ...(p.supersededBy ? { supersededBy: p.supersededBy as string } : {}) };+}+export function mailCardStatus(mail: MailCardData, now = Date.now()): string {+ return mail.pendingSend+ ? mail.pendingSend.label.replace('{seconds}', String(Math.max(0, Math.ceil((mail.pendingSend.deadline - now) / 1000))))+ : mail.status;+}+/** Remaining portion of the host's ten-second send grace period. */+export function mailSendRemainingFraction(mail: MailCardData, now = Date.now()): number {+ return mail.pendingSend ? Math.max(0, Math.min(1, (mail.pendingSend.deadline - now) / 10000)) : 0;+}+export function readMailCard(html: string): MailCardData | null {+ const value = /<div\b[^>]*\sdata-cindy-mail="([^"]*)"/.exec(html)?.[1];+ if (!value) return null;+ try { return parseMailCard(JSON.parse(value.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&'))); }+ catch { return null; }+}+export function isLegacyMailCard(html: string): boolean {+ return !readMailCard(html) && !!readGhostCardFormChange(html)?.startsWith('mail:change:');+}+const NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;+/** Adopt remote changes only where this editor has no newer local change. */+export function mergeGhostCardFormValues(+ local: Record<string, string>,+ base: Record<string, string>,+ next: Record<string, string>,+): Record<string, string> {+ return Object.fromEntries(+ Object.entries(next).map(([name, value]) => [+ name,+ local[name] === base[name] ? value : (local[name] ?? value),+ ]),+ );+}+// Only delivery promises, never form text. A chat send must not overtake local+// editor events still travelling to the Host (especially over device-link).+const deliveries = new Map<string, Map<string, Promise<boolean>>>();+export function trackGhostCardFormDelivery(+ scope: string,+ key: string,+ delivery: Promise<boolean>,+): void {+ let entries = deliveries.get(scope);+ if (!entries) deliveries.set(scope, (entries = new Map()));+ const settled = delivery.catch(() => false);+ entries.set(key, settled);+ void settled.then((ok) => {+ if (ok && entries!.get(key) === settled) entries!.delete(key);+ if (!entries!.size) deliveries.delete(scope);+ });+}+export function pendingGhostCardFormDelivery(+ scope: string,+): Promise<boolean> | undefined {+ const entries = deliveries.get(scope);+ if (!entries?.size) return undefined;+ const snapshot = [...entries.values()];+ return Promise.all(snapshot).then(async (results) => {+ if (results.some((ok) => !ok)) return false;+ return (await pendingGhostCardFormDelivery(scope)) ?? true;+ });+}+export function parseGhostCardForm(+ value: unknown,+): GhostCardFormField[] | null {+ let fields = value;+ if (typeof fields === "string") {+ if (fields.length > 200000) return null;+ try {+ fields = JSON.parse(fields);+ } catch {+ return null;+ }+ }+ if (!Array.isArray(fields) || !fields.length || fields.length > 16)+ return null;+ const names = new Set<string>();+ const result: GhostCardFormField[] = [];+ for (const item of fields) {+ if (+ !item ||+ typeof item !== "object" ||+ typeof item.name !== "string" ||+ !NAME.test(item.name) ||+ ["__proto__", "constructor", "prototype"].includes(item.name) ||+ names.has(item.name) ||+ typeof item.label !== "string" ||+ !item.label ||+ item.label.length > 128 ||+ typeof item.value !== "string" ||+ item.value.length > ghostCardFieldMaxValue(item.name) ||+ (item.multiline !== undefined && typeof item.multiline !== "boolean") ||+ (item.collapsed !== undefined && typeof item.collapsed !== "boolean") ||+ (item.row !== undefined &&+ (typeof item.row !== "string" || !NAME.test(item.row)))+ )+ return null;+ names.add(item.name);+ if (item.kind === 'mail-attachments' && !parseMailAttachmentItems(item.value)) return null;+ result.push({+ name: item.name,+ label: item.label,+ value: item.value,+ ...(item.multiline ? { multiline: true } : {}),+ ...(item.row ? { row: item.row } : {}),+ ...(item.collapsed ? { collapsed: true } : {}),+ ...(['recipients', 'mail-html', 'mail-attachments', 'hidden'].includes(item.kind) ? { kind: item.kind as GhostCardFormField['kind'] } : {}),+ });+ }+ return result;+}++/** Display parsing only: preserve the original header string for editing/sending. */+export function ghostCardRecipients(+ value: string,+): { address: string; label: string }[] {+ const parts: string[] = [];+ let start = 0,+ quoted = false,+ escaped = false,+ angle = 0,+ comment = 0;+ for (let i = 0; i < value.length; i++) {+ const char = value[i];+ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === "\\" && (quoted || comment)) {+ escaped = true;+ continue;+ }+ if (char === '"' && !comment) quoted = !quoted;+ if (quoted) continue;+ if (char === "(") comment++;+ if (char === ")") comment = Math.max(0, comment - 1);+ if (comment) continue;+ if (char === "<") angle++;+ if (char === ">") angle = Math.max(0, angle - 1);+ if ((char === "," || char === ";") && !angle) {+ parts.push(value.slice(start, i));+ start = i + 1;+ }+ }+ parts.push(value.slice(start));+ return parts+ .map((part) => part.trim())+ .filter(Boolean)+ .map((address) => ({+ address,+ label: (/^(.+)\s*<[^<>]+>$/.exec(address)?.[1]?.trim() || address)+ .replace(/^"(.*)"$/, "$1")+ .replace(/\\(["\\])/g, "$1"),+ }));+}++/** Both clients measure their own typography; only the packing decision is shared. */+export function fitGhostCardRecipients(+ available: number,+ groups: { label: number; chips: number[]; more: number[] }[],+ gap = 4,+): number[] {+ const counts = groups.map((group) => group.chips.length);+ const width = (index: number, count: number) => {+ const group = groups[index],+ remaining = group.chips.length - count;+ return (+ group.label ++ gap ++ group.chips.slice(0, count).reduce((a, b) => a + b + gap, 0) ++ (remaining || !group.chips.length ? group.more[remaining] : -gap)+ );+ };+ const total = () =>+ counts.reduce((sum, count, i) => sum + width(i, count), 0);+ while (total() > available) {+ let candidate = -1;+ const hasExtraNames = counts.some((count) => count > 1);+ counts.forEach((count, i) => {+ if (+ count > (hasExtraNames ? 1 : 0) &&+ (candidate < 0 ||+ !hasExtraNames ||+ width(i, count) > width(candidate, counts[candidate]))+ )+ candidate = i;+ });+ // Keep one name per group first, then preserve earlier fields (To before Cc).+ if (candidate < 0) break;+ counts[candidate]--;+ }+ // A shorter name may fit even when the wider group's next name does not.+ for (let i = 0; i < groups.length; i++) {+ while (counts[i] < groups[i].chips.length) {+ counts[i]++;+ if (total() > available) {+ counts[i]--;+ break;+ }+ }+ }+ return counts;+}++/** A stable change action also identifies the editing session across autosave updates. */+export function readGhostCardFormChange(html: string): string | undefined {+ const match = /<div\b[^>]*\sdata-ghost-change="([a-zA-Z0-9_:-]{1,128})"/.exec(+ html,+ );+ return readGhostCardForm(html) && match ? match[1] : undefined;+}+export function parseGhostCardFormValues(+ value: unknown,+): Record<string, string> | null {+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;+ const entries = Object.entries(value);+ if (!entries.length || entries.length > 16) return null;+ if (+ entries.some(+ ([name, text]) =>+ !NAME.test(name) ||+ ["__proto__", "constructor", "prototype"].includes(name) ||+ typeof text !== "string" ||+ text.length > ghostCardFieldMaxValue(name),+ )+ )+ return null;+ if (JSON.stringify(value).length > 200000) return null;+ return Object.fromEntries(entries) as Record<string, string>;+}+/** Sanitized HTML attributes only; text is never interpreted as markup. */+export function readGhostCardForm(html: string): GhostCardFormField[] | null {+ const matches = [...html.matchAll(/<div\b[^>]*\sdata-ghost-form="([^"]*)"/g)];+ if (matches.length !== 1) return null;+ return parseGhostCardForm(+ matches[0][1]+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/&/g, "&"),+ );+}++/** Omit the legacy preview only when a client will render the native fields. */+export function omitGhostCardFormPreview(html: string): string {+ if (!readGhostCardForm(html)) return html;+ const source = html.replace(/<(style|script)\b[^>]*>[\s\S]*?<\/\1>/gi, "");+ let start = -1,+ depth = 0;+ for (const match of source.matchAll(/<\/?div\b[^>]*>/g)) {+ if (start < 0) {+ if (!/\sdata-ghost-form="/.test(match[0])) continue;+ start = match.index!;+ depth = 1;+ } else if (match[0].startsWith("</")) {+ if (--depth === 0)+ return (+ source.slice(0, start) + source.slice(match.index! + match[0].length)+ );+ } else depth++;+ }+ return html;+}diff --git a/packages/maker-shared/src/mailMessage.ts b/packages/maker-shared/src/mailMessage.tsnew file mode 100644index 0000000000..65a02a71d8--- /dev/null+++ b/packages/maker-shared/src/mailMessage.ts@@ -0,0 +1,99 @@+import { parseMailAttachmentItems, type GhostCardFormField, type MailAttachmentItem } from './ghostCardForm.js';++/** Mail providers return data; Cindy owns the read-only presentation. */+export interface MailReaderDeclaration {+ tool: string;+ hosts: string[];+ /** The reader accepts markRead:true for an explicit user opening, never background reads. */+ markRead?: true;+}+export function parseMailReader(value: unknown): MailReaderDeclaration | null {+ if (!value || typeof value !== 'object') return null;+ const p = value as Record<string, unknown>;+ if (typeof p.tool !== 'string' || !/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(p.tool) ||+ !Array.isArray(p.hosts) || !p.hosts.length || p.hosts.length > 16 ||+ !p.hosts.every(h => typeof h === 'string' && h.length <= 253 && /^[a-z0-9]+(?:[.-][a-z0-9]+)*\.[a-z]{2,}$/.test(h))) return null;+ return { tool: p.tool, hosts: [...new Set(p.hosts as string[])], ...(p.markRead === true ? { markRead: true } : {}) };+}+export function mailReaderMatches(reader: MailReaderDeclaration, url: string): boolean {+ try {+ const target = new URL(url);+ return url.length <= 2048 && target.protocol === 'https:' && !target.username && !target.password &&+ !target.port && reader.hosts.includes(target.hostname);+ } catch { return false; }+}+export interface MailMessage {+ accountId: string;+ messageId: string;+ from: string;+ to: string;+ cc: string;+ bcc: string;+ subject: string;+ date: string;+ bodyText: string;+ bodyHtml: string;+ attachments: MailAttachmentItem[];+ /** Optional, chronological metadata only. Bodies are read on explicit expansion. */+ conversation?: MailConversation;+ conversationUnavailable?: boolean;+ markReadFailed?: boolean;+}+export interface MailMessageSummary {+ messageId: string;+ url: string;+ from: string;+ date: string;+ subject: string;+ snippet: string;+}+export interface MailConversation {+ threadId: string;+ messages: MailMessageSummary[];+}+function parseConversation(value: unknown, selectedId: string): MailConversation | null {+ if (!value || typeof value !== 'object') return null;+ const p = value as MailConversation;+ if (typeof p.threadId !== 'string' || !p.threadId || p.threadId.length > 512 ||+ !Array.isArray(p.messages) || !p.messages.length || p.messages.length > 1000) return null;+ const ids = new Set<string>();+ const messages: MailMessageSummary[] = [];+ const limits = { messageId: 512, url: 2048, from: 16000, date: 256, subject: 16000, snippet: 2048 };+ for (const item of p.messages) {+ if (!item || typeof item !== 'object' || Object.entries(limits).some(([key, max]) =>+ typeof item[key as keyof MailMessageSummary] !== 'string' || item[key as keyof MailMessageSummary].length > max) ||+ !item.messageId || ids.has(item.messageId)) return null;+ try {+ const url = new URL(item.url);+ if (url.protocol !== 'https:' || url.username || url.password || url.port) return null;+ } catch { return null; }+ ids.add(item.messageId);+ messages.push(Object.fromEntries(Object.keys(limits).map(k => [k, item[k as keyof MailMessageSummary]])) as unknown as MailMessageSummary);+ }+ return ids.has(selectedId) ? { threadId: p.threadId, messages } : null;+}+export function parseMailMessage(value: unknown): MailMessage | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const p = value as Record<string, unknown>;+ const limits = { accountId: 256, messageId: 512, from: 16000, to: 16000, cc: 16000, bcc: 16000,+ subject: 16000, date: 256, bodyText: 1024 * 1024, bodyHtml: 1024 * 1024 };+ if (Object.entries(limits).some(([key, max]) => typeof p[key] !== 'string' || (p[key] as string).length > max) ||+ !p.accountId || !p.messageId) return null;+ const attachments = parseMailAttachmentItems(JSON.stringify(p.attachments));+ if (!attachments) return null;+ const conversation = parseConversation(p.conversation, p.messageId as string);+ return { ...Object.fromEntries(Object.keys(limits).map(k => [k, p[k]])), attachments,+ ...(p.markReadFailed === true ? { markReadFailed: true } : {}),+ ...(conversation ? { conversation } : {}),+ ...(p.conversationUnavailable === true || (p.conversation !== undefined && !conversation) ? { conversationUnavailable: true } : {}),+ } as unknown as MailMessage;+}+/** Reuse the compose card's HTML, recipients, CID and attachment renderers, with no actions. */+export function mailMessageFields(mail: MailMessage, label: (key: string) => string): GhostCardFormField[] {+ return [+ ...(['to', 'cc', 'bcc'] as const).map(name => ({ name, label: label(name), value: mail[name], kind: 'recipients' as const, row: 'recipients' })),+ { name: 'subject', label: label('subject'), value: mail.subject },+ mail.bodyHtml ? { name: 'bodyHtml', label: '', value: mail.bodyHtml, kind: 'mail-html' } : { name: 'body', label: '', value: mail.bodyText, multiline: true },+ { name: 'attachmentItems', label: '', value: JSON.stringify(mail.attachments), kind: 'mail-attachments' },+ ];+}diff --git a/packages/maker-shared/src/mailTextEdit.ts b/packages/maker-shared/src/mailTextEdit.tsnew file mode 100644index 0000000000..7684f45ff0--- /dev/null+++ b/packages/maker-shared/src/mailTextEdit.ts@@ -0,0 +1,168 @@+import { parse, serialize, defaultTreeAdapter as adapter, html as htmlNames, type DefaultTreeAdapterTypes } from 'parse5';++type Run = { start: number; end: number; text: string };+type Paragraph = { text: string; runs: Run[] };+const blocks = new Set('p div section article header footer main blockquote pre li ul ol table tr td th h1 h2 h3 h4 h5 h6'.split(' '));+const omitted = new Set('head script style template noscript svg math iframe object textarea select'.split(' '));++/** Source offsets let both clients change text without serializing the document:+ * styles, links, CID references and untouched markup retain their original bytes.+ * No HTML is evaluated and preview URLs never enter the saved draft. */+export function mailTextParagraphs(html: string): Paragraph[] {+ const doc = parse(html, { sourceCodeLocationInfo: true });+ const result: Paragraph[] = [];+ let runs: Run[] = [];+ let insertAt = html.length;+ const flush = (force = false) => {+ const text = runs.map(run => run.text).join('');+ if (text.trim() || (force && runs.length)) result.push({ text, runs });+ runs = [];+ };+ const walk = (node: DefaultTreeAdapterTypes.Node) => {+ if ('tagName' in node) {+ if (omitted.has(node.tagName) || node.attrs.some(a => a.name === 'hidden' || (a.name === 'aria-hidden' && a.value === 'true'))) return;+ if (node.tagName === 'body') insertAt = node.sourceCodeLocation?.endTag?.startOffset ?? html.length;+ if (blocks.has(node.tagName)) flush();+ if (node.tagName === 'br' && node.sourceCodeLocation) {+ runs.push({ start: node.sourceCodeLocation.startOffset, end: node.sourceCodeLocation.endOffset, text: '\n' });+ }+ }+ const count = result.length;+ if ('value' in node && node.sourceCodeLocation && (node.value.trim() || !/[\r\n]/.test(node.value))) {+ runs.push({ start: node.sourceCodeLocation.startOffset, end: node.sourceCodeLocation.endOffset, text: node.value });+ }+ if ('childNodes' in node) for (const child of node.childNodes) walk(child);+ if ('tagName' in node && blocks.has(node.tagName)) {+ if (!runs.length && result.length === count && node.sourceCodeLocation?.startTag) {+ const at = node.sourceCodeLocation.startTag.endOffset;+ runs.push({ start: at, end: at, text: '' });+ }+ flush(true);+ }+ };+ walk(doc); flush();+ return result.length ? result : [{ text: '', runs: [{ start: insertAt, end: insertAt, text: '' }] }];+}++const escape = (text: string) => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\r\n?|\n/g, '<br>');++export const mailInlineRuns = (source: string) => mailTextParagraphs(source).flatMap(p => p.runs);++/** Only text from known source spans is accepted, never HTML from the WebView. */+export function applyMailInlineEdits(source: string, edits: Record<string, string>): { html: string; text: string } | null {+ const runs = mailInlineRuns(source);+ const patches: { start: number; end: number; value: string }[] = [];+ for (const [id, text] of Object.entries(edits)) {+ if (!/^(0|[1-9]\d*)$/.test(id) || !runs[Number(id)] || typeof text !== 'string' || text.length > 16000 || text.includes('\0')) return null;+ const run = runs[Number(id)];+ if (text !== run.text) patches.push({ start: run.start, end: run.end, value: escape(text) });+ }+ let html = source;+ for (const p of patches.sort((a, b) => b.start - a.start)) html = html.slice(0, p.start) + p.value + html.slice(p.end);+ const text = mailTextParagraphs(html).map(p => p.text).join('\n\n');+ return html.length <= 64000 && text.length <= 16000 ? { html, text } : null;+}++const tags = new Set('html head body style a b strong i em u s strike p div span br hr blockquote pre code ul ol li h1 h2 h3 h4 h5 h6 table thead tbody tfoot tr td th colgroup col img font sub sup section header footer main article center'.split(' '));+const attrs = new Set('class id href src alt title width height colspan rowspan align valign dir color bgcolor face size cellpadding cellspacing role'.split(' '));+const cleanCss = (value: string) => /expression|\\/i.test(value) ? '' : value.replace(/@import[^;]*;?/gi, '').replace(/url\s*\([^)]*\)/gi, 'none');+export type MailInlineImage = { cid: string; url: string };++/** Sanitize before creating our markers. Mail-provided editing attributes,+ * scripts, nested contexts and event handlers can never become editor controls. */+export function safeMailDocument(source: string, inline = false, images: MailInlineImage[] = []): string {+ const doc = parse(source, { sourceCodeLocationInfo: true });+ const runs = inline ? mailInlineRuns(source) : [];+ const byStart = new Map(runs.map((run, id) => [run.start, { ...run, id }]));+ const used = new Set<number>();+ const span = (id: number) => {+ used.add(id);+ const el = adapter.createElement('span', htmlNames.NS.HTML, [{ name: 'data-cindy-mail-run', value: String(id) }]);+ adapter.appendChild(el, adapter.createTextNode(runs[id].text));+ return el;+ };+ const visit = (parent: DefaultTreeAdapterTypes.ParentNode) => {+ const children: DefaultTreeAdapterTypes.ChildNode[] = [];+ for (const node of parent.childNodes) {+ if ('tagName' in node) {+ if (!tags.has(node.tagName) || node.namespaceURI !== htmlNames.NS.HTML) continue;+ node.attrs = node.attrs.filter(a => a.name === 'style' || (attrs.has(a.name) &&+ (a.name !== 'href' || /^(https?:|mailto:)/i.test(a.value)) &&+ (a.name !== 'src' || /^(https:\/\/|cid:|data:image\/(png|jpeg|gif|webp);base64,)/i.test(a.value))));+ for (const attr of node.attrs) if (attr.name === 'style') attr.value = cleanCss(attr.value);+ if (node.tagName === 'style') {+ node.childNodes = node.childNodes.filter(n => 'value' in n);+ for (const child of node.childNodes) if ('value' in child) child.value = cleanCss(child.value);+ } else visit(node);+ if (node.tagName === 'img') {+ const src = node.attrs.find(a => a.name === 'src');+ const cid = /^cid:(.*)$/.exec(src?.value || '')?.[1];+ if (cid) {+ node.attrs.push({ name: 'data-cindy-mail-cid', value: cid });+ const image = images.find(i => i.cid === cid);+ if (image && validMailImageUrl(image.url)) src!.value = image.url;+ }+ }+ } else if (!('value' in node)) continue;+ const run = byStart.get(node.sourceCodeLocation?.startOffset ?? -1);+ const isText = 'value' in node || ('tagName' in node && node.tagName === 'br');+ if (run && isText) children.push(span(run.id));+ else children.push(node);+ }+ parent.childNodes = children;+ for (const child of children) child.parentNode = parent;+ if ('tagName' in parent) {+ const at = parent.sourceCodeLocation?.startTag?.endOffset;+ const empty = at === undefined ? undefined : byStart.get(at);+ if (empty && empty.start === empty.end && !used.has(empty.id)) adapter.appendChild(parent, span(empty.id));+ }+ };+ visit(doc);+ // Image-only documents and fragments still need somewhere to place a caret.+ const root = doc.childNodes.find(n => 'tagName' in n && n.tagName === 'html') as DefaultTreeAdapterTypes.Element;+ const body = root.childNodes.find(n => 'tagName' in n && n.tagName === 'body') as DefaultTreeAdapterTypes.Element;+ runs.forEach((run, id) => { if (run.start === run.end && !used.has(id)) adapter.appendChild(body, span(id)); });+ return serialize(doc);+}++export const validMailImageUrl = (url: string) => /^cindy-media:\/\/blobs\/[a-f0-9]{64}\.(png|jpg|jpeg|gif|webp)$/.test(url) || /^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=]+$/i.test(url);+// Intrinsic mail paper, also used by reader chrome so it meets the document+// without the app theme's warm-white tint. Authored body colors still win.+export const MAIL_PAPER_COLOR = 'white';+export const MAIL_INLINE_STYLE = `html{color-scheme:light}body{margin:4px;background:${MAIL_PAPER_COLOR};color:#111;font:16px/1.6 Arial,Helvetica,sans-serif;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{max-width:100%}[data-cindy-mail-run]{white-space:pre-wrap;outline:none}[data-cindy-mail-run]:empty{display:inline-block;min-width:1ch;min-height:1em}`;+export function mailInlineDocument(source: string, images: MailInlineImage[] = []): string {+ return '<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'none\'; img-src https: data: cindy-media:; style-src \'unsafe-inline\'; form-action \'none\'; base-uri \'none\'"><meta name="viewport" content="width=device-width,initial-scale=1"><style>' + MAIL_INLINE_STYLE + '</style>' + safeMailDocument(source, true, images);+}++/** Executed only by the native WebView injection API. The document CSP allows+ * no page scripts. The sole bridge message contains a run index and plain text. */+export function mailInlineBindingScript(documentId: number): string {+ return `(function(){+ if(document.documentElement.dataset.cindyMailBound==='1')return;+ document.documentElement.dataset.cindyMailBound='1';+ var composing=false;+ function changed(event){+ if(composing||document.documentElement.dataset.cindyMailEditable!=='1')return;+ var el=event.target.closest('[data-cindy-mail-run]');if(!el)return;+ var text=el.innerText===undefined?el.textContent:el.innerText;+ if(text.length>16000)return;+ window.ReactNativeWebView.postMessage(JSON.stringify({type:'mail-text',documentId:${JSON.stringify(documentId)},id:el.getAttribute('data-cindy-mail-run'),text:text}));+ }+ document.addEventListener('compositionstart',function(){composing=true});+ document.addEventListener('compositionend',function(e){composing=false;changed(e)});+ document.addEventListener('input',changed);+ document.addEventListener('click',function(e){if(e.target.closest('a'))e.preventDefault()});+ document.addEventListener('drop',function(e){e.preventDefault()});+ document.addEventListener('paste',function(e){e.preventDefault();if(document.documentElement.dataset.cindyMailEditable==='1')document.execCommand('insertText',false,e.clipboardData.getData('text/plain'))});+ })();true;`;+}++export function mailInlineRefreshScript(enabled: boolean, images: MailInlineImage[]): string {+ const safeImages = images.filter(i => validMailImageUrl(i.url));+ return `(function(){+ document.documentElement.dataset.cindyMailEditable=${JSON.stringify(enabled ? '1' : '0')};+ document.querySelectorAll('[data-cindy-mail-run]').forEach(function(el){el.contentEditable=${JSON.stringify(enabled ? 'plaintext-only' : 'false')};el.spellcheck=true});+ var images=${JSON.stringify(safeImages)};+ document.querySelectorAll('img[data-cindy-mail-cid]').forEach(function(el){var image=images.find(function(i){return i.cid===el.getAttribute('data-cindy-mail-cid')});if(image)el.src=image.url});+ })();true;`;+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b0810cf61b..42d728a772 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1317,6 +1317,10 @@ importers:version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])packages/maker-shared:+ dependencies:+ parse5:+ specifier: 8.0.1+ version: 8.0.1devDependencies:'@eslint/js':specifier: ^9.0.0