wishforge-ide/tests/integration/codex-sdk.test.ts
eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

261 lines
10 KiB
TypeScript

import { createServer } from 'node:http';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import type { Actor } from '@wishforge/contracts';
import { ControlPlane } from '../../apps/api/src/domain/control-plane.js';
import { Connections } from '../../apps/api/src/domain/connections.js';
import { ProviderProxy } from '../../apps/api/src/domain/provider-proxy.js';
import { MemoryStore } from '../helpers/memory-store.js';
import { CodexAdapter, GitWorkspace } from '../../packages/runtime/src/index.js';
/** Real pinned SDK/CLI, local protocol fixture only: no external model or credentials. */
describe.skipIf(process.env.WF_CODEX_SDK_INTEGRATION !== '1')('Codex SDK local HTTP protocol', () => {
it('uses the configured proxy origin and consumes a complete Responses stream', async () => {
const root = await mkdtemp(path.join(tmpdir(), 'wishforge-codex-wire-'));
const requests: {
method: string;
path: string;
authorized: boolean;
model?: string;
stream?: boolean;
keys?: string[];
toolTypes?: unknown;
}[] = [];
let workingDirectory = '';
const fixtureStream = (toolCall = false) => {
if (toolCall) {
const item = {
id: 'fc_fixture',
type: 'function_call',
call_id: 'call_fixture',
name: 'exec_command',
arguments: JSON.stringify({ cmd: "printf 'LOCAL_TOOL_OK\\n' > sdk-wire.txt", workdir: workingDirectory }),
};
const response = {
id: 'resp_tool_fixture',
object: 'response',
created_at: Math.floor(Date.now() / 1000),
model: 'fixture-model',
status: 'completed',
output: [item],
usage: { input_tokens: 10, output_tokens: 3, total_tokens: 13 },
};
return new Response(
[
{ type: 'response.output_item.added', output_index: 0, item },
{ type: 'response.output_item.done', output_index: 0, item },
{ type: 'response.completed', response },
]
.map(
(event, sequence_number) =>
`event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`,
)
.join(''),
{ headers: { 'content-type': 'text/event-stream' } },
);
}
const item = {
id: 'msg_fixture',
type: 'message',
status: 'completed',
role: 'assistant',
content: [{ type: 'output_text', text: 'LOCAL_WIRE_OK', annotations: [] }],
};
const response = {
id: 'resp_fixture',
object: 'response',
created_at: Math.floor(Date.now() / 1000),
model: 'fixture-model',
status: 'completed',
output: [item],
usage: {
input_tokens: 10,
output_tokens: 3,
total_tokens: 13,
input_tokens_details: { cached_tokens: 0 },
output_tokens_details: { reasoning_tokens: 0 },
},
};
const events = [
{ type: 'response.created', response: { ...response, status: 'in_progress', output: [], usage: null } },
{ type: 'response.output_item.added', output_index: 0, item: { ...item, status: 'in_progress', content: [] } },
{
type: 'response.content_part.added',
item_id: item.id,
output_index: 0,
content_index: 0,
part: { type: 'output_text', text: '', annotations: [] },
},
{
type: 'response.output_text.delta',
item_id: item.id,
output_index: 0,
content_index: 0,
delta: 'LOCAL_WIRE_OK',
},
{
type: 'response.output_text.done',
item_id: item.id,
output_index: 0,
content_index: 0,
text: 'LOCAL_WIRE_OK',
},
{
type: 'response.content_part.done',
item_id: item.id,
output_index: 0,
content_index: 0,
part: item.content[0],
},
{ type: 'response.output_item.done', output_index: 0, item },
{ type: 'response.completed', response },
];
return new Response(
events
.map(
(event, sequence_number) =>
`event: ${event.type}\ndata: ${JSON.stringify({ ...event, sequence_number })}\n\n`,
)
.join(''),
{ headers: { 'content-type': 'text/event-stream' } },
);
};
let proxy: ProviderProxy;
let scopedToken = '';
const failures: string[] = [];
const server = createServer((req, res) => {
void (async () => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(Buffer.from(chunk));
const raw = Buffer.concat(chunks);
const body = raw.length ? JSON.parse(raw.toString()) : {};
requests.push({
method: req.method ?? '',
path: req.url ?? '',
authorized: req.headers.authorization === `Bearer ${scopedToken}`,
model: body.model,
stream: body.stream,
keys: Object.keys(body),
toolTypes: body.tools?.map((t: any) => ({
type: t.type,
name: t.name,
keys: Object.keys(t),
nested: t.tools?.map((n: any) => ({ type: n.type, name: n.name })),
})),
});
const response = await proxy.forward({
authorization: req.headers.authorization,
method: req.method ?? '',
path: (req.url ?? '').replace('/provider-proxy/v1', ''),
body: raw,
});
res.writeHead(response.status, Object.fromEntries(response.headers));
if (response.body) for await (const chunk of response.body as any) res.write(chunk);
res.end();
})().catch(error => {
failures.push(error.code ?? error.message);
if (!res.headersSent) res.writeHead(error.status ?? 500, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: { message: error.code ?? 'Fixture failed' } }));
});
});
server.on('upgrade', (_req, socket) => socket.destroy());
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const address = server.address() as { port: number };
const env = {
NODE_ENV: 'test',
WF_VAULT_KEY: 'a'.repeat(64),
WF_PROVIDER_PROXY_ENABLED: 'true',
WF_PROVIDER_PROXY_PUBLIC_URL: `http://127.0.0.1:${address.port}/provider-proxy/v1`,
WF_PROVIDER_PROXY_SIGNING_KEY: 'local-wire-proxy-signing-key-00000000000',
WF_PROVIDER_PROXY_ALLOWED_MODELS: 'fixture-model',
};
const owner: Actor = { tenantId: 'fixture', userId: 'owner', role: 'owner', kind: 'human' },
worker: Actor = { ...owner, userId: 'worker', kind: 'worker' };
const db = new MemoryStore();
db.seed('fixture');
const control = new ControlPlane(db, env);
const project = await control.createProject(owner, {
name: 'Wire fixture',
repositoryUrl: 'https://example.test/fixture.git',
});
await new Connections(db, env).create(owner, {
provider: 'codex',
label: 'Local fixture',
apiKey: 'fixture_upstream_secret_never_passed_to_sdk',
});
const { run_id } = await control.submit(
owner,
project.id,
{ goal: 'Wire fixture', acceptanceCriteria: ['Complete local stream'], budget: { maxTokens: 500000 } },
'wire-fixture-submit',
);
const run = await control.lease(worker, run_id, 'fixture-worker');
let upstreamCalls = 0;
proxy = new ProviderProxy(db, env, {
fetcher: (async (url, init) => {
expect(String(url)).toBe('https://api.openai.com/v1/responses');
expect(new Headers(init?.headers).get('authorization')).toBe(
'Bearer fixture_upstream_secret_never_passed_to_sdk',
);
upstreamCalls++;
return fixtureStream(upstreamCalls === 1);
}) as typeof fetch,
});
const credential = await proxy.credential(worker, run);
scopedToken = credential.apiKey;
const adapter = new CodexAdapter({
apiKey: credential.apiKey,
baseUrl: credential.baseUrl,
isolatedHome: path.join(root, 'provider-home'),
model: 'fixture-model',
});
const timeout = setTimeout(() => void adapter.cancel('wire').catch(() => undefined), 20000);
try {
const workspace = await new GitWorkspace().create({ root, runId: 'source' });
workingDirectory = workspace.workspace;
await adapter.start({
runId: 'wire',
tenantId: 'fixture',
workspace: workspace.workspace,
baseCommit: workspace.baseCommit,
prompt:
'Create sdk-wire.txt containing LOCAL_TOOL_OK, then respond LOCAL_WIRE_OK. Do not contact any external service.',
});
const events = [];
for await (const event of adapter.events('wire')) events.push(event);
const observed = await adapter.inspect('wire');
if (observed.status !== 'completed') throw new Error(JSON.stringify({ observed, requests, failures }));
expect(observed.status).toBe('completed');
expect(
requests.some(
r =>
r.method === 'POST' &&
r.path === '/provider-proxy/v1/responses' &&
r.authorized &&
r.stream &&
r.model === 'fixture-model',
),
).toBe(true);
expect(upstreamCalls).toBe(2);
expect(failures).toEqual([]);
expect((await control.usage(owner)).tokens).toBe(26);
expect((await readFile(path.join(workspace.workspace, 'sdk-wire.txt'), 'utf8')).trim()).toBe('LOCAL_TOOL_OK');
const checkpoint = await adapter.exportCheckpoint('wire');
expect(checkpoint.patch).toContain('sdk-wire.txt');
expect(JSON.stringify(events)).not.toContain('fixture_upstream_secret_never_passed_to_sdk');
expect(JSON.stringify(events)).toContain('LOCAL_WIRE_OK');
expect(events.some(e => e.type === 'usage' && e.data.input_tokens === 20 && e.data.output_tokens === 6)).toBe(
true,
);
} finally {
clearTimeout(timeout);
await adapter.cancel('wire').catch(() => undefined);
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
await rm(root, { recursive: true, force: true });
}
}, 30000);
});