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): 修复草稿恢复、引用同步与阅读边界

Dash53abb9ffc70b
diff --git a/apps/desktop/scripts/mailComposeRuntime.test.mjs b/apps/desktop/scripts/mailComposeRuntime.test.mjs
index 9560e3cb5d..c62d38d256 100644
--- a/apps/desktop/scripts/mailComposeRuntime.test.mjs
+++ b/apps/desktop/scripts/mailComposeRuntime.test.mjs
@@ -294,6 +294,29 @@ test('a draft read in another task still presents its own card', async () => {
assert.equal(f.cards.at(-1).callId, 'agent-call');
});
+// The plain quote editor and HTML MIME alternative must describe the same reply.
+for (const quote of ['Updated <quote>\nSecond line', '']) test('editing the plain quote updates or clears its HTML alternative: ' + JSON.stringify(quote), async () => {
+ const f = fixture({ richText: true });
+ f.externalEdit({ quote: 'Original quote', quoteHtml: '<blockquote><b>Original quote</b></blockquote>' });
+ await f.present();
+ const values = f.values();
+ await f.card('change', { ...values, quote: 'Intermediate' });
+ await f.card('change', { ...values, quote });
+ assert.ok((await f.tool('send')).ok);
+ const sent = f.writes.find(x => x.send).fields;
+ assert.equal(sent.quote, quote);
+ assert.equal(sent.quoteHtml, quote ? '<div>Updated &lt;quote&gt;<br>Second line</div>' : '');
+});
+test('editing other fields preserves authored HTML quotes byte for byte', async () => {
+ const f = fixture({ richText: true });
+ const quoteHtml = '<blockquote style="color:red"><b>Original quote</b></blockquote>';
+ f.externalEdit({ quote: 'Original quote', quoteHtml });
+ await f.present();
+ await f.card('change', { ...f.values(), subject: 'New subject' });
+ assert.ok((await f.tool('send')).ok);
+ assert.equal(f.writes.find(x => x.send).fields.quoteHtml, quoteHtml);
+});
+
// Regression: the real sent reply nested a full HTML document inside its quote.
// Existing adapter tests covered edits, not outgoing HTML structure or CID integrity.
// Unit tier: production present/send entries, fake providers, no network or real sends.
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
index 1ffe05dcfd..9671545fe6 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
import { GhostCardActionDispatcher } from '../cardActionDispatch.js';
import { GhostPreviewGate } from '../previewGate.js';
+import { prepareMailAttachmentUpload } from '../mailAttachmentUpload.js';
import { ghostInstallApprovalToken, ghostWebviewEntryPaths, type InstalledGhost } from '../../../shared/ghost.js';
import { findInstalledGhostByInstanceId, installedGhostLogicalIdentity, installedGhostPhysicalKeys, installedGhostStoragePart,
parsePluginStoragePart, pluginStoragePart, resolveInstalledGhost } from '../../../shared/pluginIdentity.js';
@@ -53,7 +54,7 @@ function harness() {
sendToGhostLogic: send, getGhostAgentSlot: () => ({ issueUserActionToken: () => null, clearGhost: vi.fn() }),
getGhostSessionActivityTracker: () => ({ begin: vi.fn() }), ghostOwnerScope: undefined,
ghostInstallApprovalToken, log: { info: vi.fn(), warn: vi.fn() },
- getGhostPreviewGate: () => preview,
+ getGhostPreviewGate: () => preview, prepareMailAttachmentUpload,
});
return { ...api, root, organization, ghosts, send, setEnabled, stop, ghostCanRead, setStoredId: (id: string) => { storedId = id; } };
}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
index ef8b721eba..afe1b8d95f 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
+++ b/apps/desktop/src/main/cindy-brain/runtime/mailComposeRuntime.js
@@ -900,6 +900,13 @@ var cindyMail = (function () {
const incoming = { ...edit.fields, ...message.formValues };
const base = edit.error?.stale ? edit.conflictBase : edit.inputFields || edit.fields;
const merged = mergeFields(base, incoming, edit.error?.stale ? draftValues(edit.readBack) : edit.fields);
+ // The quote text field edits the outgoing quote too. Preserve authored
+ // HTML unless that text changed, including an explicit deletion.
+ if (adapter.richText && incoming.quote !== base?.quote && incoming.quoteHtml === base?.quoteHtml) {
+ merged.fields.quoteHtml = merged.fields.quote
+ ? '<div>' + merged.fields.quote.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r\n?|\n/g, '<br>') + '</div>'
+ : '';
+ }
edit.conflictBase = merged.conflicts.length ? base : undefined;
edit.fields = merged.fields;
edit.inputFields = incoming;
diff --git a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
index 0cca8f9cbc..61672fca8e 100644
--- a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
@@ -2,7 +2,7 @@ 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 { readGhostCardForm, readMailCard, mailCardStatus, mailSendRemainingFraction, isLegacyMailCard, readGhostCardFormChange, mergeGhostCardFormValues, trackGhostCardFormDelivery, releaseGhostCardFormDelivery, pendingGhostCardFormDelivery } from '@cindy/maker-shared/ghost-card-form';
import { openMailCard } from '@/features/right-sidebar/lib/mailPreview';
import sliderCss from '@/components/ui/slider.css?inline';
/**
@@ -239,6 +239,10 @@ function GhostCardCanvas({
}, [mail]);
const changeAction = readGhostCardFormChange(html);
const formKey = changeAction ?? JSON.stringify(formFields);
+ const formRetired = !!mail?.supersededBy || ['sent', 'deleted'].includes(mail?.state ?? '');
+ useEffect(() => () => {
+ if (sessionId) releaseGhostCardFormDelivery(sessionId, `${callId}:${editorId}`);
+ }, [sessionId, callId, editorId, formKey, formRetired]);
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);
diff --git a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
index 3cae170a9c..7be74e42ff 100644
--- a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
+++ b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
@@ -120,7 +120,7 @@ export function MailHtmlPreview(props: PreviewProps) {
<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>
+ <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>
</div>
<div className="min-h-0 flex-1"><PreviewFrame {...props} enlarged /></div>
</Dialog.Content>
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx
index 161988af5d..f4ed79ba30 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx
@@ -5,12 +5,36 @@ 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';
+import { pendingGhostCardFormDelivery } 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: an old useId must not block chat after the failed editor is gone.
+it('releases a failed view on unmount and allows the remounted editor to sync', async () => {
+ vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ const dispatch = vi.fn().mockResolvedValueOnce({ ok: false }).mockResolvedValue({ ok: true });
+ vi.stubGlobal('electronAPI', { ghosts: { dispatchCardAction: dispatch } });
+ const mail: MailCardData = { accountId: 'account', draftId: 'draft', key: '20000000-0000-0000-0000-000000000000',
+ from: 'sender', fields: ['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: '', multiline: name === 'body' })),
+ attachments: [], state: 'draft', status: 'Synced', sendLabel: 'Send', fromLabel: 'From' };
+ const props = { callId: 'failed-view', sessionId: 'reopened-session', height: 80, html: renderMailCard(mail) };
+ const first = render(<MailCardEditor {...props} />);
+ fireEvent.change(screen.getByLabelText('body'), { target: { value: 'First edit' } });
+ await act(async () => {});
+ expect(await pendingGhostCardFormDelivery(props.sessionId)).toBe(false);
+ first.unmount();
+ await act(async () => {});
+ expect(pendingGhostCardFormDelivery(props.sessionId)).toBeUndefined();
+ render(<MailCardEditor {...props} />);
+ fireEvent.change(screen.getByLabelText('body'), { target: { value: 'New edit' } });
+ await act(async () => {});
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ expect(pendingGhostCardFormDelivery(props.sessionId)).toBeUndefined();
+});
+
// 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 () => {
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
index b04bcc349c..2916e3843f 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
@@ -186,7 +186,7 @@ it('enlarges the read-only preview and reflects later AI updates without changin
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' }));
+ fireEvent.click(screen.getByRole('button', { name: 'chat.lightbox.close' }));
expect(screen.queryByRole('dialog')).toBeNull();
expect(change).not.toHaveBeenCalled();
});
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.tsx
index 47575b4495..fa704d97e9 100644
--- 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.tsx
@@ -18,6 +18,16 @@ 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: [] });
+it.each(['inactive', 'hidden'])('does not mark a restored %s tab read until it is visible', async kind => {
+ h.read.mockResolvedValue({ message: mail('Selected') });
+ const view = render(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} active={kind !== 'inactive'} shellVisible={kind !== 'hidden'} />);
+ await act(async () => {});
+ expect(h.read).not.toHaveBeenCalled();
+ view.rerender(<MailPreviewBody state={{ url: 'https://mail.example/a' }} ctx={ctx} active shellVisible />);
+ await act(async () => {});
+ expect(h.read).toHaveBeenCalledExactlyOnceWith('a', 'https://mail.example/a', true, null, true);
+ expect(screen.getByText('Selected')).toBeTruthy();
+});
afterEach(() => { cleanup(); vi.clearAllMocks(); vi.unstubAllGlobals(); h.owner = 1; });
// New sidebar entry: follow host edits/supersession, but never reuse another task's card.
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.tsx
index a2e94b6281..1763f407a7 100644
--- 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.tsx
@@ -12,26 +12,27 @@ import { MailCardBody } from './MailCardBody';
import { MailConversationView } from './MailConversationView';
type State = { url: string; callId?: string };
-export function MailPreviewBody({ state, ctx }: TabKindBodyProps<State>) {
+export function MailPreviewBody({ state, ctx, active: tabActive = true, shellVisible = true }: 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]);
+ const visible = tabActive && shellVisible;
useEffect(() => {
let active = true;
- if (ctx.deviceLinkDeviceId === undefined) return;
+ if (!visible || 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]);
+ }, [binding, visible]);
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);
+ const response = await readMailPreview(ctx.sessionId, url || state.url, true, ctx.deviceLinkDeviceId, opened && visible);
return isDataOwnerGenerationCurrent(owner) ? response : { message: null };
- }, [owner, ctx.sessionId, ctx.deviceLinkDeviceId, state.url]);
+ }, [owner, ctx.sessionId, ctx.deviceLinkDeviceId, state.url, visible]);
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">
diff --git a/apps/desktop/src/shared/__tests__/mailMessage.test.ts b/apps/desktop/src/shared/__tests__/mailMessage.test.ts
index bc45850f76..ac1ca7230f 100644
--- a/apps/desktop/src/shared/__tests__/mailMessage.test.ts
+++ b/apps/desktop/src/shared/__tests__/mailMessage.test.ts
@@ -1,12 +1,25 @@
import { expect, it } from 'vitest';
import { parseMailMessage, parseMailReader, mailMessageFields } from '@cindy/maker-shared/mail-message';
import { validateGhostManifest } from '../ghost';
+import { validateGhostManifest as validateProtocolManifest } from '@cindy/plugin-protocol';
+it.each([null, false, [], { tool: 'read_mail', hosts: 'mail.example.com' }, { tool: 'read_mail', hosts: ['*.com'] }, { hosts: ['mail.example.com'] }])('rejects a malformed known mailReader declaration: %j', mailReader => {
+ for (const validate of [validateGhostManifest, validateProtocolManifest]) {
+ const result = validate({ schemaVersion: 3, minCindyVersion: '0.1.92', id: 'example-mail', name: 'Mail', version: '1.0.0', entry: 'main.js', mailReader });
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.reason).toContain('mailReader');
+ }
+});
it('preserves a declared reader through manifest normalization', () => {
- const reader = { tool: 'read_mail', hosts: ['mail.example.com'], markRead: true };
+ const reader = { tool: 'read_mail', hosts: ['mail.example.com'], markRead: true, future: { mode: 'extension' } };
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);
+ if (result.ok) {
+ const protocol = validateProtocolManifest(result.manifest);
+ expect(protocol.ok).toBe(true);
+ if (protocol.ok) expect(protocol.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', () => {
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 1cb5b57bc6..f4e890506d 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -3000,6 +3000,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([
'slots',
'card',
'mail',
+ 'mailReader',
'tools',
'cindy',
'model',
@@ -3828,6 +3829,10 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
if (!preparation.ok) return preparation;
const prepared = preparation.prepared;
const raw = prepared.raw;
+ const mailReader = raw.mailReader === undefined ? undefined : parseMailReader(raw.mailReader);
+ if (raw.mailReader !== undefined && !mailReader) {
+ return { ok: false, reason: 'mailReader 必须声明合法的 tool 与 hosts' };
+ }
if (!isValidGhostId(raw.id)) {
return { ok: false, reason: 'id 必须是 1–32 位小写字母/数字/连字符(不能以连字符开头)' };
}
@@ -6030,7 +6035,7 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
...(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)! } : {}),
+ ...(mailReader ? { mailReader: { ...(raw.mailReader as Record<string, unknown>), ...mailReader } } : {}),
...(card !== undefined || prepared.v3BaseCard || slots.includes('card')
? { card: card ?? {} }
: {}),
diff --git a/apps/mobile/src/__tests__/mobileMailAttachment.test.ts b/apps/mobile/src/__tests__/mobileMailAttachment.test.ts
index d57ad53803..3f60f60c05 100644
--- a/apps/mobile/src/__tests__/mobileMailAttachment.test.ts
+++ b/apps/mobile/src/__tests__/mobileMailAttachment.test.ts
@@ -15,7 +15,17 @@ beforeEach(() => {
h.remove.mockResolvedValue(undefined);
h.upload.mockResolvedValue({ path: 'uploaded-reference' });
});
-const options = (isActive = () => true) => ({ deviceId: 'host', getAccessToken: async () => 'token', signal: new AbortController().signal, isActive });
+const options = (isActive = () => true) => ({ deviceId: 'host', getAccessToken: async () => 'token', signal: new AbortController().signal, isActive, deliver: vi.fn(async () => true) });
+it.each(['rejected', 'thrown'])('discards an upload when card delivery is %s', async failure => {
+ const input = options();
+ input.deliver.mockImplementation(async () => { if (failure === 'thrown') throw new Error('disconnected'); return false; });
+ if (failure === 'thrown') await expect(pickMobileMailAttachment(input)).rejects.toThrow('disconnected');
+ else expect(await pickMobileMailAttachment(input)).toBeNull();
+ expect(h.discard).toHaveBeenCalledWith({ path: 'uploaded-reference' }, expect.any(Object));
+ const cleanup = h.discard.mock.calls[0][1];
+ expect(await cleanup.getToken()).toBe('token');
+ expect(h.remove).toHaveBeenCalledOnce();
+});
it('picker cancel performs no upload or file deletion', async () => {
h.pick.mockResolvedValue({ canceled: true });
expect(await pickMobileMailAttachment(options())).toBeNull();
diff --git a/apps/mobile/src/__tests__/pluginCardActions.test.tsx b/apps/mobile/src/__tests__/pluginCardActions.test.tsx
index 24bfbf3e57..d6c7aef22f 100644
--- a/apps/mobile/src/__tests__/pluginCardActions.test.tsx
+++ b/apps/mobile/src/__tests__/pluginCardActions.test.tsx
@@ -210,7 +210,10 @@ describe("native plugin card deliberate actions", () => {
await act(async () => button().click());
expect(dispatch).not.toHaveBeenCalled();
const upload = { url: 'xdt-attach-oss://test-reference', name: 'plan.pdf' };
- h.pick.mockResolvedValueOnce(upload);
+ h.pick.mockImplementationOnce(async ({ deliver }: { deliver(file: typeof upload): Promise<boolean> }) => {
+ await deliver(upload);
+ return 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}`,
diff --git a/apps/mobile/src/plugins/PluginCardActions.tsx b/apps/mobile/src/plugins/PluginCardActions.tsx
index 64cffafcdb..905a4dbe1a 100644
--- a/apps/mobile/src/plugins/PluginCardActions.tsx
+++ b/apps/mobile/src/plugins/PluginCardActions.tsx
@@ -7,6 +7,7 @@ import {
type MailCardData,
mergeGhostCardFormValues,
trackGhostCardFormDelivery,
+ releaseGhostCardFormDelivery,
GHOST_CARD_FORM_MAX_VALUE,
visibleMailAttachments,
removeMailAttachment,
@@ -193,6 +194,9 @@ function CardControls({
const [prompt, setPrompt] = useState<Action>();
const [draft, setDraft] = useState("");
const formKey = changeAction ?? JSON.stringify(form);
+ const formRetired = history || ['sent', 'deleted'].includes(mail?.state ?? '');
+ useEffect(() => () => releaseGhostCardFormDelivery(JSON.stringify([deviceId, sessionId]), callId),
+ [deviceId, sessionId, callId, formKey, formRetired]);
const changeQueue = useRef(Promise.resolve(true));
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
const incoming = Object.fromEntries(
@@ -469,8 +473,8 @@ function CardControls({
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);
+ await pickMobileMailAttachment({ deviceId, getAccessToken, signal: controller.signal, isActive,
+ deliver: file => isActive() ? submit({ id: `mail:attach:${mail.key}`, label: '', disabled: false, submit: true }, undefined, undefined, file) : Promise.resolve(false) });
} catch (error) {
if (isActive()) setUploadError(error instanceof Error && error.message === t('plugins.mailAttachTooLarge') ? error.message : t('plugins.mailAttachFailed'));
} finally {
diff --git a/apps/mobile/src/plugins/mobileMailAttachment.ts b/apps/mobile/src/plugins/mobileMailAttachment.ts
index 1ba874f1e1..39095961b9 100644
--- a/apps/mobile/src/plugins/mobileMailAttachment.ts
+++ b/apps/mobile/src/plugins/mobileMailAttachment.ts
@@ -4,6 +4,7 @@ import { uploadMobileAttachmentFromFile, discardMobileUploadedAttachment } from
/** 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;
+ deliver(file: { url: string; name: string }): Promise<boolean>;
}) {
const picker = await import('expo-document-picker');
const selected = await picker.getDocumentAsync({ multiple: false, copyToCacheDirectory: true });
@@ -20,10 +21,14 @@ export async function pickMobileMailAttachment(options: {
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;
+ let delivered = false;
+ try {
+ if (!options.isActive()) return null;
+ const attachment = { url: uploaded.url || uploaded.path, name: file.name };
+ delivered = await options.deliver(attachment);
+ return delivered ? attachment : null;
+ } finally {
+ if (!delivered) discardMobileUploadedAttachment(uploaded, { getToken: () => Promise.resolve(token) });
}
- return { url: uploaded.url || uploaded.path, name: file.name };
} finally { await fs.deleteAsync(file.uri, { idempotent: true }).catch(() => undefined); }
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 07b2b88d93..38cc89c1a8 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2436,12 +2436,15 @@ blocked; preview sanitization never mutates the saved HTML.
### Read-only mail preview
Mail providers may declare `mailReader: { tool, hosts }` alongside `mail: true`.
+Desktop and plugin-protocol validate this known declaration and retain future
+extension data; malformed declarations cannot survive as unknown top-level fields.
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
+passes it; AI reads, probes and neighboring preloads remain read-only. Restored
+inactive tabs and a hidden sidebar must not mark mail read merely by mounting.
+Mark only the successfully resolved, visibly opened message, never the whole thread or drafts. A failed
mark must retain the body and return `markReadFailed:true` for a non-blocking notice.
It returns `MailMessage` (maker-shared/mail-message).
Credentials and MIME parsing remain with the provider. Cindy validates the data
diff --git a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
index b0fec2457c..d4b80d6277 100644
--- a/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
+++ b/packages/maker-shared/src/__tests__/ghostCardForm.test.ts
@@ -6,6 +6,7 @@ import {
readGhostCardForm,
omitGhostCardFormPreview,
trackGhostCardFormDelivery,
+ releaseGhostCardFormDelivery,
pendingGhostCardFormDelivery,
ghostCardRecipients,
fitGhostCardRecipients,
@@ -17,6 +18,31 @@ import {
} from "../ghostCardForm";
describe("declarative card forms", () => {
+ // 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;
+ trackGhostCardFormDelivery('retiring', 'old', new Promise(resolve => { finish = resolve; }));
+ releaseGhostCardFormDelivery('retiring', 'old');
+ expect(pendingGhostCardFormDelivery('retiring')).toBeDefined();
+ finish(false);
+ await Promise.resolve(); await Promise.resolve();
+ expect(pendingGhostCardFormDelivery('retiring')).toBeUndefined();
+ trackGhostCardFormDelivery('retiring', 'new', Promise.resolve(false));
+ await Promise.resolve();
+ releaseGhostCardFormDelivery('retiring', 'new');
+ trackGhostCardFormDelivery('retiring', 'new', Promise.resolve(false));
+ await Promise.resolve();
+ expect(await pendingGhostCardFormDelivery('retiring')).toBe(false);
+ releaseGhostCardFormDelivery('retiring', 'new');
+ await Promise.resolve();
+ expect(pendingGhostCardFormDelivery('retiring')).toBeUndefined();
+ });
+ it('keeps preheaders hidden and out of editable text without changing outgoing HTML', () => {
+ const source = '<div hidden>Private preheader</div><p>Hello</p>';
+ expect(safeMailDocument(source, true)).toContain('<div hidden="">Private preheader</div>');
+ expect(mailInlineRuns(source).map(r => r.text)).toEqual(['Hello']);
+ expect(applyMailInlineEdits(source, { 0: 'Hi' })!.html).toBe('<div hidden>Private preheader</div><p>Hi</p>');
+ });
// 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', () => {
diff --git a/packages/maker-shared/src/ghostCardForm.ts b/packages/maker-shared/src/ghostCardForm.ts
index 04d044a6b7..a6d57dc8e6 100644
--- a/packages/maker-shared/src/ghostCardForm.ts
+++ b/packages/maker-shared/src/ghostCardForm.ts
@@ -196,7 +196,17 @@ export function trackGhostCardFormDelivery(
entries.set(key, settled);
void settled.then((ok) => {
if (ok && entries!.get(key) === settled) entries!.delete(key);
- if (!entries!.size) deliveries.delete(scope);
+ if (!entries!.size && deliveries.get(scope) === entries) deliveries.delete(scope);
+ });
+}
+/** Retire an editor's failed barrier without letting chat overtake an in-flight edit. */
+export function releaseGhostCardFormDelivery(scope: string, key: string): void {
+ const entries = deliveries.get(scope);
+ const delivery = entries?.get(key);
+ if (!delivery) return;
+ void delivery.then(() => {
+ if (entries!.get(key) === delivery) entries!.delete(key);
+ if (!entries!.size && deliveries.get(scope) === entries) deliveries.delete(scope);
});
}
export function pendingGhostCardFormDelivery(
diff --git a/packages/maker-shared/src/mailTextEdit.ts b/packages/maker-shared/src/mailTextEdit.ts
index 7684f45ff0..d55d4fe153 100644
--- a/packages/maker-shared/src/mailTextEdit.ts
+++ b/packages/maker-shared/src/mailTextEdit.ts
@@ -64,7 +64,7 @@ export function applyMailInlineEdits(source: string, edits: Record<string, strin
}
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 attrs = new Set('class id href src alt title width height colspan rowspan align valign dir color bgcolor face size cellpadding cellspacing role hidden aria-hidden'.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 };
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 953264669e..7023265798 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -856,6 +856,8 @@ export const GHOST_SETUP_KV_KEY_RE = /^[A-Za-z0-9_.-]{1,64}$/;
/** 已校验的 ghost.json 协议文档;Desktop 会再投影成无 slots 的运行时模型。 */
export interface GhostManifest {
+ /** Provider-owned read capability; Cindy owns mail presentation. */
+ mailReader?: { tool: string; hosts: string[]; markRead?: true };
/** Optional v3 extension; consumers validate it without changing legacy approval content. */
recommendations?: unknown;
/** v2 仅作存量兼容;新插件使用 v3。 */
@@ -1172,6 +1174,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([
'settingsHeight',
'slots',
'card',
+ 'mailReader',
'tools',
'cindy',
'model',
@@ -1335,6 +1338,14 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (!preparation.ok) return preparation;
const prepared = preparation.prepared;
const raw = prepared.raw;
+ // Keep this shape aligned with maker-shared's runtime reader parser.
+ const reader = raw.mailReader as Record<string, unknown> | undefined;
+ if (raw.mailReader !== undefined && (!reader || typeof reader !== 'object' ||
+ typeof reader.tool !== 'string' || !/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(reader.tool) ||
+ !Array.isArray(reader.hosts) || !reader.hosts.length || reader.hosts.length > 16 ||
+ !reader.hosts.every(h => typeof h === 'string' && h.length <= 253 && /^[a-z0-9]+(?:[.-][a-z0-9]+)*\.[a-z]{2,}$/.test(h)))) {
+ return { ok: false, reason: 'mailReader 必须声明合法的 tool 与 hosts' };
+ }
if (!isValidGhostId(raw.id)) {
return {
ok: false,
@@ -3753,6 +3764,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
? { card: card ?? {} }
: {}),
...(tools !== undefined ? { tools } : {}),
+ ...(reader ? { mailReader: { ...reader, tool: reader.tool as string, hosts: [...new Set(reader.hosts as string[])] } } : {}),
...(cindy !== undefined ? { cindy } : {}),
...(subscribe !== undefined ? { subscribe } : {}),
...(routineEvents !== undefined ? { routineEvents } : {}),