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。

fix(pi): propagate native stream failures

Chris3cf8b2cfe653
diff --cc apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
index 7751d81ec1,0000000000..0ea37fabe4
mode 100644,000000..100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@@ -1,210 -1,0 +1,251 @@@
+import { EventEmitter } from 'node:events';
+import { describe, expect, it, vi } from 'vitest';
+
++import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';
++
+vi.mock('electron', () => ({
+ app: { getPath: () => '/tmp/cindy-pi-native-forwarding-test' },
+}));
+
+vi.mock('../logger-adapter.js', () => ({
+ createMakerLogger: () => {
+ const make = (): Record<string, unknown> => ({
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+ child: vi.fn(() => make()),
+ });
+ return make();
+ },
+ desktopMakerLogger: {
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+ child: vi.fn(() => ({
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+ child: vi.fn(),
+ })),
+ },
+}));
+
+import {
+ getPiNativeSubscriptionHandler,
+ type PiNativeSubscriptionHandlerDeps,
+} from '../anthropic-responses-bridge-host.js';
+
+function responseRecorder() {
+ const response = new EventEmitter() as EventEmitter & {
+ destroyed: boolean;
+ headersSent: boolean;
+ status: number;
+ headers: Record<string, string>;
+ chunks: Buffer[];
+ writeHead: (status: number, headers?: Record<string, string>) => void;
+ write: (chunk: Uint8Array | string) => boolean;
+ end: (chunk?: Uint8Array | string) => void;
+ };
+ response.destroyed = false;
+ response.headersSent = false;
+ response.status = 0;
+ response.headers = {};
+ response.chunks = [];
+ response.writeHead = (status, headers = {}) => {
+ response.status = status;
+ response.headers = headers;
+ response.headersSent = true;
+ };
+ response.write = (chunk) => {
+ response.chunks.push(Buffer.from(chunk));
+ return true;
+ };
+ response.end = (chunk) => {
+ if (chunk !== undefined) response.chunks.push(Buffer.from(chunk));
+ };
+ return response;
+}
+
+function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativeSubscriptionHandlerDeps {
+ return {
+ fetch: vi.fn(async () => new Response('ok', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ })) as PiNativeSubscriptionHandlerDeps['fetch'],
+ getChatgptAuth: vi.fn(async () => ({ accessToken: 'host-openai-token', accountId: 'account-1' })),
+ getGrokToken: vi.fn(async () => 'host-xai-token'),
+ invalidateChatgpt: vi.fn(async () => false),
+ invalidateXai: vi.fn(async () => 'ignored' as const),
+ recordXaiRateLimit: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe('PI native subscription forwarding', () => {
+ it('forwards Codex Responses bytes unchanged with host-owned ChatGPT auth', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const injected = deps({ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'] });
+ const handler = getPiNativeSubscriptionHandler('openai', 'session-1', injected);
+ const rawBody = Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x01]);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody,
+ parsedBody: undefined,
+ ctx: {
+ reqId: 1,
+ method: 'POST',
+ url: '/codex/responses',
+ headers: {
+ 'content-type': 'application/json',
+ 'content-encoding': 'zstd',
+ authorization: 'Bearer placeholder-that-must-not-leak',
+ },
+ },
+ res,
+ } as never);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(url).toBe('https://chatgpt.com/backend-api/codex/responses');
+ expect(init?.headers).toMatchObject({
+ authorization: 'Bearer host-openai-token',
+ 'chatgpt-account-id': 'account-1',
+ 'content-encoding': 'zstd',
+ 'content-type': 'application/json',
+ });
+ expect(Buffer.from(init?.body as Uint8Array)).toEqual(rawBody);
+ expect(JSON.stringify(init?.headers)).not.toContain('placeholder-that-must-not-leak');
+ expect(res.status).toBe(200);
+ expect(Buffer.concat(res.chunks).toString('utf8')).toContain('event: done');
+ });
+
++ it('destroys the local bridge response when a native upstream stream fails after headers', async () => {
++ const upstreamError = new Error('native upstream disconnected mid-stream');
++ let sentFirstChunk = false;
++ const body = new ReadableStream<Uint8Array>({
++ pull(controller) {
++ if (!sentFirstChunk) {
++ sentFirstChunk = true;
++ controller.enqueue(Buffer.from('event: response.output_text.delta\ndata: {"delta":"partial"}\n\n'));
++ return;
++ }
++ controller.error(upstreamError);
++ },
++ });
++ const handler = getPiNativeSubscriptionHandler('openai', 'session-stream-error', deps({
++ fetch: vi.fn(async () => new Response(body, {
++ status: 200,
++ headers: { 'content-type': 'text/event-stream' },
++ })) as PiNativeSubscriptionHandlerDeps['fetch'],
++ }));
++ const proxy = await createAnthropicCompatProxy({
++ upstream: null,
++ transformRequest: [],
++ routingTransform: () => ({ localHandler: handler }),
++ });
++
++ try {
++ await expect((async () => {
++ const response = await fetch(`${proxy.url}/codex/responses`, {
++ method: 'POST',
++ headers: { 'content-type': 'application/json' },
++ body: '{}',
++ });
++ await response.text();
++ })()).rejects.toThrow();
++ } finally {
++ await proxy.dispose();
++ }
++ });
++
+ it('forwards xAI Chat Completions natively and invalidates the failed host token', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('{"error":"expired"}', {
+ status: 401,
+ headers: { 'content-type': 'application/json' },
+ }));
+ const invalidateXai = vi.fn(async () => 'ignored' as const);
+ const injected = deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ invalidateXai,
+ });
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-2', injected);
+ const rawBody = Buffer.from('{"model":"grok-build-0.1"}');
+ const res = responseRecorder();
+
+ await handler({
+ rawBody,
+ parsedBody: undefined,
+ ctx: {
+ reqId: 2,
+ method: 'POST',
+ url: '/v1/chat/completions',
+ headers: { 'content-type': 'application/json' },
+ },
+ res,
+ } as never);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.x.ai/v1/chat/completions',
+ expect.objectContaining({
+ headers: expect.objectContaining({ authorization: 'Bearer host-xai-token' }),
+ }),
+ );
+ expect(invalidateXai).toHaveBeenCalledWith(expect.objectContaining({
+ status: 401,
+ failedAccessToken: 'host-xai-token',
+ }));
+ expect(res.status).toBe(401);
+ expect(Buffer.concat(res.chunks).toString('utf8')).toContain('expired');
+ });
+
+ it('records only xAI rate-limit headers that are actually present', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>
+ new Response('event: done\n\n', {
+ status: 200,
+ headers: {
+ 'content-type': 'text/event-stream',
+ 'x-ratelimit-remaining-requests': '9',
+ },
+ }));
+ const recordXaiRateLimit = vi.fn();
+ const injected = deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ recordXaiRateLimit,
+ });
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-rate', injected);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: Buffer.from('{}'),
+ parsedBody: {},
+ ctx: {
+ reqId: 4,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res,
+ } as never);
+
+ expect(recordXaiRateLimit).toHaveBeenCalledWith({
+ limitRequests: undefined,
+ remainingRequests: 9,
+ limitTokens: undefined,
+ remainingTokens: undefined,
+ });
+ });
+
+ it('rejects unsupported native paths without contacting an upstream', async () => {
+ const injected = deps();
+ const handler = getPiNativeSubscriptionHandler('openai', 'session-3', injected);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: Buffer.alloc(0),
+ parsedBody: undefined,
+ ctx: { reqId: 3, method: 'GET', url: '/models', headers: {} },
+ res,
+ } as never);
+
+ expect(injected.fetch).not.toHaveBeenCalled();
+ expect(res.status).toBe(404);
+ });
+});
diff --cc apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 5f8e8da2e2,eec7efbaa7..6c705795db
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@@ -325,206 -324,3 +325,211 @@@ export function getResponsesBridgeHandl
}
return _handler;
}
+
+type PiNativeSubscriptionProvider = 'openai' | 'xai';
+
+export interface PiNativeSubscriptionHandlerDeps {
+ fetch: typeof outboundFetch;
+ getChatgptAuth: typeof getChatgptBridgeAuth;
+ getGrokToken: typeof getGrokAccessToken;
+ invalidateChatgpt: typeof invalidateChatgptBridgeAuth;
+ invalidateXai: typeof invalidateXaiBridgeAuth;
+ recordXaiRateLimit: typeof recordXaiRateLimitSnapshot;
+}
+
+const defaultPiNativeSubscriptionHandlerDeps: PiNativeSubscriptionHandlerDeps = {
+ fetch: outboundFetch,
+ getChatgptAuth: getChatgptBridgeAuth,
+ getGrokToken: getGrokAccessToken,
+ invalidateChatgpt: invalidateChatgptBridgeAuth,
+ invalidateXai: invalidateXaiBridgeAuth,
+ recordXaiRateLimit: recordXaiRateLimitSnapshot,
+};
+
+function piNativeUpstreamUrl(
+ providerId: PiNativeSubscriptionProvider,
+ requestUrl: string,
+): string | null {
+ let pathname: string;
+ try {
+ pathname = new URL(requestUrl, 'http://127.0.0.1').pathname;
+ } catch {
+ return null;
+ }
+ if (providerId === 'openai') {
+ return pathname === '/codex/responses'
+ ? 'https://chatgpt.com/backend-api/codex/responses'
+ : null;
+ }
+ const normalized = pathname.startsWith('/v1/') ? pathname : `/v1${pathname}`;
+ return normalized === '/v1/responses' || normalized === '/v1/chat/completions'
+ ? `https://api.x.ai${normalized}`
+ : null;
+}
+
+function nativeResponseHeaders(response: Response): Record<string, string> {
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, name) => {
+ const lower = name.toLowerCase();
+ if (
+ lower === 'content-type'
+ || lower === 'cache-control'
+ || lower === 'retry-after'
+ || lower === 'x-request-id'
+ || lower.startsWith('x-ratelimit-')
+ || lower.startsWith('openai-')
+ ) {
+ headers[lower] = value;
+ }
+ });
+ return headers;
+}
+
+function finiteRateLimitHeader(headers: Headers, name: string): number | undefined {
+ const raw = headers.get(name);
+ if (raw === null || raw.trim().length === 0) return undefined;
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : undefined;
+}
+
+function recordNativeXaiRateLimit(
+ headers: Headers,
+ record: typeof recordXaiRateLimitSnapshot,
+): void {
+ const info = {
+ limitRequests: finiteRateLimitHeader(headers, 'x-ratelimit-limit-requests'),
+ remainingRequests: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-requests'),
+ limitTokens: finiteRateLimitHeader(headers, 'x-ratelimit-limit-tokens'),
+ remainingTokens: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-tokens'),
+ };
+ if (Object.values(info).some((value) => value !== undefined)) {
+ record(info);
+ }
+}
+
+async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res']): Promise<void> {
+ res.writeHead(response.status, nativeResponseHeaders(response));
+ if (!response.body) {
+ res.end();
+ return;
+ }
+ const reader = response.body.getReader();
+ try {
+ while (!res.destroyed) {
+ const chunk = await reader.read();
+ if (chunk.done) break;
+ if (!res.write(Buffer.from(chunk.value))) {
+ await new Promise<void>((resolve) => {
+ const done = (): void => {
+ res.off('drain', done);
+ res.off('close', done);
+ resolve();
+ };
+ res.once('drain', done);
+ res.once('close', done);
+ });
+ }
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ }
+ if (!res.destroyed) res.end();
+}
+
+/**
+ * Forward an already-native PI request. Unlike getResponsesBridgeHandler this
+ * performs no Messages/Responses conversion: PI constructs the provider's
+ * native payload, while the host only swaps placeholder loopback credentials
+ * for the connected account credential.
+ */
+export function getPiNativeSubscriptionHandler(
+ providerId: PiNativeSubscriptionProvider,
+ sessionId: string,
+ deps: PiNativeSubscriptionHandlerDeps = defaultPiNativeSubscriptionHandlerDeps,
+): LocalRequestHandler {
+ return async ({ rawBody, ctx, res }) => {
+ const upstreamUrl = piNativeUpstreamUrl(providerId, ctx.url);
+ if (ctx.method !== 'POST' || !upstreamUrl) {
+ res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
+ res.end(JSON.stringify({ error: { message: 'Unsupported PI subscription endpoint.' } }));
+ return;
+ }
+ const controller = new AbortController();
+ const abortOnClose = (): void => controller.abort();
+ res.once('close', abortOnClose);
+ try {
+ let accessToken: string;
+ let headers: Record<string, string>;
+ if (providerId === 'openai') {
+ const auth = await deps.getChatgptAuth();
+ accessToken = auth.accessToken;
+ headers = buildChatgptBridgeHeaders({
+ accessToken,
+ accountId: auth.accountId,
+ sessionId,
+ });
+ } else {
+ accessToken = await deps.getGrokToken();
+ headers = { authorization: `Bearer ${accessToken}` };
+ }
+ headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';
+ headers.accept = ctx.headers.accept ?? 'text/event-stream';
+ const contentEncoding = ctx.headers['content-encoding'];
+ if (contentEncoding) headers['content-encoding'] = contentEncoding;
+
+ const response = await deps.fetch(upstreamUrl, {
+ method: 'POST',
+ headers,
+ body: new Uint8Array(rawBody),
+ signal: controller.signal,
+ });
+ if (providerId === 'xai' && response.ok) {
+ recordNativeXaiRateLimit(response.headers, deps.recordXaiRateLimit);
+ }
+ if (!response.ok) {
+ const errorBody = Buffer.from(await response.arrayBuffer());
+ const errorText = errorBody.toString('utf8');
+ if (providerId === 'openai') {
+ await deps.invalidateChatgpt({
+ status: response.status,
+ body: errorText,
+ failedAccessToken: accessToken,
+ });
+ } else {
+ await deps.invalidateXai({
+ status: response.status,
+ body: errorText,
+ failedAccessToken: accessToken,
+ });
+ }
+ res.writeHead(response.status, nativeResponseHeaders(response));
+ res.end(errorBody);
+ return;
+ }
+ await pipeNativeResponse(response, res);
+ } catch (err) {
- if (controller.signal.aborted || res.headersSent || res.destroyed) return;
++ if (controller.signal.aborted || res.destroyed) return;
++ // Once a 200/SSE response has started, an upstream body failure cannot
++ // be converted into a structured 502. Propagate it to runLocalHandler,
++ // which destroys the client response so PI observes a transport failure
++ // instead of accepting a cleanly-ended truncated stream.
++ if (res.headersSent) throw err;
+ log.warn('PI native subscription forwarding failed', {
+ providerId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ res.writeHead(502, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ res.end(JSON.stringify({
+ error: {
+ type: 'upstream_error',
+ message: err instanceof Error ? err.message : String(err),
+ },
+ }));
+ } finally {
+ res.off('close', abortOnClose);
+ }
+ };
+}