Repository navigation
FIX: guard preset editor navigation while edits are pending - #4284
Manohar Paturi (ManoharPaturi) wants to merge 7 commits into
Conversation
2077094 to
bc7e54f
Compare
|
The one remaining red job looks unrelated to this change. main-job (macos-latest, 3.12, dev) failed on tests/unit/backend/test_target_types_concurrency.py::test_health_remains_schedulable_during_cold_target_types[two-workers-completion] with a test watchdog TimeoutError. This PR touches only the preset editor and its tests, and the same test suite passes in the matrix on the same commit: macos 3.12 dev_all, every other macos cell, and every ubuntu and windows cell are green. The run also shows several unrelated tests taking 13 to 15 seconds on that runner, so it reads like a loaded machine tripping the watchdog backstop. A rerun of that job should clear it. |
| } else { | ||
| await scenarioPresetsApi.update(loaded.preset.name, preset, loaded.version) | ||
| } | ||
| allowNavigation.current = true |
There was a problem hiding this comment.
[P2] Do not offer to discard a save that is in progress
Edit a stored preset, click Save preset, and click a sidebar item while the button shows "Saving...". The new dialog says that the changes will be lost. If you click Discard changes, the sidebar page opens, but the PUT still completes and saves the edit. Then navigate(PRESETS_ROUTE) on line 380 runs from the unmounted editor (the data-router navigate stays active after unmount) and moves you to the preset library. Thus the dialog states the wrong result, and the app replaces the page that you chose. The redirect after unmount existed before this PR, but this dialog now offers it as Discard changes. While saving is true, show text that matches the real result, and navigate after a save only if the editor is still mounted. The test at line 681 expects navigate after unmount; change it to expect no navigate. Add a real-router test that leaves during a deferred save, resolves the save, and expects the chosen page to stay open.
const mounted = useRef(false)
useEffect(() => {
mounted.current = true
return () => { mounted.current = false }
}, [])
// in handleSubmit, after the await
allowNavigation.current = true
if (mounted.current) navigate(PRESETS_ROUTE)
// dialog
<ConfirmDialog
open={blocker.state === 'blocked'}
title={saving ? 'Leave while saving?' : 'Discard unsaved changes?'}
confirmLabel={saving ? 'Leave' : 'Discard changes'}
cancelLabel={saving ? 'Stay' : 'Keep editing'}
onConfirm={discardAndLeave}
onCancel={keepEditing}
>
{saving
? 'The save continues after you leave. If it fails, you will not see the error.'
: 'Your unsaved preset changes will be lost if you continue.'}
</ConfirmDialog>There was a problem hiding this comment.
You were right on both counts. While a save is pending the dialog now reads Leave while saving?, with Leave and Stay, and says that the save continues and that a failure would not be seen. The redirect after a successful save only runs if the editor is still mounted. I confirmed that second half with a real router: navigate does fire after unmount, so the mounted check is the thing that stops it.
The test that expected navigate after unmount now expects none, and a new real router test leaves during a deferred save, resolves it, and expects the chosen page to stay open. I also tried the case you did not mention, where the save finishes while the prompt is still open: the editor goes to the preset library and the prompt closes, which is where every successful save goes anyway.
| } | ||
| const hasUnsavedChanges = status === 'ready' | ||
| && !readOnly | ||
| && !scenarioLoading |
There was a problem hiding this comment.
[P2] Keep the leave guard on while a scenario loads
!scenarioLoading turns off both useBlocker and useBeforeUnload for the full getScenario request, but Description and the scanner switch stay enabled. In edit mode, type in Description while "Loading scenario..." shows and click Cancel: the editor leaves with no prompt, and the edit is lost. In create mode, the same occurs when you select a scenario and leave before it loads; the test at line 572 now expects this. Set the saved metadata from response.preset when the preset response arrives, with config: null, and set only the saved config when hydration finishes. Then remove !scenarioLoading here. An untouched editor stays clean because config is null on both sides during the first load.
// when the preset response arrives
setSavedDraft({
name: response.preset.name,
description: response.preset.description ?? '',
showInScanner: response.preset.show_in_scanner !== false,
scenarioName: response.preset.scenario_name,
config: null,
})
// after hydration succeeds
setSavedDraft((previous) => ({ ...previous, config: hydrated }))
const hasUnsavedChanges = status === 'ready'
&& !readOnly
&& presetDraftSignature(currentDraft) !== presetDraftSignature(savedDraft)There was a problem hiding this comment.
Done the way you described. The stored fields become the baseline as soon as the preset response arrives, with config null, and only the saved config is set when hydration finishes, so !scenarioLoading is gone from the guard.
Regressions: in edit mode, typing in Description while Loading scenario... is shown and then pressing Cancel opens the discard dialog, where it used to leave silently. In create mode the Cancel test you pointed at now goes through the dialog. The clean editor test holds the scenario load open with a deferred promise and checks that an untouched editor stays clean both while it loads and after it has loaded.
| config: ScenarioConfigFormState | null | ||
| } | ||
|
|
||
| const presetDraftSignature = (draft: PresetDraft): string => JSON.stringify(draft) |
There was a problem hiding this comment.
[P2] Ignore technique click order in the draft signature
JSON.stringify(draft) compares config.techniques in array order, but the technique selector appends each checked technique to the end. With two selected techniques, uncheck the first and check it again: the checkboxes are the same, but [a, b] becomes [b, a], so both guards ask the user to discard changes that they undid. matchesTechniques in scenarioPresetForm.ts already treats techniques as a set for this reason. Sort a copy for the signature only, and add an uncheck-and-recheck regression.
const presetDraftSignature = (draft: PresetDraft): string => JSON.stringify({
...draft,
config: draft.config && {
...draft.config,
techniques: [...draft.config.techniques].sort(),
},
})There was a problem hiding this comment.
Done, with the sort applied to a copy that is used only for the comparison, and the uncheck and recheck regression is in and fails on the previous head.
The same click order problem exists one field over: the dataset table appends a dataset you add back, so removing a dataset and adding it again made the draft look edited. I reproduced that as well. The comparison now sorts dataset sources and filter values alongside techniques, and each of the three has its own regression. I checked that each one earns its place: removing the sort for just one of the three makes exactly that test fail.
There was a problem hiding this comment.
Filter key order still reads as an edit
The sort fixed techniques, sources and filter values. But with two stored filter keys, turn a harm-category chip on and off: the table deletes the key when all values are selected and adds it back last, so the guard asks to discard. Sort object keys in the signature and add a regression.
There was a problem hiding this comment.
Reproduced before touching anything: with two stored filter keys, checking the last missing harm category makes the table delete the key, and unchecking it adds the key back at the end, so the guard asked to discard an undone action.
The signature now sorts the filter keys as well, alongside techniques, sources and filter values. A regression test covers the on and off dance on a second stored key, and it fails on the previous code. I also checked it earns its place: removing only the key sort makes exactly that one test fail.
There was a problem hiding this comment.
Filter keys are fixed. But the API returns sources as {name, max_size: 'default', fetch: null}, and the picker re-adds {name}. Reset drops max_total; a retyped total comes back last. Both still ask to discard. Sort keys and treat null and 'default' as unset in the signature.
There was a problem hiding this comment.
Both reproduced before I changed anything, with the dialog asking to discard each time, and both are fixed now.
The comparison is no longer a JSON dump with sorts stacked on it. A draft goes through one normal form first, in its own module (presetDraftSignature.ts): key order never counts, techniques, datasets and filter values compare as selections, and an unset field reads as unset whether the API spells it null, 'default' or leaves it out. A value is still never folded away, so a pinned limit, policy or filter reads as an edit.
I took the fixture shape from the backend serializer itself instead of from reading the model, so the regressions use exactly what a stored preset comes back as. Four of them failed on the previous head: a dataset added back, a total typed again after a reset, a total reset to a stored default, and a dataset limit that was reset after the dataset had been added back.
| </div> | ||
| </form> | ||
|
|
||
| <ConfirmDialog |
There was a problem hiding this comment.
[P3] Return focus to the control that opened the discard dialog
When a keyboard user presses Escape or Keep editing, this dialog closes but focus goes to <body>. Focus does not go back to the control that opened the dialog. The cause is the shared ConfirmDialog: it opens only from the open prop, with no DialogTrigger, so Fluent has no element to return focus to. Every ConfirmDialog user has the same cause. Record document.activeElement when open becomes true, and focus it again on close if it is still connected. Use useLayoutEffect: Fluent moves focus into the dialog in its own effect, which runs before a useEffect in ConfirmDialog. This one change fixes this guard and the other dialogs; it can go in this PR or in a small separate PR.
// ConfirmDialog.tsx
const returnFocusTo = useRef<HTMLElement | null>(null)
useLayoutEffect(() => {
if (open) {
returnFocusTo.current = document.activeElement as HTMLElement | null
return
}
const target = returnFocusTo.current
returnFocusTo.current = null
if (target?.isConnected) target.focus()
}, [open])There was a problem hiding this comment.
Added in ConfirmDialog, essentially as you wrote it, so every confirm dialog gets it. Covered with Escape and with the cancel button, plus the case where the control that opened the dialog is gone by the time it closes. The blocker test now asserts that focus comes back to the Leave editor button, and I ran the real app in a browser and watched focus return to the sidebar item that opened the dialog.
I kept it in this PR rather than splitting it out.
|
|
||
| expect(await screen.findByLabelText('Current URL')).toHaveTextContent('/registry/scenario-presets') | ||
| expect(screen.queryByRole('dialog', { name: /discard/i })).not.toBeInTheDocument() | ||
| expect(mockCreate).toHaveBeenCalledTimes(1) |
There was a problem hiding this comment.
[P2] Test that a pending or failed save keeps the leave guard on
This test covers only a successful save. The 409 test at line 757 uses the mocked navigate and submits an unchanged preset, and the pending-save test unmounts before the save resolves. So if a later change sets allowNavigation.current = true before the await instead of after it, no test fails, and a rejected edit can be lost when the user leaves. Add a real-router test with a deferred update: edit a stored preset, click Save, and try to leave; expect a confirmation dialog and no URL change. Then reject the save with a 409 and expect the error, a prevented beforeunload, and the dialog again. In the pending step, find the dialog by role only, because the pending-save dialog text can change (see the comment on line 379).
it('keeps leave protection while a save is pending and after it is rejected', async () => {
const user = userEvent.setup()
mockUseNavigate.mockImplementation(
jest.requireActual<typeof import('react-router')>('react-router').useNavigate,
)
const saving = deferred<ScenarioPresetResponse>()
mockUpdate.mockReturnValueOnce(saving.promise)
renderEdit()
await user.type(await screen.findByTestId('preset-description-input'), ' Updated.')
await user.click(screen.getByRole('button', { name: 'Save preset' }))
await user.click(screen.getByRole('button', { name: 'Leave editor' }))
expect(await screen.findByRole('dialog')).toBeInTheDocument()
expect(screen.getByLabelText('Current URL')).toHaveTextContent('/registry/scenario-presets/nightly_probe/edit')
await user.keyboard('{Escape}')
await act(async () => { saving.reject(apiError(409, 'The preset changed since it was loaded.')) })
expect(await screen.findByText('The preset changed since it was loaded.')).toBeInTheDocument()
const event = new Event('beforeunload', { cancelable: true })
window.dispatchEvent(event)
expect(event.defaultPrevented).toBe(true)
await user.click(await screen.findByRole('button', { name: 'Leave editor' }))
expect(await screen.findByRole('dialog', { name: /discard/i })).toBeInTheDocument()
expect(screen.getByLabelText('Current URL')).toHaveTextContent('/registry/scenario-presets/nightly_probe/edit')
})There was a problem hiding this comment.
Added along the lines you outlined: a real router test with a deferred update, a leave attempt while the save is pending (dialog found by role, URL unchanged), then a 409 with the error shown, beforeunload prevented, and the discard dialog again.
It earns its keep. Moving allowNavigation.current = true to before the await makes this test fail, together with the new test from the save in progress thread. That matches what you found.
| // The dialog teardown leaves the background aria-hidden in jsdom, so the | ||
| // reloaded editor is queried with hidden elements included. | ||
| await waitFor(() => | ||
| expect(screen.getByRole('textbox', { name: 'goals', hidden: true })).toHaveValue(' Next, goal ') |
There was a problem hiding this comment.
[P2] Use accessible queries after the dialog closes
These queries use hidden: true after the discard dialog closes (also at lines 602 and 611). Thus the tests still pass if the editor stays aria-hidden after Keep editing or after the remount. The comments also say that an earlier test can change the result, which makes the tests depend on run order. frontend-test.instructions.md asks for normal accessible-role queries after a modal closes, and lists order-dependent tests as an anti-pattern. Remove hidden: true and wait for the controls with findByRole or a normal query in waitFor, because Fluent restores background accessibility after a short delay. Without hidden: true, the file passes 66 of 66 tests in order and in random order, so the workaround is not needed.
await user.click(screen.getByRole('button', { name: 'Discard changes' }))
await waitFor(() =>
expect(screen.getByRole('textbox', { name: 'goals' })).toHaveValue(' Next, goal ')
)
await user.click(await screen.findByRole('button', { name: 'Save preset' }))There was a problem hiding this comment.
All hidden: true queries are gone together with the comments about earlier tests, and after a discard the tests wait for the heading on the destination page as the guide asks.
They were flaky for me at first, and the cause turned out to be worth knowing. The tabster library behind Fluent restores the background it hid in a deferred walk, about 250 ms after a dialog closes. When the closing dialog is the last holder of that library and the route change unmounts it, the restore is dropped and the page stays aria hidden. The app shell always keeps a tab list mounted, so that never happens for users. I checked the real app in a browser: the background is back within 15 ms of the dialog leaving the page. My harness rendered only the editor, so there the dialog was the last holder. Forcing that worst case left the page hidden for good. With a TabList mounted in the harness the same forced case recovers, and the two suites now pass six times in a row in order and four times with randomized order.
While a save is pending, the dialog says the save continues instead of offering to discard, and the redirect after a successful save only runs while the editor is still mounted, so leaving during a save no longer pulls the operator to the library. The stored fields are the baseline for the leave guard as soon as the preset response arrives, and the configuration joins it once loaded, so the guard stays on while the scenario loads instead of letting a typed edit leave without a prompt. Techniques, dataset sources and filter values are compared as selections, so restoring a removed item no longer reads as an edit. ConfirmDialog returns focus to the control that opened it, which covers the discard dialog and the other confirm dialogs that open from state. Tests wait for accessible controls after dialogs close, with the harness mounting a tab list the way the app shell does.
hannahwestra25
left a comment
There was a problem hiding this comment.
The earlier comments are addressed; two items remain (one reply, one inline). Main now conflicts in this test file's @/services/api import: keep both datasetsApi and promptGeneratorsApi. After the merge, main relabels origins, so the test option 'harmbench (unknown)' must become 'harmbench (Unknown)'.
| await waitFor(() => expect(screen.getByRole('button', { name: 'Open dialog' })).toHaveFocus()) | ||
| }) | ||
|
|
||
| it('should still close cleanly when the control that opened the dialog is gone', async () => { |
There was a problem hiding this comment.
Make this test check an outcome
This test passes when the isConnected check is removed, and also when the focus return is removed. focus() on a detached element does nothing, and the test only checks that a new button exists. Delete it, or assert where focus goes after the dialog closes.
There was a problem hiding this comment.
Kept the test, but it now asserts where focus goes: once the dialog has closed with the opener already unmounted, focus must be on the page, never inside the closed dialog. That is the outcome a keyboard user gets on this path.
You are right that this case on its own cannot prove the connection check, since focus() on a detached element does nothing either way. The two tests above pin the restore itself; this one pins the degraded path.
|
Main is merged into the branch. The api mock import keeps both datasetsApi and promptGeneratorsApi, and the dataset picker option now reads 'harmbench (Unknown)' after the origin relabel. The filter key order thread and the dialog test thread have fixes pushed as well, and both suites pass on the merged tree. |
…set listing Merging main brought in microsoft#4180, which rewired useScenarioDatasets to read scenariosApi.listCompatibleDatasets instead of datasetsApi.listDatasets, so the two filter click-order regressions' listing overrides no longer reached the editor and their harm-category chips never rendered on the merged tree. The overrides now stub the compatible listing the editor reads. The guard itself compares request shapes, not listings, and is unaffected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
| techniques: [...config.techniques].sort(), | ||
| datasets: { | ||
| ...datasets, | ||
| sources: [...(datasets.sources ?? [])].sort((first, second) => first.name.localeCompare(second.name)), |
There was a problem hiding this comment.
Supporting the open thread on source shapes with the concrete cases I verified, so the next push can cover the whole class at once:
DatasetSourceInput(pyrit/models/scenario_dataset.py) defaultsmax_size: "default"andfetch: None, so a stored preset's sources come back as{name, max_size: 'default', fetch: null}while the picker re-adds a bare{name}(ScenarioDatasetTable.tsxline 165) — remove + re-add still asks to discard.- Removing the last source leaves
sources: []in the request, while a preset stored without sources hydrates with the key absent — so add + remove on an untouched editor reads as an edit too. updateTotaldeletesmax_totalwhen reset to default, so a stored explicit'default'differs by key presence, and a retyped value lands last (key order).
Rather than stacking more sorts onto JSON.stringify, consider building the signature from a canonical projection — e.g. map each source to [name, max_size ?? 'default', fetch ?? 'default'] sorted by name, fold undefined/null/'default' to one token for max_per_dataset/max_total/fetch, and treat empty sources/filters as absent. That removes value-shape, key-order and key-presence differences in one place instead of one sort per discovery.
The current dataset regressions use bare {name} fixtures, which is why they pass while the real shapes still false-positive — the regressions for this fix should use the shape the API returns.
There was a problem hiding this comment.
Thanks for laying the cases out like this. It turned the fix into one change instead of another round of sorts.
The signature now comes from a canonical projection, in its own module, and it covers your three points. Each source is reduced to its name plus whatever is actually set, with max_size read as unset when it is null or 'default', and fetch when it is null, blank or 'default', and the list is sorted by name. max_per_dataset, max_total and fetch fold null and 'default' into unset, so a stored 'default' and a reset that drops the key are the same draft. Empty sources and filters read as absent. On top of that every object is serialized with its keys sorted, so key order stops mattering anywhere in the draft and not only for the keys found so far.
One place I did not follow the suggestion literally: filter values stay sorted as a selection, but an empty filter list is kept. The table writes {harm_categories: []} to mean every value where the scenario pins a subset, so it can mean something different from an absent key.
The regressions now use the shape the API returns. I ran a stored preset through the backend serializer to get it rather than trusting my reading of the model. Four failed on the previous head: a dataset added back, a total typed again after a reset, a total reset to a stored default, and a dataset limit that was reset after the dataset had been added back. Your second case, add and remove on an untouched editor, was already clean there, because absent and empty sources both normalized to an empty list. There is a test pinning it now.
presetDraftSignature.test.ts lists the shape pairs that must compare equal and the ones that must stay different. I removed each rule from the module in turn to check that the rows earn their place. Each removal fails its own rows and nothing else, and two deliberately wrong rules, reading an empty filter list as no filter and sorting every list, each fail exactly the row written against them. Two rows about the order of the request's own keys stay green under every single removal, because the projection's fixed field order and the key sort each cover that on its own.
| expect(mockUpdate).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('blocks in-app navigation until unsaved preset edits are discarded', async () => { |
There was a problem hiding this comment.
Nit: the guard tests all navigate by push (Link / navigate). A small POP regression with the real-router harness — await act(() => router.navigate(-1)), expect the dialog, keep editing, expect the URL restored — would pin browser-back behavior too, which takes a different path through the router's blocker handling.
There was a problem hiding this comment.
Added, as "asks before the browser back button leaves unsaved edits, and stays when kept". It starts the router with a page behind the editor, edits the description, steps the history back through the router, expects the discard dialog, keeps editing, and checks that the URL is back on the editor with the edit intact.
It passed on the previous head as well, because the same blocker covers both kinds of navigation, and it fails as soon as the blocker is disarmed.
| expect(await screen.findByRole('heading', { name: 'Other page' })).toBeInTheDocument() | ||
| }) | ||
|
|
||
| it('does not treat the click order of a restored filter selection as an edit', async () => { |
There was a problem hiding this comment.
Context for the two commits I pushed to this branch: merging latest main brought in #4180, which rewired useScenarioDatasets to read scenariosApi.listCompatibleDatasets(scenarioName) instead of datasetsApi.listDatasets — so this test and the re-selected-filter-group one below stopped reaching the editor with their listing overrides, and the harm-category chips never rendered (both failed on the merged tree; everything else passed). The second commit repoints the overrides at the compatible listing and drops the now-unused datasetsApi import; all 77 tests in this file and the ConfirmDialog suite pass on the new head, tsc and eslint clean. The guard itself compares request shapes, not listings, and is unaffected.
There was a problem hiding this comment.
Thanks for fixing those on the branch. I built on top of your head. The two tests you repointed keep the listing override they have now, and only their stored preset moved to the shape the API returns.
One note on what I claimed earlier. My "full suite passes on the merged tree" was true for the main I had merged at the time, which was still before #4180 landed. That is why those two did not fail for me and did for you.
The API returns every field of a stored preset with each unset one spelled out, while the controls write only what was touched and in click order. The guard asked to discard a dataset added back, a total typed again after a reset, and a limit reset to the default. The comparison now goes through presetDraftSignature.ts: key order never counts, techniques, datasets and filter values compare as selections, and null, 'default' and absent read as the same unset field. The dataset regressions use the shape the API returns, a unit table lists the shapes that must compare equal and those that must stay different, and a browser back regression covers the router's POP path.
Description
Fixes #4279
The preset editor loses unsaved edits on navigation without a prompt. It now guards them the same way the suite, conversation, and configuration editors do.
beforeunloadguard asks for browser confirmation on refresh or closepresetDraftSignature.ts): techniques, datasets and filter values compare as selections, the order of object keys never counts, and an unset field reads as unset whether the API returns it as null, as'default', or not at allConfirmDialogreturns focus to the control that opened it, since it opens from state and has no trigger for Fluent to restore focus to