Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 避免 Fast 策略重复写盘并为失败同步增加退避
DavidShen5904aeb26a38
diff --git a/apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.ts b/apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.tsindex 866f79cacc..62b6d76c22 100644--- a/apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.ts@@ -1,7 +1,7 @@import fs from 'node:fs';import path from 'node:path';import os from 'node:os';-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ProviderGroupConfig } from '../../../shared/providerGroup.js';import { hostSessionIdFor } from '../../remote-agent/host/sessionIdentity.js';@@ -92,12 +92,17 @@ beforeEach(() => {};});afterAll(() => fs.rmSync(temporary, { recursive: true, force: true }));+afterEach(() => vi.useRealTimers());function blockCapabilitiesRequest() {let enter!: () => void;let unblock!: () => void;- const started = new Promise<void>((resolve) => { enter = resolve; });- const blocked = new Promise<void>((resolve) => { unblock = resolve; });+ const started = new Promise<void>((resolve) => {+ enter = resolve;+ });+ const blocked = new Promise<void>((resolve) => {+ unblock = resolve;+ });state.beforeCaps = () => {enter();return blocked;@@ -112,6 +117,87 @@ function blockCapabilitiesRequest() {}describe('group owner to executor enforcement handshake', () => {+ // #7848, unit: use the real sync/store and a failed peer, advancing virtual+ // polling time. Existing tests cover in-flight coalescing, not later retries+ // or the policy file's unchanged mtime after each unsuccessful poll.+ it('backs off failed peers up to five minutes without rewriting unchanged policy on polls', async () => {+ // Only virtualize the retry clock: filesystem lock mtimes use real Date.+ vi.useFakeTimers({ toFake: ['performance', 'setInterval', 'clearInterval'] });+ state.offline.add('one');+ await runtime.syncGroupFastPolicy('openai');+ const file = path.join(temporary, state.owner, 'provider-group-fast-policy.json');+ const timestamp = new Date('2020-01-01T00:00:00Z');+ fs.utimesSync(file, timestamp, timestamp);+ const stop = runtime.startGroupFastPolicySync();+ const attempts = (device: string) =>+ state.calls.filter((call) => call.device === device && call.command.op === 'caps').length;+ let count = 1;+ try {+ for (const delay of [5_000, 10_000, 20_000, 40_000, 80_000, 160_000, 300_000, 300_000]) {+ // Drain each poll's real filesystem work before advancing to the next.+ for (let elapsed = 5_000; elapsed < delay; elapsed += 5_000) {+ await vi.advanceTimersByTimeAsync(5_000);+ await runtime.syncGroupFastPolicy('openai');+ expect(attempts('one')).toBe(count);+ }+ await vi.advanceTimersByTimeAsync(5_000);+ await runtime.syncGroupFastPolicy('openai');+ expect(attempts('one')).toBe(++count);+ expect(attempts('two')).toBe(1);+ expect(fs.statSync(file).mtimeMs).toBe(timestamp.getTime());+ expect(runtime.groupFastPolicyPending('openai')).toBe(true);+ }+ state.offline.clear();+ await vi.advanceTimersByTimeAsync(300_000);+ await runtime.syncGroupFastPolicy('openai');+ expect(runtime.groupFastPolicyPending('openai')).toBe(false);+ expect(attempts('one')).toBe(count + 1);+ await vi.advanceTimersByTimeAsync(600_000);+ expect(attempts('one')).toBe(count + 1);+ } finally {+ stop();+ await runtime.syncGroupFastPolicy('openai');+ }+ });++ it('sends new revisions and removed-member releases immediately despite previous failures', async () => {+ vi.useFakeTimers({ toFake: ['performance'] });+ state.offline.add('one');+ await runtime.syncGroupFastPolicy('openai');+ const revision = groupFastPolicyStore.outgoing().openai.revision;+ state.config!.allowFast = true;+ await runtime.syncGroupFastPolicy('openai');+ expect(state.calls.filter(({ device }) => device === 'one')).toHaveLength(2);+ expect(groupFastPolicyStore.outgoing().openai.revision).toBe(revision + 1);+ state.config!.members = state.config!.members.slice(1);+ await runtime.syncGroupFastPolicy('openai');+ expect(state.calls.filter(({ device }) => device === 'one')).toHaveLength(3);+ expect(groupFastPolicyStore.outgoing().openai.targets.one).toBe(-1);+ state.offline.clear();+ await runtime.syncGroupFastPolicy('openai');+ expect(state.calls.filter(({ device }) => device === 'one')).toHaveLength(3);+ vi.advanceTimersByTime(5_000);+ await runtime.syncGroupFastPolicy('openai');+ expect(state.calls).toContainEqual({+ device: 'one',+ command: { op: 'fast-policy', group: 'openai', allowFast: true, revision: revision + 2 },+ });+ expect(groupFastPolicyStore.outgoing().openai.targets).not.toHaveProperty('one');+ expect(runtime.groupFastPolicyPending('openai')).toBe(false);+ });++ it('does not carry failed-peer cooldown into a different owner with the same group and revision', async () => {+ vi.useFakeTimers({ toFake: ['performance'] });+ state.broken.add('one');+ await runtime.syncGroupFastPolicy('openai');+ await runtime.syncGroupFastPolicy('openai');+ expect(state.calls.filter(({ device }) => device === 'one')).toHaveLength(1);+ state.owner = `other-${state.owner}`;+ await runtime.syncGroupFastPolicy('openai');+ expect(state.calls.filter(({ device }) => device === 'one')).toHaveLength(2);+ expect(groupFastPolicyStore.outgoing().openai.targets.two).toBe(1);+ });+it('coalesces repeated sync requests while the same offline revision is in flight', async () => {const caps = blockCapabilitiesRequest();// Only one remote endpoint makes the blocked request count unambiguous.@@ -193,12 +279,14 @@ describe('group owner to executor enforcement handshake', () => {});it('keeps offline and old executors pending, retries after recovery, and releases removed members with a newer revision', async () => {+ vi.useFakeTimers({ toFake: ['performance'] });state.old.add('one');state.offline.add('two');await runtime.syncGroupFastPolicy('openai');expect(runtime.groupFastPolicyPending('openai')).toBe(true);state.old.clear();state.offline.clear();+ vi.advanceTimersByTime(5_000);await runtime.syncGroupFastPolicy('openai');expect(runtime.groupFastPolicyPending('openai')).toBe(false);const revision = groupFastPolicyStore.outgoing().openai.revision;@@ -268,6 +356,7 @@ describe('group owner to executor enforcement handshake', () => {});it('shows local native failures as pending instead of acknowledging the whole group', async () => {+ vi.useFakeTimers({ toFake: ['performance'] });state.config!.members.push({key: 'local',kind: 'local',@@ -281,6 +370,7 @@ describe('group owner to executor enforcement handshake', () => {await expect(runtime.syncGroupFastPolicy('openai')).rejects.toThrow('native busy');expect(runtime.groupFastPolicyPending('openai')).toBe(true);state.notify.mockResolvedValue(undefined);+ vi.advanceTimersByTime(5_000);await runtime.syncGroupFastPolicy('openai');expect(runtime.groupFastPolicyPending('openai')).toBe(false);});diff --git a/apps/desktop/src/main/provider-group/__tests__/fastPolicyStore.test.ts b/apps/desktop/src/main/provider-group/__tests__/fastPolicyStore.test.tsindex a4f3f2edc4..bf3c55bb43 100644--- a/apps/desktop/src/main/provider-group/__tests__/fastPolicyStore.test.ts+++ b/apps/desktop/src/main/provider-group/__tests__/fastPolicyStore.test.ts@@ -27,6 +27,64 @@ const fixture = () => {const current = () => {};describe('durable subscription Fast constraints', () => {+ // #7848, unit: prepare() must preserve the file and its read cache when an+ // unacknowledged target is retried. Existing revision tests do not observe IO.+ it('does not rewrite or reload an unchanged outgoing policy with pending targets', async () => {+ const config = fixture();+ const store = createGroupFastPolicyStore(config);+ const initial = await store.prepare('group', true, ['one', 'two'], current, true);+ await store.acknowledge('group', 'one', initial.revision, current);+ const timestamp = new Date('2020-01-01T00:00:00Z');+ fs.utimesSync(config.filePath(), timestamp, timestamp);+ const before = store.outgoing().group;+ const content = fs.readFileSync(config.filePath(), 'utf8');+ const readFile = vi.spyOn(fs, 'readFileSync');+ const writeFile = vi.spyOn(fs, 'writeFileSync');+ try {+ expect(await store.prepare('group', true, ['two', 'one', 'one'], current, true)).toEqual(+ before,+ );+ expect(await store.prepare('group', true, ['one'], current)).toEqual(before);+ expect(await store.prepare('group', true, [], current)).toEqual(before);+ expect(readFile.mock.calls.filter(([file]) => file === config.filePath())).toEqual([]);+ expect(writeFile.mock.calls.filter(([file]) => file === `${config.filePath()}.tmp`)).toEqual(+ [],+ );+ expect(fs.statSync(config.filePath()).mtimeMs).toBe(timestamp.getTime());+ expect(fs.readFileSync(config.filePath(), 'utf8')).toBe(content);+ await expect(+ store.prepare('group', true, [], () => {+ throw Error('owner changed');+ }),+ ).rejects.toThrow('owner changed');+ } finally {+ readFile.mockRestore();+ writeFile.mockRestore();+ }+ });++ // The no-op fast path must still observe other instances and persist new+ // binding destinations, even when allowFast and the revision stay unchanged.+ it('refreshes external policy changes and persists a new target without replacing members', async () => {+ const config = fixture();+ const store = createGroupFastPolicyStore(config);+ const other = createGroupFastPolicyStore(config);+ await store.prepare('group', true, ['one'], current, true);+ const timestamp = new Date('2020-01-01T00:00:00Z');+ fs.utimesSync(config.filePath(), timestamp, timestamp);+ store.outgoing();+ const external = await other.prepare('group', false, ['one'], current, true);+ await other.acknowledge('group', 'one', external.revision, current);+ const next = await store.prepare('group', false, ['two'], current);+ expect(next).toEqual({+ revision: external.revision,+ allowFast: false,+ members: ['one'],+ targets: { one: external.revision, two: -1 },+ });+ expect(createGroupFastPolicyStore(config).outgoing().group).toEqual(next);+ });+it('updates actual account keys atomically across instances and survives reload', async () => {const config = fixture();const a = createProviderFastPolicyStore(config),diff --git a/apps/desktop/src/main/provider-group/fastPolicyRuntime.ts b/apps/desktop/src/main/provider-group/fastPolicyRuntime.tsindex f67793d018..b6b4652516 100644--- a/apps/desktop/src/main/provider-group/fastPolicyRuntime.ts+++ b/apps/desktop/src/main/provider-group/fastPolicyRuntime.ts@@ -28,6 +28,28 @@ const targets = (group: string) => {];};const syncing = new Map<string, Promise<void>>();+const RETRY_INITIAL_MS = 5_000;+const RETRY_MAX_MS = 5 * 60_000;+interface TargetRetry {+ delayMs: number;+ retryAt: number;+}+let retryOwner: string | undefined;+const retries = new Map<string, { revision: number; targets: Map<string, TargetRetry> }>();++function retriesFor(group: string, revision: number): Map<string, TargetRetry> {+ const owner = activeOwnerScopeKey();+ if (retryOwner !== owner) {+ retries.clear();+ retryOwner = owner;+ }+ let state = retries.get(group);+ if (state?.revision !== revision) {+ state = { revision, targets: new Map() };+ retries.set(group, state);+ }+ return state.targets;+}async function send(device: string,@@ -201,22 +223,40 @@ export function syncGroupFastPolicy(group: string): Promise<void> {assertCurrent,true,);+ assertCurrent();const active = new Set(destinations);+ const retryTargets = retriesFor(group, state.revision);+ for (const device of retryTargets.keys()) {+ if (state.targets[device] === undefined || state.targets[device] === state.revision) {+ retryTargets.delete(device);+ }+ }await Promise.allSettled(Object.entries(state.targets).filter(([, ack]) => ack !== state.revision).map(async ([device]) => {+ const retry = retryTargets.get(device);+ if (retry && performance.now() < retry.retryAt) return;const command = {group,revision: state.revision,allowFast: active.has(device) ? state.allowFast : true,};- if (device === LOCAL_TARGET) {- const self = getSelfDeviceId();- if (!self) throw new Error('[REMOTE_AGENT_UNAVAILABLE] Computer identity is not ready');- await receiveGroupFastPolicy(self, command);- } else await send(device, command, assertCurrent);- await groupFastPolicyStore.acknowledge(group, device, state.revision, assertCurrent);+ try {+ if (device === LOCAL_TARGET) {+ const self = getSelfDeviceId();+ if (!self)+ throw new Error('[REMOTE_AGENT_UNAVAILABLE] Computer identity is not ready');+ await receiveGroupFastPolicy(self, command);+ } else await send(device, command, assertCurrent);+ await groupFastPolicyStore.acknowledge(group, device, state.revision, assertCurrent);+ retryTargets.delete(device);+ } catch (error) {+ assertCurrent();+ const delayMs = retry ? Math.min(retry.delayMs * 2, RETRY_MAX_MS) : RETRY_INITIAL_MS;+ retryTargets.set(device, { delayMs, retryAt: performance.now() + delayMs });+ throw error;+ }}),);assertCurrent();@@ -228,7 +268,7 @@ export function syncGroupFastPolicy(group: string): Promise<void> {return work;}-/** Retry only unacknowledged policy changes; never reset a shared device-link connection. */+/** Poll pending revisions; each failed target backs off without resetting shared links. */export function startGroupFastPolicySync(): () => void {const sync = () => {const outgoing = groupFastPolicyStore.outgoing();@@ -249,5 +289,8 @@ export function startGroupFastPolicySync(): () => void {};const timer = setInterval(sync, 5_000);timer.unref?.();- return () => clearInterval(timer);+ return () => {+ clearInterval(timer);+ retries.clear();+ };}diff --git a/apps/desktop/src/main/provider-group/fastPolicyStore.ts b/apps/desktop/src/main/provider-group/fastPolicyStore.tsindex 1b6ea2a469..301024e23f 100644--- a/apps/desktop/src/main/provider-group/fastPolicyStore.ts+++ b/apps/desktop/src/main/provider-group/fastPolicyStore.ts@@ -213,13 +213,29 @@ export function createGroupFastPolicyStore(options: { filePath(): string; scopeKassertCurrent: () => void,replaceMembers = false,): Promise<Outgoing> {+ assertCurrent();+ const snapshot = read();+ writable(snapshot);+ const previous = snapshot.outgoing[group];+ const members = replaceMembers ? [...new Set(destinations)].sort() : undefined;+ // Retrying an unacknowledged revision is a read, not a mutation. Avoid+ // updateAtomic's forced cache invalidation and disk write in this case.+ // Real changes still recompute from the latest snapshot under its lock.+ if (+ previous &&+ previous.allowFast === allowFast &&+ (!replaceMembers || JSON.stringify(previous.members) === JSON.stringify(members)) &&+ destinations.every((device) => previous.targets[device] !== undefined)+ ) {+ return previous;+ }const value = await store.updateAtomic(({ value }) => {assertCurrent();writable(value);const previous = value.outgoing[group];- const members = replaceMembers ? [...new Set(destinations)].sort() : previous?.members;+ const nextMembers = replaceMembers ? members : previous?.members;const sameMembers =- !replaceMembers || JSON.stringify(previous?.members) === JSON.stringify(members);+ !replaceMembers || JSON.stringify(previous?.members) === JSON.stringify(nextMembers);const revision =previous && previous.allowFast === allowFast && sameMembers? previous.revision@@ -229,7 +245,12 @@ export function createGroupFastPolicyStore(options: { filePath(): string; scopeKreturn {outgoing: {...value.outgoing,- [group]: { revision, allowFast, targets, ...(members ? { members } : {}) },+ [group]: {+ revision,+ allowFast,+ targets,+ ...(nextMembers ? { members: nextMembers } : {}),+ },},};});