import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; import { GlobalWindow } from 'happy-dom'; import { act, createElement } from 'react'; import type { Root } from 'react-dom/client'; import type { ResearchArtifact, ResearchHypothesis, ResearchProject, StrategyRecord, } from '@stock-bot/types'; const browser = new GlobalWindow({ url: 'http://localhost:5173' }); const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const; const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); let createRoot: typeof import('react-dom/client').createRoot; let router: typeof import('react-router-dom'); let ResearchListPage: typeof import('../../apps/stock/web-app/src/features/research/ResearchListPage').ResearchListPage; let ResearchProjectPage: typeof import('../../apps/stock/web-app/src/features/research/ResearchProjectPage').ResearchProjectPage; let root: Root | undefined; let host: HTMLDivElement; let navigate: ReturnType; let location = ''; function deferred() { let resolve!: (value: T) => void; let reject!: (error: Error) => void; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } type Pending = ReturnType> & { path: string; method: string; body: unknown; settled: boolean; }; const requests: Pending[] = []; function request(path: string, method = 'GET') { const found = requests.find( item => item.path === `/api/v2/${path}` && item.method === method && !item.settled ); if (!found) { throw new Error( `Missing ${method} ${path}: ${requests .filter(item => !item.settled) .map(item => item.path) .join(', ')}` ); } return found; } function reply(item: Pending, body: unknown, status = 200) { item.settled = true; item.resolve(status === 204 ? new Response(null, { status }) : Response.json(body, { status })); } async function flush(action: () => void = () => {}) { await act(async () => { action(); await Promise.resolve(); }); } function button(label: string) { const found = [...host.querySelectorAll('button')].find( item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label ); if (!found) { throw new Error(`Missing button ${label}: ${host.textContent}`); } return found; } function click(label: string) { button(label).click(); } function field(label: string) { const found = host.querySelector(`[aria-label="${label}"]`) as | HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null; if (!found) { throw new Error(`Missing field ${label}`); } return found; } function edit(label: string, value: string) { const input = field(label); const prototype = input.tagName === 'SELECT' ? browser.HTMLSelectElement.prototype : input.tagName === 'TEXTAREA' ? browser.HTMLTextAreaElement.prototype : browser.HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value); input.dispatchEvent( new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true, }) as unknown as Event ); } function Probe() { navigate = router.useNavigate(); const current = router.useLocation(); location = current.pathname + current.search; return null; } async function mount(path = '/research/p1') { root = createRoot(host); await flush(() => root!.render( createElement( router.MemoryRouter, { initialEntries: [path] }, createElement( router.Routes, null, createElement(router.Route, { path: '/research', element: createElement(ResearchListPage), }), createElement(router.Route, { path: '/research/:projectId', element: createElement(ResearchProjectPage), }) ), createElement(Probe) ) ) ); } const time = '2026-10-23T12:00:00Z'; const project = (id = 'p1', extra: Partial = {}): ResearchProject => ({ id, title: `Project ${id}`, description: 'Description', revision: 1, ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: time, updatedAt: time, ...extra, }); const hypothesis = (id = 'h1', extra: Partial = {}): ResearchHypothesis => ({ id, projectId: 'p1', ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: time, updatedAt: time, latestRevision: { id: `${id}-r1`, hypothesisId: id, ordinal: 1, title: 'Momentum hypothesis', proposition: '', validationCriteria: 'Out of sample', validationState: 'unvalidated', submittedBy: 'operator', contentOrigin: 'ai', createdAt: time, }, ...extra, }); const artifact = (id = 'a1', extra: Partial = {}): ResearchArtifact => ({ id, projectId: 'p1', hypothesisRevisionId: null, kind: 'note', ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: time, updatedAt: time, latestRevision: { id: `${id}-r1`, artifactId: id, ordinal: 1, title: 'Research note', body: '', validationState: 'unvalidated', evidenceState: 'none', evidence: [], submittedBy: 'operator', contentOrigin: 'human', createdAt: time, }, ...extra, }); const strategy: StrategyRecord = { id: 's1', name: 'Trend', description: '', ownerPrincipal: 'operator', updatedBy: 'operator', archived: false, createdAt: time, updatedAt: time, }; function replyProject( value = project(), hypotheses: ResearchHypothesis[] = [], artifacts: ResearchArtifact[] = [], strategies: StrategyRecord[] = [] ) { reply(request(`research-projects/${value.id}`), { project: value }); reply(request(`research-projects/${value.id}/strategies`), { strategies }); reply(request(`research-projects/${value.id}/hypotheses?includeArchived=true`), { hypotheses }); reply(request(`research-projects/${value.id}/analysis-artifacts?includeArchived=true`), { artifacts, }); reply(request('strategies'), { strategies: [strategy, { ...strategy, id: 'archived', name: 'Retired', archived: true }], }); } function replyHypothesis(value = hypothesis(), revisions = [value.latestRevision]) { reply(request(`hypotheses/${value.id}`), { hypothesis: value }); reply(request(`hypotheses/${value.id}/revisions`), { revisions }); } function replyArtifact(value = artifact(), revisions = [value.latestRevision]) { reply(request(`analysis-artifacts/${value.id}`), { artifact: value }); reply(request(`analysis-artifacts/${value.id}/revisions`), { revisions }); } beforeAll(async () => { for (const [key, value] of Object.entries({ window: browser, document: browser.document, IS_REACT_ACT_ENVIRONMENT: true, })) { Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); } ({ createRoot } = await import('react-dom/client')); router = await import('react-router-dom'); ({ ResearchListPage } = await import( '../../apps/stock/web-app/src/features/research/ResearchListPage' )); ({ ResearchProjectPage } = await import( '../../apps/stock/web-app/src/features/research/ResearchProjectPage' )); }); beforeEach(() => { requests.length = 0; host = browser.document.createElement('div') as unknown as HTMLDivElement; browser.document.body.append(host as never); Object.defineProperty(browser, 'confirm', { configurable: true, writable: true, value: () => true, }); browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => { const parsed = new URL(String(url)); const item: Pending = { ...deferred(), path: parsed.pathname + parsed.search, method: init?.method ?? 'GET', body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, settled: false, }; requests.push(item); return item.promise; // Deliberately ignore cancellation to exercise stale-response guards. }) as unknown as typeof browser.fetch; }); afterEach(async () => { if (root) { await flush(() => root!.unmount()); } root = undefined; host.remove(); }); afterAll(async () => { await browser.happyDOM.close(); for (const key of keys) { const descriptor = originals.get(key); if (descriptor) { Object.defineProperty(globalThis, key, descriptor); } else { delete (globalThis as Record)[key]; } } }); describe('research workspace', () => { test('project listing distinguishes loading, error and empty and retries reads', async () => { await mount('/research'); expect(host.textContent).toContain('Loading research projects'); await flush(() => reply(request('research-projects?includeArchived=false'), { error: 'Read failed' }, 503) ); expect(host.textContent).toContain('Read failed'); expect(host.textContent).not.toContain('No research projects yet'); await flush(() => click('Retry projects')); await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] })); expect(host.textContent).toContain('No research projects yet'); }); test('ambiguous project create freezes draft, prevents duplicate requests, and requires deliberate restart', async () => { await mount('/research'); await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] })); await flush(() => click('New project')); await flush(() => edit('Project title', 'Lost response')); await flush(() => { click('Create project'); click('Create project'); }); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); await flush(() => { const item = request('research-projects', 'POST'); item.settled = true; item.reject(new Error('Lost')); }); expect(field('Project title').value).toBe('Lost response'); expect(button('Create project').disabled).toBe(true); await flush(() => click('Check saved projects')); await flush(() => reply(request('research-projects?includeArchived=true'), { projects: [project()] }) ); expect(field('Project title').value).toBe('Lost response'); await flush(() => click('Start new request')); expect(button('Create project').disabled).toBe(false); }); test('late create success cannot navigate away from a newer project', async () => { await mount('/research'); await flush(() => reply(request('research-projects?includeArchived=false'), { projects: [] })); await flush(() => click('New project')); await flush(() => edit('Project title', 'Original')); await flush(() => click('Create project')); const old = request('research-projects', 'POST'); await flush(() => navigate('/research/p2')); await flush(() => replyProject(project('p2'))); await flush(() => reply(old, { project: project('p1') })); expect(location).toBe('/research/p2'); expect(host.textContent).toContain('Project p2'); }); test('section errors never masquerade as empty records and stale project responses are ignored', async () => { await mount(); const old = requests.slice(); await flush(() => navigate('/research/p2')); await flush(() => { const p = project('p2'); reply(request('research-projects/p2'), { project: p }); reply(request('research-projects/p2/strategies'), { strategies: [] }); reply( request('research-projects/p2/hypotheses?includeArchived=true'), { error: 'Hypotheses unavailable' }, 500 ); reply(request('research-projects/p2/analysis-artifacts?includeArchived=true'), { artifacts: [], }); const catalogs = requests.filter(item => item.path === '/api/v2/strategies'); reply(catalogs[1]!, { strategies: [] }); }); await flush(() => { for (const item of old) { if (item.path.endsWith('/p1')) { reply(item, { project: project('p1') }); } else if (item.path.includes('hypotheses')) { reply(item, { hypotheses: [hypothesis()] }); } else if (item.path.includes('analysis-artifacts')) { reply(item, { artifacts: [] }); } else { reply(item, { strategies: [] }); } } }); expect(host.textContent).toContain('Project p2'); expect(host.textContent).not.toContain('Project p1'); expect(host.textContent).toContain('Hypotheses unavailable'); expect(host.textContent).not.toContain('No hypotheses yet'); }); test('creates declared AI hypothesis and renders escaped, unvalidated narrative with immutable history', async () => { await mount(); await flush(() => replyProject()); await flush(() => click('New hypothesis')); await flush(() => { edit('Hypothesis title', 'Momentum hypothesis'); edit('Proposition', ''); edit('Validation criteria', 'Out of sample'); edit('Declared content origin', 'ai'); }); await flush(() => click('Create hypothesis')); expect(request('research-projects/p1/hypotheses', 'POST').body).toEqual({ title: 'Momentum hypothesis', proposition: '', validationCriteria: 'Out of sample', contentOrigin: 'ai', }); await flush(() => reply(request('research-projects/p1/hypotheses', 'POST'), { hypothesis: hypothesis() }) ); await flush(() => { replyProject(project(), [hypothesis()]); replyHypothesis(); }); expect(location).toBe('/research/p1?hypothesis=h1'); expect(host.textContent).toContain('Unvalidated narrative'); expect(host.textContent).toContain('AI-authored (declared)'); expect(host.querySelector('img')).toBeNull(); await flush(() => click('View revision 1')); await flush(() => replyHypothesis()); expect(host.textContent).toContain('Immutable history'); expect( [...host.querySelectorAll('button')].some(item => item.textContent === 'Edit latest revision') ).toBe(false); }); test('note creation sends no measured claims and preserves an ambiguous draft across record refresh', async () => { await mount(); await flush(() => replyProject()); await flush(() => click('New note')); await flush(() => { edit('Note title', 'Observation'); edit('Note body', 'Needs validation'); }); await flush(() => click('Create note')); expect(request('research-projects/p1/analysis-artifacts', 'POST').body).toEqual({ kind: 'note', title: 'Observation', body: 'Needs validation', contentOrigin: 'human', }); await flush(() => reply(request('research-projects/p1/analysis-artifacts', 'POST'), { error: 'Uncertain' }, 500) ); await flush(() => click('Check saved records')); await flush(() => replyProject(project(), [], [artifact()])); expect(field('Note body').value).toBe('Needs validation'); expect(button('Create note').disabled).toBe(true); expect(host.textContent).toContain('unvalidated narrative'); }); test('409 retains revision draft and never silently rebases onto refreshed history', async () => { await mount('/research/p1?artifact=a1'); await flush(() => replyProject(project(), [], [artifact()])); await flush(() => replyArtifact()); await flush(() => click('Edit latest revision')); await flush(() => edit('Revision body', 'Unsaved conclusion')); await flush(() => click('Save new revision')); expect(request('analysis-artifacts/a1/revisions', 'POST').body).toMatchObject({ expectedRevision: 1, body: 'Unsaved conclusion', evidence: [], }); await flush(() => reply(request('analysis-artifacts/a1/revisions', 'POST'), { error: 'Revision conflict' }, 409) ); expect(field('Revision body').value).toBe('Unsaved conclusion'); expect(button('Save new revision').disabled).toBe(true); await flush(() => click('Refresh project')); await flush(() => replyProject(project(), [], [artifact()])); expect(field('Revision body').value).toBe('Unsaved conclusion'); expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); }); test('membership refreshes project revision before the next metadata write; archived strategies remain visible', async () => { await mount(); await flush(() => replyProject()); expect(field('Strategy to link').textContent).not.toContain('Retired'); await flush(() => edit('Strategy to link', 's1')); await flush(() => click('Link strategy')); await flush(() => reply(request('research-projects/p1/strategies/s1', 'PUT'), undefined, 204)); await flush(() => replyProject(project('p1', { revision: 2 }), [], [], [{ ...strategy, archived: true }]) ); expect(host.textContent).toContain('Archived strategy'); await flush(() => click('Edit project')); await flush(() => edit('Project description', 'New description')); await flush(() => click('Save project')); expect(request('research-projects/p1', 'PATCH').body).toMatchObject({ expectedRevision: 2, description: 'New description', }); }); test('archived project retains entries and history but exposes only project restore', async () => { await mount('/research/p1?artifact=a1'); await flush(() => replyProject(project('p1', { archived: true }), [], [artifact('a1', { archived: true })]) ); await flush(() => replyArtifact(artifact('a1', { archived: true }))); expect(host.textContent).toContain('Research note'); expect(host.textContent).toContain('Revision history'); const labels = [...host.querySelectorAll('button')].map(item => item.textContent); expect(labels).toContain('Restore project'); for (const label of [ 'New note', 'New hypothesis', 'Restore entry', 'Archive entry', 'Edit latest revision', 'Link strategy', ]) { expect(labels).not.toContain(label); } await flush(() => click('Restore project')); expect(request('research-projects/p1', 'PATCH').body).toEqual({ expectedRevision: 1, archived: false, }); }); test('cross-project entries and foreign revision IDs fail visibly', async () => { await mount('/research/p1?hypothesis=h1&revision=foreign'); await flush(() => replyProject()); await flush(() => replyHypothesis()); expect(host.textContent).toContain('requested revision does not belong'); await flush(() => navigate('/research/p1?artifact=a1')); await flush(() => replyArtifact(artifact('a1', { projectId: 'p2' }))); expect(host.textContent).toContain('Artifact does not belong to this project'); expect(host.textContent).not.toContain('