Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(mail): 收紧预览边界并恢复过期倒计时操作

Dashb18de54f72d3
diff --git a/apps/desktop/scripts/mailComposeRuntime.test.mjs b/apps/desktop/scripts/mailComposeRuntime.test.mjs
index c62d38d256..d2df277082 100644
--- a/apps/desktop/scripts/mailComposeRuntime.test.mjs
+++ b/apps/desktop/scripts/mailComposeRuntime.test.mjs
@@ -102,7 +102,13 @@ function fixture({
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 };
+ if (!stored || !allowCardRead) return { ok: false };
+ const draft = copy(stored.draft);
+ // Host persists status-only patches as part of the same card.
+ for (const update of cards.slice(cards.indexOf(stored) + 1)) {
+ if (update.callId === card.callId && update.statusOnly) Object.assign(draft, copy(update.statusOnly));
+ }
+ return { ok: true, draft };
}
cards.push(copy(card));
return { ok: acceptCard || !card.statusOnly?.pendingSend };
@@ -682,6 +688,10 @@ test('unknown writes allow inspecting the mailbox without unlocking or repeating
const f = fixture({ write: async () => { throw new Error('lost response'); } });
await f.present();
assert.equal((await f.tool('send')).execution, 'unknown');
+ const unknownCardCount = f.cards.length;
+ await f.card('cancel', undefined, { formValues: undefined });
+ await f.card('now', undefined, { formValues: undefined });
+ assert.equal(f.cards.length, unknownCardCount);
f.restart();
assert.equal((await f.tool('get')).ok, true);
assert.equal(f.cards.at(-1).draft.state, 'unconfirmed');
@@ -726,6 +736,11 @@ test("expiry sends exactly once and restart never resumes a waiting send", async
await f.advance(1);
assert.equal((await pending).data.sent, true);
assert.equal(f.writes.length, 1);
+ const sentCardCount = f.cards.length;
+ await f.card('cancel', undefined, { formValues: undefined });
+ await f.card('now', undefined, { formValues: undefined });
+ assert.equal(f.cards.length, sentCardCount);
+ assert.equal(f.writes.length, 1);
const restarted = fixture({ autoSend: false });
await restarted.present();
@@ -741,6 +756,25 @@ test("expiry sends exactly once and restart never resumes a waiting send", async
assert.equal((await freshSend).execution, 'not_executed');
assert.equal(restarted.writes.length, 0);
});
+for (const action of ['cancel', 'now']) test(`stale countdown ${action} restores the draft after restart without sending`, async () => {
+ const f = fixture({ autoSend: false });
+ await f.present();
+ void f.tool('send');
+ await f.waitCountdown();
+ assert.equal(f.cards.at(-1).statusOnly.state, 'sending');
+ f.restart();
+ await f.card(action, undefined, { formValues: undefined });
+ assert.equal(f.reads.length, 1);
+ assert.equal(f.cards.at(-1).draft.state, 'draft');
+ assert.equal(f.cards.at(-1).draft.pendingSend, undefined);
+ await f.advance(10000);
+ assert.equal(f.writes.length, 0);
+ const fresh = f.tool('send');
+ await f.waitCountdown();
+ await f.card('cancel', undefined, { formValues: undefined });
+ assert.equal((await fresh).execution, 'not_executed');
+ assert.equal(f.writes.length, 0);
+});
test("a rejected countdown card or a draft without a presented card cannot send", async () => {
const f = fixture({ acceptCard: false });
assert.equal((await f.tool("send")).execution, "not_executed");
diff --git a/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
index afe1b8d95f..2195a74d60 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
+++ b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
@@ -866,7 +866,7 @@ var cindyMail = (function () {
return;
var key = match[2];
var edit = mailEdits.get(key);
- if (!edit && ['change', 'send', 'attach', 'image'].includes(match[1])) {
+ if (!edit && ['change', 'send', 'attach', 'image', 'cancel', 'now'].includes(match[1])) {
await restoreMailDraft(key, message.callId);
edit = mailEdits.get(key);
}
@@ -946,18 +946,19 @@ var cindyMail = (function () {
(record.state === "sent" || edit.sent || edit.sending)
)
return;
- if (match[1] === "cancel") {
- if (cancelMailSend(key)) {
+ if (match[1] === "cancel" || match[1] === "now") {
+ if (record.state !== "draft" || edit.sent || edit.sending) return;
+ if (match[1] === "now" && edit.pendingSend) {
+ await edit.pendingSend.finish();
+ } else if (cancelMailSend(key) || !edit.pendingSend) {
+ // After restart the persisted countdown has no live send behind it.
+ // Restore a draft; a new send request must start a fresh grace period.
const selected = await adapter.selectAccount(record.account);
if (selected.ok) await showMailDraft({ callId: record.callId },
selected, edit.readBack, undefined, key, edit.fields, true);
}
return;
}
- if (match[1] === "now") {
- await edit.pendingSend?.finish();
- return;
- }
clearTimeout(edit.timer);
if (["change", "attach", "image"].includes(match[1])) {
if (!edit.timer) {
diff --git a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
index 7be74e42ff..0cb3319a2f 100644
--- a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
+++ b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
@@ -116,8 +116,8 @@ export function MailHtmlPreview(props: PreviewProps) {
<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">
+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-50" />
+ <Dialog.Content aria-describedby={undefined} onPointerDownOutside={event => event.preventDefault()} className="modal-panel 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 p-4">
<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('chat.lightbox.close')} className="rounded p-1 text-muted-foreground hover:bg-[var(--surface-hover)]"><X className="h-4 w-4" /></Dialog.Close>
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 38cc89c1a8..389829699c 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -44,7 +44,8 @@ card-update 可选 sourceCallId:只接受当前在途、同插件同任务的
公共邮件发送沿用 sending 状态,可选 pendingSend(deadline、label、cancelLabel、sendNowLabel)。
Host 仅在此等待阶段接受 mail:cancel / mail:now;动作不提交表单,草稿编辑锁定。
两端只显示倒计时,真正的 10 秒等待和发送由公共邮件 SDK 执行;同草稿重复请求共用一次等待。
-撤销、重新读取或修改草稿取消等待,重启不会恢复自动发送。旧端忽略 pendingSend,仍按 sending
+撤销、重新读取或修改草稿取消等待,重启不会恢复自动发送。重启后点击旧倒计时的撤销或立即发送,
+SDK 重新读取并恢复草稿;再次发送必须重新经过完整倒计时。旧端忽略 pendingSend,仍按 sending
锁定编辑;旧手机可能无法操作新增按钮,完整撤销交互需升级查看端。没有新 channel 或原生配置。
## MCP Apps
@@ -2357,6 +2358,9 @@ kinds, with `bodyHtml` / `quoteHtml` (64k characters) and `attachmentItems` (bou
JSON metadata). Ordinary text remains 16k. Only Host mail gets the 1 MiB card
budget; arbitrary plugin HTML remains limited to 32 KiB. HTML previews are inert,
sandboxed documents, not markup mounted in Cindy's privileged renderer DOM.
+Both clients block remote image sources and CSS fetches in mail previews; CSP
+permits only data and managed CID substitutions. Original outgoing HTML remains
+unchanged by this preview policy; remote images can be viewed in the mailbox.
HTML supports typing directly into rendered text in both clients and the enlarged
view, without an edit-mode button, formatting toolbar or source editor. Edits patch source text
only, preserving styles, links and CID image references, and synchronize the
diff --git a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
index d4b80d6277..ac99bdbc7f 100644
--- a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
+++ b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
-import { applyMailInlineEdits, mailInlineRuns, mailTextParagraphs, safeMailDocument } from '../mailTextEdit';
+import { parse, type DefaultTreeAdapterTypes } from 'parse5';
+import { applyMailInlineEdits, mailInlineDocument, mailInlineRuns, mailTextParagraphs, safeMailDocument } from '../mailTextEdit';
import {
parseGhostCardForm,
parseGhostCardFormValues,
@@ -18,6 +19,34 @@ import {
} from "../ghostCardForm";
describe("declarative card forms", () => {
+ const elements = (node: DefaultTreeAdapterTypes.Node): DefaultTreeAdapterTypes.Element[] => [
+ ...('tagName' in node ? [node] : []),
+ ...('childNodes' in node ? node.childNodes.flatMap(elements) : []),
+ ];
+ // Both clients use this preview document. Rendering untrusted mail must not
+ // contact a sender's tracking endpoint, nor rewrite the outgoing source.
+ it('blocks remote images and CSS fetches while retaining managed inline images', () => {
+ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ const source = '<p>Hello</p><img src="https://tracker.example.test/open" srcset="https://tracker.example.test/retina 2x"><img src="cid:photo"><img src="data:image/png;base64,YQ=="><div style="background:url(https://tracker.example.test/bg)">Footer</div>';
+ const nodes = elements(parse(mailInlineDocument(source, [{ cid: 'photo', url }])));
+ const images = nodes.filter(n => n.tagName === 'img');
+ expect(images.map(n => n.attrs.find(a => a.name === 'src')?.value)).toEqual([undefined, url, 'data:image/png;base64,YQ==']);
+ expect(images.some(n => n.attrs.some(a => a.name === 'srcset'))).toBe(false);
+ expect(nodes.find(n => n.tagName === 'div')?.attrs.find(a => a.name === 'style')?.value).toBe('background:none');
+ const csp = nodes.find(n => n.tagName === 'meta' && n.attrs.some(a => a.name === 'http-equiv' && a.value === 'Content-Security-Policy'))!;
+ expect(csp.attrs.find(a => a.name === 'content')?.value.split(';').map(s => s.trim())).toContain('img-src data: cindy-media:');
+ expect(applyMailInlineEdits(source, {})!.html).toBe(source);
+ });
+ it('omits legacy form nodes without joining malformed markup into executable tags', () => {
+ const form = '<div data-ghost-form="[{&quot;name&quot;:&quot;body&quot;,&quot;label&quot;:&quot;Body&quot;,&quot;value&quot;:&quot;text&quot;}]"><div>Preview</div></div>';
+ for (const split of ['<scr<style></style>ipt>alert(1)</script>', '<scr<script></script>ipt>alert(1)</script>']) {
+ const result = omitGhostCardFormPreview(split + form + '<p>Sender</p>');
+ const nodes = elements(parse(result));
+ expect(nodes.some(n => ['script', 'style'].includes(n.tagName))).toBe(false);
+ expect(nodes.some(n => n.attrs.some(a => a.name === 'data-ghost-form'))).toBe(false);
+ expect(result).toContain('<p>Sender</p>');
+ }
+ });
// A failed view must not poison a task after remount; live edits still gate chat.
it('retires a failed editor while preserving in-flight and replacement deliveries', async () => {
let finish!: (ok: boolean) => void;
diff --git a/packages/maker-shared/src/ghostCardForm.ts b/packages/maker-shared/src/ghostCardForm.ts
index a6d57dc8e6..95a7a01325 100644
--- a/packages/maker-shared/src/ghostCardForm.ts
+++ b/packages/maker-shared/src/ghostCardForm.ts
@@ -1,4 +1,4 @@
-import { parse, type DefaultTreeAdapterTypes } from 'parse5';
+import { parse, parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5';
/** Declarative, non-secret text fields. Plugins never supply executable controls. */
export interface GhostCardFormField {
@@ -405,20 +405,21 @@ export function readGhostCardForm(html: string): GhostCardFormField[] | null {
/** 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;
+ // Remove nodes, never source substrings: deletion must not join malformed
+ // markup into a new executable tag. Serialization escapes remaining text.
+ const doc = parseFragment(html);
+ let removed = false;
+ const visit = (parent: DefaultTreeAdapterTypes.ParentNode) => {
+ parent.childNodes = parent.childNodes.filter(node => {
+ if ('tagName' in node) {
+ const form = node.tagName === 'div' && node.attrs.find(a => a.name === 'data-ghost-form');
+ if (form && parseGhostCardForm(form.value)) { removed = true; return false; }
+ if (node.tagName === 'style' || node.tagName === 'script') return false;
+ }
+ if ('childNodes' in node) visit(node);
+ return true;
+ });
+ };
+ visit(doc);
+ return removed ? serialize(doc) : html;
}
diff --git a/packages/maker-shared/src/mailTextEdit.ts b/packages/maker-shared/src/mailTextEdit.ts
index d55d4fe153..5865132b26 100644
--- a/packages/maker-shared/src/mailTextEdit.ts
+++ b/packages/maker-shared/src/mailTextEdit.ts
@@ -88,7 +88,7 @@ export function safeMailDocument(source: string, inline = false, images: MailInl
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))));
+ (a.name !== 'src' || /^(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);
@@ -131,7 +131,7 @@ export const validMailImageUrl = (url: string) => /^cindy-media:\/\/blobs\/[a-f0
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);
+ return '<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'none\'; img-src 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