Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): recheck Fast policy after async authorization
zqchris5c5a0abb3583
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.tsindex 08eaa79cc9..c0eb954787 100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts@@ -237,6 +237,47 @@ describe('PI native subscription forwarding', () => {expect(zstdDecompress).toHaveBeenCalledTimes(compressed ? 1 : 0);});+ // Credential refresh and the final guest grant check can both suspend while+ // the provider/group closes Fast. The outgoing bytes must reflect that change.+ it.each(['auth', 'final-grant'].flatMap(timing => [false, true].map(compressed => ({ timing, compressed }))))(+ 'rechecks Fast after $timing, compressed=$compressed', async ({ timing, compressed }) => {+ const providerId = 'openai-fast-race-fixture';+ setCustomProviders([buildUserProvider({ id: providerId, name: 'Fast race fixture',+ auth: { method: 'oauth', native: 'codex' },+ runtimes: { codex: { baseUrl: 'https://chatgpt.example', wireProtocol: 'openai-responses',+ models: [{ id: 'gpt-6.1-sol', name: 'Fixture' }] } } })]);+ let authRead = false;+ const binding = registerGuestProviderRoute('pi-fast-race', providerId, async () => {+ if (authRead && timing === 'final-grant') ownerState.fastAllowed = false;+ return true;+ });+ const injected = deps({ getChatgptAuth: vi.fn(async () => {+ authRead = true;+ if (timing === 'auth') ownerState.fastAllowed = false;+ return { accessToken: 'fixture-token', accountId: 'fixture-account' };+ }) });+ const payload = { model: 'gpt-6.1-sol', service_tier: 'priority', input: [] };+ const raw = Buffer.from(JSON.stringify(payload));+ try {+ const res = responseRecorder();+ await getPiNativeSubscriptionHandler(providerId, 'pi-fast-race', injected)({+ rawBody: compressed ? zstdCompressSync(raw) : raw, parsedBody: compressed ? undefined : payload,+ ctx: { reqId: 1, method: 'POST', url: '/codex/responses', headers: compressed ? { 'content-encoding': 'zstd' } : {} },+ res,+ } as never);+ expect(res.status).toBe(200);+ expect(injected.getChatgptAuth).toHaveBeenCalledOnce();+ expect(injected.fetch).toHaveBeenCalledOnce();+ const sent = vi.mocked(injected.fetch).mock.calls[0]![1]!;+ const bytes = Buffer.from(sent.body as Uint8Array);+ expect(JSON.parse((compressed ? zstdDecompressSync(bytes) : bytes).toString()))+ .toEqual({ ...payload, service_tier: 'default' });+ expect(zstdDecompress).toHaveBeenCalledTimes(compressed ? 1 : 0);+ expect(zstdCompress).toHaveBeenCalledTimes(compressed ? 1 : 0);+ } finally { binding.release(); }+ },+ );+it('rechecks Fast after asynchronous profile recompression before dispatch', async () => {const actual = await vi.importActual<typeof import('node:zlib')>('node:zlib');vi.mocked(zstdCompress).mockImplementationOnce(((...args: unknown[]) => {diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.tsindex bd09325fdd..40fadc5f52 100644--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts@@ -780,6 +780,7 @@ export function getPiNativeSubscriptionHandler(let recordGuestUsage: ReturnType<typeof captureGuestRequestUsage>;let outboundBody = rawBody;let contentEncoding: string | undefined = ctx.headers['content-encoding'];+ let rewriteOpenaiBody: (() => Promise<void> | null) | undefined;if (isOpenAiSubscriptionProviderId(providerId)) {// Retain the decoded object across both rewrites. Unchanged requests keep// their original bytes; changed zstd requests stay compressed on the wire.@@ -802,10 +803,10 @@ export function getPiNativeSubscriptionHandler(current = profile ?? current;let changed = profile !== null;let standardApplied = false;- for (;;) {- throwIfOwnerBoundDispatchUnsafe(scopeAtStart);- // Restrictions may tighten while decoding or encoding. Once restricted,- // this request cannot regain priority while an asynchronous codec runs.+ // Finalize only after credentials and the latest model grant are read.+ // Return pending codec work so every async rewrite is followed by another+ // grant/Fast check, with no async gap between the last check and dispatch.+ rewriteOpenaiBody = () => {forceStandard ||= !subscriptionRequestAllowsFast(sessionId, providerId);if (forceStandard && !standardApplied) {if (decodeError) throw decodeError;@@ -814,15 +815,15 @@ export function getPiNativeSubscriptionHandler(current = standard;standardApplied = true;}- if (!changed) break;+ if (!changed) return null;const bytes = Buffer.from(JSON.stringify(current));- // Keep large codecs off Electron main, as in the existing profile path.- outboundBody = compressed ? await zstdCompressAsync(bytes) : bytes;- if (!compressed) contentEncoding = undefined;changed = false;- if (standardApplied || !compressed) break;- // A profile-only compression can yield to a newly restrictive policy.- }+ // Keep large codecs off Electron main, as in the existing profile path.+ if (compressed) return zstdCompressAsync(bytes).then(encoded => { outboundBody = encoded; });+ outboundBody = bytes;+ contentEncoding = undefined;+ return null;+ };} else if (isXaiSubscriptionProviderId(providerId)) {const parsed = isPlainRecord(parsedBody)? parsedBody@@ -861,10 +862,15 @@ export function getPiNativeSubscriptionHandler(}headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';headers.accept = ctx.headers.accept ?? 'text/event-stream';+ for (;;) {+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);+ if (!await modelAllowed()) return;+ throwIfOwnerBoundDispatchUnsafe(scopeAtStart);+ const pendingRewrite = rewriteOpenaiBody?.();+ if (!pendingRewrite) break;+ await pendingRewrite;+ }if (contentEncoding) headers['content-encoding'] = contentEncoding;-- throwIfOwnerBoundDispatchUnsafe(scopeAtStart);- if (!await modelAllowed()) return;throwIfOwnerBoundDispatchUnsafe(scopeAtStart);const response = await deps.fetch(upstream.url, {method: 'POST',