Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugins): bound sync delivery and invalidate stale grants
zqchris5fac6b2da12f
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.tsindex a63c4b7127..b123bfca96 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts@@ -317,3 +317,83 @@ it.each([2, 32])('counts incoming requests toward the combined %i request budgetexpect(await extra).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });expect(await Promise.all(requests)).toEqual(Array.from({ length: count }, () => ({ ok: false, errorCode: 'SYNC_RESULT_UNKNOWN' })));});++// Async boundary regressions (unit): real encrypted traffic and fake time.+it('releases a timed-out startup so a later healthy plugin frame can proceed', async () => {+ const { a, b, frames, ready, flush } = pair(); await ready();+ let release!: () => void, entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ const loading = new Promise<void>(resolve => { release = resolve; });+ b.deliver.mockImplementationOnce(async (_ghost, msg, valid) => {+ entered(); await loading;+ if (!valid()) return false;+ b.delivered.push(msg); return true;+ });+ const stuck = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: { stuck: true } });+ await Promise.resolve(); await Promise.resolve();+ const first = frames.shift()!; let settled = false;+ const receiving = b.svc.receive(first.from, first.data).then(() => { settled = true; });+ await started; await vi.advanceTimersByTimeAsync(15000);+ const healthy = a.svc.handle('other-sync', { op: 'request', peer: 'b', data: { healthy: true } });+ await Promise.resolve(); await Promise.resolve();+ const second = frames.shift()!;+ const queued = b.svc.receive(second.from, second.data);+ await vi.advanceTimersByTimeAsync(15001);+ expect(settled).toBe(true);+ await receiving; await queued;+ expect(b.delivered.map(m => m.data)).toEqual([{ healthy: true }]);+ await b.svc.handle('other-sync', { op: 'reply', requestId: b.delivered[0].requestId, data: 'stored' });+ await flush(); expect(await healthy).toEqual({ ok: true, data: 'stored' });+ expect(await stuck).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });+ release(); await Promise.resolve(); await Promise.resolve();+ expect(b.delivered).toHaveLength(1);+});++it('rejects pre-replacement frames waiting for keys or behind another frame', async () => {+ const { a, b, frames, ready, flush } = pair(); await ready();+ let release!: () => void, entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ const loading = new Promise<void>(resolve => { release = resolve; });+ b.keys.prepare.mockImplementationOnce(() => { entered(); return loading; });+ const requests = [0, 1].map(n => a.svc.handle('example-sync', { op: 'request', peer: 'b', data: { n } }));+ await Promise.resolve(); await Promise.resolve();+ const receiving = frames.splice(0).map(f => b.svc.receive(f.from, f.data));+ await started; b.g.approval = { state: 'approved', revision: '2' };+ release(); await Promise.all(receiving);+ expect(b.delivered).toHaveLength(0);+ a.svc.reset(); a.svc.setActive(true); await Promise.all(requests);+ const fresh = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: { fresh: true } });+ await Promise.resolve(); await Promise.resolve(); await flush();+ expect(b.delivered.map(m => m.data)).toEqual([{ fresh: true }]);+ a.svc.reset(); await fresh;+});++it('does not revive old inbound or outbound requests when peer access is restored', async () => {+ const { a, b, frames, ready, flush } = pair(); await ready();+ let release!: () => void, entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ const loading = new Promise<void>(resolve => { release = resolve; });+ b.deliver.mockImplementationOnce(async (_ghost, msg, valid) => {+ entered(); await loading;+ if (!valid()) return false;+ b.delivered.push(msg); return true;+ });+ const request = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} });+ await Promise.resolve(); await Promise.resolve();+ const frame = frames.shift()!;+ const receiving = b.svc.receive(frame.from, frame.data);+ await started; b.blocked.add('a'); b.svc.invalidatePeer('a'); b.blocked.delete('a');+ release(); await receiving;+ expect(b.delivered).toHaveLength(0);+ a.svc.reset(); a.svc.setActive(true); await request;+ let releaseKeys!: () => void;+ a.keys.prepare.mockImplementationOnce(() => new Promise<void>(resolve => { releaseKeys = resolve; }));+ const oldGrant = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} });+ a.blocked.add('b'); a.svc.invalidatePeer('b'); a.blocked.delete('b'); releaseKeys();+ expect(await oldGrant).toMatchObject({ errorCode: 'SYNC_OFFLINE' });+ expect(frames).toHaveLength(0);+ const fresh = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: { fresh: true } });+ await Promise.resolve(); await Promise.resolve(); await flush();+ expect(b.delivered.map(m => m.data)).toEqual([{ fresh: true }]);+ a.svc.invalidatePeer('b'); expect(await fresh).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });+});diff --git a/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts b/apps/desktop/src/main/cindy-brain/deviceSyncSlot.tsindex 57b3ed3e7c..7347c9e4aa 100644--- a/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts+++ b/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts@@ -83,6 +83,7 @@ export class PluginDeviceSync {private readonly receiving = new Map<string, Promise<void>>();private receivingCount = 0;private readonly epochs = new Map<string, number>();+ private readonly peerEpochs = new Map<string, number>();constructor(private readonly deps: Deps) {}connect(transport: PluginSyncTransport): void {this.reset();@@ -103,6 +104,7 @@ export class PluginDeviceSync {this.pending.clear();this.incoming.clear();this.keyReplies.clear();+ this.peerEpochs.clear();this.receiving.clear();this.receivingCount = 0;this.scope = this.deps.scope();@@ -121,6 +123,20 @@ export class PluginDeviceSync {this.incoming.delete(id);}}+ invalidatePeer(peer: string): void {+ this.peerEpochs.set(peer, (this.peerEpochs.get(peer) ?? 0) + 1);+ this.keyReplies.delete(peer);+ for (const [id, p] of this.pending) if (p.peer === peer) {+ clearTimeout(p.timer); this.pending.delete(id); p.finish(error('SYNC_RESULT_UNKNOWN'));+ }+ for (const [id, p] of this.incoming) if (p.peer === peer) {+ clearTimeout(p.timer); this.incoming.delete(id);+ }+ }+ private capturePeer(peer: string): () => boolean {+ const epoch = this.peerEpochs.get(peer) ?? 0;+ return () => epoch === (this.peerEpochs.get(peer) ?? 0) && this.transport?.allowed(peer) === true;+ }private capture(instance: string): (() => boolean) | null {const ghost = this.deps.getGhost(instance);if (!identity(ghost)) return null;@@ -173,9 +189,11 @@ export class PluginDeviceSync {}}if (raw.op !== 'request' || typeof raw.peer !== 'string') return error('INVALID_PARAMS');- const current = this.capture(instance),- peer = raw.peer;- if (!current?.() || !this.transport?.allowed(peer)) return error('SYNC_OFFLINE');+ const pluginCurrent = this.capture(instance),+ peer = raw.peer,+ peerCurrent = this.capturePeer(peer);+ const current = () => pluginCurrent?.() === true && peerCurrent();+ if (!current()) return error('SYNC_OFFLINE');if (this.atCapacity(instance)) return error('SYNC_BUSY');try {await this.deps.keys.prepare();@@ -250,26 +268,45 @@ export class PluginDeviceSync {(raw.kind === 'key' && !isValidContactsSyncPublicKey(raw.publicKey))) return;const generation = this.generation,scope = this.deps.scope(),- receivedAt = Date.now();+ receivedAt = Date.now(),+ peerCurrent = this.capturePeer(peer);+ let expired = false;const current = () =>- this.active &&+ !expired && this.active &&generation === this.generation &&scope === this.deps.scope() &&Date.now() - receivedAt < TIMEOUT_MS &&- this.transport?.allowed(peer) === true;+ peerCurrent();const previous = this.receiving.get(peer);let release!: () => void;const turn = new Promise<void>((resolve) => { release = resolve; });this.receiving.set(peer, turn);this.receivingCount++;+ let deadlineTimer!: ReturnType<typeof setTimeout>;+ let incomingId: string | undefined;+ const deadline = new Promise<never>((_, reject) => {+ deadlineTimer = setTimeout(() => {+ expired = true;+ reject(new Error('sync frame expired'));+ }, Math.max(0, receivedAt + TIMEOUT_MS - Date.now()));+ deadlineTimer.unref?.();+ });+ const wait = <T>(work: Promise<T>): Promise<T> => Promise.race([work, deadline]);try {- await previous;+ // The encrypted target is not known until after key preparation. Capture eligible+ // installs now so queued frames cannot acquire a replacement's new approval.+ const targets = raw.kind === 'data' ? this.deps.listGhosts().flatMap(ghost => {+ const plugin = identity(ghost), instance = installedGhostStoragePart(ghost);+ const valid = this.capture(instance);+ return plugin && valid ? [{ ghost, plugin, instance, valid }] : [];+ }) : [];+ await wait(Promise.resolve(previous));if (!current()) return;- await this.deps.keys.prepare();+ await wait(this.deps.keys.prepare());if (!current()) return;if (raw.kind === 'key') {if (!isValidContactsSyncPublicKey(raw.publicKey)) return;- await this.deps.keys.pinPeerPublicKey(peer, raw.publicKey);+ await wait(this.deps.keys.pinPeerPublicKey(peer, raw.publicKey));if (!current()) return;if (Date.now() - (this.keyReplies.get(peer) ?? 0) > 5000) {this.keyReplies.set(peer, Date.now());@@ -326,23 +363,20 @@ export class PluginDeviceSync {clearTimeout(pending.timer);pending.finish({ ok: true, data: p.data });} else if (p.kind === 'request') {- const ghost = this.deps.listGhosts().find((g) => {- const i = identity(g);- return i && same(i, packet.plugin);- });- if (!ghost) return;- const instance = installedGhostStoragePart(ghost),- pluginCurrent = this.capture(instance);- if (!pluginCurrent?.() || this.atCapacity(instance)) return;+ const target = targets.find(t => same(t.plugin, packet.plugin));+ if (!target) return;+ const { ghost, instance, valid: pluginCurrent } = target;+ if (!pluginCurrent() || this.atCapacity(instance)) return;const requestId = randomUUID();+ incomingId = requestId;// A queued/startup-delayed request must still belong to this peer grant,// account, plugin revision and unexpired incoming request at actual delivery.const valid = () => current() && pluginCurrent();- const timer = setTimeout(() => this.incoming.delete(requestId), TIMEOUT_MS);+ const timer = setTimeout(() => this.incoming.delete(requestId), Math.max(0, receivedAt + TIMEOUT_MS - Date.now()));timer.unref?.();this.incoming.set(requestId, { peer, packet, instance, current: valid, timer });if (- !(await this.deps.deliver(+ !(await wait(this.deps.deliver(ghost,{type: 'device-sync-request',@@ -351,7 +385,7 @@ export class PluginDeviceSync {data: p.data,},() => valid() && this.incoming.has(requestId),- )) ||+ ))) ||!valid()) {clearTimeout(timer);@@ -361,6 +395,12 @@ export class PluginDeviceSync {} catch {/* Invalid/unauthenticated frames never surface their contents or mutate plugin data. */} finally {+ clearTimeout(deadlineTimer);+ if (incomingId && !current()) {+ const incoming = this.incoming.get(incomingId);+ if (incoming) clearTimeout(incoming.timer);+ this.incoming.delete(incomingId);+ }release();if (generation === this.generation) {this.receivingCount--;diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex b7687a86c6..47b2ccd664 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -1036,6 +1036,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v// 撤权后在途请求会陆续超时——那不是「设备无响应」,是访问被收回。清熔断并// 作废在途结果(翻代),避免 unresponsive 状态与撤权状态并存(对齐 mobile 语义)。revokedByRemote.add(env.src);+ pluginDeviceSync.invalidatePeer(env.src);responsivenessTracker?.clearDevice(env.src);broadcast(DEVICE_LINK_PUSH.ACCESS_REVOKED, { deviceId: env.src });}@@ -1526,6 +1527,7 @@ export function disconnectAllControllers(): void {*/export async function revokeController(deviceId: string): Promise<void> {invalidatePluginOauth(deviceId);+ pluginDeviceSync.invalidatePeer(deviceId);// 先消化并 enforce 盘上的外部变化,避免快照刷新吞掉别的实例刚写入的撤销(见 setRemoteControlEnabled)pollExternalSettingsChange();// updater 在写锁内基于盘上最新名单追加,不能锁外算好整数组再整值写@@ -1533,6 +1535,7 @@ export async function revokeController(deviceId: string): Promise<void> {await updateDeviceLinkSetting('revokedControllers', (latest) =>latest.includes(deviceId) ? latest : [...latest, deviceId],);+ pluginDeviceSync.invalidatePeer(deviceId);// 在线连着的:发 link-close('revoked'),控制端据此立即移除本机项目/对话 + 标记「已撤销」。try {client?.closeLink(deviceId, 'revoked', 'inbound');@@ -1628,6 +1631,7 @@ function pollExternalSettingsChange(): void {const newlyRevoked = revokedControllers.filter((id) => !prev.revokedControllers.includes(id));for (const deviceId of newlyRevoked) {+ pluginDeviceSync.invalidatePeer(deviceId);try {client.closeLink(deviceId, 'revoked', 'inbound');} catch (err) {diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 9d6d560072..942bad19e4 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -2755,6 +2755,8 @@ namespace + id 下同一插件的有界 JSON 请求;`deviceSync: true` 是独每请求 64 KiB、每插件 2 个/全机 32 个在途、30 秒超时;应用持久化后才回复。接收按 peer 顺序排队,全机最多 64 帧;等待不会拦住其他 peer,账号重置后旧队列失效。投递等待同一插件沙箱入口加载完成,并在实际发送前重查撤权与请求有效期。+排队、密钥准备和沙箱启动共享从帧入站起计算的 30 秒截止时间;超时释放该 peer 队列,迟到的启动不能再投递。+入站等待前捕获各候选插件安装状态;更新后的插件不接收旧帧。撤权翻转 peer 授权代次并清理双向在途请求,重新授权只放行新请求。显式断开远程控制后此通道可走 unlinked legacy;不重新打开控制链路,仍执行同账号与撤权检查。账号/owner、安装 revision、插件启停和撤权每次重新核验,旧请求失效只影响其调用,不重连共享 relay。恢复由插件持久状态对账,不恢复失效请求。