Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-management): 避免设置页续签阻塞确认回复
nanaaeedfc49c7d9
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.tsindex 66405d372b..e3c18f84e8 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts@@ -91,7 +91,9 @@ function fixture(namespace: string | null = null) {} as unknown as InstalledGhost;const stored = new Map<string, string>(),controllerStored = new Map<string, string>();- const settingsFetch = vi.fn(+ const settingsFetch = vi.fn<+ NonNullable<ConstructorParameters<typeof MobilePluginPages>[0]['settingsFetch']>+ >(async (_ghost: InstalledGhost,path: string,@@ -293,6 +295,50 @@ describe('original remote plugin settings', () => {expect(f.stored.get('/secrets/key')).toContain('submitted-once');expect(f.deps.trustIdentity).toHaveBeenCalledTimes(1);});+ it('renews while a save awaits confirmation, then returns the original save result', async () => {+ const f = fixture(),+ { fetch } = await f.open();+ const html = await (await fetch('/settings.html')).text();+ const internal = /src="([^"]+\.js)"/.exec(html)![1].slice(0, -3);+ const now = Date.now();+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now);+ let poll: Promise<Response> | undefined;+ let writing: Promise<Response> | undefined;+ try {+ for (const elapsed of [100_000, 200_000, 239_000]) {+ clock.mockReturnValue(now + elapsed);+ expect((await fetch('/secrets')).status).toBe(200);+ }+ f.settingsFetch.mockImplementationOnce(+ async (_ghost, path, _method, body, current, confirmConnection) => {+ if (!(await confirmConnection!('New connection', 'example.invalid')) || !current())+ throw new Error('CLOSED');+ f.stored.set(path, body!);+ return { status: 200, mime: 'application/json', base64: '' };+ },+ );+ mock.dialog.mockResolvedValueOnce({ response: 0 });+ writing = fetch('/connections/account', { method: 'PUT', body: '{"label":"new"}' });+ await vi.waitFor(() => expect(f.settingsFetch).toHaveBeenCalledTimes(4));+ clock.mockReturnValue(now + 241_000);+ poll = fetch(internal, { method: 'POST', body: '{"kind":"poll","after":0}' });+ await vi.waitFor(() => expect(mock.dialog).toHaveBeenCalledTimes(1));+ expect((await poll).status).toBe(200);+ expect((await writing).status).toBe(200);+ expect(f.stored.get('/connections/account')).toBe('{"label":"new"}');+ expect(f.deps.trustIdentity).toHaveBeenCalledTimes(2);+ expect(f.settingsFetch).toHaveBeenCalledTimes(4);+ } finally {+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];+ await f.service.settingsRequest('controller-a', {+ op: 'settings',+ id: pageId,+ command: { kind: 'close' },+ });+ await Promise.allSettled([poll, writing]);+ clock.mockRestore();+ }+ });it('renews all four open settings pages without closing any page or consuming another slot', async () => {const f = fixture();const pages = await Promise.all(Array.from({ length: 4 }, () => f.open()));diff --git a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.tsindex 6eee0a79be..1bde33a367 100644--- a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts+++ b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts@@ -193,12 +193,10 @@ export async function openRemotePluginSettings(const src = origin + '/' + doc.entry;const internal = '/__cindy_remote_settings_' + randomUUID();let exchange: ((request: PluginOauthRequest) => Promise<unknown>) | undefined;- const inFlight = new Set<Promise<unknown>>();let renew: Promise<void> | undefined,renewedAt = 0,sent = 0;const connect = async () => {- await Promise.allSettled(inFlight);assertCurrent();const target = await deps.identity(input.deviceId, assertCurrent);if (target.deviceId !== input.deviceId) throw unavailable();@@ -233,13 +231,7 @@ export async function openRemotePluginSettings(}assertCurrent();sent++;- const response = exchange!({ op: 'settings', id: doc.pageId, command });- inFlight.add(response);- try {- return await response;- } finally {- inFlight.delete(response);- }+ return exchange!({ op: 'settings', id: doc.pageId, command });};await connect();assertCurrent();diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.tsindex 1f926d201c..913e1371b2 100644--- a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts+++ b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts@@ -8,6 +8,7 @@ import {import { OauthBox } from '../box.js';import {parsePluginOauthHelloReply,+ PLUGIN_OAUTH_TTL_MS,type PluginOauthAction,type PluginOauthPeerIdentity,} from '@cindy/device-link';@@ -208,38 +209,57 @@ describe('signed OAuth transport with explicit peer trust', () => {otherPeer({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } }),).resolves.toBeDefined();});- it('lets an in-flight settings response finish on its original encrypted connection after renewal', async () => {- const f = fixture('test-plugin', undefined, true);- const options = {- ...f.options,- action: { requestId: 'page-1', actionId: 'settings-page', expectedRevision: 0 },- };- const call = await authenticateOauthController(options);- let start!: () => void, finish!: () => void;- const started = new Promise<void>((resolve) => {- start = resolve;- });- const completed = new Promise<void>((resolve) => {- finish = resolve;- });- f.request.mockImplementationOnce(async () => {- start();- await completed;- return { phase: 'starting', marker: 'original-result' };- });- const pending = call({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } });- await started;- const renewal = authenticateOauthController(options);- finish();- await expect(pending).resolves.toMatchObject({ marker: 'original-result' });- const renewed = await renewal;- await expect(- renewed({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } }),- ).resolves.toBeDefined();- await expect(- call({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } }),- ).rejects.toThrow();- });+ it.each(['none', 'owner', 'peer', 'all', 'binding', 'expiry'] as const)(+ 'renews without waiting for a settings response and rechecks %s invalidation before returning it',+ async (change) => {+ const f = fixture('test-plugin', undefined, true);+ const options = {+ ...f.options,+ action: { requestId: 'page-1', actionId: 'settings-page', expectedRevision: 0 },+ };+ const call = await authenticateOauthController(options);+ let start!: () => void, finish!: () => void;+ const started = new Promise<void>((resolve) => {+ start = resolve;+ });+ const completed = new Promise<void>((resolve) => {+ finish = resolve;+ });+ f.request.mockImplementationOnce(async () => {+ start();+ await completed;+ return { phase: 'starting', marker: 'original-result' };+ });+ const pending = call({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } });+ await started;+ let renewed: typeof call | undefined;+ const renewal = authenticateOauthController(options).then((value) => {+ renewed = value;+ });+ try {+ await vi.waitFor(() => expect(renewed).toBeDefined());+ if (change === 'owner') f.owner('different-owner');+ else if (change === 'peer') f.host.invalidate('desktop');+ else if (change === 'all') f.host.invalidate();+ else if (change === 'binding') f.invalidateBinding();+ else if (change === 'expiry') f.now(f.target.observedAtMs + PLUGIN_OAUTH_TTL_MS);+ } finally {+ finish();+ }+ await renewal;+ if (change !== 'none') {+ await expect(pending).rejects.toThrow();+ return;+ }+ await expect(pending).resolves.toMatchObject({ marker: 'original-result' });+ await expect(+ renewed!({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } }),+ ).resolves.toBeDefined();+ await expect(+ call({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } }),+ ).rejects.toThrow();+ },+ );it('rejects a mutated authenticated envelope without invoking the transaction', async () => {const f = fixture(),diff --git a/apps/desktop/src/main/plugin-oauth/authentication.ts b/apps/desktop/src/main/plugin-oauth/authentication.tsindex 3ef31935be..744d635d47 100644--- a/apps/desktop/src/main/plugin-oauth/authentication.ts+++ b/apps/desktop/src/main/plugin-oauth/authentication.ts@@ -82,7 +82,7 @@ interface Connection {binding: OauthCardBinding;started: boolean;finished: boolean;- pending: number;+ current(): boolean;innerId?: string;messages: Map<string, { box: string; promise: Promise<unknown> }>;}@@ -117,7 +117,8 @@ export class AuthenticatedOauthHost {}private assertCurrent(c: Connection): void {if (- this.connections.get(c.id) !== c ||+ (this.connections.get(c.id) !== c && !c.binding.settingsPage) ||+ !c.current() ||c.owner !== this.deps.owner() ||!this.deps.available(c.peer) ||this.now() >= c.expiresAtMs@@ -160,6 +161,7 @@ export class AuthenticatedOauthHost {const generation = this.generation,peerGeneration = this.peerGenerations.get(peer) ?? 0;const binding = await this.deps.bind(hello.action);+ const currentIdentity = await this.deps.identity();const previous = binding?.settingsPage? [...this.connections.values()].filter((c) =>@@ -169,15 +171,7 @@ export class AuthenticatedOauthHost {sameAction(c.hello.action, hello.action),): [];- // Keep each response on its original encrypted connection until it settles.- await Promise.allSettled(- previous.flatMap((c) => [...c.messages.values()].map((m) => m.promise)),- );- const currentIdentity = await this.deps.identity();- const replaceable = previous.filter(- (c) => this.connections.get(c.id) === c && c.pending === 0,- );- const remaining = [...this.connections.values()].filter((c) => !replaceable.includes(c));+ const remaining = [...this.connections.values()].filter((c) => !previous.includes(c));if (!binding?.current() ||(binding.controllerDeviceId !== undefined && binding.controllerDeviceId !== peer) ||@@ -210,7 +204,8 @@ export class AuthenticatedOauthHost {peer,),);- for (const c of replaceable) this.connections.delete(c.id);+ // Retire old keys for new requests; accepted responses keep their original key and lease.+ for (const c of previous) this.connections.delete(c.id);this.connections.set(id, {id,peer,@@ -221,7 +216,10 @@ export class AuthenticatedOauthHost {binding,started: false,finished: false,- pending: 0,+ current: () =>+ generation === this.generation &&+ peerGeneration === (this.peerGenerations.get(peer) ?? 0) &&+ (!binding.settingsPage || binding.current()),messages: new Map(),});return {@@ -260,7 +258,6 @@ export class AuthenticatedOauthHost {} else if (request.op !== 'capabilities' && (!c.innerId || request.id !== c.innerId))throw fail();const requestNonce = payload.nonce;- c.pending++;const promise = (async () => {try {this.assertCurrent(c);@@ -295,9 +292,7 @@ export class AuthenticatedOauthHost {}),};}- })().finally(() => {- c.pending--;- });+ })();c.messages.set(requestNonce, { box: v.box, promise });return promise;}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex c66befc64b..6eec8ce389 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -2246,9 +2246,11 @@ KV、secret、OAuth、connection 与原 BroadcastChannel 请求通过已有 v3版本和连接代次在真实执行前复核。新增命令有严格白名单及大小限制;密封 callback 上限追加到 144KB,以容纳原设置页 64KiB 请求及 JSON 转义,原 OAuth 各内层契约的限制不变。旧端未声明能力时不发送新 op,不回退到未加密请求。-设置页续签只替换同一控制设备、同一页面与同一插件的旧握手,等待在途响应完成后回收,-不关闭页面或重放写请求。v3 消息格式和每 Host 16/每 peer 4 个连接、每连接 1024 条消息-的上限不变;旧控制端兼容新版 Host,完整续签回收需要更新目标 Host。+设置页续签只替换同一控制设备、同一页面与同一插件的旧握手,不等待在途请求,+使轮询和确认回复可经新连接完成。旧连接不再接受新请求;已受理请求仍用原密钥返回,+返回前复核原有效期、owner、控制设备代次和页面租约,不关闭页面或重放写请求。+v3 消息格式和每 Host 16/每 peer 4 个连接、每连接 1024 条消息+的上限不变;旧控制端兼容新版 Host,完整续签交接需要控制端与目标 Host 均更新。原 /oauth/<key>/connect 先生成绑定页面的一次性 ticket,沿现有 v3 浏览器授权桥执行目标原端点;原 HTTP 结果送回 settings.js。已有账户只读脱敏原端点投影,令牌保存在 B。