Skip to content

A full-featured download manager.

fix(ui): prevent overlay exit flicker and chart range replay (#2396)

Dr_rOot5d901d45b825
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
index ea64a5fc..24e7dd41 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
@@ -6,6 +6,7 @@ import { transport } from '@renderer/lib/transport'
import { ADD_TASK_COLLAPSED_HEIGHT } from '@shared/constants/add-task'
import { Events } from '@shared/protocol/events'
import type { AddTaskFormValues } from '@shared/schemas/add-task'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { useState } from 'react'
import { MemoryRouter, Route, Routes } from 'react-router'
import { AddTaskDialogHost } from './add-task-dialog-host'
@@ -94,6 +95,21 @@ function renderWithRouter() {
}
describe('AddTaskDialogHost', () => {
+ it('keeps the current form mounted throughout exit after invalidating its store session', async () => {
+ useAddTaskDialogStore.getState().openWith({ tab: 'torrent' })
+ renderWithRouter()
+ const dialog = screen.getByRole('dialog')
+ const form = screen.getByTestId('add-task-form-stub')
+ const defaults = screen.getByTestId('initial-values').textContent
+ const revision = useAddTaskDialogStore.getState().revision
+ const finish = holdExitAnimation(dialog)
+ act(() => useAddTaskDialogStore.getState().close())
+ expect(useAddTaskDialogStore.getState().revision).toBeGreaterThan(revision)
+ expect(useAddTaskDialogStore.getState().prefill).toBeUndefined()
+ expect(dialog).toContainElement(form)
+ expect(screen.getByTestId('initial-values').textContent).toBe(defaults)
+ await finish()
+ })
it('preserves edited drafts until discard is confirmed', () => {
useAddTaskDialogStore.getState().openWith({ tab: 'links' })
renderWithRouter()
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
index 9a4810ee..06d6062c 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
@@ -9,6 +9,7 @@ import {
import { WindowChromeCaptionIcon } from '@renderer/components/window-chrome/window-chrome'
import { MenuConfirmation } from '@renderer/features/application-menu/menu-confirmation'
import { WebDirectoryPickerDialog } from '@renderer/features/web-directory-picker/web-directory-picker-dialog'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { showMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
import { transport } from '@renderer/lib/transport'
import { PlatformServicesProvider } from '@renderer/platform/services'
@@ -47,6 +48,11 @@ export function AddTaskDialogHost() {
[]
)
const prefill = useAddTaskDialogStore((s) => s.prefill)
+ const presentation = useExitSnapshot(open, {
+ revision,
+ prefill,
+ torrentFiles,
+ })
const openWith = useAddTaskDialogStore((s) => s.openWith)
const close = useAddTaskDialogStore((s) => s.close)
const requestClose = useCallback(() => {
@@ -176,9 +182,10 @@ export function AddTaskDialogHost() {
</DialogHeader>
<PlatformServicesProvider services={webServices}>
<AddTaskForm
- key={revision}
- defaultValues={prefill}
- initialTorrentFiles={torrentFiles}
+ active={open}
+ key={presentation.revision}
+ defaultValues={presentation.prefill}
+ initialTorrentFiles={presentation.torrentFiles}
onDraftStateChange={onDraftStateChange}
onSubmitSuccess={onSubmitSuccess}
onCancel={requestClose}
diff --git a/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.test.ts b/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.test.ts
index b6ed4051..ecdc9253 100644
--- a/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.test.ts
+++ b/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.test.ts
@@ -1,5 +1,50 @@
-import { describe, expect, it } from 'vitest'
-import { clampDialogHeight } from './use-adaptive-dialog-height'
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ clampDialogHeight,
+ useAdaptiveDialogHeight,
+} from './use-adaptive-dialog-height'
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+it('holds the expanded height during exit and resets for the next opening', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ }
+ )
+ const frames: FrameRequestCallback[] = []
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ frames.push(callback)
+ return frames.length
+ })
+ vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
+ const dialog = document.createElement('div')
+ dialog.innerHTML =
+ '<header data-slot="dialog-header"></header><div data-adaptive-content></div><footer data-slot="add-task-form-footer"></footer>'
+ Object.defineProperty(dialog.children[1], 'scrollHeight', { value: 600 })
+ const ref = { current: dialog }
+ const { result, rerender } = renderHook(
+ ({ open }) =>
+ useAdaptiveDialogHeight(ref, {
+ collapsedHeight: 374,
+ maxHeight: 760,
+ open,
+ }),
+ { initialProps: { open: true } }
+ )
+ act(() => frames.pop()?.(0))
+ expect(result.current.height).toBe(600)
+ rerender({ open: false })
+ expect(result.current.height).toBe(600)
+ rerender({ open: true })
+ expect(result.current.height).toBe(374)
+})
describe('clampDialogHeight', () => {
const base = {
diff --git a/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.ts b/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.ts
index b174bda7..afbaaf33 100644
--- a/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.ts
+++ b/src/renderer/components/add-task-dialog/use-adaptive-dialog-height.ts
@@ -88,10 +88,8 @@ export function useAdaptiveDialogHeight(
}, [collapsedHeight])
useLayoutEffect(() => {
- if (!open) {
- setHeight(collapsedHeight)
- return
- }
+ if (!open) return
+ setHeight(collapsedHeight)
const dialog = dialogRef.current
if (!dialog) return
diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsx
index dd75a8c3..1e5ef527 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -8,6 +8,7 @@ import { readTorrentFile } from '@renderer/lib/parse-torrent-file'
import type { PlatformServices } from '@renderer/platform/services'
import { PlatformServicesProvider } from '@renderer/platform/services'
import { Events } from '@shared/protocol/events'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { AddTaskForm } from './add-task-form'
const { recordRecentMock, invokeMock } = vi.hoisted(() => ({
@@ -911,6 +912,28 @@ describe('AddTaskForm', () => {
)
})
+ it('keeps a closing draft visible without accepting click or global shortcut submissions', async () => {
+ const { transport } = await import('@renderer/lib/transport')
+ renderForm({
+ active: false,
+ defaultValues: {
+ tab: 'links',
+ urls: 'https://example.test/closing.zip',
+ saveDir: '/d',
+ },
+ })
+ expect(screen.getByRole('textbox')).toHaveValue(
+ 'https://example.test/closing.zip'
+ )
+ fireEvent.keyDown(window, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyDown(window, { key: 'Enter', metaKey: true })
+ await userEvent.click(screen.getByRole('button', { name: /download/i }))
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ 'command:createTask',
+ expect.anything()
+ )
+ })
+
it('requires confirmation before creating a renamed torrent copy', async () => {
const onSubmitSuccess = vi.fn()
const user = userEvent.setup()
@@ -953,6 +976,9 @@ describe('AddTaskForm', () => {
})
).toBeInTheDocument()
expect(recordRecentMock).not.toHaveBeenCalled()
+ const conflictDialog = screen.getByRole('alertdialog')
+ const conflictContent = conflictDialog.textContent
+ const finishExit = holdExitAnimation(conflictDialog)
await user.click(
screen.getByRole('button', { name: 'Create separate copy' })
)
@@ -965,5 +991,7 @@ describe('AddTaskForm', () => {
)
expect(onSubmitSuccess).toHaveBeenCalledWith('copy-task')
expect(recordRecentMock).not.toHaveBeenCalled()
+ expect(conflictDialog.textContent).toBe(conflictContent)
+ await finishExit()
})
})
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index af469566..02d96510 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -22,6 +22,7 @@ import {
TabsList,
TabsTrigger,
} from '@renderer/components/ui/tabs'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { invalidateTaskList } from '@renderer/hooks/use-task-list'
import type { ParsedTorrentFile } from '@renderer/lib/parse-torrent-file'
import { transport } from '@renderer/lib/transport'
@@ -83,6 +84,8 @@ import {
} from './use-external-hydration'
interface AddTaskFormProps {
+ /** A closing dialog retains its draft but must stop accepting submissions. */
+ active?: boolean
initialTorrentFiles?: ParsedTorrentFile[]
onDraftStateChange?: (dirty: boolean, busy: boolean) => void
defaultValues?: DeepPartial<AddTaskFormValues>
@@ -134,6 +137,7 @@ function notifyTaskCreateFailure(
}
export function AddTaskForm({
+ active = true,
defaultValues,
initialTorrentFiles,
onDraftStateChange,
@@ -161,6 +165,10 @@ export function AddTaskForm({
draft?: string
line?: number
} | null>(null)
+ const conflictPresentation = useExitSnapshot(
+ duplicateConflict !== null,
+ duplicateConflict
+ )
const form = useForm<AddTaskFormValues>({
resolver: zodResolver(addTaskFormSchema) as Resolver<AddTaskFormValues>,
@@ -401,7 +409,7 @@ export function AddTaskForm({
}, [advanceTorrentQueue, hasNextQueuedTorrent, onCancel])
const handleDownloadAllTorrents = useCallback(async () => {
- if (!hasNextQueuedTorrent()) return
+ if (!active || !hasNextQueuedTorrent()) return
setBatchSubmitting(true)
try {
const parsedValues = addTaskFormSchema.safeParse(form.getValues())
@@ -500,11 +508,18 @@ export function AddTaskForm({
} finally {
setBatchSubmitting(false)
}
- }, [form, hasNextQueuedTorrent, localTorrentQueue, onSubmitSuccess, platform])
+ }, [
+ active,
+ form,
+ hasNextQueuedTorrent,
+ localTorrentQueue,
+ onSubmitSuccess,
+ platform,
+ ])
const onSubmit = useCallback(
async (values: AddTaskFormValues) => {
- if (submitting || advancingTorrent || batchSubmitting) return
+ if (!active || submitting || advancingTorrent || batchSubmitting) return
setSubmitting(true)
try {
form.clearErrors('urls')
@@ -632,6 +647,7 @@ export function AddTaskForm({
}
},
[
+ active,
advancingTorrent,
batchSubmitting,
completeCurrentSubmission,
@@ -664,7 +680,7 @@ export function AddTaskForm({
)
const createSeparateCopy = useCallback(async () => {
- if (!duplicateConflict) return
+ if (!active || !duplicateConflict) return
setSubmitting(true)
try {
const result = (await transport.invoke(Commands.CreateTask, {
@@ -692,10 +708,11 @@ export function AddTaskForm({
} finally {
setSubmitting(false)
}
- }, [completeConflict, duplicateConflict, platform])
+ }, [active, completeConflict, duplicateConflict, platform])
// ⌘↵ / Ctrl+Enter submit
useEffect(() => {
+ if (!active) return
const handler = (e: KeyboardEvent) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
@@ -710,7 +727,7 @@ export function AddTaskForm({
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
- }, [form, onSubmit])
+ }, [active, form, onSubmit])
return (
<AddTaskLayoutProvider onAdvancedOpenChange={onAdvancedOpenChange}>
@@ -765,10 +782,10 @@ export function AddTaskForm({
</AlertDialogTitle>
<AlertDialogDescription>
{t(
- `task.add.duplicate.${duplicateConflict?.result.conflict.reason}`,
+ `task.add.duplicate.${conflictPresentation?.result.conflict.reason}`,
{
name:
- duplicateConflict?.result.conflict.existingTaskName ??
+ conflictPresentation?.result.conflict.existingTaskName ??
t('task.add.duplicate.filesOnDisk'),
}
)}
@@ -776,11 +793,12 @@ export function AddTaskForm({
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
- {duplicateConflict?.result.conflict.existingTaskId && (
+ {conflictPresentation?.result.conflict.existingTaskId && (
<AlertDialogAction
+ disabled={!duplicateConflict}
onClick={() => {
const taskId =
- duplicateConflict.result.conflict.existingTaskId
+ duplicateConflict?.result.conflict.existingTaskId
setDuplicateConflict(null)
if (taskId) void completeConflict(taskId)
}}
@@ -788,8 +806,11 @@ export function AddTaskForm({
{t('task.add.duplicate.showExisting')}
</AlertDialogAction>
)}
- {duplicateConflict?.result.conflict.canCreateCopy && (
- <AlertDialogAction onClick={() => void createSeparateCopy()}>
+ {conflictPresentation?.result.conflict.canCreateCopy && (
+ <AlertDialogAction
+ disabled={!duplicateConflict}
+ onClick={() => void createSeparateCopy()}
+ >
{t('task.add.duplicate.createCopy')}
</AlertDialogAction>
)}
diff --git a/src/renderer/components/desktop-kit/directory-history-menu.test.tsx b/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
index 4c75396c..bf7020f1 100644
--- a/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
+++ b/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
@@ -132,6 +132,51 @@ describe('DirectoryHistoryMenu', () => {
expect(screen.queryByText('/favorite')).not.toBeInTheDocument()
})
+ it.each([
+ ['electron', 'trigger'],
+ ['electron', 'outside'],
+ ['web', 'trigger'],
+ ['web', 'outside'],
+ ] as const)(
+ 'keeps %s history content until the exit animation finishes when closing via %s',
+ async (kind, dismissal) => {
+ mocks.kind = kind
+ const user = userEvent.setup()
+ render(
+ <>
+ <DirectoryHistoryMenu currentPath="/current" onSelect={vi.fn()} />
+ <button type="button">Outside</button>
+ </>
+ )
+ const trigger = screen.getByRole('button', { name: 'Directory history' })
+ await user.click(trigger)
+ const menu = await screen.findByRole('menu')
+ const content = menu.textContent
+ const items = screen.getAllByRole('menuitem')
+ let finishAnimation!: () => void
+ const finished = new Promise<void>((resolve) => {
+ finishAnimation = resolve
+ })
+ // JSDOM has no CSS animations; hold the real menu in its exit phase.
+ Object.defineProperty(menu, 'getAnimations', {
+ value: () => [{ finished }],
+ })
+
+ await user.click(
+ dismissal === 'trigger'
+ ? trigger
+ : screen.getByRole('button', { name: 'Outside' })
+ )
+ await waitFor(() => expect(menu).toHaveAttribute('data-closed'))
+ expect(menu).toBeInTheDocument()
+ expect(menu.textContent).toBe(content)
+ for (const item of items) expect(menu).toContainElement(item)
+
+ await act(async () => finishAnimation())
+ await waitFor(() => expect(menu).not.toBeInTheDocument())
+ }
+ )
+
it('supports keyboard selection and Escape with trigger focus restoration', async () => {
const onSelect = vi.fn()
const user = userEvent.setup()
diff --git a/src/renderer/components/desktop-kit/directory-history-menu.tsx b/src/renderer/components/desktop-kit/directory-history-menu.tsx
index 88a090ad..e344b23e 100644
--- a/src/renderer/components/desktop-kit/directory-history-menu.tsx
+++ b/src/renderer/components/desktop-kit/directory-history-menu.tsx
@@ -97,28 +97,25 @@ export function DirectoryHistoryMenu({
onKeyDownCapture={containSubmitShortcut}
onKeyDown={(event) => event.stopPropagation()}
>
- {open && (
- <>
- {kind === 'web' ? (
- <ServerHistoryItems
- currentPath={currentPath}
- onSelect={onSelect}
- popup={popup}
- />
- ) : (
- <AppHistoryItems
- currentPath={currentPath}
- onSelect={onSelect}
- popup={popup}
- />
- )}
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={openManager}>
- <DirectoryPreferencesIcon aria-hidden="true" />
- {t('directoryPreferences.manage')}
- </DropdownMenuItem>
- </>
+ {/* The portal keeps content mounted through the exit animation. */}
+ {kind === 'web' ? (
+ <ServerHistoryItems
+ currentPath={currentPath}
+ onSelect={onSelect}
+ popup={popup}
+ />
+ ) : (
+ <AppHistoryItems
+ currentPath={currentPath}
+ onSelect={onSelect}
+ popup={popup}
+ />
)}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={openManager}>
+ <DirectoryPreferencesIcon aria-hidden="true" />
+ {t('directoryPreferences.manage')}
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<DirectoryPreferencesDialog
diff --git a/src/renderer/components/window-chrome/motrix-menu-button.tsx b/src/renderer/components/window-chrome/motrix-menu-button.tsx
index 5f0adfb0..19536b05 100644
--- a/src/renderer/components/window-chrome/motrix-menu-button.tsx
+++ b/src/renderer/components/window-chrome/motrix-menu-button.tsx
@@ -265,7 +265,6 @@ function ElectronMotrixMenuButton() {
pendingExecution.current = null
restoreFocusRef.current = false
setOpen(false)
- setStack([])
setNarrow(small.matches)
}
const hide = () => {
diff --git a/src/renderer/features/application-menu/menu-confirmation.test.tsx b/src/renderer/features/application-menu/menu-confirmation.test.tsx
new file mode 100644
index 00000000..3f79e731
--- /dev/null
+++ b/src/renderer/features/application-menu/menu-confirmation.test.tsx
@@ -0,0 +1,29 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+import { MenuConfirmation } from './menu-confirmation'
+
+describe('MenuConfirmation exit', () => {
+ it('preserves its request while closing and uses a fresh request when reopened', async () => {
+ const run = vi.fn()
+ const close = vi.fn()
+ const view = render(
+ <MenuConfirmation request={{ kind: 'discard', run }} close={close} />
+ )
+ const dialog = screen.getByRole('dialog')
+ const finish = holdExitAnimation(dialog)
+ const content = dialog.textContent
+ view.rerender(<MenuConfirmation request={null} close={close} />)
+ expect(dialog).toHaveAttribute('data-closed')
+ expect(dialog.textContent).toBe(content)
+ fireEvent.click(screen.getByRole('button', { name: 'Discard' }))
+ expect(run).not.toHaveBeenCalled()
+ await finish()
+ view.rerender(
+ <MenuConfirmation request={{ kind: 'logout', run }} close={close} />
+ )
+ expect(screen.getByRole('dialog').textContent).not.toBe(content)
+ })
+})
diff --git a/src/renderer/features/application-menu/menu-confirmation.tsx b/src/renderer/features/application-menu/menu-confirmation.tsx
index 93a7960f..a218ffa6 100644
--- a/src/renderer/features/application-menu/menu-confirmation.tsx
+++ b/src/renderer/features/application-menu/menu-confirmation.tsx
@@ -7,8 +7,9 @@ import {
DialogHeader,
DialogTitle,
} from '@renderer/components/ui/dialog'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { useOperatorSession } from '@renderer/lib/operator-auth'
-import { useRef, useState } from 'react'
+import { useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
export interface MenuConfirmationRequest {
@@ -26,6 +27,11 @@ export function MenuConfirmation({
const { t } = useTranslation()
const [busy, setBusy] = useState(false)
const [failed, setFailed] = useState(false)
+ const open = request !== null
+ const presentation = useExitSnapshot(open, request)
+ useLayoutEffect(() => {
+ if (open) setFailed(false)
+ }, [open])
const pending = useRef(false)
const cancel = useRef<HTMLButtonElement>(null)
const session = useOperatorSession((state) => state.state)
@@ -46,23 +52,22 @@ export function MenuConfirmation({
}
return (
<Dialog
- open={request !== null}
+ open={open}
onOpenChange={(open) => {
if (!open && !busy) {
close()
- setFailed(false)
}
}}
>
<DialogContent initialFocus={cancel} showCloseButton={!busy}>
<DialogHeader>
<DialogTitle>
- {t(`applicationMenu.${request?.kind ?? 'clear'}Title`, {
- count: request?.count,
+ {t(`applicationMenu.${presentation?.kind ?? 'clear'}Title`, {
+ count: presentation?.count,
})}
</DialogTitle>
<DialogDescription>
- {t(`applicationMenu.${request?.kind ?? 'clear'}Description`)}
+ {t(`applicationMenu.${presentation?.kind ?? 'clear'}Description`)}
</DialogDescription>
</DialogHeader>
{failed && (
@@ -76,10 +81,10 @@ export function MenuConfirmation({
</Button>
<Button
variant="destructive"
- disabled={busy}
+ disabled={busy || !open}
onClick={() => void confirm()}
>
- {t(`applicationMenu.${request?.kind ?? 'clear'}Confirm`)}
+ {t(`applicationMenu.${presentation?.kind ?? 'clear'}Confirm`)}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/src/renderer/features/plugin-operations/operation-dialog.test.tsx b/src/renderer/features/plugin-operations/operation-dialog.test.tsx
new file mode 100644
index 00000000..df89b47e
--- /dev/null
+++ b/src/renderer/features/plugin-operations/operation-dialog.test.tsx
@@ -0,0 +1,42 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { OperationDialogHost } from './operation-dialog'
+import { useOperationDialog } from './operation-store'
+
+vi.mock('./operation-form', () => ({
+ default: ({ operationId }: { operationId: string }) => (
+ <input aria-label="Operation draft" defaultValue={operationId} />
+ ),
+}))
+
+describe('OperationDialogHost exit', () => {
+ beforeEach(() => useOperationDialog.getState().close())
+ it('preserves the mounted draft until exit finishes without retaining the live request', async () => {
+ useOperationDialog
+ .getState()
+ .openWith({ pluginId: 'example', operationId: 'first' })
+ render(<OperationDialogHost />)
+ const input = await screen.findByRole('textbox', {
+ name: 'Operation draft',
+ })
+ fireEvent.change(input, { target: { value: 'unsaved draft' } })
+ const dialog = screen.getByRole('dialog')
+ const finish = holdExitAnimation(dialog)
+ act(() => useOperationDialog.getState().close())
+ expect(useOperationDialog.getState().request).toBeNull()
+ expect(dialog).toContainElement(input)
+ expect(input).toHaveValue('unsaved draft')
+ await finish()
+ act(() =>
+ useOperationDialog
+ .getState()
+ .openWith({ pluginId: 'example', operationId: 'second' })
+ )
+ expect(
+ await screen.findByRole('textbox', { name: 'Operation draft' })
+ ).toHaveValue('second')
+ })
+})
diff --git a/src/renderer/features/plugin-operations/operation-dialog.tsx b/src/renderer/features/plugin-operations/operation-dialog.tsx
index beb59d55..f14f8fb1 100644
--- a/src/renderer/features/plugin-operations/operation-dialog.tsx
+++ b/src/renderer/features/plugin-operations/operation-dialog.tsx
@@ -5,6 +5,7 @@ import {
DialogHeader,
DialogTitle,
} from '@renderer/components/ui/dialog'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { lazy, Suspense } from 'react'
import { useTranslation } from 'react-i18next'
import { OperationsBoundary } from './operation-boundary'
@@ -14,6 +15,7 @@ import { operationSessionKey, useOperationDialog } from './operation-store'
const OperationForm = lazy(() => import('./operation-form'))
export function OperationDialogHost() {
const { request, close } = useOperationDialog()
+ const presentation = useExitSnapshot(!!request, request)
const { t } = useTranslation()
return (
<Dialog
@@ -34,10 +36,10 @@ export function OperationDialogHost() {
retry={t('common.retry')}
>
<Suspense fallback={<OperationSkeleton />}>
- {request && (
+ {presentation && (
<OperationForm
- key={operationSessionKey(request)}
- {...request}
+ key={operationSessionKey(presentation)}
+ {...presentation}
onClose={close}
/>
)}
diff --git a/src/renderer/hooks/use-exit-snapshot.ts b/src/renderer/hooks/use-exit-snapshot.ts
new file mode 100644
index 00000000..de9b6910
--- /dev/null
+++ b/src/renderer/hooks/use-exit-snapshot.ts
@@ -0,0 +1,10 @@
+import { useLayoutEffect, useRef } from 'react'
+
+/** Preserve presentation during exit; actions must still use the live state. */
+export function useExitSnapshot<T>(open: boolean, value: T): T {
+ const snapshot = useRef(value)
+ useLayoutEffect(() => {
+ if (open) snapshot.current = value
+ }, [open, value])
+ return open ? value : snapshot.current
+}
diff --git a/src/renderer/routes/dashboard/components/dashboard-grid.tsx b/src/renderer/routes/dashboard/components/dashboard-grid.tsx
index 0539b608..749239c5 100644
--- a/src/renderer/routes/dashboard/components/dashboard-grid.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-grid.tsx
@@ -700,7 +700,7 @@ function AddTileMenu({
)?.failureReason
const availableCount = tiles.filter((option) => option.available).length
return (
- <DropdownMenu onOpenChange={() => setHintReason(null)}>
+ <DropdownMenu onOpenChange={(open) => open && setHintReason(null)}>
<ToolbarButton
label={label}
disabled={disabled}
diff --git a/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx b/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx
index 44bef2a5..38b334cc 100644
--- a/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx
+++ b/src/renderer/routes/dashboard/components/dashboard-tile-frame.tsx
@@ -176,7 +176,7 @@ export function DashboardTileFrame({
<RemoveIcon aria-hidden />
</Button>
</ControlTooltip>
- <DropdownMenu onOpenChange={() => setHintReason(null)}>
+ <DropdownMenu onOpenChange={(open) => open && setHintReason(null)}>
<DropdownMenuTrigger
render={
<Button
diff --git a/src/renderer/routes/downloads/inspector/lifetime-transfer-card.test.tsx b/src/renderer/routes/downloads/inspector/lifetime-transfer-card.test.tsx
index dd7200ee..a27ccb3b 100644
--- a/src/renderer/routes/downloads/inspector/lifetime-transfer-card.test.tsx
+++ b/src/renderer/routes/downloads/inspector/lifetime-transfer-card.test.tsx
@@ -4,7 +4,7 @@ import { i18n } from '@renderer/lib/i18n'
import enUS from '@shared/locales/en-US.json'
import zhCN from '@shared/locales/zh-CN.json'
import { TaskTransferSampleFlag } from '@shared/types/task-inspector-activity'
-import { fireEvent, render, screen, within } from '@testing-library/react'
+import { act, fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
@@ -71,7 +71,10 @@ describe('LifetimeTransferCard', () => {
}
)
})
- afterEach(() => vi.restoreAllMocks())
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.useRealTimers()
+ })
it('uses independent smooth paths and the Dashboard colors with 12% fills', () => {
const { container } = render(card())
expect(container.querySelectorAll('.recharts-bar')).toHaveLength(0)
@@ -98,6 +101,41 @@ describe('LifetimeTransferCard', () => {
screen.getByTestId('activity-transfer-speed-scale')
).toHaveTextContent('4.1 KB/s')
})
+ it('starts live updates from the displayed scale after repeated range switches', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
+ const { rerender } = render(card(model()))
+ const firstX = () => {
+ const path = screen
+ .getByTestId('activity-transfer-chart-viewport')
+ .querySelector('.activity-transfer-line-down .recharts-area-curve')
+ ?.getAttribute('d')
+ return Number(path?.match(/^M(-?[\d.]+)/)?.[1])
+ }
+
+ let end = 400000
+ for (const range of [
+ 'lifetime',
+ 'session',
+ 'lifetime',
+ 'session',
+ ] as const) {
+ rerender(card(model(end), range))
+ const displayedX = firstX()
+ expect(Number.isFinite(displayedX)).toBe(true)
+ end += 1000
+ rerender(card(model(end), range))
+ expect(
+ screen.getByTestId('activity-transfer-chart-viewport')
+ ).toHaveAttribute('data-animating', 'true')
+ // The first sample may move by one second, never replay the other scale.
+ await act(async () => vi.advanceTimersByTime(100))
+ expect(Math.abs(firstX() - displayedX)).toBeLessThan(20)
+ // Exercise switches both during an animation and after it settles.
+ if (range === 'session')
+ await act(async () => vi.advanceTimersByTime(1500))
+ }
+ })
it.each(['ltr', 'rtl'] as const)(
'keeps a 60-second window that follows and pauses when browsing in %s',
(direction) => {
diff --git a/src/renderer/routes/downloads/inspector/lifetime-transfer-card.tsx b/src/renderer/routes/downloads/inspector/lifetime-transfer-card.tsx
index 08f0a76f..e1858d0a 100644
--- a/src/renderer/routes/downloads/inspector/lifetime-transfer-card.tsx
+++ b/src/renderer/routes/downloads/inspector/lifetime-transfer-card.tsx
@@ -219,7 +219,8 @@ export function LifetimeTransferCard({
const series = (overview = false) =>
(['down', 'up'] as const).map((kind) => (
<Area
- key={kind}
+ // A new range must not reuse the previous scale on the next live tick.
+ key={`${range}-${kind}`}
className={`activity-transfer-line-${kind}`}
dataKey={kind}
type="monotoneX"
diff --git a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx
index 0fdc196c..a69e29d7 100644
--- a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx
+++ b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.test.tsx
@@ -1,10 +1,33 @@
import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { makeDownloadTask } from '@test-utils/task'
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { RedownloadOverwriteDialog } from './redownload-overwrite-dialog'
describe('RedownloadOverwriteDialog', () => {
+ it('finishes its exit with the original task description after the target is cleared', async () => {
+ const props = { onOpenChange: vi.fn(), onConfirm: vi.fn() }
+ const view = render(
+ <RedownloadOverwriteDialog
+ open
+ target={makeDownloadTask({ name: 'sample.mp4' })}
+ {...props}
+ />
+ )
+ const dialog = screen.getByRole('alertdialog')
+ const content = dialog.textContent
+ const finish = holdExitAnimation(dialog)
+ view.rerender(
+ <RedownloadOverwriteDialog open={false} target={null} {...props} />
+ )
+ expect(dialog).toHaveAttribute('data-closed')
+ expect(dialog.textContent).toBe(content)
+ fireEvent.click(screen.getByRole('button', { name: 'Re-download' }))
+ expect(props.onConfirm).not.toHaveBeenCalled()
+ await finish()
+ })
it('does not render when target is null', () => {
const { container } = render(
<RedownloadOverwriteDialog
diff --git a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx
index d6254582..2f95cd5a 100644
--- a/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx
+++ b/src/renderer/routes/downloads/inspector/redownload-overwrite-dialog.tsx
@@ -9,6 +9,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from '@renderer/components/ui/alert-dialog'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import type { DownloadTask } from '@shared/types/task'
import { useTranslation } from 'react-i18next'
@@ -31,8 +32,9 @@ export function RedownloadOverwriteDialog({
onConfirm,
}: RedownloadOverwriteDialogProps) {
const { t } = useTranslation()
+ const presentation = useExitSnapshot(open, target)
- if (!target) return null
+ if (!presentation) return null
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
@@ -46,7 +48,7 @@ export function RedownloadOverwriteDialog({
</div>
<AlertDialogDescription>
{t('panel.downloads.action.redownloadOverwriteDescription', {
- name: target.name,
+ name: presentation.name,
})}
</AlertDialogDescription>
</AlertDialogHeader>
@@ -55,7 +57,7 @@ export function RedownloadOverwriteDialog({
{t('common.cancel')}
</AlertDialogCancel>
<AlertDialogAction
- disabled={busy}
+ disabled={busy || !open || !target}
onClick={(event) => {
event.preventDefault()
onConfirm()
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx
index f771b1d1..f5036a7b 100644
--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx
@@ -5,6 +5,8 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { RemoveTasksDialog } from './remove-tasks-dialog'
// Kept overrides: id:'t1' (≠ 'task-1'), name:'A task' (≠ 'task'),
@@ -31,6 +33,24 @@ function makeTask(overrides: Partial<DownloadTask> = {}): DownloadTask {
}
describe('RemoveTasksDialog', () => {
+ it('keeps the title and disk estimate after closing clears the target selection', async () => {
+ const props = {
+ preCheckDeleteFiles: true,
+ onOpenChange: vi.fn(),
+ onConfirm: vi.fn(),
+ }
+ const view = render(
+ <RemoveTasksDialog open selected={[makeTask()]} {...props} />
+ )
+ const dialog = screen.getByRole('dialog')
+ const content = dialog.textContent
+ const finish = holdExitAnimation(dialog)
+ view.rerender(<RemoveTasksDialog open={false} selected={[]} {...props} />)
+ expect(dialog).toHaveAttribute('data-closed')
+ expect(dialog.textContent).toBe(content)
+ expect(screen.getByRole('button', { name: 'Remove' })).toBeDisabled()
+ await finish()
+ })
it('renders single-task title with a middle ellipsis that keeps the extension', () => {
render(
<RemoveTasksDialog
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
index 17363b10..b8182d98 100644
--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
@@ -9,6 +9,7 @@ import {
DialogTitle,
} from '@renderer/components/ui/dialog'
import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { truncatePath } from '@shared/lib/path-display'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
@@ -78,6 +79,7 @@ export function RemoveTasksDialog({
onConfirm,
}: RemoveTasksDialogProps) {
const { formatBytes } = useByteFormat()
+ const presentation = useExitSnapshot(open, selected)
const { t } = useTranslation()
const checkboxId = useId()
@@ -93,8 +95,8 @@ export function RemoveTasksDialog({
}
}, [open, preCheckDeleteFiles])
- const showEstimate = deleteFiles && hasOutput(selected)
- const title = buildTitle(selected, t)
+ const showEstimate = deleteFiles && hasOutput(presentation)
+ const title = buildTitle(presentation, t)
return (
<Dialog
@@ -123,7 +125,7 @@ export function RemoveTasksDialog({
<WarningIcon className="size-3.5" />
<span>
{t('panel.downloads.action.removeFilesEstimate', {
- bytes: formatBytes(estimateDiskUsage(selected)),
+ bytes: formatBytes(estimateDiskUsage(presentation)),
})}
</span>
</div>
diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsx
index 11b66cab..1d92cd56 100644
--- a/src/renderer/routes/downloads/task-actions-menu.test.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx
@@ -20,6 +20,7 @@ import { TransportError } from '@shared/protocol/errors'
import { Queries } from '@shared/protocol/queries'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { makeDownloadTask } from '@test-utils/task'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -116,6 +117,22 @@ function setup(context = true, items = tasks) {
}
describe('TaskActionsMenu', () => {
+ it.each([true, false])(
+ 'keeps captured actions through dismissal after selection changes (context: %s)',
+ async (context) => {
+ const selection = setup(context)
+ if (context) fireEvent.contextMenu(screen.getByTestId('context-list'))
+ else await userEvent.click(screen.getByRole('button', { name: 'More' }))
+ const menu = await screen.findByRole('menu')
+ const content = menu.textContent
+ const finish = holdExitAnimation(menu)
+ act(() => selection.getState().clearSelection())
+ fireEvent.keyDown(menu, { key: 'Escape' })
+ await waitFor(() => expect(menu).toHaveAttribute('data-closed'))
+ expect(menu.textContent).toBe(content)
+ await finish()
+ }
+ )
it.each([true, false])(
're-downloads the selected completed task after confirmation (context menu: %s)',
async (context) => {
diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsx
index 32c5522a..f556ebb5 100644
--- a/src/renderer/routes/downloads/task-actions-menu.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.tsx
@@ -23,6 +23,7 @@ import {
subscribeMenuContext,
} from '@renderer/features/application-menu/task-context'
import { OperationTaskMenuItems } from '@renderer/features/plugin-operations/operation-task-menu'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { openMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
import { openTaskFile } from '@renderer/lib/open-task-file'
@@ -505,6 +506,7 @@ export function TaskActionsMenu({
<DropdownMenuGroup>{group.content}</DropdownMenuGroup>
</Fragment>
))
+ const presentation = useExitSnapshot(menuOpen, items)
if (children)
return (
<ContextMenu
@@ -536,7 +538,7 @@ export function TaskActionsMenu({
onCopyCapture={handleCopy}
className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
>
- {items}
+ {presentation}
</ContextMenuContent>
</ContextMenu>
)
@@ -569,7 +571,7 @@ export function TaskActionsMenu({
data-menu-density="compact"
className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
>
- {items}
+ {presentation}
</DropdownMenuContent>
</DropdownMenu>
)
diff --git a/src/renderer/routes/plugins/components/builtin-update-dialog.test.tsx b/src/renderer/routes/plugins/components/builtin-update-dialog.test.tsx
index e9eaed9b..ec86b41f 100644
--- a/src/renderer/routes/plugins/components/builtin-update-dialog.test.tsx
+++ b/src/renderer/routes/plugins/components/builtin-update-dialog.test.tsx
@@ -1,6 +1,7 @@
import '@renderer/lib/i18n'
import '@testing-library/jest-dom/vitest'
import { Commands } from '@shared/protocol/commands'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -18,6 +19,24 @@ beforeEach(() => {
})
describe('BuiltinUpdateDialog', () => {
+ it('keeps consent details throughout exit instead of reverting to working', async () => {
+ mockInvoke.mockResolvedValue({
+ needsConsent: true,
+ stagingId: 's1',
+ added: ['perm:ffmpeg'],
+ newVersion: '1.1.0',
+ })
+ const props = { pluginId: 'motrix.scraper-hook', onOpenChange: vi.fn() }
+ const view = render(<BuiltinUpdateDialog open {...props} />)
+ await screen.findByText('perm:ffmpeg')
+ const dialog = screen.getByRole('dialog')
+ const content = dialog.textContent
+ const finish = holdExitAnimation(dialog)
+ view.rerender(<BuiltinUpdateDialog open={false} {...props} />)
+ expect(dialog).toHaveAttribute('data-closed')
+ expect(dialog.textContent).toBe(content)
+ await finish()
+ })
it('renders the added list on needsConsent and confirm invokes ConfirmBuiltinUpdate', async () => {
mockInvoke.mockImplementation((channel: string) => {
if (channel === Commands.InstallBuiltinUpdate) {
diff --git a/src/renderer/routes/plugins/components/builtin-update-dialog.tsx b/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
index 38986c06..270680fe 100644
--- a/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
+++ b/src/renderer/routes/plugins/components/builtin-update-dialog.tsx
@@ -8,6 +8,7 @@ import {
DialogHeader,
DialogTitle,
} from '@renderer/components/ui/dialog'
+import { useExitSnapshot } from '@renderer/hooks/use-exit-snapshot'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import type { PluginNetworkFailure } from '@shared/schemas/plugin-network'
@@ -31,6 +32,7 @@ type Phase =
export function BuiltinUpdateDialog({ pluginId, open, onOpenChange }: Props) {
const { t } = useTranslation()
const [phase, setPhase] = useState<Phase>({ kind: 'working' })
+ const presentation = useExitSnapshot(open, phase)
const startedRef = useRef(false)
const clearUpdate = usePluginsStore((s) => s.clearUpdate)
@@ -123,41 +125,41 @@ export function BuiltinUpdateDialog({ pluginId, open, onOpenChange }: Props) {
<DialogContent className="max-w-[480px]">
<DialogHeader>
<DialogTitle>{t('plugins.registry.builtinUpdateTitle')}</DialogTitle>
- {phase.kind === 'consent' && (
+ {presentation.kind === 'consent' && (
<DialogDescription>
{t('plugins.registry.builtinConsentLead')}
</DialogDescription>
)}
</DialogHeader>
- {phase.kind === 'error' && (
+ {presentation.kind === 'error' && (
<Alert variant="destructive">
<span className="text-xs">
- {phase.message.endsWith('plugins.security.blocked')
+ {presentation.message.endsWith('plugins.security.blocked')
? t('plugins.security.blocked')
- : phase.message.endsWith('plugins.security.pending')
+ : presentation.message.endsWith('plugins.security.pending')
? t('plugins.security.pending')
- : phase.message}
+ : presentation.message}
</span>
</Alert>
)}
- {phase.kind === 'consent' && (
+ {presentation.kind === 'consent' && (
<ul className="list-disc ps-5 font-mono text-xs">
- {phase.added.map((a) => (
+ {presentation.added.map((a) => (
<li key={a}>{a}</li>
))}
</ul>
)}
- {phase.kind === 'done' && (
+ {presentation.kind === 'done' && (
<p className="text-sm text-muted-foreground">
- {phase.restartRequired
+ {presentation.restartRequired
? t('plugins.registry.restartRequired')
: t('plugins.registry.updateInstalled')}
</p>
)}
<DialogFooter>
- {phase.kind === 'consent' ? (
+ {presentation.kind === 'consent' ? (
<>
<Button variant="outline" size="sm" onClick={() => void cancel()}>
{t('common.cancel')}
diff --git a/src/renderer/routes/plugins/plugin-install-dialog.test.tsx b/src/renderer/routes/plugins/plugin-install-dialog.test.tsx
index f69baa81..dad61a02 100644
--- a/src/renderer/routes/plugins/plugin-install-dialog.test.tsx
+++ b/src/renderer/routes/plugins/plugin-install-dialog.test.tsx
@@ -1,11 +1,16 @@
import '@test-utils/dom-animations'
import '@renderer/lib/i18n'
import '@testing-library/jest-dom/vitest'
+import {
+ type PlatformServices,
+ PlatformServicesProvider,
+} from '@renderer/platform/services'
import type {
ConsentPayload,
ConsentPayloadFfmpegRuntime,
} from '@shared/types/plugin-install'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
interface MockInstallState {
@@ -71,6 +76,73 @@ beforeEach(() => {
})
describe('PluginInstallDialog', () => {
+ it('starts a fresh input session and ignores an old file preparation when reopened during exit', async () => {
+ let finishFile!: (value: {
+ sourceType: 'local'
+ absPath: string
+ fileHash: string
+ }) => void
+ const prepare = vi.fn().mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishFile = resolve
+ })
+ )
+ const services: PlatformServices = {
+ kind: 'electron',
+ pluginInstallFile: { mode: 'local-path', prepare },
+ pickSaveDir: vi.fn(),
+ closeHost: vi.fn(),
+ readClipboard: vi.fn(),
+ openExternal: vi.fn(),
+ notify: vi.fn(),
+ }
+ const onOpenChange = vi.fn()
+ const content = (open: boolean) => (
+ <PlatformServicesProvider services={services}>
+ <PluginInstallDialog open={open} onOpenChange={onOpenChange} />
+ </PlatformServicesProvider>
+ )
+ const view = render(content(true))
+ const dialog = screen.getByRole('dialog')
+ const input = screen.getByPlaceholderText(/Paste a GitHub/i)
+ const finishExit = holdExitAnimation(dialog)
+ fireEvent.change(dialog.querySelector('input[type="file"]')!, {
+ target: { files: [new File(['plugin'], 'old.moext')] },
+ })
+ expect(prepare).toHaveBeenCalledOnce()
+ view.rerender(content(false))
+ expect(dialog).toContainElement(input)
+ expect(input).toHaveValue('old.moext')
+ view.rerender(content(true))
+ expect(screen.getByPlaceholderText(/Paste a GitHub/i)).not.toBe(input)
+ expect(screen.getByPlaceholderText(/Paste a GitHub/i)).toHaveValue('')
+ await act(async () =>
+ finishFile({
+ sourceType: 'local',
+ absPath: '/old.moext',
+ fileHash: 'a'.repeat(64),
+ })
+ )
+ expect(state.startInstall).not.toHaveBeenCalled()
+ view.rerender(content(false))
+ await finishExit()
+ })
+
+ it('keeps the source input and its draft throughout exit', async () => {
+ const props = { onOpenChange: vi.fn() }
+ const view = render(<PluginInstallDialog open {...props} />)
+ const input = screen.getByPlaceholderText(/Paste a GitHub/i)
+ fireEvent.change(input, { target: { value: 'owner/repo' } })
+ const dialog = screen.getByRole('dialog')
+ const finish = holdExitAnimation(dialog)
+ view.rerender(<PluginInstallDialog open={false} {...props} />)
+ expect(dialog).toHaveAttribute('data-closed')
+ expect(dialog).toContainElement(input)
+ expect(input).toHaveValue('owner/repo')
+ await finish()
+ })
+
it('renders only PluginInputGroup in stage 1', () => {
render(<PluginInstallDialog open onOpenChange={vi.fn()} />)
expect(screen.getByText('Add plugin')).toBeInTheDocument()
diff --git a/src/renderer/routes/plugins/plugin-install-dialog.tsx b/src/renderer/routes/plugins/plugin-install-dialog.tsx
index 814f787a..72cd4881 100644
--- a/src/renderer/routes/plugins/plugin-install-dialog.tsx
+++ b/src/renderer/routes/plugins/plugin-install-dialog.tsx
@@ -106,6 +106,11 @@ function PluginInstallSession({
const install = usePluginInstall()
const clearUpdate = usePluginsStore((s) => s.clearUpdate)
const [grants, setGrants] = useState<GrantsMap>({})
+ const [inputSession, setInputSession] = useState({ open, revision: 0 })
+ if (inputSession.open !== open) {
+ // Retain the closing input, but fence its async work from a rapid reopen.
+ setInputSession({ open, revision: inputSession.revision + Number(open) })
+ }
const startedRef = useRef(false)
const wasOpenRef = useRef(false)
const cancelButtonRef = useRef<HTMLButtonElement>(null)
@@ -283,18 +288,22 @@ function PluginInstallSession({
</Alert>
)}
- {preparing && !renderTrigger && (
- <div
- role="status"
- className="flex items-center gap-3 py-6 text-sm text-muted-foreground"
- >
- <Spinner aria-hidden="true" />
- <span>{t('plugins.install.preparing')}</span>
- </div>
- )}
+ {fixedSource &&
+ !install.consent &&
+ !install.error &&
+ !renderTrigger && (
+ <div
+ role="status"
+ className="flex items-center gap-3 py-6 text-sm text-muted-foreground"
+ >
+ <Spinner aria-hidden="true" />
+ <span>{t('plugins.install.preparing')}</span>
+ </div>
+ )}
- {open && !fixedSource && !install.consent && (
+ {!fixedSource && !install.consent && (
<PluginInputGroup
+ key={inputSession.revision}
onCheck={onCheck}
checking={install.pending}
/>
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
index cc890644..59cd5f60 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.test.tsx
@@ -3,6 +3,7 @@ import '@renderer/lib/i18n'
import '@testing-library/jest-dom/vitest'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
+import { holdExitAnimation } from '@test-utils/hold-exit-animation'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -66,6 +67,22 @@ describe('<AdvancedDialog>', () => {
expect(transport.invoke).toHaveBeenCalledWith(Queries.GetSettings)
})
+ it('keeps the settings file section throughout exit', async () => {
+ const props = {
+ onClose: vi.fn(),
+ labelKey: 'settings.cards.advanced.title',
+ descKey: 'settings.cards.advanced.desc',
+ }
+ const view = render(<AdvancedDialog open {...props} />)
+ const path = await screen.findByTitle('/profile/settings.json')
+ const dialog = screen.getByRole('dialog')
+ const finish = holdExitAnimation(dialog)
+ view.rerender(<AdvancedDialog open={false} {...props} />)
+ expect(dialog).toHaveAttribute('data-closed')
+ expect(dialog).toContainElement(path)
+ await finish()
+ })
+
it('aborts submit when no fields are dirty', async () => {
const onClose = vi.fn()
render(
diff --git a/src/renderer/routes/settings/cards/advanced-dialog.tsx b/src/renderer/routes/settings/cards/advanced-dialog.tsx
index ee3fdaa3..69c5ea42 100644
--- a/src/renderer/routes/settings/cards/advanced-dialog.tsx
+++ b/src/renderer/routes/settings/cards/advanced-dialog.tsx
@@ -499,7 +499,7 @@ export function AdvancedDialog({
</form>
</Form>
<Separator className="my-4" />
- {open && <SettingsFileSection />}
+ <SettingsFileSection />
{__MOTRIX_TARGET__ === 'electron' && (
<>
<Separator className="my-4" />
diff --git a/src/test-utils/hold-exit-animation.ts b/src/test-utils/hold-exit-animation.ts
new file mode 100644
index 00000000..033ecf96
--- /dev/null
+++ b/src/test-utils/hold-exit-animation.ts
@@ -0,0 +1,18 @@
+import { act, waitFor } from '@testing-library/react'
+import { expect } from 'vitest'
+
+/** Keep the real Base UI popup mounted while asserting its exit presentation. */
+export function holdExitAnimation(popup: Element) {
+ let finish!: () => void
+ const finished = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ Object.defineProperty(popup, 'getAnimations', {
+ configurable: true,
+ value: () => [{ finished }],
+ })
+ return async () => {
+ await act(async () => finish())
+ await waitFor(() => expect(popup.isConnected).toBe(false))
+ }
+}