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(remote-management): 修复技能取消与设置页连接续签

nana78901a44ec50
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 9eb376c8e4..66405d372b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
@@ -293,6 +293,28 @@ describe('original remote plugin settings', () => {
expect(f.stored.get('/secrets/key')).toContain('submitted-once');
expect(f.deps.trustIdentity).toHaveBeenCalledTimes(1);
});
+ 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()));
+ const now = Date.now();
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(now);
+ try {
+ for (const elapsed of [100_000, 200_000, 241_000]) {
+ clock.mockReturnValue(now + elapsed);
+ const responses = await Promise.all(pages.map(({ fetch }) => fetch('/secrets')));
+ expect(responses.map((response) => response.status)).toEqual([200, 200, 200, 200]);
+ }
+ expect(f.deps.trustIdentity).toHaveBeenCalledTimes(8);
+ expect(f.disconnect).not.toHaveBeenCalled();
+ expect(
+ (await pages[0].fetch('/secrets/key', { method: 'PUT', body: '{"value":"renewed"}' }))
+ .status,
+ ).toBe(200);
+ expect(f.stored.get('/secrets/key')).toContain('renewed');
+ } finally {
+ clock.mockRestore();
+ }
+ });
it.each(['owner', 'revision', 'revoke', 'peer'] as const)(
'rejects a late write after %s changes',
async (change) => {
diff --git a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
index 6cf87f859a..6eee0a79be 100644
--- a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
+++ b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
@@ -193,10 +193,13 @@ 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();
exchange = await authenticateOauthController({
@@ -230,7 +233,13 @@ export async function openRemotePluginSettings(
}
assertCurrent();
sent++;
- return exchange!({ op: 'settings', id: doc.pageId, command });
+ const response = exchange!({ op: 'settings', id: doc.pageId, command });
+ inFlight.add(response);
+ try {
+ return await response;
+ } finally {
+ inFlight.delete(response);
+ }
};
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.ts
index e14160b33d..1f926d201c 100644
--- a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts
+++ b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts
@@ -36,7 +36,12 @@ function fixture(ghostId = 'test-plugin', controllerDeviceId?: string, settingsP
identity: () => identity,
owner: () => owner,
available: () => true,
- bind: async () => ({ ghostId, controllerDeviceId, ...(settingsPage ? { settingsPage: true as const } : {}), current: () => current }),
+ bind: async () => ({
+ ghostId,
+ controllerDeviceId,
+ ...(settingsPage ? { settingsPage: true as const } : {}),
+ current: () => current,
+ }),
request,
now: () => now,
});
@@ -166,6 +171,75 @@ describe('signed OAuth transport with explicit peer trust', () => {
await expect(f.host.request('desktop', frame())).rejects.toThrow();
expect(f.request).toHaveBeenCalledTimes(1);
});
+ it('replaces only the same peer and settings page without exhausting the connection quota', async () => {
+ const f = fixture('test-plugin', undefined, true);
+ const settingsAction = { requestId: 'page-1', actionId: 'settings-page', expectedRevision: 0 };
+ const options = { ...f.options, action: settingsAction };
+ const calls = [];
+ for (let i = 0; i < 4; i++) {
+ calls.push(
+ await authenticateOauthController({
+ ...options,
+ action: { ...settingsAction, requestId: `page-${i + 1}` },
+ }),
+ );
+ }
+ const otherPeer = await authenticateOauthController({
+ ...options,
+ peer: 'desktop-b',
+ invoke: (raw) => f.host.request('desktop-b', raw),
+ });
+ for (let i = 0; i < 6; i++) {
+ const renewed = await authenticateOauthController(options);
+ await expect(
+ renewed({ op: 'settings', id: 'page-1', command: { kind: 'poll', after: 0 } }),
+ ).resolves.toBeDefined();
+ }
+ await expect(
+ authenticateOauthController({
+ ...options,
+ action: { ...settingsAction, requestId: 'page-5' },
+ }),
+ ).rejects.toThrow();
+ await expect(
+ calls[1]({ op: 'settings', id: 'page-2', command: { kind: 'poll', after: 0 } }),
+ ).resolves.toBeDefined();
+ await expect(
+ 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('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.ts
index 1303411c3e..3ef31935be 100644
--- a/apps/desktop/src/main/plugin-oauth/authentication.ts
+++ b/apps/desktop/src/main/plugin-oauth/authentication.ts
@@ -82,6 +82,7 @@ interface Connection {
binding: OauthCardBinding;
started: boolean;
finished: boolean;
+ pending: number;
innerId?: string;
messages: Map<string, { box: string; promise: Promise<unknown> }>;
}
@@ -156,15 +157,27 @@ export class AuthenticatedOauthHost {
if ((raw as { op?: unknown })?.op === 'hello') {
const hello = parsePluginOauthHello(raw);
for (const [id, c] of this.connections) if (c.finished) this.connections.delete(id);
- if (
- this.connections.size >= 16 ||
- [...this.connections.values()].filter((c) => c.peer === peer).length >= 4
- )
- throw fail();
const generation = this.generation,
peerGeneration = this.peerGenerations.get(peer) ?? 0;
const binding = await this.deps.bind(hello.action);
+ const previous = binding?.settingsPage
+ ? [...this.connections.values()].filter(
+ (c) =>
+ c.peer === peer &&
+ c.binding.settingsPage &&
+ c.binding.ghostId === binding.ghostId &&
+ 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));
if (
!binding?.current() ||
(binding.controllerDeviceId !== undefined && binding.controllerDeviceId !== peer) ||
@@ -173,8 +186,8 @@ export class AuthenticatedOauthHost {
generation !== this.generation ||
peerGeneration !== (this.peerGenerations.get(peer) ?? 0) ||
currentIdentity?.key !== identity.key ||
- this.connections.size >= 16 ||
- [...this.connections.values()].filter((c) => c.peer === peer).length >= 4
+ remaining.length >= 16 ||
+ remaining.filter((c) => c.peer === peer).length >= 4
)
throw fail();
const key = new OauthBox(),
@@ -189,6 +202,15 @@ export class AuthenticatedOauthHost {
ghostId: binding.ghostId,
expiresAtMs,
};
+ const signature = identity.key.sign(
+ transcript(
+ hello,
+ reply,
+ { ...identity, publicKey: identity.key.descriptor.publicKey },
+ peer,
+ ),
+ );
+ for (const c of replaceable) this.connections.delete(c.id);
this.connections.set(id, {
id,
peer,
@@ -199,18 +221,12 @@ export class AuthenticatedOauthHost {
binding,
started: false,
finished: false,
+ pending: 0,
messages: new Map(),
});
return {
...reply,
- signature: identity.key.sign(
- transcript(
- hello,
- reply,
- { ...identity, publicKey: identity.key.descriptor.publicKey },
- peer,
- ),
- ),
+ signature,
};
}
const v = oauthExact(raw, ['op', 'id', 'box']);
@@ -244,6 +260,7 @@ 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);
@@ -278,7 +295,9 @@ export class AuthenticatedOauthHost {
}),
};
}
- })();
+ })().finally(() => {
+ c.pending--;
+ });
c.messages.set(requestNonce, { box: v.box, promise });
return promise;
}
diff --git a/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.ts b/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.ts
index 03be552ce3..b82f051beb 100644
--- a/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.ts
@@ -278,6 +278,80 @@ describe('remote Skills reuse the Host instances and mutation services', () => {
expect((await invoke('operation', { operationId: 'cancel' })).phase).toBe('cancelled');
expect(mutate).not.toHaveBeenCalled();
});
+ it('cancels a running update before its commit without replaying the operation', async () => {
+ let start!: () => void, finish!: () => void;
+ const started = new Promise<void>((resolve) => {
+ start = resolve;
+ });
+ const downloaded = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ let committed = false;
+ mutate.mockImplementationOnce(async (_kind, _record, _market, current) => {
+ start();
+ await downloaded;
+ if (!current()) throw new Error('CANCELLED');
+ committed = true;
+ });
+ const input = {
+ operationId: 'running-cancel',
+ kind: 'update',
+ expectedRevision: 'r1',
+ version: '2.0.0',
+ };
+ const receipt = await invoke('begin', input, 'global-instance');
+ await invoke('answer', {
+ operationId: receipt.operationId,
+ requestId: receipt.confirmation!.requestId,
+ accepted: true,
+ });
+ await started;
+ await expect(
+ invoke('cancel', { operationId: receipt.operationId }, undefined, 'control-b'),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await invoke('cancel', { operationId: receipt.operationId });
+ finish();
+ await vi.waitFor(async () =>
+ expect((await invoke('operation', { operationId: receipt.operationId })).phase).toBe(
+ 'cancelled',
+ ),
+ );
+ expect(committed).toBe(false);
+ expect((await invoke('begin', input, 'global-instance')).phase).toBe('cancelled');
+ expect(mutate).toHaveBeenCalledOnce();
+ });
+ it('preserves a committed result when cancellation arrives before the receipt settles', async () => {
+ let start!: () => void, finish!: () => void;
+ const committed = new Promise<void>((resolve) => {
+ start = resolve;
+ });
+ const completed = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ mutate.mockImplementationOnce(async () => {
+ start();
+ await completed;
+ });
+ const receipt = await invoke(
+ 'begin',
+ { operationId: 'late-cancel', kind: 'update', expectedRevision: 'r1', version: '2.0.0' },
+ 'global-instance',
+ );
+ await invoke('answer', {
+ operationId: receipt.operationId,
+ requestId: receipt.confirmation!.requestId,
+ accepted: true,
+ });
+ await committed;
+ await invoke('cancel', { operationId: receipt.operationId });
+ finish();
+ await vi.waitFor(async () =>
+ expect((await invoke('operation', { operationId: receipt.operationId })).phase).toBe(
+ 'succeeded',
+ ),
+ );
+ expect(mutate).toHaveBeenCalledOnce();
+ });
it('allocates one receipt for overlapping requests with the same operation id', async () => {
const input = { operationId: 'overlap', kind: 'uninstall', expectedRevision: 'r1' };
const [first, second] = await Promise.all([
diff --git a/apps/desktop/src/main/skillhub/remoteManagement.ts b/apps/desktop/src/main/skillhub/remoteManagement.ts
index 4bb3331301..f658df6b39 100644
--- a/apps/desktop/src/main/skillhub/remoteManagement.ts
+++ b/apps/desktop/src/main/skillhub/remoteManagement.ts
@@ -43,6 +43,7 @@ type Operation = {
peer: string;
fingerprint: string;
receipt: RemoteSkillReceipt;
+ cancelled: boolean;
current(): boolean;
visible(): boolean;
run(): Promise<void>;
@@ -77,6 +78,8 @@ export class RemoteSkillsManagement<T> {
if (request.actionId === 'management:cancel' || request.actionId === 'management:answer') {
const operation = this.operation(peer, input.operationId);
if (request.actionId === 'management:cancel') {
+ if (['confirmation', 'running'].includes(operation.receipt.phase))
+ operation.cancelled = true;
if (operation.receipt.phase === 'confirmation')
operation.receipt = { operationId: operation.receipt.operationId, phase: 'cancelled' };
} else if (operation.receipt.phase === 'confirmation') {
@@ -261,13 +264,15 @@ export class RemoteSkillsManagement<T> {
peer,
fingerprint,
receipt,
+ cancelled: false,
...access,
+ current: () => !operation.cancelled && access.current(),
timer: setTimeout(() => {
this.operations.delete(operationId);
}, 15 * 60_000),
run: async () => {
try {
- if (!access.current()) fail('NOT_FOUND');
+ if (!operation.current()) fail('NOT_FOUND');
if (
record &&
!(await this.deps.scan()).some(
@@ -276,7 +281,7 @@ export class RemoteSkillsManagement<T> {
)
)
fail('NOT_FOUND');
- if (!access.current()) fail('NOT_FOUND');
+ if (!operation.current()) fail('NOT_FOUND');
if (
project &&
!(await this.deps.projects!()).some(
@@ -284,10 +289,10 @@ export class RemoteSkillsManagement<T> {
)
)
fail('NOT_FOUND');
- await this.deps.mutate(kind, record, market, access.current, project);
+ await this.deps.mutate(kind, record, market, operation.current, project);
operation.receipt = { operationId, phase: 'succeeded' };
} catch {
- operation.receipt = { operationId, phase: 'failed' };
+ operation.receipt = { operationId, phase: operation.cancelled ? 'cancelled' : 'failed' };
}
},
};
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 0ddbf5c52d..c66befc64b 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -2246,6 +2246,9 @@ KV、secret、OAuth、connection 与原 BroadcastChannel 请求通过已有 v3
版本和连接代次在真实执行前复核。新增命令有严格白名单及大小限制;密封 callback 上限
追加到 144KB,以容纳原设置页 64KiB 请求及 JSON 转义,原 OAuth 各内层契约的限制不变。
旧端未声明能力时不发送新 op,不回退到未加密请求。
+设置页续签只替换同一控制设备、同一页面与同一插件的旧握手,等待在途响应完成后回收,
+不关闭页面或重放写请求。v3 消息格式和每 Host 16/每 peer 4 个连接、每连接 1024 条消息
+的上限不变;旧控制端兼容新版 Host,完整续签回收需要更新目标 Host。
原 /oauth/<key>/connect 先生成绑定页面的一次性 ticket,沿现有 v3 浏览器授权桥执行
目标原端点;原 HTTP 结果送回 settings.js。已有账户只读脱敏原端点投影,令牌保存在 B。
@@ -2276,6 +2279,8 @@ Claude 原生 `user` 范围投影为 `global`;控制端读取早期 Host 的 `
发送技能 `management:answer`。确认不占用目标安装锁;批准后重读实体版本,安装器在原锁和
跨进程租约内、下载解包后复核目标及授权目录,继续复用备份和回滚。卸载在租约内再次复核后
复用系统回收站。启停、已提交结果与取消分别表达;离线只查原回执,不重放写操作。
+运行中取消通过原 mutation guard 进入安装器的提交前检查;操作结束后记录取消结果,
+已经提交的成功结果仍保留,不将取消回执误当作事务回滚。
现有本机接口、路径授权及原生卸载确认保持原行为。仅新增可选 Main 内部 mutation guard;
不改变协议版本、manifest、运行期 fingerprint 或持久数据格式。手机可通过标准 list/get 读取