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): 保持草稿同步和发送过程中的卡片稳定

Dash8e374ae6b0da
diff --git a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
index 0d248524c8..4746042208 100644
--- a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
@@ -36,12 +36,12 @@ import sliderCss from '@/components/ui/slider.css?inline';
* 历史卡片纯静态(净化器已剥 CSS 动画之外的一切动源,iframe 无脚本)。
*/
-import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useId, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Copy, FolderOpen, Ghost, Loader2 } from 'lucide-react';
import { ImageLightbox } from './ImageLightbox';
-import { mailCardFooterHtml } from './mailCardFooter';
+import { mailCardFooterHtml, updateMailCardDocument } from './mailCardFooter';
import { ModelLightbox } from './ModelLightbox';
import { GhostCardLinkConfirm, GhostCardPromptPanel } from './GhostCardHostPrompts';
import { toast } from '@/lib/toast';
@@ -239,7 +239,7 @@ function GhostCardCanvas({
return () => { window.clearInterval(timer); animation?.cancel(); };
}, [mail]);
const changeAction = readGhostCardFormChange(html);
- const formKey = changeAction ?? JSON.stringify(formFields);
+ const formKey = mail ? `mail:change:${mail.key}` : changeAction ?? JSON.stringify(formFields);
const formRetired = !!mail?.supersededBy || ['sent', 'deleted'].includes(mail?.state ?? '');
useEffect(() => () => {
if (sessionId) releaseGhostCardFormDelivery(sessionId, `${callId}:${editorId}`);
@@ -253,7 +253,19 @@ function GhostCardCanvas({
}
formState.current.values = mergeGhostCardFormValues(formState.current.values, formState.current.base, incoming);
formState.current.base = incoming;
- useEffect(() => { formState.current.busy = false; setFormBusy(false); }, [html]);
+ useEffect(() => {
+ // Delivery acknowledgement is not send completion. Autosave echoes must
+ // not unlock a send while the provider is still preparing its countdown.
+ if (!mail || !['draft', 'syncing'].includes(mail.state)) {
+ formState.current.busy = false;
+ setFormBusy(false);
+ if (mail) iframeRef.current?.contentDocument?.querySelectorAll<HTMLElement>('[data-ghost-submit]').forEach(el => {
+ el.removeAttribute('aria-disabled');
+ el.style.opacity = '';
+ el.style.pointerEvents = '';
+ });
+ }
+ }, [html, mail]);
const [lightbox, setLightbox] = useState<{ src: string; galleryId: string } | null>(null);
// data-ghost-model 声明的 3D 预览:点击开应用内 3D 查看器(GLB 已在媒体
// 总仓,blob 来源直读,预览图作 poster)。
@@ -541,6 +553,13 @@ function GhostCardCanvas({
formState.current.busy = true;
setFormBusy(true);
lockActionEl(el);
+ const unlock = () => {
+ formState.current.busy = false;
+ setFormBusy(false);
+ el.removeAttribute('aria-disabled');
+ el.style.opacity = '';
+ el.style.pointerEvents = '';
+ };
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.
@@ -550,9 +569,7 @@ function GhostCardCanvas({
? 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(() => {});
+ }).then(result => { if (!result.ok) unlock(); }).catch(unlock);
return;
}
// data-ghost-prompt 类动作:先弹宿主输入框收集文字,发送时才派发
@@ -613,6 +630,17 @@ function GhostCardCanvas({
measureHeight();
}, [measureHeight, callId, lockActionEl, bindAudioSlot, allowExternalLinks, html, sessionId]);
+ const cardSrcDoc = buildCardSrcDoc(renderedCardHtml, themeVars);
+ const initialMailDocument = useRef(cardSrcDoc);
+ const refreshMailDocument = useCallback(() => {
+ const doc = iframeRef.current?.contentDocument;
+ if (mail && doc?.body && doc.head) updateMailCardDocument(doc, cardSrcDoc);
+ attachClickBridge();
+ }, [mail, cardSrcDoc, attachClickBridge]);
+ useLayoutEffect(() => {
+ if (mail) refreshMailDocument();
+ }, [mail, refreshMailDocument]);
+
useEffect(() => {
// srcDoc 更新后 load 事件可能在 effect 前已触发(同进程同步解析),补挂一次。
// 依赖含 running/animatedHtml:settle 时动画版 → 静态版的换装同样要补挂;
@@ -721,8 +749,8 @@ function GhostCardCanvas({
<iframe
ref={iframeRef}
sandbox="allow-same-origin"
- srcDoc={buildCardSrcDoc(renderedCardHtml, themeVars)}
- onLoad={attachClickBridge}
+ srcDoc={mail ? initialMailDocument.current : cardSrcDoc}
+ onLoad={refreshMailDocument}
title={ariaTitle}
className="block w-full border-0"
style={{
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 f4ed79ba30..4f12e2682c 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailCardEditor.test.tsx
@@ -12,6 +12,57 @@ vi.mock('@/cindy-brain/useGhostCardThemeVars', () => ({ useGhostCardThemeVars: (
vi.mock('@/features/right-sidebar/lib/mailPreview', () => ({ openMailCard: vi.fn() }));
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+// User regression (unit): syncing between pointerdown/click lost Send, and
+// sending changed the editor key. Existing tests never rerendered these states.
+it('keeps the send target and HTML preview alive across sync and send states', async () => {
+ vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ let finish!: (result: { ok: boolean }) => void;
+ const dispatch = vi.fn(() => new Promise<{ ok: boolean }>(resolve => { finish = resolve; }));
+ vi.stubGlobal('electronAPI', { ghosts: { dispatchCardAction: dispatch } });
+ const mail: MailCardData = {
+ accountId: 'account', draftId: 'draft', key: '30000000-0000-0000-0000-000000000000',
+ from: 'sender', fields: [
+ ...['to', 'cc', 'bcc', 'subject', 'body'].map(name => ({ name, label: name, value: '' })),
+ { name: 'bodyHtml', kind: 'mail-html', label: 'Body', value: '<p>Hello</p>' },
+ ],
+ attachments: [], state: 'draft', status: 'Synced', sendLabel: 'Send', fromLabel: 'From',
+ };
+ const props = { callId: 'stable-editor', sessionId: 'stable-session', height: 80 };
+ const view = render(<MailCardEditor {...props} html={renderMailCard(mail)} />);
+ const frame = screen.getByTitle('mailReader.title') as HTMLIFrameElement;
+ frame.contentDocument!.open(); frame.contentDocument!.write(frame.srcdoc); frame.contentDocument!.close();
+ fireEvent.load(frame);
+ const srcDoc = frame.srcdoc;
+ const body = screen.getByTitle('chat.ghostCall.mailPreview');
+ const send = frame.contentDocument!.querySelector('[data-ghost-submit]')!;
+ fireEvent.pointerDown(send);
+ view.rerender(<MailCardEditor {...props} html={renderMailCard({ ...mail, state: 'syncing', status: 'Syncing' })} />);
+ expect(frame.contentDocument!.querySelector('[data-ghost-submit]')).toBe(send);
+ fireEvent.click(send);
+ await act(async () => {});
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ await act(async () => finish({ ok: true }));
+ view.rerender(<MailCardEditor {...props} html={renderMailCard(mail)} />);
+ fireEvent.click(send);
+ await act(async () => {});
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ view.rerender(<MailCardEditor {...props} html={renderMailCard({ ...mail, state: 'error', status: 'Save failed' })} />);
+ fireEvent.click(send);
+ await act(async () => {});
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ await act(async () => finish({ ok: true }));
+ const countdown: MailCardData = { ...mail, state: 'sending', status: 'sending', pendingSend: {
+ deadline: Date.now() + 10000, label: 'sending in {seconds}', cancelLabel: 'Cancel', sendNowLabel: 'Now',
+ } };
+ for (const next of [countdown, { ...mail, state: 'sending' as const, status: 'sending' }, { ...mail, state: 'sent' as const, status: 'sent' }]) {
+ view.rerender(<MailCardEditor {...props} html={renderMailCard(next)} />);
+ expect(screen.getByTitle('chat.ghostCall.mailPreview')).toBe(body);
+ expect(frame.srcdoc).toBe(srcDoc);
+ expect(frame.contentDocument!.body.textContent).toContain(next.state);
+ expect(frame.contentDocument!.querySelector('[data-ghost-submit]')).toBeNull();
+ }
+});
+
// 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 }));
diff --git a/apps/desktop/src/renderer/components/chat/mailCardFooter.ts b/apps/desktop/src/renderer/components/chat/mailCardFooter.ts
index b42ce0e2f8..cb2b9968e0 100644
--- a/apps/desktop/src/renderer/components/chat/mailCardFooter.ts
+++ b/apps/desktop/src/renderer/components/chat/mailCardFooter.ts
@@ -9,3 +9,34 @@ export function mailCardFooterHtml(html: string): string {
fragment.content.querySelectorAll('[data-cindy-mail], [data-ghost-form]').forEach(node => node.remove());
return fragment.innerHTML;
}
+
+/** Update the host-authored footer without navigating its browsing context.
+ * Matching action nodes stay in place so a save between pointerdown and click
+ * cannot discard the user's send gesture. Never used for plugin-authored cards. */
+export function updateMailCardDocument(doc: Document, srcDoc: string): void {
+ const next = new DOMParser().parseFromString(srcDoc, 'text/html');
+ const update = (target: Node, source: Node): void => {
+ if (target.nodeType === 3) {
+ if (target.nodeValue !== source.nodeValue) target.nodeValue = source.nodeValue;
+ return;
+ }
+ if (target.nodeType === 1) {
+ const element = target as Element;
+ for (const attr of (source as Element).attributes) {
+ if (element.getAttribute(attr.name) !== attr.value) element.setAttribute(attr.name, attr.value);
+ }
+ }
+ const children = [...source.childNodes];
+ children.forEach((child, index) => {
+ const old = target.childNodes[index];
+ const action = (node: Node) => node.nodeType === 1 ? (node as Element).getAttribute('data-ghost-action') : null;
+ if (!old) target.appendChild(doc.importNode(child, true));
+ else if (old.nodeType !== child.nodeType || old.nodeName !== child.nodeName || action(old) !== action(child)) {
+ target.replaceChild(doc.importNode(child, true), old);
+ } else update(old, child);
+ });
+ while (target.childNodes.length > children.length) target.lastChild!.remove();
+ };
+ update(doc.head, next.head);
+ update(doc.body, next.body);
+}