feat(research): add workspace and evidence-linked finding UI
This commit is contained in:
parent
ee45257507
commit
e3bd708838
21 changed files with 4566 additions and 1379 deletions
|
|
@ -414,6 +414,9 @@ export async function fixture(browser: Browser, native = false) {
|
|||
!pathname.startsWith('/api/v2/datasets') &&
|
||||
!pathname.startsWith('/api/v2/strategies') &&
|
||||
!pathname.startsWith('/api/v2/strategy-versions') &&
|
||||
!pathname.startsWith('/api/v2/research-projects') &&
|
||||
!pathname.startsWith('/api/v2/hypotheses/') &&
|
||||
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
/\/(pause|resume|speed)$/.test(pathname)
|
||||
) {
|
||||
|
|
|
|||
|
|
@ -709,7 +709,7 @@ test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
|
||||
test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_reopen', async () => {
|
||||
const f = await fixture(true);
|
||||
f.page.on('dialog', dialog => void dialog.accept());
|
||||
try {
|
||||
|
|
@ -719,7 +719,51 @@ test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
|
|||
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
|
||||
expect(selected.reviewStatus).toBe('pending');
|
||||
await f.login();
|
||||
await f.page.goto(`${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`);
|
||||
await f.page.getByRole('link', { name: 'Research', exact: true }).click();
|
||||
await visible(f.page, 'No research projects yet. Create a project to begin.');
|
||||
await f.page.getByRole('button', { name: 'New project', exact: true }).click();
|
||||
await f.page.getByLabel('Project title', { exact: true }).fill('Trend research');
|
||||
await f.page.getByLabel('Project description', { exact: true }).fill('Retained SMA evidence');
|
||||
const creatingProject = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' && response.url().endsWith('/research-projects')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Create project', exact: true }).click();
|
||||
const projectResponse = await creatingProject;
|
||||
expect(projectResponse.status()).toBe(201);
|
||||
const { project } = await projectResponse.json();
|
||||
await f.page.waitForURL(`${f.origin}/research/${project.id}`);
|
||||
await f.page.getByRole('button', { name: 'New hypothesis', exact: true }).click();
|
||||
await f.page.getByLabel('Hypothesis title', { exact: true }).fill('AI trend hypothesis');
|
||||
await f.page
|
||||
.getByLabel('Proposition', { exact: true })
|
||||
.fill('A hypothesis, not validated alpha.');
|
||||
await f.page
|
||||
.getByLabel('Validation criteria', { exact: true })
|
||||
.fill('Out-of-sample evidence required.');
|
||||
await f.page.getByLabel('Declared content origin', { exact: true }).selectOption('ai');
|
||||
const creatingHypothesis = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/research-projects/${project.id}/hypotheses`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Create hypothesis', exact: true }).click();
|
||||
const hypothesisResponse = await creatingHypothesis;
|
||||
expect(hypothesisResponse.status()).toBe(201);
|
||||
const { hypothesis } = await hypothesisResponse.json();
|
||||
await visible(f.page, /AI-authored \(declared\).*Submitted by operator.*Unvalidated narrative/);
|
||||
await f.page.getByLabel('Strategy to link', { exact: true }).selectOption(selected.strategyId);
|
||||
const linking = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'PUT' &&
|
||||
response
|
||||
.url()
|
||||
.endsWith(`/research-projects/${project.id}/strategies/${selected.strategyId}`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Link strategy', exact: true }).click();
|
||||
expect((await linking).status()).toBe(204);
|
||||
await f.page.locator(`a[href="/strategies/${selected.strategyId}"]`).click();
|
||||
await f.page.getByLabel('Strategy version', { exact: true }).selectOption(selected.id);
|
||||
|
||||
// Approval is an authenticated human review of an immutable built-in, not a run bypass.
|
||||
await f.page
|
||||
|
|
@ -905,6 +949,106 @@ test('browser_approved_canonical_strategy_setup_run_and_reopen', async () => {
|
|||
expect(stored.metrics).toBeNull();
|
||||
expect(stored.trades).toBeNull();
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
|
||||
|
||||
// Citations are resolved from the persisted canonical result, never copied browser metrics.
|
||||
await f.page.getByRole('button', { name: 'Save finding', exact: true }).click();
|
||||
const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true });
|
||||
await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id);
|
||||
await dialog
|
||||
.getByLabel('Finding hypothesis', { exact: true })
|
||||
.selectOption(hypothesis.latestRevision.id);
|
||||
await dialog.getByLabel('Finding title', { exact: true }).fill('SMA fixture finding');
|
||||
await dialog
|
||||
.getByLabel('Finding body', { exact: true })
|
||||
.fill('Costs and losses require further validation.');
|
||||
await dialog.getByLabel('Round Trip Count', { exact: true }).check();
|
||||
const creatingFinding = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/research-projects/${project.id}/analysis-artifacts`)
|
||||
);
|
||||
await dialog.getByRole('button', { name: 'Save finding', exact: true }).click();
|
||||
const findingResponse = await creatingFinding;
|
||||
expect(findingResponse.status()).toBe(201);
|
||||
const submitted = findingResponse.request().postDataJSON();
|
||||
expect(submitted.evidence).toEqual([
|
||||
{
|
||||
runId: run.id,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
strategyVersionId: selected.id,
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
},
|
||||
{
|
||||
runId: run.id,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
strategyVersionId: selected.id,
|
||||
metricPath: 'analytics.metrics.roundTripCount',
|
||||
},
|
||||
]);
|
||||
const { artifact } = await findingResponse.json();
|
||||
expect(artifact.hypothesisRevisionId).toBe(hypothesis.latestRevision.id);
|
||||
expect(artifact.latestRevision.evidence[0].value).toBe(result.analytics.metrics.totalReturn);
|
||||
expect(artifact.latestRevision.evidence[1].value).toBeNull();
|
||||
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click();
|
||||
await f.page.waitForURL(`${f.origin}/research/${project.id}?artifact=${artifact.id}`);
|
||||
const evidence = f.page.getByRole('region', { name: 'Referenced measurements', exact: true });
|
||||
await evidence.waitFor({ state: 'visible' });
|
||||
expect(await evidence.textContent()).toContain('Unavailable — unsupported round trips');
|
||||
expect(await evidence.textContent()).toContain('Unit: fraction');
|
||||
expect(await evidence.textContent()).toContain(
|
||||
`Raw value: ${result.analytics.metrics.totalReturn}`
|
||||
);
|
||||
expect(await evidence.textContent()).toContain(retained.hash);
|
||||
expect(
|
||||
await evidence
|
||||
.getByRole('link', { name: 'Open cited run', exact: true })
|
||||
.first()
|
||||
.getAttribute('href')
|
||||
).toBe(`/backtests/${backtestId}/run/${run.id}`);
|
||||
expect(
|
||||
await evidence
|
||||
.getByRole('link', { name: 'Open cited strategy version', exact: true })
|
||||
.first()
|
||||
.getAttribute('href')
|
||||
).toBe(`/strategies/versions/${selected.id}`);
|
||||
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
|
||||
await f.page
|
||||
.getByLabel('Revision body', { exact: true })
|
||||
.fill('Revised conclusion; original evidence retained.');
|
||||
const revising = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`)
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
|
||||
expect((await revising).status()).toBe(201);
|
||||
await f.page.getByRole('button', { name: 'View revision 2', exact: true }).waitFor();
|
||||
await visible(f.page, 'Revised conclusion; original evidence retained.');
|
||||
const history = await f.request(`/api/v2/analysis-artifacts/${artifact.id}/revisions`);
|
||||
expect(history.revisions).toHaveLength(2);
|
||||
expect(history.revisions[0].evidence).toEqual(history.revisions[1].evidence);
|
||||
await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click();
|
||||
await visible(f.page, 'Costs and losses require further validation.');
|
||||
await visible(f.page, 'Immutable history: this revision is read-only.');
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Costs and losses require further validation.');
|
||||
await f.page.getByRole('link', { name: 'Open exact hypothesis revision', exact: true }).click();
|
||||
await f.page.waitForURL(
|
||||
`${f.origin}/research/${project.id}?hypothesis=${hypothesis.id}&revision=${hypothesis.latestRevision.id}`
|
||||
);
|
||||
await visible(f.page, /AI-authored \(declared\).*Unvalidated narrative/);
|
||||
await f.page.getByRole('button', { name: 'Archive project', exact: true }).click();
|
||||
await visible(f.page, 'Archived project: research entries are read-only.');
|
||||
expect(await f.page.getByRole('button', { name: 'New note', exact: true }).count()).toBe(0);
|
||||
expect(await f.page.getByRole('button', { name: 'New hypothesis', exact: true }).count()).toBe(
|
||||
0
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'SMA fixture finding', exact: true }).click();
|
||||
await visible(f.page, 'Revised conclusion; original evidence retained.');
|
||||
await evidence.getByRole('link', { name: 'Open cited run', exact: true }).first().click();
|
||||
await f.page.waitForURL(completedUrl);
|
||||
await visible(f.page, '9969.30000000');
|
||||
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
|
|
|
|||
150
test/integration/research-client.test.tsx
Normal file
150
test/integration/research-client.test.tsx
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import { afterAll, beforeAll, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import type { ResearchEvidence } from '@stock-bot/types';
|
||||
import {
|
||||
evidenceReferences,
|
||||
ResearchAuthorshipBadge,
|
||||
ResearchEvidenceList,
|
||||
} from '../../apps/stock/web-app/src/features/research/components/ResearchEvidence';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const setFetch = (value: (input: unknown, init?: RequestInit) => Promise<Response>) =>
|
||||
Object.defineProperty(browser, 'fetch', { configurable: true, value });
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
let client: typeof import('../../apps/stock/web-app/src/features/research/services/researchApi');
|
||||
beforeAll(async () => {
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: browser });
|
||||
client = await import('../../apps/stock/web-app/src/features/research/services/researchApi');
|
||||
});
|
||||
afterAll(() => {
|
||||
if (previous) {
|
||||
Object.defineProperty(globalThis, 'window', previous);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, 'window');
|
||||
}
|
||||
browser.close();
|
||||
});
|
||||
|
||||
test('research response envelopes reject ambiguous successful saves without retrying', async () => {
|
||||
for (const response of [
|
||||
Response.json(null),
|
||||
Response.json({}),
|
||||
Response.json({ project: null }),
|
||||
Response.json({ project: {} }),
|
||||
Response.json({ project: [] }),
|
||||
new Response('{'),
|
||||
new Response(null, { status: 204 }),
|
||||
]) {
|
||||
let calls = 0;
|
||||
setFetch(async () => {
|
||||
calls++;
|
||||
return response;
|
||||
});
|
||||
try {
|
||||
await client.researchApi.createProject({ title: 'Possible committed save' });
|
||||
throw new Error('Invalid success accepted');
|
||||
} catch (cause) {
|
||||
expect(cause).toBeInstanceOf(client.ResearchApiError);
|
||||
expect((cause as InstanceType<typeof client.ResearchApiError>).ambiguous).toBe(true);
|
||||
}
|
||||
expect(calls).toBe(1);
|
||||
}
|
||||
});
|
||||
|
||||
test('research client preserves credentials, revision guards and HTTP error classification', async () => {
|
||||
const calls: { path: string; init?: RequestInit }[] = [];
|
||||
setFetch(async (input: unknown, init?: RequestInit) => {
|
||||
calls.push({ path: String(input), init });
|
||||
return Response.json({ error: 'Revision conflict' }, { status: 409 });
|
||||
});
|
||||
try {
|
||||
await client.researchApi.updateProject('project/id', { title: 'Draft', expectedRevision: 7 });
|
||||
throw new Error('Conflict response accepted');
|
||||
} catch (cause) {
|
||||
expect(cause).toBeInstanceOf(client.ResearchApiError);
|
||||
expect((cause as InstanceType<typeof client.ResearchApiError>).ambiguous).toBe(false);
|
||||
expect((cause as Error).message).toBe('Revision conflict');
|
||||
}
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.path).toEndWith('/api/v2/research-projects/project%2Fid');
|
||||
expect(calls[0]!.init?.credentials).toBe('include');
|
||||
expect(JSON.parse(calls[0]!.init!.body as string)).toEqual({
|
||||
title: 'Draft',
|
||||
expectedRevision: 7,
|
||||
});
|
||||
setFetch(async () => new Response(null, { status: 204 }));
|
||||
await expect(client.researchApi.linkStrategy('project', 'strategy')).resolves.toBeUndefined();
|
||||
setFetch(async () => Response.json({ projects: {} }));
|
||||
await expect(client.researchApi.listProjects()).rejects.toBeInstanceOf(client.ResearchApiError);
|
||||
setFetch(async () => Response.json({ projects: [] }));
|
||||
await expect(client.researchApi.listProjects()).resolves.toEqual({ projects: [] });
|
||||
});
|
||||
|
||||
const evidence: ResearchEvidence = {
|
||||
runId: 'run',
|
||||
backtestId: 'backtest',
|
||||
strategyVersionId: 'version',
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
value: 0.123456789012345,
|
||||
unit: 'fraction',
|
||||
availability: 'available',
|
||||
unavailableReason: null,
|
||||
resultKind: 'canonical',
|
||||
financialEngine: 'rust',
|
||||
datasetHash: 'a'.repeat(64),
|
||||
limitations: [{ code: 'fixture', message: '<script>unsafe narrative</script>' }],
|
||||
};
|
||||
test('research evidence exposes exact source, units, raw value, unavailable and legacy limits', () => {
|
||||
const unavailable: ResearchEvidence = {
|
||||
...evidence,
|
||||
runId: 'legacy',
|
||||
strategyVersionId: undefined,
|
||||
metricsVersion: 'legacy-display/v1',
|
||||
metricPath: 'metrics.sharpeRatio',
|
||||
value: null,
|
||||
unit: 'ratio',
|
||||
availability: 'unavailable',
|
||||
unavailableReason: 'insufficient-data',
|
||||
resultKind: 'legacy',
|
||||
financialEngine: 'typescript',
|
||||
};
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(
|
||||
MemoryRouter,
|
||||
null,
|
||||
createElement(ResearchEvidenceList, { evidence: [evidence, unavailable] })
|
||||
)
|
||||
);
|
||||
expect(html).toContain('/backtests/backtest/run/run');
|
||||
expect(html).toContain('/strategies/versions/version');
|
||||
expect(html).toContain('0.123456789012345');
|
||||
expect(html).toContain('Unit: fraction');
|
||||
expect(html).toContain('Unavailable — insufficient data');
|
||||
expect(html).toContain('Unverified economics');
|
||||
expect(html).toContain('typescript');
|
||||
expect(html).toContain('They do not validate the narrative');
|
||||
expect(html).not.toContain('<script>');
|
||||
expect(evidenceReferences([evidence])).toEqual([
|
||||
{
|
||||
runId: 'run',
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
strategyVersionId: 'version',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('ai_authorship_badge separates declared origin from authenticated submitter and validation', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(ResearchAuthorshipBadge, {
|
||||
authorship: { contentOrigin: 'ai', submittedBy: 'operator' },
|
||||
})
|
||||
);
|
||||
expect(html).toContain('AI-authored (declared)');
|
||||
expect(html).toContain('Submitted by operator');
|
||||
expect(html).toContain('Unvalidated narrative');
|
||||
});
|
||||
650
test/integration/research-finding-ui.test.tsx
Normal file
650
test/integration/research-finding-ui.test.tsx
Normal file
|
|
@ -0,0 +1,650 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type {
|
||||
CanonicalRunResult,
|
||||
ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
BacktestRunResult,
|
||||
ResearchArtifact,
|
||||
ResearchHypothesis,
|
||||
ResearchProject,
|
||||
} from '@stock-bot/types';
|
||||
import type {
|
||||
Backtest,
|
||||
Run,
|
||||
} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', '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 SaveFindingDialog: typeof import('../../apps/stock/web-app/src/features/research/components/SaveFindingDialog').SaveFindingDialog;
|
||||
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let closed: number;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: 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;
|
||||
signal?: AbortSignal | null;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const value = requests.find(
|
||||
item => !item.settled && item.path === path && item.method === method
|
||||
);
|
||||
if (!value) {
|
||||
throw new Error(
|
||||
`Missing ${method} ${path}; requests ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(',')}`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function reply(item: Pending, body: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(body, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const item = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label
|
||||
);
|
||||
if (!item) {
|
||||
throw new Error(`Missing ${label}: ${host.textContent}`);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
function field(label: string) {
|
||||
const item = host.querySelector(`[aria-label="${label}"]`) as
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLTextAreaElement
|
||||
| null;
|
||||
if (!item) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
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();
|
||||
return null;
|
||||
}
|
||||
const project = (id = 'p1', archived = false): ResearchProject => ({
|
||||
id,
|
||||
archived,
|
||||
title: `Project ${id}`,
|
||||
description: '',
|
||||
revision: 1,
|
||||
ownerPrincipal: 'operator',
|
||||
updatedBy: 'operator',
|
||||
createdAt: '2026-10-23',
|
||||
updatedAt: '2026-10-23',
|
||||
});
|
||||
const hypothesis = (id = 'h1', projectId = 'p1', archived = false): ResearchHypothesis => ({
|
||||
id,
|
||||
projectId,
|
||||
archived,
|
||||
ownerPrincipal: 'operator',
|
||||
updatedBy: 'operator',
|
||||
createdAt: '2026-10-23',
|
||||
updatedAt: '2026-10-23',
|
||||
latestRevision: {
|
||||
id: `${id}-revision`,
|
||||
hypothesisId: id,
|
||||
ordinal: 2,
|
||||
title: `Hypothesis ${id}`,
|
||||
proposition: 'Candidate',
|
||||
validationCriteria: '',
|
||||
validationState: 'unvalidated',
|
||||
contentOrigin: 'human',
|
||||
submittedBy: 'operator',
|
||||
createdAt: '2026-10-23',
|
||||
},
|
||||
});
|
||||
const artifact = (hypothesisRevisionId: string | null = null): ResearchArtifact => ({
|
||||
id: 'saved-finding',
|
||||
projectId: 'p1',
|
||||
hypothesisRevisionId,
|
||||
kind: 'finding',
|
||||
archived: false,
|
||||
ownerPrincipal: 'operator',
|
||||
updatedBy: 'operator',
|
||||
createdAt: '2026-10-23',
|
||||
updatedAt: '2026-10-23',
|
||||
latestRevision: {
|
||||
id: 'a-revision',
|
||||
artifactId: 'saved-finding',
|
||||
ordinal: 1,
|
||||
title: 'Finding',
|
||||
body: 'Narrative',
|
||||
validationState: 'unvalidated',
|
||||
evidenceState: 'referenced',
|
||||
evidence: [],
|
||||
submittedBy: 'operator',
|
||||
contentOrigin: 'human',
|
||||
createdAt: '2026-10-23',
|
||||
},
|
||||
});
|
||||
function legacy(runId = 'run'): BacktestRunResult {
|
||||
return {
|
||||
runId,
|
||||
backtestId: 'definition',
|
||||
engine: 'typescript',
|
||||
status: 'completed',
|
||||
completedAt: '2026-10-23',
|
||||
config: {
|
||||
name: 'Historical config',
|
||||
strategy: 'sma',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-02-01',
|
||||
initialCapital: 1000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
parameters: {},
|
||||
},
|
||||
metrics: {
|
||||
totalReturn: 0.23,
|
||||
sharpeRatio: null,
|
||||
maxDrawdown: -0.05,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
},
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
trades: [],
|
||||
positions: [],
|
||||
analytics: { exposureTime: null },
|
||||
executionTime: 1,
|
||||
};
|
||||
}
|
||||
/** Only fields read by the citation picker; the financial report itself is not simulated here. */
|
||||
function canonical(): CanonicalRunResult {
|
||||
return {
|
||||
kind: 'canonical-result/v1',
|
||||
runId: 'run',
|
||||
backtestId: 'definition',
|
||||
status: 'completed',
|
||||
financialEngine: 'rust',
|
||||
request: { strategy: { versionId: 'frozen-version' } },
|
||||
financial: {
|
||||
limitations: ['Only retained exchange sessions'],
|
||||
modelLimitations: ['No market impact'],
|
||||
},
|
||||
analytics: { metrics: { totalReturn: 0.23, sharpeRatio: null }, fillCount: 3 },
|
||||
} as unknown as CanonicalRunResult;
|
||||
}
|
||||
const definition: Backtest = {
|
||||
id: 'definition',
|
||||
name: 'Mutable template',
|
||||
strategy: 'sma',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-02-01',
|
||||
initialCapital: 1000,
|
||||
config: {},
|
||||
createdAt: '2024-01-01',
|
||||
updatedAt: '2024-01-01',
|
||||
archivedAt: null,
|
||||
};
|
||||
const run = (id = 'run', status: Run['status'] = 'completed'): Run => ({
|
||||
id,
|
||||
backtestId: 'definition',
|
||||
status,
|
||||
runNumber: 1,
|
||||
speedMultiplier: null,
|
||||
progress: 100,
|
||||
createdAt: '2026-10-23',
|
||||
updatedAt: '2026-10-23',
|
||||
});
|
||||
async function render(element: ReactElement, initial = '/') {
|
||||
if (!root) {
|
||||
root = createRoot(host);
|
||||
}
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: [initial] },
|
||||
element,
|
||||
createElement(Probe)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
async function mountDialog(result: ResearchRunResult = canonical()) {
|
||||
await render(
|
||||
createElement(SaveFindingDialog, {
|
||||
result,
|
||||
onClose: () => {
|
||||
closed++;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/research-projects?includeArchived=false'), {
|
||||
projects: [project(), project('p2'), project('archived', true)],
|
||||
})
|
||||
);
|
||||
}
|
||||
async function destination(id = 'p1', items = [hypothesis()]) {
|
||||
await flush(() => edit('Finding project', id));
|
||||
await flush(() => {
|
||||
reply(request(`/api/v2/research-projects/${id}`), { project: project(id) });
|
||||
reply(request(`/api/v2/research-projects/${id}/hypotheses?includeArchived=false`), {
|
||||
hypotheses: items,
|
||||
});
|
||||
});
|
||||
}
|
||||
async function draft() {
|
||||
await destination();
|
||||
await flush(() => {
|
||||
edit('Finding title', 'Exact finding');
|
||||
edit('Finding body', 'Keep this narrative');
|
||||
});
|
||||
}
|
||||
async function preflight() {
|
||||
await flush(() => button('Save finding').click());
|
||||
await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() }));
|
||||
}
|
||||
const post = () => request('/api/v2/research-projects/p1/analysis-artifacts', 'POST');
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
Event: browser.Event,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
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');
|
||||
({ SaveFindingDialog } = await import(
|
||||
'../../apps/stock/web-app/src/features/research/components/SaveFindingDialog'
|
||||
));
|
||||
({ BacktestDetailPageV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
closed = 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 = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = new URL(String(input));
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: url.pathname + url.search,
|
||||
method: init?.method ?? 'GET',
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
signal: init?.signal,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Deliberately ignore abort: identity fences must handle late replies.
|
||||
}) 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 {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('saved-result finding', () => {
|
||||
test('canonical citations use the frozen strategy version and immutable hypothesis revision, never metric copies', async () => {
|
||||
await mountDialog();
|
||||
await draft();
|
||||
expect(host.textContent).toContain('No market impact');
|
||||
expect(host.textContent).toContain('Sharpe Ratio · Unavailable');
|
||||
expect(field('Finding project').textContent).not.toContain('Project archived');
|
||||
await flush(() => {
|
||||
edit('Finding hypothesis', 'h1-revision');
|
||||
edit('Finding content origin', 'ai');
|
||||
(field('Sharpe Ratio') as HTMLInputElement).click();
|
||||
});
|
||||
await preflight();
|
||||
await flush(() => reply(request('/api/v2/hypotheses/h1'), { hypothesis: hypothesis() }));
|
||||
expect(post().body).toEqual({
|
||||
kind: 'finding',
|
||||
title: 'Exact finding',
|
||||
body: 'Keep this narrative',
|
||||
contentOrigin: 'ai',
|
||||
hypothesisRevisionId: 'h1-revision',
|
||||
evidence: [
|
||||
{
|
||||
runId: 'run',
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
strategyVersionId: 'frozen-version',
|
||||
},
|
||||
{
|
||||
runId: 'run',
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.sharpeRatio',
|
||||
strategyVersionId: 'frozen-version',
|
||||
},
|
||||
],
|
||||
});
|
||||
await flush(() => reply(post(), { artifact: artifact('h1-revision') }, 201));
|
||||
expect(host.querySelector('a')?.getAttribute('href')).toBe(
|
||||
'/research/p1?artifact=saved-finding'
|
||||
);
|
||||
expect(host.textContent).toContain('narrative remains unvalidated');
|
||||
expect(closed).toBe(0);
|
||||
});
|
||||
test('legacy citations retain qualification and do not infer a strategy version', async () => {
|
||||
await mountDialog(legacy());
|
||||
await draft();
|
||||
await preflight();
|
||||
expect(host.textContent).toContain('Legacy · Unverified economics');
|
||||
expect(post().body).toEqual({
|
||||
kind: 'finding',
|
||||
title: 'Exact finding',
|
||||
body: 'Keep this narrative',
|
||||
contentOrigin: 'human',
|
||||
hypothesisRevisionId: null,
|
||||
evidence: [
|
||||
{ runId: 'run', metricsVersion: 'legacy-display/v1', metricPath: 'metrics.totalReturn' },
|
||||
],
|
||||
});
|
||||
});
|
||||
test('late project and hypothesis responses cannot overwrite the current destination', async () => {
|
||||
await mountDialog();
|
||||
await flush(() => edit('Finding project', 'p1'));
|
||||
const oldProject = request('/api/v2/research-projects/p1');
|
||||
const oldHypotheses = request('/api/v2/research-projects/p1/hypotheses?includeArchived=false');
|
||||
await destination('p2', [
|
||||
hypothesis('h2', 'p2'),
|
||||
hypothesis('foreign', 'p1'),
|
||||
hypothesis('archived', 'p2', true),
|
||||
]);
|
||||
await flush(() => edit('Finding hypothesis', 'h2-revision'));
|
||||
await flush(() => {
|
||||
reply(oldProject, { project: project('p1') });
|
||||
reply(oldHypotheses, { hypotheses: [hypothesis()] });
|
||||
});
|
||||
expect(oldProject.signal?.aborted).toBe(true);
|
||||
expect(field('Finding project').value).toBe('p2');
|
||||
expect(field('Finding hypothesis').value).toBe('h2-revision');
|
||||
expect(field('Finding hypothesis').textContent).not.toContain('Hypothesis h1');
|
||||
expect(field('Finding hypothesis').textContent).not.toContain('foreign');
|
||||
expect(field('Finding hypothesis').textContent).not.toContain('archived');
|
||||
await destination();
|
||||
expect(field('Finding hypothesis').value).toBe('');
|
||||
});
|
||||
for (const status of [422, 409, 401]) {
|
||||
test(`${status} preserves the finding draft and never retries automatically`, async () => {
|
||||
await mountDialog();
|
||||
await draft();
|
||||
await preflight();
|
||||
await flush(() =>
|
||||
reply(
|
||||
post(),
|
||||
{ error: status === 422 ? 'Saved evidence is incomplete' : 'Destination write rejected' },
|
||||
status
|
||||
)
|
||||
);
|
||||
expect(field('Finding title').value).toBe('Exact finding');
|
||||
expect(field('Finding body').value).toBe('Keep this narrative');
|
||||
expect(host.querySelector('[role="alert"]')?.textContent).toContain(
|
||||
status === 422 ? 'incomplete' : 'rejected'
|
||||
);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(button('Save finding').disabled).toBe(false);
|
||||
});
|
||||
}
|
||||
test('archived destination found during preflight denies any POST', async () => {
|
||||
await mountDialog();
|
||||
await draft();
|
||||
await flush(() => button('Save finding').click());
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/research-projects/p1'), { project: project('p1', true) })
|
||||
);
|
||||
expect(button('Save finding').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('destination project is archived');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
expect(field('Finding title').value).toBe('Exact finding');
|
||||
});
|
||||
test('archived selected hypothesis cannot be cited by a new request', async () => {
|
||||
await mountDialog();
|
||||
await draft();
|
||||
await flush(() => edit('Finding hypothesis', 'h1-revision'));
|
||||
await preflight();
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/hypotheses/h1'), { hypothesis: hypothesis('h1', 'p1', true) })
|
||||
);
|
||||
expect(host.textContent).toContain('selected hypothesis is archived');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
});
|
||||
for (const response of ['lost', '500', 'malformed'] as const) {
|
||||
test(`${response} create outcome freezes draft until explicit new request`, async () => {
|
||||
await mountDialog();
|
||||
await draft();
|
||||
await flush(() => {
|
||||
button('Save finding').click();
|
||||
button('Save finding').click();
|
||||
button('Close').click();
|
||||
});
|
||||
expect(closed).toBe(0);
|
||||
expect(requests.filter(item => item.path === '/api/v2/research-projects/p1')).toHaveLength(2);
|
||||
await flush(() => reply(request('/api/v2/research-projects/p1'), { project: project() }));
|
||||
const pending = post();
|
||||
await flush(() => {
|
||||
if (response === 'lost') {
|
||||
pending.settled = true;
|
||||
pending.reject(new Error('Response lost'));
|
||||
} else if (response === '500') {
|
||||
reply(pending, { error: 'Server interrupted' }, 500);
|
||||
} else {
|
||||
reply(pending, {}, 201);
|
||||
}
|
||||
});
|
||||
expect(host.textContent).toContain('Check saved records before creating another');
|
||||
expect(button('Save finding').disabled).toBe(true);
|
||||
expect(field('Finding title').disabled).toBe(true);
|
||||
expect(field('Finding title').value).toBe('Exact finding');
|
||||
expect(host.querySelector('a[target="_blank"]')?.getAttribute('href')).toBe('/research/p1');
|
||||
await flush(() => button('Save finding').click());
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
await flush(() => button('Start new request').click());
|
||||
expect(field('Finding title').disabled).toBe(false);
|
||||
expect(button('Save finding').disabled).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
});
|
||||
}
|
||||
test('changing result identity resets draft and rejects a late create success', async () => {
|
||||
await mountDialog();
|
||||
await draft();
|
||||
await preflight();
|
||||
const pending = post();
|
||||
await render(
|
||||
createElement(SaveFindingDialog, {
|
||||
result: legacy('next-run'),
|
||||
onClose: () => {
|
||||
closed++;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => reply(pending, { artifact: artifact() }, 201));
|
||||
expect(host.textContent).toContain('Run: next-run');
|
||||
expect(field('Finding title').value).toBe('');
|
||||
expect(field('Finding project').value).toBe('');
|
||||
expect(host.textContent).not.toContain('Open saved finding');
|
||||
});
|
||||
test('changed result ignores late projects and unsaved close requires confirmation', async () => {
|
||||
await render(
|
||||
createElement(SaveFindingDialog, {
|
||||
result: legacy(),
|
||||
onClose: () => {
|
||||
closed++;
|
||||
},
|
||||
})
|
||||
);
|
||||
const oldList = request('/api/v2/research-projects?includeArchived=false');
|
||||
await render(
|
||||
createElement(SaveFindingDialog, {
|
||||
result: legacy('next-run'),
|
||||
onClose: () => {
|
||||
closed++;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => reply(oldList, { projects: [project('old')] }));
|
||||
expect(field('Finding project').textContent).not.toContain('Project old');
|
||||
await flush(() => edit('Finding title', 'Keep draft'));
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => false,
|
||||
});
|
||||
await flush(() => button('Close').click());
|
||||
expect(closed).toBe(0);
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
await flush(() => button('Close').click());
|
||||
expect(closed).toBe(1);
|
||||
});
|
||||
test('project load failure is distinct from empty projects and can be retried', async () => {
|
||||
await render(createElement(SaveFindingDialog, { result: legacy(), onClose: () => {} }));
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/research-projects?includeArchived=false'),
|
||||
{ error: 'Unavailable projects' },
|
||||
503
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('Unavailable projects');
|
||||
expect(host.textContent).not.toContain('No active research projects');
|
||||
await flush(() => button('Retry projects').click());
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/research-projects?includeArchived=false'), { projects: [] })
|
||||
);
|
||||
expect(host.textContent).toContain('No active research projects');
|
||||
});
|
||||
});
|
||||
|
||||
async function mountPage(status: Run['status'] = 'completed') {
|
||||
await render(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id/run/:runId',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition/run/run'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), { ...definition, archivedAt: '2026-10-23' });
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
reply(request('/api/v2/runs/run'), run('run', status));
|
||||
});
|
||||
}
|
||||
describe('backtest finding entry point', () => {
|
||||
test('archived backtest permits completed matching results and run navigation closes the dialog', async () => {
|
||||
await mountPage();
|
||||
expect(button('Save finding').disabled).toBe(true);
|
||||
await flush(() => reply(request('/api/v2/runs/run/results'), legacy()));
|
||||
expect(button('Save finding').disabled).toBe(false);
|
||||
await flush(() => button('Save finding').click());
|
||||
expect(host.querySelector('[role="dialog"]')).not.toBeNull();
|
||||
const pending = request('/api/v2/research-projects?includeArchived=false');
|
||||
await flush(() => navigate('/backtests/definition/run/next-run'));
|
||||
expect(host.querySelector('[role="dialog"]')).toBeNull();
|
||||
await flush(() => reply(pending, { projects: [project()] }));
|
||||
expect(host.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
for (const source of ['missing', 'wrong-parent', 'wrong-run', 'cancelled'] as const) {
|
||||
test(`${source} results cannot open finding creation`, async () => {
|
||||
await mountPage();
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/runs/run/results'),
|
||||
source === 'missing'
|
||||
? { error: 'Missing results' }
|
||||
: {
|
||||
...legacy(),
|
||||
...(source === 'wrong-parent'
|
||||
? { backtestId: 'foreign' }
|
||||
: source === 'wrong-run'
|
||||
? { runId: 'foreign' }
|
||||
: { status: 'cancelled' }),
|
||||
},
|
||||
source === 'missing' ? 404 : 200
|
||||
)
|
||||
);
|
||||
expect(button('Save finding').disabled).toBe(true);
|
||||
await flush(() => button('Save finding').click());
|
||||
expect(host.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
}
|
||||
test('failed runs have no usable evidence action', async () => {
|
||||
await mountPage('failed');
|
||||
expect(button('Save finding').disabled).toBe(true);
|
||||
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
|
||||
});
|
||||
});
|
||||
679
test/integration/research-workspace-ui.test.tsx
Normal file
679
test/integration/research-workspace-ui.test.tsx
Normal file
|
|
@ -0,0 +1,679 @@
|
|||
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);
|
||||
});
|
||||
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');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue