stock-bot/test/integration/research-workspace-ui.test.tsx

778 lines
31 KiB
TypeScript

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<typeof router.useNavigate>;
let location = '';
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
type Pending = ReturnType<typeof deferred<Response>> & {
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> = {}): 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> = {}): 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: '<img src=x onerror=alert(1)>',
validationCriteria: 'Out of sample',
validationState: 'unvalidated',
submittedBy: 'operator',
contentOrigin: 'ai',
createdAt: time,
},
...extra,
});
const artifact = (id = 'a1', extra: Partial<ResearchArtifact> = {}): 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: '<script>doNotRun()</script>',
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<Response>(),
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<string, unknown>)[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', '<img src=x onerror=alert(1)>');
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: '<img src=x onerror=alert(1)>',
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('<script>doNotRun()');
});
test('failed refresh and remote archival retain an uncertain note draft until explicit discard', async () => {
await mount();
await flush(() => replyProject());
await flush(() => click('New note'));
await flush(() => {
edit('Note title', 'Retained title');
edit('Note body', 'Retained body');
});
await flush(() => click('Create note'));
await flush(() =>
reply(
request('research-projects/p1/analysis-artifacts', 'POST'),
{ error: 'Uncertain write' },
500
)
);
await flush(() => click('Check saved records'));
await flush(() => {
reply(request('research-projects/p1'), { error: 'Project refresh unavailable' }, 503);
reply(request('research-projects/p1/strategies'), { strategies: [] });
reply(request('research-projects/p1/hypotheses?includeArchived=true'), { hypotheses: [] });
reply(request('research-projects/p1/analysis-artifacts?includeArchived=true'), {
artifacts: [],
});
reply(request('strategies'), { strategies: [] });
});
expect(field('Note title').value).toBe('Retained title');
expect(field('Note body').value).toBe('Retained body');
expect(button('Create note').disabled).toBe(true);
expect(host.textContent).toContain('Project status could not be verified');
await flush(() => click('Refresh project'));
await flush(() => replyProject(project('p1', { archived: true })));
expect(field('Note body').value).toBe('Retained body');
expect(button('Create note').disabled).toBe(true);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
});
test('finding revisions retain exact evidence references and link archived hypothesis history', async () => {
const original = hypothesis().latestRevision;
const linked = hypothesis('h1', {
archived: true,
latestRevision: { ...original, id: 'h1-r2', ordinal: 2, title: 'Revised hypothesis' },
});
const originalNote = artifact().latestRevision;
const finding = artifact('a1', {
kind: 'finding',
hypothesisRevisionId: original.id,
latestRevision: {
...originalNote,
title: 'Finding',
evidenceState: 'referenced',
evidence: [
{
runId: '11111111-1111-4111-8111-111111111111',
backtestId: '22222222-2222-4222-8222-222222222222',
strategyVersionId: '33333333-3333-4333-8333-333333333333',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
value: 0.12,
unit: 'fraction',
availability: 'available',
unavailableReason: null,
resultKind: 'canonical',
financialEngine: 'rust',
datasetHash: 'frozen-dataset',
limitations: [],
},
],
},
});
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [linked], [finding]));
await flush(() => replyArtifact(finding));
await flush(() =>
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })
);
const historyLink = host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]');
expect(historyLink).not.toBeNull();
expect(
host.querySelector(
'a[href="/backtests/22222222-2222-4222-8222-222222222222/run/11111111-1111-4111-8111-111111111111"]'
)
).not.toBeNull();
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Updated interpretation, same evidence'));
await flush(() => click('Save new revision'));
expect(request('analysis-artifacts/a1/revisions', 'POST').body).toEqual({
expectedRevision: 1,
title: 'Finding',
body: 'Updated interpretation, same evidence',
contentOrigin: 'human',
evidence: [
{
runId: '11111111-1111-4111-8111-111111111111',
strategyVersionId: '33333333-3333-4333-8333-333333333333',
metricsVersion: 'canonical-analytics/v1',
metricPath: 'analytics.metrics.totalReturn',
},
],
});
await flush(() =>
reply(request('analysis-artifacts/a1/revisions', 'POST'), { artifact: finding })
);
await flush(() => {
replyProject(project(), [linked], [finding]);
replyArtifact(finding);
});
await flush(() =>
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] })
);
await flush(() =>
(
host.querySelector(
'a[href="/research/p1?hypothesis=h1&revision=h1-r1"]'
) as HTMLAnchorElement
).click()
);
await flush(() => replyHypothesis(linked, [original, linked.latestRevision]));
expect(host.textContent).toContain('Momentum hypothesis');
expect(host.textContent).toContain('Immutable history');
expect(
[...host.querySelectorAll('button')].some(item => item.textContent === 'Edit latest revision')
).toBe(false);
});
for (const failureFirst of [false, true]) {
test(`exact hypothesis link survives unrelated history failure (${failureFirst ? 'failure first' : 'match first'})`, async () => {
const original = hypothesis().latestRevision;
const linked = hypothesis('h1', {
latestRevision: { ...original, id: 'h1-r2', ordinal: 2 },
});
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: original.id });
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [linked, hypothesis('h2')], [finding]));
await flush(() => replyArtifact(finding));
const match = () =>
reply(request('hypotheses/h1/revisions'), {
revisions: [original, linked.latestRevision],
});
const failure = () =>
reply(request('hypotheses/h2/revisions'), { error: 'Temporary history failure' }, 503);
await flush(failureFirst ? failure : match);
await flush(failureFirst ? match : failure);
expect(
host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]')
).not.toBeNull();
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
expect(host.textContent).not.toContain('unavailable in the loaded project history');
});
}
test('incomplete hypothesis lookup remains retryable through project refresh', async () => {
const original = hypothesis().latestRevision;
const linked = hypothesis('h1', {
latestRevision: { ...original, id: 'h1-r2', ordinal: 2 },
});
const unrelated = hypothesis('h2');
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: original.id });
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [linked, unrelated], [finding]));
await flush(() => replyArtifact(finding));
await flush(() => {
reply(request('hypotheses/h1/revisions'), { error: 'Temporary history failure' }, 503);
reply(request('hypotheses/h2/revisions'), { revisions: [unrelated.latestRevision] });
});
expect(host.textContent).toContain('Could not resolve the linked hypothesis history');
expect(host.textContent).not.toContain('unavailable in the loaded project history');
expect(host.querySelector('a[href*="?hypothesis=h1&revision=h1-r1"]')).toBeNull();
await flush(() => click('Refresh project'));
await flush(() => replyProject(project(), [linked, unrelated], [finding]));
await flush(() => {
reply(request('hypotheses/h1/revisions'), { revisions: [original, linked.latestRevision] });
reply(request('hypotheses/h2/revisions'), { revisions: [unrelated.latestRevision] });
});
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
expect(
host.querySelector('a[href="/research/p1?hypothesis=h1&revision=h1-r1"]')
).not.toBeNull();
});
test('fully read hypothesis history distinguishes absence and rejects a foreign revision owner', async () => {
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: 'missing-r1' });
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [hypothesis()], [finding]));
await flush(() => replyArtifact(finding));
await flush(() =>
reply(request('hypotheses/h1/revisions'), {
revisions: [
hypothesis().latestRevision,
{ ...hypothesis('h2').latestRevision, id: 'missing-r1' },
],
})
);
expect(host.textContent).toContain('unavailable in the loaded project history');
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
expect(host.querySelector('a[href*="?hypothesis="]')).toBeNull();
});
for (const destination of ['finding', 'project'] as const) {
test(`late hypothesis resolution cannot attach to a different ${destination}`, async () => {
const original = hypothesis().latestRevision;
const linked = hypothesis('h1', {
latestRevision: { ...original, id: 'h1-r2', ordinal: 2 },
});
const finding = artifact('a1', { kind: 'finding', hypothesisRevisionId: original.id });
await mount('/research/p1?artifact=a1');
await flush(() => replyProject(project(), [linked, hypothesis('h2')], [finding]));
await flush(() => replyArtifact(finding));
const previousMatch = request('hypotheses/h1/revisions');
const previousFailure = request('hypotheses/h2/revisions');
const nextProjectId = destination === 'project' ? 'p2' : 'p1';
const next = artifact('a2', { projectId: nextProjectId, kind: 'finding' });
await flush(() => navigate(`/research/${nextProjectId}?artifact=a2`));
if (destination === 'project') {
await flush(() => replyProject(project('p2'), [], [next]));
}
await flush(() => replyArtifact(next));
await flush(() => {
reply(previousMatch, { revisions: [original, linked.latestRevision] });
reply(previousFailure, { error: 'Temporary history failure' }, 503);
});
expect(location).toBe(`/research/${nextProjectId}?artifact=a2`);
expect(host.querySelector('a[href*="?hypothesis="]')).toBeNull();
expect(host.textContent).not.toContain('Linked hypothesis revision:');
expect(host.textContent).not.toContain('Could not resolve the linked hypothesis history');
});
}
test('late entry read and late revision success cannot overwrite a newly selected entry', async () => {
await mount('/research/p1?hypothesis=h1');
await flush(() => replyProject());
const oldRead = request('hypotheses/h1');
const oldHistory = request('hypotheses/h1/revisions');
await flush(() => navigate('/research/p1?artifact=a1'));
await flush(() => replyArtifact());
await flush(() => {
reply(oldRead, { hypothesis: hypothesis() });
reply(oldHistory, { revisions: [hypothesis().latestRevision] });
});
expect(host.textContent).not.toContain('Momentum hypothesis');
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Pending revision'));
await flush(() => click('Save new revision'));
const oldSave = request('analysis-artifacts/a1/revisions', 'POST');
await flush(() => navigate('/research/p1?hypothesis=h2'));
await flush(() => replyHypothesis(hypothesis('h2')));
const before = requests.length;
await flush(() => reply(oldSave, { artifact: artifact() }));
expect(location).toBe('/research/p1?hypothesis=h2');
expect(requests).toHaveLength(before);
});
test('discarding a draft by reopening the same entry reloads it and owned navigation respects refusal', 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', 'Discard me'));
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => false,
});
await flush(() => (host.querySelector('a[href="/research"]') as HTMLAnchorElement).click());
expect(location).toBe('/research/p1?artifact=a1');
expect(field('Revision body').value).toBe('Discard me');
await flush(() => click('View latest revision'));
expect(field('Revision body').value).toBe('Discard me');
Object.defineProperty(browser, 'confirm', {
configurable: true,
writable: true,
value: () => true,
});
await flush(() => click('View latest revision'));
await flush(() => replyArtifact());
expect(host.querySelector('[aria-label="Revision body"]')).toBeNull();
expect(host.textContent).not.toContain('Discard me');
});
});