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。

Merge remote-tracking branch 'origin/main' into cindy/wise-mclean

DavidShen0e7c590bccc6
diff --cc apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.ts
index 62b6d76c22,6dfdf88bcf..f3aa8a922b
--- a/apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.ts
+++ b/apps/desktop/src/main/provider-group/__tests__/fastPolicyRuntime.test.ts
@@@ -91,9 -231,242 +231,243 @@@ beforeEach(() =>
})),
};
});
+ afterEach(async () => {
+ disposeRemoteAgentHost();
+ await state.usage?.flush();
+ vi.restoreAllMocks();
+ });
afterAll(() => fs.rmSync(temporary, { recursive: true, force: true }));
+afterEach(() => vi.useRealTimers());
+ const guestPeer = providerShareGuestPeer('share', 'member', 'laptop');
+ const directTask = (sessionId: string) => hostSessionIdFor(guestPeer, sessionId);
+ const usageFile = () => path.join(temporary, state.owner, 'usage.json');
+ async function installDirectHost() {
+ state.direct = true;
+ state.usage = createProviderShareUsageStore(usageFile());
+ // Host snapshot preparation persists the membership baseline before admission.
+ // Use the real ledger on initial install and restart; never bypass its cleanup fence.
+ await state.usage.reconcileMemberGenerations(state.owner, 'self', ownedShareSnapshot()!);
+ installRemoteAgentHost({ userDataDir: path.join(temporary, state.owner),
+ getMaker: () => { throw Error('Allocation must not start an agent on O'); } });
+ }
+ const allocate = (sessionId: string) => state.hostDeps!.directGuestExecution!.allocate(guestPeer,
+ { op: 'allocate', sessionId, agentKind: 'codex', model: 'gpt-5' });
+ function failAllocationAt(stage: 'Fast' | 'commit' | 'register') {
+ if (stage === 'Fast') state.notify.mockRejectedValue(Error('native policy failed'));
+ else vi.spyOn(state.usage!, stage === 'commit' ? 'commitDirectReceiptRoute' : 'registerDirectReceiptRoute')
+ .mockRejectedValue(Error('journal write failed'));
+ }
+
+ // Unit / real installed O callbacks + durable journal. Previously only active
+ // 30-minute receipts were tested: expiry/restart could send a native ID to M2.
+ // Location grants no authority; the current guest and fresh lease still gate use.
+ describe('durable direct task routing', () => {
+ const locate = (sessionId: string, peer = guestPeer) => state.hostDeps!.directGuestExecution!.locate!(peer,
+ { op: 'direct-locate', sessionId });
+ // Unit integration: O's live budget has no offline delegated enforcement.
+ // Exercise real allocation, policy callback and M lease revocation together.
+ it('withdraws direct leases when a member requires live budget checks, preserving history affinity', async () => {
+ await installDirectHost();
+ await allocate('budget-history');
+ expect(delegation.delegatedProviderShareTaskAccess(guestPeer, 'budget-history')).not.toBeNull();
+ state.delegatedAllowed = false;
+ state.modelChanged!();
+ await vi.waitFor(() => expect(delegation.delegatedProviderShareTaskAccess(guestPeer, 'budget-history')).toBeNull());
+ expect(await allocate('budget-new')).toBeNull();
+ expect(await allocate('budget-history')).toBeNull();
+ expect(await locate('budget-history')).toEqual({ deviceId: 'one' });
+ state.delegatedAllowed = true;
+ expect((await allocate('budget-history'))?.deviceId).toBe('one');
+ });
+ it('renews the original M after 31 minutes and O restart, despite a new M2 plan', async () => {
+ await installDirectHost();
+ const first = await allocate('history');
+ expect(first?.deviceId).toBe('one');
+ disposeRemoteAgentHost();
+ await state.usage!.flush();
+ // Advance the persisted receipt's age instead of the OS file-lock clock.
+ // This is the disk image an O restart sees 31 minutes after allocation.
+ const persisted = JSON.parse(fs.readFileSync(usageFile(), 'utf8'));
+ for (const route of persisted.directReceiptRoutes) route.expiresAt -= 31 * 60_000;
+ fs.writeFileSync(usageFile(), JSON.stringify(persisted));
+ state.planDevice = 'two';
+ await installDirectHost();
+ expect(await allocate('history')).toMatchObject({ deviceId: 'one' });
+ expect(await locate('history')).toEqual({ deviceId: 'one' });
+ expect(state.pair?.generation).not.toBe(first?.generation);
+ });
+
+ it('returns null for legacy history and never exposes another member or account location', async () => {
+ await installDirectHost();
+ expect(await allocate('history')).not.toBeNull();
+ expect(await locate('legacy')).toBeNull();
+ await expect(locate('history', providerShareGuestPeer('share', 'other-member', 'laptop'))).rejects.toThrow();
+ state.approved = false;
+ await expect(locate('history')).rejects.toThrow();
+ state.approved = true;
+ state.owner = 'another-account';
+ await expect(locate('history')).rejects.toThrow('REMOTE_AGENT_UNAVAILABLE');
+ });
+
+ it('keeps the pin and fails closed when M1 is unavailable or no longer allowed', async () => {
+ await installDirectHost();
+ expect(await allocate('history')).not.toBeNull();
+ state.planDevice = 'two';
+ state.offline.add('one');
+ expect(await allocate('history')).toBeNull();
+ expect(await locate('history')).toEqual({ deviceId: 'one' });
+ state.offline.clear();
+ state.config!.members = state.config!.members.filter((member) => member.key !== 'device:one:openai');
+ // Removal changes the new-task pool, not the location of existing history.
+ expect(await allocate('history')).toMatchObject({ deviceId: 'one' });
+ state.revoked = ['one'];
+ expect(await allocate('history')).toBeNull();
+ expect(await locate('history')).toEqual({ deviceId: 'one' });
+ expect(await state.hostDeps!.directGuestExecution!.allocate(guestPeer,
+ { op: 'allocate', sessionId: 'history', agentKind: 'codex', model: 'gpt-5', preferredExecutorDeviceId: 'two' })).toBeNull();
+ });
+
+ it('clears the durable pin only when O accepts the switch token', async () => {
+ await installDirectHost();
+ expect(await allocate('history')).not.toBeNull();
+ state.planDevice = 'two';
+ const direct = state.hostDeps!.directGuestExecution!;
+ const { token } = await direct.switch(guestPeer, { op: 'direct-switch', sessionId: 'history' });
+ expect(token).toBeTruthy();
+ expect(await locate('history')).toEqual({ deviceId: 'one' });
+ const handoff = vi.spyOn(state.usage!, 'markDirectTaskRelayed')
+ .mockRejectedValueOnce(Error('handoff journal write failed'));
+ await expect(direct.switched!(guestPeer, 'history', token!)).rejects.toThrow('handoff journal write failed');
+ expect(await locate('history')).toEqual({ deviceId: 'one' });
+ handoff.mockRestore();
+ await direct.switched!(guestPeer, 'history', token!);
+ disposeRemoteAgentHost();
+ await state.usage!.flush();
+ await installDirectHost();
+ expect(await locate('history')).toBeNull();
+ });
+
+ it('retains historical affinity on release but clears it on accepted fresh O fallback', async () => {
+ await installDirectHost();
+ const first = await allocate('history');
+ const direct = state.hostDeps!.directGuestExecution!;
+ await direct.release(guestPeer, { op: 'direct-release', sessionId: 'history', generation: first!.generation });
+ expect(await locate('history')).toEqual({ deviceId: 'one' });
+ await expect(direct.acceptRelay!(guestPeer, 'history', true)).rejects.toThrow();
+ await direct.acceptRelay!(guestPeer, 'history', false);
+ disposeRemoteAgentHost();
+ await state.usage!.flush();
+ await installDirectHost();
+ expect(await locate('history')).toBeNull();
+ });
+ });
+
+ // Production entry: installRemoteAgentHost's allocate + real M delegation/Fast
+ // receiver and durable stores. Unit tier; transport, server pair API and member
+ // selection are in-memory boundaries. Existing policy tests never allocated two
+ // tasks or paused between Fast confirmation and granting an executable M lease.
+ // Regression: B rollback must not revoke A's pair; group Fast prohibition must
+ // be durable and applied before a guest can start (provider-groups.md §15).
+ describe('direct allocation authorization and Fast prebinding', () => {
+ it.each(['Fast', 'commit', 'register'] as const)(
+ 'keeps A executable when new B fails at %s', async (stage) => {
+ await installDirectHost();
+ expect(await allocate('task_a')).not.toBeNull();
+ failAllocationAt(stage);
+ expect(await allocate('task_b')).toBeNull();
+ expect(state.pair).not.toBeNull();
+ expect(delegation.delegatedProviderShareSessionAllowed(guestPeer, 'task_a')).toBe(true);
+ expect(delegation.delegatedProviderShareSessionAllowed(guestPeer, 'task_b')).toBe(false);
+ expect(state.usage!.listActiveDirectReceiptRoutes(state.owner).map((route) => route.sessionId))
+ .toEqual(['task_a']);
+ },
+ );
+
+ it.each(['Fast', 'commit', 'register'] as const)(
+ 'keeps sibling A authorized when B renewal and its restoration fail at %s', async (stage) => {
+ await installDirectHost();
+ expect(await allocate('task_a')).not.toBeNull();
+ expect(await allocate('task_b')).not.toBeNull();
+ failAllocationAt(stage);
+ expect(await allocate('task_b')).toBeNull();
+ expect(state.pair).not.toBeNull();
+ expect(delegation.delegatedProviderShareSessionAllowed(guestPeer, 'task_a')).toBe(true);
+ },
+ );
+
+ it('revokes an unsuccessful allocation pair when no valid sibling needs it', async () => {
+ await installDirectHost();
+ failAllocationAt('Fast');
+ expect(await allocate('task_b')).toBeNull();
+ expect(state.pair).toBeNull();
+ expect(delegation.delegatedProviderShareSessionAllowed(guestPeer, 'task_b')).toBe(false);
+ });
+
+ it.each(['provisional', 'moved'] as const)(
+ 'does not preserve a pair for an obsolete committed sibling superseded by a %s assignment', async (latest) => {
+ await installDirectHost();
+ expect(await allocate('task_a')).not.toBeNull();
+ const oldA = state.usage!.listActiveDirectReceiptRoutes(state.owner)[0];
+ const newer = { ...oldA, generation: randomUUID(), committedAt: undefined,
+ ...(latest === 'moved' ? { executorDeviceId: 'two', memberKey: 'device:two:openai' } : {}) };
+ await state.usage!.registerDirectReceiptRoute(newer);
+ if (latest === 'moved') await state.usage!.commitDirectReceiptRoute(newer);
+ disposeRemoteAgentHost();
+ await state.usage!.flush();
+ await installDirectHost();
+ failAllocationAt('Fast');
+ expect(await allocate('task_b')).toBeNull();
+ expect(state.pair).toBeNull();
+ },
+ );
+
+ it('has no executable guest lease while durable Fast policy is still awaiting application', async () => {
+ await installDirectHost();
+ let entered!: () => void;
+ let release!: () => void;
+ const applying = new Promise<void>((resolve) => { entered = resolve; });
+ const applied = new Promise<void>((resolve) => { release = resolve; });
+ state.notify.mockImplementationOnce(() => { entered(); return applied; });
+ const pending = allocate('task_a');
+ await applying;
+ const executableBeforeAck = delegation.delegatedProviderShareSessionAllowed(guestPeer, 'task_a');
+ const fastBeforeAck = groupFastPolicyStore.allows(directTask('task_a'));
+ release();
+ expect(await pending).not.toBeNull();
+ expect(executableBeforeAck).toBe(false);
+ expect(fastBeforeAck).toBe(false);
+ expect(delegation.delegatedProviderShareSessionAllowed(guestPeer, 'task_a')).toBe(true);
+ // Read fresh store instances to verify the restriction crossed the restart boundary.
+ const restarted = createGroupFastPolicyStore({ scopeKey: () => state.owner,
+ filePath: () => path.join(temporary, state.owner, 'provider-group-fast-policy.json') });
+ expect(restarted.allows(directTask('task_a'))).toBe(false);
+ });
+
+ it.each(['grant', 'Fast'] as const)(
+ 'preserves A after O restarts with provisional B and restoration fails at %s', async (stage) => {
+ await installDirectHost();
+ expect(await allocate('task_a')).not.toBeNull();
+ expect(await allocate('task_b')).not.toBeNull();
+ const oldB = state.usage!.listActiveDirectReceiptRoutes(state.owner).find((row) => row.sessionId === 'task_b')!;
+ const provisional = { ...oldB, generation: randomUUID(), committedAt: undefined };
+ await state.usage!.registerDirectReceiptRoute(provisional);
+ state.pair = { ...state.pair!, generation: provisional.generation };
+ disposeRemoteAgentHost();
+ await state.usage!.flush();
+ await installDirectHost();
+ if (stage === 'grant') state.failGrant = true;
+ else failAllocationAt('Fast');
+ state.hostChanged!();
+ await vi.waitFor(() => expect(state.delegateCalls.some((request) => request.op === 'delegate'
+ && request.action === 'revoke' && request.generation === provisional.generation)).toBe(true));
+ expect(state.pair).not.toBeNull();
+ expect(state.usage!.listActiveDirectReceiptRoutes(state.owner)
+ .some((row) => row.sessionId === 'task_a' && row.committedAt !== undefined)).toBe(true);
+ },
+ );
+ });
+
function blockCapabilitiesRequest() {
let enter!: () => void;
let unblock!: () => void;