From 77815060a2c3934637be563625c742a4a3abb59e Mon Sep 17 00:00:00 2001 From: YektaY Date: Sun, 18 Oct 2026 07:54:40 -0700 Subject: [PATCH 1/6] Serialize config-store modal operations behind one busy slot The modal tracked a single busySlug and disabled only that row's buttons, so Load A followed by Load B overwrote the marker: both requests ran, both called onLoaded, and the later response won. Each `finally` also cleared the marker unconditionally, re-enabling a row whose operation was still in flight. Save and every row's Load/Rename/Delete now share one slot (state for the render, a ref for handlers), and every action is disabled while it is held. A successful Load closes the modal, so nothing useful can run beside it. An operation releases the slot only if it still holds it. A status line names the running row operation, which also explains why the buttons are disabled. Save, Rename and Delete now block X, Escape and the backdrop until they settle. The old `onClose={saving ? undefined : onClose}` did not block: on X or backdrop Carbon hid the dialog while the parent's `open` stayed true, so the toolbar could not reopen it. Escape still closed it, because Carbon registers its Escape listener once per open and keeps that render's onClose. The guard returns false from a stable handler that reads the slot's ref, which holds on all three paths. A Load stays dismissible; it is cancelled on close in the next commit. Refs #92 --- src/components/ConfigStoreModal.test.tsx | 372 +++++++++++++++++++++++ src/components/ConfigStoreModal.tsx | 101 ++++-- 2 files changed, 448 insertions(+), 25 deletions(-) create mode 100644 src/components/ConfigStoreModal.test.tsx diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx new file mode 100644 index 0000000..fd6b529 --- /dev/null +++ b/src/components/ConfigStoreModal.test.tsx @@ -0,0 +1,372 @@ +// @vitest-environment jsdom +// +// Pins ConfigStoreModal's async lifecycle (slaclab/react-trace#92). Save and +// every row's Load/Rename/Delete share one busy slot, so only one runs at a +// time. Save, Rename and Delete block all three of Carbon's dismissal paths (X, +// Escape, backdrop) until they settle. +// +// Every magpie call returns a promise the test settles by hand, so each case +// controls exactly when a response lands relative to clicks and dismissals. +import { useState } from 'react'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { ConfigStoreModal } from './ConfigStoreModal'; +import { CanopyError } from '../api/client'; +import type * as Magpie from '../api/magpie'; +import type { ConfigDTO, PagedResult } from '../api/types'; + +const api = vi.hoisted(() => ({ + saveConfig: vi.fn(), + getConfig: vi.fn(), + listConfigs: vi.fn(), + updateConfig: vi.fn(), + deleteConfig: vi.fn(), +})); +vi.mock('../api/magpie', () => api); +// The workspace codec isn't under test: Save sends {}, Load hands `data` through. +vi.mock('../io/serialize', () => ({ + serializeConfigData: () => ({}), + deserializeConfigData: (data: unknown) => data, +})); + +interface Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (reason: unknown) => void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +function config(slug: string, name: string, createdDate: string): ConfigDTO { + return { + id: `id-${slug}`, + app: 'trace', + slug, + name, + description: null, + data: { from: slug }, + createdBy: null, + createdDate, + lastModifiedDate: createdDate, + }; +} + +// The list renders newest first, so A is the first row. +const A = config('slug-a', 'Config A', '2026-10-02T00:00:00Z'); +const B = config('slug-b', 'Config B', '2026-10-01T00:00:00Z'); +const PAGE: PagedResult = { results: [B, A], continuationToken: null, totalCount: 2 }; + +// Pending calls, in call order. getConfig doesn't reject on abort by itself: +// a test either settles it by hand (a response that beat the abort) or rejects +// it with an AbortError, as fetch would. +let loads: (Deferred & { slug: string; signal: AbortSignal | undefined })[]; +let saves: Deferred[]; +let renames: Deferred[]; +let deletes: Deferred[]; + +const onLoaded = vi.fn(); +const onToast = vi.fn(); +const parentClose = vi.fn(); + +// Stands in for TraceApp: owns `open`, always mounts the modal, and has a +// toolbar button that can only set `open` to true. +function Harness() { + const [open, setOpen] = useState(true); + return ( + <> + + + { + parentClose(); + setOpen(false); + }} + onLoaded={onLoaded} + onToast={onToast} + /> + + ); +} + +// Run `fn`, then let every promise continuation and React update it triggers finish. +async function settle(fn: () => void = () => {}) { + await act(async () => { + fn(); + await new Promise((r) => setTimeout(r, 0)); + }); +} + +async function mount() { + const result = render(); + await settle(); + return result; +} + +async function reopen() { + fireEvent.click(screen.getByText('toolbar-open')); + await settle(); +} + +function modal(): HTMLElement { + return document.querySelector('.cds--modal') as HTMLElement; +} + +function isVisible(): boolean { + return modal().classList.contains('is-visible'); +} + +type RowAction = 'Load' | 'Rename' | 'Delete'; +const ROW_ACTIONS: RowAction[] = ['Load', 'Rename', 'Delete']; + +// `hidden: true` throughout: after a close, aria-hidden follows the `open` prop. +function rowButton(name: string, action: RowAction): HTMLButtonElement { + const row = screen.getByText(name).closest('.cds--structured-list-row') as HTMLElement; + return within(row).getByRole('button', { name: action, hidden: true }) as HTMLButtonElement; +} + +function saveButton(): HTMLButtonElement { + return screen.getByRole('button', { + name: /^(Save & copy share link|Saving…)$/, + hidden: true, + }) as HTMLButtonElement; +} + +function allRowButtons(): HTMLButtonElement[] { + return [A, B].flatMap((c) => ROW_ACTIONS.map((action) => rowButton(c.name!, action))); +} + +function errorBanner(): Element | null { + return document.querySelector('.cds--inline-notification'); +} + +const PATHS = ['X', 'Escape', 'backdrop'] as const; +type DismissPath = (typeof PATHS)[number]; + +function dismiss(path: DismissPath) { + switch (path) { + case 'X': + fireEvent.click(screen.getByRole('button', { name: 'Close', hidden: true })); + break; + case 'Escape': + fireEvent.keyDown(document, { key: 'Escape', keyCode: 27 }); + break; + case 'backdrop': + fireEvent.mouseDown(modal()); + fireEvent.click(modal()); + break; + } +} + +beforeAll(() => { + // Carbon's icon-button tooltips observe their size; jsdom has no ResizeObserver. + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + } + ); +}); + +afterAll(() => { + vi.unstubAllGlobals(); +}); + +beforeEach(() => { + loads = []; + saves = []; + renames = []; + deletes = []; + api.listConfigs.mockResolvedValue(PAGE); + api.getConfig.mockImplementation((slug, signal) => { + const d = deferred(); + loads.push({ ...d, slug, signal }); + return d.promise; + }); + api.saveConfig.mockImplementation(() => { + const d = deferred(); + saves.push(d); + return d.promise; + }); + api.updateConfig.mockImplementation(() => { + const d = deferred(); + renames.push(d); + return d.promise; + }); + api.deleteConfig.mockImplementation(() => { + const d = deferred(); + deletes.push(d); + return d.promise; + }); + vi.spyOn(window, 'prompt').mockReturnValue('Renamed'); + vi.spyOn(window, 'confirm').mockReturnValue(true); +}); + +afterEach(() => { + // No vitest globals, so RTL can't register its own cleanup. + cleanup(); + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); + +describe('ConfigStoreModal: one operation at a time', () => { + it.each([ + ['B, then A', ['slug-b', 'slug-a']], + ['A, then B', ['slug-a', 'slug-b']], + ])('applies only the first of two Load clicks (responses %s)', async (_order, slugs) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + fireEvent.click(rowButton('Config B', 'Load')); + for (const slug of slugs) { + const load = loads.find((l) => l.slug === slug); + if (load) await settle(() => load.resolve(slug === A.slug ? A : B)); + } + expect(api.getConfig.mock.calls.map(([slug]) => slug)).toEqual([A.slug]); + expect(onLoaded).toHaveBeenCalledTimes(1); + expect(onLoaded).toHaveBeenCalledWith(A.data); + expect(onToast).toHaveBeenCalledTimes(1); + }); + + it('disables every row action and Save while a Load is in flight', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + expect(allRowButtons().map((b) => b.disabled)).toEqual(Array(6).fill(true)); + expect(saveButton().disabled).toBe(true); + }); + + it('disables every row action while a Save is in flight', async () => { + await mount(); + fireEvent.click(saveButton()); + expect(allRowButtons().map((b) => b.disabled)).toEqual(Array(6).fill(true)); + }); + + it.each(['Rename', 'Delete'] as const)( + 'does not start a %s while a Load is in flight', + async (action) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + fireEvent.click(rowButton('Config B', action)); + expect(window.prompt).not.toHaveBeenCalled(); + expect(window.confirm).not.toHaveBeenCalled(); + expect(api.updateConfig).not.toHaveBeenCalled(); + expect(api.deleteConfig).not.toHaveBeenCalled(); + } + ); + + it('does not start a Load while a Delete is in flight', async () => { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + fireEvent.click(rowButton('Config A', 'Load')); + expect(api.getConfig).not.toHaveBeenCalled(); + }); + + it("keeps A's Load disabled when a Rename clicked during it would have finished", async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + fireEvent.click(rowButton('Config B', 'Rename')); + await settle(() => renames.forEach((r) => r.resolve(B))); + expect(rowButton('Config A', 'Load').disabled).toBe(true); + }); + + it.each([ + ['Load', 'Loading "Config A"…'], + ['Rename', 'Renaming "Config A"…'], + ['Delete', 'Deleting "Config A"…'], + ] as const)('shows a %s in the status line', async (action, status) => { + await mount(); + fireEvent.click(rowButton('Config A', action)); + expect(screen.queryByText(status)).not.toBeNull(); + }); + + it('shows a Load failure and re-enables the row (control: passes before the fix too)', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + await settle(() => loads[0].reject(new CanopyError('config_not_found', 404, 'not found'))); + expect(screen.queryByText('not found')).not.toBeNull(); + expect(rowButton('Config A', 'Load').disabled).toBe(false); + expect(isVisible()).toBe(true); + expect(onLoaded).not.toHaveBeenCalled(); + }); +}); + +describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { + it.each(PATHS)( + 'blocks %s during a Save, then closes on it once the Save settles', + async (path) => { + await mount(); + fireEvent.click(saveButton()); + dismiss(path); + expect(isVisible()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + + await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + expect(saveButton().disabled).toBe(false); + dismiss(path); + expect(isVisible()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + await reopen(); + expect(isVisible()).toBe(true); + } + ); + + it('can still be opened from the toolbar after X was pressed during a Save', async () => { + await mount(); + fireEvent.click(saveButton()); + dismiss('X'); + await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + await reopen(); + expect(isVisible()).toBe(true); + }); + + it.each(PATHS.flatMap((path) => (['Rename', 'Delete'] as const).map((a) => [a, path] as const)))( + 'blocks dismissal during a %s (%s), then refreshes the list and closes', + async (action, path) => { + await mount(); + fireEvent.click(rowButton('Config B', action)); + dismiss(path); + expect(isVisible()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + + const listCalls = api.listConfigs.mock.calls.length; + await settle(() => (action === 'Rename' ? renames[0].resolve(B) : deletes[0].resolve())); + expect(api.listConfigs).toHaveBeenCalledTimes(listCalls + 1); + expect(rowButton('Config A', 'Load').disabled).toBe(false); + dismiss(path); + expect(isVisible()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + } + ); + + it('shows a Delete failure in the dialog it kept open', async () => { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + dismiss('Escape'); + await settle(() => deletes[0].reject(new CanopyError('forbidden', 403, 'not allowed'))); + expect(isVisible()).toBe(true); + expect(screen.queryByText('not allowed')).not.toBeNull(); + expect(rowButton('Config B', 'Delete').disabled).toBe(false); + }); + + it('keeps Save disabled across a parent-driven close and reopen until the Save settles', async () => { + await mount(); + fireEvent.click(saveButton()); + fireEvent.click(screen.getByText('parent-close')); + await reopen(); + expect(saveButton().disabled).toBe(true); + await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + expect(saveButton().disabled).toBe(false); + expect(errorBanner()).toBeNull(); + }); +}); diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index 7b2546b..dc78086 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -39,6 +39,15 @@ interface ConfigStoreModalProps { onToast: (t: { kind: 'success' | 'error'; title: string; subtitle?: string }) => void; } +// What the modal is busy with. Save and every row's Load/Rename/Delete share +// this one slot, so only one runs at a time: a successful Load closes the +// modal, which would orphan anything running beside it. +type BusyOp = + | { kind: 'save' } + | { kind: 'load' | 'rename' | 'delete'; slug: string; label: string }; + +const BUSY_VERB = { load: 'Loading', rename: 'Renaming', delete: 'Deleting' } as const; + // One unpaginated page. Truncation is surfaced in the list header rather than // silently hidden; real paging is slaclab/react-trace#80. const PAGE_SIZE = 200; @@ -77,14 +86,23 @@ export function ConfigStoreModal({ }: ConfigStoreModalProps) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); - const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [configs, setConfigs] = useState([]); const [totalCount, setTotalCount] = useState(null); const [listing, setListing] = useState(false); - // Slug currently undergoing a row action (delete/load), to disable its buttons. - const [busySlug, setBusySlug] = useState(null); + + // The one operation in flight (see BusyOp). State drives the render; the ref + // gives handlers and the close guard the current value without waiting for a + // re-render, so a second click in the same tick can't also claim the slot. + const [busy, setBusyState] = useState(null); + const busyRef = useRef(null); + const setBusy = useCallback((op: BusyOp | null) => { + busyRef.current = op; + setBusyState(op); + }, []); + const saving = busy?.kind === 'save'; + // Monotonic refresh id. A Save/Delete fires its own refresh while the open // refresh may still be in flight; without this, the slower (older) response // could land last and overwrite the newer post-mutation list. Only the latest @@ -126,14 +144,40 @@ export function ConfigStoreModal({ initialized.current = true; setName(''); setDescription(''); - setSaving(false); setError(null); void refresh(); }, [open, refresh]); - const handleSave = async () => { - setSaving(true); + // Carbon's X, Escape and backdrop all call this; returning false keeps the + // dialog open. Save, Rename and Delete block dismissal until they settle: the + // server change happens either way, so closing would only hide its outcome. + // This must read refs, not render state. Carbon registers its Escape listener + // once per open and keeps the onClose from that render, when nothing was busy. + const onCloseRef = useRef(onClose); + useEffect(() => { + onCloseRef.current = onClose; + }, [onClose]); + const requestClose = useCallback(() => { + const op = busyRef.current; + if (op && op.kind !== 'load') return false; + onCloseRef.current(); + }, []); + + // Claim the slot for `op`; false if another operation holds it. + const begin = (op: BusyOp): boolean => { + if (busyRef.current) return false; + setBusy(op); setError(null); + return true; + }; + // Release the slot only if `op` still holds it. + const end = (op: BusyOp) => { + if (busyRef.current === op) setBusy(null); + }; + + const handleSave = async () => { + const op: BusyOp = { kind: 'save' }; + if (!begin(op)) return; try { const data = serializeConfigData({ theme, plots }); const dto = await saveConfig(data, { @@ -156,59 +200,62 @@ export function ConfigStoreModal({ } catch (err) { setError(errText(err)); } finally { - setSaving(false); + end(op); } }; - const handleLoad = async (slug: string) => { - setBusySlug(slug); - setError(null); + const handleLoad = async (config: ConfigDTO) => { + const op: BusyOp = { kind: 'load', slug: config.slug, label: config.name || config.slug }; + if (!begin(op)) return; try { - const dto = await getConfig(slug); + const dto = await getConfig(config.slug); const result = deserializeConfigData(dto.data); onLoaded(result); onToast({ kind: 'success', title: 'Workspace loaded', - subtitle: dto.name ? `Loaded "${dto.name}"` : `Loaded config ${slug}`, + subtitle: dto.name ? `Loaded "${dto.name}"` : `Loaded config ${config.slug}`, }); onClose(); } catch (err) { setError(errText(err)); } finally { - setBusySlug(null); + end(op); } }; const handleRename = async (config: ConfigDTO) => { + // Don't prompt for an action that can't start. + if (busyRef.current) return; const next = window.prompt('Rename config', config.name ?? ''); if (next === null) return; // No-op a blank rename (Save likewise omits empty names) or an unchanged one. const trimmed = next.trim(); if (trimmed === '' || trimmed === (config.name ?? '')) return; - setBusySlug(config.slug); - setError(null); + const op: BusyOp = { kind: 'rename', slug: config.slug, label: config.name || config.slug }; + if (!begin(op)) return; try { await updateConfig(config.slug, { name: trimmed }); await refresh(); } catch (err) { setError(errText(err)); } finally { - setBusySlug(null); + end(op); } }; const handleDelete = async (config: ConfigDTO) => { + if (busyRef.current) return; if (!window.confirm(`Delete "${config.name || config.slug}"? This cannot be undone.`)) return; - setBusySlug(config.slug); - setError(null); + const op: BusyOp = { kind: 'delete', slug: config.slug, label: config.name || config.slug }; + if (!begin(op)) return; try { await deleteConfig(config.slug); await refresh(); } catch (err) { setError(errText(err)); } finally { - setBusySlug(null); + end(op); } }; @@ -222,7 +269,7 @@ export function ConfigStoreModal({ }; return ( - +
@@ -258,7 +305,7 @@ export function ConfigStoreModal({ rows={2} />
-
@@ -282,6 +329,10 @@ export function ConfigStoreModal({ onClick={() => void refresh()} disabled={listing} /> + {/* Save shows its progress on its own button. */} + {busy && busy.kind !== 'save' && ( + + )}
{listing ? ( @@ -314,8 +365,8 @@ export function ConfigStoreModal({ @@ -323,7 +374,7 @@ export function ConfigStoreModal({ size="sm" kind="ghost" onClick={() => void handleRename(c)} - disabled={busySlug === c.slug} + disabled={busy !== null} > Rename @@ -342,7 +393,7 @@ export function ConfigStoreModal({ iconDescription="Delete" renderIcon={TrashCan} onClick={() => void handleDelete(c)} - disabled={busySlug === c.slug} + disabled={busy !== null} /> From fb49de3cef032808984539f033ca5de937bebd4f Mon Sep 17 00:00:00 2001 From: YektaY Date: Sun, 18 Oct 2026 07:57:48 -0700 Subject: [PATCH 2/6] Abort and ignore an in-flight config Load when the modal closes A Load stayed live after X, Escape or the backdrop dismissed the modal. Nothing cancelled getConfig, and the modal is always mounted, so the response still called onLoaded and replaced the workspace after the dialog was gone. A reopen also kept the dismissed row's Load disabled until the old request settled, and then that stale response closed the new dialog. Each open is now a session. Closing ends it in requestClose and again in the `open` -> false effect (unmounting ends it too), and ending a session aborts the pending Load through the signal getConfig already accepts. Every operation applies its result, including errors, only while its session is current, which also covers a response that beat the abort. A reopen releases a slot still held by a dismissed Load. It leaves a Save, Rename or Delete in place: those block dismissal, so one can only reach a reopen through a close the parent made itself, and it is still running. The slot is released by identity rather than by session, so such an operation frees it when it settles, and a stale Load can't free a newer operation's slot. Refs #92 --- src/components/ConfigStoreModal.test.tsx | 77 +++++++++++++++++++++++- src/components/ConfigStoreModal.tsx | 72 +++++++++++++++++----- 2 files changed, 132 insertions(+), 17 deletions(-) diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx index fd6b529..cfade01 100644 --- a/src/components/ConfigStoreModal.test.tsx +++ b/src/components/ConfigStoreModal.test.tsx @@ -3,7 +3,8 @@ // Pins ConfigStoreModal's async lifecycle (slaclab/react-trace#92). Save and // every row's Load/Rename/Delete share one busy slot, so only one runs at a // time. Save, Rename and Delete block all three of Carbon's dismissal paths (X, -// Escape, backdrop) until they settle. +// Escape, backdrop) until they settle. A Load doesn't: dismissing aborts it and +// drops its result, even a response that beat the abort. // // Every magpie call returns a promise the test settles by hand, so each case // controls exactly when a response lands relative to clicks and dismissals. @@ -301,6 +302,80 @@ describe('ConfigStoreModal: one operation at a time', () => { }); }); +describe('ConfigStoreModal: dismissing cancels a Load', () => { + it.each(PATHS)( + 'closes on %s during a Load and ignores a response that beat the abort', + async (path) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + dismiss(path); + expect(isVisible()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + + await settle(() => loads[0].resolve(A)); + expect(onLoaded).not.toHaveBeenCalled(); + expect(onToast).not.toHaveBeenCalled(); + expect(parentClose).toHaveBeenCalledTimes(1); + } + ); + + it.each(PATHS)('aborts the Load request on %s and shows no error for it', async (path) => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + const { signal } = loads[0]; + dismiss(path); + expect(signal?.aborted).toBe(true); + + await settle(() => + loads[0].reject(new DOMException('The operation was aborted.', 'AbortError')) + ); + await reopen(); + expect(errorBanner()).toBeNull(); + expect(onLoaded).not.toHaveBeenCalled(); + }); + + it('re-enables Load on reopen, and the old response neither applies nor frees the new Load', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + dismiss('Escape'); + await reopen(); + expect(isVisible()).toBe(true); + expect(rowButton('Config A', 'Load').disabled).toBe(false); + + fireEvent.click(rowButton('Config A', 'Load')); + await settle(() => loads[0].resolve(A)); + expect(onLoaded).not.toHaveBeenCalled(); + expect(isVisible()).toBe(true); + expect(parentClose).toHaveBeenCalledTimes(1); + expect(rowButton('Config A', 'Load').disabled).toBe(true); + + await settle(() => loads[1].resolve(A)); + expect(onLoaded).toHaveBeenCalledTimes(1); + expect(isVisible()).toBe(false); + }); + + it('shows no error from a dismissed Load that fails after a reopen', async () => { + await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + dismiss('Escape'); + await reopen(); + await settle(() => loads[0].reject(new CanopyError('config_not_found', 404, 'not found'))); + expect(errorBanner()).toBeNull(); + expect(rowButton('Config A', 'Load').disabled).toBe(false); + }); + + it('aborts an in-flight Load on unmount and drops its response', async () => { + const { unmount } = await mount(); + fireEvent.click(rowButton('Config A', 'Load')); + const { signal } = loads[0]; + unmount(); + expect(signal?.aborted).toBe(true); + await settle(() => loads[0].resolve(A)); + expect(onLoaded).not.toHaveBeenCalled(); + expect(onToast).not.toHaveBeenCalled(); + }); +}); + describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { it.each(PATHS)( 'blocks %s during a Save, then closes on it once the Save settles', diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index dc78086..232c00c 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -133,24 +133,44 @@ export function ConfigStoreModal({ } }, []); + // Each open of the modal is a session. Closing or unmounting ends it and + // aborts a pending Load, and an operation applies its result only while its + // session is current, so a dismissed Load can't replace the workspace after + // the dialog is gone. + const sessionRef = useRef(0); + const loadAbortRef = useRef(null); + const endSession = useCallback(() => { + sessionRef.current++; + loadAbortRef.current?.abort(); + loadAbortRef.current = null; + }, []); + useEffect(() => endSession, [endSession]); + // Reset the form and reload the list once per open. const initialized = useRef(false); useEffect(() => { if (!open) { initialized.current = false; + endSession(); return; } if (initialized.current) return; initialized.current = true; setName(''); setDescription(''); + // A dismissed Load holds the slot until its request settles, which the + // abort doesn't guarantee. Save, Rename and Delete keep it: they block + // dismissal, so one only gets here through a close the parent made itself, + // and it is still running. + if (busyRef.current?.kind === 'load') setBusy(null); setError(null); void refresh(); - }, [open, refresh]); + }, [open, refresh, endSession, setBusy]); // Carbon's X, Escape and backdrop all call this; returning false keeps the // dialog open. Save, Rename and Delete block dismissal until they settle: the // server change happens either way, so closing would only hide its outcome. + // A Load doesn't block; closing cancels it. // This must read refs, not render state. Carbon registers its Escape listener // once per open and keeps the onClose from that render, when nothing was busy. const onCloseRef = useRef(onClose); @@ -160,24 +180,30 @@ export function ConfigStoreModal({ const requestClose = useCallback(() => { const op = busyRef.current; if (op && op.kind !== 'load') return false; + // The `!open` effect ends the session as well, but only once React has + // committed the close; ending it here leaves no gap for a response. + endSession(); onCloseRef.current(); - }, []); + }, [endSession]); - // Claim the slot for `op`; false if another operation holds it. - const begin = (op: BusyOp): boolean => { - if (busyRef.current) return false; + // Claim the slot for `op`. Returns the session it runs in, or null if another + // operation holds the slot. + const begin = (op: BusyOp): number | null => { + if (busyRef.current) return null; setBusy(op); setError(null); - return true; + return sessionRef.current; }; - // Release the slot only if `op` still holds it. + // Release the slot only if `op` still holds it: a reopen may have taken a + // dismissed Load's slot and given it to a newer operation. const end = (op: BusyOp) => { if (busyRef.current === op) setBusy(null); }; const handleSave = async () => { const op: BusyOp = { kind: 'save' }; - if (!begin(op)) return; + const session = begin(op); + if (session === null) return; try { const data = serializeConfigData({ theme, plots }); const dto = await saveConfig(data, { @@ -194,11 +220,14 @@ export function ConfigStoreModal({ title: 'Workspace saved', subtitle: copied ? `Share link copied to clipboard (${dto.slug})` : `Share link: ${link}`, }); + // The toast goes out regardless: the config exists and its link is + // useful. The form and the list belong to the session. + if (session !== sessionRef.current) return; setName(''); setDescription(''); await refresh(); } catch (err) { - setError(errText(err)); + if (session === sessionRef.current) setError(errText(err)); } finally { end(op); } @@ -206,9 +235,14 @@ export function ConfigStoreModal({ const handleLoad = async (config: ConfigDTO) => { const op: BusyOp = { kind: 'load', slug: config.slug, label: config.name || config.slug }; - if (!begin(op)) return; + const session = begin(op); + if (session === null) return; + const abort = new AbortController(); + loadAbortRef.current = abort; try { - const dto = await getConfig(config.slug); + const dto = await getConfig(config.slug, abort.signal); + // Closing aborts the request, but the response may have arrived first. + if (session !== sessionRef.current) return; const result = deserializeConfigData(dto.data); onLoaded(result); onToast({ @@ -218,8 +252,10 @@ export function ConfigStoreModal({ }); onClose(); } catch (err) { - setError(errText(err)); + // A stale session also covers the AbortError from closing. + if (session === sessionRef.current) setError(errText(err)); } finally { + if (loadAbortRef.current === abort) loadAbortRef.current = null; end(op); } }; @@ -233,12 +269,14 @@ export function ConfigStoreModal({ const trimmed = next.trim(); if (trimmed === '' || trimmed === (config.name ?? '')) return; const op: BusyOp = { kind: 'rename', slug: config.slug, label: config.name || config.slug }; - if (!begin(op)) return; + const session = begin(op); + if (session === null) return; try { await updateConfig(config.slug, { name: trimmed }); + if (session !== sessionRef.current) return; await refresh(); } catch (err) { - setError(errText(err)); + if (session === sessionRef.current) setError(errText(err)); } finally { end(op); } @@ -248,12 +286,14 @@ export function ConfigStoreModal({ if (busyRef.current) return; if (!window.confirm(`Delete "${config.name || config.slug}"? This cannot be undone.`)) return; const op: BusyOp = { kind: 'delete', slug: config.slug, label: config.name || config.slug }; - if (!begin(op)) return; + const session = begin(op); + if (session === null) return; try { await deleteConfig(config.slug); + if (session !== sessionRef.current) return; await refresh(); } catch (err) { - setError(errText(err)); + if (session === sessionRef.current) setError(errText(err)); } finally { end(op); } From b296a9ec3dba33cee60da99790ab8fb68c61f8ae Mon Sep 17 00:00:00 2001 From: YektaY Date: Sun, 18 Oct 2026 08:11:27 -0700 Subject: [PATCH 3/6] Stop blocking config-store dismissal during the post-mutation refresh Save, Rename and Delete held the busy slot through the list refresh that follows them, so a hung listConfigs left the dialog impossible to close. Before this branch Rename and Delete never blocked closing, so that would have been a regression. The refresh is only a read, so the slot is now released as soon as the server call settles, and only the mutation itself blocks dismissal. Also from review: - A successful Load ends its session before calling onClose, as requestClose does, so every close path ends the session first. - Test two Load clicks that land before React re-renders. Only the slot's ref can turn the second one away, because its button is still enabled. - Rename a test whose name overstated what it checks. - Share one label helper between the status line and the delete prompt. Refs #92 --- src/components/ConfigStoreModal.test.tsx | 33 +++++++++++++++++++----- src/components/ConfigStoreModal.tsx | 30 +++++++++++++++------ 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx index cfade01..cdcbbd5 100644 --- a/src/components/ConfigStoreModal.test.tsx +++ b/src/components/ConfigStoreModal.test.tsx @@ -240,6 +240,17 @@ describe('ConfigStoreModal: one operation at a time', () => { expect(onToast).toHaveBeenCalledTimes(1); }); + it('starts only one Load when both clicks land before React re-renders', async () => { + await mount(); + // Inside one act() the second button is still enabled in the DOM, so only + // the slot's ref can turn the click away. + act(() => { + rowButton('Config A', 'Load').click(); + rowButton('Config B', 'Load').click(); + }); + expect(api.getConfig.mock.calls.map(([slug]) => slug)).toEqual([A.slug]); + }); + it('disables every row action and Save while a Load is in flight', async () => { await mount(); fireEvent.click(rowButton('Config A', 'Load')); @@ -273,7 +284,9 @@ describe('ConfigStoreModal: one operation at a time', () => { expect(api.getConfig).not.toHaveBeenCalled(); }); - it("keeps A's Load disabled when a Rename clicked during it would have finished", async () => { + // Before the fix the Rename ran, and its `finally` re-enabled A's Load while + // the Load was still in flight. Now the Rename never starts. + it("keeps A's Load disabled after a Rename click during it", async () => { await mount(); fireEvent.click(rowButton('Config A', 'Load')); fireEvent.click(rowButton('Config B', 'Rename')); @@ -378,7 +391,7 @@ describe('ConfigStoreModal: dismissing cancels a Load', () => { describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { it.each(PATHS)( - 'blocks %s during a Save, then closes on it once the Save settles', + 'blocks %s during a Save until its server call settles, then closes on it', async (path) => { await mount(); fireEvent.click(saveButton()); @@ -386,11 +399,16 @@ describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { expect(isVisible()).toBe(true); expect(parentClose).not.toHaveBeenCalled(); + // Hold the list refresh that follows: only the server call blocks closing. + const list = deferred>(); + api.listConfigs.mockReturnValueOnce(list.promise); await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); + expect(api.listConfigs).toHaveBeenCalledTimes(2); expect(saveButton().disabled).toBe(false); dismiss(path); expect(isVisible()).toBe(false); expect(parentClose).toHaveBeenCalledTimes(1); + await settle(() => list.resolve(PAGE)); await reopen(); expect(isVisible()).toBe(true); } @@ -406,7 +424,7 @@ describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { }); it.each(PATHS.flatMap((path) => (['Rename', 'Delete'] as const).map((a) => [a, path] as const)))( - 'blocks dismissal during a %s (%s), then refreshes the list and closes', + 'blocks dismissal during a %s (%s) until its server call settles, not the list refresh after it', async (action, path) => { await mount(); fireEvent.click(rowButton('Config B', action)); @@ -414,13 +432,16 @@ describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { expect(isVisible()).toBe(true); expect(parentClose).not.toHaveBeenCalled(); - const listCalls = api.listConfigs.mock.calls.length; + // Hold the list refresh that follows: only the server call blocks closing. + const list = deferred>(); + api.listConfigs.mockReturnValueOnce(list.promise); await settle(() => (action === 'Rename' ? renames[0].resolve(B) : deletes[0].resolve())); - expect(api.listConfigs).toHaveBeenCalledTimes(listCalls + 1); - expect(rowButton('Config A', 'Load').disabled).toBe(false); + expect(api.listConfigs).toHaveBeenCalledTimes(2); + expect(screen.queryByText(/^(Renaming|Deleting) /)).toBeNull(); dismiss(path); expect(isVisible()).toBe(false); expect(parentClose).toHaveBeenCalledTimes(1); + await settle(() => list.resolve(PAGE)); } ); diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index 232c00c..9efcaf2 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -60,6 +60,11 @@ function shareUrl(slug: string): string { return url.toString(); } +// How a config is named in the status line and the delete prompt. +function configLabel(config: ConfigDTO): string { + return config.name || config.slug; +} + function errText(err: unknown): string { if (err instanceof CanopyError) return err.detail; return (err as Error | null)?.message ?? 'Unknown error'; @@ -136,7 +141,9 @@ export function ConfigStoreModal({ // Each open of the modal is a session. Closing or unmounting ends it and // aborts a pending Load, and an operation applies its result only while its // session is current, so a dismissed Load can't replace the workspace after - // the dialog is gone. + // the dialog is gone. Save, Rename and Delete block dismissal, so their + // session ends early only if the parent closes the modal itself or unmounts + // it. Their outcome is then dropped, apart from Save's toast. const sessionRef = useRef(0); const loadAbortRef = useRef(null); const endSession = useCallback(() => { @@ -168,9 +175,9 @@ export function ConfigStoreModal({ }, [open, refresh, endSession, setBusy]); // Carbon's X, Escape and backdrop all call this; returning false keeps the - // dialog open. Save, Rename and Delete block dismissal until they settle: the - // server change happens either way, so closing would only hide its outcome. - // A Load doesn't block; closing cancels it. + // dialog open. Save, Rename and Delete block dismissal until their server + // call settles: the change happens either way, so closing would only hide + // its outcome. A Load doesn't block; closing cancels it. // This must read refs, not render state. Carbon registers its Escape listener // once per open and keeps the onClose from that render, when nothing was busy. const onCloseRef = useRef(onClose); @@ -225,6 +232,9 @@ export function ConfigStoreModal({ if (session !== sessionRef.current) return; setName(''); setDescription(''); + // The server call has settled. The refresh is only a read, so it doesn't + // hold the slot or block closing. + end(op); await refresh(); } catch (err) { if (session === sessionRef.current) setError(errText(err)); @@ -234,7 +244,7 @@ export function ConfigStoreModal({ }; const handleLoad = async (config: ConfigDTO) => { - const op: BusyOp = { kind: 'load', slug: config.slug, label: config.name || config.slug }; + const op: BusyOp = { kind: 'load', slug: config.slug, label: configLabel(config) }; const session = begin(op); if (session === null) return; const abort = new AbortController(); @@ -250,6 +260,8 @@ export function ConfigStoreModal({ title: 'Workspace loaded', subtitle: dto.name ? `Loaded "${dto.name}"` : `Loaded config ${config.slug}`, }); + // Like requestClose, end the session before the parent sees the close. + endSession(); onClose(); } catch (err) { // A stale session also covers the AbortError from closing. @@ -268,12 +280,13 @@ export function ConfigStoreModal({ // No-op a blank rename (Save likewise omits empty names) or an unchanged one. const trimmed = next.trim(); if (trimmed === '' || trimmed === (config.name ?? '')) return; - const op: BusyOp = { kind: 'rename', slug: config.slug, label: config.name || config.slug }; + const op: BusyOp = { kind: 'rename', slug: config.slug, label: configLabel(config) }; const session = begin(op); if (session === null) return; try { await updateConfig(config.slug, { name: trimmed }); if (session !== sessionRef.current) return; + end(op); await refresh(); } catch (err) { if (session === sessionRef.current) setError(errText(err)); @@ -284,13 +297,14 @@ export function ConfigStoreModal({ const handleDelete = async (config: ConfigDTO) => { if (busyRef.current) return; - if (!window.confirm(`Delete "${config.name || config.slug}"? This cannot be undone.`)) return; - const op: BusyOp = { kind: 'delete', slug: config.slug, label: config.name || config.slug }; + if (!window.confirm(`Delete "${configLabel(config)}"? This cannot be undone.`)) return; + const op: BusyOp = { kind: 'delete', slug: config.slug, label: configLabel(config) }; const session = begin(op); if (session === null) return; try { await deleteConfig(config.slug); if (session !== sessionRef.current) return; + end(op); await refresh(); } catch (err) { if (session === sessionRef.current) setError(errText(err)); From f480fd898aea9c7c44fa40b385a4b8d45ea1028c Mon Sep 17 00:00:00 2001 From: YektaY Date: Mon, 26 Oct 2026 22:36:12 -0700 Subject: [PATCH 4/6] Stop holding the config-store Save slot during the share-link copy Save kept the busy slot until the clipboard write settled, so a pending clipboard permission prompt left every action disabled and X, Escape and the backdrop blocked after the workspace was already saved. Free the slot, clear the form and start the refresh as soon as saveConfig resolves; the copy and the toast follow, and the toast still goes out if the dialog has closed in the meantime. Refs #92 --- src/components/ConfigStoreModal.test.tsx | 69 +++++++++++++++++++++++- src/components/ConfigStoreModal.tsx | 28 +++++----- 2 files changed, 83 insertions(+), 14 deletions(-) diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx index cdcbbd5..338b2a0 100644 --- a/src/components/ConfigStoreModal.test.tsx +++ b/src/components/ConfigStoreModal.test.tsx @@ -3,8 +3,8 @@ // Pins ConfigStoreModal's async lifecycle (slaclab/react-trace#92). Save and // every row's Load/Rename/Delete share one busy slot, so only one runs at a // time. Save, Rename and Delete block all three of Carbon's dismissal paths (X, -// Escape, backdrop) until they settle. A Load doesn't: dismissing aborts it and -// drops its result, even a response that beat the abort. +// Escape, backdrop) until their server call settles. A Load doesn't: dismissing +// aborts it and drops its result, even a response that beat the abort. // // Every magpie call returns a promise the test settles by hand, so each case // controls exactly when a response lands relative to clicks and dismissals. @@ -169,6 +169,15 @@ function dismiss(path: DismissPath) { } } +// jsdom has no clipboard API, so a Save's share-link copy normally fails at +// once. Cases that need a pending or rejected copy install one; afterEach +// removes it. +function stubClipboard(writeText: (text: string) => Promise) { + const clipboard = { writeText: vi.fn(writeText) }; + Object.defineProperty(navigator, 'clipboard', { value: clipboard, configurable: true }); + return clipboard; +} + beforeAll(() => { // Carbon's icon-button tooltips observe their size; jsdom has no ResizeObserver. vi.stubGlobal( @@ -218,6 +227,7 @@ beforeEach(() => { afterEach(() => { // No vitest globals, so RTL can't register its own cleanup. cleanup(); + Reflect.deleteProperty(navigator, 'clipboard'); vi.restoreAllMocks(); vi.clearAllMocks(); }); @@ -466,3 +476,58 @@ describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { expect(errorBanner()).toBeNull(); }); }); + +describe('ConfigStoreModal: the share-link copy does not hold the Save slot', () => { + const NEW = config('slug-new', 'New', '2026-10-03T00:00:00Z'); + + it.each(PATHS)( + 'frees every action and allows %s once the Save lands, while the copy is pending', + async (path) => { + const copy = deferred(); + const clipboard = stubClipboard(() => copy.promise); + await mount(); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Mine' } }); + fireEvent.click(saveButton()); + await settle(() => saves[0].resolve(NEW)); + expect(clipboard.writeText).toHaveBeenCalledWith(expect.stringMatching(/config=slug-new$/)); + expect(saveButton().disabled).toBe(false); + expect(allRowButtons().map((b) => b.disabled)).toEqual(Array(6).fill(false)); + expect((screen.getByLabelText('Name') as HTMLInputElement).value).toBe(''); + expect(api.listConfigs).toHaveBeenCalledTimes(2); + expect(onToast).not.toHaveBeenCalled(); + + dismiss(path); + expect(isVisible()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); + + // The toast still reports the copy after the dialog has gone. + await settle(() => copy.resolve()); + expect(onToast).toHaveBeenCalledWith({ + kind: 'success', + title: 'Workspace saved', + subtitle: 'Share link copied to clipboard (slug-new)', + }); + } + ); + + it('lets another operation start while the copy is pending', async () => { + stubClipboard(() => new Promise(() => {})); + await mount(); + fireEvent.click(saveButton()); + await settle(() => saves[0].resolve(NEW)); + fireEvent.click(rowButton('Config A', 'Load')); + expect(api.getConfig.mock.calls.map(([slug]) => slug)).toEqual([A.slug]); + }); + + it('shows the link itself when the copy is rejected', async () => { + stubClipboard(() => Promise.reject(new DOMException('Denied', 'NotAllowedError'))); + await mount(); + fireEvent.click(saveButton()); + await settle(() => saves[0].resolve(NEW)); + expect(onToast).toHaveBeenCalledWith({ + kind: 'success', + title: 'Workspace saved', + subtitle: expect.stringMatching(/^Share link: .*\?config=slug-new$/), + }); + }); +}); diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index 9efcaf2..4ee90b4 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -141,9 +141,10 @@ export function ConfigStoreModal({ // Each open of the modal is a session. Closing or unmounting ends it and // aborts a pending Load, and an operation applies its result only while its // session is current, so a dismissed Load can't replace the workspace after - // the dialog is gone. Save, Rename and Delete block dismissal, so their - // session ends early only if the parent closes the modal itself or unmounts - // it. Their outcome is then dropped, apart from Save's toast. + // the dialog is gone. Save, Rename and Delete block dismissal until their + // server call settles, so their session ends before that only if the parent + // closes the modal itself or unmounts it. Their outcome is then dropped, apart + // from Save's toast, which also outlives a close during the share-link copy. const sessionRef = useRef(0); const loadAbortRef = useRef(null); const endSession = useCallback(() => { @@ -217,25 +218,28 @@ export function ConfigStoreModal({ name: name.trim() || undefined, description: description.trim() || undefined, }); + // The server call has settled. Neither the refresh nor the clipboard write + // is part of the save, so neither holds the slot or blocks closing: a + // pending clipboard permission prompt would otherwise lock the dialog. + end(op); + // The form and the list belong to the session. + if (session === sessionRef.current) { + setName(''); + setDescription(''); + void refresh(); + } // Don't claim a copy that didn't happen: the clipboard API is absent on a // non-secure origin and rejects when permission is denied or the document // isn't focused. Show the link itself so it can still be copied by hand. const link = shareUrl(dto.slug); const copied = await copyToClipboard(link); + // The toast goes out regardless, even if the dialog has closed since: the + // config exists and its link is useful. onToast({ kind: 'success', title: 'Workspace saved', subtitle: copied ? `Share link copied to clipboard (${dto.slug})` : `Share link: ${link}`, }); - // The toast goes out regardless: the config exists and its link is - // useful. The form and the list belong to the session. - if (session !== sessionRef.current) return; - setName(''); - setDescription(''); - // The server call has settled. The refresh is only a read, so it doesn't - // hold the slot or block closing. - end(op); - await refresh(); } catch (err) { if (session === sessionRef.current) setError(errText(err)); } finally { From 5f405330fd8792d61fe4b4dd7506e34ee0c5b68b Mon Sep 17 00:00:00 2001 From: YektaY Date: Wed, 11 Nov 2026 18:31:51 -0800 Subject: [PATCH 5/6] Clear a failed Delete's error on cancel; find modals by role Cancelling the delete confirmation (X, Escape or Cancel) after a failed Delete left the error set, so the store's banner showed it for a Delete that had been cancelled. requestCancelDelete now clears it. Name both dialogs with aria-label. Carbon names a ComposedModal from its aria-label or ModalHeader's label, not the title, so both were unnamed. The tests now find the dialogs, rows and the confirmation's Delete by role and name, and tell open from closed by aria-hidden, instead of reading Carbon's class names. Escape-driven steps keep the onClose guards covered: Carbon only sends Escape to a modal it still shows. --- src/components/ConfigStoreModal.test.tsx | 79 ++++++++++++++++++------ src/components/ConfigStoreModal.tsx | 14 ++++- 2 files changed, 70 insertions(+), 23 deletions(-) diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx index c98128c..a36a350 100644 --- a/src/components/ConfigStoreModal.test.tsx +++ b/src/components/ConfigStoreModal.test.tsx @@ -128,30 +128,33 @@ async function reopen() { await settle(); } +// Each ComposedModal renders a dialog named by its aria-label. Carbon marks a +// closed one aria-hidden, which only a `hidden` query finds. +function dialog(name: string, hidden: boolean): HTMLElement | null { + return screen.queryByRole('dialog', { name, hidden }); +} + // The config store, or null once TraceApp has unmounted it. function storeModal(): HTMLElement | null { - return document.querySelector('.cds--modal:not(.cds--modal--danger)'); + return dialog('Config store', true); } // The delete confirmation. It stays mounted, hidden, while the store is. function confirmModal(): HTMLElement | null { - return document.querySelector('.cds--modal--danger'); -} - -function shown(modal: HTMLElement | null): boolean { - return modal?.classList.contains('is-visible') ?? false; + return dialog('Delete config?', true); } -const storeOpen = () => shown(storeModal()); -const confirmOpen = () => shown(confirmModal()); +const storeOpen = () => dialog('Config store', false) !== null; +const confirmOpen = () => dialog('Delete config?', false) !== null; type RowAction = 'Load' | 'Rename' | 'Delete'; const ROW_ACTIONS: RowAction[] = ['Load', 'Rename', 'Delete']; -// `hidden: true` throughout: Carbon hides what's under a modal from the -// accessibility tree, including the store under the delete confirmation. +// `hidden: true` throughout: these also reach the store while the delete +// confirmation is open over it, which a browser hides from assistive tech +// (the confirmation is aria-modal). Testing Library's check ignores aria-modal. function rowButton(name: string, action: RowAction): HTMLButtonElement { - const row = screen.getByText(name).closest('.cds--structured-list-row') as HTMLElement; + const row = screen.getByText(name).closest('[role="row"]') as HTMLElement; return within(row).getByRole('button', { name: action, hidden: true }) as HTMLButtonElement; } @@ -167,9 +170,12 @@ function allRowButtons(): HTMLButtonElement[] { } // The confirmation's own Delete button, which starts the delete. Its -// accessible name starts with the danger description, so find it by class. +// accessible name starts with the danger description, so match the end. function confirmDeleteButton(): HTMLButtonElement { - return confirmModal()!.querySelector('.cds--modal-footer .cds--btn--danger')!; + return within(confirmModal()!).getByRole('button', { + name: /(Delete|Deleting…)$/, + hidden: true, + }) as HTMLButtonElement; } // A row's Delete, then the confirmation's. @@ -197,10 +203,13 @@ function dismiss(path: DismissPath) { case 'Escape': fireEvent.keyDown(document, { key: 'Escape', keyCode: 27 }); break; - case 'backdrop': - fireEvent.mouseDown(store); - fireEvent.click(store); + case 'backdrop': { + // The dialog's presentation wrapper is the overlay around it. + const backdrop = store.closest('[role="presentation"]')!; + fireEvent.mouseDown(backdrop); + fireEvent.click(backdrop); break; + } } } @@ -559,6 +568,14 @@ describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { expect(storeOpen()).toBe(true); expect(confirmOpen()).toBe(true); expect(parentClose).not.toHaveBeenCalled(); + + // Carbon hides a modal whose onClose doesn't return false, even while + // `open` stays true, and then sends Escape past it. So Escape closing + // the store shows both refusals left it open. + await settle(() => deletes[0].resolve()); + dismiss('Escape'); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); } ); @@ -576,14 +593,36 @@ describe('ConfigStoreModal: Save, Rename and Delete block dismissal', () => { expect(within(confirmModal()!).queryByText('not allowed')).toBeNull(); }); + it.each(CONFIRM_PATHS)( + "drops a failed Delete's error from the store when %s closes the confirmation", + async (path) => { + await mount(); + startDelete('Config B'); + // Refused while the Delete runs. It must leave Carbon's own state open + // too: for Escape, the second press below would otherwise go to the store. + dismissConfirm(path); + await settle(() => deletes[0].reject(new CanopyError('forbidden', 403, 'not allowed'))); + expect(within(confirmModal()!).queryByText('not allowed')).not.toBeNull(); + + dismissConfirm(path); + expect(confirmOpen()).toBe(false); + expect(storeOpen()).toBe(true); + expect(parentClose).not.toHaveBeenCalled(); + expect(within(storeModal()!).queryByText('not allowed')).toBeNull(); + } + ); + + // Escape closing the store shows the refused X left Carbon's own state open + // (see the case above that refuses X under the delete confirmation). it('can still be used after X was pressed during a Save', async () => { await mount(); fireEvent.click(saveButton()); dismiss('X'); await settle(() => saves[0].resolve(config('slug-new', 'New', '2026-10-03T00:00:00Z'))); - await reopen(); - expect(storeOpen()).toBe(true); expect(saveButton().disabled).toBe(false); + dismiss('Escape'); + expect(storeOpen()).toBe(false); + expect(parentClose).toHaveBeenCalledTimes(1); }); it('still toasts a Save that outlives the modal, and touches nothing else', async () => { @@ -602,7 +641,7 @@ describe('ConfigStoreModal: the delete confirmation', () => { await mount(); fireEvent.click(rowButton('Config B', 'Delete')); - expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(2); + expect(screen.getAllByRole('dialog')).toHaveLength(2); expect(screen.getByText('Save current workspace')).toBeTruthy(); expect( within(confirmModal()!).getByText( @@ -613,7 +652,7 @@ describe('ConfigStoreModal: the delete confirmation', () => { expect(api.deleteConfig).not.toHaveBeenCalled(); dismissConfirm('Cancel'); - expect(document.querySelectorAll('.cds--modal.is-visible')).toHaveLength(1); + expect(screen.getAllByRole('dialog')).toHaveLength(1); expect(screen.getByText('Config B')).toBeTruthy(); expect(api.deleteConfig).not.toHaveBeenCalled(); }); diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index b3bbdb4..acb1840 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -203,9 +203,11 @@ export function ConfigStoreModal({ // The delete confirmation's X, Escape and Cancel. It stays open while the // Delete's server call runs, so a failure can show in it. Reads the slot's - // ref for the same reason as requestClose. + // ref for the same reason as requestClose. Closing it drops that failure too, + // or the store's banner would show it for a Delete that was cancelled. const requestCancelDelete = useCallback(() => { if (busyRef.current?.kind === 'delete') return false; + setError(null); setDeleteTarget(null); }, [setDeleteTarget]); @@ -360,7 +362,7 @@ export function ConfigStoreModal({ return ( <> - +
@@ -500,7 +502,13 @@ export function ConfigStoreModal({ - + {error && ( From 27ef3864420851dd4c28852df32b3290e7f02fc8 Mon Sep 17 00:00:00 2001 From: YektaY Date: Tue, 17 Nov 2026 16:30:24 -0800 Subject: [PATCH 6/6] Start nothing else while the delete confirmation is open begin() checked only the busy slot, which a Delete takes only once it's confirmed. While the confirmation was open, a Load, Rename or Save from the store behind it could claim the slot. The confirmation's Delete then did nothing, a failed Rename showed under "Could not delete config", and a Load that succeeded closed the store, confirmation and all. begin() now turns away everything but the confirmation's own Delete while it is open. Rename checks this before its prompt, and a row's Delete can't switch the confirmation to another config. A Load's success closes through requestClose, like X, Escape and the backdrop. --- src/components/ConfigStoreModal.test.tsx | 56 ++++++++++++++++++++++++ src/components/ConfigStoreModal.tsx | 25 +++++++---- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/src/components/ConfigStoreModal.test.tsx b/src/components/ConfigStoreModal.test.tsx index df42ef7..a1de64e 100644 --- a/src/components/ConfigStoreModal.test.tsx +++ b/src/components/ConfigStoreModal.test.tsx @@ -692,6 +692,62 @@ describe('ConfigStoreModal: the delete confirmation', () => { }); }); +// In a browser the confirmation's overlay covers the store, but the store's +// buttons stay enabled in the DOM, so these click them directly. +describe('ConfigStoreModal: nothing else starts while the delete confirmation is open', () => { + async function confirmDeleteOfB() { + await mount(); + fireEvent.click(rowButton('Config B', 'Delete')); + expect(confirmOpen()).toBe(true); + } + + // The confirmation is still about B, and its own Delete still deletes B. + async function expectConfirmationStillDeletesB() { + expect(confirmOpen()).toBe(true); + expect(within(confirmModal()!).getByText('Config B')).toBeTruthy(); + expect(confirmDeleteButton().disabled).toBe(false); + fireEvent.click(confirmDeleteButton()); + expect(api.deleteConfig.mock.calls).toEqual([[B.slug]]); + await settle(() => deletes[0].resolve()); + expect(confirmOpen()).toBe(false); + expect(parentClose).not.toHaveBeenCalled(); + } + + it("does not start another row's Load, so the store stays open", async () => { + await confirmDeleteOfB(); + fireEvent.click(rowButton('Config A', 'Load')); + await settle(); + expect(api.getConfig).not.toHaveBeenCalled(); + expect(onLoaded).not.toHaveBeenCalled(); + expect(parentClose).not.toHaveBeenCalled(); + await expectConfirmationStillDeletesB(); + }); + + it("does not prompt for or start another row's Rename", async () => { + await confirmDeleteOfB(); + fireEvent.click(rowButton('Config A', 'Rename')); + await settle(); + expect(window.prompt).not.toHaveBeenCalled(); + expect(api.updateConfig).not.toHaveBeenCalled(); + await expectConfirmationStillDeletesB(); + }); + + it('does not start a Save', async () => { + await confirmDeleteOfB(); + fireEvent.click(saveButton()); + await settle(); + expect(api.saveConfig).not.toHaveBeenCalled(); + await expectConfirmationStillDeletesB(); + }); + + it("does not switch the confirmation to another row's Delete", async () => { + await confirmDeleteOfB(); + fireEvent.click(rowButton('Config A', 'Delete')); + await settle(); + await expectConfirmationStillDeletesB(); + }); +}); + describe('ConfigStoreModal: focus around the delete confirmation', () => { // The store's scrolling body, which Carbon makes focusable. Carbon up to 1.108 // names it by its aria-label ("Config store contents"), later versions by the diff --git a/src/components/ConfigStoreModal.tsx b/src/components/ConfigStoreModal.tsx index 1740a49..589b04a 100644 --- a/src/components/ConfigStoreModal.tsx +++ b/src/components/ConfigStoreModal.tsx @@ -220,10 +220,15 @@ export function ConfigStoreModal({ setDeleteTarget(null); }, [setDeleteTarget]); - // Claim the slot for `op`. Returns the session it runs in, or null if another - // operation holds the slot. + // Claim the slot for `op`. Returns the session it runs in, or null if `op` + // can't start now. const begin = (op: BusyOp): number | null => { if (busyRef.current) return null; + // While the delete confirmation is open, only its own Delete can start. The + // store's buttons behind it stay enabled, and an operation started there + // would show its error under the confirmation's "Could not delete config", + // and a Load would close the store, confirmation and all, on success. + if (deleteTargetRef.current && op.kind !== 'delete') return null; setBusy(op); setError(null); return sessionRef.current; @@ -315,9 +320,10 @@ export function ConfigStoreModal({ ].join('\n'), timeout: result.warnings.length > 0 ? 0 : undefined, }); - // Like requestClose, end the session before the parent sees the close. - endSession(); - onClose(); + // Close the way X, Escape and the backdrop do. requestClose can't refuse + // here: this Load holds the slot, and begin() turns a Load away while the + // delete confirmation is open. + requestClose(); } catch (err) { // A stale session also covers the AbortError from closing. if (session === sessionRef.current) setError(errText(err)); @@ -328,8 +334,8 @@ export function ConfigStoreModal({ }; const handleRename = async (config: ConfigDTO) => { - // Don't prompt for an action that can't start. - if (busyRef.current) return; + // Don't prompt for an action that can't start (see begin). + if (busyRef.current || deleteTargetRef.current) return; const next = window.prompt('Rename config', config.name ?? ''); if (next === null) return; // No-op a blank rename (Save likewise omits empty names) or an unchanged one. @@ -352,8 +358,9 @@ export function ConfigStoreModal({ // A row's Delete opens the confirmation; only its Delete button deletes. const askDelete = (config: ConfigDTO, trigger: HTMLButtonElement) => { - // Don't ask about an action that can't start. - if (busyRef.current) return; + // Don't ask about an action that can't start, or switch an open + // confirmation to another config. + if (busyRef.current || deleteTargetRef.current) return; deleteTriggerRef.current = trigger; setError(null); setDeleteTarget(config);