fix(research): preserve settings and capture across tabs (RP06)

This commit is contained in:
Boki 2026-10-27 09:31:46 -04:00
parent 6d549542a9
commit c838e3d05a
4 changed files with 405 additions and 46 deletions

View file

@ -36,6 +36,8 @@ export function BacktestDetailPageV2() {
const [showFinding, setShowFinding] = useState(false);
const [showArchiveDialog, setShowArchiveDialog] = useState(false);
const [showCanonicalSetup, setShowCanonicalSetup] = useState(false);
// A visited editor owns drafts and captured dataset retries until this backtest changes.
const [settingsOwner, setSettingsOwner] = useState<string | null>(null);
const navigationGeneration = useRef(0);
const {
@ -95,13 +97,18 @@ export function BacktestDetailPageV2() {
navigationGeneration.current++;
setShowNewRun(false);
setShowArchiveDialog(false);
setShowCanonicalSetup(false);
setShowFinding(false);
return () => {
navigationGeneration.current++;
};
}, [id, runId]);
useEffect(() => {
setSettingsOwner(null);
setShowCanonicalSetup(false);
setActiveTab('runs');
}, [id]);
useEffect(() => {
if (id) {
void loadBacktest(id);
@ -217,6 +224,44 @@ export function BacktestDetailPageV2() {
[backtest]
);
const renderSettings = () => (
<div className="max-w-4xl mx-auto space-y-4">
{catalog && backtest && (showCanonicalSetup || backtest.config.canonical) ? (
<CanonicalSetup
key={backtest.id}
backtest={backtest}
disabled={archived || isLoading}
onSave={request => updateBacktest(backtest.id, request)}
onClose={!backtest.config.canonical ? () => setShowCanonicalSetup(false) : undefined}
/>
) : (
<>
{catalog && (
<div className="space-y-2">
<p className="text-sm text-text-secondary">
This draft is not configured for canonical execution. Select an eligible retained
dataset and inspect the simulation policy before running.
</p>
<button
type="button"
className="px-3 py-2 border border-border rounded-md text-primary-500 disabled:opacity-50"
disabled={archived || isLoading}
onClick={() => setShowCanonicalSetup(true)}
>
Configure canonical research
</button>
</div>
)}
<BacktestConfiguration
onSubmit={handleConfigSubmit}
disabled={archived || isLoading}
initialConfig={backtestConfig}
/>
</>
)}
</div>
);
const renderTabContent = () => {
if (['details', 'trades'].includes(activeTab)) {
if (isLoading) {
@ -329,46 +374,6 @@ export function BacktestDetailPageV2() {
/>
</div>
);
case 'settings':
return (
<div className="max-w-4xl mx-auto space-y-4">
{catalog && backtest && (showCanonicalSetup || backtest.config.canonical) ? (
<CanonicalSetup
key={backtest.id}
backtest={backtest}
disabled={archived || isLoading}
onSave={request => updateBacktest(backtest.id, request)}
onClose={
!backtest.config.canonical ? () => setShowCanonicalSetup(false) : undefined
}
/>
) : (
<>
{catalog && (
<div className="space-y-2">
<p className="text-sm text-text-secondary">
This draft is not configured for canonical execution. Select an eligible
retained dataset and inspect the simulation policy before running.
</p>
<button
type="button"
className="px-3 py-2 border border-border rounded-md text-primary-500 disabled:opacity-50"
disabled={archived || isLoading}
onClick={() => setShowCanonicalSetup(true)}
>
Configure canonical research
</button>
</div>
)}
<BacktestConfiguration
onSubmit={handleConfigSubmit}
disabled={archived || isLoading}
initialConfig={backtestConfig}
/>
</>
)}
</div>
);
case 'details':
// Only render if we have matching results or no results yet
if (runResults && currentRun && runResults.runId !== currentRun.id) {
@ -462,7 +467,12 @@ export function BacktestDetailPageV2() {
{(currentRun ? runTabs : []).concat(baseTabs).map(tab => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
onClick={() => {
if (tab.id === 'settings' && id) {
setSettingsOwner(id);
}
setActiveTab(tab.id);
}}
className={`
whitespace-nowrap py-2 px-3 border-b-2 font-medium text-sm
${
@ -621,7 +631,12 @@ export function BacktestDetailPageV2() {
currentRun.id === runId &&
currentRun.backtestId === id &&
backtest?.id === id && <RunReproduction run={currentRun} archived={archived} />}
{renderTabContent()}
{settingsOwner === id && backtest?.id === id && (
<div key={id} hidden={activeTab !== 'settings'} aria-label="Backtest settings panel">
{renderSettings()}
</div>
)}
{activeTab !== 'settings' && renderTabContent()}
</div>
</div>
{showFinding && findingResult && (

View file

@ -11,3 +11,5 @@ Files/locks: `apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx`
Acceptance/tests: demonstrate the original loss before changing code; ordinary name/policy changes survive Settings → Runs → Settings; capture and ambiguous-retention retry retain exactly the same input/hash without another source read; late completion while hidden stays owned by the same template; same-backtest run navigation preserves the draft. Other tabs cannot expose/focus hidden settings, and entering a backtest does not eagerly fetch the catalog. Changing backtest ID clears the old editor and fences late completion; explicit discard/save still work. Verify zero unintended template/run writes during navigation, with a real browser retention retry scenario. Existing polling, cancellation, archived and legacy-history behavior must pass.
Gates: focused page/lifecycle tests, application/authored-test types, strict lint, production build; root full repository and Chromium suite. Parallel with RP05 because the parent owns mounting while the child owns dataset choice. No broad navigation refactor; the main regression risks are stale ownership, hidden focusable inputs and newly eager requests.
Accepted October 27, 2026: the original name-draft loss was reproduced before the fix. One lazily mounted settings panel now survives same-backtest tabs/run URLs; another backtest disposes it. Independent review passed 45 lifecycle tests / 279 assertions; broader implementer suites passed 198 / 967. Root full repository gate and both real browser regressions passed: unsaved name survives index-to-run navigation without changing the saved definition, and a committed retention response can be lost, followed by tab changes and exact retry after source removal, without a source reread. Hidden controls are absent from accessible role queries. [Combined evidence](../../real-data-research.md) records the in-memory scope; no persistent draft or general navigation framework was added.

View file

@ -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({

View file

@ -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 () => {