From ec3dfa6437be1ab823b0c16e88aaa82943a96c19 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 12:05:56 +0800 Subject: [PATCH 1/3] fix(agents): keep user questions in the Claw coordinator --- .../core/src/agentic/agents/definitions/modes/claw.rs | 2 ++ .../src/agentic/agents/definitions/subagents/computer_use.rs | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs index 9f7cf7ea50..796338e8f7 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs @@ -16,6 +16,7 @@ impl ClawMode { pub fn new() -> Self { Self { default_tools: vec![ + "AskUserQuestion".to_string(), "AgentSpawn".to_string(), "AgentSendInput".to_string(), "AgentControl".to_string(), @@ -118,6 +119,7 @@ mod tests { assert!(tools.contains(&"ListModels".to_string())); assert!(tools.contains(&"ListWorkspaces".to_string())); assert!(tools.contains(&"DesktopCard".to_string())); + assert!(tools.contains(&"AskUserQuestion".to_string())); } #[test] diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/subagents/computer_use.rs b/src/crates/assembly/core/src/agentic/agents/definitions/subagents/computer_use.rs index 45bad5cc34..e899c27323 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/subagents/computer_use.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/subagents/computer_use.rs @@ -19,7 +19,6 @@ impl ComputerUseMode { pub fn new() -> Self { Self { default_tools: vec![ - "AskUserQuestion".to_string(), "TodoWrite".to_string(), "Skill".to_string(), "view_image".to_string(), @@ -84,6 +83,9 @@ mod tests { assert!(agent.default_tools().contains(&"ControlHub".to_string())); assert!(agent.default_tools().contains(&"ComputerUse".to_string())); assert!(!agent.default_tools().contains(&"Write".to_string())); + assert!(!agent + .default_tools() + .contains(&"AskUserQuestion".to_string())); assert!(!agent.is_readonly()); assert!(agent .description() From 959e4189f009a2c7260657a3d51be6e6064a3832 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 12:06:15 +0800 Subject: [PATCH 2/3] fix(ui): keep confirmations beside their triggering actions --- design-system/packages/ui/README.md | 14 ++ .../ConfirmDialog/ConfirmDialog.meta.ts | 1 + .../ConfirmDialog/ConfirmDialog.tsx | 19 ++- .../ui/src/components/ConfirmDialog/index.ts | 1 + .../src/components/Dialog/Dialog.module.css | 21 +++ .../ui/src/components/Dialog/Dialog.tsx | 34 +++-- .../ui/src/components/Menu/Menu.module.css | 12 ++ .../src/components/Menu/MenuConfirmItem.tsx | 75 +++++++++ .../ui/src/components/Menu/MenuPopover.tsx | 24 ++- .../packages/ui/src/components/Menu/index.ts | 1 + design-system/packages/ui/src/index.ts | 5 + .../ui/src/internal/confirmationAnchor.ts | 31 ++++ .../ui/src/internal/useAnchoredLayer.ts | 10 +- .../packages/ui/src/overlay/useFocusScope.ts | 7 +- .../packages/ui/tests/dialog.test.mjs | 2 +- .../packages/ui/tests/overlay-kernel.test.mjs | 2 +- src/web-ui/AGENTS.md | 10 ++ .../DesktopCard/DesktopCardWindow.scss | 16 -- .../DesktopCard/DesktopCardWindow.test.tsx | 30 +++- .../DesktopCard/DesktopCardWindow.tsx | 27 +--- .../NavPanel/components/MiniAppShortcuts.tsx | 5 +- .../devices/CatalogSessionMenu.test.tsx | 15 +- .../sections/devices/CatalogSessionMenu.tsx | 12 ++ .../sections/devices/openOnDevice.test.ts | 15 +- .../NavPanel/sections/devices/openOnDevice.ts | 7 +- .../ArchivedSessionMenuItems.test.tsx | 15 +- .../sessions/ArchivedSessionMenuItems.tsx | 24 +-- .../sessions/SessionDeleteMenuItem.scss | 15 ++ .../sessions/SessionDeleteMenuItem.test.tsx | 142 ++++++++++++++++++ .../sessions/SessionDeleteMenuItem.tsx | 130 ++++++++++++++++ .../sections/sessions/SessionsSection.tsx | 10 +- .../NavPanel/sections/sessions/appearance.ts | 1 + .../sessionActionConfirmation.test.ts | 9 +- .../sections/sessions/sessionRowActions.ts | 10 ++ .../WorkspaceProjectPermissionsDialog.tsx | 8 +- .../RemoteConnectDialog/AccountPanel.tsx | 7 +- .../scheduled-jobs/ScheduledJobsView.tsx | 9 +- .../src/app/scenes/agents/AgentsScene.tsx | 7 +- .../agents/components/ToolGroupPicker.tsx | 8 +- .../src/app/scenes/miniapps/MiniAppScene.tsx | 7 +- .../components/MiniAppDetailModal.tsx | 12 +- .../components/MiniAppInstalledCard.tsx | 6 +- .../components/MiniAppLaunchActions.tsx | 8 +- .../miniapps/hooks/useMiniAppLaunch.test.tsx | 20 +++ .../scenes/miniapps/hooks/useMiniAppLaunch.ts | 6 +- .../miniapps/views/MiniAppGalleryView.tsx | 7 +- .../MiniAppLibraryView.navigation.test.tsx | 9 +- .../miniapps/views/MiniAppLibraryView.tsx | 22 +-- .../src/app/scenes/pages/PagesScene.tsx | 13 +- .../OverviewDesktopCardsSection.tsx | 8 +- .../PersonalOverviewScene.actions.test.tsx | 40 ++--- .../PersonalOverviewScene.tsx | 9 -- .../views/NurseryGallery.actions.test.tsx | 49 ++---- .../scenes/profile/views/NurseryGallery.tsx | 10 +- .../ProjectDirectoriesSection.test.tsx | 2 +- .../ProjectDirectoriesSection.tsx | 4 +- .../ProjectResourcesScene.tsx | 2 +- .../useProjectDirectoryActions.ts | 5 +- .../pages/ai/ModelPoolCardActions.tsx | 2 +- .../settings/pages/ai/ModelPoolsSection.tsx | 6 +- .../settings/pages/ai/ModelSettingsPage.tsx | 12 +- .../pages/application/PetSettingsSection.tsx | 4 +- .../data/ArchivedSessionsSettingsPage.tsx | 12 +- .../pages/tools/HooksSettingsSection.tsx | 6 +- .../tools/QuickActionsSettingsSection.tsx | 11 +- .../src/app/scenes/skills/SkillsScene.tsx | 9 +- .../skills/components/SkillGroupsView.tsx | 10 +- .../src/app/scenes/todos/TodosScene.tsx | 12 +- .../scenes/todos/components/TodoItemRow.tsx | 4 +- .../features/ssh-remote/RemoteFileBrowser.tsx | 10 +- .../src/flow_chat/components/ChatInput.tsx | 4 +- .../components/ChatInputWorkspaceStrip.tsx | 2 +- .../HarnessProfileSelector.test.tsx | 2 + .../components/HarnessProfileSelector.tsx | 4 +- .../components/modern/FlowChatHeader.tsx | 6 +- .../modern/ModernFlowChatContainer.tsx | 5 +- .../modern/SessionTreePopover.test.tsx | 2 +- .../components/modern/SessionTreePopover.tsx | 13 +- .../thread-goal/ThreadGoalDialogs.tsx | 6 +- .../thread-goal/ThreadGoalStripControl.tsx | 4 +- .../hooks/useThreadGoalController.ts | 8 +- .../components/AppearanceMarketWorkflows.tsx | 7 +- .../AppearancePackageConfigSection.tsx | 7 +- .../components/LocalVoiceModelsConfig.tsx | 7 +- .../config/components/McpToolsConfig.test.tsx | 2 +- .../config/components/McpToolsConfig.tsx | 7 +- .../config/components/SkillsConfig.tsx | 6 +- .../ImageGenerationSection.tsx | 2 +- .../useImageGenerationSettings.ts | 5 +- .../confirm-dialog/ConfirmDialogRenderer.tsx | 1 + .../confirmDialogService.test.ts | 14 ++ .../confirm-dialog/confirmDialogService.ts | 12 +- src/web-ui/src/locales/en-US/common.json | 3 + src/web-ui/src/locales/zh-CN/common.json | 3 + src/web-ui/src/locales/zh-TW/common.json | 3 + .../commands/builtin/file/DeleteCommand.ts | 2 + .../ContextList/ContextList.test.tsx | 19 +++ .../components/ContextList/ContextList.tsx | 9 +- .../ui/ConfirmationInteraction.test.tsx | 131 ++++++++++++++++ 99 files changed, 1078 insertions(+), 346 deletions(-) create mode 100644 design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx create mode 100644 design-system/packages/ui/src/internal/confirmationAnchor.ts create mode 100644 src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.scss create mode 100644 src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.test.tsx create mode 100644 src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.tsx create mode 100644 src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx diff --git a/design-system/packages/ui/README.md b/design-system/packages/ui/README.md index daaf4956af..0d7da35164 100644 --- a/design-system/packages/ui/README.md +++ b/design-system/packages/ui/README.md @@ -779,6 +779,20 @@ restores focus before dispatching `onSelect`; the host owns asynchronous work and error handling. The popup flips and clamps to the viewport, keeps keyboard navigation in the active menu, and supports safe pointer travel to either side. +For a simple destructive menu action, add `confirmation: { description, +confirmText, cancelText }` to its entry. `MenuConfirmItem` exposes the same +behavior for composed menus: the row changes to Cancel / Confirm, focuses +Cancel first, and Escape restores the original row. The confirmed action is +awaited with both controls disabled; the host owns error presentation. + +Use `ConfirmDialog anchor={captureConfirmationAnchor(event.currentTarget)}` +when a single-item action needs a short explanation beside its trigger. Capture +the anchor before awaiting work or closing a menu. It retains the trigger's +rectangle and overlay owner, flips within the viewport, and restores focus to +the trigger or its surviving owner. Without an anchor the dialog remains modal; +keep this presentation for bulk deletion, overwrite, reset, and permission +decisions. Confirmations focus Cancel first when it is available. + Portals resolve through `DesignSystemProvider.portalHost`, then fall back to one document-owned overlay host above application content. Stable `parts` wrappers preserve host data hooks; they must forward all props and refs and retain public component ownership. diff --git a/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.meta.ts b/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.meta.ts index 3bf26da2f9..3fd62cc675 100644 --- a/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.meta.ts +++ b/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.meta.ts @@ -6,6 +6,7 @@ export const confirmDialogMeta = { maturity: "stable", name: "ConfirmDialog", props: [ + { name: "anchor", type: "ConfirmationAnchor" }, { name: "open", type: "boolean" }, { name: "title", type: "ReactNode" }, { name: "message", type: "ReactNode" }, diff --git a/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.tsx b/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.tsx index 6cdcda29ae..8bb301a21a 100644 --- a/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.tsx +++ b/design-system/packages/ui/src/components/ConfirmDialog/ConfirmDialog.tsx @@ -24,12 +24,14 @@ import { type DialogCloseReason, } from "../Dialog"; import styles from "./ConfirmDialog.module.css"; +import type { ConfirmationAnchor } from "../../internal/confirmationAnchor"; export type ConfirmDialogCloseReason = DialogCloseReason | "cancel-button"; export type ConfirmDialogType = "info" | "warning" | "error" | "success"; export type ConfirmDialogAction = () => void | Promise; export interface ConfirmDialogProps { + anchor?: ConfirmationAnchor; cancelText?: ReactNode; closeOnEscape?: boolean; closeOnPointerOutside?: boolean; @@ -63,6 +65,7 @@ const defaultIcons: Record = { export const ConfirmDialog = forwardRef( function ConfirmDialog({ + anchor, cancelText, closeOnEscape = true, closeOnPointerOutside = true, @@ -87,6 +90,8 @@ export const ConfirmDialog = forwardRef( }, ref) { const designSystem = useDesignSystem(); const confirmButtonRef = useRef(null); + const cancelButtonRef = useRef(null); + const pendingRef = useRef(false); const mountedRef = useRef(true); const [internalPendingAction, setInternalPendingAction] = useState<"confirm" | "secondary" | null>(null); const pendingAction = controlledPendingAction ?? internalPendingAction; @@ -99,8 +104,9 @@ export const ConfirmDialog = forwardRef( const resolvedCancelText = cancelText ?? designSystem.messages.confirmCancel; const resolvedConfirmText = confirmText ?? designSystem.messages.confirmAction; - useEffect(() => () => { - mountedRef.current = false; + useEffect(() => { + mountedRef.current = true; + return () => { mountedRef.current = false; }; }, []); useEffect(() => { @@ -111,7 +117,8 @@ export const ConfirmDialog = forwardRef( actionName: "confirm" | "secondary", action: ConfirmDialogAction | undefined, ) => { - if (!action || busy) return; + if (!action || busy || pendingRef.current) return; + pendingRef.current = true; try { const result = action(); if (result && typeof result.then === "function") { @@ -121,6 +128,7 @@ export const ConfirmDialog = forwardRef( } catch (error) { onActionError?.(error, actionName); } finally { + pendingRef.current = false; if (mountedRef.current) setInternalPendingAction(null); } }, [busy, onActionError]); @@ -131,7 +139,7 @@ export const ConfirmDialog = forwardRef( }, [busy, onOpenChange]); const cancelButton = showCancel ? ( - ) : null; @@ -161,10 +169,11 @@ export const ConfirmDialog = forwardRef( return ( requestClose(reason)} open={open} ref={ref} diff --git a/design-system/packages/ui/src/components/ConfirmDialog/index.ts b/design-system/packages/ui/src/components/ConfirmDialog/index.ts index 42fabe6922..86b749d0b8 100644 --- a/design-system/packages/ui/src/components/ConfirmDialog/index.ts +++ b/design-system/packages/ui/src/components/ConfirmDialog/index.ts @@ -5,3 +5,4 @@ export { type ConfirmDialogProps, type ConfirmDialogType, } from "./ConfirmDialog"; +export { captureConfirmationAnchor, type ConfirmationAnchor } from "../../internal/confirmationAnchor"; diff --git a/design-system/packages/ui/src/components/Dialog/Dialog.module.css b/design-system/packages/ui/src/components/Dialog/Dialog.module.css index 56efa88dfa..640000a528 100644 --- a/design-system/packages/ui/src/components/Dialog/Dialog.module.css +++ b/design-system/packages/ui/src/components/Dialog/Dialog.module.css @@ -44,6 +44,27 @@ .surface[data-size="xl"] { max-inline-size: var(--openbitfun-overlay-dialog-max-inline-size-xlarge); } .surface[data-size="2xl"] { max-inline-size: var(--openbitfun-overlay-dialog-max-inline-size-xxlarge); } + .anchoredOverlay { + display: contents; + } + + .anchoredSurface { + inline-size: min(var(--openbitfun-overlay-dialog-max-inline-size-small), calc(100vw - 2 * var(--openbitfun-space-2))); + box-shadow: var(--openbitfun-shadow-overlay); + transform-origin: top left; + animation: none; + } + + .anchoredSurface[data-placement="top"] { transform-origin: bottom left; } + + .anchoredSurface > .header, + .anchoredSurface > .body, + .anchoredSurface > .footer { + padding: var(--openbitfun-space-3); + } + + .anchoredSurface > .body { padding-block-start: 0; } + .surface[data-preset="panel"] { --_dialog-panel-title-gap: calc(var(--openbitfun-overlay-dialog-header-padding-block-start) + var(--openbitfun-space-4)); diff --git a/design-system/packages/ui/src/components/Dialog/Dialog.tsx b/design-system/packages/ui/src/components/Dialog/Dialog.tsx index 605c07579d..5fbb532a9a 100644 --- a/design-system/packages/ui/src/components/Dialog/Dialog.tsx +++ b/design-system/packages/ui/src/components/Dialog/Dialog.tsx @@ -24,6 +24,8 @@ import { useFocusScope } from "../../overlay/useFocusScope"; import { usePresence } from "../../overlay/usePresence"; import { IconButton, type IconButtonProps } from "../IconButton"; import { inertProps } from "../../internal/inert"; +import { useAnchoredLayer } from "../../internal/useAnchoredLayer"; +import type { ConfirmationAnchor } from "../../internal/confirmationAnchor"; import styles from "./Dialog.module.css"; const EXIT_DURATION_MS = 180; @@ -68,6 +70,8 @@ interface OverlaySurfaceProps closeOnEscape?: boolean; closeOnPointerOutside?: boolean; initialFocusRef?: RefObject; + /** A compact, non-modal confirmation attached to an explicit user action. */ + anchor?: ConfirmationAnchor; kind: "dialog" | "sheet"; onOpenChange: (open: false, reason: DialogCloseReason) => void; /** Called after the closed surface has finished exiting and unmounted. */ @@ -94,6 +98,7 @@ const OverlaySurface = forwardRef(function closeOnEscape = true, closeOnPointerOutside = true, initialFocusRef, + anchor, kind, onOpenChange, onExitComplete, @@ -115,15 +120,15 @@ const OverlaySurface = forwardRef(function const titleId = `openbitfun-dialog-title-${useId()}`; const descriptionId = `openbitfun-dialog-description-${useId()}`; const { present, state } = usePresence(open, EXIT_DURATION_MS); - const presentation = { children, className, overlayProps, placement, preset, size, style }; + const presentation = { children, className, overlayProps, placement, preset, size, style, anchor }; const lastOpenPresentation = useRef(null); const wasPresent = useRef(present); // Owners often clear selection or form state in the same update as closing. // Retain the content and its geometry together until the exit finishes. useLayoutEffect(() => { - if (open) lastOpenPresentation.current = { children, className, overlayProps, placement, preset, size, style }; + if (open) lastOpenPresentation.current = { children, className, overlayProps, placement, preset, size, style, anchor }; else if (!present) lastOpenPresentation.current = null; - }, [children, className, open, overlayProps, placement, preset, present, size, style]); + }, [children, className, open, overlayProps, placement, preset, present, size, style, anchor]); useEffect(() => { const completed = wasPresent.current && !present && !open; wasPresent.current = present; @@ -133,6 +138,14 @@ const OverlaySurface = forwardRef(function const renderedChildren = rendered.children; const hasTitle = containsType(renderedChildren, DialogTitle); const hasDescription = containsType(renderedChildren, DialogDescription); + const anchorRef = useRef(null); + const ownerRef = useRef(null); + const returnFocusRef = useRef(null); + anchorRef.current = rendered.anchor?.element ?? null; + ownerRef.current = rendered.anchor?.owner ?? null; + returnFocusRef.current = anchorRef.current?.isConnected ? anchorRef.current : ownerRef.current; + const anchored = Boolean(rendered.anchor); + const layout = useAnchoredLayer({ open: present && anchored, anchorRef, layerRef: surfaceRef, fallbackRect: rendered.anchor?.rect }); const close = useCallback((reason: DialogCloseReason) => { if (open) onOpenChange(false, reason); @@ -165,6 +178,7 @@ const OverlaySurface = forwardRef(function autoFocus, containerRef: surfaceRef, initialFocusRef, + returnFocusRef: anchored ? returnFocusRef : undefined, ownerDocument, trapFocus, restoreFocus, @@ -174,10 +188,10 @@ const OverlaySurface = forwardRef(function const exiting = state === "exiting"; return ( - +
(function aria-hidden={exiting || undefined} aria-label={ariaLabel} aria-labelledby={ariaLabelledBy ?? (!ariaLabel && hasTitle ? titleId : undefined)} - aria-modal="true" - className={classNames(styles.surface, rendered.className)} + aria-modal={!anchored} + className={classNames(styles.surface, anchored && styles.anchoredSurface, rendered.className)} data-openbitfun-component={kind} data-openbitfun-part="surface" - data-placement={rendered.placement} + data-placement={anchored ? layout?.placement : rendered.placement} + data-presentation={anchored ? "anchored" : "modal"} + data-openbitfun-native-webview-occlusion={anchored || undefined} data-preset={rendered.preset} data-size={rendered.size} data-state={exiting ? "exiting" : "open"} ref={setSurfaceRef} role={role} - style={rendered.style} + style={anchored ? { ...rendered.style, ...layout?.style, visibility: layout ? undefined : "hidden" } : rendered.style} tabIndex={-1} > {renderedChildren} diff --git a/design-system/packages/ui/src/components/Menu/Menu.module.css b/design-system/packages/ui/src/components/Menu/Menu.module.css index 0bb894c074..ecee2f3fc8 100644 --- a/design-system/packages/ui/src/components/Menu/Menu.module.css +++ b/design-system/packages/ui/src/components/Menu/Menu.module.css @@ -113,6 +113,18 @@ border-radius: var(--openbitfun-overlay-menu-item-radius); } + .confirmation { + display: grid; + grid-template-columns: minmax(0, 1fr) var(--openbitfun-border-width-default) minmax(0, 1fr); + align-items: center; + } + .confirmationButton { text-align: center; } + .confirmationDivider { + align-self: stretch; + margin-block: var(--openbitfun-space-2); + background: var(--openbitfun-color-border-subtle); + } + .item > [data-openbitfun-part="trigger"] { gap: var(--openbitfun-overlay-menu-item-gap); } diff --git a/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx b/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx new file mode 100644 index 0000000000..d40c80efdd --- /dev/null +++ b/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx @@ -0,0 +1,75 @@ +import { useLayoutEffect, useRef, useState } from "react"; +import { MenuItem, MenuList, type MenuItemProps } from "./Menu"; +import { useDesignSystem } from "../../overlay/useDesignSystem"; +import styles from "./Menu.module.css"; + +export interface MenuConfirmation { + description: string; + confirmText?: string; + cancelText?: string; +} + +export interface MenuConfirmItemProps extends Omit { + confirmation: MenuConfirmation; + onConfirm: (trigger: HTMLButtonElement) => void | Promise; + onActionError?: (error: unknown) => void; +} + +/** The action stays in its menu row until the user explicitly confirms it. */ +export function MenuConfirmItem({ confirmation, onConfirm, onActionError, disabled, ...props }: MenuConfirmItemProps) { + const { messages } = useDesignSystem(); + const [confirming, setConfirming] = useState(false); + const [pending, setPending] = useState(false); + const pendingRef = useRef(false); + const triggerRef = useRef(null); + const cancelRef = useRef(null); + const confirmRef = useRef(null); + const restoreFocus = useRef(false); + useLayoutEffect(() => { + if (confirming) cancelRef.current?.focus({ preventScroll: true }); + else if (restoreFocus.current) { + triggerRef.current?.focus({ preventScroll: true }); + restoreFocus.current = false; + } + }, [confirming]); + const cancel = () => { + if (pendingRef.current) return; + restoreFocus.current = true; + setConfirming(false); + }; + const confirm = async (trigger: HTMLButtonElement) => { + if (disabled || pendingRef.current) return; + pendingRef.current = true; + setPending(true); + try { await onConfirm(trigger); } + catch (error) { onActionError?.(error); } + finally { + pendingRef.current = false; + setPending(false); + setConfirming(false); + } + }; + if (!confirming) return { event.stopPropagation(); setConfirming(true); }} />; + + return
+ { + if (event.key === "Escape" && !pending) { event.preventDefault(); event.stopPropagation(); cancel(); } + else if (event.key === "ArrowLeft" || event.key === "ArrowRight") { + event.preventDefault(); event.stopPropagation(); + (event.key === "ArrowLeft" ? cancelRef : confirmRef).current?.focus({ preventScroll: true }); + } + }}> + { event.stopPropagation(); cancel(); }}> + {confirmation.cancelText ?? messages.confirmCancel} + + +
; +} diff --git a/design-system/packages/ui/src/components/Menu/MenuPopover.tsx b/design-system/packages/ui/src/components/Menu/MenuPopover.tsx index f34ed4b45c..42d6cc6057 100644 --- a/design-system/packages/ui/src/components/Menu/MenuPopover.tsx +++ b/design-system/packages/ui/src/components/Menu/MenuPopover.tsx @@ -11,6 +11,7 @@ import { useFocusScope } from "../../overlay/useFocusScope"; import { usePresence } from "../../overlay/usePresence"; import { inertProps } from "../../internal/inert"; import styles from "./MenuPopover.module.css"; +import { MenuConfirmItem, type MenuConfirmation } from "./MenuConfirmItem"; export interface MenuEntry { id: string; @@ -24,7 +25,8 @@ export interface MenuEntry { checked?: boolean; tone?: "neutral" | "danger"; /** Dispatch only: the host owns async work and error presentation. */ - onSelect?: () => void; + onSelect?: (trigger: HTMLButtonElement) => void | Promise; + confirmation?: MenuConfirmation; } export interface MenuPopoverProps extends Omit { @@ -79,7 +81,11 @@ export function MenuPopover({ items, open, onClose, anchorRef, ownerRef, positio && target.closest("[data-openbitfun-menu-tree]")?.getAttribute("data-openbitfun-menu-tree") === treeId, enabled: open, layerRef: menuRef, - onDismiss: closeAndRestoreFocus, + onDismiss: reason => { + const cancel = menuRef.current?.querySelector("[data-openbitfun-menu-confirmation-cancel]"); + if (reason === "escape-key" && cancel) { cancel.click(); return; } + closeAndRestoreFocus(); + }, }); useFocusScope({ active: open && present, @@ -155,10 +161,10 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos intent.openNow(item.id); if (keyboard && activeId === item.id && submenuRef.current) ownItems(submenuRef.current)[0]?.focus(); }; - const activate = (item: MenuEntry) => { + const activate = (item: MenuEntry, trigger: HTMLButtonElement) => { if (item.disabled || item.separator) return; onClose(); - item.onSelect?.(); + void item.onSelect?.(trigger); }; useEffect(() => { if (!open) intent.closeNow(); }, [open, intent.closeNow]); @@ -172,6 +178,7 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos const current = enabled.indexOf(doc.activeElement as HTMLButtonElement); const button = enabled[current]; const item = items.find(entry => entry.id === button?.getAttribute("data-menu-id")); + if (button?.closest("[data-openbitfun-menu-confirmation]") && event.key !== "Tab") return; let index: number | undefined; switch (event.key) { case "ArrowDown": index = (current + 1) % enabled.length; break; @@ -188,7 +195,7 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos case "Enter": case " ": event.preventDefault(); event.stopPropagation(); - if (item && button) { if (item.submenu?.length) openSubmenu(item, button, true); else activate(item); } + if (item && button) { if (item.submenu?.length) openSubmenu(item, button, true); else if (item.confirmation) button.click(); else activate(item, button); } return; default: if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) { @@ -212,10 +219,13 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos { (menuRef as { current: HTMLDivElement | null }).current = node; }} className={classNames(styles.popup, className)} inlineSize={inlineSize} autoFocusFirstItem={open && autoFocusFirstItem && Boolean(layout)} tabIndex={-1} style={{ ...layout?.style, ...style, visibility: layout ? undefined : "hidden" }} data-openbitfun-native-webview-occlusion data-openbitfun-menu-tree={treeId} data-placement={layout?.placement ?? placement} data-state={phase} aria-hidden={!open || undefined} {...inertProps(!open)} onContextMenu={event => event.preventDefault()}> - {items.map(item => item.separator ? : {item.icon} : undefined} shortcut={item.shortcut ? {item.shortcut} : undefined} tone={item.tone} role={item.role} checked={item.checked} + {items.map(item => item.separator ? : item.confirmation ? { await item.onSelect?.(trigger); onClose(); }}>{item.label} + : {item.icon} : undefined} shortcut={item.shortcut ? {item.shortcut} : undefined} tone={item.tone} role={item.role} checked={item.checked} disabled={item.disabled} aria-disabled={item.disabled || undefined} aria-haspopup={item.submenu?.length ? "menu" : undefined} aria-expanded={item.submenu?.length ? activeEntry?.id === item.id : undefined} aria-controls={activeEntry?.id === item.id ? submenuId : undefined} metadata={item.submenu?.length ? : undefined} - onClick={event => { event.stopPropagation(); if (item.submenu?.length) openSubmenu(item, event.currentTarget, true); else activate(item); }} + onClick={event => { event.stopPropagation(); if (item.submenu?.length) openSubmenu(item, event.currentTarget, true); else activate(item, event.currentTarget); }} onPointerEnter={event => { if (activeId === null || activeId === item.id) submenuAnchor.current = event.currentTarget; keyboardOpen.current = false; intent.requestChange(!item.disabled && item.submenu?.length ? item.id : null, event); }} onPointerLeave={intent.requestClose} ref={element => { if (activeEntry?.id === item.id && element) submenuAnchor.current = element; }}> diff --git a/design-system/packages/ui/src/components/Menu/index.ts b/design-system/packages/ui/src/components/Menu/index.ts index 06bdb2cf93..63c0e704c6 100644 --- a/design-system/packages/ui/src/components/Menu/index.ts +++ b/design-system/packages/ui/src/components/Menu/index.ts @@ -13,3 +13,4 @@ export { type MenuSeparatorProps, } from "./Menu"; export { MenuPopover, type MenuPopoverProps, type MenuPopoverParts, type MenuEntry } from "./MenuPopover"; +export { MenuConfirmItem, type MenuConfirmItemProps, type MenuConfirmation } from "./MenuConfirmItem"; diff --git a/design-system/packages/ui/src/index.ts b/design-system/packages/ui/src/index.ts index afbbd6c04f..4f0d7d6794 100644 --- a/design-system/packages/ui/src/index.ts +++ b/design-system/packages/ui/src/index.ts @@ -103,6 +103,8 @@ export { } from "./components/MultiSelect"; export { ConfirmDialog, + captureConfirmationAnchor, + type ConfirmationAnchor, type ConfirmDialogAction, type ConfirmDialogCloseReason, type ConfirmDialogProps, @@ -167,6 +169,9 @@ export { type MenuPopoverParts, type MenuEntry, MenuItem, + MenuConfirmItem, + type MenuConfirmItemProps, + type MenuConfirmation, MenuList, MenuSection, MenuSeparator, diff --git a/design-system/packages/ui/src/internal/confirmationAnchor.ts b/design-system/packages/ui/src/internal/confirmationAnchor.ts new file mode 100644 index 0000000000..a73fccb96b --- /dev/null +++ b/design-system/packages/ui/src/internal/confirmationAnchor.ts @@ -0,0 +1,31 @@ +import { getOverlayLayerStack } from "../overlay/LayerStack"; + +/** A user action's origin, captured before a menu can close or its row unmount. */ +export interface ConfirmationAnchor { + element: HTMLElement; + owner: HTMLElement; + rect: Pick; +} + +export function captureConfirmationAnchor(element: HTMLElement | null | undefined): ConfirmationAnchor | undefined { + if (!element?.isConnected) return undefined; + const box = element.getBoundingClientRect(); + const stack = getOverlayLayerStack(element.ownerDocument); + let owner = element; + let layer = stack.getLayerForElement(owner); + // A closing menu is not the owner of the next confirmation. Preserve the + // trigger (and its modal ancestor) rather than attaching to an exiting layer. + const visited = new Set(); + while (layer && !layer.modal && !visited.has(owner)) { + visited.add(owner); + const next = layer.ownerElement?.() ?? layer.activationFocus; + if (!next?.isConnected || next === owner) break; + owner = next; + layer = stack.getLayerForElement(owner); + } + return { + element, + owner, + rect: { left: box.left, top: box.top, right: box.right, bottom: box.bottom, width: box.width, height: box.height }, + }; +} diff --git a/design-system/packages/ui/src/internal/useAnchoredLayer.ts b/design-system/packages/ui/src/internal/useAnchoredLayer.ts index 068ed625c2..40e02cc677 100644 --- a/design-system/packages/ui/src/internal/useAnchoredLayer.ts +++ b/design-system/packages/ui/src/internal/useAnchoredLayer.ts @@ -11,7 +11,7 @@ export function resolveLayerPortal(target: PortalTarget | undefined, anchor: HTM return target ?? anchor?.closest("[data-openbitfun-design-system-root]") ?? anchor?.ownerDocument.body ?? null; } -export function useAnchoredLayer({ open, anchorRef, layerRef, placement = "bottom", matchWidth = false, overlapAnchor = false, revision, point }: { +export function useAnchoredLayer({ open, anchorRef, layerRef, placement = "bottom", matchWidth = false, overlapAnchor = false, revision, point, fallbackRect }: { open: boolean; anchorRef: RefObject; layerRef: RefObject; @@ -22,6 +22,8 @@ export function useAnchoredLayer({ open, anchorRef, layerRef, placement = "botto overlapAnchor?: boolean; revision?: unknown; point?: { x: number; y: number }; + /** Keep the action's origin when a menu item disappears before the layer mounts. */ + fallbackRect?: Pick; }) { const [layout, setLayout] = useState<{ style: CSSProperties; placement: LayerPlacement } | null>(null); const measuredContentWidth = useRef(0); @@ -30,13 +32,13 @@ export function useAnchoredLayer({ open, anchorRef, layerRef, placement = "botto const anchor = anchorRef.current; const layer = layerRef.current; const view = layer?.ownerDocument.defaultView; - if (!layer || !view || (!anchor && !point)) return; + if (!layer || !view || (!anchor && !point && !fallbackRect)) return; const update = () => { const padding = 8; const resolvedGap = point ? 0 : 4; const rect = point ? { left: point.x, right: point.x, top: point.y, bottom: point.y, width: 0, height: 0 } - : anchor!.getBoundingClientRect(); + : anchor?.isConnected ? anchor.getBoundingClientRect() : fallbackRect ?? anchor!.getBoundingClientRect(); const viewport = view.visualViewport; const vx = viewport?.offsetLeft ?? 0; const vy = viewport?.offsetTop ?? 0; @@ -105,6 +107,6 @@ export function useAnchoredLayer({ open, anchorRef, layerRef, placement = "botto view.visualViewport?.removeEventListener("resize", update); view.visualViewport?.removeEventListener("scroll", update); }; - }, [open, anchorRef, layerRef, placement, matchWidth, overlapAnchor, revision, point?.x, point?.y]); + }, [open, anchorRef, layerRef, placement, matchWidth, overlapAnchor, revision, point?.x, point?.y, fallbackRect]); return layout; } diff --git a/design-system/packages/ui/src/overlay/useFocusScope.ts b/design-system/packages/ui/src/overlay/useFocusScope.ts index 8533dd87ec..413a15f2d0 100644 --- a/design-system/packages/ui/src/overlay/useFocusScope.ts +++ b/design-system/packages/ui/src/overlay/useFocusScope.ts @@ -8,13 +8,14 @@ export interface UseFocusScopeOptions { autoFocus?: boolean; containerRef: RefObject; initialFocusRef?: RefObject; + returnFocusRef?: RefObject; ownerDocument?: Document | null; restoreFocus?: boolean; trapFocus?: boolean; } export function useFocusScope({ - active, autoFocus = true, containerRef, initialFocusRef, ownerDocument, + active, autoFocus = true, containerRef, initialFocusRef, returnFocusRef, ownerDocument, restoreFocus = true, trapFocus = true, }: UseFocusScopeOptions): void { const identity = useRef(Symbol("openbitfun-focus-scope")); @@ -31,7 +32,7 @@ export function useFocusScope({ trapFocus, restoreFocus, initialFocus: initialFocusRef?.current, - previousFocus: HTMLElementType && doc.activeElement instanceof HTMLElementType ? doc.activeElement : null, + previousFocus: returnFocusRef?.current ?? (HTMLElementType && doc.activeElement instanceof HTMLElementType ? doc.activeElement : null), }); - }, [active, autoFocus, containerRef, initialFocusRef, ownerDocument, restoreFocus, trapFocus]); + }, [active, autoFocus, containerRef, initialFocusRef, returnFocusRef, ownerDocument, restoreFocus, trapFocus]); } diff --git a/design-system/packages/ui/tests/dialog.test.mjs b/design-system/packages/ui/tests/dialog.test.mjs index e7a195d6c1..ea1c490d8e 100644 --- a/design-system/packages/ui/tests/dialog.test.mjs +++ b/design-system/packages/ui/tests/dialog.test.mjs @@ -14,7 +14,7 @@ test("Dialog and Sheet compose the shared overlay kernel and compound anatomy", assert.match(source, / ({ setAlwaysOnTop: vi.fn(), nativeWindow: true, card: null as unknown, + deleteCard: vi.fn(async () => {}), startResize: vi.fn(async (_direction: string) => {}), startDrag: vi.fn(async () => {}), })); @@ -36,20 +37,25 @@ vi.mock('./DesktopCardTemplates', () => { }; }); -vi.mock('@openbitfun/ui', () => ({ +vi.mock('@openbitfun/ui', async importOriginal => { + const actual = await importOriginal(); + return ({ Button: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) => , Icon: () => , IconButton: React.forwardRef void }>( ({ 'aria-label': label, onClick }, ref) => ))}
) : null, OverflowText: ({ children, ...props }: { children: React.ReactNode }) => {children}, Spinner: () => , -})); + }); +}); vi.mock('@/infrastructure/i18n/hooks/useI18n', () => ({ useI18n: () => ({ @@ -75,7 +81,7 @@ vi.mock('@/infrastructure/api/service-api/DesktopCardAPI', () => ({ onChanged: vi.fn(() => () => {}), setChecklistItem: vi.fn(), setVisible: vi.fn(async () => mocks.card), - delete: vi.fn(async () => {}), + delete: mocks.deleteCard, refresh: vi.fn(async () => mocks.card), setAlwaysOnTop: mocks.setAlwaysOnTop, setDesktopPinned: mocks.setDesktopPinned, @@ -137,6 +143,7 @@ describe('DesktopCardWindow', () => { mocks.setAlwaysOnTop.mockReset().mockImplementation(async (_id: string, top: boolean) => ({ ...noteCard(), alwaysOnTop: top, desktopPinned: false })); mocks.startResize.mockClear(); mocks.startDrag.mockClear(); + mocks.deleteCard.mockClear(); }); afterEach(() => { @@ -160,6 +167,19 @@ describe('DesktopCardWindow', () => { }); } + it('confirms deletion inside the menu without replacing the card body', async () => { + await render(); + await click('[aria-label="desktopCard.menu.more"]'); + await click('[data-menu-id="delete"]'); + expect(container.querySelector('.openbitfun-desktop-card__body [data-template="note"]')?.textContent).toBe('hello'); + expect(container.querySelector('.openbitfun-desktop-card__confirm')).toBeNull(); + expect(mocks.deleteCard).not.toHaveBeenCalled(); + const confirm = [...container.querySelectorAll('button')].find(button => button.textContent === 'common:actions.confirm')!; + expect(confirm.closest('[role="menu"]')).not.toBeNull(); + await act(async () => confirm.click()); + expect(mocks.deleteCard).toHaveBeenCalledExactlyOnceWith('card-1'); + }); + it('switches between desktop pinning and global topmost without hiding the card', async () => { mocks.card = { ...noteCard(), desktopPinningSupported: true }; await render(); diff --git a/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx b/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx index 563b8f82db..c4b0ced9f3 100644 --- a/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx +++ b/src/web-ui/src/app/components/DesktopCard/DesktopCardWindow.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Ellipsis, RefreshCw, X } from 'lucide-react'; -import { Button, Icon, IconButton, MenuPopover, OverflowText, Spinner, type MenuEntry } from '@openbitfun/ui'; +import { Icon, IconButton, MenuPopover, OverflowText, Spinner, type MenuEntry } from '@openbitfun/ui'; import { useI18n } from '@/infrastructure/i18n/hooks/useI18n'; import { desktopCardAPI, hasDesktopPinFailure, isDesktopPinned, type DesktopCardRecord } from '@/infrastructure/api/service-api/DesktopCardAPI'; import { systemAPI } from '@/infrastructure/api/service-api/SystemAPI'; @@ -133,7 +133,6 @@ export default function DesktopCardWindow() { const [card, setCard] = useState(null); const [loadFailed, setLoadFailed] = useState(false); const [menuOpen, setMenuOpen] = useState(false); - const [confirmingDelete, setConfirmingDelete] = useState(false); const [refreshing, setRefreshing] = useState(false); const [desktopPinningSupported, setDesktopPinningSupported] = useState(false); const [stackingBusy, setStackingBusy] = useState(false); @@ -196,7 +195,7 @@ export default function DesktopCardWindow() { const remove = useCallback(() => { if (!cardId) return; - void desktopCardAPI.delete(cardId).catch(error => { + return desktopCardAPI.delete(cardId).catch(error => { log.warn('Failed to delete desktop card', { cardId, error }); }); }, [cardId]); @@ -244,7 +243,6 @@ export default function DesktopCardWindow() { const sessionId = card.origin?.sessionId; const link = isSafeWebLink(card.link) ? card.link : null; const menuItems: MenuEntry[] = [ - ...(hasDataSource(card) ? [{ id: 'refresh', label: t('desktopCard.menu.refresh'), onSelect: refresh }] : []), ...(link ? [{ id: 'open-link', label: t('desktopCard.menu.openLink'), onSelect: () => openLink(link) }] : []), ...(sessionId ? [{ id: 'open-session', @@ -273,7 +271,8 @@ export default function DesktopCardWindow() { }] : []), { id: 'separator', label: '', separator: true }, { id: 'hide', label: t('desktopCard.menu.hide'), onSelect: hide }, - { id: 'delete', label: t('desktopCard.menu.delete'), tone: 'danger', onSelect: () => setConfirmingDelete(true) }, + { id: 'delete', label: t('desktopCard.menu.delete'), tone: 'danger', onSelect: remove, + confirmation: { description: t('desktopCard.deleteConfirm.message'), cancelText: t('desktopCard.deleteConfirm.cancel'), confirmText: t('common:actions.confirm') } }, ]; const CardIcon = desktopCardIcon(card); @@ -294,10 +293,8 @@ export default function DesktopCardWindow() { )}
- {hasDataSource(card) && ( - } onClick={refresh} /> - )} + } onClick={refresh} /> } onClick={() => setMenuOpen(open => !open)} /> } onClick={hide} /> @@ -306,17 +303,7 @@ export default function DesktopCardWindow() {
{stackingError === null && hasDesktopPinFailure(card) &&

{t('desktopCard.pinRecoveryFailed')}

} {stackingError !== null &&

{t('desktopCard.stackingFailed', { error: stackingError })}

} - {confirmingDelete ? ( -
-

{t('desktopCard.deleteConfirm.message')}

-
- - -
-
- ) : ( - - )} +
setMenuOpen(false)} anchorRef={menuButtonRef} diff --git a/src/web-ui/src/app/components/NavPanel/components/MiniAppShortcuts.tsx b/src/web-ui/src/app/components/NavPanel/components/MiniAppShortcuts.tsx index 80cebd3c59..373618fdf6 100644 --- a/src/web-ui/src/app/components/NavPanel/components/MiniAppShortcuts.tsx +++ b/src/web-ui/src/app/components/NavPanel/components/MiniAppShortcuts.tsx @@ -1,4 +1,4 @@ -import { ConfirmDialog, Icon, IconButton, NavigationPanelItem, Tooltip } from '@openbitfun/ui'; +import { captureConfirmationAnchor, ConfirmDialog, Icon, IconButton, NavigationPanelItem, Tooltip } from '@openbitfun/ui'; import { useCurrentWorkspace } from '@/infrastructure/contexts/WorkspaceContext'; import { useI18n } from '@/infrastructure/i18n'; import { isRemoteWorkspace } from '@/shared/types'; @@ -41,7 +41,7 @@ function MiniAppShortcutItems({ scope, pinnedAppIds, setPinned }: ReturnType void launch.openApp(app.id)} + onClick={event => void launch.openApp(app.id, 'tab', undefined, captureConfirmationAnchor(event.currentTarget))} leading={{renderMiniAppIcon(app.icon || 'box', 'sm')}} actionContent={ ; })} { if (!open) launch.cancelTransfer(); }} title={t('presentation.openTab')} diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.test.tsx index 7a91205181..c19e5be7c0 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.test.tsx @@ -87,6 +87,7 @@ describe('device catalog session row menu', () => { 'nav-device-session-menu-export-markdown', 'nav-device-session-menu-open-storage', 'nav-device-session-menu-archive', + 'nav-device-session-menu-delete', ]); // Opening the menu is not an intent to open the session. expect(device.openSession).not.toHaveBeenCalled(); @@ -100,11 +101,17 @@ describe('device catalog session row menu', () => { expect(reveal.getAttribute('title')).toBe('nav.sessions.storageDirectoryDesktopOnly'); }); - it('runs a chosen action on the owning device and closes the menu', async () => { + it.each(['archive', 'delete'] as const)('runs %s on the owning device and closes the menu', async kind => { await openMenu(); - await act(async () => menu()!.querySelector('[data-testid="nav-device-session-menu-archive"]')!.click()); - expect(actions.run).toHaveBeenCalledWith('session-action:s-1:archive', expect.any(Function), 'nav.devices.sessionActionFailed'); - expect(device.runAction).toHaveBeenCalledWith(null, slot, 's-1', { kind: 'archive' }, expect.any(Function)); + await act(async () => menu()!.querySelector(`[data-testid="nav-device-session-menu-${kind}"]`)!.click()); + if (kind === 'delete') { + expect(actions.run).not.toHaveBeenCalled(); + expect(device.runAction).not.toHaveBeenCalled(); + expect(menu()).not.toBeNull(); + await act(async () => menu()!.querySelector('[data-testid="nav-device-session-menu-delete-confirm"]')!.click()); + } + expect(actions.run).toHaveBeenCalledWith(`session-action:s-1:${kind}`, expect.any(Function), 'nav.devices.sessionActionFailed'); + expect(device.runAction).toHaveBeenCalledWith(null, slot, 's-1', { kind }, expect.any(Function)); expect(device.openSession).not.toHaveBeenCalled(); expect(menu()).toBeNull(); }); diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx index 9fbecaab2c..90b5c7d923 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/CatalogSessionMenu.tsx @@ -22,6 +22,7 @@ import { isWorktreeIsolatedSession } from '@/flow_chat/utils/sessionOrdering'; import { sessionWorktreeRootPath } from '@/flow_chat/utils/sessionWorktree'; import { useSideAnchoredPopoverPosition } from '@/shared/utils/useSideAnchoredPopoverPosition'; import ArchivedSessionMenuItems from '../sessions/ArchivedSessionMenuItems'; +import SessionDeleteMenuItem from '../sessions/SessionDeleteMenuItem'; import { activateDeviceSlot, runDeviceSessionAction, type DeviceSessionAction } from './openOnDevice'; import type { BackgroundActions } from './BackgroundSessionList'; import type { SidebarDeviceSlot } from './useSidebarDevices'; @@ -269,6 +270,17 @@ export const CatalogSessionMenu: React.FC<{ > {t('nav.sessions.archive')} + { + close(); + runCatalogSessionAction(actions, peer, slot, session.sessionId, { kind: 'delete' }, t); + }} + /> )} , diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts index c39d334d51..5782cedacc 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.test.ts @@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({ openLatestAssistant: vi.fn(async () => undefined), workspaces: new Map(), archiveRow: vi.fn(async () => undefined), + deleteRow: vi.fn(async () => undefined), duplicateRow: vi.fn(async () => undefined), renameRow: vi.fn(async () => undefined), worktreeRow: vi.fn(async () => undefined), @@ -28,6 +29,7 @@ const mocks = vi.hoisted(() => ({ })); vi.mock('../sessions/sessionRowActions', () => ({ archiveSessionRow: mocks.archiveRow, + deleteSessionRow: mocks.deleteRow, duplicateSessionRow: mocks.duplicateRow, renameSessionRow: mocks.renameRow, openWorktreeWorkspaceRow: mocks.worktreeRow, @@ -186,6 +188,7 @@ describe('openOnDevice', () => { const peer = peerContext(); for (const action of [ { kind: 'archive' as const }, + { kind: 'delete' as const }, { kind: 'rename' as const, title: 'Renamed' }, { kind: 'open-worktree' as const, worktreePath: '/wt' }, ]) await runDeviceSessionAction(peer, peerSlot, 's-1', action, t); @@ -194,22 +197,26 @@ describe('openOnDevice', () => { const switchedAt = peer.switchToDevice.mock.invocationCallOrder[0]; expect(mocks.promote.mock.invocationCallOrder[0]).toBeGreaterThan(switchedAt); expect(mocks.archiveRow).toHaveBeenCalledWith('s-1', t); + expect(mocks.deleteRow).toHaveBeenCalledWith('s-1'); + expect(mocks.deleteRow.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.promote.mock.invocationCallOrder[1]); expect(mocks.archiveRow.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.promote.mock.invocationCallOrder[0]); expect(mocks.renameRow).toHaveBeenCalledWith('s-1', 'Renamed', t); expect(mocks.worktreeRow).toHaveBeenCalledWith('/wt', t); expect(mocks.exportMarkdown).toHaveBeenCalledWith({ sessionId: 's-1', title: 'Chat', workspaceId: 'ws-1' }, 'full'); }); - it('runs nothing when a newer switch superseded the action', async () => { + it.each(['archive', 'delete'] as const)('does not %s when a newer switch superseded the action', async kind => { mocks.sessions.set('s-1', seeded); - await runDeviceSessionAction(peerContext('superseded'), peerSlot, 's-1', { kind: 'archive' }, t); + await runDeviceSessionAction(peerContext('superseded'), peerSlot, 's-1', { kind }, t); expect(mocks.archiveRow).not.toHaveBeenCalled(); + expect(mocks.deleteRow).not.toHaveBeenCalled(); }); - it('fails loudly when the rendered device no longer has the session', async () => { - await expect(runDeviceSessionAction(peerContext(), peerSlot, 'gone', { kind: 'archive' }, t)) + it.each(['archive', 'delete'] as const)('fails %s when the rendered device no longer has the session', async kind => { + await expect(runDeviceSessionAction(peerContext(), peerSlot, 'gone', { kind }, t)) .rejects.toThrow('common:nav.devices.sessionUnavailable'); expect(mocks.archiveRow).not.toHaveBeenCalled(); + expect(mocks.deleteRow).not.toHaveBeenCalled(); }); it('re-checks copy gates on the rendered device instead of faking success', async () => { diff --git a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts index 1713d76bfd..38b9dfb1c6 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/devices/openOnDevice.ts @@ -41,6 +41,7 @@ import { exportSessionToMarkdown } from '@/flow_chat/services/sessionMarkdownExp import type { TranscriptExportScope } from '@/flow_chat/utils/dialogTranscriptExport'; import { archiveSessionRow, + deleteSessionRow, duplicateSessionRow, openWorktreeWorkspaceRow, renameSessionRow, @@ -191,7 +192,8 @@ export type DeviceSessionAction = | { kind: 'export'; scope: TranscriptExportScope; title: string } | { kind: 'open-worktree'; worktreePath: string } | { kind: 'reveal-storage' } - | { kind: 'archive' }; + | { kind: 'archive' } + | { kind: 'delete' }; /** * Render `slot`'s device and return the session as the rendered surface knows @@ -261,5 +263,8 @@ export async function runDeviceSessionAction( case 'archive': await archiveSessionRow(sessionId, t); return; + case 'delete': + await deleteSessionRow(sessionId); + return; } } diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx index f3920bed95..810014d43a 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.test.tsx @@ -62,7 +62,7 @@ describe('archived session row menu', () => { , )); }; - const click = async (action: 'restore' | 'delete-archived') => { + const click = async (action: 'restore' | 'delete-archived' | 'delete-archived-confirm' | 'delete-archived-cancel') => { await act(async () => container.querySelector(`[data-testid="nav-session-menu-${action}"]`)!.click()); }; @@ -97,16 +97,17 @@ describe('archived session row menu', () => { }); it('confirms permanent deletion and preserves the record when cancelled', async () => { - mocks.confirm.mockResolvedValueOnce(false); await render(); await click('delete-archived'); expect(mocks.delete).not.toHaveBeenCalled(); expect(mocks.changed).not.toHaveBeenCalled(); expect(mocks.state.sessions.get(session.sessionId)?.persistedStatus).toBe('archived'); + await click('delete-archived-cancel'); + expect(mocks.delete).not.toHaveBeenCalled(); await click('delete-archived'); - expect(mocks.confirm).toHaveBeenLastCalledWith( - 'Delete Archived Session', expect.stringContaining('Archived chat'), { confirmText: 'Delete' }, - ); + expect(container.querySelector('[role="group"]')?.getAttribute('aria-label')).toContain('Archived chat'); + await click('delete-archived-confirm'); + expect(mocks.confirm).not.toHaveBeenCalled(); expect(mocks.delete).toHaveBeenCalledExactlyOnceWith('archived-one'); expect(mocks.changed).toHaveBeenCalledOnce(); }); @@ -122,12 +123,10 @@ describe('archived session row menu', () => { }); it('does not delete on another device if the surface changes while confirmation is open', async () => { - let confirm!: (value: boolean) => void; - mocks.confirm.mockImplementationOnce(() => new Promise(resolve => { confirm = resolve; })); await render(); await click('delete-archived'); activateSurface('peer-one'); - await act(async () => confirm(true)); + await click('delete-archived-confirm'); expect(mocks.delete).not.toHaveBeenCalled(); expect(mocks.changed).not.toHaveBeenCalled(); expect(mocks.error).not.toHaveBeenCalled(); diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx index 29dc2f23b0..b46b2fd5e6 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/ArchivedSessionMenuItems.tsx @@ -6,11 +6,11 @@ import { flowChatManager } from '@/flow_chat/services/FlowChatManager'; import { flowChatStore } from '@/flow_chat/store/FlowChatStore'; import { requireSessionOwningWorkspaceId } from '@/flow_chat/utils/sessionOrdering'; import { sessionAPI } from '@/infrastructure/api/service-api/SessionAPI'; -import { confirmDanger } from '@/infrastructure/confirm-dialog'; import { useI18n } from '@/infrastructure/i18n'; import { getActiveSurfaceScope, isSurfaceChangedError } from '@/infrastructure/peer-device/deviceSurface'; import { notificationService } from '@/shared/notification-system'; import { createLogger } from '@/shared/utils/logger'; +import SessionDeleteMenuItem from './SessionDeleteMenuItem'; const log = createLogger('ArchivedSessionMenuItems'); @@ -41,12 +41,6 @@ export default function ArchivedSessionMenuItems({ session, title, workspaceName const sourceView = session.externalHistory?.mode === 'follow'; try { if (action === 'delete') { - const confirmed = await confirmDanger( - t(sourceView ? 'nav.sessions.removeSourceConfirmTitle' : 'nav.sessions.deleteArchivedConfirmTitle'), - t(sourceView ? 'nav.sessions.removeSourceConfirmMessage' : 'nav.sessions.deleteArchivedConfirmMessage', labels), - { confirmText: t('nav.sessions.deleteArchived') }, - ); - if (!confirmed) return; scope.assertCurrent('delete archived session'); if (activate) { if (!await activate()) return; @@ -104,15 +98,13 @@ export default function ArchivedSessionMenuItems({ session, title, workspaceName > {t('nav.sessions.restore')} - } - tone="danger" + { event.stopPropagation(); void runAction('delete'); }} - > - {t('nav.sessions.deleteArchived')} - + testId="nav-session-menu-delete-archived" + onConfirm={() => runAction('delete')} + /> ; } diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.scss b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.scss new file mode 100644 index 0000000000..004aff517f --- /dev/null +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.scss @@ -0,0 +1,15 @@ +.openbitfun-session-delete-menu__confirmation { + display: grid; + grid-template-columns: minmax(0, 1fr) var(--openbitfun-border-width-default) minmax(0, 1fr); + align-items: center; +} + +.openbitfun-session-delete-menu__button { + text-align: center; +} + +.openbitfun-session-delete-menu__divider { + align-self: stretch; + margin-block: var(--openbitfun-space-2); + background: var(--openbitfun-color-border-subtle); +} diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.test.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.test.tsx new file mode 100644 index 0000000000..4e94b08425 --- /dev/null +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.test.tsx @@ -0,0 +1,142 @@ +// @vitest-environment jsdom +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Menu, MenuItem } from '@openbitfun/ui'; +import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; + +const mocks = vi.hoisted(() => ({ delete: vi.fn(), error: vi.fn(), confirm: vi.fn() })); +vi.mock('@/flow_chat/services/FlowChatManager', () => ({ + flowChatManager: { deleteChatSession: mocks.delete }, +})); +vi.mock('@/infrastructure/services/business/workspaceManager', () => ({ workspaceManager: {} })); +vi.mock('@/shared/notification-system', () => ({ notificationService: {} })); +vi.mock('@/shared/utils/logger', () => ({ + createLogger: () => ({ error: mocks.error, warn: vi.fn(), info: vi.fn(), debug: vi.fn() }), +})); +vi.mock('@/infrastructure/confirm-dialog', () => ({ confirmDanger: mocks.confirm })); +vi.mock('@/infrastructure/i18n', async () => { + const { createTestI18nT } = await import('@/test/i18nTestUtils'); + return { useI18n: () => ({ t: createTestI18nT('common') }) }; +}); + +import SessionDeleteMenuItem from './SessionDeleteMenuItem'; +import { deleteSessionRow } from './sessionRowActions'; + +describe('session menu inline deletion confirmation', () => { + let container: HTMLDivElement; + let root: Root; + const description = 'This session and its child sessions will be permanently deleted.'; + const button = (action: string) => container.querySelector(`[data-testid="delete${action ? `-${action}` : ''}"]`)!; + const click = async (action = '') => { await act(async () => button(action).click()); }; + const render = async (open = true, sessionId = 'session-one') => { + await act(async () => root.render(open ? ( + + Archive + deleteSessionRow(sessionId)} + /> + + ) : null)); + }; + + beforeEach(async () => { + vi.resetAllMocks(); + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + resetDeviceSurfaceForTest(); + mocks.delete.mockResolvedValue(undefined); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + await render(); + }); + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + resetDeviceSurfaceForTest(); + vi.unstubAllGlobals(); + }); + + it('replaces only the delete row with Cancel and danger Confirm before deleting', async () => { + await click(); + expect([...container.querySelectorAll('[role="menuitem"]')].map(item => item.textContent)).toEqual(['Archive', 'Cancel', 'Confirm']); + expect(button('confirm').closest('[data-openbitfun-tone]')?.getAttribute('data-openbitfun-tone')).toBe('danger'); + expect(container.querySelector('[role="group"]')?.getAttribute('aria-label')).toBe(description); + expect(document.activeElement).toBe(button('cancel')); + expect(mocks.delete).not.toHaveBeenCalled(); + expect(mocks.confirm).not.toHaveBeenCalled(); + expect(container.querySelector('[role="dialog"], [role="alertdialog"]')).toBeNull(); + await click('confirm'); + expect(mocks.delete).toHaveBeenCalledExactlyOnceWith('session-one'); + }); + + it('restores the delete row and focus when Cancel is selected', async () => { + await click(); + await click('cancel'); + expect(button().textContent).toBe('Delete'); + expect(document.activeElement).toBe(button()); + expect(mocks.delete).not.toHaveBeenCalled(); + }); + + it('supports horizontal keyboard navigation and cancels with Escape', async () => { + await click(); + await act(async () => button('cancel').dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))); + expect(document.activeElement).toBe(button('confirm')); + await act(async () => button('confirm').dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))); + expect(document.activeElement).toBe(button()); + expect(mocks.delete).not.toHaveBeenCalled(); + }); + + it('forgets pending confirmation when the menu closes', async () => { + await click(); + await render(false); + await render(); + expect(button().textContent).toBe('Delete'); + expect(button('confirm')).toBeNull(); + expect(mocks.delete).not.toHaveBeenCalled(); + }); + + it('requires fresh confirmation when a retained menu targets another session', async () => { + await click(); + await render(true, 'session-two'); + expect(button('confirm')).toBeNull(); + expect(button().dataset.sessionId).toBe('session-two'); + await render(true, 'session-one'); + expect(button('confirm')).toBeNull(); + expect(mocks.delete).not.toHaveBeenCalled(); + await click(); + await click('confirm'); + expect(mocks.delete).toHaveBeenCalledExactlyOnceWith('session-one'); + }); + + it.each([false, true])('does not reuse confirmation after switching device (switch back: %s)', async switchBack => { + await click(); + activateSurface('peer-one'); + if (switchBack) activateSurface('local'); + await click('confirm'); + expect(mocks.delete).not.toHaveBeenCalled(); + expect(button().textContent).toBe('Delete'); + }); + + it('disables confirmation while deletion is pending and does not submit twice', async () => { + let finish!: () => void; + mocks.delete.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })); + await click(); + await click('confirm'); + expect(button('confirm').disabled).toBe(true); + expect(button('cancel').disabled).toBe(true); + await click('confirm'); + expect(mocks.delete).toHaveBeenCalledOnce(); + await act(async () => finish()); + }); + + it('handles a failed deletion without retrying the mutation', async () => { + const error = new Error('Host unavailable'); + mocks.delete.mockRejectedValueOnce(error); + await click(); + await click('confirm'); + expect(mocks.delete).toHaveBeenCalledOnce(); + expect(mocks.error).toHaveBeenCalledWith('Failed to delete session', { sessionId: 'session-one', error }); + }); +}); diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.tsx new file mode 100644 index 0000000000..0a54bfcc50 --- /dev/null +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionDeleteMenuItem.tsx @@ -0,0 +1,130 @@ +import { useLayoutEffect, useRef, useState } from 'react'; +import { Icon, MenuItem, MenuList } from '@openbitfun/ui'; +import { useI18n } from '@/infrastructure/i18n'; +import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; +import './SessionDeleteMenuItem.scss'; + +interface Props { + sessionId: string; + label: string; + description: string; + testId: string; + disabled?: boolean; + onConfirm: () => void | Promise; +} + +/** Replace the delete action with two controls in the same menu row. */ +export default function SessionDeleteMenuItem(props: Props) { + // A retained menu may be retargeted without closing. Its confirmation belongs + // to one session and must not authorize the next row, even when returning. + return ; +} + +function SessionDeleteConfirmation({ sessionId, label, description, testId, disabled, onConfirm }: Props) { + const { t } = useI18n('common'); + const [confirmation, setConfirmation] = useState | null>(null); + const [pending, setPending] = useState(false); + const pendingRef = useRef(false); + const deleteRef = useRef(null); + const cancelRef = useRef(null); + const confirmRef = useRef(null); + const restoreFocusRef = useRef(false); + + useLayoutEffect(() => { + if (confirmation) cancelRef.current?.focus(); + else if (restoreFocusRef.current) { + deleteRef.current?.focus(); + restoreFocusRef.current = false; + } + }, [confirmation]); + + const cancel = () => { + restoreFocusRef.current = true; + setConfirmation(null); + }; + + const confirm = async () => { + if (disabled || pendingRef.current || !confirmation) return; + if (!confirmation.isCurrent()) { + cancel(); + return; + } + pendingRef.current = true; + setPending(true); + try { + await onConfirm(); + } finally { + pendingRef.current = false; + setPending(false); + setConfirmation(null); + } + }; + + if (!confirmation) return ( + } + disabled={disabled} + title={description} + data-testid={testId} + data-session-id={sessionId} + onClick={event => { + event.stopPropagation(); + setConfirmation(getActiveSurfaceScope()); + }} + > + {label} + + ); + + return ( +
+ { + if (event.key === 'Escape' && !pending) { + event.preventDefault(); + event.stopPropagation(); + cancel(); + } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + event.preventDefault(); + event.stopPropagation(); + (event.key === 'ArrowLeft' ? cancelRef : confirmRef).current?.focus(); + } + }} + > + { event.stopPropagation(); cancel(); }} + > + {t('actions.cancel')} + + +
+ ); +} diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx index 91ba88ab3e..53b0809695 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/SessionsSection.tsx @@ -65,6 +65,7 @@ import { getWorkspaceSessionHierarchy } from './sessionNavHierarchy'; import { useWorkspaceSessionCatalog } from './useWorkspaceSessionCatalog'; import { useArchivedSessionMetadata } from './useArchivedSessionMetadata'; import ArchivedSessionMenuItems from './ArchivedSessionMenuItems'; +import SessionDeleteMenuItem from './SessionDeleteMenuItem'; import { captureWorkspaceSessionCatalogQuery, countPersistedWorkspaceCatalogSessions, resolveWorkspaceSessionCatalogSource, workspaceSessionCatalogQuery, workspaceSessionCatalogSources, workspaceSessionCatalogTotal } from './workspaceSessionCatalogQuery'; import { useWorkspaceSessionDiscovery } from './useWorkspaceSessionDiscovery'; import { useSessionNavExpansion } from './useSessionNavExpansion'; @@ -122,7 +123,7 @@ import { import { useSessionRowRemovalTransition } from './sessionRowShift'; import { SessionStatusIndicator } from './SessionStatusIndicator'; import { createSessionsNavSelector } from './sessionsNavSelector'; -import { archiveSessionRow, duplicateSessionRow, openWorktreeWorkspaceRow, renameSessionRow } from './sessionRowActions'; +import { archiveSessionRow, deleteSessionRow, duplicateSessionRow, openWorktreeWorkspaceRow, renameSessionRow } from './sessionRowActions'; import './SessionsSection.scss'; /** A limited flat list reads each workspace's newest rows in steps of this many. */ @@ -1929,6 +1930,13 @@ const SessionsSection: React.FC = ({ > {t('nav.sessions.archive')} + { closeSessionMenu(); return deleteSessionRow(session.sessionId); }} + /> )} , diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/appearance.ts b/src/web-ui/src/app/components/NavPanel/sections/sessions/appearance.ts index 7b2202e97c..0d9dff15a3 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/appearance.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/appearance.ts @@ -13,6 +13,7 @@ export const sessionsSectionAppearanceDescriptor: AppearanceSurfaceDescriptor = { id: 'edit' }, { id: 'actions' }, { id: 'menu' }, + { id: 'deleteConfirmation' }, { id: 'toggle' }, ], states: [ diff --git a/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionActionConfirmation.test.ts b/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionActionConfirmation.test.ts index 003bb4436b..afa6ae5d32 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionActionConfirmation.test.ts +++ b/src/web-ui/src/app/components/NavPanel/sections/sessions/sessionActionConfirmation.test.ts @@ -17,11 +17,16 @@ function sliceBetween(source: string, startMarker: string, endMarker: string): s } describe('session action confirmation policy', () => { - it('archives a single session immediately without delete or batch actions in its menu', () => { + it('archives immediately and offers deletion through the shared confirmation handler', () => { const source = readSource('./SessionsSection.tsx'); const archiveHandler = sliceBetween(source, 'const handleArchive = useCallback(', 'const handleDuplicateSession = useCallback('); - expect(source).not.toContain('data-testid="nav-session-menu-delete"'); + expect(source).toContain('testId="nav-session-menu-delete"'); + expect(source.indexOf('testId="nav-session-menu-delete"')).toBeGreaterThan( + source.indexOf('data-testid="nav-session-menu-archive"'), + ); + expect(source).toContain(') => string; +/** Delete after menu confirmation; the session module reports failures. */ +export async function deleteSessionRow(sessionId: string): Promise { + try { + await flowChatManager.deleteChatSession(sessionId); + } catch (error) { + if (isSurfaceChangedError(error)) return; + log.error('Failed to delete session', { sessionId, error }); + } +} + /** Archive a session; the archive module reports its own failures. */ export async function archiveSessionRow(sessionId: string, t: SessionRowTranslate): Promise { try { diff --git a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceProjectPermissionsDialog.tsx b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceProjectPermissionsDialog.tsx index 3bbe768df0..987b56f1e3 100644 --- a/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceProjectPermissionsDialog.tsx +++ b/src/web-ui/src/app/components/NavPanel/sections/workspaces/WorkspaceProjectPermissionsDialog.tsx @@ -1,4 +1,4 @@ -import { Alert, OverflowText, +import { captureConfirmationAnchor, Alert, OverflowText, Button, Icon, IconButton, @@ -190,13 +190,13 @@ function WorkspaceProjectPermissionsContent({ void Promise.all([loadGrants(), loadRules()]); }, [isOpen, loadGrants, loadRules, refreshKey]); - const handleRemovePermissionGrant = async (grant: PermissionGrant) => { + const handleRemovePermissionGrant = async (grant: PermissionGrant, trigger?: HTMLElement) => { if (!current() || !active.current || mutationRunning.current) return; const confirmationEpoch = dialogEpoch.current; const confirmed = await confirmDanger( t('projectPermissions.removeGrantTitle'), t('projectPermissions.removeGrantMessage', { action: grant.action, resource: grant.resource }), - { confirmText: t('projectPermissions.removeGrantConfirm') }, + { anchor: captureConfirmationAnchor(trigger), confirmText: t('projectPermissions.removeGrantConfirm') }, ); if (!confirmed || !current() || !active.current || confirmationEpoch !== dialogEpoch.current || mutationRunning.current) { return; @@ -500,7 +500,7 @@ function WorkspaceProjectPermissionsContent({
{effectPill('allow')}
{t('projectPermissions.grantsTitle')}
void handleRemovePermissionGrant(grant)} icon={} /> + onClick={event => void handleRemovePermissionGrant(grant, event.currentTarget)} icon={} />
)} {complete && draftRules.length + permissionGrants.length === 0 &&
{t('projectPermissions.empty')}
} diff --git a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx index dc206a2696..6a6dc0a51b 100644 --- a/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx +++ b/src/web-ui/src/app/components/RemoteConnectDialog/AccountPanel.tsx @@ -1,7 +1,7 @@ import { refreshDeviceDirectory, isDeviceControllable, deviceClientVersion } from '@/infrastructure/account/deviceDirectory'; /** Account login and linked-device management. */ -import { OverflowText, Alert, Avatar, Button, Icon, IconButton, Input, ScrollArea } from '@openbitfun/ui'; +import { captureConfirmationAnchor, OverflowText, Alert, Avatar, Button, Icon, IconButton, Input, ScrollArea } from '@openbitfun/ui'; import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; import { useI18n } from '@/infrastructure/i18n'; import { @@ -672,7 +672,7 @@ export const AccountPanel: React.FC = () => { } }, [invalidateAccountRequests, isAccountEpochCurrent, reportAccountFailure, resetState]); - const handleDeleteDevice = useCallback(async (deviceId: string, deviceName: string) => { + const handleDeleteDevice = useCallback(async (deviceId: string, deviceName: string, trigger?: HTMLElement) => { const isLocal = localDeviceId === deviceId; const confirmation = isLocal ? t('accountLogin.confirmRemoveCurrentDevice', { name: deviceName }) @@ -683,6 +683,7 @@ export const AccountPanel: React.FC = () => { : t('accountLogin.removeDevice'), confirmation, { + anchor: captureConfirmationAnchor(trigger), confirmText: isLocal ? t('accountLogin.removeCurrentDevice') : t('accountLogin.removeDevice'), @@ -1026,7 +1027,7 @@ export const AccountPanel: React.FC = () => { aria-label={`${removeLabel}: ${displayName}`} disabled={loading || savingAliasId !== null} icon={} - onClick={(e) => { e.stopPropagation(); handleDeleteDevice(d.device_id, displayName); }} + onClick={(e) => { e.stopPropagation(); handleDeleteDevice(d.device_id, displayName, e.currentTarget); }} size="xs" title={removeLabel} variant="quiet" diff --git a/src/web-ui/src/app/components/scheduled-jobs/ScheduledJobsView.tsx b/src/web-ui/src/app/components/scheduled-jobs/ScheduledJobsView.tsx index 0bf7995fca..d90e656bf4 100644 --- a/src/web-ui/src/app/components/scheduled-jobs/ScheduledJobsView.tsx +++ b/src/web-ui/src/app/components/scheduled-jobs/ScheduledJobsView.tsx @@ -5,7 +5,7 @@ * job list at top, inline editor expands below the selected job. */ -import { Alert, OverflowText, Icon, Button, Combobox, Switch, IconButton, Input, Select, StatusPill, Textarea, Tooltip, Dialog, DialogBody, DialogClose, DialogFooter, DialogHeader, DialogHeading, DialogTitle, Field } from '@openbitfun/ui'; +import { captureConfirmationAnchor, Alert, OverflowText, Icon, Button, Combobox, Switch, IconButton, Input, Select, StatusPill, Textarea, Tooltip, Dialog, DialogBody, DialogClose, DialogFooter, DialogHeader, DialogHeading, DialogTitle, Field } from '@openbitfun/ui'; import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { usePeerDeviceModeOptional } from '@/infrastructure/peer-device/peerDeviceContextState'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; @@ -481,11 +481,12 @@ const ScheduledJobsView: React.FC = ({ targetKind, ]); - const handleDeleteJob = useCallback(async (job: CronJob) => { + const handleDeleteJob = useCallback(async (job: CronJob, trigger?: HTMLElement) => { const scope = getActiveSurfaceScope(); const confirmed = await confirmDanger( t('nav.scheduledJobs.deleteDialog.title', { name: job.name }), null, + { anchor: captureConfirmationAnchor(trigger) }, ); if (!confirmed || !mounted.current || !scope.isCurrent()) return; try { @@ -738,7 +739,7 @@ const ScheduledJobsView: React.FC = ({ } onClick={() => handleEditJob(job)} /> } onClick={() => void handleDeleteJob(job)} /> + icon={} onClick={event => void handleDeleteJob(job, event.currentTarget)} /> {expandedJobId === job.id &&
{renderEditor()}
} @@ -792,7 +793,7 @@ const ScheduledJobsView: React.FC = ({ size="sm" tone="danger" aria-label={t('nav.scheduledJobs.actions.delete')} - onClick={e => { e.stopPropagation(); void handleDeleteJob(job); }} + onClick={e => { e.stopPropagation(); void handleDeleteJob(job, e.currentTarget); }} icon={} /> diff --git a/src/web-ui/src/app/scenes/agents/AgentsScene.tsx b/src/web-ui/src/app/scenes/agents/AgentsScene.tsx index 427349fb99..30d0685884 100644 --- a/src/web-ui/src/app/scenes/agents/AgentsScene.tsx +++ b/src/web-ui/src/app/scenes/agents/AgentsScene.tsx @@ -1,5 +1,5 @@ import { isPrimaryAgent, isOrdinaryAgent } from './agentVisibility'; -import { +import { captureConfirmationAnchor, Button, Combobox, Dialog, DialogBody, DialogClose, DialogFooter, DialogHeader, DialogHeaderActions, DialogHeading, DialogTitle, Field, FormSection, Icon, IconButton, SearchField, Select, StatusPill, Toolbar, Tooltip, @@ -623,7 +623,7 @@ const AgentsHomeView: React.FC = () => { } }, [activeDetailSection, selectedAgentCapabilities]); - const handleDeleteCustomAgent = useCallback(async () => { + const handleDeleteCustomAgent = useCallback(async (trigger?: HTMLElement) => { if (!selectedAgent) return; if (['builtin', 'external'].includes( selectedAgent.source ?? selectedAgent.subagentSource ?? 'builtin', @@ -635,6 +635,7 @@ const AgentsHomeView: React.FC = () => { const ok = await confirmDanger( t('agentsOverview.deleteAgent'), t('agentsOverview.deleteConfirm', { name }), + { anchor: captureConfirmationAnchor(trigger) }, ); if (!ok) return; setDeletingAgent(true); @@ -982,7 +983,7 @@ const AgentsHomeView: React.FC = () => { aria-label={t('agentsOverview.deleteAgent')} size="sm" loading={deletingAgent} - onClick={() => void handleDeleteCustomAgent()} + onClick={event => void handleDeleteCustomAgent(event.currentTarget)} icon={} /> diff --git a/src/web-ui/src/app/scenes/agents/components/ToolGroupPicker.tsx b/src/web-ui/src/app/scenes/agents/components/ToolGroupPicker.tsx index fcdb721fe8..5aa2c45f08 100644 --- a/src/web-ui/src/app/scenes/agents/components/ToolGroupPicker.tsx +++ b/src/web-ui/src/app/scenes/agents/components/ToolGroupPicker.tsx @@ -1,4 +1,4 @@ -import { +import { captureConfirmationAnchor, OverflowText, Checkbox, DialogFooter, @@ -236,11 +236,11 @@ const GroupManagerModal: React.FC = ({ } }; - const deleteGroup = async (group: UserToolGroup) => { + const deleteGroup = async (group: UserToolGroup, trigger?: HTMLElement) => { const confirmed = await confirmDanger( t('agentsOverview.toolGroups.deleteTitle'), t('agentsOverview.toolGroups.deleteMessage', { name: group.name }), - { confirmText: t('agentsOverview.toolGroups.deleteConfirm') }, + { anchor: captureConfirmationAnchor(trigger), confirmText: t('agentsOverview.toolGroups.deleteConfirm') }, ); if (!confirmed) { return; @@ -409,7 +409,7 @@ const GroupManagerModal: React.FC = ({ size="sm" tone="danger" aria-label={t('agentsOverview.toolGroups.deleteGroup')} - onClick={() => void deleteGroup(group)} + onClick={event => void deleteGroup(group, event.currentTarget)} disabled={saving} icon={} /> diff --git a/src/web-ui/src/app/scenes/miniapps/MiniAppScene.tsx b/src/web-ui/src/app/scenes/miniapps/MiniAppScene.tsx index b06c245a54..3f0b439cd6 100644 --- a/src/web-ui/src/app/scenes/miniapps/MiniAppScene.tsx +++ b/src/web-ui/src/app/scenes/miniapps/MiniAppScene.tsx @@ -2,7 +2,7 @@ * MiniAppScene — standalone scene tab for a single MiniApp. * Mounts MiniAppRunner; transfers keep work, closing the final view stops the app. */ -import { Button, ConfirmDialog, Icon, IconButton, Tooltip } from '@openbitfun/ui'; +import { captureConfirmationAnchor, Button, ConfirmDialog, Icon, IconButton, Tooltip } from '@openbitfun/ui'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { Loader2, AlertTriangle, SquareArrowOutUpRight, MessageSquare } from 'lucide-react'; import { miniAppAPI } from '@/infrastructure/api/service-api/MiniAppAPI'; @@ -72,6 +72,7 @@ const MiniAppScene: React.FC = ({ appId }) => { const [strictRuntime, setStrictRuntime] = useState(false); const [key, setKey] = useState(0); const [customizeOpen, setCustomizeOpen] = useState(false); + const [windowAnchor, setWindowAnchor] = useState>(undefined); const [windowConfirm, setWindowConfirm] = useState(false); const [presentationNotice, setPresentationNotice] = useState(null); const [presentationBusy, setPresentationBusy] = useState(false); @@ -226,14 +227,14 @@ const MiniAppScene: React.FC = ({ appId }) => { setWindowConfirm(true)} aria-label={t('presentation.openWindow')} + onClick={event => { setWindowAnchor(captureConfirmationAnchor(event.currentTarget)); setWindowConfirm(true); }} aria-label={t('presentation.openWindow')} icon={} /> {app && } {presentationNotice &&
{presentationNotice}
} - void openWindow()} + void openWindow()} title={t('presentation.openWindow')} message={t('presentation.transferWarning')} confirmText={t('presentation.openWindow')} cancelText={t('confirmDelete.cancel')} />
void; - onOpen: (appId: string) => void; + onOpen: (appId: string, trigger?: HTMLElement) => void; launchActions?: React.ReactNode; systemAppActions?: React.ReactNode; - onDelete: (appId: string) => void; + onDelete: (appId: string, trigger?: HTMLElement) => void; onStop?: (appId: string) => void | Promise; } @@ -207,13 +207,13 @@ const MiniAppDetailModal: React.FC = ({ actions={<> {systemAppActions} - {launchActions ?? } {snapshot.isActive && onStop && } - + } preview={showcase ? : undefined} @@ -370,7 +370,7 @@ const MiniAppDetailModal: React.FC = ({ variant="primary" size="md" className="miniapp-detail-modal__primary" - onClick={() => onOpen(displayedApp.id)} + onClick={event => onOpen(displayedApp.id, event.currentTarget)} data-testid="miniapp-detail-primary-action" leadingIcon={} > @@ -382,7 +382,7 @@ const MiniAppDetailModal: React.FC = ({ variant="outline" size="md" className="miniapp-detail-modal__delete" - onClick={() => onDelete(displayedApp.id)} + onClick={event => onDelete(displayedApp.id, event.currentTarget)} data-testid="miniapp-detail-delete" leadingIcon={} > diff --git a/src/web-ui/src/app/scenes/miniapps/components/MiniAppInstalledCard.tsx b/src/web-ui/src/app/scenes/miniapps/components/MiniAppInstalledCard.tsx index 3b22420548..d1c0aec453 100644 --- a/src/web-ui/src/app/scenes/miniapps/components/MiniAppInstalledCard.tsx +++ b/src/web-ui/src/app/scenes/miniapps/components/MiniAppInstalledCard.tsx @@ -14,9 +14,9 @@ interface MiniAppInstalledCardProps { itemKey: string; statuses: MiniAppLibraryStatus[]; onOpenDetails: () => void; - onLaunch: () => void; + onLaunch: (trigger?: HTMLElement) => void; onAddToSystem: () => Promise; - onDelete: () => void; + onDelete: (trigger?: HTMLElement) => void; systemAppSupported: boolean; launchDisabled?: boolean; launchDisabledReason?: string; @@ -64,7 +64,7 @@ export default function MiniAppInstalledCard({ leading={renderMiniAppIcon(app.icon || 'box', 32)} actions={[ { id: 'launch', label: t('card.start'), tooltip: launchDisabledReason ?? t('card.start'), - icon: , disabled: launchDisabled || actionsDisabled, loading: busy, onClick: onLaunch }, + icon: , disabled: launchDisabled || actionsDisabled, loading: busy, onClick: event => onLaunch(event.currentTarget) }, { id: 'more', label: t('presentation.moreActions'), tooltip: t('presentation.moreActions'), icon: , disabled: actionsDisabled, loading: addingToSystem, 'aria-haspopup': 'menu', 'aria-expanded': menuOpen, 'aria-controls': menuOpen ? menuId : undefined, diff --git a/src/web-ui/src/app/scenes/miniapps/components/MiniAppLaunchActions.tsx b/src/web-ui/src/app/scenes/miniapps/components/MiniAppLaunchActions.tsx index 8e3fcb9ff3..34ba9f0516 100644 --- a/src/web-ui/src/app/scenes/miniapps/components/MiniAppLaunchActions.tsx +++ b/src/web-ui/src/app/scenes/miniapps/components/MiniAppLaunchActions.tsx @@ -3,8 +3,8 @@ import { forwardRef, useRef, useState } from 'react'; import { useI18n } from '@/infrastructure/i18n'; interface MiniAppLaunchActionsProps { - onOpenTab: () => void; - onOpenWindow: () => void; + onOpenTab: (trigger?: HTMLElement) => void; + onOpenWindow: (trigger?: HTMLElement) => void; disabled?: boolean; windowSupported: boolean; busy?: boolean; @@ -38,11 +38,11 @@ export function MiniAppLaunchActions({ onOpenTab, onOpenWindow, disabled, window ]} /> ; return <> - - diff --git a/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.test.tsx b/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.test.tsx index 45a9593b12..7813f7801b 100644 --- a/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.test.tsx +++ b/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.test.tsx @@ -2,6 +2,7 @@ import React, { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { activateSurface, resetDeviceSurfaceForTest } from '@/infrastructure/peer-device/deviceSurface'; import { WorkspaceKind, type WorkspaceInfo } from '@/shared/types'; import type { MiniAppInstanceSnapshot, MiniAppViewKind } from '@/infrastructure/api/service-api/MiniAppPresentationAPI'; @@ -99,6 +100,25 @@ describe('MiniApp catalog launch choices', () => { expect(mocks.open).not.toHaveBeenCalled(); }); + it('retains the explicit action origin across snapshot loading and menu removal', async () => { + let finish!: (value: MiniAppInstanceSnapshot) => void; + mocks.snapshot.mockReturnValueOnce(new Promise(resolve => { finish = resolve; })); + const trigger = document.createElement('button'); + document.body.append(trigger); + trigger.getBoundingClientRect = () => new DOMRect(140, 80, 40, 30); + const anchor = captureConfirmationAnchor(trigger); + await render(); + let pending!: Promise; + await act(async () => { pending = launch.openApp('notes', 'tab', undefined, anchor); }); + trigger.remove(); + await act(async () => { finish(snapshot('window')); await pending; }); + expect(launch.transfer?.anchor).toBe(anchor); + expect(launch.transfer?.anchor?.rect).toMatchObject({ left: 140, top: 80, bottom: 110 }); + expect(mocks.open).not.toHaveBeenCalled(); + await act(async () => { await launch.confirmTransfer(); }); + expect(mocks.open).toHaveBeenCalledExactlyOnceWith('notes', 'tab', '/pinned', undefined); + }); + it.each([false, true])('sends the catalog glyph for native launch, including confirmed transfers: %s', async transfer => { mocks.snapshot.mockResolvedValue(snapshot(transfer ? 'tab' : undefined)); await render(); diff --git a/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.ts b/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.ts index e864c1f52b..62740707db 100644 --- a/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.ts +++ b/src/web-ui/src/app/scenes/miniapps/hooks/useMiniAppLaunch.ts @@ -1,3 +1,4 @@ +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { useRef, useState } from 'react'; import { useSceneStore } from '@/app/stores/sceneStore'; import { hasLocalMiniAppPresentation, miniAppPresentationAPI, type MiniAppViewKind } from '@/infrastructure/api/service-api/MiniAppPresentationAPI'; @@ -16,6 +17,7 @@ interface Transfer { kind: MiniAppViewKind; workspacePath: string | null; iconSvg?: string; + anchor?: ReturnType; } /** Launch choice belongs to the catalog, before either presentation is created. */ @@ -52,7 +54,7 @@ export function useMiniAppLaunch() { } }; - const openApp = (appId: string, kind: MiniAppViewKind = 'tab', icon?: string) => run(appId, async () => { + const openApp = (appId: string, kind: MiniAppViewKind = 'tab', icon?: string, anchor?: ReturnType) => run(appId, async () => { if (!supported) { if (kind === 'window') { notification.error(t('presentation.unsupported')); @@ -69,7 +71,7 @@ export function useMiniAppLaunch() { useMiniAppPresentationStore.getState().apply(snapshot); const instance = snapshot.instances.find(candidate => candidate.appId === appId); const request = { - appId, kind, workspacePath: instance ? instance.workspacePath : workspacePath || null, + anchor, appId, kind, workspacePath: instance ? instance.workspacePath : workspacePath || null, iconSvg: kind === 'window' && icon ? renderMiniAppSystemIcon(icon) : undefined, }; if (instance?.primaryView && instance.primaryView.kind !== kind) { diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx index c4649bb5cc..121f7e5acb 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx @@ -19,7 +19,7 @@ import { type MarketPackageInspection, } from '@/infrastructure/api/service-api/MiniAppMarketAPI'; import { createLogger } from '@/shared/utils/logger'; -import { subscribeOverlayInteraction, createOverlayPortal, +import { captureConfirmationAnchor, subscribeOverlayInteraction, createOverlayPortal, ConfirmDialog, Icon, IconButton, @@ -78,6 +78,7 @@ const MiniAppGalleryView: React.FC = ({ tabs }) => { const [search, setSearch] = useState(''); const [categoryFilter, setCategoryFilter] = useState('all'); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [pendingDeleteId, setPendingDeleteId] = useState(null); const [selectedApp, setSelectedApp] = useState(null); const [pendingPackage, setPendingPackage] = useState<{ @@ -202,7 +203,8 @@ const MiniAppGalleryView: React.FC = ({ tabs }) => { [activityById, closeScene, currentLanguage, markWorkerStopped, notification, t] ); - const handleDeleteRequest = (appId: string) => { + const handleDeleteRequest = (appId: string, trigger?: HTMLElement) => { + setDeleteAnchor(captureConfirmationAnchor(trigger)); setPendingDeleteId(appId); }; @@ -556,6 +558,7 @@ const MiniAppGalleryView: React.FC = ({ tabs }) => { /> setPendingDeleteId(null)} onConfirm={handleDeleteConfirm} diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx index 0678f643d5..70e646634f 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.navigation.test.tsx @@ -190,7 +190,7 @@ describe('MiniApp detail page navigation', () => { expect(mocks.openApp).not.toHaveBeenCalled(); await act(async () => button('detail.back').click()); await act(async () => launch.click()); - expect(mocks.openApp).toHaveBeenCalledWith('notes', 'tab', 'box'); + expect(mocks.openApp).toHaveBeenCalledWith('notes', 'tab', 'box', expect.objectContaining({ element: expect.any(HTMLButtonElement) })); expect(page()).toBeNull(); expect(mocks.getListing).not.toHaveBeenCalled(); @@ -236,8 +236,9 @@ describe('MiniApp detail page navigation', () => { const menu = document.querySelector('[role="menu"][aria-label="detail.start"]')!; expect(menu).not.toBeNull(); await act(async () => button(kind === 'tab' ? 'presentation.openTab' : 'presentation.openWindow', menu).click()); - expect(mocks.openApp).toHaveBeenCalledExactlyOnceWith('notes', kind, 'box'); - expect(page()).toBeNull(); + expect(mocks.openApp).toHaveBeenCalledExactlyOnceWith('notes', kind, 'box', expect.objectContaining({ element: expect.any(HTMLButtonElement) })); + // Keep the action's context mounted while the host checks for a transfer. + expect(page()?.querySelector('h1')?.textContent).toBe('Notes'); }); it('disables the independent-window menu choice on remote surfaces and permits in-app launch', async () => { @@ -250,7 +251,7 @@ describe('MiniApp detail page navigation', () => { await act(async () => windowChoice.click()); expect(mocks.openApp).not.toHaveBeenCalled(); await act(async () => button('presentation.openTab', menu).click()); - expect(mocks.openApp).toHaveBeenCalledExactlyOnceWith('notes', 'tab', 'box'); + expect(mocks.openApp).toHaveBeenCalledExactlyOnceWith('notes', 'tab', 'box', expect.objectContaining({ element: expect.any(HTMLButtonElement) })); }); it('requires confirmation before uninstalling from details', async () => { diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx index fecffd6282..1ef2a0c746 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx @@ -1,4 +1,4 @@ -import { subscribeOverlayInteraction, createOverlayPortal, +import { captureConfirmationAnchor, subscribeOverlayInteraction, createOverlayPortal, Button, ConfirmDialog, Icon, @@ -154,6 +154,7 @@ const MiniAppLibraryContent: React.FC = ({ const [busyListingId, setBusyListingId] = useState(); const [installPrompt, setInstallPrompt] = useState(false); const [releasesExpanded, setReleasesExpanded] = useState(false); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [pendingDeleteId, setPendingDeleteId] = useState(null); const [selectedApp, setSelectedApp] = useState(initialDetailApp ?? null); const selectedInstance = presentationSnapshot?.instances.find(instance => instance.appId === selectedApp?.id); @@ -251,11 +252,10 @@ const MiniAppLibraryContent: React.FC = ({ ]), [activityById, presentationSnapshot]); const customizingIdSet = useMemo(() => new Set(customizingAppIds), [customizingAppIds]); - const handleOpenApp = (appId: string, kind: 'tab' | 'window' = 'tab') => { + const handleOpenApp = (appId: string, kind: 'tab' | 'window' = 'tab', trigger?: HTMLElement) => { const icon = useMiniAppStore.getState().apps.find(app => app.id === appId)?.icon ?? (selectedApp?.id === appId ? selectedApp.icon : undefined); - closeDetail(); - void launch.openApp(appId, kind, icon); + void launch.openApp(appId, kind, icon, captureConfirmationAnchor(trigger)); }; const handleAddToSystem = async (app: MiniAppMeta) => { @@ -270,8 +270,8 @@ const MiniAppLibraryContent: React.FC = ({ disabled={disabled} busy={launch.busyAppIds.includes(appId)} windowSupported={launch.supported} - onOpenTab={() => handleOpenApp(appId, 'tab')} - onOpenWindow={() => handleOpenApp(appId, 'window')} + onOpenTab={trigger => handleOpenApp(appId, 'tab', trigger)} + onOpenWindow={trigger => handleOpenApp(appId, 'window', trigger)} /> ); @@ -721,9 +721,9 @@ const MiniAppLibraryContent: React.FC = ({ if (item.listing) void openMarketDetail(item.listing); else openInstalledDetail(app); }} - onLaunch={() => handleOpenApp(app.id)} + onLaunch={trigger => handleOpenApp(app.id, 'tab', trigger)} onAddToSystem={() => handleAddToSystem(app)} - onDelete={() => setPendingDeleteId(app.id)} + onDelete={trigger => { setDeleteAnchor(captureConfirmationAnchor(trigger)); setPendingDeleteId(app.id); }} systemAppSupported={launch.supported} busy={launch.busyAppIds.includes(app.id)} launchDisabled={workspaceUnsupported} @@ -1022,12 +1022,12 @@ const MiniAppLibraryContent: React.FC = ({ isActive={selectedApp ? activeIdSet.has(selectedApp.id) : false} isCustomizing={selectedApp ? customizingIdSet.has(selectedApp.id) : false} onClose={closeDetail} - onOpen={handleOpenApp} + onOpen={(id, trigger) => handleOpenApp(id, 'tab', trigger)} launchActions={selectedApp ? renderLaunchActions(selectedApp.id, Boolean(workspace && isRemoteWorkspace(workspace) && requiresWorkspace(selectedApp.permissions)), 'menu') : undefined} systemAppActions={selectedApp ? : undefined} - onDelete={setPendingDeleteId} + onDelete={(id, trigger) => { setDeleteAnchor(captureConfirmationAnchor(trigger)); setPendingDeleteId(id); }} onStop={handleStopRunning} /> @@ -1205,6 +1205,7 @@ const MiniAppLibraryContent: React.FC = ({ } setPendingDeleteId(null)} onConfirm={handleDeleteConfirm} @@ -1220,6 +1221,7 @@ const MiniAppLibraryContent: React.FC = ({ /> { if (!open) launch.cancelTransfer(); }} title={launch.transfer?.kind === 'window' ? t('presentation.openWindow') : t('presentation.openTab')} diff --git a/src/web-ui/src/app/scenes/pages/PagesScene.tsx b/src/web-ui/src/app/scenes/pages/PagesScene.tsx index 6cf205b607..48bea95b5f 100644 --- a/src/web-ui/src/app/scenes/pages/PagesScene.tsx +++ b/src/web-ui/src/app/scenes/pages/PagesScene.tsx @@ -1,5 +1,5 @@ import { lazyWithRecovery } from '@/shared/utils/lazyWithRecovery'; -import { OverflowText, Button, Icon, Input, Select, type SelectOption } from '@openbitfun/ui'; +import { captureConfirmationAnchor, OverflowText, Button, Icon, Input, Select, type SelectOption } from '@openbitfun/ui'; import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { CircleStop, FileClock, HardDrive, Lock, PanelsTopLeft, Rocket, Save, Users, type LucideIcon } from 'lucide-react'; import { RetainedMountBoundary } from '@/shared/presence'; @@ -613,12 +613,13 @@ const PagesScene: React.FC = ({ isActive = true }) => { page: PageInfo, ownerEpoch: number, version: PageVersionInfo, + trigger?: HTMLElement, ) => { if (version.deployed) return; const confirmed = await confirmDanger( t('confirm.deleteVersionTitle'), t('confirm.deleteVersionMessage', { version: version.version_id, title: page.title }), - { confirmText: t('actions.deleteVersion') }, + { anchor: captureConfirmationAnchor(trigger), confirmText: t('actions.deleteVersion') }, ); if (!confirmed) return; const key = `delete-version:${page.slug}:${version.version_id}`; @@ -646,11 +647,11 @@ const PagesScene: React.FC = ({ isActive = true }) => { } }, [beginPageAction, endPageAction, notification, t, validatePageAction]); - const deletePage = useCallback(async (page: PageInfo, ownerEpoch: number) => { + const deletePage = useCallback(async (page: PageInfo, ownerEpoch: number, trigger?: HTMLElement) => { const confirmed = await confirmDanger( t('confirm.deletePageTitle'), t('confirm.deletePageMessage', { title: page.title, slug: page.slug }), - { confirmText: t('actions.deletePage') }, + { anchor: captureConfirmationAnchor(trigger), confirmText: t('actions.deletePage') }, ); if (!confirmed) return; const key = `delete-page:${page.slug}`; @@ -980,7 +981,7 @@ const PagesScene: React.FC = ({ isActive = true }) => { variant="fill" tone="danger" size="sm" - onClick={() => void deletePage(page, pageOwnerEpoch)} + onClick={event => void deletePage(page, pageOwnerEpoch, event.currentTarget)} disabled={pageBusy} loading={pendingAction === `delete-page:${page.slug}`} leadingIcon={} @@ -1072,7 +1073,7 @@ const PagesScene: React.FC = ({ isActive = true }) => { variant="fill" tone="danger" size="sm" - onClick={() => void deleteVersion(page, pageOwnerEpoch, version)} + onClick={event => void deleteVersion(page, pageOwnerEpoch, version, event.currentTarget)} disabled={pageBusy} loading={pendingAction === `delete-version:${page.slug}:${version.version_id}`} aria-label={t('actions.deleteVersionAria', { version: version.version_id })} diff --git a/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx b/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx index 2fe8010abf..cab8cf00da 100644 --- a/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/OverviewDesktopCardsSection.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useState } from 'react'; import { Eye, EyeOff, Pin, PinOff, Settings, Trash2 } from 'lucide-react'; -import { Button, Icon, IconButton, OverflowText } from '@openbitfun/ui'; +import { captureConfirmationAnchor, Button, Icon, IconButton, OverflowText } from '@openbitfun/ui'; import { desktopCardAPI, hasDesktopPinFailure, @@ -104,11 +104,11 @@ export function OverviewDesktopCardsSection({ isActive }: { isActive: boolean }) } }; - const deleteCard = async (card: DesktopCardRecord) => { + const deleteCard = async (card: DesktopCardRecord, trigger?: HTMLElement) => { const confirmed = await confirmDanger( t('desktopCards.deleteConfirmTitle'), t('desktopCards.deleteConfirmMessage', { title: card.title }), - { confirmText: t('desktopCards.delete') }, + { anchor: captureConfirmationAnchor(trigger), confirmText: t('desktopCards.delete') }, ); if (!confirmed) return; setBusyCardId(card.id); @@ -194,7 +194,7 @@ export function OverviewDesktopCardsSection({ isActive }: { isActive: boolean }) icon={} onClick={() => void toggleVisible(card)} /> } onClick={() => void deleteCard(card)} /> + icon={} onClick={event => void deleteCard(card, event.currentTarget)} /> ); })} diff --git a/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.actions.test.tsx b/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.actions.test.tsx index c9934648d5..b638a2204c 100644 --- a/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.actions.test.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.actions.test.tsx @@ -104,10 +104,6 @@ const click = async (id: string) => { const clickDialogButton = (label: string) => act(async () => { [...document.querySelectorAll('[role="dialog"] button')].find(button => button.textContent === label)!.click(); }); -const answerAssistantConfirmation = (confirm: boolean) => act(async () => { - const label = confirm ? 'agents.createAssistant' : 'dialog.confirm.cancel'; - [...document.querySelectorAll('[role="alertdialog"] button')].find(button => button.textContent === label)!.click(); -}); const fillAgentField = async (field: string, value: string, scope: ParentNode = document.querySelector('[role="dialog"]')!) => { if (field === 'prompt') { await act(async () => { await vi.dynamicImportSettled(); }); @@ -304,13 +300,10 @@ describe('overview catalog actions', () => { expect(mocks.openScene).not.toHaveBeenCalled(); }); - it('requires confirmation before creating an assistant and opening its configuration', async () => { + it('creates an assistant directly and opens its configuration', async () => { await render(); await click('personal-overview-create-assistant'); - expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('agents.createAssistantConfirmMessage'); - expect(mocks.createAssistant).not.toHaveBeenCalled(); - expect(mocks.openScene).not.toHaveBeenCalled(); - await answerAssistantConfirmation(true); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); expect(mocks.createAssistant).toHaveBeenCalledOnce(); expect(useNurseryStore.getState()).toMatchObject({ page: 'assistant', activeWorkspaceId: 'new-assistant' }); expect(mocks.openScene).toHaveBeenCalledWith('assistant'); @@ -318,29 +311,30 @@ describe('overview catalog actions', () => { expect(useNurseryStore.getState().page).toBe('gallery'); }); - it('cancels assistant creation without creating or navigating and allows retry', async () => { + it('allows retry after assistant creation fails', async () => { + mocks.createAssistant.mockRejectedValueOnce(new Error('Host unavailable')); await render(); await click('personal-overview-create-assistant'); - await answerAssistantConfirmation(false); - expect(mocks.createAssistant).not.toHaveBeenCalled(); + expect(mocks.error).toHaveBeenCalledOnce(); expect(mocks.openScene).not.toHaveBeenCalled(); expect(useNurseryStore.getState().page).toBe('gallery'); await click('personal-overview-create-assistant'); - await answerAssistantConfirmation(true); - expect(mocks.createAssistant).toHaveBeenCalledOnce(); + expect(mocks.createAssistant).toHaveBeenCalledTimes(2); + expect(mocks.openScene).toHaveBeenCalledWith('assistant'); }); - it('does not create an assistant if the device changes while confirmation is open', async () => { + it('ignores an assistant creation failure from a previous device', async () => { + let fail!: (error: Error) => void; + mocks.createAssistant.mockReturnValue(new Promise((_resolve, reject) => { fail = reject; })); await render(); await click('personal-overview-create-assistant'); - await act(async () => { activateSurface('peer-host'); }); - await answerAssistantConfirmation(true); - expect(mocks.createAssistant).not.toHaveBeenCalled(); + await act(async () => { activateSurface('peer-host'); fail(new Error('Old host unavailable')); }); + expect(mocks.createAssistant).toHaveBeenCalledOnce(); expect(mocks.openScene).not.toHaveBeenCalled(); expect(mocks.error).not.toHaveBeenCalled(); }); - it('creates only once when the entry and confirmation are clicked repeatedly', async () => { + it('creates only once when the entry is clicked repeatedly', async () => { let finish!: (workspace: { id: string }) => void; mocks.createAssistant.mockReturnValue(new Promise(resolve => { finish = resolve; })); await render(); @@ -349,14 +343,9 @@ describe('overview catalog actions', () => { button.click(); button.click(); }); - expect(mocks.createAssistant).not.toHaveBeenCalled(); - await act(async () => { - const button = [...document.querySelectorAll('[role="alertdialog"] button')].find(button => button.textContent === 'agents.createAssistant')!; - button.click(); - button.click(); - }); await click('personal-overview-create-assistant'); expect(mocks.createAssistant).toHaveBeenCalledOnce(); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); await act(async () => { finish({ id: 'new-assistant' }); }); expect(mocks.openScene).toHaveBeenCalledOnce(); }); @@ -366,7 +355,6 @@ describe('overview catalog actions', () => { mocks.createAssistant.mockReturnValue(new Promise(resolve => { finish = resolve; })); await render(); await click('personal-overview-create-assistant'); - await answerAssistantConfirmation(true); await act(async () => { activateSurface('peer-host'); finish({ id: 'old-assistant' }); }); expect(mocks.openScene).not.toHaveBeenCalled(); expect(useNurseryStore.getState().page).toBe('gallery'); diff --git a/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx b/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx index cde3d9f860..2e71c8be11 100644 --- a/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx +++ b/src/web-ui/src/app/scenes/personal-overview/PersonalOverviewScene.tsx @@ -4,7 +4,6 @@ import { useSubagentAvatarMotion } from '@openbitfun/ui/brand'; import { useAccountIdentity } from '@/infrastructure/account-identity/useAccountIdentity'; import { useI18n } from '@/infrastructure/i18n/hooks/useI18n'; import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext'; -import { confirmDialog } from '@/infrastructure/confirm-dialog'; import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; import type { MiniAppMeta } from '@/infrastructure/api/service-api/MiniAppAPI'; import { useNotification } from '@/shared/notification-system'; @@ -130,14 +129,6 @@ const PersonalOverviewScene: React.FC<{ isActive?: boolean }> = ({ isActive = tr const scope = getActiveSurfaceScope(); assistantCreationPending.current = true; try { - const confirmed = await confirmDialog({ - title: t('agents.createAssistant'), - message: t('agents.createAssistantConfirmMessage'), - confirmText: t('agents.createAssistant'), - type: 'info', - }); - if (!confirmed || !scope.isCurrent()) return; - setCreatingAssistant(true); const workspace = await createAssistantWorkspace(); scope.assertCurrent('open newly created assistant'); diff --git a/src/web-ui/src/app/scenes/profile/views/NurseryGallery.actions.test.tsx b/src/web-ui/src/app/scenes/profile/views/NurseryGallery.actions.test.tsx index 1979964d76..59fd84206f 100644 --- a/src/web-ui/src/app/scenes/profile/views/NurseryGallery.actions.test.tsx +++ b/src/web-ui/src/app/scenes/profile/views/NurseryGallery.actions.test.tsx @@ -38,11 +38,6 @@ const clickCreate = (index = 0) => act(async () => { [...container.querySelectorAll('button')] .filter(button => button.textContent === 'nursery.gallery.newAssistant')[index].click(); }); -const answerConfirmation = (confirm: boolean) => act(async () => { - const label = confirm ? 'nursery.gallery.newAssistant' : 'dialog.confirm.cancel'; - [...document.querySelectorAll('[role="alertdialog"] button')] - .find(button => button.textContent === label)!.click(); -}); beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); @@ -70,63 +65,46 @@ describe('assistant gallery creation', () => { { entry: 'header', index: 0, empty: false }, { entry: 'create card', index: 1, empty: false }, { entry: 'empty state', index: 1, empty: true }, - ])('requires confirmation from the $entry entry', async ({ index, empty }) => { + ])('creates directly from the $entry entry', async ({ index, empty }) => { if (empty) mocks.workspaces = []; await render(); await clickCreate(index); - expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain('nursery.gallery.createConfirmMessage'); - expect(mocks.createAssistant).not.toHaveBeenCalled(); - expect(useNurseryStore.getState().page).toBe('gallery'); - await answerConfirmation(true); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); expect(mocks.createAssistant).toHaveBeenCalledOnce(); expect(useNurseryStore.getState()).toMatchObject({ page: 'assistant', activeWorkspaceId: 'new-assistant' }); }); - it('cancels without creating an assistant and allows retry', async () => { - await render(); - await clickCreate(); - await answerConfirmation(false); - expect(mocks.createAssistant).not.toHaveBeenCalled(); - expect(useNurseryStore.getState().page).toBe('gallery'); - await clickCreate(); - await answerConfirmation(true); - expect(mocks.createAssistant).toHaveBeenCalledOnce(); - }); - - it('keeps one confirmation and request when multiple create entries are clicked', async () => { + it('keeps one request when multiple create entries are clicked', async () => { let finish!: (workspace: { id: string }) => void; mocks.createAssistant.mockReturnValue(new Promise(resolve => { finish = resolve; })); await render(); - await clickCreate(); - await clickCreate(1); - expect(mocks.createAssistant).not.toHaveBeenCalled(); - await answerConfirmation(true); + const entries = [...container.querySelectorAll('button')]; + await act(async () => { entries[0].click(); entries[1].click(); entries[0].click(); }); expect(mocks.createAssistant).toHaveBeenCalledOnce(); - expect([...container.querySelectorAll('button')].every(button => button.disabled)).toBe(true); + expect(entries.every(button => button.disabled)).toBe(true); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); await act(async () => { finish({ id: 'new-assistant' }); }); expect(useNurseryStore.getState().activeWorkspaceId).toBe('new-assistant'); }); - it('shows a creation failure and allows another confirmed attempt', async () => { + it('shows a creation failure and allows retry', async () => { mocks.createAssistant.mockRejectedValueOnce(new Error('Host unavailable')); await render(); await clickCreate(); - await answerConfirmation(true); expect(mocks.error).toHaveBeenCalledWith('nursery.gallery.createFailed'); expect(useNurseryStore.getState().page).toBe('gallery'); await clickCreate(); - expect(mocks.createAssistant).toHaveBeenCalledOnce(); - await answerConfirmation(true); expect(mocks.createAssistant).toHaveBeenCalledTimes(2); expect(useNurseryStore.getState().activeWorkspaceId).toBe('new-assistant'); }); - it('abandons confirmation if the device changes before creation', async () => { + it('ignores a creation failure after the device changes', async () => { + let fail!: (error: Error) => void; + mocks.createAssistant.mockReturnValue(new Promise((_resolve, reject) => { fail = reject; })); await render(); await clickCreate(); - await act(async () => { activateSurface('peer-host'); }); - await answerConfirmation(true); - expect(mocks.createAssistant).not.toHaveBeenCalled(); + await act(async () => { activateSurface('peer-host'); fail(new Error('Old host unavailable')); }); + expect(mocks.createAssistant).toHaveBeenCalledOnce(); expect(useNurseryStore.getState().page).toBe('gallery'); expect(mocks.error).not.toHaveBeenCalled(); }); @@ -136,7 +114,6 @@ describe('assistant gallery creation', () => { mocks.createAssistant.mockReturnValue(new Promise(resolve => { finish = resolve; })); await render(); await clickCreate(); - await answerConfirmation(true); await act(async () => { activateSurface('peer-host'); finish({ id: 'old-assistant' }); }); expect(useNurseryStore.getState().page).toBe('gallery'); expect(mocks.error).not.toHaveBeenCalled(); diff --git a/src/web-ui/src/app/scenes/profile/views/NurseryGallery.tsx b/src/web-ui/src/app/scenes/profile/views/NurseryGallery.tsx index 976d617494..db3d6446a1 100644 --- a/src/web-ui/src/app/scenes/profile/views/NurseryGallery.tsx +++ b/src/web-ui/src/app/scenes/profile/views/NurseryGallery.tsx @@ -10,7 +10,7 @@ import { GalleryGrid, GallerySkeleton, } from '@/app/components/GalleryLayout'; -import { confirmDanger, confirmDialog } from '@/infrastructure/confirm-dialog'; +import { confirmDanger } from '@/infrastructure/confirm-dialog'; import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext'; import { getActiveSurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; import type { WorkspaceInfo } from '@/shared/types'; @@ -51,14 +51,6 @@ const NurseryGallery: React.FC = () => { const scope = getActiveSurfaceScope(); assistantCreationPending.current = true; try { - const confirmed = await confirmDialog({ - title: t('nursery.gallery.newAssistant'), - message: t('nursery.gallery.createConfirmMessage'), - confirmText: t('nursery.gallery.newAssistant'), - type: 'info', - }); - if (!confirmed || !scope.isCurrent()) return; - setCreating(true); const newWorkspace = await createAssistantWorkspace(); scope.assertCurrent('open newly created assistant'); diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx index df017e0279..ecddc0fc96 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.test.tsx @@ -79,7 +79,7 @@ it('keeps the primary directory first and routes browsing and related-directory expect(deleteButton.getAttribute('data-openbitfun-variant')).toBe('glass'); expect(deleteButton.getAttribute('data-openbitfun-shape')).toBe('circle'); await act(async () => deleteButton.click()); - expect(remove).toHaveBeenCalledExactlyOnceWith('/related/0'); + expect(remove).toHaveBeenCalledExactlyOnceWith('/related/0', deleteButton); expect(manage).toHaveBeenCalledOnce(); expect(container.querySelector('.project-resource-cards__add')).toBeNull(); await act(async () => [...container.querySelectorAll('.project-resources__section-actions button')] diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx index 19a38217e3..ef96ea961e 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectDirectoriesSection.tsx @@ -12,7 +12,7 @@ export function ProjectDirectoriesSection({ workspace, fileAccess, onBrowse, onM onBrowse: () => void; onManage: () => void; onAdd: () => void; - onRemove: (path: string) => void; + onRemove: (path: string, trigger?: HTMLElement) => void; removingPath: string | null; canReveal: boolean; onReveal: (path: string) => void; @@ -52,7 +52,7 @@ export function ProjectDirectoriesSection({ workspace, fileAccess, onBrowse, onM loading: revealingPath === directory.path, onClick: () => onReveal(directory.path) }, ...(directory.primary ? [] : [{ id: 'remove', label: t('directories.removeDirectory', { name: directory.name }), icon: , tone: 'danger', 'aria-haspopup': 'dialog', - disabled: !!removingPath, loading: removingPath === directory.path, onClick: () => onRemove(directory.path) } satisfies ActionCardAction])]} + disabled: !!removingPath, loading: removingPath === directory.path, onClick: event => onRemove(directory.path, event.currentTarget) } satisfies ActionCardAction])]} body={<> diff --git a/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx b/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx index 33044be3be..8b73492786 100644 --- a/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx +++ b/src/web-ui/src/app/scenes/project-resources/ProjectResourcesScene.tsx @@ -129,7 +129,7 @@ function ProjectResourcesContent({ workspace, scope, isActive }: { workspace: Wo {!fileAccess &&

{t('connectionUnavailable')}

} setDialog('directories')} - onAdd={() => setDialog('addDirectory')} onRemove={path => void directoryActions.remove(path)} + onAdd={() => setDialog('addDirectory')} onRemove={(path, trigger) => void directoryActions.remove(path, trigger)} canReveal={isActive && directoryActions.canReveal} onReveal={path => void directoryActions.reveal(path)} revealingPath={directoryActions.revealingPath} removingPath={directoryActions.removingPath} error={directoryActions.error} /> diff --git a/src/web-ui/src/app/scenes/project-resources/useProjectDirectoryActions.ts b/src/web-ui/src/app/scenes/project-resources/useProjectDirectoryActions.ts index 0e1019b0ec..a9008ec99d 100644 --- a/src/web-ui/src/app/scenes/project-resources/useProjectDirectoryActions.ts +++ b/src/web-ui/src/app/scenes/project-resources/useProjectDirectoryActions.ts @@ -1,3 +1,4 @@ +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { useCallback, useEffect, useRef, useState } from 'react'; import { useWorkspaceContext } from '@/infrastructure/contexts/WorkspaceContext'; import { confirmDialog } from '@/infrastructure/confirm-dialog'; @@ -39,7 +40,7 @@ export function useProjectDirectoryActions(workspace: WorkspaceInfo, scope: Surf if (mounted.current && scope.isCurrent() && latest.current.workspace.id === workspace.id) setRevealingPath(null); } }, [canReveal, scope, t, workspace.id]); - const remove = useCallback(async (path: string) => { + const remove = useCallback(async (path: string, trigger?: HTMLElement) => { const current = () => mounted.current && scope.isCurrent() && latest.current.isActive && latest.current.workspace.id === workspace.id; const canRemove = () => path !== latest.current.workspace.rootPath @@ -48,7 +49,7 @@ export function useProjectDirectoryActions(workspace: WorkspaceInfo, scope: Surf pending.current = true; setError(null); try { - const confirmed = await confirmDialog({ title: t('directories.removeTitle'), message: t('directories.removeMessage'), + const confirmed = await confirmDialog({ anchor: captureConfirmationAnchor(trigger), title: t('directories.removeTitle'), message: t('directories.removeMessage'), type: 'warning', confirmDanger: true, confirmText: t('directories.removeConfirm') }); if (!confirmed || !current() || !canRemove()) return; setRemovingPath(path); diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolCardActions.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolCardActions.tsx index 95a9ca0358..510bf153e9 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolCardActions.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolCardActions.tsx @@ -12,7 +12,7 @@ interface ModelPoolCardActionsProps { connectionTestSupported: boolean; onEdit: () => void; onTest: () => void; - onDelete: () => void; + onDelete: (trigger?: HTMLElement) => void; onEnabledChange: (enabled: boolean) => void; } diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolsSection.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolsSection.tsx index 24c07e1544..62667252f3 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolsSection.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/ModelPoolsSection.tsx @@ -1,5 +1,5 @@ import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react'; -import { +import { captureConfirmationAnchor, Button, Capsule, Card, CardBody, CardHeader, ConfirmDialog, Dialog, DialogBody, DialogClose, DialogFooter, DialogHeader, DialogHeading, DialogTitle, Icon, IconButton, Input, MenuPopover, OverflowText, Radio, StatusPill, Tooltip, type MenuEntry, @@ -107,6 +107,7 @@ export function ModelPoolsSection({ models }: { models: AIModelConfig[] }) { const [error, setError] = useState(); const [busy, setBusy] = useState(false); const statusRequest = useRef(0); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [deleteId, setDeleteId] = useState(); const supported = supportsModelPools(); const strategyOptions = [ @@ -226,7 +227,7 @@ export function ModelPoolsSection({ models }: { models: AIModelConfig[] }) { } disabled={busy} - onClick={() => { setError(undefined); setDeleteId(pool.id); }} /> + onClick={event => { setDeleteAnchor(captureConfirmationAnchor(event.currentTarget)); setError(undefined); setDeleteId(pool.id); }} />
)} @@ -235,6 +236,7 @@ export function ModelPoolsSection({ models }: { models: AIModelConfig[] }) { { if (!busy) { setDeleteId(undefined); setError(undefined); } }} onConfirm={async () => { if (deleteId) await remove(deleteId); }} diff --git a/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx index a63452599f..1c980ca4ea 100644 --- a/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/ai/ModelSettingsPage.tsx @@ -123,7 +123,7 @@ import { useNotification } from '@/shared/notification-system'; import type { ProviderRegion } from '@/shared/types'; import { translateConnectionTestMessage } from '@/shared/utils/aiConnectionTestMessages'; import { createLogger } from '@/shared/utils/logger'; -import { +import { captureConfirmationAnchor, Button, Capsule, Card, @@ -662,6 +662,7 @@ const ModelSettingsPage: React.FC = () => { const [subscriptionLoginClock, setSubscriptionLoginClock] = useState(() => Date.now()); const [subscriptionLoginAccountId, setSubscriptionLoginAccountId] = useState(null); const [subscriptionLogoutRequest, setSubscriptionLogoutRequest] = useState(null); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [deleteRequest, setDeleteRequest] = useState(null); const modelDiscoveryRef = React.useRef(new ModelDiscoveryCoordinator()); const editorSavingRef = React.useRef(false); @@ -2340,10 +2341,12 @@ const ModelSettingsPage: React.FC = () => { .reduce((count, value) => count + countModelConfigReferences(value, ids), 0); }; - const requestDelete = async (config: AIModelConfigType) => { + const requestDelete = async (config: AIModelConfigType, trigger?: HTMLElement) => { + const anchor = captureConfirmationAnchor(trigger); if (!config.id) return; try { const referenceCount = await inspectModelReferenceCount([config.id]); + setDeleteAnchor(anchor); setDeleteRequest({ kind: 'model', config, modelIds: [config.id], referenceCount }); } catch (error) { log.error('Failed to inspect model references before deletion', { configId: config.id, error }); @@ -4604,7 +4607,7 @@ const ModelSettingsPage: React.FC = () => { aria-label={t('actions.delete')} tone="danger" size="sm" - onClick={() => void requestDelete(config)} + onClick={event => void requestDelete(config, event.currentTarget)} icon={} /> @@ -4650,7 +4653,7 @@ const ModelSettingsPage: React.FC = () => { connectionTestSupported={connectionTestSupported} onEdit={() => handleEdit(config)} onTest={() => void handleTest(config)} - onDelete={() => void requestDelete(config)} + onDelete={trigger => void requestDelete(config, trigger)} onEnabledChange={enabled => void handleToggleEnabled(config, enabled)} /> @@ -5622,6 +5625,7 @@ const ModelSettingsPage: React.FC = () => { type="warning" /> { if (!open) setDeleteRequest(null); }} onConfirm={handleDelete} diff --git a/src/web-ui/src/app/scenes/settings/pages/application/PetSettingsSection.tsx b/src/web-ui/src/app/scenes/settings/pages/application/PetSettingsSection.tsx index f8fc413ae4..12d9cc61e2 100644 --- a/src/web-ui/src/app/scenes/settings/pages/application/PetSettingsSection.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/application/PetSettingsSection.tsx @@ -22,7 +22,7 @@ import { confirmDanger } from '@/infrastructure/confirm-dialog'; import { useI18n } from '@/infrastructure/i18n'; import { useNotification } from '@/shared/notification-system'; import { createLogger } from '@/shared/utils/logger'; -import { +import { captureConfirmationAnchor, Button, Disclosure, Icon, @@ -126,7 +126,7 @@ const PetSettingsSection: React.FC<{ isActive?: boolean }> = ({ isActive = true const confirmed = await confirmDanger( t('features.pet.deleteConfirmTitle'), t('features.pet.deleteConfirmBody'), - { confirmText: t('features.pet.delete') }, + { anchor: captureConfirmationAnchor(event.currentTarget as HTMLElement), confirmText: t('features.pet.delete') }, ); if (!confirmed) return; setCompanionPetDeletingPath(pet.packagePath); diff --git a/src/web-ui/src/app/scenes/settings/pages/data/ArchivedSessionsSettingsPage.tsx b/src/web-ui/src/app/scenes/settings/pages/data/ArchivedSessionsSettingsPage.tsx index 37b50fc5bf..86e5de8bc1 100644 --- a/src/web-ui/src/app/scenes/settings/pages/data/ArchivedSessionsSettingsPage.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/data/ArchivedSessionsSettingsPage.tsx @@ -26,7 +26,7 @@ import { notificationService } from '@/shared/notification-system'; import type { SessionMetadata } from '@/shared/types/session-history'; import { externalHistoryFromMetadata } from '@/flow_chat/utils/externalHistory'; import { createLogger } from '@/shared/utils/logger'; -import { Button, Empty, Icon, OverflowText } from '@openbitfun/ui'; +import { captureConfirmationAnchor, Button, Empty, Icon, OverflowText } from '@openbitfun/ui'; import { Inbox, RotateCcw } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -78,7 +78,7 @@ function formatDateTime(timestampMs: number): string { interface ArchivedRowProps { entry: ArchivedEntry; onRestore: (entry: ArchivedEntry) => void; - onDelete: (entry: ArchivedEntry) => void; + onDelete: (entry: ArchivedEntry, trigger?: HTMLElement) => void; pendingAction: PendingAction | null; disabled: boolean; t: (key: string, options?: Record) => string; @@ -142,7 +142,7 @@ const ArchivedRow: React.FC = ({ size="sm" variant="outline" leadingIcon={} - onClick={() => onDelete(entry)} + onClick={event => onDelete(entry, event.currentTarget)} disabled={disabled} loading={pendingAction?.entryKey === archivedEntryIdentityKey(entry) && pendingAction.type === 'delete'} @@ -338,7 +338,7 @@ const ArchivedSessionsSettingsPage: React.FC = () => { // ── Delete single archived session ─────────────────────────────────────── - const handleDelete = useCallback(async (entry: ArchivedEntry) => { + const handleDelete = useCallback(async (entry: ArchivedEntry, trigger?: HTMLElement) => { if (pendingAction || bulkDeleting) return; const sourceView = !!externalHistoryFromMetadata(entry.session.customMetadata); const confirmed = await confirmDanger( @@ -351,7 +351,7 @@ const ArchivedSessionsSettingsPage: React.FC = () => { entry.remoteSshHost, ), }), - { confirmText: t(sourceView ? 'nav.sessions.removeSource' : 'nav.sessions.deleteArchived') }, + { anchor: captureConfirmationAnchor(trigger), confirmText: t(sourceView ? 'nav.sessions.removeSource' : 'nav.sessions.deleteArchived') }, ); if (!confirmed) return; @@ -540,7 +540,7 @@ const ArchivedSessionsSettingsPage: React.FC = () => { key={archivedEntryIdentityKey(entry)} entry={entry} onRestore={(e) => { void handleRestore(e); }} - onDelete={(e) => { void handleDelete(e); }} + onDelete={(entry, trigger) => { void handleDelete(entry, trigger); }} pendingAction={pendingAction} disabled={pendingAction !== null || bulkDeleting} t={t} diff --git a/src/web-ui/src/app/scenes/settings/pages/tools/HooksSettingsSection.tsx b/src/web-ui/src/app/scenes/settings/pages/tools/HooksSettingsSection.tsx index 295f59f47d..155c080535 100644 --- a/src/web-ui/src/app/scenes/settings/pages/tools/HooksSettingsSection.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/tools/HooksSettingsSection.tsx @@ -19,7 +19,7 @@ import { useCurrentWorkspace } from '@/infrastructure/contexts/WorkspaceContext' import { useNotification } from '@/shared/notification-system'; import { WorkspaceKind } from '@/shared/types'; import { createLogger } from '@/shared/utils/logger'; -import { +import { captureConfirmationAnchor, Button, ConfirmDialog, Dialog, @@ -78,6 +78,7 @@ const HooksSettingsSection: React.FC = () => { const [busyKey, setBusyKey] = useState(null); const [reviewPlan, setReviewPlan] = useState(null); const [planNotice, setPlanNotice] = useState(null); + const [confirmationAnchor, setConfirmationAnchor] = useState>(undefined); const [confirmation, setConfirmation] = useState< | { kind: 'remove'; importId: string } | { kind: 'reset'; scope: ExternalHookSource['scope'] } @@ -421,7 +422,7 @@ const HooksSettingsSection: React.FC = () => { tone="danger" size="sm" disabled={busyKey !== null} - onClick={() => setConfirmation({ kind: 'remove', importId: item.importId })} + onClick={event => { setConfirmationAnchor(captureConfirmationAnchor(event.currentTarget)); setConfirmation({ kind: 'remove', importId: item.importId }); }} > {t('imports.remove')} @@ -556,6 +557,7 @@ const HooksSettingsSection: React.FC = () => {
setConfirmation(null)} onConfirm={confirmMutation} diff --git a/src/web-ui/src/app/scenes/settings/pages/tools/QuickActionsSettingsSection.tsx b/src/web-ui/src/app/scenes/settings/pages/tools/QuickActionsSettingsSection.tsx index 4f0d83368e..e3195b3052 100644 --- a/src/web-ui/src/app/scenes/settings/pages/tools/QuickActionsSettingsSection.tsx +++ b/src/web-ui/src/app/scenes/settings/pages/tools/QuickActionsSettingsSection.tsx @@ -16,7 +16,7 @@ import { } from '@/infrastructure/config/settingsDraftRegistry'; import { useNotification } from '@/shared/notification-system'; import { createLogger } from '@/shared/utils/logger'; -import { +import { captureConfirmationAnchor, Button, ConfirmDialog, Dialog, @@ -204,7 +204,7 @@ interface ActionRowProps { action: QuickAction; onToggle: (id: string) => void; onEdit: (action: QuickAction) => void; - onDelete: (id: string) => void; + onDelete: (id: string, trigger?: HTMLElement) => void; canDelete: boolean; disabled: boolean; t: TranslationFn; @@ -246,7 +246,7 @@ const ActionRow: React.FC = ({ action, onToggle, onEdit, onDelet type="button" size="sm" aria-label={t('delete.button')} - onClick={() => onDelete(action.id)} + onClick={event => onDelete(action.id, event.currentTarget)} disabled={disabled} className="quick-actions-config__delete-btn" icon={} @@ -274,6 +274,7 @@ const QuickActionsSettingsSection: React.FC = () => { // Modal state: undefined = closed, null = create, QuickAction = edit const [modalTarget, setModalTarget] = useState(undefined); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [deleteTarget, setDeleteTarget] = useState(null); const isModalOpen = modalTarget !== undefined; @@ -329,7 +330,8 @@ const QuickActionsSettingsSection: React.FC = () => { void persist(actions.map(a => a.id === id ? { ...a, enabled: !a.enabled } : a)); }, [actions, persist, saving]); - const handleDelete = useCallback((id: string) => { + const handleDelete = useCallback((id: string, trigger?: HTMLElement) => { + setDeleteAnchor(captureConfirmationAnchor(trigger)); const target = actions.find(action => action.id === id); if (target) setDeleteTarget(target); }, [actions]); @@ -451,6 +453,7 @@ const QuickActionsSettingsSection: React.FC = () => { t={t} /> { if (!open && !saving) setDeleteTarget(null); }} onConfirm={confirmDelete} diff --git a/src/web-ui/src/app/scenes/skills/SkillsScene.tsx b/src/web-ui/src/app/scenes/skills/SkillsScene.tsx index 6e63ab40e0..fa5300fa89 100644 --- a/src/web-ui/src/app/scenes/skills/SkillsScene.tsx +++ b/src/web-ui/src/app/scenes/skills/SkillsScene.tsx @@ -1,4 +1,4 @@ -import { +import { captureConfirmationAnchor, Button, ConfirmDialog, Empty, @@ -121,6 +121,7 @@ const SkillsScene: React.FC = () => { const [marketSettingsOpen, setMarketSettingsOpen] = useState(false); useEffect(() => { if (!desktopConfigAvailable) setMarketSettingsOpen(false); }, [desktopConfigAvailable]); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [deleteTarget, setDeleteTarget] = useState(null); const [installedSearch, setInstalledSearch] = useState(''); const [groupSearch, setGroupSearch] = useState(''); @@ -851,9 +852,9 @@ const SkillsScene: React.FC = () => { variant="text" tone="danger" size="sm" - onClick={() => { + onClick={event => { + setDeleteAnchor(captureConfirmationAnchor(event.currentTarget)); setDeleteTarget(selectedInstalledSkill); - setSelectedDetail(null); }} leadingIcon={} > @@ -894,6 +895,7 @@ const SkillsScene: React.FC = () => { /> setDeleteTarget(null)} onConfirm={async () => { @@ -904,6 +906,7 @@ const SkillsScene: React.FC = () => { const deleted = await installed.handleDelete(deleteTarget); if (deleted) { setDeleteTarget(null); + setSelectedDetail(null); } }} title={t('deleteModal.title')} diff --git a/src/web-ui/src/app/scenes/skills/components/SkillGroupsView.tsx b/src/web-ui/src/app/scenes/skills/components/SkillGroupsView.tsx index be6070284b..0012953e6e 100644 --- a/src/web-ui/src/app/scenes/skills/components/SkillGroupsView.tsx +++ b/src/web-ui/src/app/scenes/skills/components/SkillGroupsView.tsx @@ -4,7 +4,6 @@ import { type MenuEntry, } from '@openbitfun/ui'; import { useI18n } from '@/infrastructure/i18n/hooks/useI18n'; -import { confirmDialog } from '@/infrastructure/confirm-dialog'; import { isSurfaceChangedError } from '@/infrastructure/peer-device/deviceSurface'; import type { UserSkillGroup } from '@/infrastructure/config/types'; import { @@ -87,11 +86,7 @@ export default function SkillGroupsView({ searchQuery, skills, collection, catal }; const remove = async (group: UserSkillGroup) => { - const confirmed = await confirmDialog({ - title: t('groups.deleteTitle'), message: t('groups.deleteMessage', { name: group.name }), - confirmText: t('groups.delete'), cancelText: t('groups.cancel'), confirmDanger: true, type: 'warning', - }); - if (confirmed && collection.scope.isCurrent()) await mutate(current => deleteUserSkillGroup(current, group)); + if (collection.scope.isCurrent()) await mutate(current => deleteUserSkillGroup(current, group)); }; const renderGroup = (group: ResolvedSkillGroup) => { @@ -105,7 +100,8 @@ export default function SkillGroupsView({ searchQuery, skills, collection, catal { id: 'down', label: t('groups.moveDown'), disabled: index === collection.groups.length - 1, onSelect: () => { if (original) void mutate(current => moveUserSkillGroup(current, original.id, 1)); } }, { id: 'delete', label: t('groups.delete'), tone: 'danger', - onSelect: () => { if (original) void remove(original); } }, + confirmation: { description: t('groups.deleteMessage', { name: group.label }), confirmText: t('groups.delete'), cancelText: t('groups.cancel') }, + onSelect: async () => { if (original) await remove(original); } }, ]; return (
= ({ isActive = true }) => { } }, [loadJobs, t]); - const handleDelete = useCallback(async (job: CronJob) => { - const confirmed = await confirmDanger(t('deleteDialog.title', { name: job.name }), null); + const handleDelete = useCallback(async (job: CronJob, trigger?: HTMLElement) => { + const confirmed = await confirmDanger(t('deleteDialog.title', { name: job.name }), null, { anchor: captureConfirmationAnchor(trigger) }); if (!confirmed) return; try { @@ -519,7 +519,7 @@ const TodosScene: React.FC<{ isActive?: boolean }> = ({ isActive = true }) => { workspaces={openedWorkspacesList} isSelected={editingJob?.id === occurrence.job.id} onEdit={handleEdit} - onDelete={(job) => { void handleDelete(job); }} + onDelete={(job, trigger) => { void handleDelete(job, trigger); }} onToggleEnabled={(job, enabled) => { void handleToggleEnabled(job, enabled); }} /> ))} @@ -542,7 +542,7 @@ const TodosScene: React.FC<{ isActive?: boolean }> = ({ isActive = true }) => { statusLabel={inactiveStatusLabel(entry.reason)} isSelected={editingJob?.id === entry.job.id} onEdit={handleEdit} - onDelete={(job) => { void handleDelete(job); }} + onDelete={(job, trigger) => { void handleDelete(job, trigger); }} onToggleEnabled={(job, enabled) => { void handleToggleEnabled(job, enabled); }} /> ))} @@ -619,7 +619,7 @@ const TodosScene: React.FC<{ isActive?: boolean }> = ({ isActive = true }) => { workspaces={openedWorkspacesList} isSelected={editingJob?.id === occurrence.job.id} onEdit={handleEdit} - onDelete={(job) => { void handleDelete(job); }} + onDelete={(job, trigger) => { void handleDelete(job, trigger); }} onToggleEnabled={(job, enabled) => { void handleToggleEnabled(job, enabled); }} /> ))} diff --git a/src/web-ui/src/app/scenes/todos/components/TodoItemRow.tsx b/src/web-ui/src/app/scenes/todos/components/TodoItemRow.tsx index cce287f46b..f53d459d8f 100644 --- a/src/web-ui/src/app/scenes/todos/components/TodoItemRow.tsx +++ b/src/web-ui/src/app/scenes/todos/components/TodoItemRow.tsx @@ -34,7 +34,7 @@ export interface TodoItemRowProps { statusLabel?: string; isSelected?: boolean; onEdit: (job: CronJob) => void; - onDelete: (job: CronJob) => void; + onDelete: (job: CronJob, trigger?: HTMLElement) => void; onToggleEnabled: (job: CronJob, enabled: boolean) => void; } @@ -169,7 +169,7 @@ const TodoItemRow: React.FC = ({ tone="danger" aria-label={t('actions.delete')} icon={} - onClick={() => onDelete(job)} + onClick={event => onDelete(job, event.currentTarget)} />
diff --git a/src/web-ui/src/features/ssh-remote/RemoteFileBrowser.tsx b/src/web-ui/src/features/ssh-remote/RemoteFileBrowser.tsx index 6b9f863eaf..ac9bd0c49d 100644 --- a/src/web-ui/src/features/ssh-remote/RemoteFileBrowser.tsx +++ b/src/web-ui/src/features/ssh-remote/RemoteFileBrowser.tsx @@ -3,7 +3,7 @@ * Used to browse and select remote directory as workspace */ -import { subscribeOverlayInteraction, createOverlayPortal, Button, Dialog, DialogHeader, DialogHeading, DialogTitle, DialogClose, DialogBody, DialogFooter, Field, ConfirmDialog, Icon, IconButton, Input, Menu, MenuItem, MenuSeparator, ScrollArea } from '@openbitfun/ui'; +import { captureConfirmationAnchor, subscribeOverlayInteraction, createOverlayPortal, Button, Dialog, DialogHeader, DialogHeading, DialogTitle, DialogClose, DialogBody, DialogFooter, Field, ConfirmDialog, Icon, IconButton, Input, Menu, MenuItem, MenuSeparator, ScrollArea } from '@openbitfun/ui'; import React, { useState, useEffect, useRef, useCallback } from 'react'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost'; import { useI18n } from '@/infrastructure/i18n'; @@ -108,6 +108,7 @@ export const RemoteFileBrowser: React.FC = ({ }); const [renameEntry, setRenameEntry] = useState(null); const [renameValue, setRenameValue] = useState(''); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [deleteConfirm, setDeleteConfirm] = useState({ show: false, entry: null, @@ -327,7 +328,8 @@ export const RemoteFileBrowser: React.FC = ({ } }; - const handleContextMenuAction = async (action: string) => { + const handleContextMenuAction = async (action: string, trigger?: HTMLElement) => { + const anchor = captureConfirmationAnchor(trigger); if (!contextMenu.entry) return; const entry = contextMenu.entry; @@ -336,6 +338,7 @@ export const RemoteFileBrowser: React.FC = ({ try { switch (action) { case 'delete': + setDeleteAnchor(anchor); setDeleteConfirm({ show: true, entry }); break; case 'open': @@ -747,7 +750,7 @@ export const RemoteFileBrowser: React.FC = ({ } tone="danger" - onClick={() => handleContextMenuAction('delete')} + onClick={event => handleContextMenuAction('delete', event.currentTarget)} > {t('actions.delete') || 'Delete'} @@ -824,6 +827,7 @@ export const RemoteFileBrowser: React.FC = ({ {/* Delete Confirmation Dialog */} = ({ onOpen: () => { void threadGoalController.openGoalEntry(); }, - onAction: action => { - void threadGoalController.runUiAction(action); + onAction: (action, trigger) => { + void threadGoalController.runUiAction(action, trigger); }, } : undefined} diff --git a/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx b/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx index 97f3b2b334..165884a061 100644 --- a/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInputWorkspaceStrip.tsx @@ -129,7 +129,7 @@ export interface ChatInputWorkspaceStripProps { /** Actions the goal menu offers for the current status; the track mirrors them. */ actions?: ThreadGoalUiAction[]; onOpen: () => void; - onAction?: (action: ThreadGoalStripAction) => void; + onAction?: (action: ThreadGoalStripAction, trigger?: HTMLElement) => void; }; /** Immutable per-session dispatch destination. Hidden on embedded/mini composers. */ dispatchControl?: { diff --git a/src/web-ui/src/flow_chat/components/HarnessProfileSelector.test.tsx b/src/web-ui/src/flow_chat/components/HarnessProfileSelector.test.tsx index 19a190bd1f..6da1c64bdf 100644 --- a/src/web-ui/src/flow_chat/components/HarnessProfileSelector.test.tsx +++ b/src/web-ui/src/flow_chat/components/HarnessProfileSelector.test.tsx @@ -429,6 +429,7 @@ describe('HarnessProfileSelector', () => { }); expect(onSelectProfile).not.toHaveBeenCalled(); expect(confirmation.dialog).toHaveBeenCalledWith({ + anchor: expect.objectContaining({ element: expect.any(HTMLButtonElement) }), title: 'chatInput.harness.newSessionConfirmation.title', message: 'chatInput.harness.newSessionConfirmation.message', confirmText: 'chatInput.harness.newSessionConfirmation.confirm', @@ -481,6 +482,7 @@ describe('HarnessProfileSelector', () => { }); expect(onSelectAgent).not.toHaveBeenCalled(); expect(confirmation.dialog).toHaveBeenCalledWith({ + anchor: expect.objectContaining({ element: expect.any(HTMLButtonElement) }), title: 'chatInput.harness.newSessionConfirmation.title', message: 'chatInput.harness.newSessionConfirmation.message', confirmText: 'chatInput.harness.newSessionConfirmation.confirm', diff --git a/src/web-ui/src/flow_chat/components/HarnessProfileSelector.tsx b/src/web-ui/src/flow_chat/components/HarnessProfileSelector.tsx index d2cf674a0d..4c542c80be 100644 --- a/src/web-ui/src/flow_chat/components/HarnessProfileSelector.tsx +++ b/src/web-ui/src/flow_chat/components/HarnessProfileSelector.tsx @@ -2,7 +2,7 @@ import { HARNESS_IDS, canonicalAgentId, type HarnessId } from '@/shared/agents/i import { HARNESS_PRESENTATION } from '@/shared/agents/harnessPresentation'; import React, { useCallback, useEffect, useId, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, Menu, MenuItem, MenuSection, MenuSeparator, Tooltip } from '@openbitfun/ui'; +import { captureConfirmationAnchor, subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, Menu, MenuItem, MenuSection, MenuSeparator, Tooltip } from '@openbitfun/ui'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost'; import { confirmDialog } from '@/infrastructure/confirm-dialog'; import { notificationService } from '@/shared/notification-system'; @@ -167,8 +167,10 @@ export const HarnessProfileSelector: React.FC = ({ selection: HarnessNewSessionSelection, targetName: string, ) => { + const anchor = captureConfirmationAnchor(triggerRef.current); finishSelection(); const confirmed = await confirmDialog({ + anchor, title: t('chatInput.harness.newSessionConfirmation.title', { name: targetName }), message: t('chatInput.harness.newSessionConfirmation.message', { name: targetName }), confirmText: t('chatInput.harness.newSessionConfirmation.confirm'), diff --git a/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.tsx b/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.tsx index 669274f4f9..1059e7a41a 100644 --- a/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.tsx +++ b/src/web-ui/src/flow_chat/components/modern/FlowChatHeader.tsx @@ -6,7 +6,7 @@ import React, { useEffect, useLayoutEffect, useMemo, useRef, useState, useCallback, useSyncExternalStore } from 'react'; import { Keyboard, Square } from 'lucide-react'; -import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, IconButton, Menu, MenuItem, SearchField, Switch, ToolbarSeparator, Tooltip } from '@openbitfun/ui'; +import { captureConfirmationAnchor, subscribeOverlayInteraction, createOverlayPortal, OverflowText, Icon, IconButton, Menu, MenuItem, SearchField, Switch, ToolbarSeparator, Tooltip } from '@openbitfun/ui'; import { SceneChromeContribution } from '@/app/components/SceneTopBar/SceneChrome'; import { useSceneChromeContext } from '@/app/components/SceneTopBar/sceneChromeContext'; import { useTranslation } from 'react-i18next'; @@ -75,8 +75,8 @@ export interface FlowChatHeaderProps { /** Whether the active Agent tree contains running descendants. */ hasActiveSessionTreeDescendants?: boolean; /** Cancel one running session from the active Agent tree without cancelling descendants. */ - onCancelSessionTreeSession?: (selection: SessionTreeSelection) => Promise; - onDeleteSessionTreeSession?: (selection: SessionTreeSelection) => Promise; + onCancelSessionTreeSession?: (selection: SessionTreeSelection, anchor?: ReturnType) => Promise; + onDeleteSessionTreeSession?: (selection: SessionTreeSelection, anchor?: ReturnType) => Promise; /** Long-running background commands launched by the active parent session. */ backgroundCommands?: FlowChatHeaderCommandSummary[]; /** Open a read-only output panel for a background command. */ diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx index a28d6aa8fe..8a3ccdc330 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx @@ -1,3 +1,4 @@ +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { globalEventBus } from '@/infrastructure/event-bus'; import { requireSessionOwningWorkspaceId } from '../../utils/sessionOrdering'; /** @@ -2490,7 +2491,7 @@ export const ModernFlowChatContainer: React.FC = ( } }, [t]); - const handleDeleteSessionTreeSession = useCallback(async (selection: SessionTreeSelection) => { + const handleDeleteSessionTreeSession = useCallback(async (selection: SessionTreeSelection, anchor?: ReturnType) => { if (selection.isRoot) return false; if (activeSession && resolveSessionDriverId(activeSession.sessionId, activeSession) === 'dispatch') { notificationService.error(t('flowChatHeader.agentTreeDeleteUnsupported'), { duration: 5000 }); @@ -2501,7 +2502,7 @@ export const ModernFlowChatContainer: React.FC = ( const confirmed = await confirmDanger( t('flowChatHeader.agentTreeDelete'), t('flowChatHeader.agentTreeDeleteConfirm', { name: selection.displayTitle }), - { confirmText: t('flowChatHeader.agentTreeDelete') }, + { anchor, confirmText: t('flowChatHeader.agentTreeDelete') }, ); if (!confirmed) return false; await deleteSessionTreeBranch({ sessionId: selection.sessionId, workspaceId: requireSessionOwningWorkspaceId(flowChatStore.getState().sessions.get(selection.sessionId) || activeSession!) }, scope); diff --git a/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.test.tsx b/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.test.tsx index c10e740dfd..cd33ebac11 100644 --- a/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.test.tsx @@ -136,7 +136,7 @@ describe('SessionTreePopover', () => { await act(async () => { menu?.querySelector('[role="menuitem"]')?.click(); }); - expect(onDeleteSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'child' })); + expect(onDeleteSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'child' }), expect.objectContaining({ element: expect.any(HTMLButtonElement) })); expect(onSelectSession).not.toHaveBeenCalled(); expect(mocks.getSessionLineage).toHaveBeenCalledTimes(2); }); diff --git a/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.tsx b/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.tsx index ab85796c73..42c39b7a69 100644 --- a/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.tsx +++ b/src/web-ui/src/flow_chat/components/modern/SessionTreePopover.tsx @@ -1,6 +1,6 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { Square } from 'lucide-react'; -import { subscribeOverlayInteraction, createOverlayPortal, OverflowText, Spinner, Tooltip } from '@openbitfun/ui'; +import { captureConfirmationAnchor, subscribeOverlayInteraction, createOverlayPortal, OverflowText, Spinner, Tooltip } from '@openbitfun/ui'; import { RetainedMountBoundary } from '@/shared/presence'; import { sessionAPI, type SessionLineageSnapshot } from '@/infrastructure/api/service-api/SessionAPI'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance'; @@ -45,8 +45,8 @@ interface SessionTreePopoverProps { fallbackWorkspaceId?: string; hasActiveDescendants?: boolean; onSelectSession?: (selection: SessionTreeSelection) => void; - onCancelSession?: (selection: SessionTreeSelection) => Promise; - onDeleteSession?: (selection: SessionTreeSelection) => Promise; + onCancelSession?: (selection: SessionTreeSelection, anchor?: ReturnType) => Promise; + onDeleteSession?: (selection: SessionTreeSelection, anchor?: ReturnType) => Promise; /** Render the tree inside a parent-owned popover instead of creating another trigger and surface. */ embedded?: boolean; activeOnly?: boolean; @@ -362,14 +362,15 @@ export const SessionTreePopover: React.FC = ({ updateActionMenuPosition(); }, [onCancelSession, onDeleteSession, openActionSessionId, updateActionMenuPosition]); - const handleDelete = useCallback(async (node: SessionLineageNode) => { + const handleDelete = useCallback(async (node: SessionLineageNode, trigger?: HTMLElement) => { + const anchor = captureConfirmationAnchor(trigger); if (!onDeleteSession || node.isRoot || deletingSessionId) return; const scope = getActiveSurfaceScope(); setOpenActionSessionId(null); setActionMenuPosition(null); setDeletingSessionId(node.sessionId); try { - await onDeleteSession({ ...node, displayTitle: nodeDisplayTitle(node) }); + await onDeleteSession({ ...node, displayTitle: nodeDisplayTitle(node) }, anchor); } finally { setDeletingSessionId(null); if (scope.isCurrent()) await refreshSnapshot(); @@ -531,7 +532,7 @@ export const SessionTreePopover: React.FC = ({ {canDelete ? void handleDelete(node)} + onClick={event => void handleDelete(node, event.currentTarget)} disabled={deletingSessionId !== null} leading={} > diff --git a/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalDialogs.tsx b/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalDialogs.tsx index 826a2cfc0e..a7dc036985 100644 --- a/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalDialogs.tsx +++ b/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalDialogs.tsx @@ -117,7 +117,7 @@ export const ThreadGoalDialogs: React.FC = ({ : null; const runAction = useCallback( - async (action: ThreadGoalUiAction) => { + async (action: ThreadGoalUiAction, trigger?: HTMLElement) => { if (disabled) return; if (action === 'edit') { controller.openEdit(goal ? 'update' : 'create'); @@ -128,7 +128,7 @@ export const ThreadGoalDialogs: React.FC = ({ return; } if (action === 'clear' || action === 'pause' || action === 'resume') { - await controller.runUiAction(action); + await controller.runUiAction(action, trigger); } }, [controller, disabled, goal] @@ -225,7 +225,7 @@ export const ThreadGoalDialogs: React.FC = ({ tone={action === 'clear' ? 'danger' : 'neutral'} size="sm" disabled={disabled} - onClick={() => void runAction(action)} + onClick={event => void runAction(action, event.currentTarget)} > {resolveThreadGoalActionLabel(t, action)} diff --git a/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalStripControl.tsx b/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalStripControl.tsx index 43b70a55f9..327bcd7bf3 100644 --- a/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalStripControl.tsx +++ b/src/web-ui/src/flow_chat/components/thread-goal/ThreadGoalStripControl.tsx @@ -22,7 +22,7 @@ export interface ThreadGoalStripControlProps { actions?: ThreadGoalUiAction[]; onOpen: () => void; /** Omitted where the surface cannot run goal actions; those controls then stay away. */ - onAction?: (action: ThreadGoalStripAction) => void; + onAction?: (action: ThreadGoalStripAction, trigger?: HTMLElement) => void; } /** @@ -139,7 +139,7 @@ export const ThreadGoalStripControl: React.FC = ({ aria-label={clearLabel} onClick={event => { event.stopPropagation(); - onAction?.('clear'); + onAction?.('clear', event.currentTarget); }} > diff --git a/src/web-ui/src/flow_chat/hooks/useThreadGoalController.ts b/src/web-ui/src/flow_chat/hooks/useThreadGoalController.ts index 6dbdf4807d..91add43b21 100644 --- a/src/web-ui/src/flow_chat/hooks/useThreadGoalController.ts +++ b/src/web-ui/src/flow_chat/hooks/useThreadGoalController.ts @@ -1,3 +1,4 @@ +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { useTranslation } from 'react-i18next'; import { confirmWarning } from '@/infrastructure/confirm-dialog'; @@ -39,7 +40,7 @@ export interface ThreadGoalController { /** Fetch latest goal from backend, then open menu or create dialog. */ openGoalEntry: () => Promise; runSlashAction: (message: string) => Promise; - runUiAction: (action: 'clear' | 'pause' | 'resume') => Promise; + runUiAction: (action: 'clear' | 'pause' | 'resume', trigger?: HTMLElement) => Promise; saveEdit: (objective: string) => Promise; confirmResume: () => Promise; dismissResume: () => void; @@ -272,14 +273,15 @@ export function useThreadGoalController( ); const runUiAction = useCallback( - async (action: 'clear' | 'pause' | 'resume') => { + async (action: 'clear' | 'pause' | 'resume', trigger?: HTMLElement) => { if (!session || disabled) return; // Clearing drops the objective together with the time and tokens spent on // it, and none of that can be recovered, so every entry point asks first. if (action === 'clear') { const confirmed = await confirmWarning( t('threadGoal.clearConfirmTitle'), - t('threadGoal.clearConfirmMessage', { objective: goal?.objective ?? '' }) + t('threadGoal.clearConfirmMessage', { objective: goal?.objective ?? '' }), + { anchor: captureConfirmationAnchor(trigger) } ); if (!confirmed) return; } diff --git a/src/web-ui/src/infrastructure/config/components/AppearanceMarketWorkflows.tsx b/src/web-ui/src/infrastructure/config/components/AppearanceMarketWorkflows.tsx index 5f141f86ab..bbae872334 100644 --- a/src/web-ui/src/infrastructure/config/components/AppearanceMarketWorkflows.tsx +++ b/src/web-ui/src/infrastructure/config/components/AppearanceMarketWorkflows.tsx @@ -1,4 +1,4 @@ -import { OverflowText, Button, Disclosure, Empty, Field, Icon, Input, Select, ScrollArea, Textarea } from '@openbitfun/ui'; +import { captureConfirmationAnchor, OverflowText, Button, Disclosure, Empty, Field, Icon, Input, Select, ScrollArea, Textarea } from '@openbitfun/ui'; import { type FormEvent, useCallback, useEffect, useState } from 'react'; import { AlertTriangle, Inbox, ShieldCheck } from 'lucide-react'; import { confirmDialog } from '@/infrastructure/confirm-dialog'; @@ -137,8 +137,9 @@ export function AppearanceMarketWorkflows({ workflow }: AppearanceMarketWorkflow // eslint-disable-next-line react-hooks/exhaustive-deps }, [workflow]); - const withdraw = async (submission: AppearanceMarketSubmission) => { + const withdraw = async (submission: AppearanceMarketSubmission, trigger?: HTMLElement) => { const confirmed = await confirmDialog({ + anchor: captureConfirmationAnchor(trigger), title: t('package.market.submissions.withdrawTitle'), message: t('package.market.submissions.withdrawMessage', { name: submission.name || submission.slug }), confirmText: t('package.market.submissions.withdraw'), @@ -468,7 +469,7 @@ export function AppearanceMarketWorkflows({ workflow }: AppearanceMarketWorkflow variant="outline" size="sm" loading={actingId === submission.submissionId} - onClick={() => void withdraw(submission)} + onClick={event => void withdraw(submission, event.currentTarget)} > {t('package.market.submissions.withdraw')} diff --git a/src/web-ui/src/infrastructure/config/components/AppearancePackageConfigSection.tsx b/src/web-ui/src/infrastructure/config/components/AppearancePackageConfigSection.tsx index 8322690604..4958c9c47a 100644 --- a/src/web-ui/src/infrastructure/config/components/AppearancePackageConfigSection.tsx +++ b/src/web-ui/src/infrastructure/config/components/AppearancePackageConfigSection.tsx @@ -1,4 +1,4 @@ -import { ActionCard } from '@openbitfun/ui'; +import { captureConfirmationAnchor, ActionCard } from '@openbitfun/ui'; import React, { useEffect, useMemo, useRef, useState } from 'react'; import { AlertTriangle } from 'lucide-react'; import { useTranslation } from 'react-i18next'; @@ -392,8 +392,9 @@ export function AppearancePackageConfigSection() { } }; - const handleDelete = async (id: string, name: string) => { + const handleDelete = async (id: string, name: string, trigger?: HTMLElement) => { const confirmed = await confirmDialog({ + anchor: captureConfirmationAnchor(trigger), title: t('package.deleteTitle'), message: t('package.deleteMessage', { name }), confirmText: t('package.delete'), @@ -461,7 +462,7 @@ export function AppearancePackageConfigSection() { title={t('package.delete')} aria-label={t('package.delete')} disabled={busy} - onClick={() => void handleDelete(selectedAppearance.id, selectedAppearance.name)} + onClick={event => void handleDelete(selectedAppearance.id, selectedAppearance.name, event.currentTarget)} icon={} /> diff --git a/src/web-ui/src/infrastructure/config/components/LocalVoiceModelsConfig.tsx b/src/web-ui/src/infrastructure/config/components/LocalVoiceModelsConfig.tsx index 627c06f035..1755a0e5ad 100644 --- a/src/web-ui/src/infrastructure/config/components/LocalVoiceModelsConfig.tsx +++ b/src/web-ui/src/infrastructure/config/components/LocalVoiceModelsConfig.tsx @@ -1,4 +1,4 @@ -import { OverflowText, +import { captureConfirmationAnchor, OverflowText, Button, Icon, IconButton, @@ -219,11 +219,12 @@ const LocalVoiceModelsConfig: React.FC = ({ } }, [t]); - const handleDelete = useCallback(async (model: SpeechModelStatus) => { + const handleDelete = useCallback(async (model: SpeechModelStatus, trigger?: HTMLElement) => { const confirmed = await confirmDanger( t('model.deleteConfirmTitle'), t('model.deleteConfirmMessage', { name: model.displayName }), { + anchor: captureConfirmationAnchor(trigger), confirmText: t('model.delete'), cancelText: t('model.keep'), }, @@ -271,7 +272,7 @@ const LocalVoiceModelsConfig: React.FC = ({ icon: , className: 'context-menu-item--danger', disabled: busyAction !== null, - onClick: () => handleDelete(model), + onClick: () => handleDelete(model, target), }, ]; showMenu( diff --git a/src/web-ui/src/infrastructure/config/components/McpToolsConfig.test.tsx b/src/web-ui/src/infrastructure/config/components/McpToolsConfig.test.tsx index a13c74e9ab..6866056cdb 100644 --- a/src/web-ui/src/infrastructure/config/components/McpToolsConfig.test.tsx +++ b/src/web-ui/src/infrastructure/config/components/McpToolsConfig.test.tsx @@ -925,7 +925,7 @@ describe('McpToolsConfig remote behavior', () => { expect(confirmDangerMock).toHaveBeenCalledWith( 'actions.delete', 'messages.deleteConfirm', - { confirmText: 'actions.delete', cancelText: 'actions.cancel' }, + { confirmText: 'actions.delete', cancelText: 'actions.cancel', anchor: expect.objectContaining({ element: deleteButton }) }, ); expect(deleteServerMock).toHaveBeenCalledWith({ serverId: 'local-test' }); expect(getServersMock).toHaveBeenCalledTimes(2); diff --git a/src/web-ui/src/infrastructure/config/components/McpToolsConfig.tsx b/src/web-ui/src/infrastructure/config/components/McpToolsConfig.tsx index 7dc364e47a..f94e34462a 100644 --- a/src/web-ui/src/infrastructure/config/components/McpToolsConfig.tsx +++ b/src/web-ui/src/infrastructure/config/components/McpToolsConfig.tsx @@ -4,7 +4,7 @@ * Uses settings/mcp-tools for page title/subtitle, settings/mcp for the MCP section. */ -import { +import { captureConfirmationAnchor, Button, Icon, IconButton, @@ -1063,13 +1063,14 @@ const McpToolsConfig: React.FC = () => { } }; - const handleDeleteServer = async (server: MCPServerInfo) => { + const handleDeleteServer = async (server: MCPServerInfo, trigger?: HTMLElement) => { const capabilityEpoch = currentCapabilityEpoch(); if (capabilityEpoch === null) return; const confirmed = await confirmDanger( tMcp('actions.delete'), tMcp('messages.deleteConfirm'), { + anchor: captureConfirmationAnchor(trigger), confirmText: tMcp('actions.delete'), cancelText: tMcp('actions.cancel'), }, @@ -1367,7 +1368,7 @@ const McpToolsConfig: React.FC = () => { handleDeleteServer(server)} + onClick={event => handleDeleteServer(server, event.currentTarget)} disabled={lifecyclePending} data-testid="mcp-server-delete" aria-label={tMcp('actions.delete')} diff --git a/src/web-ui/src/infrastructure/config/components/SkillsConfig.tsx b/src/web-ui/src/infrastructure/config/components/SkillsConfig.tsx index 1ed712f561..e0b84846af 100644 --- a/src/web-ui/src/infrastructure/config/components/SkillsConfig.tsx +++ b/src/web-ui/src/infrastructure/config/components/SkillsConfig.tsx @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-use-before-define */ -import { OverflowText, Button, Card, CardBody, ConfirmDialog, Field, Icon, IconButton, Input, SearchField, Select, Tooltip } from '@openbitfun/ui'; +import { captureConfirmationAnchor, OverflowText, Button, Card, CardBody, ConfirmDialog, Field, Icon, IconButton, Input, SearchField, Select, Tooltip } from '@openbitfun/ui'; import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { FolderOpen, TrendingUp } from 'lucide-react'; @@ -39,6 +39,7 @@ const SkillsConfig: React.FC = () => { const [isValidating, setIsValidating] = useState(false); const [isAdding, setIsAdding] = useState(false); + const [deleteAnchor, setDeleteAnchor] = useState>(undefined); const [deleteConfirm, setDeleteConfirm] = useState<{ show: boolean; skill: SkillInfo | null }>({ show: false, skill: null, @@ -337,7 +338,7 @@ const SkillsConfig: React.FC = () => { setDeleteConfirm({ show: true, skill })} + onClick={event => { setDeleteAnchor(captureConfirmationAnchor(event.currentTarget)); setDeleteConfirm({ show: true, skill }); }} title={t('list.item.deleteTooltip')} aria-label={t('list.item.deleteTooltip')} icon={} @@ -725,6 +726,7 @@ const SkillsConfig: React.FC = () => { setDeleteConfirm({ show: false, skill: null })} onConfirm={confirmDelete} diff --git a/src/web-ui/src/infrastructure/config/components/image-generation/ImageGenerationSection.tsx b/src/web-ui/src/infrastructure/config/components/image-generation/ImageGenerationSection.tsx index 061db103c5..a0ca943fe2 100644 --- a/src/web-ui/src/infrastructure/config/components/image-generation/ImageGenerationSection.tsx +++ b/src/web-ui/src/infrastructure/config/components/image-generation/ImageGenerationSection.tsx @@ -27,7 +27,7 @@ export function ImageGenerationAcquisitionRow({ settings }: Props) { } aria-label={t('acquisition.remove', { name: service.name || service.model_name })} disabled={settings.saving || Boolean(settings.testingId)} - onClick={() => void settings.remove(service)} /> + onClick={event => void settings.remove(service, event.currentTarget)} /> }> diff --git a/src/web-ui/src/infrastructure/config/components/image-generation/useImageGenerationSettings.ts b/src/web-ui/src/infrastructure/config/components/image-generation/useImageGenerationSettings.ts index 5338291d32..24a7815b92 100644 --- a/src/web-ui/src/infrastructure/config/components/image-generation/useImageGenerationSettings.ts +++ b/src/web-ui/src/infrastructure/config/components/image-generation/useImageGenerationSettings.ts @@ -1,3 +1,4 @@ +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { configManager } from '../../services/ConfigManager'; import { useConfigSeed } from '../../hooks/useConfigSeed'; @@ -121,9 +122,9 @@ export function useImageGenerationSettings() { await mutate(value => ({ ...value, image_services: value.image_services.map(item => item.id === service.id ? { ...item, enabled } : item), default_image_service: !enabled && value.default_image_service === service.id ? undefined : value.default_image_service })); }; - const remove = async (service: ImageServiceConfig) => { + const remove = async (service: ImageServiceConfig, trigger?: HTMLElement) => { const currentScope = scope; - if (!await confirmDialog({ title: t('delete.title'), message: t('delete.message', { name: service.name || service.model_name }), confirmText: t('delete.confirm'), type: 'warning' }) || !currentScope.isCurrent()) return; + if (!await confirmDialog({ anchor: captureConfirmationAnchor(trigger), title: t('delete.title'), message: t('delete.message', { name: service.name || service.model_name }), confirmText: t('delete.confirm'), type: 'warning' }) || !currentScope.isCurrent()) return; await mutate(value => ({ ...value, image_services: value.image_services.filter(item => item.id !== service.id), default_image_service: value.default_image_service === service.id ? undefined : value.default_image_service })); }; diff --git a/src/web-ui/src/infrastructure/confirm-dialog/ConfirmDialogRenderer.tsx b/src/web-ui/src/infrastructure/confirm-dialog/ConfirmDialogRenderer.tsx index 955eccdceb..3b55f45dd8 100644 --- a/src/web-ui/src/infrastructure/confirm-dialog/ConfirmDialogRenderer.tsx +++ b/src/web-ui/src/infrastructure/confirm-dialog/ConfirmDialogRenderer.tsx @@ -10,6 +10,7 @@ export function ConfirmDialogRenderer() { return ( { beforeEach(() => { + useConfirmDialogStore.getState().cancel(); + resetDeviceSurfaceForTest(); useConfirmDialogStore.setState({ isOpen: false, options: null, resolve: null }); }); + it('cancels a pending choice when the device changes, including a switch back', async () => { + const result = confirmDialogChoice({ title: 'Delete on this device?' }); + const oldReply = useConfirmDialogStore.getState().resolve!; + activateSurface('peer-a'); + activateSurface('local'); + oldReply('confirm'); + await expect(result).resolves.toBe('cancel'); + expect(useConfirmDialogStore.getState().isOpen).toBe(false); + expect(useConfirmDialogStore.getState().options).toBeNull(); + }); + it('resolves boolean confirmations through the shared renderer state', async () => { const result = confirmDialog({ title: 'Save?', message: 'Continue' }); diff --git a/src/web-ui/src/infrastructure/confirm-dialog/confirmDialogService.ts b/src/web-ui/src/infrastructure/confirm-dialog/confirmDialogService.ts index d37e126857..4089a2710e 100644 --- a/src/web-ui/src/infrastructure/confirm-dialog/confirmDialogService.ts +++ b/src/web-ui/src/infrastructure/confirm-dialog/confirmDialogService.ts @@ -1,10 +1,12 @@ import type { ReactNode } from 'react'; import { create } from 'zustand'; -import type { ConfirmDialogProps, ConfirmDialogType } from '@openbitfun/ui'; +import type { ConfirmationAnchor, ConfirmDialogProps, ConfirmDialogType } from '@openbitfun/ui'; +import { getActiveSurfaceScope, onSurfaceActivated } from '@/infrastructure/peer-device/deviceSurface'; export type ConfirmDialogChoice = 'confirm' | 'secondary' | 'cancel'; export interface ConfirmDialogOptions { + anchor?: ConfirmationAnchor; cancelText?: ReactNode; confirmDanger?: boolean; confirmText?: ReactNode; @@ -29,7 +31,10 @@ interface ConfirmDialogState { } export const useConfirmDialogStore = create((set, get) => { + let stopWatchingSurface: (() => void) | undefined; const settle = (choice: ConfirmDialogChoice) => { + stopWatchingSurface?.(); + stopWatchingSurface = undefined; const { resolve } = get(); set({ isOpen: false, options: null, resolve: null }); resolve?.(choice); @@ -46,7 +51,10 @@ export const useConfirmDialogStore = create((set, get) => { showChoice: (options) => new Promise((resolve) => { const previousResolve = get().resolve; if (previousResolve) previousResolve('cancel'); - set({ isOpen: true, options, resolve }); + stopWatchingSurface?.(); + const scope = getActiveSurfaceScope(); + stopWatchingSurface = onSurfaceActivated(() => get().cancel()); + set({ isOpen: true, options, resolve: choice => resolve(scope.isCurrent() ? choice : 'cancel') }); }), }; }); diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 9c9d402ea4..10958d7652 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -407,6 +407,9 @@ "exportMarkdown": "Export as Markdown", "exportMarkdownFull": "Export full process", "exportMarkdownResult": "Export result", + "delete": "Delete", + "deleteConfirmTitle": "Delete session", + "deleteConfirmMessage": "This session and its child sessions will be permanently deleted and cannot be restored.", "confirmEdit": "Confirm", "cancelEdit": "Cancel", "loading": "Loading...", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 1aa1f642fd..f88cd70512 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -407,6 +407,9 @@ "exportMarkdown": "导出为 Markdown", "exportMarkdownFull": "导出完整过程", "exportMarkdownResult": "导出结果", + "delete": "删除", + "deleteConfirmTitle": "删除会话", + "deleteConfirmMessage": "会话及其子会话将被永久删除,无法恢复。", "confirmEdit": "确认", "cancelEdit": "取消", "loading": "加载中...", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index 64cc9a2b88..d3f655f8b2 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -407,6 +407,9 @@ "exportMarkdown": "匯出為 Markdown", "exportMarkdownFull": "匯出完整過程", "exportMarkdownResult": "匯出結果", + "delete": "刪除", + "deleteConfirmTitle": "刪除會話", + "deleteConfirmMessage": "會話及其子會話將被永久刪除,無法復原。", "confirmEdit": "確認", "cancelEdit": "取消", "loading": "載入中...", diff --git a/src/web-ui/src/shared/context-menu-system/commands/builtin/file/DeleteCommand.ts b/src/web-ui/src/shared/context-menu-system/commands/builtin/file/DeleteCommand.ts index 441ced8085..87428715a5 100644 --- a/src/web-ui/src/shared/context-menu-system/commands/builtin/file/DeleteCommand.ts +++ b/src/web-ui/src/shared/context-menu-system/commands/builtin/file/DeleteCommand.ts @@ -1,3 +1,4 @@ +import { captureConfirmationAnchor } from '@openbitfun/ui'; import { BaseCommand } from '../../BaseCommand'; @@ -57,6 +58,7 @@ export class DeleteFileCommand extends BaseCommand { : t('common:contextMenu.confirmDeleteFile', { name: context.fileName }); return confirmDanger(t('common:file.delete'), message, { + anchor: captureConfirmationAnchor(context.targetElement), confirmText: t('common:actions.delete'), }); } diff --git a/src/web-ui/src/shared/context-system/components/ContextList/ContextList.test.tsx b/src/web-ui/src/shared/context-system/components/ContextList/ContextList.test.tsx index 7cfd38ef75..41a343cda3 100644 --- a/src/web-ui/src/shared/context-system/components/ContextList/ContextList.test.tsx +++ b/src/web-ui/src/shared/context-system/components/ContextList/ContextList.test.tsx @@ -27,6 +27,9 @@ const storage = vi.hoisted(() => { return implementation; }); +const confirmation = vi.hoisted(() => vi.fn()); +vi.mock('@/infrastructure/confirm-dialog', () => ({ confirmDanger: confirmation })); + vi.mock('@/infrastructure/i18n', () => ({ useI18n: () => ({ t: (key: string) => key }), })); @@ -66,6 +69,7 @@ describe('ContextList removal presence', () => { vi.useFakeTimers(); vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false }))); storage.clear(); + confirmation.mockReset().mockResolvedValue(false); useContextStore.setState({ contexts: [context('a'), context('b'), context('c')], validationStates: new Map(), @@ -112,6 +116,21 @@ describe('ContextList removal presence', () => { expect(contextIds()).toEqual(['a']); }); + it('confirms clearing beside its button and keeps contexts on cancellation', async () => { + const clear = container!.querySelector('[title="contextSystem.contextList.clearAllTitle"]')!; + await act(async () => clear.click()); + expect(confirmation).toHaveBeenCalledWith('contextSystem.contextList.clearAllTitle', 'contextSystem.contextList.clearAllConfirm', { + anchor: expect.objectContaining({ element: clear }), confirmText: 'contextSystem.contextList.clearAll', + }); + act(() => vi.advanceTimersByTime(160)); + expect(contextIds()).toEqual(['a', 'b', 'c']); + confirmation.mockResolvedValueOnce(true); + await act(async () => clear.click()); + expect(contextIds()).toEqual(['a', 'b', 'c']); + act(() => vi.advanceTimersByTime(160)); + expect(contextIds()).toEqual([]); + }); + it('commits a requested removal if the list unmounts during its exit', () => { act(() => container?.querySelector('[data-context-id="b"]')?.click()); diff --git a/src/web-ui/src/shared/context-system/components/ContextList/ContextList.tsx b/src/web-ui/src/shared/context-system/components/ContextList/ContextList.tsx index 77aabb6034..ea63cd6897 100644 --- a/src/web-ui/src/shared/context-system/components/ContextList/ContextList.tsx +++ b/src/web-ui/src/shared/context-system/components/ContextList/ContextList.tsx @@ -1,7 +1,8 @@ +import { confirmDanger } from '@/infrastructure/confirm-dialog'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { Button, Icon, ScrollArea } from '@openbitfun/ui'; +import { captureConfirmationAnchor, Button, Icon, ScrollArea } from '@openbitfun/ui'; import { AlertCircle } from 'lucide-react'; import { useContextStore, selectContexts } from '../../../stores/contextStore'; import { ContextCard } from '../ContextCard/ContextCard'; @@ -74,11 +75,13 @@ export const ContextList: React.FC = ({ removeAfterExit([id]); }, [contexts, leavingContextIds, removeAfterExit]); - const handleClearAll = useCallback(async () => { + const handleClearAll = useCallback(async (event: React.MouseEvent) => { if ( leavingContextIds.size === 0 - && await window.confirm(t('contextSystem.contextList.clearAllConfirm', { count: contexts.length })) + && await confirmDanger(t('contextSystem.contextList.clearAllTitle'), + t('contextSystem.contextList.clearAllConfirm', { count: contexts.length }), + { anchor: captureConfirmationAnchor(event.currentTarget), confirmText: t('contextSystem.contextList.clearAll') }) ) { removeAfterExit(contexts.map(context => context.id)); } diff --git a/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx b/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx new file mode 100644 index 0000000000..c1ff21b3d6 --- /dev/null +++ b/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx @@ -0,0 +1,131 @@ +// @vitest-environment jsdom +import React, { act, useRef, useState } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Button, ConfirmDialog, Dialog, MenuPopover, captureConfirmationAnchor } from '@openbitfun/ui'; + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +describe('confirmation at the action origin', () => { + let host: HTMLDivElement; + let root: Root; + let trigger: HTMLButtonElement; + const surface = () => document.querySelector('[role="alertdialog"]')!; + const button = (label: string) => [...document.querySelectorAll('button')].find(item => item.textContent === label)!; + const click = async (label: string) => { await act(async () => button(label).click()); }; + const key = async (value: string) => { await act(async () => document.activeElement!.dispatchEvent(new KeyboardEvent('keydown', { key: value, bubbles: true, cancelable: true }))); }; + + beforeEach(() => { + host = document.createElement('div'); document.body.append(host); root = createRoot(host); + trigger = document.createElement('button'); trigger.textContent = 'Origin'; document.body.append(trigger); + trigger.focus(); + vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(new DOMRect(240, 180, 48, 32)); + }); + afterEach(async () => { + await act(async () => root.unmount()); host.remove(); trigger.remove(); vi.restoreAllMocks(); + }); + + it('places a compact confirmation next to its trigger and focuses Cancel', () => { + act(() => root.render()); + expect(surface().dataset.presentation).toBe('anchored'); + expect(surface().getAttribute('aria-modal')).toBe('false'); + expect(surface().style.left).toBe('240px'); + expect(surface().style.top).toBe('216px'); + expect(document.activeElement).toBe(button('Cancel')); + expect(document.querySelector('[data-openbitfun-overlay-modal="true"]')).toBeNull(); + }); + + it('keeps the captured menu-item position after the original element unmounts', () => { + const anchor = captureConfirmationAnchor(trigger); + trigger.remove(); + act(() => root.render()); + expect(surface().style.left).toBe('240px'); + expect(surface().style.top).toBe('216px'); + }); + + it('flips and clamps at the window edge without moving to the screen center', () => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1000 }); + Object.defineProperty(window, 'innerHeight', { configurable: true, value: 600 }); + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () { + return this.getAttribute('role') === 'alertdialog' ? new DOMRect(0, 0, 320, 160) : new DOMRect(); + }); + vi.mocked(trigger.getBoundingClientRect).mockReturnValue(new DOMRect(940, 560, 40, 32)); + act(() => root.render()); + expect(surface().dataset.placement).toBe('top'); + expect(surface().style.left).toBe('672px'); + expect(surface().style.top).toBe('396px'); + }); + + it('keeps programmatic and high-impact confirmations modal without an origin', () => { + act(() => root.render()); + expect(surface().dataset.presentation).toBe('modal'); + expect(surface().getAttribute('aria-modal')).toBe('true'); + }); + + it('owns only the child confirmation inside an existing modal and returns focus', async () => { + const parentClosed = vi.fn(); + function Nested() { + const [anchor, setAnchor] = useState>(); + return <> + + + {anchor && setAnchor(undefined)} />}; + } + act(() => root.render()); + await click('Remove service'); + expect(document.activeElement).toBe(button('Cancel')); + expect(document.querySelectorAll('[data-openbitfun-overlay-modal="true"]')).toHaveLength(1); + await key('Escape'); + expect(parentClosed).not.toHaveBeenCalled(); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); + expect(document.activeElement).toBe(button('Remove service')); + }); + + it('prevents repeated confirmation and dismissal while an async action is pending', async () => { + let finish!: () => void; + const onConfirm = vi.fn(() => new Promise(resolve => { finish = resolve; })); + const onClose = vi.fn(); + act(() => root.render()); + act(() => { button('Delete').click(); button('Delete').click(); }); + expect(onConfirm).toHaveBeenCalledOnce(); + expect(button('Delete').disabled).toBe(true); + expect(button('Cancel').disabled).toBe(true); + await key('Escape'); + expect(onClose).not.toHaveBeenCalled(); + await act(async () => finish()); + expect(button('Delete').disabled).toBe(false); + }); + + it('confirms in the menu row, cancels with Escape, and forgets closed confirmations', async () => { + const deleted = vi.fn(); + function Menu() { + const anchor = useRef(null); + const [open, setOpen] = useState(false); + return <> + setOpen(false)} items={[ + { id: 'open', label: 'Open' }, + { id: 'delete', label: 'Delete card', tone: 'danger', onSelect: deleted, + confirmation: { description: 'Delete this card permanently?', cancelText: 'Cancel', confirmText: 'Confirm' } }, + ]} />; + } + act(() => root.render()); + await click('More'); await click('Delete card'); + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); + expect([...document.querySelectorAll('[role="menuitem"]')].map(item => item.textContent)).toEqual(['Open', 'Cancel', 'Confirm']); + expect(document.activeElement).toBe(button('Cancel')); + await key('ArrowRight'); expect(document.activeElement).toBe(button('Confirm')); + await key('Escape'); expect(document.activeElement).toBe(button('Delete card')); + expect(deleted).not.toHaveBeenCalled(); + await click('Delete card'); await key('Tab'); + expect(document.querySelector('[role="menu"]')?.getAttribute('aria-hidden')).toBe('true'); + await click('More'); + expect(document.querySelector('[data-openbitfun-menu-confirmation]')).toBeNull(); + await click('Delete card'); await click('More'); await click('More'); + expect(document.querySelector('[data-openbitfun-menu-confirmation]')).toBeNull(); + await click('Delete card'); await click('Confirm'); + expect(deleted).toHaveBeenCalledOnce(); + }); +}); From 20c3f921fbb42fd7698ce3539438ba346aacf40b Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Sat, 7 Nov 2026 12:10:15 +0800 Subject: [PATCH 3/3] fix(ui): retain pending actions when confirmation menus reopen --- design-system/packages/ui/README.md | 2 + .../src/components/Menu/MenuConfirmItem.tsx | 1 + .../ui/src/components/Menu/MenuPopover.tsx | 37 +++++++++++++++++-- .../ui/ConfirmationInteraction.test.tsx | 24 ++++++++++++ 4 files changed, 60 insertions(+), 4 deletions(-) diff --git a/design-system/packages/ui/README.md b/design-system/packages/ui/README.md index 0d7da35164..7c162cc644 100644 --- a/design-system/packages/ui/README.md +++ b/design-system/packages/ui/README.md @@ -784,6 +784,8 @@ confirmText, cancelText }` to its entry. `MenuConfirmItem` exposes the same behavior for composed menus: the row changes to Cancel / Confirm, focuses Cancel first, and Escape restores the original row. The confirmed action is awaited with both controls disabled; the host owns error presentation. +Reopening a `MenuPopover` keeps that action disabled until it settles, and a late +completion does not close the newly opened menu. Use `ConfirmDialog anchor={captureConfirmationAnchor(event.currentTarget)}` when a single-item action needs a short explanation beside its trigger. Capture diff --git a/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx b/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx index d40c80efdd..531b91d95d 100644 --- a/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx +++ b/design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx @@ -45,6 +45,7 @@ export function MenuConfirmItem({ confirmation, onConfirm, onActionError, disabl catch (error) { onActionError?.(error); } finally { pendingRef.current = false; + restoreFocus.current = true; setPending(false); setConfirming(false); } diff --git a/design-system/packages/ui/src/components/Menu/MenuPopover.tsx b/design-system/packages/ui/src/components/Menu/MenuPopover.tsx index 42d6cc6057..95f600d850 100644 --- a/design-system/packages/ui/src/components/Menu/MenuPopover.tsx +++ b/design-system/packages/ui/src/components/Menu/MenuPopover.tsx @@ -1,4 +1,4 @@ -import { useEffect, useId, useRef, useState, type ComponentType, type HTMLAttributes, type ReactNode, type RefObject } from "react"; +import { useEffect, useId, useLayoutEffect, useRef, useState, type ComponentType, type HTMLAttributes, type ReactNode, type RefObject } from "react"; import { Menu, MenuItem, MenuSeparator, type MenuProps, type MenuItemRole } from "./Menu"; import { Icon } from "../Icon"; import { classNames } from "../../internal/classNames"; @@ -68,12 +68,34 @@ export function MenuPopover({ items, open, onClose, anchorRef, ownerRef, positio const menuRef = useRef(null); const treeId = useId(); const { present, state: phase } = usePresence(open, exitDurationMs); + // Mutations outlive a dismissed menu. Keep their lock above the mounted rows, + // and do not let a late completion dismiss a newer opening of the menu. + const inFlightActions = useRef(new Set()); + const [pendingActions, setPendingActions] = useState>(new Set()); + const openingRevision = useRef(0); + useLayoutEffect(() => { + openingRevision.current += 1; + return () => { openingRevision.current += 1; }; + }, [open]); const resolvedAnchor = anchorRef ?? markerRef; const branchRefs = anchorRef ? [anchorRef] : []; const closeAndRestoreFocus = () => { if (anchorRef?.current?.isConnected) anchorRef.current.focus(); onClose(); }; + const confirmEntry = async (item: MenuEntry, key: string, trigger: HTMLButtonElement) => { + if (inFlightActions.current.has(key)) return; + inFlightActions.current.add(key); + setPendingActions(new Set(inFlightActions.current)); + const revision = openingRevision.current; + try { + await item.onSelect?.(trigger); + if (revision === openingRevision.current) closeAndRestoreFocus(); + } finally { + inFlightActions.current.delete(key); + setPendingActions(new Set(inFlightActions.current)); + } + }; useDismissibleLayer({ branchRefs, @@ -103,6 +125,8 @@ export function MenuPopover({ items, open, onClose, anchorRef, ownerRef, positio items={items} menuRef={menuRef} onClose={closeAndRestoreFocus} + onConfirmEntry={confirmEntry} + pendingActions={pendingActions} open={open} phase={phase} placement={placement} @@ -125,6 +149,9 @@ interface MenuLevelProps extends Omit { phase: string; treeId: string; onClose: () => void; + onConfirmEntry: (item: MenuEntry, key: string, trigger: HTMLButtonElement) => Promise; + pendingActions: ReadonlySet; + actionPath?: string; onBack?: () => void; anchorRef: RefObject; position?: { x: number; y: number }; @@ -134,7 +161,7 @@ interface MenuLevelProps extends Omit { parts?: MenuPopoverParts; } -function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, position, placement, overlapAnchor, menuRef: externalRef, autoFocusFirstItem, className, inlineSize, style, parts, ...props }: MenuLevelProps) { +function MenuLevel({ items, open, phase, treeId, onClose, onConfirmEntry, pendingActions, actionPath = "", onBack, anchorRef, position, placement, overlapAnchor, menuRef: externalRef, autoFocusFirstItem, className, inlineSize, style, parts, ...props }: MenuLevelProps) { const MenuSurface = parts?.root ?? Menu; const Item = parts?.item ?? MenuItem; const Separator = parts?.separator ?? MenuSeparator; @@ -154,6 +181,7 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos // Keep geometry until presence unmounts the menu, including its exit transition. const layout = useAnchoredLayer({ open: true, anchorRef, layerRef: menuRef, placement, overlapAnchor, point: position }); const activeEntry = items.find(item => item.id === activeId && !item.disabled && item.submenu?.length); + const actionKey = (id: string) => `${actionPath}/${encodeURIComponent(id)}`; const openSubmenu = (item: MenuEntry, trigger: HTMLElement, keyboard: boolean) => { if (item.disabled || !item.submenu?.length) return; submenuAnchor.current = trigger; @@ -212,6 +240,7 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos }); const submenu = activeEntry ? { intent.closeNow(); submenuAnchor.current?.focus(); }} anchorRef={submenuAnchor} placement="right" autoFocusFirstItem={keyboardOpen.current} onPointerEnter={intent.keepOpen} onPointerLeave={intent.requestClose} /> : null; @@ -220,8 +249,8 @@ function MenuLevel({ items, open, phase, treeId, onClose, onBack, anchorRef, pos style={{ ...layout?.style, ...style, visibility: layout ? undefined : "hidden" }} data-openbitfun-native-webview-occlusion data-openbitfun-menu-tree={treeId} data-placement={layout?.placement ?? placement} data-state={phase} aria-hidden={!open || undefined} {...inertProps(!open)} onContextMenu={event => event.preventDefault()}> {items.map(item => item.separator ? : item.confirmation ? { await item.onSelect?.(trigger); onClose(); }}>{item.label} + confirmation={item.confirmation} disabled={item.disabled || pendingActions.has(actionKey(item.id))} tone={item.tone} leading={item.icon} + onConfirm={trigger => onConfirmEntry(item, actionKey(item.id), trigger)}>{item.label} : {item.icon} : undefined} shortcut={item.shortcut ? {item.shortcut} : undefined} tone={item.tone} role={item.role} checked={item.checked} disabled={item.disabled} aria-disabled={item.disabled || undefined} aria-haspopup={item.submenu?.length ? "menu" : undefined} aria-expanded={item.submenu?.length ? activeEntry?.id === item.id : undefined} aria-controls={activeEntry?.id === item.id ? submenuId : undefined} metadata={item.submenu?.length ? : undefined} diff --git a/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx b/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx index c1ff21b3d6..042cbaaf85 100644 --- a/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx +++ b/src/web-ui/src/shared/ui/ConfirmationInteraction.test.tsx @@ -128,4 +128,28 @@ describe('confirmation at the action origin', () => { await click('Delete card'); await click('Confirm'); expect(deleted).toHaveBeenCalledOnce(); }); + + it('keeps an in-flight menu action disabled after reopening and preserves the new opening', async () => { + let finish!: () => void; + const deleted = vi.fn(() => new Promise(resolve => { finish = resolve; })); + function Menu() { + const anchor = useRef(null); + const [open, setOpen] = useState(false); + return <> + setOpen(false)} exitDurationMs={0} items={[ + { id: 'delete', label: 'Delete card', onSelect: deleted, + confirmation: { description: 'Delete this card?', cancelText: 'Cancel', confirmText: 'Confirm' } }, + ]} />; + } + act(() => root.render()); + await click('More'); await click('Delete card'); await click('Confirm'); + expect(deleted).toHaveBeenCalledOnce(); + await click('More'); await click('More'); + expect(button('Delete card').disabled).toBe(true); + await click('Delete card'); + expect(deleted).toHaveBeenCalledOnce(); + await act(async () => finish()); + expect(document.querySelector('[role="menu"]')?.getAttribute('aria-hidden')).toBeNull(); + expect(button('Delete card').disabled).toBe(false); + }); });