// Creation response loss cannot be tested by daemon E2E; exercise the real web API request/recovery path. import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { stripTypeScriptTypes } from 'node:module'; import test from 'node:test'; const source = stripTypeScriptTypes( ( await readFile(new URL('../src/lib/api.ts', import.meta.url), 'utf8') ).replace(/^import type .*;\n/gm, ''), { mode: 'transform' }, ); const { createSession, ApiError } = await import( `data:text/javascript;base64,${Buffer.from(source).toString('base64')}` ); const choice = { provider_profile: 'codex', model: 'gpt-6-sol', effort: 'high', cyber_access: 'daybreak_blue', }; const intent = { kind: 'new', workspace: '/project', name: null, ...choice }; const existing = { id: 'fixed-id', creation: { submitted: intent } }; const response = (status, body) => ({ ok: status >= 200 && status < 300, status, statusText: 'rejected', headers: new Headers(), json: async () => body, }); for (const lost of [true, false]) test(`create recovers exact persisted intent after ${lost ? 'lost response' : '412 retry'}`, async (t) => { const seen = []; globalThis.fetch = async (url, init) => { seen.push({ url, init }); if (init.method === 'PUT') return lost ? Promise.reject(new TypeError('response lost')) : response(412, { code: 'precondition_failed' }); return response(200, existing); }; t.after(() => { delete globalThis.fetch; }); assert.equal(await createSession('/project', choice, 'fixed-id'), existing); assert.deepEqual( seen.map(({ url }) => url), ['/api/sessions/fixed-id', '/api/sessions/fixed-id?tail=0'], ); assert.equal(seen[0].init.headers['if-none-match'], '*'); assert.deepEqual(JSON.parse(seen[0].init.body), { kind: 'new', workspace: '/project', ...choice, }); }); test('different persisted Blue intent cannot be claimed by Standard retry', async (t) => { globalThis.fetch = async (_, init) => init.method === 'PUT' ? response(412, { code: 'precondition_failed' }) : response(200, existing); t.after(() => { delete globalThis.fetch; }); await assert.rejects( createSession('/project', { ...choice, cyber_access: null }, 'fixed-id'), (error) => error instanceof ApiError && error.status === 412, ); }); test('failed creation without persisted receipt remains failed', async (t) => { globalThis.fetch = async (_, init) => init.method === 'PUT' ? response(503, { code: 'capability_unavailable' }) : response(404, { code: 'not_found' }); t.after(() => { delete globalThis.fetch; }); await assert.rejects( createSession('/project', choice, 'fixed-id'), (error) => error instanceof ApiError && error.status === 503, ); });