feat(research): download exact saved revisions (RP26)

This commit is contained in:
Boki 2026-10-27 23:11:22 -04:00
parent 6ce3b68b3d
commit 5434950263
7 changed files with 320 additions and 3 deletions

View file

@ -36,7 +36,9 @@ import type {
HistoricalDatasetInputV2,
HistoricalDatasetV2,
ResearchArtifact,
ResearchArtifactRevision,
ResearchFindingSource,
ResearchHypothesisRevision,
} from '@stock-bot/types';
import {
createDatasetV2,
@ -94,6 +96,55 @@ async function downloadDatasetInBrowser(
expect(validateDatasetV2(JSON.parse(readFileSync(path, 'utf8')))).toEqual(expected);
}
async function downloadResearchRevisionInBrowser(
f: Awaited<ReturnType<typeof fixture>>,
projectId: string,
entry: {
id: string;
kind: 'hypothesis' | 'note' | 'finding';
hypothesisRevisionId?: string | null;
},
revision: ResearchArtifactRevision | ResearchHypothesisRevision
) {
const counts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
(SELECT count(*)::int FROM analysis_artifact_revisions) AS artifacts,
(SELECT count(*)::int FROM research_hypothesis_revisions) AS hypotheses`)
).rows[0];
const before = await counts();
const requests: string[] = [];
const record = (request: Request) => {
if (new URL(request.url()).pathname.startsWith('/api/')) {
requests.push(request.url());
}
};
f.page.on('request', record);
try {
const downloading = f.page.waitForEvent('download');
await f.page.getByRole('button', { name: 'Download saved revision', exact: true }).click();
const download = await downloading;
expect(download.suggestedFilename()).toBe(`research-${entry.id}-${revision.id}.json`);
expect(await download.failure()).toBeNull();
const path = await download.path();
if (!path) {
throw new Error('Expected a downloaded research revision file');
}
expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual({
kind: 'research-revision-export/v1',
projectId,
entry,
revision,
});
expect(requests).toEqual([]);
expect(await counts()).toEqual(before);
} finally {
f.page.off('request', record);
}
}
test('operator_provisions_bounded_agent_views_usage_and_revokes_without_corrupting_accepted_work_browser', async () => {
const f = await fixture(true);
try {
@ -3725,6 +3776,14 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
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 downloadResearchRevisionInBrowser(
f,
project.id,
{ id: artifact.id, kind: 'finding', hypothesisRevisionId: hypothesis.latestRevision.id },
history.revisions.find(
(item: ResearchArtifactRevision) => item.id === artifact.latestRevision.id
)!
);
// Move the cited hypothesis forward so the exact link requires history resolution.
await f.request(`/api/v2/hypotheses/${hypothesis.id}/revisions`, 'POST', {
expectedRevision: 1,
@ -3755,6 +3814,12 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
await f.page.unroute(unrelatedHistoryPath);
await visible(f.page, 'A hypothesis, not validated alpha.');
await visible(f.page, /AI-authored \(declared\).*Unvalidated narrative/);
await downloadResearchRevisionInBrowser(
f,
project.id,
{ id: hypothesis.id, kind: 'hypothesis' },
hypothesis.latestRevision
);
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);

View file

@ -1,4 +1,13 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
spyOn,
test,
} from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement } from 'react';
import type { Root } from 'react-dom/client';
@ -281,6 +290,192 @@ afterAll(async () => {
});
describe('research workspace', () => {
describe('saved revision download', () => {
const blobs: Blob[] = [];
const downloads: string[] = [];
const revoked: string[] = [];
let failure: 'url' | 'click' | undefined;
let restore: () => void;
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
beforeEach(() => {
blobs.length = downloads.length = revoked.length = 0;
failure = undefined;
const createUrl = spyOn(URL, 'createObjectURL').mockImplementation(blob => {
if (failure === 'url') {
throw new Error('Browser file creation failed');
}
blobs.push(blob as Blob);
return `blob:research-${blobs.length}`;
});
const revokeUrl = spyOn(URL, 'revokeObjectURL').mockImplementation(url => revoked.push(url));
const clickAnchor = spyOn(browser.HTMLAnchorElement.prototype, 'click').mockImplementation(
() => {
if (failure === 'click') {
throw new Error('Browser download failed');
}
const anchor = browser.document.querySelector('a[download]');
if (!(anchor instanceof browser.HTMLAnchorElement)) {
throw new Error('Missing download anchor');
}
downloads.push(anchor.download);
}
);
restore = () => {
createUrl.mockRestore();
revokeUrl.mockRestore();
clickAnchor.mockRestore();
};
});
afterEach(async () => {
await tick();
restore();
});
test.each(['hypothesis', 'note', 'finding'] as const)(
'%s download excludes unsaved edits and issues no requests',
async kind => {
const value = kind === 'hypothesis' ? hypothesis() : artifact('a1', { kind });
await mount(
`/research/p1?${kind === 'hypothesis' ? 'hypothesis' : 'artifact'}=${value.id}`
);
expect(host.textContent).not.toContain('Download saved revision');
await flush(() => replyProject(project(), [hypothesis()], [artifact()]));
await flush(() => {
if ('hypothesisId' in value.latestRevision) {
replyHypothesis(value as ResearchHypothesis);
} else {
replyArtifact(value as ResearchArtifact);
}
});
const original = structuredClone(value.latestRevision);
await flush(() => click('Edit latest revision'));
await flush(() => edit('Revision body', 'Unsaved research interpretation'));
const before = requests.length;
await flush(() => click('Download saved revision'));
expect(host.textContent).toContain('Unsaved edits are excluded');
expect(JSON.parse(await blobs[0]!.text())).toEqual({
kind: 'research-revision-export/v1',
projectId: 'p1',
entry: {
id: value.id,
kind,
...(kind !== 'hypothesis' ? { hypothesisRevisionId: null } : {}),
},
revision: original,
});
expect(downloads).toEqual([`research-${value.id}-${original.id}.json`]);
expect(field('Revision body').value).toBe('Unsaved research interpretation');
expect(value.latestRevision).toEqual(original);
expect(requests).toHaveLength(before);
expect(browser.document.querySelector('a[download]')).toBeNull();
await tick();
expect(revoked).toEqual(['blob:research-1']);
await flush(() => click('Save new revision'));
expect(button('Download saved revision').disabled).toBe(true);
await flush(() => click('Download saved revision'));
expect(blobs).toHaveLength(1);
}
);
test('historical archived finding exports its own source, raw values and unavailable reasons', async () => {
const original = {
...artifact().latestRevision,
title: 'Original interpretation',
source: {
kind: 'experiment/v1' as const,
experimentId: '22222222-2222-4222-8222-222222222222',
previewHash: 'a'.repeat(64),
},
evidenceState: 'referenced' as const,
evidence: [0.123456789012345, null].map((value, index) => ({
runId: 'run',
backtestId: 'backtest',
strategyVersionId: 'version',
metricsVersion: 'canonical-analytics/v1' as const,
metricPath: index ? 'analytics.metrics.sharpeRatio' : 'analytics.metrics.totalReturn',
value,
unit: 'fraction' as const,
availability: index ? ('unavailable' as const) : ('available' as const),
unavailableReason: index ? 'insufficient-data' : null,
resultKind: 'canonical' as const,
financialEngine: 'rust' as const,
datasetHash: 'b'.repeat(64),
limitations: [{ code: 'fixture', message: 'Retained limitation' }],
})),
};
const latest = {
...original,
id: 'a1-r2',
ordinal: 2,
title: 'Latest interpretation',
source: null,
};
const value = artifact('a1', {
kind: 'finding',
archived: true,
hypothesisRevisionId: 'h1-r1',
latestRevision: latest,
});
await mount('/research/p1?artifact=a1&revision=a1-r1');
await flush(() => replyProject(project('p1', { archived: true }), [hypothesis()], [value]));
await flush(() => replyArtifact(value, [original, latest]));
const before = requests.length;
await flush(() => click('Download saved revision'));
expect(JSON.parse(await blobs[0]!.text())).toEqual({
kind: 'research-revision-export/v1',
projectId: 'p1',
entry: { id: 'a1', kind: 'finding', hypothesisRevisionId: 'h1-r1' },
revision: original,
});
expect(downloads).toEqual(['research-a1-a1-r1.json']);
expect(requests).toHaveLength(before);
expect(value.latestRevision).toEqual(latest);
});
test.each(['url', 'click'] as const)(
'%s failure retries the saved revision with cleanup',
async stage => {
await mount('/research/p1?artifact=a1');
await flush(() => replyProject());
await flush(() => replyArtifact());
failure = stage;
const before = requests.length;
await flush(() => click('Download saved revision'));
expect(host.textContent).toContain(
stage === 'url' ? 'Browser file creation failed' : 'Browser download failed'
);
expect(downloads).toHaveLength(0);
expect(browser.document.querySelector('a[download]')).toBeNull();
await tick();
expect(revoked).toEqual(stage === 'url' ? [] : ['blob:research-1']);
failure = undefined;
await flush(() => click('Retry saved revision download'));
expect(downloads).toHaveLength(1);
expect(JSON.parse(await blobs.at(-1)!.text()).revision).toEqual(artifact().latestRevision);
expect(requests).toHaveLength(before);
await flush(() => click('View revision 1'));
await flush(() => replyArtifact());
expect(host.textContent).not.toContain('Retry saved revision download');
}
);
test('missing or failed history exposes no download action', async () => {
await mount('/research/p1?artifact=a1&revision=missing');
await flush(() => replyProject());
await flush(() => replyArtifact());
expect(host.textContent).toContain('requested revision does not belong');
expect(host.textContent).not.toContain('Download saved revision');
await flush(() => click('Retry research entry'));
await flush(() => {
reply(request('analysis-artifacts/a1'), { error: 'Entry unavailable' }, 503);
reply(request('analysis-artifacts/a1/revisions'), { revisions: [] });
});
expect(host.textContent).toContain('Entry unavailable');
expect(host.textContent).not.toContain('Download saved revision');
expect(blobs).toHaveLength(0);
});
});
test('project listing distinguishes loading, error and empty and retries reads', async () => {
await mount('/research');
expect(host.textContent).toContain('Loading research projects');