Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): enforce live Fast restrictions on websocket requests
xuzini-xzn430fd634e9b0
diff --git a/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.ts b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.tsindex 2c6ab7cee0..c4390e592b 100644--- a/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.e2e.test.ts@@ -19,7 +19,9 @@ vi.mock('../codex-account-auth.js', () => ({ isOpenAiSubscriptionProviderId: (idvi.mock('../session-provider-store.js', () => ({ getSessionProvider: () => null, hasHostedSessionModelAccess: () => false }));vi.mock('../guest-provider-route-store.js', () => ({ guestProviderRouteForSession: () => null }));vi.mock('../anthropic-responses-bridge-host.js', () => ({ getChatgptBridgeAuthForDispatch: vi.fn() }));-import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream } from '../pi-subscription-websocket.js';+const fastPolicy = vi.hoisted(() => ({ allowed: true }));+vi.mock('../subscription-fast-request-policy.js', () => ({ subscriptionRequestAllowsFast: () => fastPolicy.allowed }));+import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream, piWebSocketTransforms } from '../pi-subscription-websocket.js';import { registerPiProxySession } from '../pi-proxy-session-auth.js';const binary = process.env.CINDY_TEST_PI_BINARY ?? resolve('../../apps/pi-bin', `${process.platform}-${process.arch}`, process.platform === 'win32' ? 'pi.exe' : 'pi');@@ -60,8 +62,10 @@ describe.skipIf(!existsSync(binary))('actual Pi subscription incremental transpo{ label: 'native SSE fallback', source: 'openai', provider: 'openai-codex', fast: false, fallback: true, reconnect: false },{ label: 'original SSE baseline', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false, baseline: true },{ label: 'live Fast change', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false, toggleFast: true },+ { label: 'Fast restriction between tool steps', source: 'openai', provider: 'openai-codex', fast: true, fallback: false, reconnect: false, restrictFast: true },{ label: 'missing continuation', source: 'openai', provider: 'openai-codex', fast: false, fallback: false, reconnect: false, missingContinuation: true },])('preserves tool/image history and native recovery: $label', async scenario => {+ fastPolicy.allowed = true;const directory = await mkdtemp(join(tmpdir(), 'cindy-pi-ws-'));const requests: Array<Record<string, any>> = [];const handshakes: Array<Record<string, any>> = [];@@ -87,6 +91,7 @@ describe.skipIf(!existsSync(binary))('actual Pi subscription incremental transporeturn;}if (scenario.toggleFast && index === 0) await writeFile(join(directory, 'options.json'), JSON.stringify({ fast: true }));+ if (scenario.restrictFast && index === 0) fastPolicy.allowed = false;for (const event of responseEvents(index, index < 3)) client.send(JSON.stringify(event));if (scenario.reconnect && index === 1) client.close();});@@ -100,6 +105,7 @@ describe.skipIf(!existsSync(binary))('actual Pi subscription incremental transpoupstream: upstreamUrl, transformRequest: [],resolveWebSocketUpstream: ctx => resolvePiWebSocketUpstream(ctx) ? upstreamUrl : null,prepareWebSocketRequest: prepare,+ webSocketTransforms: piWebSocketTransforms,routingTransform: () => ({ localHandler: async ({ rawBody, parsedBody, ctx, res }) => {const index = requests.length;const decoded = parsedBody ?? JSON.parse((ctx.headers['content-encoding'] === 'zstd' ? zstdDecompressSync(rawBody) : rawBody).toString());@@ -167,7 +173,12 @@ export default async function(pi: any) {} else if (scenario.fallback) {expect(requests.every(body => body.fallback)).toBe(true);} else {- expect(requests.every((body, index) => body.model === 'gpt-6-astra' && body.service_tier === (scenario.fast || (scenario.toggleFast && index > 0) ? 'priority' : undefined))).toBe(true);+ for (const [index, body] of requests.entries()) {+ const tier = scenario.restrictFast && index > 0 ? 'default'+ : scenario.fast || (scenario.toggleFast && index > 0) ? 'priority' : undefined;+ expect(body.model).toBe('gpt-6-astra');+ expect(body.service_tier, `request ${index}`).toBe(tier);+ }expect(JSON.stringify(requests[0]).length).toBeGreaterThan(900_000);expect(JSON.stringify(requests[1].input)).toContain('data:image/png;base64,');expect(requests[1].previous_response_id).toBe(scenario.toggleFast ? undefined : 'resp_0');diff --git a/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.ts b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.tsindex f94b550c5e..0df3d80040 100644--- a/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piSubscriptionWebsocket.test.ts@@ -1,13 +1,17 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createWebSocketMessageTransform } from '@cindy/anthropic-compat-proxy';-const state = vi.hoisted(() => ({ owner: 'owner-a', pending: false, provider: 'openai' as string | null, guest: false, hosted: false }));+const state = vi.hoisted(() => ({ owner: 'owner-a', pending: false, provider: 'openai' as string | null, guest: false, hosted: false, fastAllowed: true }));vi.mock('../../appSessionState.js', () => ({ activeOwnerScopeKey: () => state.owner, isAppSessionBoundaryPending: () => state.pending }));vi.mock('../codex-account-auth.js', () => ({ isOpenAiSubscriptionProviderId: (id: string) => id === 'openai' || id === 'account-b' }));vi.mock('../session-provider-store.js', () => ({ getSessionProvider: () => state.provider, hasHostedSessionModelAccess: () => state.hosted }));vi.mock('../guest-provider-route-store.js', () => ({ guestProviderRouteForSession: () => state.guest ? {} : null }));vi.mock('../anthropic-responses-bridge-host.js', () => ({ getChatgptBridgeAuthForDispatch: vi.fn() }));-import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream } from '../pi-subscription-websocket.js';+vi.mock('../subscription-fast-request-policy.js', () => ({ subscriptionRequestAllowsFast: vi.fn(() => state.fastAllowed) }));++import { subscriptionRequestAllowsFast } from '../subscription-fast-request-policy.js';+import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream, piWebSocketTransforms } from '../pi-subscription-websocket.js';import { registerPiProxySession, resetPiProxySessionsForTest } from '../pi-proxy-session-auth.js';const context = (provider = 'openai', token = 'fixture-token') => ({ url: '/codex/responses', headers: {@@ -18,11 +22,50 @@ const context = (provider = 'openai', token = 'fixture-token') => ({ url: '/code'openai-beta': 'responses_websockets=2026-02-06',} });+function frame(body: unknown): Buffer {+ const payload = Buffer.from(JSON.stringify(body));+ const mask = Buffer.from([1, 2, 3, 4]);+ const header = Buffer.alloc(payload.length < 126 ? 6 : 8);+ header[0] = 129; header[1] = 128 | (payload.length < 126 ? payload.length : 126);+ if (payload.length >= 126) header.writeUInt16BE(payload.length, 2);+ mask.copy(header, header.length - 4);+ for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4]!;+ return Buffer.concat([header, payload]);+}+describe('Pi subscription WebSocket routing', () => {beforeEach(() => {resetPiProxySessionsForTest();state.owner = 'owner-a'; state.pending = false; state.provider = 'openai';- state.guest = false; state.hosted = false;+ state.guest = false; state.hosted = false; state.fastAllowed = true;+ });++ // Regression #7427: the native Fast intent can remain true before the policy poll.+ // A reused socket must enforce the live account/task restriction on the actual request.+ it('downgrades stale Fast intent on reused sockets and preserves unrelated messages', async () => {+ registerPiProxySession('fixture-session', 'fixture-token', () => 'openai');+ const { outbound, inbound } = piWebSocketTransforms(context());+ const messages: unknown[] = [];+ const decode = createWebSocketMessageTransform(true, bytes => {+ messages.push(JSON.parse(bytes.toString())); return bytes;+ });+ outbound.pipe(decode); decode.resume();+ const send = (body: unknown) => new Promise<void>((resolve, reject) =>+ outbound.write(frame(body), error => error ? reject(error) : resolve()));+ try {+ const request = { type: 'response.create', model: 'gpt-6-astra', service_tier: 'priority', previous_response_id: 'resp_fixture', input: [{ type: 'function_call_output', call_id: 'call_fixture', output: 'next' }] };+ await send(request);+ expect(messages.at(-1)).toEqual(request);+ state.fastAllowed = false; // No timer, setFastMode, or notification has run.+ await send(request);+ expect(messages.at(-1)).toEqual({ ...request, service_tier: 'default' });+ expect(subscriptionRequestAllowsFast).toHaveBeenLastCalledWith('fixture-session', 'openai');+ const cancel = { type: 'response.cancel', response_id: 'resp_fixture' };+ await send(cancel); expect(messages.at(-1)).toEqual(cancel);+ state.fastAllowed = true;+ await send({ ...request, service_tier: 'default' });+ expect(messages.at(-1)).toEqual({ ...request, service_tier: 'default' });+ } finally { outbound.destroy(); inbound.destroy(); decode.destroy(); }});it('keeps hosted and shared-provider routes on HTTP for live per-model authorization', () => {diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex efc67fed41..6e173efa1c 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -53,7 +53,7 @@ import { outboundFetch } from './outbound-fetch.js';import { invocationModelRecord, requiresNativeProviderAuth } from './pi-provider-transport.js';import { createClaudeProviderBridge } from './claude-provider-bridge.js';import { isOpenAiSubscriptionProviderId } from './codex-account-auth.js';-import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream } from './pi-subscription-websocket.js';+import { createPiWebSocketRequestPreparer, resolvePiWebSocketUpstream, piWebSocketTransforms } from './pi-subscription-websocket.js';import { isClaudeSubscriptionProviderId, isXaiSubscriptionProviderId } from './subscription-account-auth.js';import {getPiNativeSubscriptionHandler,@@ -1166,6 +1166,7 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {upstream: () => claudeUpstreamEndpoint(),resolveWebSocketUpstream: resolvePiWebSocketUpstream,prepareWebSocketRequest: createPiWebSocketRequestPreparer(),+ webSocketTransforms: piWebSocketTransforms,oversizedRequestRecovery: createAttachmentRecovery(headers => {const piSessionId = headerValue(headers, 'x-cindy-pi-session-id');if (piSessionId) {diff --git a/apps/desktop/src/main/maker-host/pi-subscription-websocket.ts b/apps/desktop/src/main/maker-host/pi-subscription-websocket.tsindex 5ab2da156f..9d3a9b9dec 100644--- a/apps/desktop/src/main/maker-host/pi-subscription-websocket.ts+++ b/apps/desktop/src/main/maker-host/pi-subscription-websocket.ts@@ -1,4 +1,7 @@-import { type ProxyOptions } from '@cindy/anthropic-compat-proxy';+import { PassThrough } from 'node:stream';+import { standardSpeedRequest } from '@cindy/maker-core';+import { subscriptionRequestAllowsFast } from './subscription-fast-request-policy.js';+import { createWebSocketMessageTransform, type ProxyOptions } from '@cindy/anthropic-compat-proxy';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';import { getChatgptBridgeAuthForDispatch } from './anthropic-responses-bridge-host.js';import { isOpenAiSubscriptionProviderId } from './codex-account-auth.js';@@ -59,3 +62,18 @@ export function createPiWebSocketRequestPreparer(} };};}++/** Enforce live account/task Fast restrictions at each response.create dispatch. */+export const piWebSocketTransforms: NonNullable<ProxyOptions['webSocketTransforms']> = (ctx) => {+ const route = authenticatedRoute(ctx);+ if (!route) throw new Error('PI_WEBSOCKET_ROUTE_UNAVAILABLE');+ return {+ outbound: createWebSocketMessageTransform(true, message => {+ // Check after the complete message arrives, including fragmented requests.+ if (subscriptionRequestAllowsFast(route.sessionId, route.providerId)) return message;+ const restricted = standardSpeedRequest(JSON.parse(message.toString('utf8')));+ return restricted === null ? message : Buffer.from(JSON.stringify(restricted));+ }),+ inbound: new PassThrough(),+ };+};