fix(research): preserve settings and capture across tabs (RP06)
This commit is contained in:
parent
6d549542a9
commit
c838e3d05a
4 changed files with 405 additions and 46 deletions
|
|
@ -1857,10 +1857,20 @@ test('canonical_native_smoke', async () => {
|
|||
const f = await fixture(true);
|
||||
try {
|
||||
await f.login();
|
||||
await createCanonicalInBrowser(f, 'Actual Rust browser smoke', true);
|
||||
const { id } = await createCanonicalInBrowser(f, 'Actual Rust browser smoke');
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await f.page.getByLabel('Backtest name', { exact: true }).fill('Unsaved native research draft');
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
await submitInBrowser(f.page);
|
||||
const runId = f.page.url().split('/').at(-1)!;
|
||||
f.dispatcher.start();
|
||||
await visible(f.page, 'Completed');
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
expect(await f.page.getByLabel('Backtest name', { exact: true }).inputValue()).toBe(
|
||||
'Unsaved native research draft'
|
||||
);
|
||||
expect((await f.request(`/api/v2/backtests/${id}`)).name).toBe('Actual Rust browser smoke');
|
||||
await f.page.getByRole('button', { name: 'Details', exact: true }).click();
|
||||
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
||||
expect(result.financialEngine).toBe('rust');
|
||||
expect(result.request.strategy.origin).toBe('builtin');
|
||||
|
|
@ -2473,7 +2483,7 @@ test('canonical_dataset_browser_reuses_older_pages_and_known_hash_without_new_ru
|
|||
}
|
||||
});
|
||||
|
||||
test('declared_session_source_browser_captures_two_windows_and_retains_without_requery', async () => {
|
||||
test('declared_session_source_browser_preserves_capture_and_retention_retry_across_tabs', async () => {
|
||||
const f = await fixture();
|
||||
try {
|
||||
await f.login();
|
||||
|
|
@ -2558,11 +2568,52 @@ test('declared_session_source_browser_captures_two_windows_and_retains_without_r
|
|||
}))
|
||||
);
|
||||
await visible(f.page, `Dataset hash: ${captured.preparation.hash}`);
|
||||
await f.page.getByLabel('Backtest name', { exact: true }).fill('Unsaved session research');
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).count()).toBe(
|
||||
0
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await visible(f.page, `Dataset hash: ${captured.preparation.hash}`);
|
||||
expect(await f.page.getByLabel('Backtest name', { exact: true }).inputValue()).toBe(
|
||||
'Unsaved session research'
|
||||
);
|
||||
f.setStoredEodBars('eodIntraday1M', []);
|
||||
// Commit through the real route, then lose its response. Navigating within
|
||||
// this backtest must preserve the exact retry even after source deletion.
|
||||
let lostInput: unknown;
|
||||
const committed = gate();
|
||||
const retentionPath = '**/api/v2/datasets/canonical/retain';
|
||||
await f.page.route(retentionPath, async route => {
|
||||
lostInput = route.request().postDataJSON();
|
||||
const response = await route.fetch();
|
||||
if (response.status() !== 200) {
|
||||
throw new Error(`Expected committed fixture retention, got ${response.status()}`);
|
||||
}
|
||||
committed.resolve();
|
||||
await route.abort('failed');
|
||||
});
|
||||
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
|
||||
await committed.wait('retention committed before lost response');
|
||||
await visible(f.page, /Retention is unconfirmed/);
|
||||
await f.page.unroute(retentionPath);
|
||||
expect(lostInput).toEqual({
|
||||
input: captured.input,
|
||||
expectedHash: captured.preparation.hash,
|
||||
});
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
expect(
|
||||
await f.page
|
||||
.getByRole('button', { name: 'Retry retaining same dataset', exact: true })
|
||||
.count()
|
||||
).toBe(0);
|
||||
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
||||
await visible(f.page, /Retention is unconfirmed/);
|
||||
expect(await f.page.getByLabel('Dataset input', { exact: true }).isDisabled()).toBe(true);
|
||||
const retaining = f.page.waitForResponse(result =>
|
||||
result.url().endsWith('/api/v2/datasets/canonical/retain')
|
||||
);
|
||||
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
|
||||
await f.page.getByRole('button', { name: 'Retry retaining same dataset', exact: true }).click();
|
||||
const retained = await retaining;
|
||||
expect(retained.status()).toBe(200);
|
||||
expect(retained.request().postDataJSON()).toEqual({
|
||||
|
|
|
|||
|
|
@ -2,11 +2,14 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } fr
|
|||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research';
|
||||
import { createDatasetV2 } from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
||||
import type {
|
||||
Backtest,
|
||||
Run,
|
||||
RunResult,
|
||||
} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
// Local to this file: no global preload, browser server or second test runner.
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
|
|
@ -208,6 +211,29 @@ function click(label: string) {
|
|||
}
|
||||
button.click();
|
||||
}
|
||||
function settingsField(label: string) {
|
||||
const field = host.querySelector(`[aria-label="${label}"]`) as
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| null;
|
||||
if (!field) {
|
||||
throw new Error(`Missing settings field ${label}`);
|
||||
}
|
||||
return field;
|
||||
}
|
||||
function editSettings(label: string, value: string) {
|
||||
const field = settingsField(label);
|
||||
const prototype =
|
||||
field.tagName === 'SELECT'
|
||||
? browser.HTMLSelectElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(field, value);
|
||||
field.dispatchEvent(
|
||||
new browser.Event(field.tagName === 'SELECT' ? 'change' : 'input', {
|
||||
bubbles: true,
|
||||
}) as unknown as Event
|
||||
);
|
||||
}
|
||||
function HookHost({ socket = false }: { socket?: boolean }) {
|
||||
latest = useBacktestV2();
|
||||
renders++;
|
||||
|
|
@ -273,6 +299,117 @@ async function mountPage(status: Run['status']) {
|
|||
});
|
||||
}
|
||||
|
||||
async function mountSettingsPage() {
|
||||
// Match App's sibling index/run routes: both URLs must retain the same page owner.
|
||||
await mount(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/backtests/definition'] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(
|
||||
router.Route,
|
||||
{ path: '/backtests/:id' },
|
||||
createElement(router.Route, {
|
||||
index: true,
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: 'run/:runId',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
)
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), definition);
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
}
|
||||
|
||||
const storedPreparationPath = '/api/v2/datasets/canonical/stored-source';
|
||||
const retentionPath = '/api/v2/datasets/canonical/retain';
|
||||
function sessionPreparation(): CanonicalStoredSourcePreparation {
|
||||
const { dataset } = nativeReplayFixture(3);
|
||||
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
||||
dataset.manifest;
|
||||
const day = 86400000;
|
||||
const metadata = {
|
||||
calendars: calendars.map(calendar => ({
|
||||
...calendar,
|
||||
endDate: '2024-01-03',
|
||||
sessions: [
|
||||
...calendar.sessions,
|
||||
...calendar.sessions.map(session => ({
|
||||
date: '2024-01-02',
|
||||
open: session.open + day,
|
||||
close: session.close + day,
|
||||
})),
|
||||
],
|
||||
})),
|
||||
series: series.map(item => ({
|
||||
...item,
|
||||
source: { provider: 'eod', revision: 'custody-fixture' },
|
||||
availability: 'interval-end-assumption' as const,
|
||||
})),
|
||||
executionSeries,
|
||||
bounds: { ...bounds, tradeEnd: bounds.tradeEnd + day },
|
||||
universe,
|
||||
corporateActions: corporateActions.map(item => ({ ...item, end: item.end + day })),
|
||||
};
|
||||
const input = {
|
||||
metadata,
|
||||
bars: [0, day]
|
||||
.flatMap(offset =>
|
||||
dataset.bars.map(bar => ({
|
||||
seriesId: bar.seriesId,
|
||||
timestamp: bar.intervalStart + offset,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
}))
|
||||
)
|
||||
.map((bar, sourceSequence) => ({ ...bar, sourceSequence })),
|
||||
};
|
||||
const normalized = createDatasetV2(input);
|
||||
return {
|
||||
selection: 'declared-sessions',
|
||||
input,
|
||||
preparation: {
|
||||
version: 'canonical-dataset-preparation/v1',
|
||||
hash: normalized.manifest.hash,
|
||||
manifest: normalized.manifest,
|
||||
available: true,
|
||||
reason: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
async function beginStoredPreparation() {
|
||||
await flush(() => click('Settings'));
|
||||
await flush(() => click('Configure canonical research'));
|
||||
await flush(() => editSettings('Dataset input', 'stored-eod-sessions'));
|
||||
const stored = sessionPreparation();
|
||||
await flush(() => {
|
||||
const input = settingsField('Source metadata JSON');
|
||||
Object.defineProperty(input, 'files', {
|
||||
configurable: true,
|
||||
value: [
|
||||
new browser.File([JSON.stringify(stored.input.metadata)], 'sessions.json', {
|
||||
type: 'application/json',
|
||||
}),
|
||||
],
|
||||
});
|
||||
input.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Preview dataset'));
|
||||
return { stored, pending: request(storedPreparationPath, 'POST') };
|
||||
}
|
||||
|
||||
function LocationProbe() {
|
||||
pageLocation = router.useLocation().pathname;
|
||||
navigatePage = router.useNavigate();
|
||||
|
|
@ -390,6 +527,160 @@ afterAll(async () => {
|
|||
}
|
||||
});
|
||||
|
||||
describe('settings custody within one backtest', () => {
|
||||
test('canonical settings draft survives tab switches without remounting', async () => {
|
||||
await mountSettingsPage();
|
||||
expect(requests.some(item => item.path === '/api/v2/datasets/canonical')).toBe(false);
|
||||
expect(requests.some(item => item.path === '/api/v2/strategies')).toBe(false);
|
||||
await flush(() => click('Settings'));
|
||||
await flush(() => click('Configure canonical research'));
|
||||
await flush(() => {
|
||||
editSettings('Backtest name', 'Research draft');
|
||||
editSettings('Owner budget', '250');
|
||||
});
|
||||
const input = settingsField('Backtest name');
|
||||
const catalogRequests = requests.filter(item => item.path === '/api/v2/datasets/canonical');
|
||||
expect(catalogRequests).toHaveLength(1);
|
||||
await flush(() => click('Runs'));
|
||||
const panel = host.querySelector('[aria-label="Backtest settings panel"]');
|
||||
expect(panel?.hasAttribute('hidden')).toBe(true);
|
||||
expect(input.isConnected).toBe(true);
|
||||
for (const id of ['A', 'B']) {
|
||||
await flush(() => {
|
||||
void navigatePage(`/backtests/definition/run/${id}`);
|
||||
});
|
||||
await flush(() => reply(request(`/api/v2/runs/${id}`), run(id, 'failed')));
|
||||
expect(settingsField('Backtest name')).toBe(input);
|
||||
expect(panel?.hasAttribute('hidden')).toBe(true);
|
||||
}
|
||||
await flush(() => {
|
||||
void navigatePage('/backtests/definition');
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
expect(panel?.hasAttribute('hidden')).toBe(false);
|
||||
expect(settingsField('Backtest name').value).toBe('Research draft');
|
||||
expect(settingsField('Owner budget').value).toBe('250');
|
||||
expect(settingsField('Backtest name')).toBe(input);
|
||||
expect(requests.filter(item => item.path === '/api/v2/datasets/canonical')).toEqual(
|
||||
catalogRequests
|
||||
);
|
||||
expect(requests.filter(item => item.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('hidden previews and ambiguous retention preserve the captured input without rereading source', async () => {
|
||||
await mountSettingsPage();
|
||||
const { stored, pending } = await beginStoredPreparation();
|
||||
await flush(() => click('Runs'));
|
||||
expect(pending.signal?.aborted).toBe(false);
|
||||
await flush(() => reply(pending, stored));
|
||||
await flush(() => click('Settings'));
|
||||
expect(host.textContent).toContain(stored.preparation.hash);
|
||||
await flush(() => click('Retain dataset'));
|
||||
const original = request(retentionPath, 'POST');
|
||||
expect(JSON.parse(submittedBody(original))).toEqual({
|
||||
input: stored.input,
|
||||
expectedHash: stored.preparation.hash,
|
||||
});
|
||||
await flush(() => fail(original));
|
||||
await flush(() => click('Runs'));
|
||||
await flush(() => {
|
||||
void navigatePage('/backtests/definition/run/A');
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'failed')));
|
||||
await flush(() => click('Settings'));
|
||||
expect(settingsField('Dataset input').disabled).toBe(true);
|
||||
expect(settingsField('Source metadata JSON').disabled).toBe(true);
|
||||
await flush(() => click('Retry retaining same dataset'));
|
||||
const retry = request(retentionPath, 'POST');
|
||||
expect(submittedBody(retry)).toBe(submittedBody(original));
|
||||
expect(requests.filter(item => item.path === storedPreparationPath)).toHaveLength(1);
|
||||
await flush(() => click('Runs'));
|
||||
expect(retry.signal?.aborted).toBe(false);
|
||||
await flush(() => reply(retry, { preparation: stored.preparation }));
|
||||
await flush(() => click('Settings'));
|
||||
expect(settingsField('Canonical dataset').value).toBe(stored.preparation.hash);
|
||||
expect(host.textContent).toContain('Dataset retained.');
|
||||
expect(requests.filter(item => item.method !== 'GET').map(item => item.path)).toEqual([
|
||||
storedPreparationPath,
|
||||
retentionPath,
|
||||
retentionPath,
|
||||
]);
|
||||
});
|
||||
|
||||
for (const phase of ['preview', 'retention'] as const) {
|
||||
test(`changing the backtest disposes the editor and fences late ${phase}`, async () => {
|
||||
await mountSettingsPage();
|
||||
const { stored, pending: preview } = await beginStoredPreparation();
|
||||
let pending = preview;
|
||||
if (phase === 'retention') {
|
||||
await flush(() => reply(preview, stored));
|
||||
await flush(() => click('Retain dataset'));
|
||||
pending = request(retentionPath, 'POST');
|
||||
}
|
||||
const original = settingsField('Source metadata JSON');
|
||||
const catalogRequests = requests.filter(
|
||||
item => item.path === '/api/v2/datasets/canonical'
|
||||
).length;
|
||||
await flush(() => {
|
||||
void navigatePage('/backtests/other');
|
||||
});
|
||||
expect(original.isConnected).toBe(false);
|
||||
expect(pending.signal?.aborted).toBe(true);
|
||||
await flush(() =>
|
||||
reply(pending, phase === 'preview' ? stored : { preparation: stored.preparation })
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/other'), {
|
||||
...definition,
|
||||
id: 'other',
|
||||
name: 'Other backtest',
|
||||
});
|
||||
reply(request('/api/v2/backtests/other/runs'), []);
|
||||
});
|
||||
expect(host.querySelector('[aria-label="Backtest settings panel"]')).toBeNull();
|
||||
expect(requests.filter(item => item.path === '/api/v2/datasets/canonical')).toHaveLength(
|
||||
catalogRequests
|
||||
);
|
||||
await flush(() => click('Settings'));
|
||||
await flush(() => click('Configure canonical research'));
|
||||
expect(settingsField('Backtest name').value).toBe('Other backtest');
|
||||
expect(settingsField('Dataset input').value).toBe('export');
|
||||
expect(settingsField('Canonical dataset').value).toBe('');
|
||||
expect(host.textContent).not.toContain('sessions.json');
|
||||
expect(host.querySelector('[aria-label="Prepared dataset metadata"]')).toBeNull();
|
||||
expect(
|
||||
requests.filter(
|
||||
item => item.method === 'PUT' || (item.path.endsWith('/runs') && item.method === 'POST')
|
||||
)
|
||||
).toHaveLength(0);
|
||||
});
|
||||
}
|
||||
|
||||
test('explicitly discarding canonical setup still removes the draft', async () => {
|
||||
await mountSettingsPage();
|
||||
await flush(() => click('Settings'));
|
||||
await flush(() => click('Configure canonical research'));
|
||||
await flush(() => editSettings('Backtest name', 'Discard this draft'));
|
||||
const oldConfirm = Object.getOwnPropertyDescriptor(browser, 'confirm');
|
||||
try {
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => click('Back to draft settings'));
|
||||
expect(settingsField('Backtest name').value).toBe('Discard this draft');
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => click('Back to draft settings'));
|
||||
expect(host.querySelector('[aria-label="Canonical dataset"]')).toBeNull();
|
||||
await flush(() => click('Configure canonical research'));
|
||||
expect(settingsField('Backtest name').value).toBe(definition.name);
|
||||
} finally {
|
||||
if (oldConfirm) {
|
||||
Object.defineProperty(browser, 'confirm', oldConfirm);
|
||||
} else {
|
||||
Reflect.deleteProperty(browser, 'confirm');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('run selection and persisted status authority', () => {
|
||||
for (const lateFailure of [false, true]) {
|
||||
test(`stale_status_response: A ${lateFailure ? 'error' : 'success'}/finally cannot replace B loading`, async () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue