import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement } from 'react'; import type { Root } from 'react-dom/client'; import { paperPromotionPreviewSchema, type PaperDeployment, type PaperPromotionInput, } from '@stock-bot/stock-config/paper-deployments'; import { paperConfig } from '../fixtures/paper-runtime'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }), names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const, old = names.map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const); let createRoot: typeof import('react-dom/client').createRoot, router: typeof import('react-router-dom'), Page: typeof import('../../apps/stock/web-app/src/features/paper/PaperDeploymentsPage').PaperDeploymentsPage, Detail: typeof import('../../apps/stock/web-app/src/features/paper/PaperDeploymentPage').PaperDeploymentPage, api: typeof import('../../apps/stock/web-app/src/features/paper/paperApi').paperApi, ApiError: typeof import('../../apps/stock/web-app/src/features/paper/paperApi').PaperApiError, validationApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi').chronologicalValidationDurableApi, experimentApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentApi').experimentApi; let root: Root | undefined, host: HTMLDivElement; const restore: Array<() => void> = []; const id = '11111111-1111-4111-8111-111111111111', testId = '22222222-2222-4222-8222-222222222222', costId = '33333333-3333-4333-8333-333333333333', hash = 'a'.repeat(64); const configuration = paperConfig(); const transport = { accountId: 'new-paper', sessionId: 'new-session', quoteSeriesId: 'X:quote', riskSession: configuration.matching.risk.ledger.riskSession, policy: configuration.policy, }; function preview(input: PaperPromotionInput) { return paperPromotionPreviewSchema.parse({ version: 'paper-promotion-preview/v1', previewHash: hash, input, strategy: { familyId: id, versionId: id, reviewId: id, origin: 'candidate', artifactSha256: hash, dependencyLockSha256: hash, }, configuration: { ...configuration, version: 2 }, host: { version: 'paper-host/v1', hostSha256: hash, engineWrapperSha256: hash, engineBinarySha256: hash, dependencyLockSha256: hash, runtime: 'bun', runtimeVersion: 'test', platform: 'linux', arch: 'x64', }, evidence: { test: { runId: testId, datasetHash: hash, economicHash: hash, resultHash: hash, metrics: { totalReturn: null }, fillCount: 0, limitations: [], }, costs: [ { runId: costId, datasetHash: hash, economicHash: hash, resultHash: hash, metrics: { totalReturn: 0 }, fillCount: 0, limitations: [], }, { runId: id, datasetHash: hash, economicHash: hash, resultHash: hash, metrics: { totalReturn: -0.1 }, fillCount: 1, limitations: [], }, ], }, limitations: ['Trusted code requires human review.'], }); } function patch(object: T, key: K, value: T[K]) { const previous = object[key]; object[key] = value; restore.push(() => { object[key] = previous; }); } async function flush(fn: () => void = () => {}) { await act(async () => { fn(); await Promise.resolve(); }); } function button(text: string) { const value = [...host.querySelectorAll('button')].find(e => e.textContent?.trim() === text); if (!value) { throw new Error('Missing button ' + text); } return value; } function fieldEvent(label: string, value: string) { const element = host.querySelector(`[aria-label="${label}"]`)!; const prototype = element.tagName === 'TEXTAREA' ? browser.HTMLTextAreaElement.prototype : browser.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(element, value); element.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event); } async function fill(label: string, value: string) { await flush(() => fieldEvent(label, value)); } function LocationProbe() { return createElement('output', { 'aria-label': 'Route' }, router.useLocation().pathname); } async function mount() { root = createRoot(host); await flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: ['/paper'] }, createElement(Page), createElement(LocationProbe) ) ) ); } beforeAll(async () => { Object.defineProperty(globalThis, 'window', { value: browser, configurable: true }); Object.defineProperty(globalThis, 'document', { value: browser.document, configurable: true }); Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true, }); createRoot = (await import('react-dom/client')).createRoot; router = await import('react-router-dom'); ({ PaperDeploymentsPage: Page } = await import( '../../apps/stock/web-app/src/features/paper/PaperDeploymentsPage' )); ({ PaperDeploymentPage: Detail } = await import( '../../apps/stock/web-app/src/features/paper/PaperDeploymentPage' )); ({ paperApi: api, PaperApiError: ApiError } = await import( '../../apps/stock/web-app/src/features/paper/paperApi' )); validationApi = ( await import( '../../apps/stock/web-app/src/features/experiments/services/chronologicalValidationDurableApi' ) ).chronologicalValidationDurableApi; experimentApi = ( await import('../../apps/stock/web-app/src/features/experiments/services/experimentApi') ).experimentApi; }); beforeEach(() => { host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.appendChild(host as never); patch(api, 'list', async () => ({ deployments: [] })); }); afterEach(async () => { await flush(() => root?.unmount()); root = undefined; host.remove(); for (const reset of restore.splice(0).reverse()) { reset(); } }); afterAll(() => { for (const [name, value] of old) { if (value) { Object.defineProperty(globalThis, name, value); } else { delete (globalThis as Record)[name]; } } browser.happyDOM.cancelAsync(); }); async function review() { patch( validationApi, 'get', async () => ({ id, report: { id, reportHash: hash, previewHash: hash, test: { runId: testId } }, }) as never ); patch( experimentApi, 'get', async () => ({ id: costId, previewHash: hash, preview: { version: 'cost-sensitivity-preview/v1', candidates: [{ costs: { feeRate: '0', slippageRate: '0' } }], }, trials: [{ runId: costId, status: 'completed' }], }) as never ); patch(api, 'preview', async input => preview(input)); await fill('Deployment name', 'Reviewed candidate'); await fill('Report owner ID', id); await fill('Cost experiment ID', costId); await flush(() => button('Load evidence').click()); await fill('Paper transport', JSON.stringify(transport)); await fill('Review rationale', 'I reviewed exact evidence and strategy'); await flush(() => (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click() ); await flush(() => button('Preview promotion').click()); } test('empty/loading/error states and explicit human review precede promotion; cost data never implies approval', async () => { await mount(); expect(host.textContent).toContain('No paper deployments yet'); expect(host.textContent).toContain('Live trading is unavailable'); await flush(() => button('Preview promotion').click()); expect(host.textContent).toContain('Load sealed test'); await review(); expect(host.textContent).toContain('candidate'); expect(host.textContent).toContain('Test return: Unavailable'); expect(host.textContent).toContain('Trusted code requires human review.'); expect(button('Create halted deployment').disabled).toBe(false); await fill('Review rationale', 'Changed review'); expect(host.textContent).not.toContain('Exact promotion preview'); }); test('uncertain create freezes the exact preview and retries the same idempotency key', async () => { const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = []; patch(api, 'create', async (input, previewHash, key) => { requests.push({ input, previewHash, key }); throw new ApiError('Response lost', null); }); await mount(); await review(); await flush(() => button('Create halted deployment').click()); expect(host.textContent).toContain('draft is frozen'); expect((host.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBe(true); await flush(() => button('Retry same promotion receipt').click()); expect(requests).toHaveLength(2); expect(requests[1]!).toEqual(requests[0]!); }); test('same-event withdrawal of trusted-code authorization cannot preview or submit the previous consent', async () => { await mount(); await review(); const previews: PaperPromotionInput[] = [], creates: PaperPromotionInput[] = []; patch(api, 'preview', async input => { previews.push(input); return preview(input); }); patch(api, 'create', async input => { creates.push(input); throw new ApiError('Unexpected create', 422); }); const oldCreate = button('Create halted deployment'); await flush(() => { (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click(); button('Preview promotion').click(); oldCreate.click(); }); expect(previews).toHaveLength(0); expect(creates).toHaveLength(0); expect(host.textContent).not.toContain('Exact promotion preview'); expect( (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).checked ).toBe(false); await flush(() => (host.querySelector('[aria-label="Authorize trusted paper code"]') as HTMLInputElement).click() ); await fill('Deployment name', 'Current draft'); await flush(() => button('Preview promotion').click()); expect(previews).toHaveLength(1); expect(previews[0]?.name).toBe('Current draft'); }); test('same-event edits cannot discard an inflight receipt or mutate an uncertain promotion draft', async () => { const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = []; let rejectCreate: (cause: Error) => void = () => { throw new Error('Create not started'); }; const pendingCreate = new Promise((_resolve, reject) => { rejectCreate = reject; }); patch(api, 'create', async (input, previewHash, key) => { requests.push({ input, previewHash, key }); if (requests.length === 1) { return pendingCreate; } throw new ApiError('Response still uncertain', null); }); await mount(); await review(); await flush(() => { button('Create halted deployment').click(); fieldEvent('Deployment name', 'Must not replace the submitted name'); }); expect(requests).toHaveLength(1); expect((host.querySelector('[aria-label="Deployment name"]') as HTMLInputElement).value).toBe( 'Reviewed candidate' ); await flush(() => rejectCreate(new ApiError('Response lost', null))); expect(host.textContent).toContain('draft is frozen'); await flush(() => { fieldEvent('Review rationale', 'Must not replace the frozen rationale'); button('Retry same promotion receipt').click(); }); expect(requests).toHaveLength(2); expect(requests.slice(1)).toEqual(requests.slice(0, 1)); expect(requests[1]?.input.name).toBe('Reviewed candidate'); expect(requests[1]?.input.reason).toBe('I reviewed exact evidence and strategy'); }); test('owned links confirm discarding pending or uncertain receipts and refusal preserves the exact retry', async () => { patch(api, 'list', async () => ({ deployments: [savedDeployment()] })); const requests: Array<{ input: PaperPromotionInput; previewHash: string; key: string }> = []; let rejectCreate: (cause: Error) => void = () => { throw new Error('Create not started'); }; const pendingCreate = new Promise((_resolve, reject) => { rejectCreate = reject; }); patch(api, 'create', async (input, previewHash, key) => { requests.push({ input, previewHash, key }); if (requests.length === 1) { return pendingCreate; } throw new ApiError('Response lost', null); }); let confirmations = 0; patch(browser as unknown as Window, 'confirm', () => { confirmations++; return false; }); await mount(); await review(); const link = (href: string) => { const element = host.querySelector(`a[href="${href}"]`) as HTMLAnchorElement | null; if (!element) { throw new Error('Missing link'); } return element; }; await flush(() => { button('Create halted deployment').click(); link('/experiments').click(); }); expect(confirmations).toBe(1); expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper'); await flush(() => rejectCreate(new ApiError('Response lost', null))); await flush(() => link(`/paper/${id}`).click()); expect(confirmations).toBe(2); expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper'); await flush(() => { link('/experiments').dispatchEvent( new browser.MouseEvent('click', { bubbles: true, cancelable: true, ctrlKey: true, }) as unknown as MouseEvent ); link(`/paper/${id}`).dispatchEvent( new browser.MouseEvent('click', { bubbles: true, cancelable: true, button: 1, }) as unknown as MouseEvent ); }); expect(confirmations).toBe(2); expect(host.querySelector('[aria-label="Route"]')?.textContent).toBe('/paper'); await flush(() => button('Retry same promotion receipt').click()); expect(requests).toHaveLength(2); expect(requests.slice(1)).toEqual(requests.slice(0, 1)); }); function savedDeployment(): PaperDeployment { const input: PaperPromotionInput = { name: 'History', outOfSample: { kind: 'chronological-report/v1', validationId: id, reportId: id, reportHash: hash, previewHash: hash, }, testRunId: testId, costExperimentId: costId, costPreviewHash: hash, costRunId: costId, transport, reason: 'Reviewed', acknowledgeTrustedCode: true, }; return { id, version: 'paper-deployment/v1', principal: 'operator', createdAt: '2026-10-24T12:00:00.000Z', promotionHash: hash, preview: preview(input), }; } test('historical deployment remains visible when host is unavailable; activation stays disabled and halt can still be requested', async () => { const deployment = savedDeployment(); patch(api, 'get', async () => deployment); patch(api, 'status', async () => { throw new ApiError('Host disabled', 503); }); root = createRoot(host); await flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: [`/paper/${id}`] }, createElement( router.Routes, {}, createElement(router.Route, { path: '/paper/:deploymentId', element: createElement(Detail), }) ) ) ) ); await flush(); expect(host.textContent).toContain('Host disabled'); expect(host.textContent).toContain('History'); expect(host.textContent).toContain('Activation is unavailable'); expect([...host.querySelectorAll('button')].some(b => b.textContent === 'Activate paper')).toBe( false ); expect(button('Halt paper').disabled).toBe(false); });