Skip to content

A full-featured download manager.

fix(add-task): read clipboard only when window opens

Dr_rOot9052cf4b225b
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 563c964a..b9c47e81 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -626,11 +626,20 @@ describe('buildCommandHandlers', () => {
it('ShowAddTaskWindow opens the add-task window', async () => {
const ctx = fakeCtx()
- ;(ctx.windowManager as any).open = vi.fn()
+ const send = vi.fn()
+ ;(ctx.windowManager as any).open = vi.fn(() => ({
+ isDestroyed: vi.fn(() => false),
+ webContents: {
+ isLoading: vi.fn(() => false),
+ once: vi.fn(),
+ send,
+ },
+ }))
// @ts-expect-error partial ctx
const handlers = buildCommandHandlers(ctx)
const result = await handlers[Commands.ShowAddTaskWindow]?.()
expect(ctx.windowManager.open).toHaveBeenCalledWith('add-task')
+ expect(send).toHaveBeenCalledWith(Events.SetAddTaskMode, { mode: 'links' })
expect(result).toEqual({ ok: true })
})
@@ -809,7 +818,9 @@ describe('buildCommandHandlers', () => {
const send = vi.fn()
const ctx = fakeCtx()
ctx.windowManager.open.mockReturnValue({
+ isDestroyed: vi.fn(() => false),
webContents: {
+ isLoading: vi.fn(() => true),
once: vi.fn((_event: string, handler: () => void) => {
didFinishLoad = handler
}),
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 35703274..41e9cb46 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -1055,10 +1055,16 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
[Commands.ShowAddTaskWindow]: async (rawPayload: unknown) => {
const { prefill } = showAddTaskWindowSchema.parse(rawPayload ?? {})
const win = windowManager.open('add-task')
- if (prefill) {
- win.webContents.once('did-finish-load', () => {
- win.webContents.send(Events.SetAddTaskMode, prefill)
- })
+ const showPayload = prefill ?? { mode: 'links' }
+ const sendShow = () => {
+ if (!win.isDestroyed()) {
+ win.webContents.send(Events.SetAddTaskMode, showPayload)
+ }
+ }
+ if (win.webContents.isLoading()) {
+ win.webContents.once('did-finish-load', sendShow)
+ } else {
+ sendShow()
}
return { ok: true }
},
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 43e39692..42430578 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -1,10 +1,11 @@
-import { render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import type { PlatformServices } from '@renderer/platform/services'
import { PlatformServicesProvider } from '@renderer/platform/services'
+import { Events } from '@shared/protocol/events'
import { AddTaskForm } from './add-task-form'
vi.mock('@renderer/lib/transport', () => ({
@@ -81,6 +82,31 @@ describe('AddTaskForm', () => {
)
})
+ it('only reads the clipboard after a precreated window is shown', async () => {
+ vi.mocked(mockServices.readClipboard).mockResolvedValue(
+ 'https://example.com/after-show.zip'
+ )
+ renderForm({ subscribeEvents: true })
+ expect(mockServices.readClipboard).not.toHaveBeenCalled()
+
+ const { transport } = await import('@renderer/lib/transport')
+ const setModeListener = vi
+ .mocked(transport.on)
+ .mock.calls.find(([channel]) => channel === Events.SetAddTaskMode)?.[1]
+ expect(setModeListener).toBeTypeOf('function')
+
+ act(() => {
+ setModeListener?.({ mode: 'links' })
+ })
+
+ await waitFor(() =>
+ expect(screen.getByRole('textbox')).toHaveValue(
+ 'https://example.com/after-show.zip'
+ )
+ )
+ expect(mockServices.readClipboard).toHaveBeenCalledOnce()
+ })
+
it('does not prefill when the setting is turned off', async () => {
const { transport } = await import('@renderer/lib/transport')
vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 929a8851..f4c61a82 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -14,7 +14,7 @@ import {
addTaskFormSchema,
formValuesToTaskCreateRequests,
} from '@shared/schemas/add-task'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import {
type DeepPartial,
FormProvider,
@@ -59,7 +59,41 @@ export function AddTaskForm({
defaultValues: { ...BASE_DEFAULTS, ...defaultValues } as AddTaskFormValues,
})
- useExternalHydration(form, subscribeEvents)
+ const clipboardAutofillRequest = useRef(0)
+
+ // Read once for each actual open. The desktop add-task window is precreated
+ // while hidden, so only its user-triggered SetAddTaskMode event starts a
+ // read; an in-page dialog is already visible when this form mounts.
+ const autofillClipboardLinks = useCallback(async () => {
+ const request = ++clipboardAutofillRequest.current
+ if (form.getValues('tab') !== 'links') return
+ if (form.getValues('urls')) return
+ try {
+ const settings = (await transport.invoke(Queries.GetSettings)) as {
+ app?: { autofillClipboardLinks?: boolean }
+ }
+ if (
+ request !== clipboardAutofillRequest.current ||
+ settings?.app?.autofillClipboardLinks === false
+ ) {
+ return
+ }
+ const content = (await platform.readClipboard()).trim()
+ if (request !== clipboardAutofillRequest.current || !content) return
+ const lines = parseUrlLines(content)
+ if (lines.length === 0 || !lines.every((line) => line.valid)) return
+ if (form.getValues('urls')) return
+ form.setValue(
+ 'urls' as never,
+ lines.map((line) => line.url).join('\n') as never,
+ { shouldValidate: true }
+ )
+ } catch {
+ // Best effort — the clipboard may be unreadable (web permissions).
+ }
+ }, [form, platform])
+
+ useExternalHydration(form, subscribeEvents, autofillClipboardLinks)
// Backfill saveDir from user settings when nothing populated it via
// URL params or an external hydration event. Without this the form
@@ -87,41 +121,16 @@ export function AddTaskForm({
}
}, [form])
- // One-shot clipboard autofill: when the dialog opens on the Links tab
- // with an empty URL field, read the clipboard once and prefill it when
- // every non-empty line is a downloadable link (http/https/ftp/magnet).
- // Gated by the autofillClipboardLinks setting; never a background
- // watcher, and external hydration always wins because it resets the form.
+ // Only immediately visible in-page dialogs read on mount. Desktop opens are
+ // triggered by useExternalHydration after SetAddTaskMode resets the
+ // precreated form, so precreation never accesses the clipboard and external
+ // prefill always wins.
useEffect(() => {
- if (form.getValues('tab') !== 'links') return
- if (form.getValues('urls')) return
- let cancelled = false
- ;(async () => {
- try {
- const settings = (await transport.invoke(Queries.GetSettings)) as {
- app?: { autofillClipboardLinks?: boolean }
- }
- if (cancelled || settings?.app?.autofillClipboardLinks === false) {
- return
- }
- const content = (await platform.readClipboard()).trim()
- if (cancelled || !content) return
- const lines = parseUrlLines(content)
- if (lines.length === 0 || !lines.every((line) => line.valid)) return
- if (form.getValues('urls')) return
- form.setValue(
- 'urls' as never,
- lines.map((line) => line.url).join('\n') as never,
- { shouldValidate: true }
- )
- } catch {
- // Best effort — the clipboard may be unreadable (web permissions).
- }
- })()
+ if (!subscribeEvents) void autofillClipboardLinks()
return () => {
- cancelled = true
+ clipboardAutofillRequest.current += 1
}
- }, [form, platform])
+ }, [autofillClipboardLinks, subscribeEvents])
const onSubmit = useCallback(
async (values: AddTaskFormValues) => {
diff --git a/src/renderer/components/add-task/use-external-hydration.test.ts b/src/renderer/components/add-task/use-external-hydration.test.ts
index 78545dab..16d2cf5d 100644
--- a/src/renderer/components/add-task/use-external-hydration.test.ts
+++ b/src/renderer/components/add-task/use-external-hydration.test.ts
@@ -116,6 +116,34 @@ describe('useExternalHydration', () => {
expect(values.urls).toBe('https://a/b')
})
+ it('notifies after SetAddTaskMode resets the form', () => {
+ const { result } = renderHook(() =>
+ useForm({
+ defaultValues: {
+ tab: 'links',
+ urls: 'https://old.example/file.zip',
+ saveDir: '/preset',
+ },
+ })
+ )
+ const onSetMode = vi.fn(() => {
+ expect(result.current.getValues('urls')).toBe('')
+ })
+ renderHook(() =>
+ useExternalHydration(
+ result.current as unknown as UseFormReturn<AddTaskFormValues>,
+ true,
+ onSetMode
+ )
+ )
+
+ act(() => {
+ fire(Events.SetAddTaskMode, { mode: 'links' })
+ })
+
+ expect(onSetMode).toHaveBeenCalledOnce()
+ })
+
it('SetAddTaskMode replaces dirty URL content from external opens', () => {
const { result } = renderHook(() =>
useForm({
diff --git a/src/renderer/components/add-task/use-external-hydration.ts b/src/renderer/components/add-task/use-external-hydration.ts
index cc7b6c95..7e13ef1d 100644
--- a/src/renderer/components/add-task/use-external-hydration.ts
+++ b/src/renderer/components/add-task/use-external-hydration.ts
@@ -12,7 +12,8 @@ import type { UseFormReturn } from 'react-hook-form'
export function useExternalHydration(
form: UseFormReturn<AddTaskFormValues>,
- enabled: boolean
+ enabled: boolean,
+ onModeHydrated?: () => void
) {
useEffect(() => {
if (!enabled) return
@@ -67,6 +68,7 @@ export function useExternalHydration(
form.reset(defaults as Partial<AddTaskFormValues>, {
keepErrors: false,
})
+ onModeHydrated?.()
}
transport.on(Events.MagnetFileSelection, onMagnet)
@@ -78,5 +80,5 @@ export function useExternalHydration(
transport.off(Events.ProtocolTorrentFile, onProtocol)
transport.off(Events.SetAddTaskMode, onSetMode)
}
- }, [form, enabled])
+ }, [form, enabled, onModeHydrated])
}