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(plugins): 按文档隔离远程配置确认与目录选择

nana9f73cc1f914e
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts
index 3e5ba3a613..827ff7bf6a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts
@@ -35,6 +35,8 @@ describe('mobile page relay', () => {
data: { op: 'delete', mobilePageId: 'forged' },
});
expect(channels[0].sent).toEqual([{ op: 'delete', mobilePageId: 'a' }]);
+ run({ op: 'post', pageId: 'a', sourceId: 'document-a', channel: 'practice', data: { mobilePageId: 'forged' } });
+ expect(channels[0].sent[1]).toEqual({ mobilePageId: 'document-a' });
channels[0].onmessage?.({ data: { saved: true } });
expect(run({ op: 'poll', pageId: 'a', after: 0 })).toHaveLength(1);
expect(run({ op: 'poll', pageId: 'a', after: 0 })).toHaveLength(1);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
index c3d66e9208..eda79c9687 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
@@ -120,8 +120,9 @@ function fixture(namespace: string | null = null) {
},
);
const disconnect = vi.fn(async () => {}),
- post = vi.fn(async () => {}),
- connect = vi.fn(async () => {});
+ post = vi.fn(async (_ghost: InstalledGhost, _pageId: string, _channel: string, _data: unknown, _sourceId?: string) => {}),
+ connect = vi.fn(async () => {}),
+ poll = vi.fn(async (): Promise<any[]> => []);
const validateDirectory = vi.fn<(path: string) => Promise<string>>(
async () => '/target/resolved',
);
@@ -144,7 +145,7 @@ function fixture(namespace: string | null = null) {
}),
connect,
post,
- poll: async () => [],
+ poll,
disconnect,
fetch: vi.fn(),
settingsFetch,
@@ -223,6 +224,7 @@ function fixture(namespace: string | null = null) {
open,
post,
connect,
+ poll,
disconnect,
wire,
auth,
@@ -614,3 +616,117 @@ describe('original remote plugin settings', () => {
).toThrow();
});
});
+
+// #6680 post-merge P1: unseen confirmations and directory replies survive package navigation.
+// Real Host entry, in-memory transport. Existing tests only covered lease close/revocation.
+// Minimal input: A creates a prompt, document advances before poll/answer, then B queries.
+it.each([false, true])('invalidates document prompts while retaining Host notices and another page (polled=%s)', async (polled) => {
+ const f = fixture();
+ const opened = await f.service.provider().invoke!({ controllerDeviceId: 'controller-a' }, {
+ collectionId: 'plugins', actionId: 'settings:open', resourceRef: { collectionId: 'plugins', kind: 'plugin', id: f.ghost.instanceKey },
+ input: { expectedInstalledApproval: ghostInstallApprovalToken(f.ghost.approval) },
+ } as never);
+ const pageId = (opened.result as any).pageId;
+ const send = (command: any) => f.service.settingsRequest('controller-a', { op: 'settings', id: pageId, command });
+ cleanup.push(() => { void send({ kind: 'close' }).catch(() => {}); });
+ const advance = (epoch: number) => send({ kind: 'document', epoch });
+ const origin = async () => {
+ await send({ kind: 'subscribe', channels: ['test'] });
+ await send({ kind: 'post', channel: 'test', data: { op: 'action' } });
+ return f.post.mock.calls.at(-1)![4] as string;
+ };
+ await advance(1);
+ const a = await origin();
+ const params = { ghostId: f.ghost.instanceKey!, ghostName: 'Original plugin', body: 'A action', confirmText: null, cancelText: null, danger: false };
+ await f.open();
+ const otherPageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()].find(id => id !== pageId)!;
+ const otherAnswer = f.service.confirm(otherPageId, params);
+ const confirm = f.service.confirm(a, params);
+ const directory = f.service.chooseDirectory(a, f.ghost.instanceKey!, 'A folder');
+ const pending = polled ? await send({ kind: 'poll', after: 0 }) as any : null;
+ const currentA = f.service.captureSource(a, f.ghost.instanceKey!);
+ expect(currentA()).toBe(true);
+ expect(f.service.notify(a, f.ghost.instanceKey!, 'Saved on Host')).toBe(true);
+ await advance(2);
+ expect(await confirm).toBe(false);
+ expect(await directory).toBeNull();
+ const otherPoll = await f.service.settingsRequest('controller-a', { op: 'settings', id: otherPageId, command: { kind: 'poll', after: 0 } }) as any;
+ expect(otherPoll.confirms).toHaveLength(1);
+ await f.service.settingsRequest('controller-a', { op: 'settings', id: otherPageId, command: { kind: 'confirm', requestId: otherPoll.confirms[0].id, accepted: true } });
+ expect(await otherAnswer).toBe(true);
+ expect(currentA()).toBe(false);
+ expect(await send({ kind: 'poll', after: 0 })).toMatchObject({ confirms: [], directories: [], notifications: [{ text: 'Saved on Host' }] });
+ if (pending) {
+ await expect(send({ kind: 'confirm', requestId: pending.confirms[0].id, accepted: true })).rejects.toThrow();
+ await expect(send({ kind: 'answer-directory', requestId: pending.directories[0].id, path: '/target/folder' })).rejects.toThrow();
+ }
+ await expect(f.service.confirm(a, params)).rejects.toThrow();
+ await expect(f.service.chooseDirectory(a, f.ghost.instanceKey!, 'Late A')).rejects.toThrow();
+ expect(f.service.notify(a, f.ghost.instanceKey!, 'A finished saving')).toBe(true);
+ const b = await origin();
+ expect(b).not.toBe(a);
+ const bDirectory = f.service.chooseDirectory(b, f.ghost.instanceKey!, 'B folder');
+ const bAnswer = f.service.confirm(b, params);
+ await advance(2); // Duplicate acknowledgement must not cancel B.
+ const bPoll = await send({ kind: 'poll', after: 0 }) as any;
+ await send({ kind: 'confirm', requestId: bPoll.confirms[0].id, accepted: true });
+ expect(await bAnswer).toBe(true);
+ await send({ kind: 'answer-directory', requestId: bPoll.directories[0].id, path: '/target/folder' });
+ expect(await bDirectory).toBe('/target/resolved');
+ expect(bPoll.notifications).toEqual([expect.objectContaining({ text: 'A finished saving' })]);
+ await expect(advance(1)).rejects.toThrow();
+ await send({ kind: 'close' });
+ expect(f.service.notify(a, f.ghost.instanceKey!, 'closed')).toBe(false);
+});
+
+it('rejects a directory answer and a delayed fetch confirmation after document replacement', async () => {
+ const f = fixture();
+ await f.open();
+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ const send = (command: any) => f.service.settingsRequest('controller-a', { op: 'settings', id: pageId, command });
+ await send({ kind: 'document', epoch: 1 });
+ await send({ kind: 'subscribe', channels: ['test'] });
+ await send({ kind: 'post', channel: 'test', data: {} });
+ const source = f.post.mock.calls.at(-1)![4] as string;
+ const chosen = f.service.chooseDirectory(source, f.ghost.instanceKey!, 'A');
+ const poll = await send({ kind: 'poll', after: 0 }) as any;
+ let resolvePath!: (path: string) => void;
+ f.validateDirectory.mockImplementationOnce(() => new Promise(resolve => { resolvePath = resolve; }));
+ const answering = send({ kind: 'answer-directory', requestId: poll.directories[0].id, path: '/target/folder' });
+ let delayedConfirm!: () => Promise<boolean>;
+ let fetchCurrent!: () => boolean;
+ f.settingsFetch.mockImplementationOnce(async (_ghost, _path, _method, _body, current, confirmConnection) => {
+ fetchCurrent = current;
+ delayedConfirm = () => confirmConnection!('Service', 'example.com');
+ return { status: 200, mime: 'application/json', base64: '' };
+ });
+ await send({ kind: 'fetch', path: '/connections/service', method: 'POST' });
+ await send({ kind: 'document', epoch: 2 });
+ resolvePath('/target/folder');
+ await expect(answering).rejects.toThrow();
+ expect(await chosen).toBeNull();
+ expect(fetchCurrent()).toBe(false);
+ await expect(delayedConfirm()).rejects.toThrow();
+});
+
+it('does not return B prompts or events in a poll started by document A', async () => {
+ const f = fixture();
+ await f.open();
+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ const send = (command: any) => f.service.settingsRequest('controller-a', { op: 'settings', id: pageId, command });
+ await send({ kind: 'document', epoch: 1 });
+ await send({ kind: 'subscribe', channels: ['test'] });
+ let finish!: (events: any[]) => void;
+ f.poll.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const aPoll = send({ kind: 'poll', after: 0 });
+ await send({ kind: 'document', epoch: 2 });
+ await send({ kind: 'post', channel: 'test', data: {} });
+ const b = f.post.mock.calls.at(-1)![4]!;
+ const answer = f.service.confirm(b, { ghostId: f.ghost.instanceKey!, ghostName: 'B', body: 'B action', confirmText: null, cancelText: null, danger: false });
+ finish([{ sequence: 1, channel: 'test', data: 'B event' }]);
+ expect(await aPoll).toMatchObject({ events: [], confirms: [], directories: [] });
+ const bPoll = await send({ kind: 'poll', after: 0 }) as any;
+ expect(bPoll.confirms).toHaveLength(1);
+ await send({ kind: 'confirm', requestId: bPoll.confirms[0].id, accepted: true });
+ expect(await answer).toBe(true);
+});
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 726f53abf8..e2b4569081 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -8089,7 +8089,7 @@ export function registerGhostIpc(): void {
await runtime.spawn(ghost);
await invokeGhostMobileRelay(ghost, { op: 'connect', pageId, channels });
},
- post: async (ghost, pageId, channel, data) => { await invokeGhostMobileRelay(ghost, { op: 'post', pageId, channel, data }); },
+ post: async (ghost, pageId, channel, data, sourceId) => { await invokeGhostMobileRelay(ghost, { op: 'post', pageId, channel, data, sourceId }); },
poll: async (ghost, pageId, after) => await invokeGhostMobileRelay(ghost, { op: 'poll', pageId, after }) as PluginPagePoll['events'],
disconnect: async (id, pageId) => {
const ghost = findGhostForPhysicalStoragePart(id);
diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
index cde9f81678..7948866a07 100644
--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts
+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts
@@ -32,6 +32,9 @@ import {
interface Page {
desktopSettings?: true;
+ documentEpoch?: number;
+ documentId?: string;
+ documentSources?: Set<string>;
channels?: string[];
authorizations?: Map<string, { path: string; body?: string; running: boolean; keepAlive?: () => boolean; result?: import('@cindy/device-link').PluginPageFetchResult }>;
id: string;
@@ -82,7 +85,7 @@ interface Dependencies {
bundle(ghost: InstalledGhost, entry: string): Promise<PluginPageFile[]>;
asset(ghost: InstalledGhost, file: PluginPageFile, offset: number): Promise<PluginPageAsset>;
connect(ghost: InstalledGhost, pageId: string, channels: string[]): Promise<void>;
- post(ghost: InstalledGhost, pageId: string, channel: string, data: unknown): Promise<void>;
+ post(ghost: InstalledGhost, pageId: string, channel: string, data: unknown, sourceId?: string): Promise<void>;
poll(ghost: InstalledGhost, pageId: string, after: number): Promise<PluginPagePoll['events']>;
disconnect(pluginId: string, pageId: string): Promise<void>;
fetch(
@@ -122,6 +125,12 @@ const record = (v: unknown): Record<string, unknown> =>
* Writes are never replayed after reconnect. Reading/polling does not acknowledge unread content. */
export class MobilePluginPages {
private readonly pages = new Map<string, Page>();
+ // Retired document IDs remain notice-only until the lease closes.
+ private readonly documentSources = new Map<string, Page>();
+ private source(id: string): Page | undefined {
+ const page = this.pages.get(id) ?? this.documentSources.get(id);
+ return page && (page.documentId ?? page.id) === id ? page : undefined;
+ }
constructor(private readonly deps: Dependencies) {}
private now() {
return this.deps.now?.() ?? Date.now();
@@ -160,6 +169,7 @@ export class MobilePluginPages {
}
private close(page: Page) {
this.pages.delete(page.id);
+ for (const id of page.documentSources ?? []) this.documentSources.delete(id);
for (const id of page.authorizations?.keys() ?? []) notifyOauthCardClosed(id);
this.cancelDirectory(page);
page.previews?.clear();
@@ -266,7 +276,8 @@ export class MobilePluginPages {
const page = this.page(request.id, controller);
if (!page.desktopSettings) return fail();
const ghost = this.check(page),
- command = request.command;
+ command = request.command,
+ sourceId = page.documentId ?? page.id;
const current = () => {
try {
return this.page(page.id, controller) === page;
@@ -279,6 +290,24 @@ export class MobilePluginPages {
return value;
};
switch (command.kind) {
+ case 'document': {
+ if (command.epoch < (page.documentEpoch ?? 0)) return fail();
+ if (command.epoch === page.documentEpoch) return {};
+ // Bound retained notice origins within this lease; a reload opens a fresh lease.
+ if ((page.documentSources?.size ?? 0) >= 1024) return fail();
+ page.documentEpoch = command.epoch;
+ page.documentId = randomUUID();
+ (page.documentSources ??= new Set()).add(page.documentId);
+ this.documentSources.set(page.documentId, page);
+ this.cancelDirectory(page);
+ for (const pending of page.confirms.values()) {
+ clearTimeout(pending.timer);
+ pending.answer(false);
+ }
+ page.confirms.clear();
+ page.directoryAnswers?.clear();
+ return {};
+ }
case 'close':
this.close(page);
return {};
@@ -296,7 +325,7 @@ export class MobilePluginPages {
}
case 'post':
if (!page.channels?.includes(command.channel)) return fail();
- await this.deps.post(ghost, page.id, command.channel, command.data);
+ await this.deps.post(ghost, page.id, command.channel, command.data, sourceId);
return done({});
case 'unsubscribe': {
const channels = (page.channels ?? []).filter((name) => name !== command.channel);
@@ -304,13 +333,16 @@ export class MobilePluginPages {
page.channels = channels;
return done({});
}
- case 'poll':
+ case 'poll': {
+ const events = page.channels?.length ? await this.deps.poll(ghost, page.id, command.after) : [];
+ const sameDocument = sourceId === (page.documentId ?? page.id);
return done({
- events: page.channels?.length ? await this.deps.poll(ghost, page.id, command.after) : [],
- confirms: [...page.confirms.values()].map((p) => p.value),
+ events: sameDocument ? events : [],
+ confirms: sameDocument ? [...page.confirms.values()].map((p) => p.value) : [],
notifications: page.notices.splice(0),
- directories: page.directory ? [page.directory.value] : [],
+ directories: sameDocument && page.directory ? [page.directory.value] : [],
});
+ }
case 'confirm': {
const pending = page.confirms.get(command.requestId);
if (!pending || pending.value.expiresAt <= this.now()) return fail();
@@ -359,9 +391,9 @@ export class MobilePluginPages {
url.pathname + url.search,
command.method,
command.body,
- current,
+ () => current() && sourceId === (page.documentId ?? page.id),
(label, host) =>
- this.confirm(page.id, {
+ this.confirm(sourceId, {
ghostId: page.plugin,
ghostName: ghost.manifest.name,
iconDataUrl: ghost.iconDataUrl,
@@ -434,13 +466,13 @@ export class MobilePluginPages {
}
captureSource(pageId: unknown, pluginId: string): () => boolean {
if (typeof pageId !== 'string') return fail();
- const page = this.pages.get(pageId);
+ const page = this.source(pageId);
if (!page || page.plugin !== pluginId || !page.active || page.sourceHidden) return fail();
this.check(page);
return () => {
try {
- this.page(pageId, page.controller);
- return page.active && !page.sourceHidden;
+ this.page(page.id, page.controller);
+ return this.source(pageId) === page && page.active && !page.sourceHidden;
} catch {
return false;
}
@@ -452,7 +484,7 @@ export class MobilePluginPages {
purpose: string | null,
): Promise<string | null> {
const current = this.captureSource(pageId, pluginId),
- page = this.pages.get(pageId)!;
+ page = this.source(pageId)!;
if (!current() || page.directory || !this.deps.validateDirectory) return fail();
const ghost = this.check(page),
id = randomUUID();
@@ -483,7 +515,7 @@ export class MobilePluginPages {
): boolean {
try {
if (!this.captureSource(pageId, pluginId)()) return false;
- const page = this.pages.get(pageId)!,
+ const page = this.source(pageId)!,
ghost = this.check(page);
if ((page.intents?.length ?? 0) >= 8) return false;
(page.intents ??= []).push({
@@ -499,7 +531,7 @@ export class MobilePluginPages {
}
notify(pageId: string, pluginId: string, text: string): boolean {
this.sweep();
- const page = this.pages.get(pageId);
+ const page = this.pages.get(pageId) ?? this.documentSources.get(pageId);
if (
!page ||
!page.active ||
@@ -540,7 +572,7 @@ export class MobilePluginPages {
/** Explicit page context supplied by a plugin handling that page's business request.
* A missing/invalid context never falls back to a different phone. */
async confirm(pageId: string, params: GhostConfirmShowParams): Promise<boolean> {
- const page = this.pages.get(pageId);
+ const page = this.source(pageId);
if (!page || !page.active || page.sourceHidden || page.plugin !== params.ghostId) return fail();
this.check(page);
if (this.now() - page.touchedAt > 120_000 || page.confirms.size) return fail();
@@ -885,6 +917,7 @@ export class MobilePluginPages {
manifestId: ghost.manifest.id,
name: ghost.manifest.name,
controllerAuthorization: true,
+ documentIsolation: true,
entry: ghost.manifest.settingsHtml,
files: page.files,
},
diff --git a/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts b/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts
index 3194e105e4..481e70e939 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts
@@ -2,7 +2,7 @@ import type { PluginPageEvent } from '@cindy/device-link';
export type MobileRelayOperation =
| { op: 'connect'; pageId: string; channels: string[] }
- | { op: 'post'; pageId: string; channel: string; data: unknown }
+ | { op: 'post'; pageId: string; channel: string; data: unknown; sourceId?: string }
| { op: 'poll'; pageId: string; after: number }
| { op: 'disconnect'; pageId: string };
@@ -80,7 +80,7 @@ function relay(operation: MobileRelayOperation) {
// Plugins forward this opaque origin when requesting a host confirmation.
channel.postMessage(
data && typeof data === 'object' && !Array.isArray(data)
- ? { ...data, mobilePageId: operation.pageId }
+ ? { ...data, mobilePageId: operation.sourceId ?? operation.pageId }
: data,
);
}
diff --git a/apps/mobile/app/plugin-management-preview.tsx b/apps/mobile/app/plugin-management-preview.tsx
index a750c6750d..b7a61a8b86 100644
--- a/apps/mobile/app/plugin-management-preview.tsx
+++ b/apps/mobile/app/plugin-management-preview.tsx
@@ -171,6 +171,7 @@ function createSettingsFixture(): PluginSettingsClientOptions {
lastField: "Long form field",
};
let saved = false;
+ let documentEpoch = 0;
let accounts = [
{ id: "one", label: "Test account one", isDefault: true },
{ id: "two", label: "Test account two", isDefault: false },
@@ -182,6 +183,7 @@ function createSettingsFixture(): PluginSettingsClientOptions {
}));
const document = {
pageId: "qa-page",
+ documentIsolation: true,
pluginId: "qa-settings",
manifestId: "qa-settings",
name: "QA settings",
@@ -201,6 +203,7 @@ function createSettingsFixture(): PluginSettingsClientOptions {
request: async (raw) => {
if (raw.op !== "settings") throw new Error("QA_ONLY");
const c = raw.command;
+ if (c.kind === "document") { documentEpoch = c.epoch; return {}; }
if (c.kind === "asset") {
const text = assets[c.path as keyof typeof assets];
const bytes = new TextEncoder()
@@ -224,7 +227,7 @@ function createSettingsFixture(): PluginSettingsClientOptions {
let body: unknown;
if (c.path === "/kv") {
if (c.method === "PUT") preferences = JSON.parse(c.body ?? "{}");
- body = preferences;
+ body = { ...preferences, documentEpoch };
} else if (c.path === "/secrets/key" && c.method === "PUT") {
saved = true;
return { status: 204, mime: "application/json", base64: "" };
diff --git a/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx b/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx
index 746d4300c1..c9d8e0444f 100644
--- a/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx
+++ b/apps/mobile/src/__tests__/pluginSettingsCard.test.tsx
@@ -584,3 +584,31 @@ it("releases old subscriptions before the new document subscribes, including an
{ kind: "subscribe", channels: ["test"] }, { kind: "unsubscribe", channel: "test" }, { kind: "subscribe", channels: ["test"] },
]);
});
+
+// #6680 unseen-confirm gap: activate the new Host document before reads/posts,
+// without serializing a confirmation-dependent fetch ahead of its cancellation.
+// Production component; memory transport, fake clock; tier: unit.
+it("activates the Host document before commands and does not deadlock navigation behind a pending fetch", async () => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ const root = createRoot(document.createElement("div"));
+ cleanup = async () => { await act(async () => root.unmount()); };
+ await act(async () => root.render(createElement(PluginSettingsCard, {
+ identity: { deviceId: "host", instanceId: "plugin", expectedInstalledApproval: "approval" },
+ active: true, generation: 1, assertCurrent() {}, invokeTarget: vi.fn(), openSession: vi.fn(),
+ })));
+ const client = state.clients[0];
+ client.document.documentIsolation = true;
+ let activate!: () => void, finishFetch!: (value: unknown) => void;
+ client.send.mockImplementationOnce(() => new Promise<void>(resolve => { activate = resolve; }));
+ client.fetch.mockImplementationOnce(() => new Promise(resolve => { finishFetch = resolve; }));
+ await act(async () => state.web.onLoadStart());
+ await act(async () => state.web.onMessage({ nativeEvent: { data: JSON.stringify({ settings: "page", id: 1, command: { kind: "fetch", path: "/kv", method: "PUT", body: '{"label":"A"}' } }) } }));
+ expect(client.fetch).not.toHaveBeenCalled();
+ await act(async () => activate());
+ expect(client.fetch).toHaveBeenCalledWith("/kv", "PUT", '{"label":"A"}');
+ await act(async () => state.web.onLoadStart());
+ expect(client.send.mock.calls.map(([command]: any[]) => command)).toEqual([{ kind: "document", epoch: 1 }, { kind: "document", epoch: 2 }]);
+ state.inject.mockClear();
+ await act(async () => finishFetch({ status: 200, mime: "application/json", base64: "e30=" }));
+ expect(state.inject).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/pluginSettingsClient.test.ts b/apps/mobile/src/__tests__/pluginSettingsClient.test.ts
index 6fe7bce6da..1c6dcc4032 100644
--- a/apps/mobile/src/__tests__/pluginSettingsClient.test.ts
+++ b/apps/mobile/src/__tests__/pluginSettingsClient.test.ts
@@ -342,3 +342,9 @@ it('routes only the fixed credential check through encrypted settings and never
expect(f.request).toHaveBeenCalledTimes(1);
await client.close();
});
+
+it('negotiates document isolation only from an explicit Host capability', () => {
+ expect(parsePluginSettingsDocument(document, document.pluginId).documentIsolation).toBeUndefined();
+ expect(parsePluginSettingsDocument({ ...document, documentIsolation: true }, document.pluginId).documentIsolation).toBe(true);
+ expect(parsePluginSettingsDocument({ ...document, documentIsolation: 'true' }, document.pluginId).documentIsolation).toBeUndefined();
+});
diff --git a/apps/mobile/src/debug/pluginSettingsPreviewAssets.json b/apps/mobile/src/debug/pluginSettingsPreviewAssets.json
index 4000eb9464..d187e672a9 100644
--- a/apps/mobile/src/debug/pluginSettingsPreviewAssets.json
+++ b/apps/mobile/src/debug/pluginSettingsPreviewAssets.json
@@ -1,4 +1,6 @@
{
- "settings.html": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>QA original plugin settings</title>\n <style>\n * { box-sizing: border-box; }\n body { margin: 0; padding: 16px; font: 16px/1.5 system-ui, sans-serif; color: var(--text-primary, CanvasText); background: var(--surface, Canvas); }\n main { width: 100%; max-width: 40rem; margin: auto; }\n h1, h2 { font-size: 18px; line-height: 1.4; }\n fieldset { min-width: 0; margin: 16px 0; padding: 12px; border: 1px solid var(--border-default, GrayText); }\n label { display: block; margin: 12px 0; }\n input:not([type=\"checkbox\"]), select, textarea { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit; color: inherit; background: var(--surface-elevated, Field); border: 1px solid var(--border-default, GrayText); }\n button { min-height: 44px; max-width: 100%; padding: 8px 12px; margin: 4px 0; font: inherit; white-space: normal; color: inherit; background: var(--surface-elevated, ButtonFace); border: 1px solid var(--border-default, GrayText); }\n output, li { overflow-wrap: anywhere; }\n :focus-visible { outline: 2px solid var(--focus-ring, Highlight); outline-offset: 2px; }\n </style>\n </head>\n <body>\n <main>\n <h1>QA original plugin settings</h1>\n <p>TEST DATA ONLY · original HTML fixture · no file import</p>\n <output id=\"status\" role=\"status\" aria-live=\"polite\">Reading target Host…</output>\n <form id=\"preferences\">\n <fieldset>\n <legend>Ordinary settings on the target Host</legend>\n <label>Display label <input id=\"displayLabel\" name=\"displayLabel\" required maxlength=\"80\"></label>\n <label><input id=\"notifications\" name=\"notifications\" type=\"checkbox\"> Notifications</label>\n <label>Language <select id=\"language\" name=\"language\"><option value=\"en\">English</option><option value=\"zh-CN\">简体中文</option></select></label>\n <button type=\"submit\">Save ordinary settings</button>\n <button id=\"reload\" type=\"button\">Read target again</button>\n </fieldset>\n </form>\n <fieldset>\n <legend>Write-only synthetic secret</legend>\n <output id=\"secretState\">Status unknown</output>\n <label>Test key <input id=\"secret\" type=\"password\" autocomplete=\"off\" placeholder=\"Use an invalid QA value only\"></label>\n <button id=\"saveSecret\" type=\"button\">Save test key to target</button>\n </fieldset>\n <fieldset>\n <legend>OAuth accounts</legend>\n <ul id=\"accounts\"></ul>\n <button id=\"connect\" type=\"button\">Connect a test account</button>\n </fieldset>\n <fieldset>\n <legend>Directory and original channel interaction</legend>\n <button id=\"pickDirectory\" type=\"button\">Choose a directory on the target</button>\n <output id=\"directory\">No directory selected</output>\n <button id=\"echo\" type=\"button\">Send channel probe</button>\n <output id=\"channelState\">No reply received</output>\n </fieldset>\n <form id=\"longForm\">\n <fieldset>\n <legend>Long form: keyboard and scroll</legend>\n <div id=\"longFields\"></div>\n <label>Last field <textarea id=\"lastField\" rows=\"4\" placeholder=\"Keep this draft while opening the keyboard or changing theme\"></textarea></label>\n <button type=\"submit\">Save bottom field</button>\n </fieldset>\n </form>\n </main>\n <script src=\"settings.js\"></script>\n </body>\n</html>\n",
- "settings.js": "// Test-only original plugin code: no local persistence, production ID branching, or external fetch.\n(() => {\n const element = (id) => document.getElementById(id);\n const status = (text) => { element('status').textContent = text; };\n const channel = new BroadcastChannel('qa-settings');\n let sequence = 0;\n let pendingDirectory;\n let pendingProbe;\n const request = async (path, method = 'GET', body) => {\n const response = await fetch(path, {\n method,\n ...(body === undefined ? {} : {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }),\n });\n if (!response.ok) throw new Error('Target request failed: ' + response.status);\n return response.status === 204 ? undefined : response.json();\n };\n const action = (id, run) => {\n element(id).addEventListener('click', async () => {\n element(id).disabled = true;\n try { await run(); } catch { status('Target request failed; read target again before retrying a write.'); }\n finally { element(id).disabled = false; }\n });\n };\n const refreshAccounts = async () => {\n const declarations = await request('/oauth');\n const accounts = declarations.find((entry) => entry.key === 'login')?.accounts ?? [];\n element('accounts').replaceChildren();\n for (const account of accounts) {\n const row = document.createElement('li');\n row.textContent = account.label + (account.isDefault ? ' (default)' : '');\n const choose = document.createElement('button');\n choose.type = 'button';\n choose.textContent = 'Use ' + account.label;\n choose.addEventListener('click', async () => {\n choose.disabled = true;\n try {\n await request('/oauth/login/default', 'POST', { accountId: account.id });\n await refreshAccounts();\n status('Default test account read back from target.');\n } catch { status('Account change not confirmed; read target again.'); }\n finally { choose.disabled = false; }\n });\n row.append(document.createTextNode(' '), choose);\n element('accounts').append(row);\n }\n };\n const readTarget = async () => {\n const preferences = await request('/kv');\n element('displayLabel').value = preferences.displayLabel ?? '';\n element('notifications').checked = preferences.notifications === true;\n element('language').value = preferences.language ?? 'en';\n element('lastField').value = preferences.lastField ?? '';\n const secrets = await request('/secrets');\n element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved\n ? 'Test key saved on target (value is not returned)' : 'No test key saved';\n await refreshAccounts();\n status('Target Host state read.');\n };\n const savePreferences = async (patch) => {\n // /kv replaces an object. Preserve unrelated keys; concurrent-edit semantics remain the plugin's.\n const preferences = { ...await request('/kv'), ...patch };\n await request('/kv', 'PUT', preferences);\n const confirmed = await request('/kv');\n status('Ordinary settings read back: ' + confirmed.displayLabel);\n };\n element('preferences').addEventListener('submit', async (event) => {\n event.preventDefault();\n const submit = element('preferences').querySelector('[type=\"submit\"]');\n if (submit.disabled) return;\n submit.disabled = true;\n try {\n await savePreferences({\n displayLabel: element('displayLabel').value,\n notifications: element('notifications').checked,\n language: element('language').value,\n });\n } catch { status('Save not confirmed; read target again.'); }\n finally { submit.disabled = false; }\n });\n action('reload', readTarget);\n action('saveSecret', async () => {\n try {\n await request('/secrets/key', 'PUT', { value: element('secret').value });\n const secrets = await request('/secrets');\n element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved\n ? 'Test key saved on target (value is not returned)' : 'No test key saved';\n status('Secret status read back from target.');\n } finally { element('secret').value = ''; }\n });\n action('connect', async () => {\n const result = await request('/oauth/login/connect', 'POST', {});\n await refreshAccounts();\n status(result?.ok ? 'Authorization completed on target.' : 'Authorization did not complete.');\n });\n action('pickDirectory', () => {\n pendingDirectory = 'directory-' + ++sequence;\n channel.postMessage({ kind: 'choose-directory', requestId: pendingDirectory });\n element('directory').textContent = 'Waiting for target directory selection…';\n });\n action('echo', () => {\n pendingProbe = 'probe-' + ++sequence;\n channel.postMessage({ kind: 'probe', requestId: pendingProbe });\n element('channelState').textContent = 'Waiting for channel reply…';\n });\n channel.onmessage = ({ data }) => {\n if (data?.kind === 'directory-result' && data.requestId === pendingDirectory) {\n pendingDirectory = undefined;\n element('directory').textContent = data.cancelled ? 'Directory selection cancelled' : data.name;\n }\n if (data?.kind === 'probe-result' && data.requestId === pendingProbe) {\n pendingProbe = undefined;\n element('channelState').textContent = data.targetLabel;\n }\n };\n for (let index = 1; index <= 16; index++) {\n const label = document.createElement('label');\n label.textContent = 'Unsaved scroll probe ' + index;\n const input = document.createElement('input');\n input.id = 'scrollProbe' + index;\n input.placeholder = 'Local page draft only';\n label.append(input);\n element('longFields').append(label);\n }\n element('longForm').addEventListener('submit', async (event) => {\n event.preventDefault();\n const submit = element('longForm').querySelector('[type=\"submit\"]');\n if (submit.disabled) return;\n submit.disabled = true;\n try { await savePreferences({ lastField: element('lastField').value }); }\n catch { status('Bottom field save not confirmed; read target again.'); }\n finally { submit.disabled = false; }\n });\n window.addEventListener('pagehide', () => {\n pendingDirectory = undefined;\n pendingProbe = undefined;\n element('secret').value = '';\n channel.close();\n }, { once: true });\n readTarget().catch(() => status('Cannot read target Host. No fallback data was substituted.'));\n})();\n"
+ "settings.html": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>QA original plugin settings</title>\n <style>\n * { box-sizing: border-box; }\n body { margin: 0; padding: 16px; font: 16px/1.5 system-ui, sans-serif; color: var(--text-primary, CanvasText); background: var(--surface, Canvas); }\n main { width: 100%; max-width: 40rem; margin: auto; }\n h1, h2 { font-size: 18px; line-height: 1.4; }\n fieldset { min-width: 0; margin: 16px 0; padding: 12px; border: 1px solid var(--border-default, GrayText); }\n label { display: block; margin: 12px 0; }\n input:not([type=\"checkbox\"]), select, textarea { display: block; width: 100%; margin-top: 4px; padding: 8px; font: inherit; color: inherit; background: var(--surface-elevated, Field); border: 1px solid var(--border-default, GrayText); }\n button { min-height: 44px; max-width: 100%; padding: 8px 12px; margin: 4px 0; font: inherit; white-space: normal; color: inherit; background: var(--surface-elevated, ButtonFace); border: 1px solid var(--border-default, GrayText); }\n output, li { overflow-wrap: anywhere; }\n :focus-visible { outline: 2px solid var(--focus-ring, Highlight); outline-offset: 2px; }\n </style>\n </head>\n <body>\n <main>\n <a href=\"navigation.html\" style=\"display:block;min-height:44px;line-height:44px;color:inherit\">Open document B</a>\n <h1>QA original plugin settings</h1>\n <p>TEST DATA ONLY · original HTML fixture · no file import</p>\n <output id=\"status\" role=\"status\" aria-live=\"polite\">Reading target Host…</output>\n <form id=\"preferences\">\n <fieldset>\n <legend>Ordinary settings on the target Host</legend>\n <label>Display label <input id=\"displayLabel\" name=\"displayLabel\" required maxlength=\"80\"></label>\n <label><input id=\"notifications\" name=\"notifications\" type=\"checkbox\"> Notifications</label>\n <label>Language <select id=\"language\" name=\"language\"><option value=\"en\">English</option><option value=\"zh-CN\">简体中文</option></select></label>\n <button type=\"submit\">Save ordinary settings</button>\n <button id=\"reload\" type=\"button\">Read target again</button>\n </fieldset>\n </form>\n <fieldset>\n <legend>Write-only synthetic secret</legend>\n <output id=\"secretState\">Status unknown</output>\n <label>Test key <input id=\"secret\" type=\"password\" autocomplete=\"off\" placeholder=\"Use an invalid QA value only\"></label>\n <button id=\"saveSecret\" type=\"button\">Save test key to target</button>\n </fieldset>\n <fieldset>\n <legend>OAuth accounts</legend>\n <ul id=\"accounts\"></ul>\n <button id=\"connect\" type=\"button\">Connect a test account</button>\n </fieldset>\n <fieldset>\n <legend>Directory and original channel interaction</legend>\n <button id=\"pickDirectory\" type=\"button\">Choose a directory on the target</button>\n <output id=\"directory\">No directory selected</output>\n <button id=\"echo\" type=\"button\">Send channel probe</button>\n <output id=\"channelState\">No reply received</output>\n </fieldset>\n <form id=\"longForm\">\n <fieldset>\n <legend>Long form: keyboard and scroll</legend>\n <div id=\"longFields\"></div>\n <label>Last field <textarea id=\"lastField\" rows=\"4\" placeholder=\"Keep this draft while opening the keyboard or changing theme\"></textarea></label>\n <button type=\"submit\">Save bottom field</button>\n </fieldset>\n </form>\n </main>\n <script src=\"settings.js\"></script>\n </body>\n</html>\n",
+ "settings.js": "// Test-only original plugin code: no local persistence, production ID branching, or external fetch.\n(() => {\n const element = (id) => document.getElementById(id);\n const status = (text) => { element('status').textContent = text; };\n const channel = new BroadcastChannel('qa-settings');\n let sequence = 0;\n let pendingDirectory;\n let pendingProbe;\n const request = async (path, method = 'GET', body) => {\n const response = await fetch(path, {\n method,\n ...(body === undefined ? {} : {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n }),\n });\n if (!response.ok) throw new Error('Target request failed: ' + response.status);\n return response.status === 204 ? undefined : response.json();\n };\n const action = (id, run) => {\n element(id).addEventListener('click', async () => {\n element(id).disabled = true;\n try { await run(); } catch { status('Target request failed; read target again before retrying a write.'); }\n finally { element(id).disabled = false; }\n });\n };\n const refreshAccounts = async () => {\n const declarations = await request('/oauth');\n const accounts = declarations.find((entry) => entry.key === 'login')?.accounts ?? [];\n element('accounts').replaceChildren();\n for (const account of accounts) {\n const row = document.createElement('li');\n row.textContent = account.label + (account.isDefault ? ' (default)' : '');\n const choose = document.createElement('button');\n choose.type = 'button';\n choose.textContent = 'Use ' + account.label;\n choose.addEventListener('click', async () => {\n choose.disabled = true;\n try {\n await request('/oauth/login/default', 'POST', { accountId: account.id });\n await refreshAccounts();\n status('Default test account read back from target.');\n } catch { status('Account change not confirmed; read target again.'); }\n finally { choose.disabled = false; }\n });\n row.append(document.createTextNode(' '), choose);\n element('accounts').append(row);\n }\n };\n const readTarget = async () => {\n const preferences = await request('/kv');\n element('displayLabel').value = preferences.displayLabel ?? '';\n element('notifications').checked = preferences.notifications === true;\n element('language').value = preferences.language ?? 'en';\n element('lastField').value = preferences.lastField ?? '';\n const secrets = await request('/secrets');\n element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved\n ? 'Test key saved on target (value is not returned)' : 'No test key saved';\n await refreshAccounts();\n status('Target Host state read.');\n };\n const savePreferences = async (patch) => {\n // /kv replaces an object. Preserve unrelated keys; concurrent-edit semantics remain the plugin's.\n const preferences = { ...await request('/kv'), ...patch };\n await request('/kv', 'PUT', preferences);\n const confirmed = await request('/kv');\n status('Ordinary settings read back: ' + confirmed.displayLabel);\n };\n element('preferences').addEventListener('submit', async (event) => {\n event.preventDefault();\n const submit = element('preferences').querySelector('[type=\"submit\"]');\n if (submit.disabled) return;\n submit.disabled = true;\n try {\n await savePreferences({\n displayLabel: element('displayLabel').value,\n notifications: element('notifications').checked,\n language: element('language').value,\n });\n } catch { status('Save not confirmed; read target again.'); }\n finally { submit.disabled = false; }\n });\n action('reload', readTarget);\n action('saveSecret', async () => {\n try {\n await request('/secrets/key', 'PUT', { value: element('secret').value });\n const secrets = await request('/secrets');\n element('secretState').textContent = secrets.find((entry) => entry.key === 'key')?.saved\n ? 'Test key saved on target (value is not returned)' : 'No test key saved';\n status('Secret status read back from target.');\n } finally { element('secret').value = ''; }\n });\n action('connect', async () => {\n const result = await request('/oauth/login/connect', 'POST', {});\n await refreshAccounts();\n status(result?.ok ? 'Authorization completed on target.' : 'Authorization did not complete.');\n });\n action('pickDirectory', () => {\n pendingDirectory = 'directory-' + ++sequence;\n channel.postMessage({ kind: 'choose-directory', requestId: pendingDirectory });\n element('directory').textContent = 'Waiting for target directory selection…';\n });\n action('echo', () => {\n pendingProbe = 'probe-' + ++sequence;\n channel.postMessage({ kind: 'probe', requestId: pendingProbe });\n element('channelState').textContent = 'Waiting for channel reply…';\n });\n channel.onmessage = ({ data }) => {\n if (data?.kind === 'directory-result' && data.requestId === pendingDirectory) {\n pendingDirectory = undefined;\n element('directory').textContent = data.cancelled ? 'Directory selection cancelled' : data.name;\n }\n if (data?.kind === 'probe-result' && data.requestId === pendingProbe) {\n pendingProbe = undefined;\n element('channelState').textContent = data.targetLabel;\n }\n };\n for (let index = 1; index <= 16; index++) {\n const label = document.createElement('label');\n label.textContent = 'Unsaved scroll probe ' + index;\n const input = document.createElement('input');\n input.id = 'scrollProbe' + index;\n input.placeholder = 'Local page draft only';\n label.append(input);\n element('longFields').append(label);\n }\n element('longForm').addEventListener('submit', async (event) => {\n event.preventDefault();\n const submit = element('longForm').querySelector('[type=\"submit\"]');\n if (submit.disabled) return;\n submit.disabled = true;\n try { await savePreferences({ lastField: element('lastField').value }); }\n catch { status('Bottom field save not confirmed; read target again.'); }\n finally { submit.disabled = false; }\n });\n window.addEventListener('pagehide', () => {\n pendingDirectory = undefined;\n pendingProbe = undefined;\n element('secret').value = '';\n channel.close();\n }, { once: true });\n readTarget().catch(() => status('Cannot read target Host. No fallback data was substituted.'));\n})();\n",
+ "navigation.html": "<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>QA document B</title><style>body{margin:0;padding:16px;font:16px/1.5 system-ui;color:var(--text-primary,CanvasText);background:var(--surface,Canvas)}a{display:block;min-height:44px;line-height:44px;color:inherit}</style></head><body><h1>Document B</h1><p id=\"result\">Reading document identity</p><a href=\"settings.html\">Return to document A</a><script src=\"navigation.js\"></script></body></html>",
+ "navigation.js": "fetch('/kv').then(response => response.json()).then(value => { document.getElementById('result').textContent = 'Host document epoch: ' + value.documentEpoch; }).catch(() => { document.getElementById('result').textContent = 'Document read failed'; });"
}
diff --git a/apps/mobile/src/plugins/PluginSettingsCard.tsx b/apps/mobile/src/plugins/PluginSettingsCard.tsx
index 7411b241a9..50b9703e74 100644
--- a/apps/mobile/src/plugins/PluginSettingsCard.tsx
+++ b/apps/mobile/src/plugins/PluginSettingsCard.tsx
@@ -341,6 +341,16 @@ export function PluginSettingsCard(props: PluginSettingsCardProps) {
clientRef.current = client;
documentChannels.current = {
send(command, epoch) {
+ if (command.kind === "fetch") {
+ // Wait for document activation, but never let a fetch waiting for a native
+ // prompt block navigation from cancelling that same prompt on Host.
+ const { path, method, body } = command;
+ return channelQueue.then(() => {
+ check();
+ if (epoch !== documentEpoch.current) throw new Error("PLUGIN_SETTINGS_CLOSED");
+ return client!.fetch(path, method, body);
+ });
+ }
const work = channelQueue.then(async () => {
check();
if (epoch !== documentEpoch.current) throw new Error("PLUGIN_SETTINGS_CLOSED");
@@ -355,10 +365,13 @@ export function PluginSettingsCard(props: PluginSettingsCardProps) {
return work;
},
reset() {
+ const epoch = documentEpoch.current;
// Keep the lease/authorization, but release A's channels before B can subscribe.
// Host unsubscribe also removes buffered events for those channels.
channelQueue = channelQueue.then(async () => {
check();
+ if (client!.document.documentIsolation)
+ await client!.send({ kind: "document", epoch });
for (const channel of channels) {
await client!.send({ kind: "unsubscribe", channel });
channels.delete(channel);
@@ -609,13 +622,11 @@ export function PluginSettingsCard(props: PluginSettingsCardProps) {
!foregroundRef.current ||
authorizationActive.current
? Promise.reject(new Error("PLUGIN_SETTINGS_COVERED"))
- : command.kind === "fetch"
- ? client.fetch(command.path, command.method, command.body)
- : ["subscribe", "unsubscribe", "post"].includes(command.kind)
- ? documentChannels.current!.send(command, requestDocument)
- : Promise.reject(
- new Error("PLUGIN_SETTINGS_COMMAND_BLOCKED"),
- );
+ : ["fetch", "subscribe", "unsubscribe", "post"].includes(command.kind)
+ ? documentChannels.current!.send(command, requestDocument)
+ : Promise.reject(
+ new Error("PLUGIN_SETTINGS_COMMAND_BLOCKED"),
+ );
if (command.kind === "fetch") command.body = undefined;
void work
.then((value) => {
diff --git a/apps/mobile/src/plugins/pluginSettingsClient.ts b/apps/mobile/src/plugins/pluginSettingsClient.ts
index a57cbcb473..3a78585854 100644
--- a/apps/mobile/src/plugins/pluginSettingsClient.ts
+++ b/apps/mobile/src/plugins/pluginSettingsClient.ts
@@ -26,6 +26,7 @@ export interface PluginSettingsDocument {
entry: string;
files: PluginPageFile[];
controllerAuthorization?: true;
+ documentIsolation?: true;
}
export interface PluginSettingsSession {
request(request: PluginOauthRequest): Promise<unknown>;
@@ -103,6 +104,7 @@ export function parsePluginSettingsDocument(
name: doc.name,
entry: doc.entry,
files: doc.files.map((file) => ({ ...file })),
+ ...(doc.documentIsolation === true ? { documentIsolation: true as const } : {}),
...(doc.controllerAuthorization === true ? { controllerAuthorization: true as const } : {}),
};
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index f0dd29ed98..38cf38c4e1 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3044,3 +3044,16 @@ namespace + id 下同一插件的有界 JSON 请求;`deviceSync: true` 是独
桌面远程任务归档时,每台设备总是直取一次带 `sessionBindings: true` 的 `maker:schedule:list`(最多等
1.5 秒;失败或超时回退本地镜像里已有的快照,没有则按无绑定处理,离线设备因此每次最多多等 1.5 秒);
手机归档确认同样只发一次带该投影参数的 `maker:schedule:list`,同样有界。两端都只请求绑定投影,不拉完整列表。
+
+## 原插件设置页的文档来源隔离
+
+`settings:open` 可选返回 `documentIsolation: true`;新手机仅见到明确标记后才在既有
+加密 settings 通道发送 `{ kind: "document", epoch }`。epoch 是单租约内递增的正安全整数,
+相同值幂等、较旧值拒绝;不增加 channel、权限或持久化字段。Host 每代生成的 UUID
+继续使用插件既有 `mobilePageId` 契约,旧来源只保留同租约通知投递资格,不能创建或回答
+新确认、目录选择或其它交互。关闭租约清理全部来源。
+
+旧手机连接新 Host 时忽略新增能力、沿用旧语义;新手机连接旧 Host 时不发新命令,
+配置读取、保存与包内导航照旧,完整跨文档确认隔离须两端都更新。插件本身无需更新,
+不改变已装批准、凭证、KV、版本或原生指纹。实现与时序验证见
+[原配置页协议](../remote-plugin-oauth.md#手机原配置页授权的增量能力)。
diff --git a/docs/remote-plugin-oauth.md b/docs/remote-plugin-oauth.md
index 8ecf84c67f..24060eb435 100644
--- a/docs/remote-plugin-oauth.md
+++ b/docs/remote-plugin-oauth.md
@@ -269,6 +269,19 @@ remote context 接线一同发布;通用 OAuth capabilities 存在不代表原
新文档;旧 BroadcastChannel 订阅先释放,再建立新文档订阅。已经从 Host 消费的普通通知
仍按当前账号、目标与租约投递,不因文档切换丢失。
+Host 文档可选声明 `documentIsolation: true`。支持此能力的手机在每次文档加载时先发送
+`document`(递增 epoch),再放行该文档的 fetch、频道操作和 poll。Host 为每代文档生成
+新的、不透明的 UUID 来源,仍通过现有 `mobilePageId` 字段交给插件;插件继续原样回传,
+无需改包、重装或重新批准。切代立即取消旧确认和目录选择;旧来源迟到的新请求、旧回答、
+目录校验中的迟到完成与延迟 fetch 确认均不能作用于新文档。已启动的旧 poll 也不能带走
+新文档的确认。普通通知可由已退役来源投递到仍有效的同一租约,身份和插件校验不变。
+来源映射只在内存中,每个租约最多 1024 个文档,关闭时全部释放;达到上限走现有配置
+重载入口取得新租约,不重放写操作。
+
+该能力是双端增量:旧手机忽略标记,新 Host 在未收到 document 命令前保留旧页面语义;
+新手机连接旧 Host 不发送未知命令,保留原配置功能与已有本地 epoch 保护,但未轮询到的
+旧确认隔离仍需升级 Host。无服务端、持久化或原生 fingerprint 变更。
+
管理操作回执丢失时,手机详情显示“结果未确认”及“核实结果”入口。查询沿用原 operationId,
期间保持写操作和配置页停用;不重放 begin,核实终态并读回快照后恢复对应操作。
diff --git a/packages/device-link/src/__tests__/pluginSettings.test.ts b/packages/device-link/src/__tests__/pluginSettings.test.ts
index 7a5b7e57bf..4c2bb7d118 100644
--- a/packages/device-link/src/__tests__/pluginSettings.test.ts
+++ b/packages/device-link/src/__tests__/pluginSettings.test.ts
@@ -32,6 +32,7 @@ describe("sealed original settings commands", () => {
},
{ kind: "authorize", path: "/oauth/account/connect" },
{ kind: "authorization-result", requestId: "authorization-1" },
+ { kind: "document", epoch: 1 },
{ kind: "close" },
])("parses the settings envelope for $kind", (command) => {
expect(parsePluginSettingsRequest(request(command))).toEqual(
@@ -72,6 +73,10 @@ describe("sealed original settings commands", () => {
{ kind: "answer-directory", requestId: "directory-1", path: 42 },
{ kind: "authorization-result", requestId: "../elsewhere" },
{ kind: "close", path: "/kv" },
+ { kind: "document", epoch: 0 },
+ { kind: "document", epoch: 1.5 },
+ { kind: "document", epoch: Number.MAX_SAFE_INTEGER + 1 },
+ { kind: "document", epoch: 1, sourceId: "forged" },
{ kind: "unknown" },
])("rejects malformed or ambiguous $kind commands", (command) => {
expect(parsePluginSettingsRequest(request(command))).toBeNull();
diff --git a/packages/device-link/src/pluginSettings.ts b/packages/device-link/src/pluginSettings.ts
index d42bb413ba..e74b8ebf3f 100644
--- a/packages/device-link/src/pluginSettings.ts
+++ b/packages/device-link/src/pluginSettings.ts
@@ -2,6 +2,7 @@ export const PLUGIN_SETTINGS_ACTION = "settings-page";
const oauthId = (value: unknown): value is string =>
typeof value === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value);
export type PluginSettingsCommand =
+ | { kind: "document"; epoch: number }
| { kind: "fetch"; path: string; method: string; body?: string }
| { kind: "asset"; path: string; offset: number }
| { kind: "subscribe"; channels: string[] }
@@ -53,6 +54,9 @@ export function parsePluginSettingsRequest(
/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(name);
let valid = false;
switch (c.kind) {
+ case "document":
+ valid = exact(["kind", "epoch"]) && Number.isSafeInteger(c.epoch) && (c.epoch as number) > 0;
+ break;
case "fetch":
valid =
exact([