Skip to content

A full-featured download manager.

feat(add-task): autofill clipboard link when the dialog opens (#1889)

Dr_rOot8c8a3e1ce17f
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 da1caf28..43e39692 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -69,6 +69,83 @@ describe('AddTaskForm', () => {
expect(onCancel).toHaveBeenCalled()
})
+ it('prefills empty urls from the clipboard when autofill is enabled', async () => {
+ vi.mocked(mockServices.readClipboard).mockResolvedValue(
+ 'https://example.com/f.zip'
+ )
+ renderForm()
+ await waitFor(() =>
+ expect(screen.getByRole('textbox')).toHaveValue(
+ 'https://example.com/f.zip'
+ )
+ )
+ })
+
+ 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) => {
+ if (channel === 'query:getSettings') {
+ return { app: { autofillClipboardLinks: false } }
+ }
+ return { gid: 'test-gid' }
+ })
+ vi.mocked(mockServices.readClipboard).mockResolvedValue(
+ 'https://example.com/f.zip'
+ )
+ renderForm()
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith('query:getSettings')
+ )
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(mockServices.readClipboard).not.toHaveBeenCalled()
+ expect(screen.getByRole('textbox')).toHaveValue('')
+ })
+
+ it('does not overwrite urls that are already filled', async () => {
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) =>
+ channel === 'query:getSettings'
+ ? { app: { autofillClipboardLinks: true } }
+ : { gid: 'test-gid' }
+ )
+ vi.mocked(mockServices.readClipboard).mockResolvedValue('https://clip/x')
+ renderForm({
+ defaultValues: { tab: 'links', urls: 'https://kept/1', saveDir: '/d' },
+ })
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(screen.getByRole('textbox')).toHaveValue('https://kept/1')
+ })
+
+ it('ignores clipboard content that is not a downloadable link', async () => {
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) =>
+ channel === 'query:getSettings'
+ ? { app: { autofillClipboardLinks: true } }
+ : { gid: 'test-gid' }
+ )
+ vi.mocked(mockServices.readClipboard).mockResolvedValue(
+ 'hello world\nnot a url'
+ )
+ renderForm()
+ await waitFor(() => expect(mockServices.readClipboard).toHaveBeenCalled())
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(screen.getByRole('textbox')).toHaveValue('')
+ })
+
+ it('stays quiet when the clipboard cannot be read', async () => {
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel: string) =>
+ channel === 'query:getSettings'
+ ? { app: { autofillClipboardLinks: true } }
+ : { gid: 'test-gid' }
+ )
+ vi.mocked(mockServices.readClipboard).mockRejectedValue(new Error('denied'))
+ renderForm()
+ await waitFor(() => expect(mockServices.readClipboard).toHaveBeenCalled())
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ expect(screen.getByRole('textbox')).toHaveValue('')
+ })
+
it('submit flow calls transport and onSubmitSuccess', async () => {
const onSubmitSuccess = vi.fn()
const user = userEvent.setup()
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 9d352297..929a8851 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -27,6 +27,7 @@ import { useTranslation } from 'react-i18next'
import { FooterActions } from './footer-actions'
import { LinksTabPanel } from './links-tab-panel'
import { TorrentTabPanel } from './torrent-tab-panel'
+import { parseUrlLines } from './url-interpreters/multiline-url'
import { useExternalHydration } from './use-external-hydration'
interface AddTaskFormProps {
@@ -86,6 +87,42 @@ 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.
+ 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).
+ }
+ })()
+ return () => {
+ cancelled = true
+ }
+ }, [form, platform])
+
const onSubmit = useCallback(
async (values: AddTaskFormValues) => {
setSubmitting(true)
diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsx
index 49f1ab06..e98aaf73 100644
--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx
@@ -38,6 +38,7 @@ const SETTINGS_FIXTURE = {
notifyOnComplete: true,
notifyOnError: true,
warnBeforeQuit: true,
+ autofillClipboardLinks: true,
protocols: { magnet: true },
runMode: 1, // RunMode.Standard — numeric enum
theme: 'system',
@@ -106,6 +107,22 @@ describe('<GeneralDialog>', () => {
})
})
+ it('saves autofillClipboardLinks when toggled', async () => {
+ render(<GeneralDialog open onClose={() => {}} labelKey="" descKey="" />)
+
+ const toggle = await screen.findByRole('switch', {
+ name: /autofill link from clipboard/i,
+ })
+ await userEvent.click(toggle)
+ await userEvent.click(screen.getByRole('button', { name: /apply/i }))
+
+ await waitFor(() => {
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ app: { autofillClipboardLinks: false },
+ })
+ })
+ })
+
it('saves only dirty fields', async () => {
const onClose = vi.fn()
render(
diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsx
index 81eb7846..86a566ca 100644
--- a/src/renderer/routes/settings/cards/general-dialog.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.tsx
@@ -36,6 +36,7 @@ type GeneralFields = Pick<
| 'defaultSaveDir'
| 'notifyOnComplete'
| 'notifyOnError'
+ | 'autofillClipboardLinks'
| 'warnBeforeQuit'
>
@@ -47,6 +48,7 @@ const DEFAULTS: GeneralFields = {
defaultSaveDir: DEFAULT_APP_SETTINGS.defaultSaveDir,
notifyOnComplete: DEFAULT_APP_SETTINGS.notifyOnComplete,
notifyOnError: DEFAULT_APP_SETTINGS.notifyOnError,
+ autofillClipboardLinks: DEFAULT_APP_SETTINGS.autofillClipboardLinks,
warnBeforeQuit: DEFAULT_APP_SETTINGS.warnBeforeQuit,
}
@@ -74,6 +76,7 @@ export function GeneralDialog({
defaultSaveDir: all.app.defaultSaveDir,
notifyOnComplete: all.app.notifyOnComplete,
notifyOnError: all.app.notifyOnError,
+ autofillClipboardLinks: all.app.autofillClipboardLinks,
warnBeforeQuit: all.app.warnBeforeQuit,
})
}
@@ -157,6 +160,29 @@ export function GeneralDialog({
)}
/>
+ <FormField
+ control={form.control}
+ name="autofillClipboardLinks"
+ render={({ field }) => (
+ <FormItem className="flex items-start justify-between gap-4">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.autofillClipboardLinks')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.autofillClipboardLinksDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
<FormField
control={form.control}
name="notifyOnComplete"
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 9c83b9aa..74583ea2 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -935,6 +935,8 @@
"defaultSaveDirDesc": "New downloads land here unless overridden per-task.",
"notifyOnComplete": "Notify when download completes",
"notifyOnCompleteDesc": "Show a system notification when a task finishes.",
+ "autofillClipboardLinks": "Autofill link from clipboard",
+ "autofillClipboardLinksDesc": "When New Task opens, paste a link found in your clipboard into the empty URL field.",
"notifyOnError": "Notify on failure",
"notifyOnErrorDesc": "Show a system notification when a download fails while the window is in the background.",
"warnBeforeQuit": "Confirm before quitting",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index ff46e912..f6dfa914 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -922,6 +922,8 @@
"defaultSaveDirDesc": "新建下载默认保存到此目录,可按任务覆盖。",
"notifyOnComplete": "下载完成通知",
"notifyOnCompleteDesc": "任务完成时弹出系统通知。",
+ "autofillClipboardLinks": "新建任务时自动填入剪贴板链接",
+ "autofillClipboardLinksDesc": "打开新建任务时,若剪贴板中是链接则自动填入空白的 URL 输入框。",
"notifyOnError": "下载失败时通知",
"notifyOnErrorDesc": "当窗口处于后台时,下载失败会弹出系统通知。",
"warnBeforeQuit": "退出前确认",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index d7e0c07e..b5750f88 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -922,6 +922,8 @@
"defaultSaveDirDesc": "除非個別任務另有指定,新的下載會儲存在這裡。",
"notifyOnComplete": "下載完成時通知",
"notifyOnCompleteDesc": "任務完成時顯示系統通知。",
+ "autofillClipboardLinks": "新增任務時自動填入剪貼簿連結",
+ "autofillClipboardLinksDesc": "開啟新增任務時,若剪貼簿中是連結則自動填入空白的 URL 輸入框。",
"notifyOnError": "失敗時通知",
"notifyOnErrorDesc": "視窗在背景時,下載失敗會顯示系統通知。",
"warnBeforeQuit": "結束前確認",
diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.ts
new file mode 100644
index 00000000..b4a33bd3
--- /dev/null
+++ b/src/shared/schemas/app-settings.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { appSettingsSchema, DEFAULT_APP_SETTINGS } from './app-settings'
+
+describe('appSettingsSchema', () => {
+ it('defaults autofillClipboardLinks to true', () => {
+ expect(DEFAULT_APP_SETTINGS.autofillClipboardLinks).toBe(true)
+ expect(appSettingsSchema.parse({}).autofillClipboardLinks).toBe(true)
+ })
+
+ it('recovers from an invalid autofillClipboardLinks value', () => {
+ expect(
+ appSettingsSchema.parse({ autofillClipboardLinks: 'nope' })
+ .autofillClipboardLinks
+ ).toBe(true)
+ })
+})
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index f309cd9f..a3d08cea 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -16,6 +16,7 @@ export const appSettingsSchema = z.object({
defaultSaveDir: z.string().catch(''),
notifyOnComplete: z.boolean().catch(true),
notifyOnError: z.boolean().catch(true),
+ autofillClipboardLinks: z.boolean().catch(true),
protocols: z
.object({
magnet: z.boolean().catch(true),
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index 60b474c8..a1aea66b 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -209,6 +209,10 @@ export interface MotrixAppSettings {
defaultSaveDir: string
notifyOnComplete: boolean
notifyOnError: boolean
+ /** When true, opening the New Task dialog reads the clipboard once and
+ * fills the URL field with any link(s) found — only when the field is
+ * empty. One-shot on open; never a background clipboard watcher. */
+ autofillClipboardLinks: boolean
protocols: {
magnet: boolean
}