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 type { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const names = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const; const globals = names.map( name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const ); let createRoot: typeof import('react-dom/client').createRoot; let router: typeof import('react-router-dom'); let Page: typeof import('../../apps/stock/web-app/src/features/research/ResearchAgentsPage').ResearchAgentsPage; let api: typeof import('../../apps/stock/web-app/src/features/research/services/researchAgentsApi').researchAgentsApi; let root: Root | undefined; let host: HTMLDivElement; const agentId = 'agent:11111111-1111-4111-8111-111111111111'; const projectId = '22222222-2222-4222-8222-222222222222'; const backtestId = '33333333-3333-4333-8333-333333333333'; const record = (extra: Partial = {}): ResearchAgentRecord => ({ id: agentId, name: 'Research worker', enabled: true, revision: 1, allowedProjectIds: [projectId], grants: [{ backtestId, policyHash: 'a'.repeat(64) }], limits: { maxActiveTrials: 1, maxTrialsPerExperiment: 10, maxBarEvaluationsPerExperiment: 100000, maxAttemptWallMs: 60000, maxAttempts: 3, }, createdAt: '2026-10-24T12:00:00.000Z', updatedAt: '2026-10-24T12:00:00.000Z', ...extra, }); type Pending = { path: string; method: string; body: unknown; resolve: (response: Response) => void; reject: (error: Error) => void; settled: boolean; }; const calls: Pending[] = []; function pending(path = '', method = 'GET') { const value = calls.find( call => !call.settled && call.path === `/api/v2/research-agents${path}` && call.method === method ); if (!value) { throw new Error(`Missing request ${method} ${path}`); } return value; } function reply(call: Pending, body: unknown, status = 200) { call.settled = true; call.resolve(Response.json(body, { status })); } async function flush(action: () => void = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } function button(text: string) { const value = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === text ); if (!value) { throw new Error(`Missing button ${text}`); } return value; } async function fill(label: string, value: string) { await flush(() => { const input = host.querySelector(`[aria-label="${label}"]`)!; const prototype = input.tagName === 'TEXTAREA' ? browser.HTMLTextAreaElement.prototype : browser.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value); input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event); }); } async function mount(agents: ResearchAgentRecord[] = []) { root = createRoot(host); await flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: [`/research/agents?projectId=${projectId}`] }, createElement(Page) ) ) ); await flush(() => reply(pending(), { agents })); } async function draft() { await fill('Agent name', 'Research worker'); await fill('Allowed backtest IDs', backtestId); } beforeAll(async () => { for (const [name, value] of Object.entries({ window: browser, document: browser.document, IS_REACT_ACT_ENVIRONMENT: true, })) { Object.defineProperty(globalThis, name, { configurable: true, writable: true, value }); } ({ createRoot } = await import('react-dom/client')); router = await import('react-router-dom'); ({ ResearchAgentsPage: Page } = await import( '../../apps/stock/web-app/src/features/research/ResearchAgentsPage' )); ({ researchAgentsApi: api } = await import( '../../apps/stock/web-app/src/features/research/services/researchAgentsApi' )); }); beforeEach(() => { calls.length = 0; host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => new Promise((resolve, reject) => { calls.push({ path: new URL(String(input)).pathname, method: init?.method ?? 'GET', body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, resolve, reject, settled: false, }); })) as unknown as typeof browser.fetch; }); afterEach(async () => { if (root) { await flush(() => root!.unmount()); } root = undefined; host.remove(); }); afterAll(() => { browser.happyDOM.abort(); for (const [name, descriptor] of globals) { if (descriptor) { Object.defineProperty(globalThis, name, descriptor); } else { Reflect.deleteProperty(globalThis, name); } } }); test('explicit scoped creation posts one bounded policy, shows credential once and never starts work', async () => { await mount(); expect(host.textContent).toContain('No research agents configured.'); expect( (host.querySelector('[aria-label="Allowed project IDs"]') as HTMLTextAreaElement).value ).toBe(projectId); await draft(); await flush(() => { button('Create credential').click(); button('Create credential').click(); }); const request = pending('', 'POST'); expect(request.body).toEqual({ name: 'Research worker', allowedProjectIds: [projectId], allowedBacktestIds: [backtestId], limits: record().limits, }); expect(calls.filter(call => call.method === 'POST')).toHaveLength(1); await flush(() => reply(request, { agent: record(), token: 'fixture-generated-credential' }, 201) ); expect( (host.querySelector('[aria-label="New research token"]') as HTMLTextAreaElement).value ).toBe('fixture-generated-credential'); expect(button('Create credential').disabled).toBe(true); expect(host.textContent).toContain('Revision 1'); expect(host.textContent).toContain('a'.repeat(64)); await flush(() => button('I have saved the credential').click()); expect(host.querySelector('[aria-label="New research token"]')).toBeNull(); expect(calls.some(call => /runs|experiments|paper/.test(call.path))).toBe(false); }); test('malformed scope and invalid budgets preserve draft without writing', async () => { await mount(); await draft(); await fill('Maximum active trials', '0'); await flush(() => host .querySelector('form')! .dispatchEvent( new browser.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event ) ); expect(host.textContent).toContain('limits.maxActiveTrials'); expect(calls.some(call => call.method === 'POST')).toBe(false); await fill('Maximum active trials', '1'); await fill('Allowed project IDs', 'not-a-uuid'); await flush(() => button('Create credential').click()); expect(host.textContent).toContain('allowedProjectIds'); expect(calls.some(call => call.method === 'POST')).toBe(false); expect((host.querySelector('[aria-label="Agent name"]') as HTMLInputElement).value).toBe( 'Research worker' ); }); test('ambiguous creation forbids blind retry and permits inspecting and disabling the retained credential', async () => { await mount(); await draft(); await flush(() => button('Create credential').click()); const request = pending('', 'POST'); await flush(() => { request.settled = true; request.reject(new Error('Response lost')); }); expect(host.textContent).toContain('token cannot be recovered'); expect(button('Create credential').disabled).toBe(true); expect(button('I have checked the saved agents').disabled).toBe(true); await flush(() => button('I have checked the saved agents').click()); expect(button('Create credential').disabled).toBe(true); await flush(() => button('Create credential').click()); expect(calls.filter(call => call.method === 'POST')).toHaveLength(1); await flush(() => button('Check saved agents').click()); await flush(() => reply(pending(), { error: 'List unavailable' }, 503)); expect(button('I have checked the saved agents').disabled).toBe(true); await flush(() => button('Check saved agents').click()); expect(button('I have checked the saved agents').disabled).toBe(true); await flush(() => reply(pending(), { agents: [record()] })); expect(button('I have checked the saved agents').disabled).toBe(false); await flush(() => button('Disable Research worker').click()); expect(pending(`/${encodeURIComponent(agentId)}`, 'PATCH').body).toEqual({ expectedRevision: 1, enabled: false, }); await flush(() => reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), { agent: record({ enabled: false, revision: 2 }), }) ); expect(host.textContent).toContain('Disabled'); expect(button('Create credential').disabled).toBe(true); await flush(() => button('I have checked the saved agents').click()); expect(button('Create credential').disabled).toBe(false); }); test('failed list is explicit and refresh recovers; obsolete budget response cannot replace refreshed state', async () => { await mount([record()]); await flush(() => button('Check budget for Research worker').click()); const old = pending(`/${encodeURIComponent(agentId)}/budget`); await flush(() => button('Refresh agents').click()); await flush(() => reply(pending(), { error: 'Store unavailable' }, 503)); expect(host.textContent).toContain('Store unavailable'); expect(host.textContent).not.toContain('No research agents configured'); await flush(() => button('Refresh agents').click()); await flush(() => reply(pending(), { agents: [record()] })); await flush(() => reply(old, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 })); expect(host.textContent).not.toContain('Active trials:'); await flush(() => button('Check budget for Research worker').click()); await flush(() => reply(pending(`/${encodeURIComponent(agentId)}/budget`), { agent: record(), activeTrials: 1, remainingActiveTrials: 0, }) ); expect(host.textContent).toContain('Active trials: 1; available slots: 0'); }); test('policy conflict refreshes rather than overwriting the newer revision', async () => { await mount([record()]); await flush(() => button('Disable Research worker').click()); await flush(() => reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), { error: 'Revision changed' }, 409) ); expect(host.textContent).toContain('Refresh to verify'); await flush(() => reply(pending(), { agents: [record({ revision: 3, enabled: false })] })); expect(host.textContent).toContain('Revision 3'); expect(calls.filter(call => call.method === 'PATCH')).toHaveLength(1); }); test('budget identity/capacity and update identity/revision mismatches reject', async () => { const budget = api.budget(agentId); reply(pending(`/${encodeURIComponent(agentId)}/budget`), { agent: record(), activeTrials: 1, remainingActiveTrials: 1, }); await expect(budget).rejects.toThrow('capacity mismatch'); const update = api.update(agentId, { expectedRevision: 1, enabled: false }); reply(pending(`/${encodeURIComponent(agentId)}`, 'PATCH'), { agent: record({ revision: 1, enabled: false }), }); await expect(update).rejects.toThrow('revision mismatch'); }); test('unmount fences late credential response', async () => { await mount(); await draft(); await flush(() => button('Create credential').click()); const request = pending('', 'POST'); await flush(() => root!.unmount()); root = undefined; await flush(() => reply(request, { agent: record(), token: 'fixture-late-credential' }, 201)); expect(host.textContent).toBe(''); }); test('per-agent budget request order fences older success and failure responses', async () => { await mount([record()]); const path = `/${encodeURIComponent(agentId)}/budget`; const newerRequest = () => { const value = calls .filter(call => !call.settled && call.path === `/api/v2/research-agents${path}`) .at(-1); if (!value) { throw new Error('Missing newer budget request'); } return value; }; await flush(() => button('Check budget for Research worker').click()); const olderSuccess = pending(path); await flush(() => button('Check budget for Research worker').click()); const newestSuccess = newerRequest(); expect(newestSuccess).not.toBe(olderSuccess); await flush(() => reply(newestSuccess, { agent: record(), activeTrials: 0, remainingActiveTrials: 1 }) ); await flush(() => reply(olderSuccess, { agent: record(), activeTrials: 1, remainingActiveTrials: 0 }) ); expect(host.textContent).toContain('Active trials: 0; available slots: 1'); await flush(() => button('Check budget for Research worker').click()); const olderFailure = pending(path); await flush(() => button('Check budget for Research worker').click()); await flush(() => reply(newerRequest(), { agent: record(), activeTrials: 1, remainingActiveTrials: 0 }) ); await flush(() => reply(olderFailure, { error: 'Obsolete unavailable response' }, 503)); expect(host.textContent).toContain('Active trials: 1; available slots: 0'); expect(host.textContent).not.toContain('Obsolete unavailable response'); }); test('owned candidate permission is explicit per template and visible on saved grants', async () => { await mount(); await draft(); await fill('Allow own candidates on backtest IDs', backtestId); await flush(() => button('Create credential').click()); const request = pending('', 'POST'); expect(request.body).toMatchObject({ allowOwnCandidateBacktestIds: [backtestId] }); await flush(() => reply( request, { agent: record({ grants: [{ backtestId, policyHash: 'a'.repeat(64), allowOwnCandidates: true }], }), token: 'fixture-only-token', }, 201 ) ); expect(host.textContent).toContain('Owned isolated candidates allowed'); expect( ( host.querySelector( '[aria-label="Allow own candidates on backtest IDs"]' ) as HTMLTextAreaElement ).value ).toBe(''); });