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): 收敛跨端草稿恢复与读取调用生命周期

Dash1e37c644f70a
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.ts
index 06a354f711..dbe655f5f4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/mailReader.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import { createMailReader, mailReaderRemoteProvider, type MailReaderPlugin } from '../mailReader.js';
import type { MailReaderDeclaration } from '@cindy/maker-shared/mail-message';
import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { GhostCardService } from '../cardService.js';
import { installedGhostLogicalIdentity, pluginStoragePart, resolvePluginInstanceQuery } from '../../../shared/pluginIdentity.js';
const productionReader = createGhostProductionCallbacks<{ readMail: ReturnType<typeof createMailReader> }>({ variables: ['readMail'] });
@@ -17,6 +18,37 @@ function setup(markRead: unknown = undefined) {
return { reader, call, authorize, expire: () => { current = false; } };
}
describe('common mailbox reader', () => {
+ // Unit: the production native-open callback must close its call-bound Host
+ // capability even if scope/approval changes or dispatch rejects. Previous
+ // tests mocked card lifecycle away and only covered a successful current read.
+ it.each(['owner', 'disabled', 'approval', 'dispatch-error', 'resolve-error'])('finalizes the native call after %s invalidation', async boundary => {
+ let ownerCurrent = true, approval = 'v1';
+ const ghost = { manifest: { id: plugin.id, mail: true, mailReader: plugin.reader, tools: [{ name: 'read_mail' }] },
+ instanceKey: '_root__test-mail', namespace: null, enabled: true, approval: { state: 'approved' } };
+ const cards = new GhostCardService({ hasCardSlot: () => true, sanitize: html => ({ ok: true, html }), persist: async () => {}, broadcast: () => {} });
+ const { readMail } = productionReader({
+ createMailReader, availableGhosts: () => [ghost], getGhostSetupAssessment: () => ({ state: 'ready' }),
+ getDeviceLinkInvokeContext: () => null, getSessionRowSnapshot: async () => ({}), assertRemoteBotInvocationAllowed: async () => {},
+ captureDataOwnerBroadcastScope: () => ({}), isDataOwnerBroadcastScopeCurrent: () => ownerCurrent,
+ findGhostForInstanceId: () => ghost, ghostInstallApprovalToken: () => approval, randomUUID: () => 'native-read',
+ pluginStoragePart, installedGhostLogicalIdentity, getGhostCardService: () => cards,
+ getMailCardService: () => ({ resolveLink: async () => { throw new Error('resolve failed'); } }),
+ getGhostPipeDispatcher: () => ({ callGhostTool: async () => {
+ expect(cards.inFlightCallInfoOf('native-read')?.sessionId).toBe('session');
+ if (boundary === 'owner') ownerCurrent = false;
+ if (boundary === 'disabled') ghost.enabled = false;
+ if (boundary === 'approval') approval = 'v2';
+ if (boundary === 'dispatch-error') throw new Error('dispatch failed');
+ return { ok: true, result: message };
+ } }),
+ });
+ const result = readMail('session', 'https://mail.example.com/m', true, true);
+ if (boundary === 'owner') await expect(result).rejects.toThrow('Mail unavailable');
+ else if (boundary === 'dispatch-error') await expect(result).rejects.toThrow('dispatch failed');
+ else if (boundary === 'resolve-error') await expect(result).rejects.toThrow('resolve failed');
+ else expect((await result).message).toEqual(message);
+ expect(cards.inFlightCallInfoOf('native-read')).toBeNull();
+ });
// Regression: native reads mixed an exact installation key with a logical
// namespace query, so new root/organization installs never reached the tool.
// Exercise the production host adapter; previous tests mocked its call away.
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 8e7ee4b987..7e8ec8989e 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -8048,7 +8048,9 @@ export function registerGhostIpc(): void {
const draftCallId = await getMailCardService().resolveLink(sender, sessionId, callId, mail?.accountId, mail?.draftId, current);
return { ...result, ...(draftCallId ? { draftCallId } : {}) };
} finally {
- if (opened && current()) cards.finalizeCall(callId);
+ // Closing the call's capability window must also happen after owner or
+ // installation invalidation. current() controls editor binding, not cleanup.
+ if (opened) cards.finalizeCall(callId);
}
},
});
diff --git a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
index 2db2c68aac..fa2c4d85dd 100644
--- a/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
+++ b/apps/desktop/src/renderer/components/chat/MailHtmlPreview.tsx
@@ -61,7 +61,7 @@ function PreviewFrame({ value, images = [], enlarged = false, reading = false, d
doc.head.replaceChildren(...[...next.head.childNodes].map(node => doc.importNode(node, true)));
doc.body.replaceChildren(...[...next.body.childNodes].map(node => doc.importNode(node, true)));
}
- serialize.current = mailBodySerializer(doc, model.current.emitted);
+ serialize.current = mailBodySerializer(doc, model.current.emitted, () => current.current.images);
stopTheme.current = followMailPreviewTheme(doc, document);
bodyResize.current?.disconnect();
if (!enlarged && typeof ResizeObserver !== 'undefined') {
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 d18083aa8f..bf82e4fab3 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MailHtmlPreview.test.tsx
@@ -270,6 +270,24 @@ it('autosaves simple HTML text edits and the plain alternative, keeps the caret
expect(screen.queryByRole('textbox')).toBeNull();
expect(screen.queryByRole('button', { name: 'chat.ghostCall.mailEditText' })).toBeNull();
});
+// Unit: CodeQL #409 exposed DOM marker -> image source restoration. Existing
+// save tests only covered unresolved CID images, not Host-backed preview URLs.
+it('restores only Host-backed CID references when serializing an edited body', () => {
+ const change = vi.fn(), url = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ render(<MailHtmlPreview value={'<p>Body</p><img src="cid:[email protected]">'} images={[{ cid: '[email protected]', url }]} onChange={change} />);
+ const frame = screen.getByTitle('chat.ghostCall.mailPreview') as HTMLIFrameElement, doc = frame.contentDocument!;
+ doc.open(); doc.write(frame.srcdoc); doc.close(); fireEvent.load(frame);
+ const paragraph = doc.querySelector('p')!, image = doc.querySelector('img')!;
+ expect(image.getAttribute('src')).toBe(url);
+ fireEvent.input(paragraph);
+ expect(change.mock.calls.at(-1)![0]).toContain('src="cid:[email protected]"');
+ expect(change.mock.calls.at(-1)![0]).not.toContain('cindy-media:');
+ image.setAttribute('data-cindy-mail-cid', 'forged-reference');
+ fireEvent.input(paragraph);
+ const saved = change.mock.calls.at(-1)![0];
+ expect(saved).not.toContain('forged-reference');
+ expect(saved).not.toContain('cindy-media:');
+});
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>';
diff --git a/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts b/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts
index 8fd1b05059..1ad2342c25 100644
--- a/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts
+++ b/apps/desktop/src/renderer/components/chat/mailBodyEditing.ts
@@ -1,8 +1,8 @@
-import { mailTextParagraphs, safeMailDocument } from '@cindy/maker-shared/mail-text-edit';
+import { mailTextParagraphs, safeMailDocument, type MailInlineImage } from '@cindy/maker-shared/mail-text-edit';
/** Capture authored paint before the preview theme changes it. Only sanitized
* markup is saved; local image URLs and editor attributes never leave the UI. */
-export function mailBodySerializer(doc: Document, source: string) {
+export function mailBodySerializer(doc: Document, source: string, images: () => readonly MailInlineImage[] = () => []) {
const styles = new WeakMap<Element, string | null>();
for (const el of [doc.body, ...doc.body.querySelectorAll('*')]) {
styles.set(el, el.getAttribute('style'));
@@ -19,8 +19,11 @@ export function mailBodySerializer(doc: Document, source: string) {
if (style == null) copy.removeAttribute('style');
else copy.setAttribute('style', style);
}
- const cid = copy.getAttribute('data-cindy-mail-cid');
- if (cid) copy.setAttribute('src', `cid:${cid}`);
+ // Restore only an attachment supplied by the Host, never a reference
+ // taken straight from mutable editor DOM. Unresolved original cid: URLs
+ // already survive cloning; local preview URLs are stripped below.
+ const image = images().find(image => image.cid === copy.getAttribute('data-cindy-mail-cid'));
+ if (image) copy.setAttribute('src', `cid:${image.cid}`);
copy.removeAttribute('contenteditable');
copy.removeAttribute('spellcheck');
});
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 94030e95ec..a94628fb78 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,19 @@ 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: [] });
+// Unit regression: a remote draft binding must not replace the readable mail
+// with the local-only editor. Existing link tests only exercised local tasks.
+it('keeps remote drafts readable and preserves the mailbox link', async () => {
+ const openExternal = vi.fn(async () => ({ success: true }));
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { openExternal } });
+ h.read.mockResolvedValue({ message: mail('Remote draft body'), draftCallId: 'remote-draft' });
+ render(<MailPreviewBody state={{ url: 'https://mail.example/draft' }} ctx={{ ...ctx, deviceLinkDeviceId: 'peer' }} />);
+ await act(async () => {});
+ expect(screen.getByText('Remote draft body')).toBeTruthy();
+ expect(screen.queryByTestId('editor')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'mailReader.openMailbox' }));
+ expect(openExternal).toHaveBeenCalledWith('https://mail.example/draft');
+});
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'} />);
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 0617fca0a0..8435386c70 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
@@ -40,7 +40,9 @@ export function MailPreviewBody({ state, ctx, active: tabActive = true, shellVis
}, [owner, ctx.sessionId, ctx.deviceLinkDeviceId, state.url, visible, current?.providerId]);
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>;
- if (current?.draftCallId) return <MailCardBody ctx={ctx} state={{ callId: current.draftCallId }} />;
+ // The local editor dispatches local card actions. Remote Desktop keeps the
+ // readable message and original mailbox link until that editor supports peers.
+ if (current?.draftCallId && ctx.deviceLinkDeviceId === null) return <MailCardBody ctx={ctx} state={{ callId: current.draftCallId }} />;
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)} />
diff --git a/apps/mobile/app/mail-preview.tsx b/apps/mobile/app/mail-preview.tsx
index 04543384ad..735fb94b98 100644
--- a/apps/mobile/app/mail-preview.tsx
+++ b/apps/mobile/app/mail-preview.tsx
@@ -81,9 +81,9 @@ export default function MailPreviewScreen() {
/** Reuse the chat card's controls, subscriptions and send confirmation. */
function DraftEditor({ deviceId, sessionId, callId }: { deviceId: string; sessionId: string; callId: string }) {
const { t } = useTranslation(), styles = useThemedStyles(makeStyles);
- const { blocks, error, retry, hidden } = usePluginResultCard(deviceId, sessionId, callId);
+ const { blocks, error, retry, hidden, callId: resolvedCallId } = usePluginResultCard(deviceId, sessionId, callId, true);
const actions = !hidden && blocks?.find(block => block.primitive === 'plugin-card-actions');
- return actions ? <PluginCardActions data={actions.data} deviceId={deviceId} sessionId={sessionId} callId={callId} /> : <>
+ return actions && resolvedCallId ? <PluginCardActions key={resolvedCallId} data={actions.data} deviceId={deviceId} sessionId={sessionId} callId={resolvedCallId} /> : <>
<Text style={styles.secondary}>{t(error || hidden ? 'plugins.mailReader.failed' : 'plugins.mailReader.loading')}</Text>
{(error || hidden) && <MainWindowActionButton action={{ label: t('plugins.mailReader.retry'), onPress: retry }} />}
</>;
diff --git a/apps/mobile/src/__tests__/usePluginResultCard.test.tsx b/apps/mobile/src/__tests__/usePluginResultCard.test.tsx
index c68a9e5c89..25cdf0388b 100644
--- a/apps/mobile/src/__tests__/usePluginResultCard.test.tsx
+++ b/apps/mobile/src/__tests__/usePluginResultCard.test.tsx
@@ -19,22 +19,61 @@ import { usePluginResultCard } from '@/session/usePluginResultCard';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
let current: ReturnType<typeof usePluginResultCard>;
-function Probe({ device = 'mac', task = 's', card = 'c' }: { device?: string; task?: string; card?: string }) {
- current = usePluginResultCard(device, task, card); return null;
+function Probe({ device = 'mac', task = 's', card = 'c', follow = false }: { device?: string; task?: string; card?: string; follow?: boolean }) {
+ current = usePluginResultCard(device, task, card, follow); return null;
}
async function render(props = {}) {
root ??= createRoot(document.createElement('div'));
await act(async () => { root!.render(createElement(Probe, props)); });
}
const result = (text: string) => ({ display: { title: 'Plugin' }, blocks: [{ id: 'text', primitive: 'markdown', fallbackMarkdown: text }] });
+const draft = (supersededBy?: string, overrides: Record<string, unknown> = {}) => ({ display: { title: 'Mail' }, blocks: [
+ { id: 'actions', primitive: 'plugin-card-actions', fallbackMarkdown: '', data: { pluginId: 'provider', 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', supersededBy,
+ ...overrides,
+ } } },
+] });
beforeEach(() => {
vi.clearAllMocks(); h.focused = true; h.link.status = 'online'; h.auth.accountGeneration = 1; h.link.connectionEpoch = 1;
- h.appState.currentState = 'active'; h.get.mockResolvedValue(result('done'));
+ h.appState.currentState = 'active'; h.get.mockReset().mockResolvedValue(result('done'));
h.link.onRemoteResourceChanged.mockImplementation((cb) => { h.push = cb; return () => { h.push = undefined; }; });
h.appState.addEventListener.mockImplementation((_event, cb) => { h.foreground = cb; return { remove() {} }; });
});
afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
describe('plugin card lifecycle on Mobile', () => {
+ // Unit: an open draft editor follows host replacement and submits against the
+ // latest ID. Chat rows still hide old cards. Prior tests only checked hiding,
+ // which left an already-open editor permanently bound to the obsolete ID.
+ it('follows the same draft replacement and refreshes pushes addressed to its latest card', async () => {
+ vi.useFakeTimers();
+ h.get.mockResolvedValueOnce(draft('new')).mockResolvedValueOnce(draft());
+ await render({ follow: true });
+ expect(current.callId).toBe('new'); expect(current.hidden).toBe(false);
+ expect(h.get.mock.calls.map(call => call[2].id)).toEqual(['["s","c"]', '["s","new"]']);
+ h.get.mockResolvedValueOnce(draft('new')).mockResolvedValueOnce(draft('latest')).mockResolvedValueOnce(draft());
+ await act(async () => { h.push?.('mac', { collectionId: 'plugin-results', resourceRefs: [{ kind: 'card', id: '["s","new"]' }] }); await vi.advanceTimersByTimeAsync(250); });
+ expect(current.callId).toBe('latest'); expect(current.hidden).toBe(false);
+ });
+ it.each(['plugin', 'account', 'draft', 'cycle', 'missing'])('rejects a %s replacement instead of exposing another draft', async boundary => {
+ const replacement = draft(undefined, boundary === 'account' ? { accountId: 'other' } : boundary === 'draft' ? { draftId: 'other' } : {});
+ if (boundary === 'plugin') replacement.blocks[0].data.pluginId = 'other';
+ h.get.mockResolvedValueOnce(draft(boundary === 'cycle' ? 'c' : 'new'));
+ if (boundary === 'missing') h.get.mockRejectedValueOnce(new Error('NOT_FOUND'));
+ else h.get.mockResolvedValueOnce(replacement);
+ await render({ follow: true });
+ expect(current.error).toBe(true); expect(current.blocks).toBeUndefined(); expect(current.callId).toBeUndefined();
+ });
+ it.each(['task', 'device', 'account'])('discards a late draft replacement after the %s changes', async boundary => {
+ let release!: (value: unknown) => void;
+ h.get.mockResolvedValueOnce(draft('new')).mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
+ await render({ follow: true });
+ if (boundary === 'account') h.auth.accountGeneration += 1;
+ await render({ follow: true, ...(boundary === 'task' ? { task: 'other' } : boundary === 'device' ? { device: 'other' } : {}) });
+ await act(async () => release(draft()));
+ expect(current.callId).toBe('c'); expect(current.blocks?.[0].fallbackMarkdown).toBe('done');
+ });
// 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 () => {
diff --git a/apps/mobile/src/session/usePluginResultCard.ts b/apps/mobile/src/session/usePluginResultCard.ts
index 013822facd..187aeac003 100644
--- a/apps/mobile/src/session/usePluginResultCard.ts
+++ b/apps/mobile/src/session/usePluginResultCard.ts
@@ -11,21 +11,21 @@ import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscri
/** Card content and Host-projected actions are scoped to account + device + task.
* 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) {
- const resource = useSessionPluginResource(deviceId, sessionId, callId, 'plugin-results', 'card');
+export function usePluginResultCard(deviceId: string | undefined, sessionId: string, callId: string, followMailReplacement = false) {
+ const resource = useSessionPluginResource(deviceId, sessionId, callId, 'plugin-results', 'card', followMailReplacement);
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) {
+export function useSessionPluginResource(deviceId: string | undefined, sessionId: string, callId: string, collectionId: string, kind: string, followMailReplacement = false) {
const { invoke, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
const { accountGeneration } = useAuth();
const focused = useIsFocused();
const subscriberId = useId();
const [attempt, setAttempt] = useState(0);
- const [state, setState] = useState<{ binding: string; blocks?: RemoteResourceBlock[]; title?: string; error?: boolean }>();
- const binding = JSON.stringify([accountGeneration, deviceId, sessionId, callId, collectionId, kind]);
+ const [state, setState] = useState<{ binding: string; callId?: string; blocks?: RemoteResourceBlock[]; title?: string; error?: boolean }>();
+ const binding = JSON.stringify([accountGeneration, deviceId, sessionId, callId, collectionId, kind, followMailReplacement]);
const current = useRef(binding); current.current = binding;
const retry = useCallback(() => setAttempt((value) => value + 1), []);
useEffect(() => {
@@ -34,28 +34,54 @@ export function useSessionPluginResource(deviceId: string | undefined, sessionId
let generation = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const id = JSON.stringify([sessionId, callId]);
+ let resolvedId = id;
const load = async () => {
if (AppState.currentState !== 'active') return;
const 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', '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 });
+ const read = (next: string) => getRemoteResource(invoke, { deviceId, deviceName: deviceId }, { collectionId, kind, id: JSON.stringify([sessionId, next]) }, undefined, collectionId === 'plugin-results' ? ['plugin-card-actions', 'plugin-card-forms'] : []);
+ let next = callId, resource = await read(next);
+ if (followMailReplacement) {
+ const identity = (blocks: RemoteResourceBlock[] | undefined) => {
+ const data = blocks?.find(block => block.primitive === 'plugin-card-actions')?.data as { pluginId?: unknown; mail?: unknown } | undefined;
+ const mail = parseMailCard(data?.mail);
+ return mail && typeof data?.pluginId === 'string' && data.pluginId ? { pluginId: data.pluginId, mail } : undefined;
+ };
+ const first = identity(resource.blocks), visited = new Set([next]);
+ let card = first;
+ while (card?.mail.supersededBy) {
+ if (!valid()) return;
+ next = card.mail.supersededBy;
+ if (visited.has(next) || visited.size >= 32) throw new Error('NOT_FOUND: Mail replacement unavailable');
+ visited.add(next);
+ resource = await read(next);
+ card = identity(resource.blocks);
+ // Host verifies task ownership on every resource read; additionally
+ // reject a replacement belonging to another installation or draft.
+ if (!card || card.pluginId !== first!.pluginId || card.mail.accountId !== first!.mail.accountId || card.mail.draftId !== first!.mail.draftId)
+ throw new Error('NOT_FOUND: Mail replacement unavailable');
+ }
+ }
+ if (valid()) {
+ resolvedId = JSON.stringify([sessionId, next]);
+ setState({ binding, callId: next, 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;
const unavailable = /NOT_FOUND|FORBIDDEN|UNAUTHORIZED/.test(String(code ?? '') + String(error));
- if (valid()) setState((previous) => ({ binding, ...(!unavailable && previous?.binding === binding ? { blocks: previous.blocks, title: previous.title } : {}), error: true }));
+ if (valid()) setState((previous) => ({ binding, ...(!unavailable && previous?.binding === binding ? { callId: previous.callId, blocks: previous.blocks, title: previous.title } : {}), error: true }));
}
};
const offPush = onRemoteResourceChanged((source, payload) => {
if (source !== deviceId || payload.collectionId !== collectionId) return;
- if (payload.resourceRefs?.length && !payload.resourceRefs.some((ref) => ref.kind === kind && ref.id === id)) return;
+ if (payload.resourceRefs?.length && !payload.resourceRefs.some((ref) => ref.kind === kind && (ref.id === id || ref.id === resolvedId))) return;
if (!timer) timer = setTimeout(() => { timer = undefined; void load(); }, 200);
});
const offTopic = startFocusedTopicSubscription({ deviceId, owner: `${collectionId}:${id}:${subscriberId}`, topic: 'sessions', subscribe, unsubscribe });
const listener = AppState.addEventListener('change', (next) => { generation += 1; if (next === 'active') void load(); });
void load();
return () => { disposed = true; generation += 1; offPush(); offTopic(); listener.remove(); if (timer) clearTimeout(timer); };
- }, [subscriberId, focused, binding, deviceId, sessionId, callId, collectionId, kind, attempt, connectionEpoch, status, invoke, onRemoteResourceChanged, subscribe, unsubscribe]);
- return { title: state?.binding === binding ? state.title : undefined, blocks: state?.binding === binding ? state.blocks : undefined, error: !deviceId || status !== 'online' || (state?.binding === binding && state.error), retry };
+ }, [subscriberId, focused, binding, deviceId, sessionId, callId, collectionId, kind, followMailReplacement, attempt, connectionEpoch, status, invoke, onRemoteResourceChanged, subscribe, unsubscribe]);
+ return { callId: state?.binding === binding ? state.callId : undefined, title: state?.binding === binding ? state.title : undefined, blocks: state?.binding === binding ? state.blocks : undefined, error: !deviceId || status !== 'online' || (state?.binding === binding && state.error), retry };
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 95af3013e1..60911651b4 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3056,8 +3056,15 @@ optional `draftCallId` only after matching a current card's task, plugin, accoun
This reference is never accepted from provider result data. Background reads cannot publish
or return editor bindings. Desktop's local sidebar and Mobile use their existing card editors,
autosave and send/undo actions. The Mobile editor reuses `plugin-results/card` subscriptions;
-no new transport, persistence, credential transfer or send path is introduced. Old hosts do
-not inject `openDraft` and remain read-only; old providers ignore it, and old clients ignore
+no new transport, persistence, credential transfer or send path is introduced.
+The Mobile editor follows `supersededBy` through the same task-scoped resource reads only
+while installation, account and draft identity still match; its actions and invalidations
+use the resolved card ID. Ordinary chat rows continue hiding superseded cards.
+Remote Desktop retains the read-only message and original mailbox link because its
+existing card editor dispatches local actions only. Native reader calls are finalized
+even after owner/installation invalidation. Owner scope still guards result delivery;
+an invalid installation cannot acquire editor bindings or extend the call-bound Host capability window.
+Old hosts do not inject `openDraft` and remain read-only; old providers ignore it, and old clients ignore
`draftCallId`. Source package compatibility remains 0.1.112; editable link support requires
both the updated provider and the corresponding Host/client changes.
Desktop link opening and card enlargement both await the existing card-form delivery