Skip to content

A full-featured download manager.

feat(directories): add server picker and shared folder preferences (#2144)

Dr_rOot663c73e046a1
diff --git a/docs/docker-server.md b/docs/docker-server.md
index 8317a300..b764d98e 100644
--- a/docs/docker-server.md
+++ b/docs/docker-server.md
@@ -491,6 +491,105 @@ services:
- /srv/archive:/archive
```
+### Choosing a folder in the Web UI
+
+The folder controls in Add links, Add torrent, and General settings open a
+server folder picker. Its paths belong to the server: with the example mounts,
+`/downloads/Movies` maps to `./downloads/Movies` on the Docker host. A browser
+on another computer does not browse that computer’s local folders.
+
+Single-click a folder to select it, or double-click to enter it. The list shows
+only immediate child folders. Use Back, Forward, Up one level, or a breadcrumb
+to navigate; use Go to folder to enter an exact absolute path. The Location sidebar
+groups accessible common places, allowed roots, favorite folders and recent
+folders. Common places include the default directory, the server user’s home,
+existing Desktop/Documents/Downloads directories, and the filesystem root when
+allowed. On narrow screens, Location becomes a grouped menu. Up stops at the
+current allowed root. Open **View options → Show hidden folders** in the toolbar
+to include names beginning with a dot.
+
+The same **View options** menu sorts folders by **Name** or **Date modified**,
+in ascending or descending order. Name sorting treats numbers naturally, such
+as folder2 before folder10. Your browser remembers the choice. Sorting keeps
+the selected folder and changes only the loaded list, without another server
+request. Unknown modification times stay last; if the list is incomplete,
+sorting applies to the folders currently shown.
+
+Select folder chooses the highlighted child, or the current folder when no
+child is selected. Cancelling leaves the original form value unchanged. The
+selection is checked again by the server; submitting a download or applying
+settings remains a separate action. Browsing and selecting do not create
+folders.
+
+Add links and Add torrent also have a Directory history button beside Browse.
+Choose a favorite or recent path there to fill the form directly. This does not
+start a download. The desktop App offers the same history menu and keeps its
+system-native Browse dialog.
+
+Open **Settings → General** to manage folders below the default save directory.
+The compact form can add or remove favorites, promote a recent folder, delete
+one recent record, or clear the displayed recent records. Save applies these
+edits together with General settings; Cancel discards them. The history menu’s
+Manage directories entry opens the same folder controls with Save and Cancel.
+Removing records never deletes folders or downloads. Concurrently added records
+are preserved when saving your edits.
+If a save fails, the form keeps your edits. You can retry or change the values
+and save again; a delayed response from the earlier save will not overwrite the
+later choice. A failed response can follow a saved update, so Cancel does not
+undo a save that the server already committed.
+Favorite folders are limited to 20; the 10 most recent folders appear newest
+first. AddTask folder confirmations and directories used by successful
+AddTask submissions update recent history. General folder choices remain drafts
+and do not themselves enter recent history. Cancelling the folder picker does
+not add a record; cancelling AddTask afterward does not undo an already
+confirmed folder choice. Adding a favorite in the manager does not itself add
+a recent record. Headless/CLI downloads are not automatically imported into
+this UI history.
+
+Favorite and recent records belong to the Motrix instance: they persist in
+app settings on Desktop and on the server for Web clients. Connected clients
+receive updates, and reconnecting reloads the current records. The Web history
+menu and folder sidebar only offer paths still permitted and accessible on the
+server. The manager retains saved records so unavailable paths can be removed.
+The star in the Web picker immediately adds or removes the folder currently being
+browsed, while keeping the directory list and current position stable.
+These operations do not change the default save directory.
+
+The keyboard follows the browser computer’s operating system, independently of
+the server. With focus in the list:
+
+| Action | macOS | Windows / Linux |
+| --- | --- | --- |
+| Select a folder | Up / Down | Up / Down |
+| First / last folder | Home / End | Home / End |
+| Move by a visible page | Page Up / Page Down | Page Up / Page Down |
+| Enter the selected folder | Command + Down | Enter |
+| Up one level | Command + Up | Alt + Up, or Backspace |
+| Confirm selection | Return | Tab to Select folder, then Enter |
+| Edit the current path | `/`, or Command + Shift + G if the browser delivers it | `/` |
+| Go to Home / Desktop / Documents, when available | Command + Shift + H / D / O | Use Location |
+
+Type a folder-name prefix to select a match. Tab and Shift + Tab move between
+controls. In the path editor, Enter navigates and Escape cancels editing; Escape
+outside an editor closes the picker. Browser-reserved shortcuts keep their
+browser behavior.
+
+Use New folder at the bottom-left to create one folder inside the current
+location. Enter a name
+and press Enter or Create; Escape cancels the name editor. After creation, the
+new folder is selected so it can be confirmed immediately. **A created folder
+remains on the server even if you later cancel selection.** A conflict or
+permission error keeps the name available for correction. If the server’s
+response is lost, refresh and check the list before trying to create again.
+
+Very large folders may show an incomplete-list notice. Enter the exact path to
+reach a folder omitted from the list. Permission checks use the server process
+user and may fail on a read-only mount or a NAS ACL. The allowlist rejects path
+traversal and static symlink escape. As with saving downloads, portable path
+checks do not protect against a hostile local process replacing directory
+ancestors at the same time; restrict write access to the mounted directory
+hierarchy accordingly.
+
Built-in plugins are read-only under `/app/builtin-plugins`. User-installed
packages, provenance, grants, configuration, logs, encrypted secrets, and
enablement state persist under `/data`. Web uploads of `.moext` packages and
diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.md
index f2f28624..40a59622 100644
--- a/docs/docker-server.zh-CN.md
+++ b/docs/docker-server.zh-CN.md
@@ -433,6 +433,76 @@ services:
- /srv/archive:/archive
```
+### 在 Web 界面中选择文件夹
+
+新建链接任务、种子任务和通用设置中的目录控件都会打开服务器文件夹选择器。
+这里的路径属于服务器:使用示例挂载时,`/downloads/Movies` 对应 Docker 宿主上的
+`./downloads/Movies`。从另一台电脑打开浏览器,也不会浏览该电脑的本地文件夹。
+
+单击文件夹进行选择,双击进入。列表只显示当前目录的直接子文件夹。可通过后退、前进、
+上一级或路径面包屑切换位置,也可通过“前往文件夹”输入完整绝对路径。左侧“位置”栏按
+可访问的常用位置、允许根、常用目录和最近使用分组。常用位置包括默认目录、服务器用户
+主目录、已有的 Desktop/Documents/Downloads 目录,以及权限允许时的文件系统根目录。
+窄屏上改为分组位置菜单。到达当前允许根目录后不能继续向上。通过工具栏中的
+**视图选项 → 显示隐藏文件夹** 可显示名称以点开头的文件夹。
+
+同一**视图选项**菜单支持按**名称**或**修改时间**升序、降序排列。名称采用自然排序,
+例如folder2在folder10之前。浏览器会记住选择。排序保留选中目录,仅重排已加载列表,
+不会重新请求服务端。未知修改时间的目录始终放在末尾;列表不完整时,排序仅作用于
+当前显示的目录。
+
+点击“选择文件夹”会选择高亮的子文件夹;未选择子文件夹时,选择当前文件夹。取消会保留
+表单原来的值。确认选择时,服务器会再次检查目录;提交下载任务或应用设置仍是独立操作。
+浏览和选择不会创建文件夹。
+
+新建链接任务和种子任务的 Browse 旁也提供“目录历史”按钮,可直接选常用或最近目录
+填入表单,不会开始下载。App 端提供相同的历史菜单,浏览目录时仍打开系统原生窗口。
+
+通过 **设置 → 常规** 中默认保存目录下方的紧凑表单,可添加或移除常用目录、将最近目录
+加入常用、逐条删除或清空当前显示的最近记录。“保存”会将目录编辑与常规设置一起应用,
+“取消”会放弃草稿。历史菜单中的“管理目录”提供相同的目录控件及保存、取消操作。
+移除记录不会删除文件夹或下载任务,保存时也会保留其他客户端在此期间新增的记录。
+保存失败后,表单会保留编辑内容。可以重试,也可以修改后再次保存;上一笔保存的迟到响应
+不会覆盖后续选择。响应失败时,服务端可能已经保存成功,因此“取消”不会撤销已经提交的保存。
+常用目录最多20个,最近目录最多10个,最近使用的排在前面。
+AddTask目录确认选择、成功提交时使用的目录会更新最近记录;常规设置里的目录选择
+保留为草稿,本身不会加入最近记录。取消选择器不
+新增记录;随后取消AddTask,不撤销已确认的目录选择。管理窗口添加常用本身不新增最近
+记录。此UI历史不会自动导入headless/CLI下载。
+
+常用和最近记录属于当前Motrix实例:App保存在本机应用设置,Web保存在服务端。已连接
+客户端会收到更新,重新连接后重新加载。Web历史菜单和侧栏只提供服务端当前仍允许且
+可访问的目录;管理窗口保留已保存的记录,便于移除不可用路径。Web选择器的星按钮会
+立即将当前正在浏览的目录加入常用或移除,并保持列表、当前位置稳定。上述目录记录操作
+都不改变默认保存目录。
+
+快捷键按浏览器所在电脑的操作系统适配,与服务器系统无关。焦点位于列表时:
+
+| 操作 | macOS | Windows / Linux |
+| --- | --- | --- |
+| 选择文件夹 | Up / Down | Up / Down |
+| 首个/末个文件夹 | Home / End | Home / End |
+| 按可见区域翻页 | Page Up / Page Down | Page Up / Page Down |
+| 进入所选文件夹 | Command + Down | Enter |
+| 上一级 | Command + Up | Alt + Up,或 Backspace |
+| 确认选择 | Return | Tab 到“选择文件夹”后按 Enter |
+| 编辑当前路径 | `/`,或浏览器允许传递时使用 Command + Shift + G | `/` |
+| 前往主目录/桌面/文稿(位置可用时) | Command + Shift + H / D / O | 使用位置菜单 |
+
+直接输入文件夹名称前缀可选中匹配项。Tab 和 Shift + Tab 在控件之间移动。在路径编辑框中,
+Enter 前往输入的位置,Escape 取消编辑;未编辑时,Escape 关闭选择器。浏览器保留的
+快捷键继续执行浏览器行为。
+
+点击左下方的“新建文件夹”可在当前位置创建一个文件夹。输入名称后按 Enter 或点击“创建”;Escape
+取消名称编辑。创建成功后,新文件夹会被选中,可以直接确认。**之后即使取消目录选择,
+已创建的文件夹仍会保留在服务器上。** 重名或权限错误会保留名称,便于修改。如果服务器
+响应丢失,请先刷新并检查列表,再尝试创建。
+
+目录过大时,界面会提示仅显示部分文件夹。可输入完整路径前往未显示的目录。权限检查使用
+服务器进程的运行用户;只读挂载或 NAS ACL 都可能导致操作失败。允许根目录会拒绝路径穿越
+和静态符号链接越界。与保存下载时相同,基于路径的跨平台检查无法防止恶意本地进程同时替换
+上级目录;应相应限制对挂载目录层级的写入权限。
+
内置插件以只读方式存放在 `/app/builtin-plugins`。用户安装的包、来源记录、
授权、配置、日志、加密 secret 和启用状态都持久化在 `/data`;通过 Web 上传
`.moext`,以及正常的 registry/URL 安装都会在替换容器后保留。
diff --git a/e2e/web-directory-picker/README.md b/e2e/web-directory-picker/README.md
new file mode 100644
index 00000000..6d941914
--- /dev/null
+++ b/e2e/web-directory-picker/README.md
@@ -0,0 +1,52 @@
+# Web directory picker browser verification
+
+This suite mounts the production `AddTaskDialogHost`, add-task form, directory
+picker and Base UI dialogs. Vite replaces only
+the renderer transport with a deterministic in-memory filesystem RPC fixture;
+settings hydration/persistence and event subscriptions are also fixture-backed.
+The General settings dialog and torrent panel are production components too. The
+fixture reports the real Web transport platform by default; the explicit Mac key
+case uses a Linux platform override to check client OS independence. No server,
+aria2, Electron process, native ABI rebuild, or real filesystem mutation is used.
+This is browser interaction evidence, not authorization or filesystem evidence;
+run the companion real temporary-filesystem service/policy and authenticated RPC
+tests as well.
+
+From the repository root:
+
+```bash
+pnpm exec playwright test --config e2e/web-directory-picker/playwright.config.ts
+```
+
+The config starts and stops its own Vite server at `http://127.0.0.1:4178` and
+writes screenshots/traces under `e2e/test-results/web-directory-picker/`. The
+`.browser.ts` suffix excludes this suite from the repository’s Electron suite.
+If Chromium is not installed, use `pnpm exec playwright install chromium`.
+`MOTRIX_BROWSER_EXECUTABLE` optionally selects an already installed compatible
+Chromium executable; this does not change package versions.
+
+For manual inspection:
+
+```bash
+pnpm exec vite --config e2e/web-directory-picker/vite.config.ts
+```
+
+Open `http://127.0.0.1:4178` (or append `?theme=dark`), then Open download dialog
+and Change directory. Stop Vite with Ctrl + C. Fixture state resets on reload;
+`/archive` contains 800 folders for virtualization checks. Tests cover keyboard
+creation/confirmation, Mac client keys with a Linux transport override, pointer navigation,
+allowed-root boundaries, exact-path rejection, nested Escape/focus,
+parent dialog keyboard isolation during held creation, parent draft discard
+confirmation after picker dismissal, creation failure and editor
+focus restoration, offscreen active descendants and Refresh/Back scroll preservation,
+all three entry points and settings Cancel/Save boundaries, and narrow/short
+light/dark layouts, native-style sidebar/footer geometry, breakpoint focus and
+DOM preservation, and rapid typeahead across navigation. Screenshot capture waits for opaque, settled dialogs; the
+harness explicitly scans renderer source for production Tailwind utilities. Generated artifacts are ignored by Git and can be
+removed from `e2e/test-results/web-directory-picker/` after inspection.
+
+The keyboard helper waits for frame-scheduled focus transitions after each Tab.
+Base UI focus guards use requestAnimationFrame; sending another key before that
+transition completes can target a transiently focused control. This is frame
+settlement, not a fixed delay or a replacement for native keyboard events. Opening
+failures persist the last 100 DOM focus/key/click events and RPC calls as JSON.
diff --git a/e2e/web-directory-picker/directory-picker.browser.ts b/e2e/web-directory-picker/directory-picker.browser.ts
new file mode 100644
index 00000000..4280aafe
--- /dev/null
+++ b/e2e/web-directory-picker/directory-picker.browser.ts
@@ -0,0 +1,864 @@
+import { mkdir, writeFile } from 'node:fs/promises'
+import { dirname } from 'node:path'
+import { expect, type Locator, type Page, test } from '@playwright/test'
+import { Commands } from '../../src/shared/protocol/commands'
+import { Queries } from '../../src/shared/protocol/queries'
+import type { fixtureState } from './fixture-transport'
+
+declare global {
+ interface Window {
+ directoryPickerFixture: typeof fixtureState
+ }
+}
+
+async function saveJson(path: string, value: unknown) {
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, JSON.stringify(value, null, 2))
+}
+
+async function tabTo(page: Page, target: Locator) {
+ for (let index = 0; index < 25; index += 1) {
+ if (await target.evaluate((element) => element === document.activeElement))
+ return
+ await page.keyboard.press('Tab')
+ // Base UI focus guards defer focus with rAF. Observe the completed focus
+ // transition before another key, including callbacks queued by that frame.
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ )
+ )
+ }
+ await expect(target).toBeFocused()
+}
+
+async function openPicker(
+ page: Page,
+ mac = false,
+ query = '',
+ entry: 'links' | 'torrent' | 'general' = 'links'
+) {
+ await page.addInitScript((isMac) => {
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ get: () => (isMac ? 'MacIntel' : 'Win32'),
+ })
+ Object.defineProperty(navigator, 'userAgentData', {
+ configurable: true,
+ get: () => ({ platform: isMac ? 'macOS' : 'Windows' }),
+ })
+ }, mac)
+ await page.goto(`/${query}`)
+ const launchName =
+ entry === 'links'
+ ? 'Open download dialog'
+ : entry === 'torrent'
+ ? 'Open torrent dialog'
+ : 'Open General settings'
+ await tabTo(page, page.getByRole('button', { name: launchName }))
+ await page.keyboard.press('Enter')
+ await expect(page.getByRole('dialog')).toHaveCSS('opacity', '1')
+ const opener = page.getByRole('button', {
+ name: entry === 'general' ? 'Browse…' : 'Change directory',
+ exact: true,
+ })
+ await tabTo(page, opener)
+ await page.keyboard.press('Enter')
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ try {
+ await expect(picker).toBeVisible()
+ } catch (error) {
+ await saveJson(
+ test.info().outputPath('picker-open-interactions.json'),
+ await page.evaluate(() => ({
+ interactions: window.directoryPickerFixture.interactions,
+ calls: window.directoryPickerFixture.calls,
+ }))
+ )
+ throw error
+ }
+ // Reject misleading interaction evidence if Tailwind missed production source.
+ await expect(picker).toHaveCSS('position', 'fixed')
+ await expect(picker).toHaveCSS('display', 'flex')
+ await expect(picker).toHaveCSS('z-index', '50')
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toBeVisible()
+ await expect(picker.getByRole('listbox', { name: 'Folders' })).toBeFocused()
+ return {
+ picker,
+ opener,
+ list: picker.getByRole('listbox', { name: 'Folders' }),
+ }
+}
+
+async function switchRoot(picker: Locator, path: string) {
+ const select = picker.getByRole('combobox', { name: 'Location', exact: true })
+ if (await select.isVisible()) await select.selectOption(path)
+ else
+ await picker
+ .getByRole('navigation', { name: 'Location', exact: true })
+ .getByTitle(path, { exact: true })
+ .first()
+ .click()
+}
+
+async function calls(page: Page, channel: string) {
+ return page.evaluate(
+ (name) =>
+ window.directoryPickerFixture.calls.filter(
+ (call) => call.channel === name
+ ),
+ channel
+ )
+}
+
+async function captureSettled(page: Page, picker: Locator, path: string) {
+ await expect(picker).toHaveCSS('opacity', '1')
+ await expect
+ .poll(() =>
+ picker.evaluate((element) =>
+ element
+ .getAnimations({ subtree: true })
+ .some((animation) => animation.playState === 'running')
+ )
+ )
+ .toBe(false)
+ const alpha = await picker.evaluate((element) => {
+ const canvas = document.createElement('canvas')
+ const context = canvas.getContext('2d')
+ if (!context) return 0
+ context.fillStyle = getComputedStyle(element).backgroundColor
+ context.fillRect(0, 0, 1, 1)
+ return context.getImageData(0, 0, 1, 1).data[3]
+ })
+ expect(alpha).toBe(255)
+ await page.screenshot({ path, fullPage: true, animations: 'disabled' })
+}
+
+test('keyboard-only Windows navigation, creation and confirmation preserve the parent form', async ({
+ page,
+}) => {
+ const { picker, list, opener } = await openPicker(page)
+ await page.keyboard.type('mov')
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await page.keyboard.press('Enter')
+ await expect(picker.getByRole('option', { name: 'Classics' })).toBeVisible()
+ await tabTo(
+ page,
+ picker.getByRole('button', { name: 'New folder', exact: true })
+ )
+ await page.keyboard.press('Enter')
+ const name = picker.getByRole('textbox', { name: 'Folder name' })
+ await expect(name).toBeFocused()
+ await page.keyboard.type('Keyboard folder')
+ await page.keyboard.press('Enter')
+ await expect(
+ picker.getByRole('option', { name: 'Keyboard folder', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await expect(list).toBeFocused()
+ await tabTo(
+ page,
+ picker.getByRole('button', { name: 'Select folder', exact: true })
+ )
+ await page.keyboard.press('Enter')
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toBeFocused()
+ await expect(opener).toHaveAttribute(
+ 'title',
+ '/downloads/Movies/Keyboard folder'
+ )
+ expect(await calls(page, Commands.CreateServerDirectory)).toHaveLength(1)
+ expect(await calls(page, Queries.ValidateServerDirectory)).toEqual([
+ {
+ channel: Queries.ValidateServerDirectory,
+ args: [{ path: '/downloads/Movies/Keyboard folder' }],
+ },
+ ])
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+})
+
+test('Mac client keys enter and confirm independently of the Linux server platform', async ({
+ page,
+}) => {
+ const { picker, opener } = await openPicker(
+ page,
+ true,
+ '?transportPlatform=linux'
+ )
+ await page.keyboard.type('mov')
+ await page.keyboard.press('Meta+ArrowDown')
+ await expect(picker.getByRole('option', { name: 'Classics' })).toBeVisible()
+ await page.keyboard.press('Meta+ArrowUp')
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await page.keyboard.press('Enter')
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toHaveAttribute('title', '/downloads/Movies')
+})
+
+test('double-click, parent navigation, roots and exact paths keep a coherent listing', async ({
+ page,
+}) => {
+ const { picker } = await openPicker(page)
+ await expect(
+ picker.getByRole('button', { name: 'Up one level', exact: true })
+ ).toBeDisabled()
+ await picker.getByRole('option', { name: 'Movies', exact: true }).dblclick()
+ await expect(picker.getByRole('option', { name: 'Classics' })).toBeVisible()
+ await picker
+ .getByRole('button', { name: 'Up one level', exact: true })
+ .click()
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await picker
+ .getByRole('button', { name: 'Go to folder', exact: true })
+ .click()
+ await picker.getByRole('textbox', { name: 'Folder path' }).fill('/outside')
+ await picker.getByRole('textbox', { name: 'Folder path' }).press('Enter')
+ await expect(
+ picker.getByText('This folder is outside the allowed locations.')
+ ).toBeVisible()
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toBeVisible()
+ await page.keyboard.press('Escape')
+ await expect(
+ picker.getByRole('button', { name: 'Up one level', exact: true })
+ ).toBeDisabled()
+ await switchRoot(picker, '/archive')
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).toBeVisible()
+ await expect(
+ picker.getByRole('button', { name: 'Up one level', exact: true })
+ ).toBeDisabled()
+})
+
+test('nested Escape restores focus and preserves the parent draft until discard is confirmed', async ({
+ page,
+}) => {
+ const { picker, list, opener } = await openPicker(page)
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Control+Shift+N')
+ await page.keyboard.press('Control+,')
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+ expect(new URL(page.url()).hash).toBe('')
+ await picker.getByRole('button', { name: 'New folder', exact: true }).click()
+ await picker
+ .getByRole('textbox', { name: 'Folder name' })
+ .fill('Discarded draft')
+ await page.keyboard.press('Escape')
+ await expect(picker).toBeVisible()
+ await expect(
+ picker.getByRole('textbox', { name: 'Folder name' })
+ ).not.toBeVisible()
+ await expect(list).toBeFocused()
+ await page.keyboard.press('Escape')
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toBeVisible()
+ await expect(opener).toBeFocused()
+ await expect(opener).toHaveAttribute('title', '/downloads')
+ expect(await calls(page, Commands.CreateServerDirectory)).toHaveLength(0)
+ // Web no longer installs the legacy document-level preferences shortcut.
+ await page.keyboard.press('Control+,')
+ expect(new URL(page.url()).hash).toBe('')
+ const parent = page.getByRole('dialog', { name: 'New Task', exact: true })
+ const draft = parent.locator('textarea')
+ await draft.fill('https://example.com/retained-draft.zip')
+ await page.keyboard.press('Escape')
+ const confirmation = page.getByRole('dialog', {
+ name: 'Discard this task draft?',
+ exact: true,
+ })
+ await expect(confirmation).toBeVisible()
+ await confirmation
+ .getByRole('button', { name: 'Cancel', exact: true })
+ .click()
+ await expect(confirmation).not.toBeVisible()
+ await expect(parent).toBeVisible()
+ await expect(draft).toHaveValue('https://example.com/retained-draft.zip')
+ await parent.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(confirmation).toBeVisible()
+ await confirmation
+ .getByRole('button', { name: 'Discard', exact: true })
+ .click()
+ await expect(parent).not.toBeVisible()
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+})
+
+test('creation failure retains the editor and typed name for correction', async ({
+ page,
+}) => {
+ const { picker } = await openPicker(page)
+ await page.evaluate(() => {
+ window.directoryPickerFixture.createFailure = true
+ })
+ await picker.getByRole('button', { name: 'New folder', exact: true }).click()
+ const name = picker.getByRole('textbox', { name: 'Folder name' })
+ await name.fill('Keep this name')
+ await name.press('Enter')
+ await expect(
+ picker.getByText('You do not have permission to use this folder.')
+ ).toBeVisible()
+ await expect(name).toHaveValue('Keep this name')
+ await expect(
+ picker.getByRole('button', { name: 'Select folder', exact: true })
+ ).toBeDisabled()
+ expect(await calls(page, Commands.CreateServerDirectory)).toHaveLength(1)
+ await page.keyboard.press('Escape')
+ await expect(picker).toBeVisible()
+})
+
+test('virtualization retains the active descendant after scrolling far away', async ({
+ page,
+}) => {
+ const { picker, list } = await openPicker(page)
+ await switchRoot(picker, '/archive')
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).toBeVisible()
+ await list.focus()
+ await page.keyboard.press('ArrowDown')
+ const activeId = await list.getAttribute('aria-activedescendant')
+ expect(activeId).toBeTruthy()
+ // Scroll via the real pointer wheel without changing keyboard selection.
+ await list.hover()
+ await page.mouse.wheel(0, 20_000)
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBeGreaterThan(1000)
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).not.toBeInViewport()
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).toBeAttached()
+ await expect(list).toHaveAttribute('aria-activedescendant', activeId ?? '')
+ expect(
+ await page.evaluate(
+ (id) => !!id && document.getElementById(id) !== null,
+ activeId
+ )
+ ).toBe(true)
+ expect(await picker.getByRole('option').count()).toBeLessThan(100)
+ const wheelOffset = await list.evaluate((element) => element.scrollTop)
+ await picker.getByRole('button', { name: 'Refresh', exact: true }).click()
+ await expect(list).toBeFocused()
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBeCloseTo(wheelOffset, 0)
+ await expect(list).toHaveAttribute('aria-activedescendant', activeId ?? '')
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).not.toBeInViewport()
+ await switchRoot(picker, '/downloads')
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toBeVisible()
+ await picker.getByRole('button', { name: 'Back', exact: true }).click()
+ await expect(list).toBeFocused()
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBeCloseTo(wheelOffset, 0)
+ await expect(list).toHaveAttribute('aria-activedescendant', activeId ?? '')
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).toBeAttached()
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).not.toBeInViewport()
+ await page.keyboard.press('End')
+ await expect(
+ picker.getByRole('option', { name: 'Folder 0799', exact: true })
+ ).toBeVisible()
+})
+
+for (const theme of ['light', 'dark']) {
+ test(`small viewport keeps navigation and confirmation visible (${theme})`, async ({
+ page,
+ }, testInfo) => {
+ await page.setViewportSize({ width: 390, height: 620 })
+ const { picker } = await openPicker(page, false, `?theme=${theme}`)
+ await expect(
+ picker.getByRole('navigation', { name: 'Location', exact: true })
+ ).not.toBeVisible()
+ await expect(
+ picker.getByRole('combobox', { name: 'Location', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ picker.getByRole('button', { name: 'New folder', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ picker.getByRole('button', { name: 'Select folder', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ const overflow = await page.evaluate(() => ({
+ horizontal: document.documentElement.scrollWidth > innerWidth,
+ vertical: document.documentElement.scrollHeight > innerHeight,
+ }))
+ expect(overflow).toEqual({ horizontal: false, vertical: false })
+ await captureSettled(
+ page,
+ picker,
+ testInfo.outputPath(`picker-${theme}-390x620.png`)
+ )
+ await picker
+ .getByRole('button', { name: 'New folder', exact: true })
+ .click()
+ await expect(
+ picker.getByRole('textbox', { name: 'Folder name' })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ picker.getByRole('button', { name: 'Create', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await captureSettled(
+ page,
+ picker,
+ testInfo.outputPath(`picker-${theme}-create-390x620.png`)
+ )
+ })
+}
+
+test('torrent save directory uses the same picker without submitting a download', async ({
+ page,
+}) => {
+ const { picker, opener } = await openPicker(page, false, '', 'torrent')
+ await picker.getByRole('option', { name: 'Music', exact: true }).click()
+ await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toHaveAttribute('title', '/downloads/Music')
+ await expect(opener).toBeFocused()
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+ expect(await calls(page, Commands.UpdateSettings)).toHaveLength(0)
+})
+
+test('General settings retains its own Cancel and Save boundary after selection', async ({
+ page,
+}) => {
+ const { picker, opener } = await openPicker(page, false, '', 'general')
+ await picker.getByRole('option', { name: 'Movies', exact: true }).click()
+ await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toBeFocused()
+ const general = page.getByRole('dialog', { name: 'General', exact: true })
+ await expect(general.getByRole('textbox')).toHaveValue('/downloads/Movies')
+ expect(await calls(page, Commands.SaveGeneralSettings)).toHaveLength(0)
+ expect(await calls(page, Commands.MutateDirectoryPreferences)).toHaveLength(0)
+ await general.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await page.getByRole('button', { name: 'Open General settings' }).click()
+ await expect(general.getByRole('textbox')).toHaveValue('/downloads')
+ await general.getByRole('button', { name: 'Browse…', exact: true }).click()
+ await expect(picker).toBeVisible()
+ await picker.getByRole('option', { name: 'Music', exact: true }).click()
+ await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ await expect(general.getByRole('textbox')).toHaveValue('/downloads/Music')
+ expect(await calls(page, Commands.SaveGeneralSettings)).toHaveLength(0)
+ expect(await calls(page, Commands.MutateDirectoryPreferences)).toHaveLength(0)
+ await general.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(general).not.toBeVisible()
+ expect(await calls(page, Commands.SaveGeneralSettings)).toEqual([
+ {
+ channel: Commands.SaveGeneralSettings,
+ args: [
+ {
+ expectedRevision: expect.any(String),
+ app: { defaultSaveDir: '/downloads/Music' },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ },
+ ],
+ },
+ ])
+ await page.getByRole('button', { name: 'Open General settings' }).click()
+ await expect(general.getByRole('textbox')).toHaveValue('/downloads/Music')
+})
+
+test('desktop selection keeps the complete target path visible', async ({
+ page,
+}, testInfo) => {
+ const { picker } = await openPicker(page)
+ await picker.getByRole('option', { name: 'Movies', exact: true }).click()
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await expect(
+ picker.getByText('/downloads/Movies', { exact: true })
+ ).toBeVisible()
+ const locations = picker.getByRole('navigation', {
+ name: 'Location',
+ exact: true,
+ })
+ await expect(locations).toBeVisible()
+ await expect(
+ picker.getByRole('combobox', { name: 'Location', exact: true })
+ ).not.toBeVisible()
+ const bounds = await picker.evaluate((dialog) => {
+ const rect = (selector: string) => {
+ const element = dialog.querySelector(selector)
+ if (!element) throw new Error(`Missing layout region: ${selector}`)
+ const { x, y, width, height, right, bottom } =
+ element.getBoundingClientRect()
+ return { x, y, width, height, right, bottom }
+ }
+ return {
+ dialog: rect('[data-testid="directory-picker-main"]'),
+ side: rect('[data-testid="directory-picker-locations"]'),
+ toolbar: rect('[data-testid="directory-picker-toolbar"]'),
+ list: rect('[role="listbox"]'),
+ target: rect('[data-testid="directory-picker-target"]'),
+ actions: rect('[data-testid="directory-picker-actions"]'),
+ }
+ })
+ expect(bounds.side.right).toBeLessThanOrEqual(bounds.list.x + 1)
+ expect(bounds.side.height).toBeGreaterThanOrEqual(bounds.dialog.height - 2)
+ expect(bounds.toolbar.bottom).toBeLessThanOrEqual(bounds.list.y + 1)
+ expect(bounds.list.height).toBeGreaterThan(bounds.dialog.height * 0.45)
+ expect(bounds.target.y).toBeGreaterThanOrEqual(bounds.list.bottom - 1)
+ expect(bounds.target.bottom).toBeLessThanOrEqual(bounds.actions.y + 1)
+ const newFolder = await picker
+ .getByRole('button', { name: 'New folder', exact: true })
+ .boundingBox()
+ const cancel = await picker
+ .getByRole('button', { name: 'Cancel', exact: true })
+ .boundingBox()
+ const confirm = await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .boundingBox()
+ if (!newFolder || !cancel || !confirm)
+ throw new Error('Missing native-layout footer action')
+ expect(newFolder.x + newFolder.width).toBeLessThan(cancel.x)
+ expect(cancel.x + cancel.width).toBeLessThanOrEqual(confirm.x)
+ expect(Math.abs(newFolder.y - confirm.y)).toBeLessThanOrEqual(1)
+ await captureSettled(
+ page,
+ picker,
+ testInfo.outputPath('picker-selected-desktop-1024x768.png')
+ )
+ await picker.screenshot({
+ path: testInfo.outputPath('picker-native-panel.png'),
+ animations: 'disabled',
+ })
+ await page.setViewportSize({ width: 1200, height: 800 })
+ await picker.getByRole('option', { name: 'Empty', exact: true }).dblclick()
+ await expect(picker.getByText('No subfolders', { exact: true })).toBeVisible()
+ await expect(
+ picker.getByText('/downloads/Empty', { exact: true })
+ ).toBeVisible()
+ await captureSettled(
+ page,
+ picker,
+ testInfo.outputPath('picker-empty-native-comparison-1200x800.png')
+ )
+})
+
+test('short viewport keeps creation errors and footer controls reachable', async ({
+ page,
+}, testInfo) => {
+ await page.setViewportSize({ width: 640, height: 420 })
+ const { picker } = await openPicker(page, false, '?theme=dark')
+ await picker.getByRole('button', { name: 'New folder', exact: true }).click()
+ const name = picker.getByRole('textbox', { name: 'Folder name' })
+ await name.fill('Movies')
+ await name.press('Enter')
+ await expect(
+ picker.getByText('A file or folder with this name already exists.')
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ picker.getByRole('button', { name: 'Select folder', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(name).toBeInViewport({ ratio: 1 })
+ await captureSettled(
+ page,
+ picker,
+ testInfo.outputPath('picker-create-error-short-640x420.png')
+ )
+})
+
+test('creating then cancelling selection keeps the folder and original form path', async ({
+ page,
+}) => {
+ const { picker, opener } = await openPicker(page)
+ await picker.getByRole('button', { name: 'New folder', exact: true }).click()
+ const name = picker.getByRole('textbox', { name: 'Folder name' })
+ await name.fill('Persistent folder')
+ await name.press('Enter')
+ await expect(
+ picker.getByRole('option', { name: 'Persistent folder', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await page.keyboard.press('Escape')
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toHaveAttribute('title', '/downloads')
+ await expect(opener).toBeFocused()
+ await page.keyboard.press('Enter')
+ await expect(
+ picker.getByRole('option', { name: 'Persistent folder', exact: true })
+ ).toBeVisible()
+ expect(await calls(page, Commands.CreateServerDirectory)).toHaveLength(1)
+ expect(await calls(page, Queries.ValidateServerDirectory)).toHaveLength(0)
+})
+
+test('pending creation contains focus and shortcuts, then restores the rejected name editor', async ({
+ page,
+}) => {
+ const { picker } = await openPicker(page)
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ window.directoryPickerFixture.createFailure = true
+ }, Commands.CreateServerDirectory)
+ await picker.getByRole('button', { name: 'New folder', exact: true }).click()
+ const name = picker.getByRole('textbox', { name: 'Folder name' })
+ await name.fill('Pending folder')
+ await name.press('Enter')
+ await expect(name).toBeDisabled()
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.directoryPickerFixture.releaseRequest !== null)
+ )
+ .toBe(true)
+ await expect
+ .poll(() =>
+ picker.evaluate((element) => element.contains(document.activeElement))
+ )
+ .toBe(true)
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Control+Shift+N')
+ await page.keyboard.press('Control+,')
+ await page.keyboard.press('Escape')
+ await expect(picker).toBeVisible()
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+ expect(new URL(page.url()).hash).toBe('')
+ await page.keyboard.press('Tab')
+ await expect
+ .poll(() =>
+ picker.evaluate((element) => element.contains(document.activeElement))
+ )
+ .toBe(true)
+ await page.evaluate(() => window.directoryPickerFixture.releaseRequest?.())
+ await expect(
+ picker.getByText('You do not have permission to use this folder.')
+ ).toBeVisible()
+ await expect(name).toBeEnabled()
+ await expect(name).toBeFocused()
+ await expect(name).toHaveValue('Pending folder')
+ expect(await calls(page, Commands.CreateServerDirectory)).toHaveLength(1)
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+})
+
+test('pending path navigation and validation retain dialog focus and isolate parent shortcuts', async ({
+ page,
+}) => {
+ const { picker, opener } = await openPicker(page)
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ }, Queries.ListServerDirectories)
+ await picker
+ .getByRole('button', { name: 'Go to folder', exact: true })
+ .click()
+ const path = picker.getByRole('textbox', { name: 'Folder path' })
+ await path.fill('/downloads/Movies')
+ await path.press('Enter')
+ await expect(path).toBeDisabled()
+ await expect
+ .poll(() =>
+ picker.evaluate((element) => element.contains(document.activeElement))
+ )
+ .toBe(true)
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Control+,')
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+ expect(new URL(page.url()).hash).toBe('')
+ await page.evaluate(() => window.directoryPickerFixture.releaseRequest?.())
+ await expect(
+ picker.getByRole('option', { name: 'Classics', exact: true })
+ ).toBeVisible()
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ }, Queries.ValidateServerDirectory)
+ const select = picker.getByRole('button', {
+ name: 'Select folder',
+ exact: true,
+ })
+ await select.click()
+ await expect(select).toBeDisabled()
+ await expect
+ .poll(() =>
+ picker.evaluate((element) => element.contains(document.activeElement))
+ )
+ .toBe(true)
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Control+,')
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+ expect(new URL(page.url()).hash).toBe('')
+ await picker.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(picker).not.toBeVisible()
+ await expect(opener).toBeFocused()
+ await page.evaluate(() => window.directoryPickerFixture.releaseRequest?.())
+ await expect(opener).toHaveAttribute('title', '/downloads')
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+})
+
+test('resizing between sidebar and compact roots preserves focus and editor DOM', async ({
+ page,
+}, testInfo) => {
+ const { picker, list } = await openPicker(page)
+ const originalList = await list.elementHandle()
+ expect(originalList).not.toBeNull()
+ const locations = picker.getByRole('navigation', {
+ name: 'Location',
+ exact: true,
+ })
+ await tabTo(
+ page,
+ locations.getByRole('button', { name: '/archive', exact: true })
+ )
+ await page.setViewportSize({ width: 390, height: 620 })
+ await expect(locations).not.toBeVisible()
+ await expect(list).toBeFocused()
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Control+,')
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+ expect(new URL(page.url()).hash).toBe('')
+ const compact = picker.getByRole('combobox', {
+ name: 'Location',
+ exact: true,
+ })
+ await expect(compact).toBeVisible()
+ await tabTo(page, compact)
+ await page.setViewportSize({ width: 1024, height: 768 })
+ await expect(compact).not.toBeVisible()
+ await expect(list).toBeFocused()
+ expect(
+ await list.evaluate(
+ (element, original) => element === original,
+ originalList
+ )
+ ).toBe(true)
+ await picker
+ .getByRole('button', { name: 'Go to folder', exact: true })
+ .click()
+ const editor = picker.getByRole('textbox', { name: 'Folder path' })
+ await editor.fill('/downloads/Movies')
+ const originalEditor = await editor.elementHandle()
+ expect(originalEditor).not.toBeNull()
+ await page.setViewportSize({ width: 390, height: 620 })
+ await expect(editor).toBeFocused()
+ await expect(editor).toHaveValue('/downloads/Movies')
+ await captureSettled(
+ page,
+ picker,
+ testInfo.outputPath('picker-path-editor-narrow-390x620.png')
+ )
+ const editorBounds = await editor.boundingBox()
+ expect(editorBounds?.width).toBeGreaterThanOrEqual(190)
+ const toolbar = picker.getByTestId('directory-picker-toolbar')
+ await expect(
+ toolbar.getByRole('button', { name: 'Go', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ toolbar.getByRole('button', { name: 'Cancel', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await saveJson(
+ testInfo.outputPath('narrow-path-editor-layout.json'),
+ editorBounds
+ )
+ expect(
+ await editor.evaluate(
+ (element, original) => element === original,
+ originalEditor
+ )
+ ).toBe(true)
+ expect(
+ await list.evaluate(
+ (element, original) => element === original,
+ originalList
+ )
+ ).toBe(true)
+ await page.setViewportSize({ width: 1024, height: 768 })
+ await expect(editor).toBeFocused()
+ expect(
+ await editor.evaluate(
+ (element, original) => element === original,
+ originalEditor
+ )
+ ).toBe(true)
+ await editor.press('Escape')
+ await expect(list).toBeFocused()
+})
+
+test('native shifted keys and filename spaces match the typed prefix', async ({
+ page,
+}) => {
+ await page.clock.setFixedTime('2026-09-07T00:00:00Z')
+ const { picker, list } = await openPicker(page)
+ const target = picker.getByTestId('directory-picker-target')
+ await page.keyboard.press('Space')
+ await expect(target).toHaveText('/downloads')
+ await page.keyboard.press('Shift+M')
+ await expect(target).toHaveText('/downloads/Movies')
+ await page.evaluate(() => {
+ window.directoryPickerFixture.setDirectoryChildren('/downloads', [
+ '!Bang',
+ 'Folder 01',
+ 'Folder 12',
+ 'Movies',
+ 'Music',
+ ])
+ })
+ await picker.getByRole('button', { name: 'Refresh', exact: true }).click()
+ await expect(picker.getByRole('option', { name: '!Bang' })).toBeVisible()
+ await expect(list).toBeFocused()
+
+ await page.clock.setFixedTime('2026-09-07T00:00:01Z')
+ await page.keyboard.press('Shift+Digit1')
+ await expect(target).toHaveText('/downloads/!Bang')
+ await page.clock.setFixedTime('2026-09-07T00:00:02Z')
+ await page.keyboard.type('folder 12')
+ await expect(target).toHaveText('/downloads/Folder 12')
+ await expect(
+ picker.getByRole('option', { name: 'Folder 12', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await expect(list).toBeFocused()
+ await expect(picker).toBeVisible()
+ expect(await calls(page, Queries.ValidateServerDirectory)).toHaveLength(0)
+ expect(await calls(page, Commands.CreateTask)).toHaveLength(0)
+})
+
+test('rapid typeahead after navigation starts with the new folder name', async ({
+ page,
+}) => {
+ await page.clock.setFixedTime('2026-09-07T00:00:00Z')
+ const { picker } = await openPicker(page)
+ await page.keyboard.type('mov')
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await page.keyboard.press('Enter')
+ await expect(
+ picker.getByRole('option', { name: 'Classics', exact: true })
+ ).toBeVisible()
+ // Fixed Date.now keeps this below the typeahead reset deadline, including on slow CI.
+ await page.keyboard.type('c')
+ await expect(
+ picker.getByRole('option', { name: 'Classics', exact: true })
+ ).toHaveAttribute('aria-selected', 'true')
+ await expect(
+ picker.getByText('/downloads/Movies/Classics', { exact: true })
+ ).toBeVisible()
+})
diff --git a/e2e/web-directory-picker/fixture-transport.ts b/e2e/web-directory-picker/fixture-transport.ts
new file mode 100644
index 00000000..f07ed274
--- /dev/null
+++ b/e2e/web-directory-picker/fixture-transport.ts
@@ -0,0 +1,320 @@
+import type { Transport } from '@renderer/lib/transport/types'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
+import {
+ type DirectoryPreferences,
+ DirectoryPreferencesSchema,
+ GetDirectoryPreferencesRequestSchema,
+ MutateDirectoryPreferencesRequestSchema,
+} from '@shared/schemas/directory-preferences'
+import {
+ GeneralSettingsAppSchema,
+ GetGeneralSettingsDraftRequestSchema,
+ SaveGeneralSettingsRequestSchema,
+} from '@shared/schemas/general-settings'
+import {
+ CreateServerDirectoryRequestSchema,
+ ListServerDirectoriesRequestSchema,
+ ValidateServerDirectoryRequestSchema,
+} from '@shared/schemas/server-directory'
+
+const folders = new Map<string, string[]>([
+ ['/', ['archive', 'downloads', 'home']],
+ ['/home', ['operator']],
+ ['/home/operator', ['Desktop', 'Documents', 'Downloads']],
+ ['/home/operator/Desktop', []],
+ ['/home/operator/Documents', []],
+ ['/home/operator/Downloads', []],
+ ['/downloads', ['.hidden', 'Empty', 'Movies', 'Music']],
+ ['/downloads/.hidden', []],
+ ['/downloads/Empty', []],
+ ['/downloads/Movies', ['Classics']],
+ ['/downloads/Movies/Classics', []],
+ ['/downloads/Music', []],
+ [
+ '/archive',
+ Array.from(
+ { length: 800 },
+ (_, index) => `Folder ${String(index).padStart(4, '0')}`
+ ),
+ ],
+])
+for (const name of folders.get('/archive') ?? [])
+ folders.set(`/archive/${name}`, [])
+
+const settings = {
+ app: {
+ ...DEFAULT_APP_SETTINGS,
+ defaultSaveDir: '/downloads',
+ autofillClipboardLinks: false,
+ },
+}
+
+const unrestricted = new URLSearchParams(location.search).has('unrestricted')
+const listeners = new Map<string, Set<(...args: unknown[]) => void>>()
+const canVisit = (path: string) =>
+ folders.has(path) &&
+ (unrestricted ||
+ ['/downloads', '/archive'].some(
+ (root) => path === root || path.startsWith(`${root}/`)
+ ))
+let generalRevision = crypto.randomUUID()
+const generalSnapshot = () => ({
+ revision: generalRevision,
+ app: GeneralSettingsAppSchema.parse(settings.app),
+ directoryPreferences: preferences(),
+})
+const preferences = () => structuredClone(settings.app.directoryPreferences)
+function setPreferences(value: DirectoryPreferences) {
+ settings.app.directoryPreferences = DirectoryPreferencesSchema.parse(value)
+ generalRevision = crypto.randomUUID()
+ for (const listener of listeners.get(Events.DirectoryPreferencesChanged) ??
+ [])
+ listener(preferences())
+}
+
+export const fixtureState = {
+ modifiedAtByPath: {} as Record<string, number | undefined>,
+ setDirectoryChildren(path: string, children: string[]) {
+ folders.set(path, [...children])
+ for (const name of children) {
+ const childPath = `${path === '/' ? '' : path}/${name}`
+ if (!folders.has(childPath)) folders.set(childPath, [])
+ }
+ },
+ calls: [] as { channel: string; args: unknown[] }[],
+ interactions: [] as {
+ type: string
+ key?: string
+ tag?: string
+ label?: string
+ time: number
+ activeTag?: string
+ activeLabel?: string
+ stack?: string
+ }[],
+ createFailure: false,
+ mutationFailure: false,
+ nativePickerResult: null as string | null,
+ nativePickerCalls: 0,
+ setPreferences,
+ getPreferences: preferences,
+ getSettings: () => structuredClone(settings),
+ holdChannel: null as string | null,
+ releaseRequest: null as (() => void) | null,
+}
+
+const error = (code: string) => ({ ok: false, error: { code } })
+
+// Only RPC data and unrelated transport events are replaced. The browser runs
+// the actual add-task form, picker, Base UI dialogs, and their keyboard handlers.
+export const transport: Transport = {
+ platform:
+ new URLSearchParams(location.search).get('transportPlatform') === 'linux'
+ ? 'linux'
+ : 'web',
+ on(channel, listener) {
+ if (!listeners.has(channel)) listeners.set(channel, new Set())
+ listeners.get(channel)?.add(listener)
+ },
+ off(channel, listener) {
+ listeners.get(channel)?.delete(listener)
+ },
+ async invoke(channel, ...args) {
+ fixtureState.calls.push({ channel, args })
+ if (fixtureState.holdChannel === channel) {
+ await new Promise<void>((resolve) => {
+ fixtureState.releaseRequest = () => {
+ fixtureState.releaseRequest = null
+ resolve()
+ }
+ })
+ }
+ switch (channel) {
+ case Queries.GetSettings:
+ return settings
+ case Queries.ListAllowedSaveDirs:
+ return {
+ paths: unrestricted
+ ? []
+ : [{ path: '/downloads' }, { path: '/archive' }],
+ defaultPath: '/downloads',
+ allowCustom: true,
+ }
+ case Queries.GetGeneralSettingsDraft:
+ GetGeneralSettingsDraftRequestSchema.parse(args[0])
+ return { ok: true, value: generalSnapshot() }
+ case Queries.GetDirectoryPreferences:
+ GetDirectoryPreferencesRequestSchema.parse(args[0])
+ return { ok: true, value: preferences() }
+ case Queries.ListServerDirectoryLocations: {
+ GetDirectoryPreferencesRequestSchema.parse(args[0])
+ const common = [
+ { kind: 'default', path: '/downloads' },
+ { kind: 'home', path: '/home/operator' },
+ { kind: 'desktop', path: '/home/operator/Desktop' },
+ { kind: 'documents', path: '/home/operator/Documents' },
+ { kind: 'downloads', path: '/home/operator/Downloads' },
+ { kind: 'root', path: '/' },
+ ].filter((entry) => canVisit(entry.path))
+ const entries = (paths: string[]) =>
+ paths.filter(canVisit).map((path) => ({
+ name: path.split('/').at(-1) || '/',
+ path,
+ sourcePaths: [path],
+ }))
+ return {
+ ok: true,
+ value: {
+ common,
+ favorites: entries(settings.app.directoryPreferences.favorites),
+ recent: entries(settings.app.directoryPreferences.recent),
+ },
+ }
+ }
+ case Commands.MutateDirectoryPreferences: {
+ const action = MutateDirectoryPreferencesRequestSchema.parse(args[0])
+ if (fixtureState.mutationFailure) return error('unavailable')
+ const next = preferences()
+ if (
+ action.action === 'addFavorite' ||
+ action.action === 'recordRecent'
+ ) {
+ if (!canVisit(action.path)) return error('notFound')
+ if (action.action === 'addFavorite') {
+ if (!next.favorites.includes(action.path)) {
+ if (next.favorites.length >= 20) return error('limitReached')
+ next.favorites.push(action.path)
+ }
+ } else
+ next.recent = [
+ action.path,
+ ...next.recent.filter((path) => path !== action.path),
+ ].slice(0, 10)
+ } else if (action.action === 'removeFavorite') {
+ next.favorites = next.favorites.filter(
+ (path) => !action.paths.includes(path)
+ )
+ } else if (action.action === 'removeRecent') {
+ next.recent = next.recent.filter(
+ (path) => !action.paths.includes(path)
+ )
+ } else next.recent = []
+ setPreferences(next)
+ return { ok: true, value: preferences() }
+ }
+ case Commands.SaveGeneralSettings: {
+ const parsed = SaveGeneralSettingsRequestSchema.safeParse(args[0])
+ if (!parsed.success) return error('invalidPath')
+ if (fixtureState.mutationFailure) return error('unavailable')
+ const { app, directories, expectedRevision } = parsed.data
+ if (expectedRevision !== generalRevision)
+ return { ...error('conflict'), snapshot: generalSnapshot() }
+ if (
+ (app.defaultSaveDir !== undefined && !canVisit(app.defaultSaveDir)) ||
+ directories.addFavorites.some((path) => !canVisit(path))
+ )
+ return error('notFound')
+ // The fixture applies the draft against current committed records in
+ // one step, including events received while this request was held.
+ const current = preferences()
+ const next = {
+ favorites: current.favorites.filter(
+ (path) => !directories.removeFavorites.includes(path)
+ ),
+ recent: current.recent.filter(
+ (path) => !directories.removeRecent.includes(path)
+ ),
+ }
+ for (const path of directories.addFavorites)
+ if (!next.favorites.includes(path)) next.favorites.push(path)
+ if (next.favorites.length > 20) return error('limitReached')
+ settings.app = { ...settings.app, ...app, directoryPreferences: next }
+ if (JSON.stringify(current) !== JSON.stringify(next))
+ setPreferences(next)
+ generalRevision = crypto.randomUUID()
+ return { ok: true, value: generalSnapshot() }
+ }
+ case Queries.ListServerDirectories: {
+ const { path, showHidden } = ListServerDirectoriesRequestSchema.parse(
+ args[0]
+ )
+ const children = folders.get(path)
+ if (!children || !canVisit(path))
+ return error(
+ path.startsWith('/downloads/') || path.startsWith('/archive/')
+ ? 'notFound'
+ : 'outsideRoots'
+ )
+ const segments = path.split('/').filter(Boolean)
+ return {
+ ok: true,
+ value: {
+ path,
+ parentPath:
+ path === '/' || (!unrestricted && segments.length === 1)
+ ? null
+ : path.slice(0, path.lastIndexOf('/')) || '/',
+ breadcrumbs: [
+ ...(unrestricted ? [{ name: '/', path: '/' }] : []),
+ ...segments.map((name, index) => ({
+ name,
+ path: `/${segments.slice(0, index + 1).join('/')}`,
+ })),
+ ],
+ entries: children
+ .filter((name) => showHidden || !name.startsWith('.'))
+ .map((name) => {
+ const childPath = `${path === '/' ? '' : path}/${name}`
+ const modifiedAt = fixtureState.modifiedAtByPath[childPath]
+ return {
+ name,
+ path: childPath,
+ ...(Number.isFinite(modifiedAt) ? { modifiedAt } : {}),
+ }
+ }),
+ truncated: false,
+ canCreate: true,
+ },
+ }
+ }
+ case Queries.ValidateServerDirectory: {
+ const { path } = ValidateServerDirectoryRequestSchema.parse(args[0])
+ return folders.has(path)
+ ? { ok: true, value: { path } }
+ : error('notFound')
+ }
+ case Commands.CreateServerDirectory: {
+ const { parentPath, name } = CreateServerDirectoryRequestSchema.parse(
+ args[0]
+ )
+ if (fixtureState.createFailure) return error('permissionDenied')
+ const children = folders.get(parentPath)
+ if (!children) return error('notFound')
+ if (children.includes(name)) return error('alreadyExists')
+ const path = `${parentPath}/${name}`
+ folders.set(path, [])
+ children.push(name)
+ children.sort((left, right) =>
+ left.localeCompare(right, 'en', { numeric: true })
+ )
+ return { ok: true, value: { name, path } }
+ }
+ case Commands.UpdateSettings: {
+ const patch = args[0] as { app?: Partial<typeof settings.app> }
+ settings.app = {
+ ...settings.app,
+ ...patch.app,
+ directoryPreferences: preferences(),
+ }
+ return { saved: true, requiresRestart: false, changedRestartKeys: [] }
+ }
+ case Commands.CreateTask:
+ return { outcome: 'created', taskId: 'unexpected-parent-submit' }
+ default:
+ throw new Error(`Unhandled harness RPC: ${channel}`)
+ }
+ },
+}
diff --git a/e2e/web-directory-picker/harness.css b/e2e/web-directory-picker/harness.css
new file mode 100644
index 00000000..1a69d481
--- /dev/null
+++ b/e2e/web-directory-picker/harness.css
@@ -0,0 +1,4 @@
+@import "../../src/renderer/styles/globals.css";
+
+/* Vite runs from this harness directory; include production component classes. */
+@source "../../src/renderer";
diff --git a/e2e/web-directory-picker/harness.tsx b/e2e/web-directory-picker/harness.tsx
new file mode 100644
index 00000000..2d30393b
--- /dev/null
+++ b/e2e/web-directory-picker/harness.tsx
@@ -0,0 +1,183 @@
+import { AddTaskForm } from '@renderer/components/add-task/add-task-form'
+import { AddTaskDialogHost } from '@renderer/components/add-task-dialog/add-task-dialog-host'
+import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'
+import { Button } from '@renderer/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import { TooltipProvider } from '@renderer/components/ui/tooltip'
+import { applyRendererLocale } from '@renderer/lib/i18n'
+import { PlatformServicesProvider } from '@renderer/platform/services'
+import { webServices } from '@renderer/platform/web-services'
+import { DownloadsDialog } from '@renderer/routes/settings/cards/downloads-dialog'
+import { GeneralDialog } from '@renderer/routes/settings/cards/general-dialog'
+import { useState } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter } from 'react-router'
+import { fixtureState } from './fixture-transport'
+import './harness.css'
+
+Object.assign(window, { directoryPickerFixture: fixtureState })
+for (const type of ['focusin', 'keydown', 'keyup', 'click']) {
+ document.addEventListener(
+ type,
+ (event) => {
+ const target = event.target instanceof HTMLElement ? event.target : null
+ const active =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
+ fixtureState.interactions.push({
+ type,
+ key: event instanceof KeyboardEvent ? event.key : undefined,
+ tag: target?.tagName,
+ label:
+ target?.getAttribute('aria-label') ??
+ target?.textContent?.trim().slice(0, 80),
+ time: performance.now(),
+ activeTag: active?.tagName,
+ activeLabel:
+ active?.getAttribute('aria-label') ??
+ active?.textContent?.trim().slice(0, 80),
+ })
+ if (fixtureState.interactions.length > 100)
+ fixtureState.interactions.shift()
+ },
+ true
+ )
+}
+const parameters = new URLSearchParams(location.search)
+document.documentElement.classList.toggle(
+ 'dark',
+ parameters.get('theme') === 'dark'
+)
+await applyRendererLocale('en-US')
+
+// The App's form must inherit the native service fixture. The production Web
+// AddTaskDialogHost intentionally owns a Web provider and cannot simulate it.
+function AppFormFixture() {
+ const { open, prefill, close } = useAddTaskDialogStore()
+ return (
+ <Dialog open={open} onOpenChange={(value) => !value && close()}>
+ <DialogContent
+ className="flex h-[420px] max-h-[90vh] flex-col"
+ initialFocus={false}
+ >
+ <DialogHeader>
+ <DialogTitle>New Task</DialogTitle>
+ </DialogHeader>
+ <AddTaskForm
+ key={open ? 'open' : 'closed'}
+ defaultValues={prefill}
+ onCancel={close}
+ onSubmitSuccess={close}
+ presentation="dialog"
+ subscribeEvents={false}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function Harness() {
+ const [generalOpen, setGeneralOpen] = useState(false)
+ const [downloadsOpen, setDownloadsOpen] = useState(false)
+ const services = parameters.has('nativePicker')
+ ? {
+ ...webServices,
+ kind: 'electron' as const,
+ pickSaveDir: async () => {
+ fixtureState.nativePickerCalls++
+ return fixtureState.nativePickerResult
+ },
+ }
+ : webServices
+ return (
+ <MemoryRouter>
+ <TooltipProvider>
+ <PlatformServicesProvider services={services}>
+ <main className="min-h-svh bg-background p-8 text-foreground">
+ <Button
+ onClick={() =>
+ useAddTaskDialogStore.getState().openWith({
+ tab: 'links',
+ urls: 'https://example.com/archive.zip',
+ saveDir: '/downloads',
+ })
+ }
+ >
+ Open download dialog
+ </Button>
+ <Button
+ onClick={() =>
+ useAddTaskDialogStore.getState().openWith({
+ tab: 'torrent',
+ source: 'file',
+ base64: 'Zml4dHVyZQ==',
+ saveDir: '/downloads',
+ selectedFiles: [0],
+ torrentMeta: {
+ name: 'Fixture archive',
+ infoHash: 'a'.repeat(40),
+ totalSize: 1024,
+ files: [
+ {
+ index: 0,
+ path: 'archive.zip',
+ size: 1024,
+ extension: '.zip',
+ },
+ ],
+ },
+ })
+ }
+ >
+ Open torrent dialog
+ </Button>
+ <Button onClick={() => setGeneralOpen(true)}>
+ Open General settings
+ </Button>
+ <Button onClick={() => setDownloadsOpen(true)}>
+ Open Downloads settings
+ </Button>
+ {parameters.has('nativePicker') ? (
+ <AppFormFixture />
+ ) : (
+ <AddTaskDialogHost />
+ )}
+ {generalOpen && (
+ <GeneralDialog
+ open
+ onClose={() => {
+ fixtureState.interactions.push({
+ type: 'general-close',
+ time: performance.now(),
+ stack: new Error('General onClose').stack,
+ })
+ setGeneralOpen(false)
+ }}
+ labelKey="settings.cards.general.title"
+ descKey="settings.cards.general.desc"
+ />
+ )}
+ {downloadsOpen && (
+ <DownloadsDialog
+ open
+ onClose={() => setDownloadsOpen(false)}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )}
+ </main>
+ </PlatformServicesProvider>
+ </TooltipProvider>
+ </MemoryRouter>
+ )
+}
+
+const container = document.getElementById('root')
+if (!container) throw new Error('Missing browser harness root')
+createRoot(container).render(<Harness />)
diff --git a/e2e/web-directory-picker/index.html b/e2e/web-directory-picker/index.html
new file mode 100644
index 00000000..f1543866
--- /dev/null
+++ b/e2e/web-directory-picker/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Motrix Web directory picker verification</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/harness.tsx"></script>
+ </body>
+</html>
diff --git a/e2e/web-directory-picker/playwright.config.ts b/e2e/web-directory-picker/playwright.config.ts
new file mode 100644
index 00000000..3a805598
--- /dev/null
+++ b/e2e/web-directory-picker/playwright.config.ts
@@ -0,0 +1,31 @@
+import { defineConfig } from '@playwright/test'
+
+export default defineConfig({
+ testDir: '.',
+ // The distinct suffix keeps this Web suite out of the Electron config.
+ testMatch: '**/*.browser.ts',
+ workers: 1,
+ retries: 0,
+ timeout: 30_000,
+ expect: { timeout: 8_000 },
+ reporter: [['list']],
+ outputDir: '../test-results/web-directory-picker',
+ use: {
+ baseURL: 'http://127.0.0.1:4178',
+ browserName: 'chromium',
+ headless: true,
+ viewport: { width: 1024, height: 768 },
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ launchOptions: process.env.MOTRIX_BROWSER_EXECUTABLE
+ ? { executablePath: process.env.MOTRIX_BROWSER_EXECUTABLE }
+ : undefined,
+ },
+ webServer: {
+ command: 'pnpm exec vite --config e2e/web-directory-picker/vite.config.ts',
+ cwd: new URL('../..', import.meta.url).pathname,
+ url: 'http://127.0.0.1:4178',
+ reuseExistingServer: !process.env.CI,
+ timeout: 30_000,
+ },
+})
diff --git a/e2e/web-directory-picker/preferences.browser.ts b/e2e/web-directory-picker/preferences.browser.ts
new file mode 100644
index 00000000..82783927
--- /dev/null
+++ b/e2e/web-directory-picker/preferences.browser.ts
@@ -0,0 +1,1190 @@
+import { expect, type Locator, type Page, test } from '@playwright/test'
+import { Commands } from '../../src/shared/protocol/commands'
+import { Queries } from '../../src/shared/protocol/queries'
+
+async function seed(page: Page, query = '') {
+ await page.goto(`/${query}`)
+ await page.waitForFunction(() => !!window.directoryPickerFixture)
+ await page.evaluate(() =>
+ window.directoryPickerFixture.setPreferences({
+ favorites: ['/archive'],
+ recent: ['/downloads/Movies', '/downloads/Music', '/missing'],
+ })
+ )
+}
+
+async function openDownload(page: Page) {
+ await page
+ .getByRole('button', { name: 'Open download dialog', exact: true })
+ .click()
+ const dialog = page.getByRole('dialog')
+ await expect(dialog).toHaveCSS('opacity', '1')
+ return dialog
+}
+
+async function tabTo(page: Page, target: Locator) {
+ for (let index = 0; index < 35; index++) {
+ if (await target.evaluate((element) => element === document.activeElement))
+ return
+ await page.keyboard.press('Tab')
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ )
+ )
+ }
+ await expect(target).toBeFocused()
+}
+
+async function parentSubmissions(page: Page) {
+ return page.evaluate(
+ (channel) =>
+ window.directoryPickerFixture.calls.filter(
+ (call) => call.channel === channel
+ ),
+ Commands.CreateTask
+ )
+}
+
+async function settleFrames(page: Page) {
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ )
+ )
+}
+
+async function settlePanel(page: Page, panel: Locator) {
+ await expect(panel).toHaveCSS('opacity', '1')
+ await panel.evaluate(async (element) => {
+ await Promise.all(
+ element
+ .getAnimations({ subtree: true })
+ .filter(
+ (animation) => animation.effect?.getTiming().iterations !== Infinity
+ )
+ .map((animation) => animation.finished.catch(() => {}))
+ )
+ })
+ await settleFrames(page)
+}
+
+test('favorite updates preserve picker geometry, list state and request budget', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1024, height: 768 })
+ await seed(page, '?unrestricted=1')
+ await page.evaluate(() =>
+ window.directoryPickerFixture.setPreferences({ favorites: [], recent: [] })
+ )
+ const parent = await openDownload(page)
+ // A previously opened history mirror must stop doing optional locations IO
+ // after its menu closes; only the active picker refreshes on this mutation.
+ await parent
+ .getByRole('button', { name: 'Directory history', exact: true })
+ .click()
+ await expect(
+ page.getByRole('menu', { name: 'Directory history' })
+ ).toBeVisible()
+ await page.keyboard.press('Escape')
+ await expect(
+ page.getByRole('menu', { name: 'Directory history' })
+ ).not.toBeVisible()
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ await expect(picker.getByRole('listbox', { name: 'Folders' })).toBeFocused()
+ await picker
+ .getByRole('button', { name: 'Go to folder', exact: true })
+ .click()
+ await picker
+ .getByRole('textbox', { name: 'Folder path', exact: true })
+ .fill('/archive')
+ await picker.getByRole('button', { name: 'Go', exact: true }).click()
+ const list = picker.getByRole('listbox', { name: 'Folders', exact: true })
+ await picker.getByRole('option', { name: 'Folder 0000', exact: true }).click()
+ // The sorted display array must stay memoized across preference updates too.
+ const sortCalls = await page.evaluate(
+ () => window.directoryPickerFixture.calls
+ )
+ await picker
+ .getByRole('button', { name: 'View options', exact: true })
+ .click()
+ const viewMenu = page.getByRole('menu', { name: 'View options', exact: true })
+ await viewMenu
+ .getByRole('menuitemradio', { name: 'Descending', exact: true })
+ .click()
+ await expect(viewMenu).not.toBeVisible()
+ await expect(list).toBeFocused()
+ await expect(
+ list.getByRole('option', { name: 'Folder 0000', exact: true })
+ ).toHaveAttribute('aria-posinset', '800')
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.calls)
+ ).toEqual(sortCalls)
+ await list.evaluate((element) => {
+ element.scrollTop = 12000
+ })
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBe(12000)
+ await settleFrames(page)
+
+ const sidebar = picker.getByTestId('directory-picker-locations')
+ const main = picker.getByTestId('directory-picker-main')
+ const sidebarNode = await sidebar.elementHandle()
+ const mainNode = await main.elementHandle()
+ const listNode = await list.elementHandle()
+ const selectedNode = await list
+ .locator('[role="option"][aria-selected="true"]')
+ .elementHandle()
+ if (!sidebarNode || !mainNode || !listNode || !selectedNode)
+ throw new Error('Expected the picker nodes to exist before measurement')
+ const star = picker.getByTestId('directory-picker-favorite')
+ await star.focus()
+ const capture = async () => ({
+ mainBounds: await main.boundingBox(),
+ listBounds: await list.boundingBox(),
+ scroll: await list.evaluate((element) => element.scrollTop),
+ activeDescendant: await list.getAttribute('aria-activedescendant'),
+ selectedPath: await picker
+ .getByTestId('directory-picker-target')
+ .textContent(),
+ sidebarRetained: await sidebarNode.evaluate(
+ (element) => element.isConnected
+ ),
+ mainRetained: await mainNode.evaluate((element) => element.isConnected),
+ listRetained: await listNode.evaluate((element) => element.isConnected),
+ selectedNodeRetained: await selectedNode.evaluate(
+ (element) => element.isConnected
+ ),
+ focus: await page.evaluate(() => ({
+ tag: document.activeElement?.tagName,
+ testId: document.activeElement?.getAttribute('data-testid'),
+ label: document.activeElement?.getAttribute('aria-label'),
+ insidePicker: !!document.activeElement?.closest(
+ '[data-testid="web-directory-picker"]'
+ ),
+ })),
+ })
+ const before = await capture()
+ const baselineCalls = await page.evaluate(
+ () => window.directoryPickerFixture.calls.length
+ )
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ }, Queries.ListServerDirectoryLocations)
+ await star.click()
+ await expect
+ .poll(() =>
+ page.evaluate(
+ (channel) =>
+ window.directoryPickerFixture.calls.filter(
+ (call) => call.channel === channel
+ ).length,
+ Commands.MutateDirectoryPreferences
+ )
+ )
+ .toBe(1)
+ await settleFrames(page)
+ const pending = await capture()
+ // Retained locations are display snapshots while authorization refreshes.
+ // Synthetic activation exercises the controller guard as well as disabled UI.
+ await sidebar.locator('button[title="/home/operator"]').dispatchEvent('click')
+ await star.dispatchEvent('click')
+ const pendingCalls = await page.evaluate(
+ (offset) => window.directoryPickerFixture.calls.slice(offset),
+ baselineCalls
+ )
+ await page.evaluate(() => {
+ window.directoryPickerFixture.holdChannel = null
+ window.directoryPickerFixture.releaseRequest?.()
+ })
+ await expect(star).toHaveAttribute('aria-pressed', 'true')
+ await settleFrames(page)
+ const after = await capture()
+ const calls = await page.evaluate(
+ (offset) => window.directoryPickerFixture.calls.slice(offset),
+ baselineCalls
+ )
+ const metrics = {
+ before,
+ pending,
+ after,
+ locationsQueries: calls.filter(
+ (call) => call.channel === Queries.ListServerDirectoryLocations
+ ).length,
+ listingQueries: calls.filter(
+ (call) => call.channel === Queries.ListServerDirectories
+ ).length,
+ mutations: calls.filter(
+ (call) => call.channel === Commands.MutateDirectoryPreferences
+ ).length,
+ pendingCalls,
+ }
+ await test.info().attach('favorite-performance-metrics', {
+ body: JSON.stringify(metrics, null, 2),
+ contentType: 'application/json',
+ })
+ expect.soft(metrics.locationsQueries).toBe(1)
+ expect.soft(metrics.listingQueries).toBe(0)
+ expect.soft(metrics.mutations).toBe(1)
+ for (const state of [pending, after]) {
+ expect.soft(state.sidebarRetained).toBe(true)
+ expect.soft(state.mainRetained).toBe(true)
+ expect.soft(state.listRetained).toBe(true)
+ expect.soft(state.selectedNodeRetained).toBe(true)
+ expect.soft(state.mainBounds).toEqual(before.mainBounds)
+ expect.soft(state.listBounds).toEqual(before.listBounds)
+ expect.soft(state.scroll).toBe(before.scroll)
+ expect.soft(state.activeDescendant).toBe(before.activeDescendant)
+ expect.soft(state.selectedPath).toBe(before.selectedPath)
+ expect.soft(state.focus.insidePicker).toBe(true)
+ expect.soft(state.focus.testId).toBe('directory-picker-favorite')
+ }
+})
+
+async function openSettingsManager(page: Page) {
+ await page
+ .getByRole('button', { name: 'Open General settings', exact: true })
+ .click()
+ const manager = page.getByRole('dialog', { name: 'General', exact: true })
+ await expect(manager).toHaveCSS('opacity', '1')
+ return { manager }
+}
+
+for (const width of [1024, 390]) {
+ test(`View options offers keyboard hidden-folder filtering without parent submission at ${width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 620 })
+ await seed(page)
+ const parent = await openDownload(page)
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ const list = picker.getByRole('listbox', { name: 'Folders', exact: true })
+ await expect(list).toBeFocused()
+ await expect(
+ picker.getByRole('switch', { name: 'Show hidden folders', exact: true })
+ ).toHaveCount(0)
+ await expect(
+ picker.getByRole('option', { name: '.hidden', exact: true })
+ ).toHaveCount(0)
+ const view = picker.getByRole('button', {
+ name: 'View options',
+ exact: true,
+ })
+ await expect(
+ picker
+ .getByTestId('directory-picker-toolbar')
+ .getByRole('button', { name: 'View options', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await tabTo(page, view)
+ await page.keyboard.press('Enter')
+ const menu = page.getByRole('menu', { name: 'View options', exact: true })
+ const hidden = menu.getByRole('menuitemcheckbox', {
+ name: 'Show hidden folders',
+ exact: true,
+ })
+ await expect(hidden).toBeVisible()
+ await expect(hidden).not.toBeChecked()
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Meta+Enter')
+ expect(await parentSubmissions(page)).toHaveLength(0)
+ await expect(hidden).not.toBeChecked()
+ await expect(menu).toHaveCSS('opacity', '1')
+ await menu.screenshot({
+ path: test.info().outputPath(`view-options-${width}.png`),
+ })
+ const baseline = await page.evaluate(
+ () => window.directoryPickerFixture.calls.length
+ )
+ await hidden.focus()
+ await page.keyboard.press('Space')
+ await expect(menu).not.toBeVisible()
+ await expect(
+ picker.getByRole('option', { name: '.hidden', exact: true })
+ ).toBeVisible()
+ await expect(list).toBeFocused()
+ const calls = await page.evaluate(
+ (offset) => window.directoryPickerFixture.calls.slice(offset),
+ baseline
+ )
+ expect(
+ calls.filter((call) => call.channel === Queries.ListServerDirectories)
+ ).toEqual([
+ {
+ channel: Queries.ListServerDirectories,
+ args: [{ path: '/downloads', showHidden: true }],
+ },
+ ])
+ expect(
+ calls.filter(
+ (call) => call.channel === Queries.ListServerDirectoryLocations
+ )
+ ).toHaveLength(0)
+ await tabTo(page, view)
+ await page.keyboard.press('Enter')
+ await expect(hidden).toBeChecked()
+ await page.keyboard.press('Escape')
+ await expect(menu).not.toBeVisible()
+ await expect(view).toBeFocused()
+ await expect(picker).toBeVisible()
+ expect(await parentSubmissions(page)).toHaveLength(0)
+ await picker.screenshot({
+ path: test.info().outputPath(`picker-filtered-${width}.png`),
+ })
+ })
+}
+
+for (const app of [false, true]) {
+ test(`direct directory history selects without submitting (${app ? 'App service' : 'Web'})`, async ({
+ page,
+ }) => {
+ await seed(page, app ? '?transportPlatform=linux&nativePicker=1' : '')
+ const parent = await openDownload(page)
+ const trigger = parent.getByRole('button', {
+ name: 'Directory history',
+ exact: true,
+ })
+ await tabTo(page, trigger)
+ await page.keyboard.press('Enter')
+ const menu = page.getByRole('menu', { name: 'Directory history' })
+ await expect(
+ menu.getByRole('menuitem', { name: '/downloads/Music', exact: true })
+ ).toBeVisible()
+ if (!app)
+ await expect(
+ menu.getByRole('menuitem', { name: '/missing', exact: true })
+ ).toHaveCount(0)
+ await menu.screenshot({
+ path: test.info().outputPath('directory-history.png'),
+ })
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Meta+Enter')
+ expect(await parentSubmissions(page)).toHaveLength(0)
+ // The history menu is also navigable without the mouse.
+ await page.keyboard.press('Home')
+ await page.keyboard.press('ArrowDown')
+ await page.keyboard.press('ArrowDown')
+ await page.keyboard.press('Enter')
+ await expect(menu).not.toBeVisible()
+ await expect(
+ parent.getByRole('button', { name: 'Change directory', exact: true })
+ ).toHaveAttribute('title', '/downloads/Music')
+ const literalPath = parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .locator('span[dir="ltr"]')
+ await expect(literalPath).toHaveText('/downloads/Music')
+ await expect(literalPath).toHaveCSS('direction', 'ltr')
+ await expect(trigger).toBeFocused()
+ expect(await parentSubmissions(page)).toHaveLength(0)
+ expect(
+ await page.evaluate(
+ () => window.directoryPickerFixture.getPreferences().recent
+ )
+ ).toEqual(['/downloads/Movies', '/downloads/Music', '/missing'])
+ if (app) {
+ expect(
+ await page.evaluate(
+ (channel) =>
+ window.directoryPickerFixture.calls.filter(
+ (call) => call.channel === channel
+ ),
+ Queries.ListServerDirectoryLocations
+ )
+ ).toHaveLength(0)
+ }
+ })
+}
+
+async function preferenceWrites(page: Page) {
+ return page.evaluate(
+ (channels) =>
+ window.directoryPickerFixture.calls.filter((call) =>
+ channels.some((channel) => channel === call.channel)
+ ),
+ [
+ Commands.SaveGeneralSettings,
+ Commands.MutateDirectoryPreferences,
+ Commands.UpdateSettings,
+ ]
+ )
+}
+
+async function expandRecent(manager: Locator) {
+ const trigger = manager.getByRole('button', { name: /^Recent folders/ })
+ await expect(trigger).toBeVisible()
+ if ((await trigger.getAttribute('aria-expanded')) === 'false')
+ await trigger.click()
+}
+
+test('General directory and ordinary setting drafts cancel without any preference command', async ({
+ page,
+}) => {
+ await seed(page)
+ await page.evaluate(() =>
+ window.directoryPickerFixture.setPreferences({
+ favorites: ['/archive', '/downloads/Movies'],
+ recent: ['/downloads/Movies', '/downloads/Music', '/missing'],
+ })
+ )
+ const original = await page.evaluate(() =>
+ window.directoryPickerFixture.getSettings()
+ )
+ const { manager } = await openSettingsManager(page)
+ await expect(manager.getByRole('textbox')).toHaveValue('/downloads')
+ await expect(manager.getByRole('textbox')).toHaveAttribute(
+ 'title',
+ '/downloads'
+ )
+ await expect(manager.getByRole('textbox')).toHaveCSS('direction', 'ltr')
+ await expect(
+ manager.getByRole('button', {
+ name: 'Remove favorite /downloads/Movies',
+ exact: true,
+ })
+ ).toBeVisible()
+ await settlePanel(page, manager)
+ await manager.screenshot({
+ path: test.info().outputPath('general-directory-fields-wide-light.png'),
+ })
+ await expandRecent(manager)
+ await manager
+ .getByRole('button', {
+ name: 'Remove recent folder /downloads/Movies',
+ exact: true,
+ })
+ .click()
+ await manager
+ .getByRole('button', { name: 'Remove favorite /archive', exact: true })
+ .click()
+ await manager
+ .getByRole('button', {
+ name: 'Add to favorites /downloads/Music',
+ exact: true,
+ })
+ .click()
+ await manager
+ .getByRole('switch', {
+ name: 'Notify when download completes',
+ exact: true,
+ })
+ .click()
+ await expect(
+ manager.getByRole('button', {
+ name: 'Remove favorite /downloads/Music',
+ exact: true,
+ })
+ ).toBeVisible()
+ await expect(
+ manager.getByRole('button', {
+ name: 'Remove recent folder /downloads/Movies',
+ exact: true,
+ })
+ ).toHaveCount(0)
+ expect(await preferenceWrites(page)).toHaveLength(0)
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getSettings())
+ ).toEqual(original)
+ await manager.getByRole('button', { name: 'Cancel', exact: true }).click()
+ expect(await preferenceWrites(page)).toHaveLength(0)
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getSettings())
+ ).toEqual(original)
+ const reopened = await openSettingsManager(page)
+ await expandRecent(reopened.manager)
+ await expect(
+ reopened.manager.getByRole('button', {
+ name: 'Remove favorite /archive',
+ exact: true,
+ })
+ ).toBeVisible()
+ await expect(
+ reopened.manager.getByRole('button', {
+ name: 'Remove recent folder /downloads/Movies',
+ exact: true,
+ })
+ ).toBeVisible()
+})
+
+test('General Save atomically commits settings and directory intent against concurrent new records', async ({
+ page,
+}) => {
+ await seed(page)
+ const { manager } = await openSettingsManager(page)
+ await expandRecent(manager)
+ const notification = manager.getByRole('switch', {
+ name: 'Notify when download completes',
+ exact: true,
+ })
+ const initialNotification = await notification.isChecked()
+ await manager
+ .getByRole('button', {
+ name: 'Remove recent folder /downloads/Movies',
+ exact: true,
+ })
+ .click()
+ await manager
+ .getByRole('button', {
+ name: 'Add to favorites /downloads/Music',
+ exact: true,
+ })
+ .click()
+ await notification.click()
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ }, Commands.SaveGeneralSettings)
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect.poll(() => preferenceWrites(page)).toHaveLength(1)
+ await page.evaluate(() =>
+ window.directoryPickerFixture.setPreferences({
+ favorites: ['/archive', '/downloads/Empty'],
+ recent: ['/archive', '/downloads/Movies', '/downloads/Music', '/missing'],
+ })
+ )
+ expect(
+ (await page.evaluate(() => window.directoryPickerFixture.getSettings())).app
+ .notifyOnComplete
+ ).toBe(initialNotification)
+ await page.evaluate(() => {
+ window.directoryPickerFixture.holdChannel = null
+ window.directoryPickerFixture.releaseRequest?.()
+ })
+ await expect(manager).not.toBeVisible()
+ const writes = await preferenceWrites(page)
+ expect(writes).toHaveLength(2)
+ for (const write of writes) {
+ expect(write).toEqual({
+ channel: Commands.SaveGeneralSettings,
+ args: [
+ {
+ expectedRevision: expect.any(String),
+ app: { notifyOnComplete: !initialNotification },
+ directories: {
+ addFavorites: ['/downloads/Music'],
+ removeFavorites: [],
+ removeRecent: ['/downloads/Movies'],
+ },
+ },
+ ],
+ })
+ }
+ expect(
+ (writes[0].args[0] as { expectedRevision: string }).expectedRevision
+ ).not.toBe(
+ (writes[1].args[0] as { expectedRevision: string }).expectedRevision
+ )
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getPreferences())
+ ).toEqual({
+ favorites: ['/archive', '/downloads/Empty', '/downloads/Music'],
+ recent: ['/archive', '/downloads/Music', '/missing'],
+ })
+ expect(
+ (await page.evaluate(() => window.directoryPickerFixture.getSettings())).app
+ .notifyOnComplete
+ ).toBe(!initialNotification)
+})
+
+test('General failed Save keeps both committed settings and preferences unchanged and preserves the draft', async ({
+ page,
+}) => {
+ await seed(page)
+ const original = await page.evaluate(() =>
+ window.directoryPickerFixture.getSettings()
+ )
+ const { manager } = await openSettingsManager(page)
+ await expandRecent(manager)
+ await manager
+ .getByRole('button', { name: 'Remove recent folder /missing', exact: true })
+ .click()
+ const notification = manager.getByRole('switch', {
+ name: 'Notify when download completes',
+ exact: true,
+ })
+ await notification.click()
+ await page.evaluate(() => {
+ window.directoryPickerFixture.mutationFailure = true
+ })
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(manager.getByRole('alert')).toBeVisible()
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getSettings())
+ ).toEqual(original)
+ await expect(notification).toBeChecked({
+ checked: !original.app.notifyOnComplete,
+ })
+ await expect(
+ manager.getByRole('button', {
+ name: 'Remove recent folder /missing',
+ exact: true,
+ })
+ ).toHaveCount(0)
+ await manager.getByRole('button', { name: 'Cancel', exact: true }).click()
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getSettings())
+ ).toEqual(original)
+})
+
+test('history manager drafts contain failure shortcuts and cancel nested Web Browse without saving', async ({
+ page,
+}) => {
+ await seed(page)
+ const original = await page.evaluate(() =>
+ window.directoryPickerFixture.getPreferences()
+ )
+ const parent = await openDownload(page)
+ const history = parent.getByRole('button', {
+ name: 'Directory history',
+ exact: true,
+ })
+ await history.click()
+ await page
+ .getByRole('menuitem', { name: 'Manage directories', exact: true })
+ .click()
+ const manager = page.getByRole('dialog', {
+ name: 'Manage directories',
+ exact: true,
+ })
+ await expect(manager).toHaveCSS('opacity', '1')
+ await expandRecent(manager)
+ await manager
+ .getByRole('button', {
+ name: 'Remove recent folder /downloads/Music',
+ exact: true,
+ })
+ .click()
+ expect(await preferenceWrites(page)).toHaveLength(0)
+ await page.evaluate(() => {
+ window.directoryPickerFixture.mutationFailure = true
+ })
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(manager.getByRole('alert')).toBeVisible()
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Meta+Enter')
+ expect(await parentSubmissions(page)).toHaveLength(0)
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getPreferences())
+ ).toEqual(original)
+ await page.evaluate(() => {
+ window.directoryPickerFixture.mutationFailure = false
+ })
+ await manager
+ .getByRole('button', { name: 'Add favorite', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ await expect(picker.getByRole('listbox', { name: 'Folders' })).toBeFocused()
+ await expect(picker.getByTestId('directory-picker-favorite')).toHaveCount(0)
+ await page.keyboard.press('Escape')
+ await expect(picker).not.toBeVisible()
+ await expect(
+ manager.getByRole('button', { name: 'Add favorite', exact: true })
+ ).toBeFocused()
+ await manager.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(history).toBeFocused()
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getPreferences())
+ ).toEqual(original)
+ expect(await parentSubmissions(page)).toHaveLength(0)
+})
+
+test('history manager Save commits its directory-only draft and restores the history trigger', async ({
+ page,
+}) => {
+ await seed(page)
+ const parent = await openDownload(page)
+ const history = parent.getByRole('button', {
+ name: 'Directory history',
+ exact: true,
+ })
+ await history.click()
+ await page
+ .getByRole('menuitem', { name: 'Manage directories', exact: true })
+ .click()
+ const manager = page.getByRole('dialog', {
+ name: 'Manage directories',
+ exact: true,
+ })
+ await settlePanel(page, manager)
+ const collapsed = await manager.boundingBox()
+ if (!collapsed) throw new Error('Expected the history manager to be visible')
+ await manager.screenshot({
+ path: test.info().outputPath('history-manager-collapsed.png'),
+ })
+ await expandRecent(manager)
+ await settlePanel(page, manager)
+ const expanded = await manager.boundingBox()
+ if (!expanded)
+ throw new Error('Expected the expanded history manager to be visible')
+ expect(expanded.height).toBeGreaterThan(collapsed.height)
+ await test.info().attach('history-manager-height-metrics', {
+ body: JSON.stringify(
+ { collapsed: collapsed.height, expanded: expanded.height },
+ null,
+ 2
+ ),
+ contentType: 'application/json',
+ })
+ await manager.screenshot({
+ path: test.info().outputPath('history-manager-expanded.png'),
+ })
+ await manager
+ .getByRole('button', { name: 'Remove recent folder /missing', exact: true })
+ .click()
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(manager).not.toBeVisible()
+ await expect(history).toBeFocused()
+ expect(await preferenceWrites(page)).toEqual([
+ {
+ channel: Commands.SaveGeneralSettings,
+ args: [
+ {
+ expectedRevision: expect.any(String),
+ app: {},
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: ['/missing'],
+ },
+ },
+ ],
+ },
+ ])
+ expect(
+ await page.evaluate(
+ () => window.directoryPickerFixture.getPreferences().recent
+ )
+ ).toEqual(['/downloads/Movies', '/downloads/Music'])
+ expect(await parentSubmissions(page)).toHaveLength(0)
+})
+
+for (const app of [false, true]) {
+ test(`General Browse stages its default and favorites without recording recent use (${app ? 'App service' : 'Web'})`, async ({
+ page,
+ }) => {
+ await seed(page, app ? '?transportPlatform=linux&nativePicker=1' : '')
+ const original = await page.evaluate(() =>
+ window.directoryPickerFixture.getPreferences()
+ )
+ await page.evaluate(() => {
+ window.directoryPickerFixture.nativePickerResult = '/downloads/Movies'
+ })
+ const { manager } = await openSettingsManager(page)
+ await expandRecent(manager)
+ await manager
+ .getByRole('button', { name: 'Clear recent folders', exact: true })
+ .click()
+ const chooseMovies = async (draft = true) => {
+ if (app) return
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ await expect(picker.getByTestId('directory-picker-favorite')).toHaveCount(
+ draft ? 0 : 1
+ )
+ await picker.getByRole('option', { name: 'Movies', exact: true }).click()
+ await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ await expect(picker).not.toBeVisible()
+ }
+ await manager.getByRole('button', { name: 'Browse…', exact: true }).click()
+ await chooseMovies()
+ await expect(manager.getByRole('textbox')).toHaveValue('/downloads/Movies')
+ await expect(manager.getByRole('textbox')).toHaveAttribute(
+ 'title',
+ '/downloads/Movies'
+ )
+ await expect(manager.getByRole('textbox')).toHaveCSS('direction', 'ltr')
+ await manager
+ .getByRole('button', { name: 'Add favorite', exact: true })
+ .click()
+ await chooseMovies()
+ await expect(
+ manager.getByRole('button', {
+ name: 'Remove favorite /downloads/Movies',
+ exact: true,
+ })
+ ).toBeVisible()
+ expect(await preferenceWrites(page)).toHaveLength(0)
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getPreferences())
+ ).toEqual(original)
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(manager).not.toBeVisible()
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getPreferences())
+ ).toEqual({ favorites: ['/archive', '/downloads/Movies'], recent: [] })
+ expect(
+ (await page.evaluate(() => window.directoryPickerFixture.getSettings()))
+ .app.defaultSaveDir
+ ).toBe('/downloads/Movies')
+ const parent = await openDownload(page)
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ await chooseMovies(false)
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.directoryPickerFixture.getPreferences().recent
+ )
+ )
+ .toEqual(['/downloads/Movies'])
+ if (app) {
+ expect(
+ await page.evaluate(
+ () => window.directoryPickerFixture.nativePickerCalls
+ )
+ ).toBe(3)
+ expect(
+ await page.evaluate(
+ (channel) =>
+ window.directoryPickerFixture.calls.filter(
+ (call) => call.channel === channel
+ ),
+ Queries.ListServerDirectoryLocations
+ )
+ ).toHaveLength(0)
+ }
+ })
+}
+
+test('unrestricted common places, root breadcrumb and Mac jumps stay available without allowed roots', async ({
+ page,
+}) => {
+ await page.addInitScript(() =>
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'MacIntel',
+ })
+ )
+ await seed(page, '?unrestricted=1')
+ const parent = await openDownload(page)
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ await expect(
+ picker.getByRole('option', { name: 'Movies', exact: true })
+ ).toBeVisible()
+ await expect(
+ picker.getByRole('navigation', { name: 'Location', exact: true })
+ ).toBeVisible()
+ await expect(
+ picker.getByRole('navigation', { name: 'Folder path', exact: true })
+ ).toHaveText('/downloads')
+ await page.keyboard.press('Meta+Shift+h')
+ await expect(
+ picker.getByRole('option', { name: 'Desktop', exact: true })
+ ).toBeVisible()
+ await page.keyboard.press('Meta+Shift+o')
+ await expect(picker.getByText('No subfolders', { exact: true })).toBeVisible()
+ await expect(
+ picker
+ .getByRole('navigation', { name: 'Folder path', exact: true })
+ .getByRole('button', { name: 'Documents', exact: true })
+ ).toBeVisible()
+ await expect(picker).toHaveCSS('opacity', '1')
+ await picker.screenshot({
+ path: test.info().outputPath('unrestricted-native-places.png'),
+ })
+})
+
+test('Web star saves the browsed directory and accepted AddTask updates shared recent history', async ({
+ page,
+}) => {
+ await seed(page)
+ const parent = await openDownload(page)
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ await picker.getByRole('option', { name: 'Movies', exact: true }).click()
+ await picker
+ .getByRole('button', { name: 'Add favorite', exact: true })
+ .click()
+ await expect(
+ picker.getByRole('button', { name: 'Remove favorite', exact: true })
+ ).toBeEnabled()
+ expect(
+ await page.evaluate(
+ () => window.directoryPickerFixture.getPreferences().favorites
+ )
+ ).toEqual(['/archive', '/downloads'])
+ await picker.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await expect(
+ parent.getByRole('button', { name: 'Change directory', exact: true })
+ ).toHaveAttribute('title', '/downloads')
+ await parent
+ .getByRole('button', { name: 'Directory history', exact: true })
+ .click()
+ const menu = page.getByRole('menu', { name: 'Directory history' })
+ await expect(
+ menu.getByRole('menuitem', { name: '/downloads', exact: true })
+ ).toBeVisible()
+ await page.keyboard.press('Escape')
+ await parent.getByRole('button', { name: 'Download', exact: true }).click()
+ await expect(parent).not.toBeVisible()
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () => window.directoryPickerFixture.getPreferences().recent[0]
+ )
+ )
+ .toBe('/downloads')
+ expect(await parentSubmissions(page)).toHaveLength(1)
+})
+
+test('narrow General directory fields stay compact with centered rows, full path titles and a visible footer', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 390, height: 620 })
+ await seed(page, '?theme=dark')
+ const paths = Array.from(
+ { length: 20 },
+ (_, index) => `/downloads/${index}-${'long-folder-name-'.repeat(12)}`
+ )
+ await page.evaluate(
+ (favorites) =>
+ window.directoryPickerFixture.setPreferences({
+ favorites,
+ recent: ['/downloads/Movies', '/downloads/Music'],
+ }),
+ paths
+ )
+ const { manager } = await openSettingsManager(page)
+ const recent = manager.getByRole('button', { name: /^Recent folders/ })
+ await expect(recent).toHaveAttribute('aria-expanded', 'false')
+ const path = manager.getByTitle(paths[0], { exact: true })
+ await expect(manager.getByRole('textbox')).toHaveValue('/downloads')
+ await expect(manager.getByRole('textbox')).toHaveAttribute(
+ 'title',
+ '/downloads'
+ )
+ await expect(manager.getByRole('textbox')).toHaveCSS('direction', 'ltr')
+ await expect(path).toBeVisible()
+ const row = path.locator('..')
+ const layout = await row.evaluate((element) => {
+ const children = [...element.children]
+ .map((child) => child.getBoundingClientRect())
+ .filter((rect) => rect.width > 0 && rect.height > 0)
+ const centers = children.map((rect) => rect.y + rect.height / 2)
+ const text = element.querySelector('[title]') as HTMLElement
+ return {
+ height: element.getBoundingClientRect().height,
+ right: element.getBoundingClientRect().right,
+ dialogRight:
+ element.closest('[role="dialog"]')?.getBoundingClientRect().right ?? 0,
+ centerSpread: Math.max(...centers) - Math.min(...centers),
+ truncated: text.scrollWidth > text.clientWidth,
+ }
+ })
+ await test.info().attach('compact-directory-row-metrics', {
+ body: JSON.stringify(layout, null, 2),
+ contentType: 'application/json',
+ })
+ // A 40px content row may include its 1px divider.
+ expect(layout.height).toBeLessThanOrEqual(42)
+ expect(layout.centerSpread).toBeLessThanOrEqual(1)
+ expect(layout.truncated).toBe(true)
+ expect(layout.right).toBeLessThanOrEqual(layout.dialogRight)
+ await expect(
+ manager.getByRole('button', { name: 'Browse…', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ row.getByRole('button', {
+ name: `Remove favorite ${paths[0]}`,
+ exact: true,
+ })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ manager.getByRole('button', { name: 'Save', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await expect(
+ manager.getByRole('button', { name: 'Cancel', exact: true })
+ ).toBeInViewport({ ratio: 1 })
+ await manager.screenshot({
+ path: test.info().outputPath('general-directory-fields-narrow-dark.png'),
+ })
+ await expandRecent(manager)
+ await manager
+ .getByRole('button', { name: 'Clear recent folders', exact: true })
+ .click()
+ expect(await preferenceWrites(page)).toHaveLength(0)
+ await manager.getByRole('button', { name: 'Cancel', exact: true }).click()
+ expect(
+ await page.evaluate(
+ () => window.directoryPickerFixture.getPreferences().recent
+ )
+ ).toEqual(['/downloads/Movies', '/downloads/Music'])
+})
+
+for (const control of ['location', 'favorite'] as const) {
+ test(`external preferences event retains ${control} DOM while pending locations stay inert`, async ({
+ page,
+ }) => {
+ await page.addInitScript(() =>
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'MacIntel',
+ })
+ )
+ await page.setViewportSize({ width: 390, height: 620 })
+ await seed(page, '?unrestricted=1')
+ const parent = await openDownload(page)
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ const target =
+ control === 'location'
+ ? picker.getByRole('combobox', { name: 'Location', exact: true })
+ : picker.getByRole('button', { name: 'Add favorite', exact: true })
+ await expect(target).toBeEnabled()
+ await target.focus()
+ await expect(target).toBeFocused()
+ await settlePanel(page, picker)
+ const targetNode = await target.elementHandle()
+ if (!targetNode) throw new Error('Expected the focused location control')
+ const beforeCalls = await page.evaluate(
+ () => window.directoryPickerFixture.calls.length
+ )
+ const beforeBounds = await picker
+ .getByRole('listbox', { name: 'Folders', exact: true })
+ .boundingBox()
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ window.directoryPickerFixture.setPreferences({
+ favorites: [],
+ recent: [],
+ })
+ }, Queries.ListServerDirectoryLocations)
+ await settleFrames(page)
+ expect(await targetNode.evaluate((element) => element.isConnected)).toBe(
+ true
+ )
+ expect(
+ await picker
+ .getByRole('listbox', { name: 'Folders', exact: true })
+ .boundingBox()
+ ).toEqual(beforeBounds)
+ if (control === 'favorite') {
+ await expect(target).toBeFocused()
+ await expect(target).toHaveAttribute('aria-disabled', 'true')
+ }
+ expect(
+ await page.evaluate(
+ () =>
+ !!document.activeElement?.closest(
+ '[data-testid="web-directory-picker"]'
+ )
+ )
+ ).toBe(true)
+ await picker
+ .getByRole('combobox', { name: 'Location', exact: true })
+ .evaluate((element) => {
+ const select = element as HTMLSelectElement
+ select.value = '/home/operator'
+ select.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ await picker.getByTestId('directory-picker-favorite').dispatchEvent('click')
+ await page.keyboard.press('Meta+Shift+h')
+ await page.keyboard.press('Meta+Shift+o')
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Meta+Enter')
+ const pendingCalls = await page.evaluate(
+ (offset) => window.directoryPickerFixture.calls.slice(offset),
+ beforeCalls
+ )
+ expect(
+ pendingCalls.filter(
+ (call) => call.channel === Queries.ListServerDirectories
+ )
+ ).toHaveLength(0)
+ expect(
+ pendingCalls.filter(
+ (call) => call.channel === Commands.MutateDirectoryPreferences
+ )
+ ).toHaveLength(0)
+ expect(await parentSubmissions(page)).toHaveLength(0)
+ await expect(picker).toBeVisible()
+ })
+}
+
+test('a no-op Save fences a timed-out original even when its delayed validation finishes after the dialog closes', async ({
+ page,
+}) => {
+ await seed(page)
+ const { manager } = await openSettingsManager(page)
+ await expandRecent(manager)
+ await manager
+ .getByRole('button', {
+ name: 'Add to favorites /downloads/Music',
+ exact: true,
+ })
+ .click()
+ await page.clock.install()
+ await page.evaluate((channel) => {
+ window.directoryPickerFixture.holdChannel = channel
+ }, Commands.SaveGeneralSettings)
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect.poll(() => preferenceWrites(page)).toHaveLength(1)
+ await page.clock.fastForward(20_001)
+ await expect(manager.getByRole('alert')).toBeVisible()
+ await manager
+ .getByRole('button', {
+ name: 'Remove favorite /downloads/Music',
+ exact: true,
+ })
+ .click()
+ await page.evaluate(() => {
+ window.directoryPickerFixture.holdChannel = null
+ })
+ await manager.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(manager).not.toBeVisible()
+ expect(await preferenceWrites(page)).toHaveLength(2)
+ await page.evaluate(async () => {
+ window.directoryPickerFixture.releaseRequest?.()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ expect(
+ await page.evaluate(() => window.directoryPickerFixture.getPreferences())
+ ).toEqual({
+ favorites: ['/archive'],
+ recent: ['/downloads/Movies', '/downloads/Music', '/missing'],
+ })
+ const reopened = await openSettingsManager(page)
+ await expect(
+ reopened.manager.getByRole('button', {
+ name: 'Remove favorite /downloads/Music',
+ exact: true,
+ })
+ ).toHaveCount(0)
+})
diff --git a/e2e/web-directory-picker/sorting.browser.ts b/e2e/web-directory-picker/sorting.browser.ts
new file mode 100644
index 00000000..78c2d639
--- /dev/null
+++ b/e2e/web-directory-picker/sorting.browser.ts
@@ -0,0 +1,460 @@
+import { expect, type Locator, type Page, test } from '@playwright/test'
+import { Commands } from '../../src/shared/protocol/commands'
+import { Queries } from '../../src/shared/protocol/queries'
+
+const STORAGE_KEY = 'motrix.web-directory-picker.sort.v1'
+const names = [
+ 'Folder 10',
+ 'folder 2',
+ 'Unknown 10',
+ 'Zero',
+ 'alpha',
+ 'Folder 2',
+ 'Unknown 2',
+]
+const natural = [
+ 'alpha',
+ 'Folder 2',
+ 'folder 2',
+ 'Folder 10',
+ 'Unknown 2',
+ 'Unknown 10',
+ 'Zero',
+]
+const modifiedAscending = [
+ 'alpha',
+ 'Folder 2',
+ 'folder 2',
+ 'Zero',
+ 'Folder 10',
+ 'Unknown 2',
+ 'Unknown 10',
+]
+const modifiedDescending = [
+ 'Folder 10',
+ 'Folder 2',
+ 'folder 2',
+ 'Zero',
+ 'alpha',
+ 'Unknown 2',
+ 'Unknown 10',
+]
+
+test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() =>
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'Win32',
+ })
+ )
+})
+
+async function seedEntries(page: Page) {
+ await page.evaluate((children) => {
+ window.directoryPickerFixture.setDirectoryChildren('/downloads', children)
+ window.directoryPickerFixture.modifiedAtByPath = {
+ '/downloads/alpha': -100,
+ '/downloads/Folder 2': 0,
+ '/downloads/folder 2': 0,
+ '/downloads/Zero': 0,
+ '/downloads/Folder 10': 10.5,
+ }
+ }, names)
+}
+
+async function openPicker(page: Page) {
+ await page
+ .getByRole('button', { name: 'Open download dialog', exact: true })
+ .click()
+ const parent = page.getByRole('dialog', { name: 'New Task', exact: true })
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ const picker = page.getByRole('dialog', {
+ name: 'Select server folder',
+ exact: true,
+ })
+ const list = picker.getByRole('listbox', { name: 'Folders', exact: true })
+ await expect(list).toHaveAttribute('aria-busy', 'false')
+ await expect(picker.getByTestId('directory-picker-favorite')).toBeEnabled()
+ return { parent, picker, list }
+}
+
+async function choose(
+ page: Page,
+ picker: Locator,
+ label: 'Name' | 'Date modified' | 'Ascending' | 'Descending'
+) {
+ await picker
+ .getByRole('button', { name: 'View options', exact: true })
+ .click()
+ const menu = page.getByRole('menu', { name: 'View options', exact: true })
+ await menu.getByRole('menuitemradio', { name: label, exact: true }).click()
+ await expect(menu).not.toBeVisible()
+ await expect(
+ picker.getByRole('listbox', { name: 'Folders', exact: true })
+ ).toBeFocused()
+}
+
+async function labels(list: Locator) {
+ return list.getByRole('option').allTextContents()
+}
+
+async function expectVisibleRow(list: Locator, row: Locator) {
+ // Browser zoom/layout may leave a fraction of a pixel outside the scroll clip.
+ await expect(row).toBeInViewport({ ratio: 0.98 })
+ const container = await list.boundingBox()
+ const bounds = await row.boundingBox()
+ if (!container || !bounds) throw new Error('Expected visible list and row')
+ expect(bounds.y).toBeGreaterThanOrEqual(container.y - 1)
+ expect(bounds.y + bounds.height).toBeLessThanOrEqual(
+ container.y + container.height + 1
+ )
+}
+
+async function goTo(picker: Locator, path: string) {
+ await picker
+ .getByRole('button', { name: 'Go to folder', exact: true })
+ .click()
+ await picker
+ .getByRole('textbox', { name: 'Folder path', exact: true })
+ .fill(path)
+ await picker.getByRole('button', { name: 'Go', exact: true }).click()
+ await expect(
+ picker.getByRole('listbox', { name: 'Folders', exact: true })
+ ).toHaveAttribute('aria-busy', 'false')
+}
+
+async function calls(page: Page) {
+ return page.evaluate(() => window.directoryPickerFixture.calls)
+}
+
+test('name and modification ordering use natural ties, numeric times and missing-last without RPC', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await seedEntries(page)
+ const { picker, list } = await openPicker(page)
+ await expect.poll(() => labels(list)).toEqual(natural)
+ const before = await calls(page)
+ await choose(page, picker, 'Descending')
+ await expect.poll(() => labels(list)).toEqual([...natural].reverse())
+ await choose(page, picker, 'Date modified')
+ await expect.poll(() => labels(list)).toEqual(modifiedDescending)
+ await choose(page, picker, 'Ascending')
+ await expect.poll(() => labels(list)).toEqual(modifiedAscending)
+ await choose(page, picker, 'Name')
+ await expect.poll(() => labels(list)).toEqual(natural)
+ expect(await calls(page)).toEqual(before)
+ await test.info().attach('sort-request-budget', {
+ body: JSON.stringify({
+ changes: 4,
+ additionalCalls: 0,
+ finalOrder: natural,
+ }),
+ contentType: 'application/json',
+ })
+ expect(
+ await page.evaluate(
+ (key) => JSON.parse(localStorage.getItem(key) ?? 'null'),
+ STORAGE_KEY
+ )
+ ).toEqual({ version: 1, by: 'name', direction: 'asc' })
+})
+
+test('keyboard movement and prefix search use the displayed order while confirmation remains path-based', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await seedEntries(page)
+ const { parent, picker, list } = await openPicker(page)
+ await choose(page, picker, 'Date modified')
+ await choose(page, picker, 'Descending')
+ await page.keyboard.press('Home')
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/downloads/Folder 10'
+ )
+ await page.keyboard.press('ArrowDown')
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/downloads/Folder 2'
+ )
+ await page.keyboard.press('End')
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/downloads/Unknown 10'
+ )
+ await page.keyboard.press('f')
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/downloads/Folder 10'
+ )
+ const selected = list.locator('[aria-selected="true"]')
+ await expect(selected).toHaveAttribute('aria-posinset', '1')
+ await expect(list).toHaveAttribute(
+ 'aria-activedescendant',
+ (await selected.getAttribute('id')) ?? ''
+ )
+ await picker
+ .getByRole('button', { name: 'Select folder', exact: true })
+ .click()
+ await expect(picker).not.toBeVisible()
+ await expect(
+ parent.getByRole('button', { name: 'Change directory', exact: true })
+ ).toHaveAttribute('title', '/downloads/Folder 10')
+ expect(
+ (await calls(page)).filter((call) => call.channel === Commands.CreateTask)
+ ).toHaveLength(0)
+})
+
+for (const select of [false, true]) {
+ test(`sorting a scrolled list ${select ? 'reveals its selected path' : 'returns to the top without selecting a folder'}`, async ({
+ page,
+ }) => {
+ await page.goto('/')
+ const { picker, list } = await openPicker(page)
+ await goTo(picker, '/archive')
+ await list.evaluate((element) => {
+ element.scrollTop = 600 * 32
+ })
+ const selected = list.getByRole('option', {
+ name: 'Folder 0600',
+ exact: true,
+ })
+ await expectVisibleRow(list, selected)
+ if (select) await selected.click()
+ const before = await calls(page)
+ await choose(page, picker, 'Descending')
+ expect(await calls(page)).toEqual(before)
+ if (select) {
+ await expect(selected).toHaveAttribute('aria-selected', 'true')
+ await expect(selected).toHaveAttribute('aria-posinset', '200')
+ await expectVisibleRow(list, selected)
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/archive/Folder 0600'
+ )
+ } else {
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBe(0)
+ await expect(list.locator('[aria-selected="true"]')).toHaveCount(0)
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/archive'
+ )
+ }
+ const offset = await list.evaluate((element) => element.scrollTop)
+ await choose(page, picker, 'Descending')
+ expect(await calls(page)).toEqual(before)
+ expect(await list.evaluate((element) => element.scrollTop)).toBe(offset)
+ })
+}
+
+test('Back after sorting elsewhere reveals historical selection and refresh retains the chosen order', async ({
+ page,
+}) => {
+ await page.goto('/')
+ const { picker, list } = await openPicker(page)
+ await goTo(picker, '/archive')
+ await list.evaluate((element) => {
+ element.scrollTop = 600 * 32
+ })
+ await list.getByRole('option', { name: 'Folder 0600', exact: true }).click()
+ await goTo(picker, '/downloads')
+ await choose(page, picker, 'Descending')
+ await picker.getByRole('button', { name: 'Back', exact: true }).click()
+ const selected = list.getByRole('option', {
+ name: 'Folder 0600',
+ exact: true,
+ })
+ await expect(selected).toHaveAttribute('aria-selected', 'true')
+ await expect(selected).toHaveAttribute('aria-posinset', '200')
+ await expectVisibleRow(list, selected)
+ await expect(picker.getByTestId('directory-picker-target')).toHaveText(
+ '/archive/Folder 0600'
+ )
+ const offset = await list.evaluate((element) => element.scrollTop)
+ expect(offset).not.toBe(600 * 32)
+ await picker.getByRole('button', { name: 'Refresh', exact: true }).click()
+ await expect(list).toHaveAttribute('aria-busy', 'false')
+ await expect(selected).toHaveAttribute('aria-posinset', '200')
+ await expect
+ .poll(() => list.evaluate((element) => element.scrollTop))
+ .toBe(offset)
+ await test.info().attach('history-sort-reveal', {
+ body: JSON.stringify({
+ oldOffset: 600 * 32,
+ restoredOffset: offset,
+ selectedPosition: 200,
+ selectedBounds: await selected.boundingBox(),
+ listBounds: await list.boundingBox(),
+ }),
+ contentType: 'application/json',
+ })
+})
+
+test('sort survives picker reopening and a new page using only versioned preference data', async ({
+ page,
+}) => {
+ await page.goto('/')
+ await seedEntries(page)
+ const { parent, picker } = await openPicker(page)
+ await choose(page, picker, 'Date modified')
+ await choose(page, picker, 'Descending')
+ await picker.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ await expect
+ .poll(() =>
+ labels(picker.getByRole('listbox', { name: 'Folders', exact: true }))
+ )
+ .toEqual(modifiedDescending)
+ expect(
+ await page.evaluate(
+ (key) => JSON.parse(localStorage.getItem(key) ?? 'null'),
+ STORAGE_KEY
+ )
+ ).toEqual({ version: 1, by: 'modified', direction: 'desc' })
+ await page.reload()
+ await seedEntries(page)
+ const reopened = await openPicker(page)
+ await expect.poll(() => labels(reopened.list)).toEqual(modifiedDescending)
+})
+
+test('a blocked storage write keeps the latest in-memory choice when a picker reopens', async ({
+ page,
+}) => {
+ await page.addInitScript((key) => {
+ localStorage.setItem(
+ key,
+ JSON.stringify({ version: 1, by: 'name', direction: 'asc' })
+ )
+ const original = Storage.prototype.setItem
+ Storage.prototype.setItem = function (name, value) {
+ if (name === key)
+ throw new DOMException('Storage quota exceeded', 'QuotaExceededError')
+ original.call(this, name, value)
+ }
+ }, STORAGE_KEY)
+ await page.goto('/')
+ await seedEntries(page)
+ const { parent, picker, list } = await openPicker(page)
+ await choose(page, picker, 'Date modified')
+ await choose(page, picker, 'Descending')
+ await expect.poll(() => labels(list)).toEqual(modifiedDescending)
+ await picker.getByRole('button', { name: 'Cancel', exact: true }).click()
+ await parent
+ .getByRole('button', { name: 'Change directory', exact: true })
+ .click()
+ await expect.poll(() => labels(list)).toEqual(modifiedDescending)
+ expect(
+ await page.evaluate(
+ (key) => JSON.parse(localStorage.getItem(key) ?? 'null'),
+ STORAGE_KEY
+ )
+ ).toEqual({ version: 1, by: 'name', direction: 'asc' })
+})
+
+for (const width of [1024, 390]) {
+ test(`View sorting radios support keyboard choice, Escape and parent isolation at ${width}px`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width, height: 620 })
+ await page.goto('/')
+ await seedEntries(page)
+ const { picker, list } = await openPicker(page)
+ const trigger = picker.getByRole('button', {
+ name: 'View options',
+ exact: true,
+ })
+ await trigger.focus()
+ await page.keyboard.press('Enter')
+ const menu = page.getByRole('menu', { name: 'View options', exact: true })
+ const name = menu.getByRole('menuitemradio', { name: 'Name', exact: true })
+ const modified = menu.getByRole('menuitemradio', {
+ name: 'Date modified',
+ exact: true,
+ })
+ await expect(name).toBeChecked()
+ await expect(
+ menu.getByRole('menuitemradio', { name: 'Ascending', exact: true })
+ ).toBeChecked()
+ await expect(menu.getByText('Sort by', { exact: true })).toBeVisible()
+ await expect(menu.getByText('Order', { exact: true })).toBeVisible()
+ await name.focus()
+ const before = await calls(page)
+ await page.keyboard.press('Control+Enter')
+ await page.keyboard.press('Meta+Enter')
+ await expect(menu).toBeVisible()
+ await expect(name).toBeChecked()
+ expect(await calls(page)).toEqual(before)
+ await page.keyboard.press('ArrowDown')
+ await expect(modified).toBeFocused()
+ await page.keyboard.press('Escape')
+ await expect(menu).not.toBeVisible()
+ await expect(trigger).toBeFocused()
+ await expect(picker).toBeVisible()
+ await expect.poll(() => labels(list)).toEqual(natural)
+ await page.keyboard.press('Enter')
+ await name.focus()
+ await page.keyboard.press('ArrowDown')
+ await page.keyboard.press('Enter')
+ await expect(menu).not.toBeVisible()
+ await expect(list).toBeFocused()
+ await expect.poll(() => labels(list)).toEqual(modifiedAscending)
+ await trigger.click()
+ await expect(modified).toBeChecked()
+ await menu
+ .getByRole('menuitemradio', { name: 'Descending', exact: true })
+ .focus()
+ await page.keyboard.press('Space')
+ await expect(menu).not.toBeVisible()
+ await expect(list).toBeFocused()
+ await expect.poll(() => labels(list)).toEqual(modifiedDescending)
+ await trigger.click()
+ await expect(modified).toBeChecked()
+ await expect(
+ menu.getByRole('menuitemradio', { name: 'Descending', exact: true })
+ ).toBeChecked()
+ await expect(menu).toHaveCSS('opacity', '1')
+ const menuBounds = await menu.boundingBox()
+ if (!menuBounds) throw new Error('Expected the View options menu to exist')
+ expect(menuBounds.height).toBeLessThan(252)
+ expect(menuBounds.x).toBeGreaterThanOrEqual(0)
+ expect(menuBounds.y).toBeGreaterThanOrEqual(0)
+ expect(menuBounds.x + menuBounds.width).toBeLessThanOrEqual(width)
+ expect(menuBounds.y + menuBounds.height).toBeLessThanOrEqual(620)
+ const rows = await menu
+ .locator('[role="menuitemradio"], [role="menuitemcheckbox"]')
+ .evaluateAll((elements) =>
+ elements.map((element) => ({
+ label: element.textContent,
+ height: element.getBoundingClientRect().height,
+ }))
+ )
+ expect(rows).toHaveLength(5)
+ for (const row of rows) {
+ expect(row.height).toBeGreaterThanOrEqual(24)
+ expect(row.height).toBeLessThanOrEqual(28)
+ }
+ await test.info().attach(`compact-view-menu-${width}`, {
+ body: JSON.stringify({
+ viewport: { width, height: 620 },
+ menuBounds,
+ rows,
+ }),
+ contentType: 'application/json',
+ })
+ await picker.screenshot({
+ path: test.info().outputPath(`sort-picker-${width}.png`),
+ })
+ await menu.screenshot({
+ path: test.info().outputPath(`sort-menu-${width}.png`),
+ })
+ expect(
+ (await calls(page)).filter((call) => call.channel === Commands.CreateTask)
+ ).toHaveLength(0)
+ expect(
+ (await calls(page)).filter(
+ (call) => call.channel === Queries.ListServerDirectories
+ )
+ ).toHaveLength(1)
+ })
+}
diff --git a/e2e/web-directory-picker/vite.config.ts b/e2e/web-directory-picker/vite.config.ts
new file mode 100644
index 00000000..9afc65a2
--- /dev/null
+++ b/e2e/web-directory-picker/vite.config.ts
@@ -0,0 +1,35 @@
+import path from 'node:path'
+import tailwindcss from '@tailwindcss/vite'
+import { defineConfig } from 'vite'
+
+const repositoryRoot = path.resolve(import.meta.dirname, '../..')
+
+export default defineConfig({
+ root: import.meta.dirname,
+ plugins: [tailwindcss()],
+ define: {
+ __MOTRIX_TARGET__: JSON.stringify('web'),
+ __MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(false),
+ },
+ resolve: {
+ alias: [
+ {
+ find: /^@renderer\/lib\/transport$/,
+ replacement: path.join(import.meta.dirname, 'fixture-transport.ts'),
+ },
+ {
+ find: '@renderer',
+ replacement: path.join(repositoryRoot, 'src/renderer'),
+ },
+ { find: '@shared', replacement: path.join(repositoryRoot, 'src/shared') },
+ {
+ find: 'path',
+ replacement: path.join(
+ repositoryRoot,
+ 'src/renderer/lib/path-browser-shim.ts'
+ ),
+ },
+ ],
+ },
+ server: { host: '127.0.0.1', port: 4178, strictPort: true },
+})
diff --git a/src/core/settings/directory-preferences.test.ts b/src/core/settings/directory-preferences.test.ts
new file mode 100644
index 00000000..cab42654
--- /dev/null
+++ b/src/core/settings/directory-preferences.test.ts
@@ -0,0 +1,119 @@
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createDirectoryPreferencesHandlers } from './directory-preferences'
+import { SettingsManager } from './settings-manager'
+
+const temporary: string[] = []
+afterEach(async () => {
+ vi.restoreAllMocks()
+ await Promise.all(
+ temporary
+ .splice(0)
+ .map((root) => rm(root, { recursive: true, force: true }))
+ )
+})
+async function fixture() {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-preferences-'))
+ temporary.push(root)
+ const settingsPath = path.join(root, 'settings.json')
+ const manager = new SettingsManager(settingsPath)
+ await manager.load()
+ return {
+ root,
+ settingsPath,
+ manager,
+ handlers: createDirectoryPreferencesHandlers(manager),
+ }
+}
+
+describe('host-neutral directory preference handlers', () => {
+ it('validates Desktop directories, normalizes aliases, keeps literal spaces, and permits stale record removal', async () => {
+ const { root, manager, handlers } = await fixture()
+ const target = path.join(
+ root,
+ process.platform === 'win32' ? 'folder' : 'folder '
+ )
+ await mkdir(target)
+ const alias = path.join(root, 'alias')
+ await symlink(target, alias)
+ const canonical = await realpath(target)
+ expect(
+ await handlers.mutate({ action: 'addFavorite', path: alias })
+ ).toEqual({ ok: true, value: { favorites: [canonical], recent: [] } })
+ await handlers.mutate({ action: 'addFavorite', path: target })
+ expect(manager.getApp().directoryPreferences.favorites).toEqual([canonical])
+ await rm(alias)
+ await rm(target, { recursive: true })
+ expect(await handlers.get({})).toEqual({
+ ok: true,
+ value: { favorites: [canonical], recent: [] },
+ })
+ expect(
+ await handlers.mutate({ action: 'removeFavorite', paths: [canonical] })
+ ).toEqual({ ok: true, value: { favorites: [], recent: [] } })
+ })
+
+ it('rejects invalid requests before filesystem or settings work and sanitizes missing/files', async () => {
+ const { root, manager, handlers } = await fixture()
+ const resolve = vi.fn(async (value: string) => value)
+ const guarded = createDirectoryPreferencesHandlers(manager, resolve)
+ const mutate = vi.spyOn(manager, 'mutateDirectoryPreferences')
+ expect(
+ await guarded.mutate({ action: 'addFavorite', path: root, extra: true })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(resolve).not.toHaveBeenCalled()
+ expect(mutate).not.toHaveBeenCalled()
+ expect(await guarded.get({ extra: true })).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ expect(
+ await handlers.mutate({ action: 'addFavorite', path: 'relative' })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(
+ await handlers.mutate({
+ action: 'recordRecent',
+ path: path.join(root, 'missing'),
+ })
+ ).toEqual({ ok: false, error: { code: 'notFound' } })
+ const file = path.join(root, 'file')
+ await writeFile(file, '')
+ expect(
+ await handlers.mutate({ action: 'addFavorite', path: file })
+ ).toEqual({ ok: false, error: { code: 'notDirectory' } })
+ })
+
+ it('leaves the durable snapshot unchanged when persistence fails', async () => {
+ const { root, manager, handlers, settingsPath } = await fixture()
+ await handlers.mutate({ action: 'addFavorite', path: root })
+ const before = await readFile(settingsPath, 'utf8')
+ // Fail the atomic save before publication; the earlier real file remains readable.
+ vi.spyOn(
+ manager as unknown as { saveSettings: () => Promise<void> },
+ 'saveSettings'
+ ).mockRejectedValueOnce(new Error('/private/disk failure'))
+ expect(await handlers.mutate({ action: 'clearRecent' })).toMatchObject({
+ ok: true,
+ })
+ expect(
+ await handlers.mutate({
+ action: 'removeFavorite',
+ paths: [await realpath(root)],
+ })
+ ).toEqual({ ok: false, error: { code: 'unavailable' } })
+ expect(await readFile(settingsPath, 'utf8')).toBe(before)
+ expect(manager.getApp().directoryPreferences.favorites).toEqual([
+ await realpath(root),
+ ])
+ })
+})
diff --git a/src/core/settings/directory-preferences.ts b/src/core/settings/directory-preferences.ts
new file mode 100644
index 00000000..0949f461
--- /dev/null
+++ b/src/core/settings/directory-preferences.ts
@@ -0,0 +1,96 @@
+import { constants } from 'node:fs'
+import { access, realpath, stat } from 'node:fs/promises'
+import path from 'node:path'
+import {
+ type DirectoryPreferencesErrorCode,
+ DirectoryPreferencesErrorCodeSchema,
+ type DirectoryPreferencesResult,
+ DirectoryPreferencesResultSchema,
+ GetDirectoryPreferencesRequestSchema,
+ MutateDirectoryPreferencesRequestSchema,
+} from '@shared/schemas/directory-preferences'
+import type { SettingsManager } from './settings-manager'
+
+export function directoryPreferenceFailure(
+ error: unknown
+): Extract<DirectoryPreferencesResult, { ok: false }> {
+ const directoryCode = DirectoryPreferencesErrorCodeSchema.safeParse(
+ (error as { directoryCode?: unknown } | null)?.directoryCode
+ )
+ let code: DirectoryPreferencesErrorCode = 'unavailable'
+ if (directoryCode.success) code = directoryCode.data
+ else {
+ switch ((error as NodeJS.ErrnoException | null)?.code) {
+ case 'ENOENT':
+ code = 'notFound'
+ break
+ case 'ENOTDIR':
+ code = 'notDirectory'
+ break
+ case 'EPERM':
+ case 'EACCES':
+ case 'EROFS':
+ code = 'permissionDenied'
+ break
+ case 'ENAMETOOLONG':
+ code = 'tooLarge'
+ break
+ case 'EINVAL':
+ code = 'invalidPath'
+ break
+ }
+ }
+ return { ok: false, error: { code } }
+}
+
+export async function resolveDesktopDirectory(value: string): Promise<string> {
+ if (!path.isAbsolute(value) || value.includes('\0')) {
+ throw Object.assign(new Error('Invalid directory'), { code: 'EINVAL' })
+ }
+ const canonical = await realpath(value)
+ if (!(await stat(canonical)).isDirectory()) {
+ throw Object.assign(new Error('Not a directory'), { code: 'ENOTDIR' })
+ }
+ await access(canonical, constants.R_OK | constants.X_OK)
+ return canonical
+}
+
+/** Both shells validate their own path boundary before the serialized action. */
+export function createDirectoryPreferencesHandlers(
+ settingsManager: SettingsManager,
+ resolveDirectory: (value: string) => Promise<string> = resolveDesktopDirectory
+) {
+ return {
+ get: async (raw: unknown): Promise<DirectoryPreferencesResult> => {
+ if (!GetDirectoryPreferencesRequestSchema.safeParse(raw).success) {
+ return { ok: false, error: { code: 'invalidPath' } }
+ }
+ try {
+ return DirectoryPreferencesResultSchema.parse({
+ ok: true,
+ value: settingsManager.getApp().directoryPreferences,
+ })
+ } catch {
+ return { ok: false, error: { code: 'unavailable' } }
+ }
+ },
+ mutate: async (raw: unknown): Promise<DirectoryPreferencesResult> => {
+ const parsed = MutateDirectoryPreferencesRequestSchema.safeParse(raw)
+ if (!parsed.success) return { ok: false, error: { code: 'invalidPath' } }
+ try {
+ const action = parsed.data
+ if (
+ action.action === 'addFavorite' ||
+ action.action === 'recordRecent'
+ ) {
+ action.path = await resolveDirectory(action.path)
+ }
+ return DirectoryPreferencesResultSchema.parse(
+ await settingsManager.mutateDirectoryPreferences(action)
+ )
+ } catch (error) {
+ return directoryPreferenceFailure(error)
+ }
+ },
+ }
+}
diff --git a/src/core/settings/general-settings.test.ts b/src/core/settings/general-settings.test.ts
new file mode 100644
index 00000000..5ea5968b
--- /dev/null
+++ b/src/core/settings/general-settings.test.ts
@@ -0,0 +1,259 @@
+import { mkdir, mkdtemp, readFile, realpath, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createSaveGeneralSettingsHandler } from './general-settings'
+import { SettingsManager } from './settings-manager'
+
+function createCurrentSave(
+ manager: SettingsManager,
+ options?: Parameters<typeof createSaveGeneralSettingsHandler>[1]
+) {
+ const save = createSaveGeneralSettingsHandler(manager, options)
+ return (raw: object) =>
+ save({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ ...raw,
+ })
+}
+
+const temporary: string[] = []
+const empty = { addFavorites: [], removeFavorites: [], removeRecent: [] }
+afterEach(async () => {
+ vi.restoreAllMocks()
+ await Promise.all(
+ temporary
+ .splice(0)
+ .map((root) => rm(root, { recursive: true, force: true }))
+ )
+})
+async function fixture() {
+ const root = await realpath(
+ await mkdtemp(path.join(tmpdir(), 'motrix-general-'))
+ )
+ temporary.push(root)
+ const file = path.join(root, 'settings.json')
+ const change = vi.fn()
+ const manager = new SettingsManager(file, { onChange: change })
+ await manager.load()
+ change.mockClear()
+ return { root, file, manager, change }
+}
+
+describe('General settings save handler', () => {
+ it('validates every addition then atomically persists General fields and exact directory deltas', async () => {
+ const { root, file, manager, change } = await fixture()
+ const destination = path.join(root, 'destination ')
+ await mkdir(destination)
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/stale ',
+ })
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/old ',
+ })
+ const apply = vi.fn(async () => {
+ const disk = JSON.parse(await readFile(file, 'utf8'))
+ expect(disk.app.notifyOnComplete).toBe(false)
+ expect(disk.app.directoryPreferences).toEqual({
+ favorites: [await realpath(destination)],
+ recent: [],
+ })
+ })
+ change.mockClear()
+ const save = createCurrentSave(manager, {
+ applySavedApp: apply,
+ })
+ expect(
+ await save({
+ app: { defaultSaveDir: destination, notifyOnComplete: false },
+ directories: {
+ addFavorites: [destination],
+ removeFavorites: ['/stale '],
+ removeRecent: ['/old '],
+ },
+ })
+ ).toMatchObject({
+ ok: true,
+ value: {
+ directoryPreferences: {
+ favorites: [await realpath(destination)],
+ recent: [],
+ },
+ },
+ })
+ expect(change).toHaveBeenCalledOnce()
+ expect(apply).toHaveBeenCalledOnce()
+ const reloaded = new SettingsManager(file)
+ await reloaded.load()
+ expect(reloaded.getApp()).toMatchObject({
+ defaultSaveDir: await realpath(destination),
+ notifyOnComplete: false,
+ directoryPreferences: {
+ favorites: [await realpath(destination)],
+ recent: [],
+ },
+ })
+ })
+
+ it('rejects malformed payload before any resolver, settings read/write or runtime effect', async () => {
+ const { manager } = await fixture()
+ const resolve = vi.fn(async (value: string) => value)
+ const commit = vi.spyOn(manager, 'saveGeneralSettings')
+ const apply = vi.fn()
+ const save = createCurrentSave(manager, {
+ resolveFavorite: resolve,
+ resolveDefaultDirectory: resolve,
+ applySavedApp: apply,
+ })
+ expect(
+ await save({
+ app: { defaultSaveDir: '/bad', directoryPreferences: {} },
+ directories: { ...empty, addFavorites: ['/bad'] },
+ })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(resolve).not.toHaveBeenCalled()
+ expect(commit).not.toHaveBeenCalled()
+ expect(apply).not.toHaveBeenCalled()
+ })
+
+ it('does not apply partial General fields or removals when an added or default directory is invalid', async () => {
+ const { root, file, manager, change } = await fixture()
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/keep',
+ })
+ const before = await readFile(file, 'utf8')
+ change.mockClear()
+ const apply = vi.fn()
+ const save = createCurrentSave(manager, {
+ applySavedApp: apply,
+ })
+ for (const request of [
+ {
+ app: { notifyOnError: false },
+ directories: {
+ ...empty,
+ addFavorites: [root, path.join(root, 'missing')],
+ removeFavorites: ['/keep'],
+ },
+ },
+ {
+ app: {
+ notifyOnError: false,
+ defaultSaveDir: path.join(root, 'missing'),
+ },
+ directories: { ...empty, removeFavorites: ['/keep'] },
+ },
+ ]) {
+ expect(await save(request)).toEqual({
+ ok: false,
+ error: { code: 'notFound' },
+ })
+ }
+ expect(await readFile(file, 'utf8')).toBe(before)
+ expect(manager.getApp().directoryPreferences.favorites).toEqual(['/keep'])
+ expect(change).not.toHaveBeenCalled()
+ expect(apply).not.toHaveBeenCalled()
+ })
+
+ it('preserves both aggregates and the previous real settings file when atomic persistence fails', async () => {
+ const { file, manager, change } = await fixture()
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/keep',
+ })
+ const before = await readFile(file, 'utf8')
+ const app = structuredClone(manager.getApp())
+ change.mockClear()
+ vi.spyOn(
+ manager as unknown as { saveSettings: () => Promise<void> },
+ 'saveSettings'
+ ).mockRejectedValueOnce(new Error('/private/disk failure'))
+ const apply = vi.fn()
+ const save = createCurrentSave(manager, {
+ applySavedApp: apply,
+ })
+ expect(
+ await save({
+ app: { notifyOnError: false },
+ directories: { ...empty, removeRecent: ['/keep'] },
+ })
+ ).toEqual({ ok: false, error: { code: 'unavailable' } })
+ expect(manager.getApp()).toEqual(app)
+ expect(await readFile(file, 'utf8')).toBe(before)
+ expect(change).not.toHaveBeenCalled()
+ expect(apply).not.toHaveBeenCalled()
+ })
+
+ it('reapplies submitted runtime fields when a prior effect failed after durable commit', async () => {
+ const { manager, change } = await fixture()
+ const apply = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('engine unavailable'))
+ .mockResolvedValue(undefined)
+ const save = createCurrentSave(manager, {
+ applySavedApp: apply,
+ })
+ const request = { app: { warnBeforeQuit: false }, directories: empty }
+ expect(await save(request)).toMatchObject({
+ ok: false,
+ error: { code: 'unavailable' },
+ snapshot: { app: { warnBeforeQuit: false } },
+ })
+ expect(manager.getApp().warnBeforeQuit).toBe(false)
+ expect(await save(request)).toMatchObject({ ok: true })
+ expect(apply).toHaveBeenCalledTimes(2)
+ expect(change).toHaveBeenCalledOnce()
+ })
+})
+
+it('fences a timed-out save still resolving directories when an empty compensation commits first', async () => {
+ const { root, file, manager, change } = await fixture()
+ const before = await readFile(file, 'utf8')
+ const revision = manager.getGeneralSettingsSnapshot().revision
+ let release!: (path: string) => void
+ const save = createSaveGeneralSettingsHandler(manager, {
+ resolveFavorite: () =>
+ new Promise((resolve) => {
+ release = resolve
+ }),
+ })
+ const original = save({
+ expectedRevision: revision,
+ app: { notifyOnError: false },
+ directories: { ...empty, addFavorites: [root] },
+ })
+ const compensation = await save({
+ expectedRevision: revision,
+ app: {},
+ directories: empty,
+ })
+ expect(compensation.ok).toBe(true)
+ expect(manager.getGeneralSettingsSnapshot().revision).not.toBe(revision)
+ release(root)
+ expect(await original).toMatchObject({
+ ok: false,
+ error: { code: 'conflict' },
+ })
+ expect(manager.getApp().notifyOnError).toBe(true)
+ expect(manager.getApp().directoryPreferences.favorites).toEqual([])
+ expect(await readFile(file, 'utf8')).toBe(before)
+ expect(change).not.toHaveBeenCalled()
+})
+
+it('rejects favorite normalization that would make uncertain additions impossible to remove by their draft key', async () => {
+ const { manager } = await fixture()
+ const save = createCurrentSave(manager, {
+ resolveFavorite: async () => '/canonical',
+ })
+ expect(
+ await save({
+ app: { notifyOnError: false },
+ directories: { ...empty, addFavorites: ['/alias'] },
+ })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(manager.getApp().directoryPreferences.favorites).toEqual([])
+ expect(manager.getApp().notifyOnError).toBe(true)
+})
diff --git a/src/core/settings/general-settings.ts b/src/core/settings/general-settings.ts
new file mode 100644
index 00000000..0190741a
--- /dev/null
+++ b/src/core/settings/general-settings.ts
@@ -0,0 +1,93 @@
+import { constants } from 'node:fs'
+import { access } from 'node:fs/promises'
+import { AppError } from '@shared/errors'
+import {
+ type GeneralSettingsResult,
+ GeneralSettingsResultSchema,
+ type GeneralSettingsSnapshot,
+ GetGeneralSettingsDraftRequestSchema,
+ type SaveGeneralSettingsRequest,
+ SaveGeneralSettingsRequestSchema,
+} from '@shared/schemas/general-settings'
+import {
+ directoryPreferenceFailure,
+ resolveDesktopDirectory,
+} from './directory-preferences'
+import type { SettingsManager } from './settings-manager'
+
+interface GeneralSettingsOptions {
+ resolveFavorite?: (path: string) => Promise<string>
+ resolveDefaultDirectory?: (path: string) => Promise<string>
+ applySavedApp?: (
+ patch: SaveGeneralSettingsRequest['app']
+ ) => Promise<void> | void
+}
+
+async function resolveDesktopDefaultDirectory(path: string): Promise<string> {
+ const canonical = await resolveDesktopDirectory(path)
+ await access(canonical, constants.W_OK | constants.X_OK)
+ return canonical
+}
+
+export function createGetGeneralSettingsDraftHandler(
+ settings: SettingsManager
+) {
+ return async (raw: unknown): Promise<GeneralSettingsResult> => {
+ if (!GetGeneralSettingsDraftRequestSchema.safeParse(raw).success)
+ return { ok: false, error: { code: 'invalidPath' } }
+ return { ok: true, value: settings.getGeneralSettingsSnapshot() }
+ }
+}
+
+/** Validate all new destinations before one queue-owned settings transaction. */
+export function createSaveGeneralSettingsHandler(
+ settings: SettingsManager,
+ options: GeneralSettingsOptions = {}
+) {
+ let sideEffectTail: Promise<void> = Promise.resolve()
+ return async (raw: unknown): Promise<GeneralSettingsResult> => {
+ const parsed = SaveGeneralSettingsRequestSchema.safeParse(raw)
+ if (!parsed.success) return { ok: false, error: { code: 'invalidPath' } }
+ let committed: GeneralSettingsSnapshot | undefined
+ try {
+ const request = parsed.data
+ const resolveFavorite = options.resolveFavorite ?? resolveDesktopDirectory
+ request.directories.addFavorites = await Promise.all(
+ request.directories.addFavorites.map(async (path) => {
+ const resolved = await resolveFavorite(path)
+ // Draft deltas use exact keys. Changing a key during an uncertain
+ // write would make its later removal indistinguishable from a remote add.
+ if (resolved !== path)
+ throw Object.assign(new Error('Noncanonical favorite'), {
+ code: 'EINVAL',
+ })
+ return path
+ })
+ )
+ if (request.app.defaultSaveDir !== undefined) {
+ request.app.defaultSaveDir = await (
+ options.resolveDefaultDirectory ?? resolveDesktopDefaultDirectory
+ )(request.app.defaultSaveDir)
+ }
+ const result = await settings.saveGeneralSettings(request)
+ if (!result.ok) return result
+ committed = result.value
+ // Runtime effects follow the durable commit. Reapplying submitted fields
+ // on retries also repairs a prior effect failure after a successful save.
+ const apply = sideEffectTail.then(() =>
+ options.applySavedApp?.(request.app)
+ )
+ sideEffectTail = apply.then(
+ () => undefined,
+ () => undefined
+ )
+ await apply
+ return GeneralSettingsResultSchema.parse(result)
+ } catch (error) {
+ const failure = directoryPreferenceFailure(
+ error instanceof AppError && error.cause ? error.cause : error
+ )
+ return { ...failure, ...(committed ? { snapshot: committed } : {}) }
+ }
+ }
+}
diff --git a/src/core/settings/settings-manager.test.ts b/src/core/settings/settings-manager.test.ts
index 339050ce..50e9b51b 100644
--- a/src/core/settings/settings-manager.test.ts
+++ b/src/core/settings/settings-manager.test.ts
@@ -67,6 +67,340 @@ describe('SettingsManager', () => {
manager = new SettingsManager(TEST_PATH, { onChange })
})
+ describe('directory preferences', () => {
+ beforeEach(() => {
+ mockWriteFileAtomic.mockResolvedValue(undefined)
+ })
+
+ it('loads old and corrupt preference values with safe empty defaults', async () => {
+ for (const value of [
+ undefined,
+ { favorites: [''], recent: [] },
+ 'broken',
+ ]) {
+ mockReadFile.mockResolvedValue(
+ JSON.stringify({ app: { directoryPreferences: value } })
+ )
+ await manager.load()
+ expect(manager.getApp().directoryPreferences).toEqual({
+ favorites: [],
+ recent: [],
+ })
+ }
+ })
+
+ it('serializes concurrent favorites and maintains bounded true MRU without trimming', async () => {
+ await Promise.all(
+ Array.from({ length: 20 }, (_, index) =>
+ manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: `/saved/${index}`,
+ })
+ )
+ )
+ expect(manager.getApp().directoryPreferences.favorites).toHaveLength(20)
+ expect(
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/extra',
+ })
+ ).toEqual({ ok: false, error: { code: 'limitReached' } })
+ const writes = mockWriteFileAtomic.mock.calls.length
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/saved/0',
+ })
+ expect(mockWriteFileAtomic).toHaveBeenCalledTimes(writes)
+ await Promise.all(
+ Array.from({ length: 12 }, (_, index) =>
+ manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: `/recent/${index}`,
+ })
+ )
+ )
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/recent/5',
+ })
+ expect(manager.getApp().directoryPreferences.recent).toEqual([
+ '/recent/5',
+ '/recent/11',
+ '/recent/10',
+ '/recent/9',
+ '/recent/8',
+ '/recent/7',
+ '/recent/6',
+ '/recent/4',
+ '/recent/3',
+ '/recent/2',
+ ])
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/literal/ ',
+ })
+ expect(manager.getApp().directoryPreferences.recent[0]).toBe('/literal/ ')
+ })
+
+ it('preserves the latest queued preferences against stale and malformed ordinary app patches', async () => {
+ const gate = deferred()
+ mockWriteFileAtomic.mockImplementationOnce(() => gate.promise)
+ const addition = manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/new',
+ })
+ const stale = manager.update({
+ app: { ...manager.getApp(), theme: 'dark' },
+ })
+ const corrupt = manager.update({
+ app: { directoryPreferences: 'bad' as never, notifyOnComplete: false },
+ })
+ gate.resolve()
+ await Promise.all([addition, stale, corrupt])
+ expect(manager.getApp()).toMatchObject({
+ theme: 'dark',
+ notifyOnComplete: false,
+ directoryPreferences: { favorites: ['/new'], recent: [] },
+ })
+ expect(
+ onChange.mock.calls.filter(
+ ([old, next]) =>
+ JSON.stringify(old.app.directoryPreferences) !==
+ JSON.stringify(next.app.directoryPreferences)
+ )
+ ).toHaveLength(1)
+ })
+
+ it('removes exact identities independently and treats missing removals as no-ops', async () => {
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/stale',
+ })
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/stale',
+ })
+ await manager.mutateDirectoryPreferences({
+ action: 'removeFavorite',
+ paths: ['/stale', '/missing'],
+ })
+ expect(manager.getApp().directoryPreferences).toEqual({
+ favorites: [],
+ recent: ['/stale'],
+ })
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/kept',
+ })
+ await manager.mutateDirectoryPreferences({ action: 'clearRecent' })
+ expect(manager.getApp().directoryPreferences).toEqual({
+ favorites: ['/kept'],
+ recent: [],
+ })
+ const writes = mockWriteFileAtomic.mock.calls.length
+ await manager.mutateDirectoryPreferences({
+ action: 'removeRecent',
+ paths: ['/missing'],
+ })
+ expect(mockWriteFileAtomic).toHaveBeenCalledTimes(writes)
+ })
+
+ it('keeps committed memory and events unchanged on atomic failure, and recovers its queue', async () => {
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/kept',
+ })
+ onChange.mockClear()
+ mockWriteFileAtomic.mockRejectedValueOnce(new Error('disk full'))
+ await expect(
+ manager.mutateDirectoryPreferences({
+ action: 'removeFavorite',
+ paths: ['/kept'],
+ })
+ ).rejects.toThrow('disk full')
+ expect(manager.getApp().directoryPreferences.favorites).toEqual(['/kept'])
+ expect(onChange).not.toHaveBeenCalled()
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/later',
+ })
+ expect(manager.getApp().directoryPreferences).toEqual({
+ favorites: ['/kept'],
+ recent: ['/later'],
+ })
+ })
+ })
+
+ describe('atomic General settings', () => {
+ const empty = { addFavorites: [], removeFavorites: [], removeRecent: [] }
+ beforeEach(() => mockWriteFileAtomic.mockResolvedValue(undefined))
+
+ it('applies baseline-relative deletes against latest queued preferences while committing General fields once', async () => {
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/baseline',
+ })
+ await manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/seen',
+ })
+ const gate = deferred()
+ mockWriteFileAtomic.mockImplementationOnce(() => gate.promise)
+ const add = manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/other-client',
+ })
+ const recent = manager.mutateDirectoryPreferences({
+ action: 'recordRecent',
+ path: '/new-recent',
+ })
+ const save = manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnComplete: false },
+ directories: {
+ addFavorites: ['/new-favorite '],
+ removeFavorites: ['/baseline'],
+ removeRecent: ['/seen'],
+ },
+ })
+ gate.resolve()
+ await Promise.all([add, recent, save])
+ expect(await save).toMatchObject({
+ ok: false,
+ error: { code: 'conflict' },
+ })
+ expect(manager.getApp().notifyOnComplete).toBe(true)
+ expect(
+ await manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnComplete: false },
+ directories: {
+ addFavorites: ['/new-favorite '],
+ removeFavorites: ['/baseline'],
+ removeRecent: ['/seen'],
+ },
+ })
+ ).toMatchObject({
+ ok: true,
+ value: {
+ directoryPreferences: {
+ favorites: ['/other-client', '/new-favorite '],
+ recent: ['/new-recent'],
+ },
+ },
+ })
+ expect(manager.getApp().notifyOnComplete).toBe(false)
+ expect(mockWriteFileAtomic).toHaveBeenCalledTimes(5)
+ const saved = JSON.parse(mockWriteFileAtomic.mock.calls.at(-1)?.[1])
+ expect(saved.app).toMatchObject({
+ notifyOnComplete: false,
+ directoryPreferences: {
+ favorites: ['/other-client', '/new-favorite '],
+ recent: ['/new-recent'],
+ },
+ })
+ })
+
+ it('checks the latest resulting cap before applying any General field, and permits replacement at the cap', async () => {
+ await Promise.all(
+ Array.from({ length: 20 }, (_, index) =>
+ manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: `/favorite/${index}`,
+ })
+ )
+ )
+ const before = structuredClone(manager.getApp())
+ mockWriteFileAtomic.mockClear()
+ onChange.mockClear()
+ expect(
+ await manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnError: false },
+ directories: { ...empty, addFavorites: ['/extra'] },
+ })
+ ).toEqual({ ok: false, error: { code: 'limitReached' } })
+ expect(manager.getApp()).toEqual(before)
+ expect(mockWriteFileAtomic).not.toHaveBeenCalled()
+ expect(onChange).not.toHaveBeenCalled()
+ expect(
+ await manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnError: false },
+ directories: {
+ ...empty,
+ addFavorites: ['/extra', '/extra'],
+ removeFavorites: ['/favorite/0'],
+ },
+ })
+ ).toMatchObject({ ok: true })
+ expect(manager.getApp().directoryPreferences.favorites).toHaveLength(20)
+ expect(manager.getApp().directoryPreferences.favorites).toContain(
+ '/extra'
+ )
+ expect(manager.getApp().notifyOnError).toBe(false)
+ expect(mockWriteFileAtomic).toHaveBeenCalledOnce()
+ expect(onChange).toHaveBeenCalledOnce()
+ })
+
+ it('publishes neither aggregate on writer failure and recovers without letting generic settings overwrite preferences', async () => {
+ await manager.mutateDirectoryPreferences({
+ action: 'addFavorite',
+ path: '/keep',
+ })
+ const before = structuredClone(manager.getApp())
+ onChange.mockClear()
+ mockWriteFileAtomic.mockRejectedValueOnce(new Error('disk full'))
+ await expect(
+ manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnError: false },
+ directories: { ...empty, removeFavorites: ['/keep'] },
+ })
+ ).rejects.toThrow('disk full')
+ expect(manager.getApp()).toEqual(before)
+ expect(onChange).not.toHaveBeenCalled()
+ await manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnError: false },
+ directories: { ...empty, addFavorites: ['/new'] },
+ })
+ await manager.update({
+ app: { directoryPreferences: 'malformed' as never, theme: 'dark' },
+ })
+ expect(manager.getApp()).toMatchObject({
+ notifyOnError: false,
+ theme: 'dark',
+ directoryPreferences: { favorites: ['/keep', '/new'], recent: [] },
+ })
+ })
+
+ it('fences earlier requests without writing or publishing an empty General transaction', async () => {
+ const revision = manager.getGeneralSettingsSnapshot().revision
+ expect(
+ await manager.saveGeneralSettings({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: {},
+ directories: empty,
+ })
+ ).toMatchObject({
+ ok: true,
+ value: { directoryPreferences: { favorites: [], recent: [] } },
+ })
+ expect(manager.getGeneralSettingsSnapshot().revision).not.toBe(revision)
+ expect(
+ await manager.saveGeneralSettings({
+ expectedRevision: revision,
+ app: { notifyOnError: false },
+ directories: empty,
+ })
+ ).toMatchObject({ ok: false, error: { code: 'conflict' } })
+ expect(manager.getApp().notifyOnError).toBe(true)
+ expect(mockWriteFileAtomic).not.toHaveBeenCalled()
+ expect(onChange).not.toHaveBeenCalled()
+ })
+ })
+
describe('load', () => {
it.each([
['darwin', 64_000, 512_000],
diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.ts
index d9f0d1ee..635c7221 100644
--- a/src/core/settings/settings-manager.ts
+++ b/src/core/settings/settings-manager.ts
@@ -13,6 +13,21 @@ import {
DEFAULT_BRIDGE_SETTINGS,
} from '@shared/schemas/bridge-settings'
import type { ByteUnitSystem } from '@shared/schemas/byte-unit-system'
+import {
+ DIRECTORY_FAVORITES_LIMIT,
+ DIRECTORY_RECENT_LIMIT,
+ type DirectoryPreferencesResult,
+ DirectoryPreferencesSchema,
+ type MutateDirectoryPreferencesRequest,
+ MutateDirectoryPreferencesRequestSchema,
+} from '@shared/schemas/directory-preferences'
+import {
+ GeneralSettingsAppSchema,
+ type GeneralSettingsResult,
+ type GeneralSettingsSnapshot,
+ type SaveGeneralSettingsRequest,
+ SaveGeneralSettingsRequestSchema,
+} from '@shared/schemas/general-settings'
import {
DEFAULT_PROXY_SETTINGS,
proxySettingsSchema,
@@ -154,6 +169,7 @@ export interface SettingsManagerOptions {
export class SettingsManager {
private settings: AppSettings
+ private generalSettingsRevision = randomUUID()
private readonly defaultSaveDir: string
private readonly isLegacyDefaultSaveDir?: (value: string) => boolean
private readonly liquidGlassEffectDefault: boolean
@@ -265,6 +281,22 @@ export class SettingsManager {
return this.settings.engine
}
+ getGeneralSettingsSnapshot(): GeneralSettingsSnapshot {
+ return {
+ revision: this.generalSettingsRevision,
+ app: GeneralSettingsAppSchema.parse(this.settings.app),
+ directoryPreferences: structuredClone(
+ this.settings.app.directoryPreferences
+ ),
+ }
+ }
+
+ private commitSettings(old: AppSettings, next: AppSettings): void {
+ this.settings = next
+ this.generalSettingsRevision = randomUUID()
+ this.onChange?.(old, next)
+ }
+
getApp(): MotrixAppSettings {
return this.settings.app
}
@@ -299,8 +331,7 @@ export class SettingsManager {
next.app = validateAppSettings({ ...next.app, language })
await this.saveSettings(next)
- this.settings = next
- this.onChange?.(old, this.settings)
+ this.commitSettings(old, next)
return {
saved: true,
@@ -325,8 +356,7 @@ export class SettingsManager {
})
await this.saveSettings(next)
- this.settings = next
- this.onChange?.(old, this.settings)
+ this.commitSettings(old, next)
return {
saved: true,
@@ -361,6 +391,105 @@ export class SettingsManager {
return this.enqueueMutation(() => this.persistUpdate(patch))
}
+ /** Compute against the committed snapshot only after earlier writes settle. */
+ async mutateDirectoryPreferences(
+ raw: MutateDirectoryPreferencesRequest
+ ): Promise<DirectoryPreferencesResult> {
+ const parsed = MutateDirectoryPreferencesRequestSchema.safeParse(raw)
+ if (!parsed.success) return { ok: false, error: { code: 'invalidPath' } }
+ const action = parsed.data
+ return this.enqueueMutation(async () => {
+ const old = structuredClone(this.settings)
+ const next = structuredClone(this.settings)
+ const preferences = next.app.directoryPreferences
+ switch (action.action) {
+ case 'addFavorite':
+ if (!preferences.favorites.includes(action.path)) {
+ if (preferences.favorites.length >= DIRECTORY_FAVORITES_LIMIT) {
+ return { ok: false, error: { code: 'limitReached' } }
+ }
+ preferences.favorites.push(action.path)
+ }
+ break
+ case 'recordRecent':
+ preferences.recent = [
+ action.path,
+ ...preferences.recent.filter((entry) => entry !== action.path),
+ ].slice(0, DIRECTORY_RECENT_LIMIT)
+ break
+ case 'removeFavorite':
+ preferences.favorites = preferences.favorites.filter(
+ (entry) => !action.paths.includes(entry)
+ )
+ break
+ case 'removeRecent':
+ preferences.recent = preferences.recent.filter(
+ (entry) => !action.paths.includes(entry)
+ )
+ break
+ case 'clearRecent':
+ preferences.recent = []
+ break
+ }
+ if (
+ JSON.stringify(old.app.directoryPreferences) !==
+ JSON.stringify(preferences)
+ ) {
+ await this.saveSettings(next)
+ this.commitSettings(old, next)
+ }
+ return { ok: true, value: DirectoryPreferencesSchema.parse(preferences) }
+ })
+ }
+
+ /** General fields and baseline-relative directory edits share one commit. */
+ async saveGeneralSettings(
+ raw: SaveGeneralSettingsRequest
+ ): Promise<GeneralSettingsResult> {
+ const parsed = SaveGeneralSettingsRequestSchema.safeParse(raw)
+ if (!parsed.success) return { ok: false, error: { code: 'invalidPath' } }
+ const { app, directories, expectedRevision } = parsed.data
+ return this.enqueueMutation(async () => {
+ if (expectedRevision !== this.generalSettingsRevision) {
+ return {
+ ok: false,
+ error: { code: 'conflict' },
+ snapshot: this.getGeneralSettingsSnapshot(),
+ }
+ }
+ const old = structuredClone(this.settings)
+ const next = structuredClone(this.settings)
+ const preferences = next.app.directoryPreferences
+ preferences.favorites = [
+ ...new Set([
+ ...preferences.favorites.filter(
+ (path) => !directories.removeFavorites.includes(path)
+ ),
+ ...directories.addFavorites,
+ ]),
+ ]
+ if (preferences.favorites.length > DIRECTORY_FAVORITES_LIMIT) {
+ return { ok: false, error: { code: 'limitReached' } }
+ }
+ preferences.recent = preferences.recent.filter(
+ (path) => !directories.removeRecent.includes(path)
+ )
+ next.app = validateAppSettings({
+ ...next.app,
+ ...app,
+ directoryPreferences: preferences,
+ })
+ if (JSON.stringify(old.app) !== JSON.stringify(next.app)) {
+ await this.saveSettings(next)
+ this.commitSettings(old, next)
+ } else {
+ // An empty accepted Save fences a previous request still validating.
+ this.generalSettingsRevision = randomUUID()
+ }
+ return { ok: true, value: this.getGeneralSettingsSnapshot() }
+ })
+ }
+
/**
* Remove the durable configuration namespace owned by an uninstalled
* plugin. A normal partial update cannot express deletion because plugin
@@ -378,8 +507,7 @@ export class SettingsManager {
const next = structuredClone(this.settings)
delete next.plugins[pluginId]
await this.saveSettings(next)
- this.settings = next
- this.onChange?.(old, this.settings)
+ this.commitSettings(old, next)
return {
saved: true,
requiresRestart: false,
@@ -434,7 +562,12 @@ export class SettingsManager {
// Merge app settings
if (partial.app) {
- const merged = { ...next.app, ...partial.app }
+ const merged = {
+ ...next.app,
+ ...partial.app,
+ // Only dedicated queue actions can change this aggregate.
+ directoryPreferences: next.app.directoryPreferences,
+ }
const validated = validateAppSettings(merged as MotrixAppSettings)
// Detect app-namespace restart-required key changes
@@ -557,8 +690,7 @@ export class SettingsManager {
await this.saveSettings(next)
- this.settings = next
- this.onChange?.(old, this.settings)
+ this.commitSettings(old, next)
return {
saved: true,
diff --git a/src/main/index.ts b/src/main/index.ts
index 7b485ec8..1e848bd3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -348,6 +348,15 @@ const settingsManager = new SettingsManager(settingsPath, {
byteUnitSystem: updated.app.byteUnitSystem,
})
}
+ if (
+ JSON.stringify(old.app.directoryPreferences) !==
+ JSON.stringify(updated.app.directoryPreferences)
+ ) {
+ eventBus.emit(
+ Events.DirectoryPreferencesChanged,
+ structuredClone(updated.app.directoryPreferences)
+ )
+ }
if (old.app.reduceMotion !== updated.app.reduceMotion) {
eventBus.emit(Events.ReducedMotionChanged, {
reduceMotion: updated.app.reduceMotion,
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index d4831f5b..17c83d49 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -1,9 +1,10 @@
-import { access, mkdir, mkdtemp, rm } from 'node:fs/promises'
+import { access, mkdir, mkdtemp, realpath, rm, symlink } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'
import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'
import { AppliedDownloadProxyPolicy } from '@core/proxy/applied-download-proxy-policy'
+import { SettingsManager } from '@core/settings/settings-manager'
import { EXTERNAL_URLS } from '@shared/external-urls'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
@@ -36,6 +37,11 @@ const { reconcileAppImageIntegrationFromSettingsMock } = vi.hoisted(() => ({
),
}))
+const syncAutoLaunchMock = vi.hoisted(() => vi.fn())
+vi.mock('../platform/auto-launch', () => ({
+ syncAutoLaunch: syncAutoLaunchMock,
+}))
+
vi.mock('../platform/appimage-integration-host', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
reconcileAppImageIntegrationFromSettings:
@@ -980,7 +986,7 @@ describe('buildCommandHandlers', () => {
fromWebContentsMock.mockReturnValue(parent)
showOpenDialogMock
.mockResolvedValueOnce({ canceled: true, filePaths: [] })
- .mockResolvedValueOnce({ canceled: false, filePaths: ['/downloads'] })
+ .mockResolvedValueOnce({ canceled: false, filePaths: [tmpdir()] })
// @ts-expect-error partial ctx
const handlers = buildCommandHandlers(fakeCtx())
@@ -989,7 +995,7 @@ describe('buildCommandHandlers', () => {
).resolves.toBeNull()
await expect(
handlers[Commands.PickSaveDir]?.(sender, { defaultPath: '/tmp' })
- ).resolves.toEqual({ path: '/downloads' })
+ ).resolves.toEqual({ path: await realpath(tmpdir()) })
expect(showOpenDialogMock).toHaveBeenCalledWith(parent, {
properties: ['openDirectory'],
defaultPath: '/tmp',
@@ -1023,8 +1029,8 @@ describe('buildCommandHandlers', () => {
).resolves.toBeNull()
expect(showOpenDialogMock).toHaveBeenCalledOnce()
- resolvePick({ canceled: false, filePaths: ['/picked'] })
- await expect(first).resolves.toEqual({ path: '/picked' })
+ resolvePick({ canceled: false, filePaths: [tmpdir()] })
+ await expect(first).resolves.toEqual({ path: await realpath(tmpdir()) })
showOpenDialogMock.mockResolvedValueOnce({ canceled: true, filePaths: [] })
await expect(
@@ -1298,6 +1304,160 @@ describe('SetTaskBtTracker handler', () => {
})
describe('Commands.UpdateSettings', () => {
+ it('returns the canonical native directory identity for General favorite drafts', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-native-directory-'))
+ try {
+ const target = path.join(root, 'target')
+ const alias = path.join(root, 'alias')
+ await mkdir(target)
+ await symlink(target, alias)
+ fromWebContentsMock.mockReturnValue(null)
+ showOpenDialogMock.mockResolvedValueOnce({
+ canceled: false,
+ filePaths: [alias],
+ })
+ const pick = buildCommandHandlers(fakeCtx() as unknown as CommandContext)[
+ Commands.PickSaveDir
+ ]
+ expect(await pick?.({ id: 423 }, {})).toEqual({
+ path: await realpath(target),
+ })
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('atomically saves General fields and directories and applies the submitted Desktop runtime fields', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-app-general-'))
+ try {
+ const manager = new SettingsManager(path.join(root, 'settings.json'))
+ await manager.load()
+ const ctx = { ...fakeCtx(), settingsManager: manager }
+ const save = buildCommandHandlers(ctx as unknown as CommandContext)[
+ Commands.SaveGeneralSettings
+ ]
+ const canonical = await realpath(root)
+ expect(
+ await save?.({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: {
+ defaultSaveDir: root,
+ launchAtStartup: true,
+ notifyOnComplete: false,
+ },
+ directories: {
+ addFavorites: [canonical],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ })
+ ).toMatchObject({
+ ok: true,
+ value: { directoryPreferences: { favorites: [canonical], recent: [] } },
+ })
+ expect(manager.getApp()).toMatchObject({
+ defaultSaveDir: canonical,
+ launchAtStartup: true,
+ notifyOnComplete: false,
+ })
+ expect(syncAutoLaunchMock).toHaveBeenCalledWith(true)
+ expect(
+ ctx.supervisor.applyDefaultSaveDir
+ ).toHaveBeenCalledExactlyOnceWith(canonical)
+ ctx.supervisor.applyDefaultSaveDir.mockClear()
+ syncAutoLaunchMock.mockClear()
+ const previousRevision = manager.getGeneralSettingsSnapshot().revision
+ expect(
+ await save?.({
+ expectedRevision: previousRevision,
+ app: { showMainWindowAtLogin: true },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ })
+ ).toMatchObject({
+ ok: true,
+ value: { app: { showMainWindowAtLogin: true } },
+ })
+ expect(manager.getApp().showMainWindowAtLogin).toBe(true)
+ expect(syncAutoLaunchMock).toHaveBeenCalledExactlyOnceWith(true)
+ expect(ctx.supervisor.applyDefaultSaveDir).not.toHaveBeenCalled()
+ syncAutoLaunchMock.mockClear()
+ expect(
+ await save?.({
+ expectedRevision: previousRevision,
+ app: { showMainWindowAtLogin: false },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ })
+ ).toMatchObject({
+ ok: false,
+ error: { code: 'conflict' },
+ snapshot: { app: { showMainWindowAtLogin: true } },
+ })
+ expect(syncAutoLaunchMock).not.toHaveBeenCalled()
+ const before = structuredClone(manager.getApp())
+ expect(
+ await save?.({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: {
+ defaultSaveDir: path.join(root, 'missing'),
+ launchAtStartup: false,
+ notifyOnComplete: true,
+ },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [canonical],
+ removeRecent: [],
+ },
+ })
+ ).toEqual({ ok: false, error: { code: 'notFound' } })
+ expect(manager.getApp()).toEqual(before)
+ expect(ctx.supervisor.applyDefaultSaveDir).not.toHaveBeenCalled()
+ expect(syncAutoLaunchMock).not.toHaveBeenCalled()
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('keeps queued preferences through stale and malformed App updates using the real Desktop handler', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-app-preferences-'))
+ try {
+ const manager = new SettingsManager(path.join(root, 'settings.json'))
+ await manager.load()
+ const staleApp = manager.getApp()
+ const handlers = buildCommandHandlers({
+ ...fakeCtx(),
+ settingsManager: manager,
+ } as unknown as CommandContext)
+ expect(
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'addFavorite',
+ path: root,
+ })
+ ).toMatchObject({ ok: true })
+ const stored = manager.getApp().directoryPreferences
+ await handlers[Commands.UpdateSettings]?.({
+ app: { ...staleApp, theme: 'dark' },
+ })
+ await handlers[Commands.UpdateSettings]?.({
+ app: { directoryPreferences: 'invalid', notifyOnComplete: false },
+ })
+ expect(manager.getApp()).toMatchObject({
+ theme: 'dark',
+ notifyOnComplete: false,
+ directoryPreferences: stored,
+ })
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
// Namespaces come in as one named object, not as trailing positional
// parameters: five defaulted `object` slots in a row means a call site can
// silently put its override in the wrong namespace and still type-check.
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index b0b14e0f..d39ef7da 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -1,3 +1,4 @@
+import { realpath } from 'node:fs/promises'
import path from 'node:path'
import type { AdaptedMux } from '@core/bridge-receiver/submit-download-adapter'
import type { DnsFallbackConsumer } from '@core/engine/aria2/dns-fallback'
@@ -40,6 +41,8 @@ import {
} from '@core/proxy/applied-download-proxy-policy'
import type { MotrixDatabase } from '@core/session/motrix-database'
import type { SessionManager } from '@core/session/session-manager'
+import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'
+import { createSaveGeneralSettingsHandler } from '@core/settings/general-settings'
import type { SettingsManager } from '@core/settings/settings-manager'
import {
clearStoppedTasks,
@@ -903,6 +906,28 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return createAndPersist(request as Parameters<typeof handleCreateTask>[0])
},
+ [Commands.MutateDirectoryPreferences]:
+ createDirectoryPreferencesHandlers(settingsManager).mutate,
+
+ [Commands.SaveGeneralSettings]: createSaveGeneralSettingsHandler(
+ settingsManager,
+ {
+ applySavedApp: async (patch) => {
+ if (
+ patch.launchAtStartup !== undefined ||
+ patch.showMainWindowAtLogin !== undefined
+ ) {
+ syncAutoLaunch(settingsManager.getApp().launchAtStartup)
+ }
+ if (patch.defaultSaveDir !== undefined) {
+ await supervisor.applyDefaultSaveDir(
+ settingsManager.getApp().defaultSaveDir
+ )
+ }
+ },
+ }
+ ),
+
[Commands.UpdateSettings]: async (partial: unknown) => {
const oldFull = settingsManager.get()
@@ -1194,7 +1219,8 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
if (result.canceled || result.filePaths.length === 0) {
return null
}
- return { path: result.filePaths[0] }
+ const selected = await realpath(result.filePaths[0]).catch(() => null)
+ return selected ? { path: selected } : null
} finally {
saveDirPickersInFlight.delete(sender)
}
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index 9525bf56..fa077df6 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -12,6 +12,7 @@ import {
EngineRecoveryRecommendation,
EngineState,
} from '@shared/types/engine'
+import { generalSettingsSnapshot } from '@test-utils/general-settings'
import { makeTaskInspectorActivitySnapshot } from '@test-utils/task-inspector-activity'
import { ipcMain } from 'electron'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -145,6 +146,47 @@ function serializeCommandGraphRecords(): string {
}
describe('buildQueryHandlers', () => {
+ it('returns one General draft snapshot and validates before reading it', async () => {
+ const snapshot = generalSettingsSnapshot({
+ favorites: ['/saved'],
+ recent: [],
+ })
+ const getGeneralSettingsSnapshot = vi.fn(() => snapshot)
+ const handlers = buildQueryHandlers({
+ settingsManager: { getGeneralSettingsSnapshot },
+ } as unknown as QueryContext)
+ expect(
+ await handlers[Queries.GetGeneralSettingsDraft]?.({ extra: true })
+ ).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ expect(getGeneralSettingsSnapshot).not.toHaveBeenCalled()
+ expect(await handlers[Queries.GetGeneralSettingsDraft]?.({})).toEqual({
+ ok: true,
+ value: snapshot,
+ })
+ expect(getGeneralSettingsSnapshot).toHaveBeenCalledOnce()
+ })
+
+ it('returns only raw directory preferences and rejects invalid requests before reading settings', async () => {
+ const preferences = { favorites: ['/saved/missing'], recent: ['/previous'] }
+ const getApp = vi.fn(() => ({
+ directoryPreferences: preferences,
+ private: 'not forwarded',
+ }))
+ const handlers = buildQueryHandlers({
+ settingsManager: { getApp },
+ } as unknown as QueryContext)
+ expect(
+ await handlers[Queries.GetDirectoryPreferences]?.({ extra: true })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(getApp).not.toHaveBeenCalled()
+ const result = await handlers[Queries.GetDirectoryPreferences]?.({})
+ expect(result).toEqual({ ok: true, value: preferences })
+ expect(handlers[Queries.ListServerDirectoryLocations]).toBeUndefined()
+ })
+
it('reads the OS proxy through an isolated system-mode session', async () => {
ipcMocks.systemProxySession.setProxy.mockResolvedValue(undefined)
ipcMocks.systemProxySession.forceReloadProxyConfig.mockResolvedValue(
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index e303d58b..3b84f8a9 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -18,6 +18,8 @@ import {
import type { RegistryClient } from '@core/plugin/registry/registry-client'
import { parseElectronProxyChain } from '@core/proxy/system-proxy'
import type { MotrixDatabase } from '@core/session/motrix-database'
+import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'
+import { createGetGeneralSettingsDraftHandler } from '@core/settings/general-settings'
import type { SettingsManager } from '@core/settings/settings-manager'
import type { SpeedLimitController } from '@core/speed-limit/speed-limit-controller'
import type {
@@ -161,6 +163,11 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
return taskInspectorActivityRuntime.snapshot(params)
},
+ [Queries.GetGeneralSettingsDraft]:
+ createGetGeneralSettingsDraftHandler(settingsManager),
+ [Queries.GetDirectoryPreferences]:
+ createDirectoryPreferencesHandlers(settingsManager).get,
+
[Queries.GetSettings]: async () => {
return settingsManager.get()
},
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 6c3cff25..da5d8f31 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
@@ -1,5 +1,4 @@
import { AddTaskForm } from '@renderer/components/add-task/add-task-form'
-import { Button } from '@renderer/components/ui/button'
import {
Dialog,
DialogClose,
@@ -7,15 +6,14 @@ import {
DialogHeader,
DialogTitle,
} from '@renderer/components/ui/dialog'
-import { Input } from '@renderer/components/ui/input'
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 { showMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
import { transport } from '@renderer/lib/transport'
import { PlatformServicesProvider } from '@renderer/platform/services'
import {
__setWebCloseHandler,
- __webPathPickerBus,
webServices,
} from '@renderer/platform/web-services'
import {
@@ -23,7 +21,6 @@ import {
ADD_TASK_MAX_HEIGHT,
} from '@shared/constants/add-task'
import { Events } from '@shared/protocol/events'
-import { Queries } from '@shared/protocol/queries'
import {
magnetFileSelectionPayloadSchema,
magnetFileSelectionSettledPayloadSchema,
@@ -31,7 +28,7 @@ import {
setAddTaskModeEventPayloadSchema,
urlParamsToFormDefaults,
} from '@shared/schemas/add-task'
-import { useCallback, useEffect, useId, useRef, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router'
import { useAdaptiveDialogHeight } from './use-adaptive-dialog-height'
@@ -213,103 +210,7 @@ export function AddTaskDialogHost() {
}
close={() => setDiscard(false)}
/>
- <WebPathPickerDialog />
+ <WebDirectoryPickerDialog />
</>
)
}
-
-function WebPathPickerDialog() {
- const { t } = useTranslation()
- const customInputId = useId()
- const [open, setOpen] = useState(false)
- const [defaultPath, setDefaultPath] = useState<string | undefined>()
- const [allowed, setAllowed] = useState<{ path: string; label?: string }[]>([])
- const [allowCustom, setAllowCustom] = useState(true)
- const [custom, setCustom] = useState('')
- const [selected, setSelected] = useState('')
-
- useEffect(() => {
- const unsubscribe = __webPathPickerBus.subscribe(async (req) => {
- setDefaultPath(req.defaultPath)
- setCustom('')
- try {
- const res = (await transport.invoke(Queries.ListAllowedSaveDirs)) as {
- paths: { path: string; label?: string }[]
- defaultPath: string
- allowCustom: boolean
- }
- setAllowed(res.paths)
- setAllowCustom(res.allowCustom)
- setSelected(req.defaultPath ?? res.defaultPath ?? '')
- } catch {
- setAllowed([])
- setAllowCustom(true)
- setSelected(req.defaultPath ?? '')
- }
- setOpen(true)
- })
- return () => unsubscribe()
- }, [])
-
- const confirm = (path: string | null) => {
- setOpen(false)
- __webPathPickerBus.resolve(path)
- }
-
- return (
- <Dialog open={open} onOpenChange={(v) => !v && confirm(null)}>
- <DialogContent className="max-w-[400px]">
- <DialogHeader>
- <DialogTitle>{t('task.add.pickPathTitle')}</DialogTitle>
- </DialogHeader>
- <div className="space-y-3">
- {allowed.length > 0 && (
- <div className="space-y-1">
- {allowed.map((p) => (
- <label key={p.path} className="flex items-center gap-2 text-sm">
- <input
- type="radio"
- checked={selected === p.path}
- onChange={() => setSelected(p.path)}
- />
- <span dir="ltr">{p.label ?? p.path}</span>
- </label>
- ))}
- </div>
- )}
- {allowCustom && (
- <div className="space-y-1">
- <label
- htmlFor={customInputId}
- className="text-xs text-muted-foreground"
- >
- {t('task.add.pickPathCustom')}
- </label>
- <Input
- id={customInputId}
- value={custom}
- onChange={(e) => {
- setCustom(e.target.value)
- setSelected(e.target.value)
- }}
- placeholder={defaultPath ?? '/downloads'}
- dir="ltr"
- />
- </div>
- )}
- <div className="flex justify-end gap-2">
- <Button variant="outline" onClick={() => confirm(null)}>
- {t('common.cancel')}
- </Button>
- <Button
- onClick={() => confirm(selected || null)}
- disabled={!selected}
- >
- {t('common.confirm')}
- </Button>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- )
-}
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 6dc48103..b174bda7 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
@@ -57,17 +57,15 @@ export function useAdaptiveDialogHeight(
const header = dialog.querySelector<HTMLElement>(
'[data-slot="dialog-header"]'
)
- const body = dialog.querySelector<HTMLElement>(
- '[data-slot="add-task-form-body"]'
- )
+ const content = dialog.querySelector<HTMLElement>('[data-adaptive-content]')
const footer = dialog.querySelector<HTMLElement>(
'[data-slot="add-task-form-footer"]'
)
- if (!header || !body || !footer) return
+ if (!header || !content || !footer) return
const naturalHeight =
header.getBoundingClientRect().height +
- body.scrollHeight +
+ content.scrollHeight +
footer.getBoundingClientRect().height
const nextHeight = clampDialogHeight({
collapsedHeight,
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 a13d800e..8efeb1f9 100644
--- a/src/renderer/components/add-task/add-task-form.test.tsx
+++ b/src/renderer/components/add-task/add-task-form.test.tsx
@@ -9,9 +9,28 @@ import { PlatformServicesProvider } from '@renderer/platform/services'
import { Events } from '@shared/protocol/events'
import { AddTaskForm } from './add-task-form'
+const { recordRecentMock, invokeMock } = vi.hoisted(() => ({
+ recordRecentMock: vi.fn().mockResolvedValue(undefined),
+ invokeMock: vi.fn().mockResolvedValue({ gid: 'test-gid' }),
+}))
+vi.mock('@renderer/lib/directory-preferences', () => ({
+ recordRecentDirectory: (...args: unknown[]) => recordRecentMock(...args),
+}))
+vi.mock('@renderer/components/desktop-kit/directory-history-menu', () => ({
+ DirectoryHistoryMenu: ({
+ onSelect,
+ }: {
+ onSelect: (path: string) => void
+ }) => (
+ <button type="button" onClick={() => onSelect('/later')}>
+ History
+ </button>
+ ),
+}))
+
vi.mock('@renderer/lib/transport', () => ({
transport: {
- invoke: vi.fn().mockResolvedValue({ gid: 'test-gid' }),
+ invoke: invokeMock,
on: vi.fn(),
off: vi.fn(),
},
@@ -45,7 +64,10 @@ function renderForm(props = {}, services: PlatformServices = mockServices) {
}
describe('AddTaskForm', () => {
- afterEach(() => vi.clearAllMocks())
+ afterEach(() => {
+ vi.clearAllMocks()
+ invokeMock.mockResolvedValue({ gid: 'test-gid' })
+ })
it('renders links tab by default', () => {
renderForm()
@@ -58,7 +80,11 @@ describe('AddTaskForm', () => {
expect(content).toBeInTheDocument()
expect(content).not.toHaveClass('overflow-y-auto')
- expect(content?.parentElement).toHaveClass('overflow-y-auto')
+ expect(content?.parentElement).toHaveAttribute(
+ 'data-slot',
+ 'scroll-area-viewport'
+ )
+ expect(content?.parentElement).toHaveAttribute('tabindex', '-1')
})
it('keeps the footer inside an in-page dialog', () => {
@@ -295,8 +321,74 @@ describe('AddTaskForm', () => {
)
)
expect(onSubmitSuccess).toHaveBeenCalledWith('test-gid')
+ expect(recordRecentMock).toHaveBeenCalledWith('/d')
})
+ it.each([
+ ['electron', 'created'],
+ ['electron', 'reused'],
+ ['electron', 'rechecked'],
+ ['web', 'created'],
+ ['web', 'reused'],
+ ['web', 'rechecked'],
+ ] as const)(
+ 'records the accepted %s %s request snapshot even after a field change',
+ async (kind, outcome) => {
+ let accept!: (value: unknown) => void
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === 'query:getSettings') return { app: {} }
+ if (channel === 'command:createTask')
+ return new Promise((resolve) => {
+ accept = resolve
+ })
+ return {}
+ })
+ const success = vi.fn()
+ renderForm(
+ {
+ onSubmitSuccess: success,
+ defaultValues: {
+ tab: 'links',
+ urls: 'https://a/1',
+ saveDir: '/submitted ',
+ },
+ },
+ { ...mockServices, kind }
+ )
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Download' }))
+ await waitFor(() => expect(accept).toBeDefined())
+ await user.click(screen.getByRole('button', { name: 'History' }))
+ expect(recordRecentMock).not.toHaveBeenCalled()
+ await act(async () =>
+ accept({ outcome, gid: 'accepted', taskId: 'accepted' })
+ )
+ expect(success).toHaveBeenCalledWith('accepted')
+ expect(recordRecentMock.mock.calls).toEqual([['/submitted ']])
+ }
+ )
+
+ it.each(['electron', 'web'] as const)(
+ 'records %s picker confirmation but not history-only selection or parent cancellation',
+ async (kind) => {
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockResolvedValue({ app: {} })
+ const onCancel = vi.fn()
+ const pick = vi.fn().mockResolvedValue('/selected ')
+ renderForm({ onCancel }, { ...mockServices, kind, pickSaveDir: pick })
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'History' }))
+ expect(recordRecentMock).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'Change directory' }))
+ expect(pick).toHaveBeenCalledWith('/later')
+ expect(recordRecentMock.mock.calls).toEqual([['/selected ']])
+ await user.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(onCancel).toHaveBeenCalledOnce()
+ expect(recordRecentMock.mock.calls).toEqual([['/selected ']])
+ }
+ )
+
it('submits one createTask per link line', async () => {
const onSubmitSuccess = vi.fn()
const user = userEvent.setup()
@@ -321,159 +413,181 @@ describe('AddTaskForm', () => {
)
expect(onSubmitSuccess).toHaveBeenCalledWith('test-gid')
expect(mockServices.notify).toHaveBeenCalledWith('info', 'task.add.created')
+ expect(recordRecentMock.mock.calls).toEqual([['/d'], ['/d']])
})
- it('parses and creates a local multi-torrent batch without shell RPCs', async () => {
- const onSubmitSuccess = vi.fn()
- const user = userEvent.setup()
- const { transport } = await import('@renderer/lib/transport')
- vi.mocked(readTorrentFile).mockImplementation(async (file) => {
- const isAlpha = file.name.startsWith('alpha')
- return {
- name: file.name,
- base64: isAlpha ? 'YWxwaGE=' : 'YmV0YQ==',
- meta: {
- name: isAlpha ? 'alpha.bin' : 'beta.bin',
- infoHash: isAlpha ? 'a'.repeat(40) : 'b'.repeat(40),
- totalSize: 1,
- comment: '',
- isPrivate: false,
- files: [
- {
- index: 0,
- path: isAlpha ? 'alpha.bin' : 'beta.bin',
- size: 1,
- extension: 'bin',
- },
- ],
- },
- }
- })
- vi.mocked(transport.invoke).mockImplementation(async (channel, request) => {
- if (channel === 'query:getSettings') {
- return { app: { defaultSaveDir: '/d' } }
- }
- if (channel === 'command:createTask') {
- const base64 = (request as { payload?: { base64?: string } }).payload
- ?.base64
+ it.each(['created', 'conflict', 'failure'] as const)(
+ 'records accepted local batch paths when its second item is %s',
+ async (secondOutcome) => {
+ const onSubmitSuccess = vi.fn()
+ const user = userEvent.setup()
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(readTorrentFile).mockImplementation(async (file) => {
+ const isAlpha = file.name.startsWith('alpha')
return {
- outcome: 'created',
- gid: base64 === 'YWxwaGE=' ? 'alpha-gid' : 'beta-gid',
- taskId: base64 === 'YWxwaGE=' ? 'alpha-task' : 'beta-task',
+ name: file.name,
+ base64: isAlpha ? 'YWxwaGE=' : 'YmV0YQ==',
+ meta: {
+ name: isAlpha ? 'alpha.bin' : 'beta.bin',
+ infoHash: isAlpha ? 'a'.repeat(40) : 'b'.repeat(40),
+ totalSize: 1,
+ comment: '',
+ isPrivate: false,
+ files: [
+ {
+ index: 0,
+ path: isAlpha ? 'alpha.bin' : 'beta.bin',
+ size: 1,
+ extension: 'bin',
+ },
+ ],
+ },
}
- }
- return {}
- })
- const webServices = { ...mockServices, kind: 'web' as const }
- const { container } = renderForm(
- {
- onSubmitSuccess,
- defaultValues: { tab: 'torrent', saveDir: '/d' },
- },
- webServices
- )
- const input =
- container.querySelector<HTMLInputElement>('input[type="file"]')
- expect(input).toHaveAttribute('multiple')
-
- fireEvent.change(input as HTMLInputElement, {
- target: {
- files: [
- new File(['alpha'], 'alpha.torrent'),
- new File(['beta'], 'beta.torrent'),
- ],
- },
- })
-
- expect(await screen.findByText('Torrent 1 of 2')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'Download All (2)' }))
-
- await waitFor(() =>
- expect(onSubmitSuccess).toHaveBeenCalledWith('alpha-task')
- )
- expect(transport.invoke).toHaveBeenCalledWith(
- 'command:createTask',
- expect.objectContaining({
- payload: { kind: 'torrent-base64', base64: 'YWxwaGE=' },
})
- )
- expect(transport.invoke).toHaveBeenCalledWith(
- 'command:createTask',
- expect.objectContaining({
- payload: { kind: 'torrent-base64', base64: 'YmV0YQ==' },
- })
- )
- expect(transport.invoke).not.toHaveBeenCalledWith(
- 'command:downloadAllTorrents'
- )
- })
-
- it('passes the current torrent form options to the App batch command', async () => {
- const onSubmitSuccess = vi.fn()
- const user = userEvent.setup()
- const { transport } = await import('@renderer/lib/transport')
- vi.mocked(transport.invoke).mockImplementation(async (channel) => {
- if (channel === 'query:getSettings') {
- return { app: { defaultSaveDir: '/default' } }
- }
- if (channel === 'command:downloadAllTorrents') {
- return {
- total: 2,
- succeeded: 2,
- failed: 0,
- firstTaskId: 'first-task',
+ vi.mocked(transport.invoke).mockImplementation(
+ async (channel, request) => {
+ if (channel === 'query:getSettings') {
+ return { app: { defaultSaveDir: '/d' } }
+ }
+ if (channel === 'command:createTask') {
+ const base64 = (request as { payload?: { base64?: string } })
+ .payload?.base64
+ if (base64 === 'YmV0YQ==' && secondOutcome === 'failure')
+ throw new Error('test rejection')
+ if (base64 === 'YmV0YQ==' && secondOutcome === 'conflict')
+ return { outcome: 'conflict' }
+ return {
+ outcome: 'created',
+ gid: base64 === 'YWxwaGE=' ? 'alpha-gid' : 'beta-gid',
+ taskId: base64 === 'YWxwaGE=' ? 'alpha-task' : 'beta-task',
+ }
+ }
+ return {}
}
- }
- return {}
- })
- renderForm({
- subscribeEvents: true,
- onSubmitSuccess,
- defaultValues: {
- tab: 'torrent',
- source: 'file',
- base64: 'dG9ycmVudA==',
- torrentMeta: {
- name: 'current.bin',
- infoHash: 'a'.repeat(40),
- totalSize: 2,
+ )
+ const webServices = { ...mockServices, kind: 'web' as const }
+ const { container } = renderForm(
+ {
+ onSubmitSuccess,
+ defaultValues: { tab: 'torrent', saveDir: '/d' },
+ },
+ webServices
+ )
+ const input =
+ container.querySelector<HTMLInputElement>('input[type="file"]')
+ expect(input).toHaveAttribute('multiple')
+
+ fireEvent.change(input as HTMLInputElement, {
+ target: {
files: [
- { index: 0, path: 'skip.bin', size: 1, extension: '.bin' },
- { index: 1, path: 'keep.bin', size: 1, extension: '.bin' },
+ new File(['alpha'], 'alpha.torrent'),
+ new File(['beta'], 'beta.torrent'),
],
},
- selectedFiles: [1],
- saveDir: '/custom',
- dlLimit: 2048,
- ulLimit: 1024,
- seedRatio: 1.5,
- },
- })
+ })
- const queueListener = vi
- .mocked(transport.on)
- .mock.calls.find(
- ([channel]) => channel === Events.TorrentQueueSizeChanged
- )?.[1]
- act(() => queueListener?.({ queueTotal: 2 }))
- await user.click(
- await screen.findByRole('button', { name: 'Download All (2)' })
- )
+ expect(await screen.findByText('Torrent 1 of 2')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Download All (2)' }))
- await waitFor(() =>
+ await waitFor(() =>
+ expect(onSubmitSuccess).toHaveBeenCalledWith('alpha-task')
+ )
expect(transport.invoke).toHaveBeenCalledWith(
- 'command:downloadAllTorrents',
- {
+ 'command:createTask',
+ expect.objectContaining({
+ payload: { kind: 'torrent-base64', base64: 'YWxwaGE=' },
+ })
+ )
+ expect(transport.invoke).toHaveBeenCalledWith(
+ 'command:createTask',
+ expect.objectContaining({
+ payload: { kind: 'torrent-base64', base64: 'YmV0YQ==' },
+ })
+ )
+ expect(transport.invoke).not.toHaveBeenCalledWith(
+ 'command:downloadAllTorrents'
+ )
+ expect(recordRecentMock.mock.calls).toEqual(
+ secondOutcome === 'created' ? [['/d'], ['/d']] : [['/d']]
+ )
+ }
+ )
+
+ it.each([2, 1, 0])(
+ 'records App batch snapshot only if at least one torrent is accepted (%s)',
+ async (succeeded) => {
+ const onSubmitSuccess = vi.fn()
+ const user = userEvent.setup()
+ const { transport } = await import('@renderer/lib/transport')
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === 'query:getSettings') {
+ return { app: { defaultSaveDir: '/default' } }
+ }
+ if (channel === 'command:downloadAllTorrents') {
+ return {
+ total: 2,
+ succeeded,
+ failed: 2 - succeeded,
+ firstTaskId: succeeded > 0 ? 'first-task' : null,
+ }
+ }
+ return {}
+ })
+ renderForm({
+ subscribeEvents: true,
+ onSubmitSuccess,
+ defaultValues: {
+ tab: 'torrent',
+ source: 'file',
+ base64: 'dG9ycmVudA==',
+ torrentMeta: {
+ name: 'current.bin',
+ infoHash: 'a'.repeat(40),
+ totalSize: 2,
+ files: [
+ { index: 0, path: 'skip.bin', size: 1, extension: '.bin' },
+ { index: 1, path: 'keep.bin', size: 1, extension: '.bin' },
+ ],
+ },
selectedFiles: [1],
saveDir: '/custom',
dlLimit: 2048,
ulLimit: 1024,
seedRatio: 1.5,
- }
+ },
+ })
+
+ const queueListener = vi
+ .mocked(transport.on)
+ .mock.calls.find(
+ ([channel]) => channel === Events.TorrentQueueSizeChanged
+ )?.[1]
+ act(() => queueListener?.({ queueTotal: 2 }))
+ await user.click(
+ await screen.findByRole('button', { name: 'Download All (2)' })
)
- )
- expect(onSubmitSuccess).toHaveBeenCalledWith('first-task')
- })
+
+ await waitFor(() =>
+ expect(transport.invoke).toHaveBeenCalledWith(
+ 'command:downloadAllTorrents',
+ {
+ selectedFiles: [1],
+ saveDir: '/custom',
+ dlLimit: 2048,
+ ulLimit: 1024,
+ seedRatio: 1.5,
+ }
+ )
+ )
+ if (succeeded > 0) {
+ expect(onSubmitSuccess).toHaveBeenCalledWith('first-task')
+ expect(recordRecentMock).toHaveBeenCalledWith('/custom')
+ } else {
+ expect(onSubmitSuccess).not.toHaveBeenCalled()
+ expect(recordRecentMock).not.toHaveBeenCalled()
+ }
+ }
+ )
it('closes an external queue when the shell reports no valid next torrent', async () => {
const onCancel = vi.fn()
@@ -546,6 +660,7 @@ describe('AddTaskForm', () => {
)
)
expect(onSubmitSuccess).toHaveBeenCalledWith('ok-gid')
+ expect(recordRecentMock.mock.calls).toEqual([['/d']])
})
it('surfaces the create failure reason without Electron IPC prefixes', async () => {
@@ -574,6 +689,7 @@ describe('AddTaskForm', () => {
)
)
expect(onSubmitSuccess).not.toHaveBeenCalled()
+ expect(recordRecentMock).not.toHaveBeenCalled()
await waitFor(() => expect(submit).toBeEnabled())
})
@@ -646,6 +762,7 @@ describe('AddTaskForm', () => {
name: 'This torrent already exists',
})
).toBeInTheDocument()
+ expect(recordRecentMock).not.toHaveBeenCalled()
await user.click(
screen.getByRole('button', { name: 'Create separate copy' })
)
@@ -657,5 +774,6 @@ describe('AddTaskForm', () => {
)
)
expect(onSubmitSuccess).toHaveBeenCalledWith('copy-task')
+ expect(recordRecentMock.mock.calls).toEqual([['/d']])
})
})
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 785542c6..292a4d09 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -9,12 +9,19 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from '@renderer/components/ui/alert-dialog'
+import {
+ ScrollArea,
+ ScrollAreaContent,
+ ScrollAreaViewport,
+ ScrollBar,
+} from '@renderer/components/ui/scroll-area'
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from '@renderer/components/ui/tabs'
+import { recordRecentDirectory } from '@renderer/lib/directory-preferences'
import type { ParsedTorrentFile } from '@renderer/lib/parse-torrent-file'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
@@ -391,6 +398,7 @@ export function AddTaskForm({
continue
}
succeeded += 1
+ void recordRecentDirectory(request.saveDir)
firstTaskId ??= created.taskId ?? created.gid
} catch (error) {
console.error(error)
@@ -415,6 +423,9 @@ export function AddTaskForm({
Commands.DownloadAllTorrents,
options
)) as TorrentBatchCreateResult
+ if (result.succeeded > 0) {
+ void recordRecentDirectory(options.saveDir)
+ }
}
setLocalTorrentQueue(null)
setTorrentQueue(null)
@@ -465,6 +476,7 @@ export function AddTaskForm({
break
}
successes.push(result)
+ void recordRecentDirectory(request.saveDir)
} catch (err) {
failed += 1
firstFailureReason ??= taskCreateFailureReason(err)
@@ -519,6 +531,7 @@ export function AddTaskForm({
return
}
setDuplicateConflict(null)
+ void recordRecentDirectory(duplicateConflict.request.saveDir)
platform.notify('info', 'task.add.createdCopy')
await completeCurrentSubmission(result.taskId)
} catch (error) {
@@ -549,25 +562,29 @@ export function AddTaskForm({
return (
<AddTaskLayoutProvider onAdvancedOpenChange={onAdvancedOpenChange}>
<FormProvider {...form}>
- <div
+ <ScrollArea
data-slot="add-task-form-body"
- className={cn(
- 'flex flex-col overflow-y-auto',
- presentation === 'dialog'
- ? 'min-h-0 flex-auto'
- : 'max-h-[calc(100vh-40px)]'
- )}
+ className={cn(presentation === 'dialog' ? 'flex-auto' : 'flex-1')}
>
- <div
- data-adaptive-content
- className={cn(
- 'px-4 pt-2',
- presentation === 'dialog' ? 'pb-4' : 'pb-[72px]'
- )}
+ <ScrollAreaViewport
+ tabIndex={-1}
+ className="overscroll-contain focus-visible:ring-0"
>
- <TabsSection onTorrentFilesLoaded={handleLocalTorrentFilesLoaded} />
- </div>
- </div>
+ <ScrollAreaContent
+ data-adaptive-content
+ className={cn(
+ 'px-4 pt-2',
+ presentation === 'dialog' ? 'pb-4' : 'pb-[72px]'
+ )}
+ style={{ minWidth: '100%' }}
+ >
+ <TabsSection
+ onTorrentFilesLoaded={handleLocalTorrentFilesLoaded}
+ />
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar />
+ </ScrollArea>
<div
data-slot="add-task-form-footer"
className={cn(
diff --git a/src/renderer/components/add-task/links-tab-panel.tsx b/src/renderer/components/add-task/links-tab-panel.tsx
index bc7ef163..6c91f3c0 100644
--- a/src/renderer/components/add-task/links-tab-panel.tsx
+++ b/src/renderer/components/add-task/links-tab-panel.tsx
@@ -11,6 +11,7 @@ export function LinksTabPanel() {
<DirectoryPicker
name="saveDir"
variant="compact"
+ showHistory
prefixLabel={t('task.add.saveTo')}
placeholder={t('task.add.saveDirEmpty')}
/>
diff --git a/src/renderer/components/add-task/torrent-file-panel.tsx b/src/renderer/components/add-task/torrent-file-panel.tsx
index 689338af..d31bff03 100644
--- a/src/renderer/components/add-task/torrent-file-panel.tsx
+++ b/src/renderer/components/add-task/torrent-file-panel.tsx
@@ -39,8 +39,9 @@ export function TorrentFilePanel({ onClear }: TorrentFilePanelProps) {
<div className="flex min-h-0 min-w-0 flex-1 flex-col gap-2">
<TorrentInfoHeader onClear={onClear} />
- <div className="flex min-h-[200px] max-h-[calc(100vh-380px)] min-w-0 overflow-hidden rounded-md border border-border">
+ <div className="flex min-h-[200px] max-h-[calc(100vh-380px)] min-w-0 overflow-hidden rounded-md border border-border [&_[data-slot=scroll-area-viewport]]:focus-visible:ring-0">
<FileList<TorrentFileInfo>
+ scrollbar="custom"
files={meta.files}
selectedIndices={selected ?? []}
onSelectionChange={handleSelection}
@@ -50,6 +51,7 @@ export function TorrentFilePanel({ onClear }: TorrentFilePanelProps) {
<DirectoryPicker
name="saveDir"
variant="compact"
+ showHistory
prefixLabel={t('task.add.saveTo')}
placeholder={t('task.add.saveDirEmpty')}
/>
diff --git a/src/renderer/components/desktop-kit/directory-history-menu.test.tsx b/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
new file mode 100644
index 00000000..babdca90
--- /dev/null
+++ b/src/renderer/components/desktop-kit/directory-history-menu.test.tsx
@@ -0,0 +1,234 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { DirectoryHistoryMenu } from './directory-history-menu'
+
+const mocks = vi.hoisted(() => ({
+ kind: 'electron' as 'electron' | 'web',
+ preferences: { favorites: ['/favorite'], recent: ['/recent ', '/current'] },
+ locations: {
+ common: [],
+ favorites: [
+ { name: 'allowed', path: '/allowed', sourcePaths: ['/allowed'] },
+ ],
+ recent: [],
+ },
+ loading: false,
+ error: null as string | null,
+ refresh: vi.fn(),
+ appHook: vi.fn(),
+ serverHook: vi.fn(),
+ managerOpenedFrom: null as Element | null,
+}))
+
+vi.mock('@renderer/platform/services', () => ({
+ usePlatformServices: () => ({ kind: mocks.kind }),
+}))
+vi.mock('@renderer/lib/directory-preferences', () => ({
+ useDirectoryPreferences: () => {
+ mocks.appHook()
+ return {
+ preferences: mocks.preferences,
+ loading: mocks.loading,
+ error: mocks.error,
+ refresh: mocks.refresh,
+ }
+ },
+ useServerDirectoryLocations: () => {
+ mocks.serverHook()
+ return {
+ locations: mocks.locations,
+ loading: mocks.loading,
+ error: mocks.error,
+ refresh: mocks.refresh,
+ }
+ },
+}))
+vi.mock(
+ '@renderer/features/directory-preferences/directory-preferences-dialog',
+ () => ({
+ DirectoryPreferencesDialog: ({
+ open,
+ onClose,
+ }: {
+ open: boolean
+ onClose: () => void
+ }) => {
+ if (!open) return null
+ mocks.managerOpenedFrom = document.activeElement
+ return (
+ <div role="dialog" aria-label="Manage directories">
+ <button type="button" onClick={onClose}>
+ Close
+ </button>
+ </div>
+ )
+ },
+ })
+)
+
+describe('DirectoryHistoryMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.kind = 'electron'
+ mocks.preferences = {
+ favorites: ['/favorite'],
+ recent: ['/recent ', '/current'],
+ }
+ mocks.loading = false
+ mocks.error = null
+ mocks.managerOpenedFrom = null
+ mocks.locations = {
+ common: [],
+ favorites: [
+ { name: 'allowed', path: '/allowed', sourcePaths: ['/allowed'] },
+ ],
+ recent: [],
+ }
+ })
+
+ it('shows App favorites before recent with literal paths and current check without Server queries', async () => {
+ const onSelect = vi.fn()
+ render(<DirectoryHistoryMenu currentPath="/current" onSelect={onSelect} />)
+ expect(mocks.appHook).not.toHaveBeenCalled()
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Directory history' }))
+ await screen.findByRole('menu')
+ expect(mocks.appHook).toHaveBeenCalled()
+ expect(mocks.serverHook).not.toHaveBeenCalled()
+ expect(
+ screen.getAllByRole('menuitem').map((item) => item.textContent)
+ ).toEqual(['/favorite', '/recent ', '/current', 'Manage directories'])
+ expect(screen.getByRole('menuitem', { name: '/current' })).toHaveAttribute(
+ 'aria-current',
+ 'true'
+ )
+ await userEvent
+ .setup()
+ .click(screen.getByRole('menuitem', { name: '/recent' }))
+ expect(onSelect).toHaveBeenCalledWith('/recent ')
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ })
+
+ it('shows only authorized Server entries without exposing raw saved paths', async () => {
+ mocks.kind = 'web'
+ render(<DirectoryHistoryMenu currentPath="/allowed" onSelect={vi.fn()} />)
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Directory history' }))
+ await screen.findByRole('menu')
+ expect(mocks.serverHook).toHaveBeenCalled()
+ expect(mocks.appHook).not.toHaveBeenCalled()
+ expect(
+ screen.getByRole('menuitem', { name: '/allowed' })
+ ).toBeInTheDocument()
+ expect(screen.queryByText('/favorite')).not.toBeInTheDocument()
+ })
+
+ it('supports keyboard selection and Escape with trigger focus restoration', async () => {
+ const onSelect = vi.fn()
+ const user = userEvent.setup()
+ render(<DirectoryHistoryMenu currentPath="/current" onSelect={onSelect} />)
+ const trigger = screen.getByRole('button', { name: 'Directory history' })
+ trigger.focus()
+ await user.keyboard('{ArrowDown}')
+ await waitFor(() =>
+ expect(screen.getByRole('menuitem', { name: '/favorite' })).toHaveFocus()
+ )
+ await user.keyboard('{Enter}')
+ expect(onSelect).toHaveBeenCalledWith('/favorite')
+ await waitFor(() => expect(trigger).toHaveFocus())
+ await user.keyboard('{ArrowDown}')
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(trigger).toHaveFocus())
+ expect(onSelect).toHaveBeenCalledOnce()
+ })
+
+ it.each(['Control', 'Meta'])(
+ 'contains %s+Enter and Escape before parent window shortcuts',
+ async (modifier) => {
+ const parent = vi.fn()
+ window.addEventListener('keydown', parent)
+ try {
+ const onSelect = vi.fn()
+ const user = userEvent.setup()
+ render(
+ <DirectoryHistoryMenu currentPath="/current" onSelect={onSelect} />
+ )
+ await user.click(
+ screen.getByRole('button', { name: 'Directory history' })
+ )
+ await screen.findByRole('menu')
+ const first = screen.getByRole('menuitem', { name: '/favorite' })
+ first.focus()
+ const properties =
+ modifier === 'Control' ? { ctrlKey: true } : { metaKey: true }
+ parent.mockClear()
+ fireEvent.keyDown(first, { key: 'Enter', ...properties })
+ expect(parent).not.toHaveBeenCalled()
+ expect(onSelect).not.toHaveBeenCalled()
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ fireEvent.keyDown(first, { key: 'Escape' })
+ expect(parent).not.toHaveBeenCalled()
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ } finally {
+ window.removeEventListener('keydown', parent)
+ }
+ }
+ )
+
+ it('preserves a live manager opener instead of the disappearing menu entry', async () => {
+ render(<DirectoryHistoryMenu currentPath="/current" onSelect={vi.fn()} />)
+ const user = userEvent.setup()
+ const trigger = screen.getByRole('button', { name: 'Directory history' })
+ await user.click(trigger)
+ await screen.findByRole('menu')
+ await user.click(
+ screen.getByRole('menuitem', { name: 'Manage directories' })
+ )
+ expect(
+ await screen.findByRole('dialog', { name: 'Manage directories' })
+ ).toBeInTheDocument()
+ expect(mocks.managerOpenedFrom).toBe(trigger)
+ await waitFor(() =>
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ )
+ })
+
+ it('keeps failed locations retryable without selecting an unverified saved path', async () => {
+ mocks.kind = 'web'
+ mocks.error = 'unavailable'
+ mocks.locations = { common: [], favorites: [], recent: [] }
+ render(<DirectoryHistoryMenu currentPath="/current" onSelect={vi.fn()} />)
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Directory history' }))
+ await screen.findByRole('menu')
+ expect(screen.getByRole('alert')).toBeInTheDocument()
+ await user.click(screen.getByRole('menuitem', { name: 'Retry' }))
+ expect(mocks.refresh).toHaveBeenCalledOnce()
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ })
+
+ it('restores menu focus when a settings event removes its focused record', async () => {
+ const props = { currentPath: '/current', onSelect: vi.fn() }
+ const view = render(<DirectoryHistoryMenu {...props} />)
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Directory history' }))
+ await screen.findByRole('menu')
+ const item = screen.getByRole('menuitem', { name: '/favorite' })
+ act(() => item.focus())
+ mocks.preferences = { favorites: [], recent: [] }
+ await act(async () => view.rerender(<DirectoryHistoryMenu {...props} />))
+ expect(screen.getByRole('menu')).toContainElement(
+ document.activeElement as HTMLElement
+ )
+ })
+})
diff --git a/src/renderer/components/desktop-kit/directory-history-menu.tsx b/src/renderer/components/desktop-kit/directory-history-menu.tsx
new file mode 100644
index 00000000..43a4857d
--- /dev/null
+++ b/src/renderer/components/desktop-kit/directory-history-menu.tsx
@@ -0,0 +1,238 @@
+import { Button } from '@renderer/components/ui/button'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { DirectoryPreferencesDialog } from '@renderer/features/directory-preferences/directory-preferences-dialog'
+import {
+ useDirectoryPreferences,
+ useServerDirectoryLocations,
+} from '@renderer/lib/directory-preferences'
+import { usePlatformServices } from '@renderer/platform/services'
+import { Check, History, Settings2 } from 'lucide-react'
+import {
+ type KeyboardEvent,
+ type RefObject,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+
+interface DirectoryHistoryMenuProps {
+ currentPath: string
+ disabled?: boolean
+ onSelect: (path: string) => void
+}
+
+function containSubmitShortcut(event: KeyboardEvent) {
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault()
+ event.stopPropagation()
+ }
+}
+
+export function DirectoryHistoryMenu({
+ currentPath,
+ disabled,
+ onSelect,
+}: DirectoryHistoryMenuProps) {
+ const { t } = useTranslation()
+ const { kind } = usePlatformServices()
+ const [open, setOpen] = useState(false)
+ const [managerOpen, setManagerOpen] = useState(false)
+ const trigger = useRef<HTMLButtonElement>(null)
+ const popup = useRef<HTMLDivElement>(null)
+ const openingManager = useRef(false)
+
+ const openManager = () => {
+ openingManager.current = true
+ setOpen(false)
+ }
+
+ return (
+ <>
+ <DropdownMenu
+ open={open}
+ onOpenChange={(next) => {
+ if (next) openingManager.current = false
+ setOpen(next)
+ }}
+ onOpenChangeComplete={(next) => {
+ if (!next && openingManager.current) {
+ // Wait for the menu focus trap to close, then let the manager
+ // capture the live trigger instead of a removed menu item.
+ trigger.current?.focus()
+ setManagerOpen(true)
+ }
+ }}
+ >
+ <DropdownMenuTrigger
+ ref={trigger}
+ disabled={disabled}
+ onKeyDownCapture={containSubmitShortcut}
+ render={<Button type="button" variant="outline" size="icon-sm" />}
+ aria-label={t('directoryPreferences.history')}
+ title={t('directoryPreferences.history')}
+ className="h-auto min-h-8 shrink-0"
+ >
+ <History aria-hidden="true" className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ ref={popup}
+ align="end"
+ className="w-96 max-w-[calc(100vw-2rem)]"
+ aria-label={t('directoryPreferences.history')}
+ finalFocus={() => !openingManager.current}
+ 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}>
+ <Settings2 aria-hidden="true" />
+ {t('directoryPreferences.manage')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <DirectoryPreferencesDialog
+ open={managerOpen}
+ onClose={() => setManagerOpen(false)}
+ />
+ </>
+ )
+}
+
+interface HistoryItemsProps {
+ currentPath: string
+ onSelect: (path: string) => void
+ popup: RefObject<HTMLDivElement | null>
+}
+
+function AppHistoryItems(props: HistoryItemsProps) {
+ const { preferences, loading, error, refresh } = useDirectoryPreferences()
+ return (
+ <HistoryItems
+ {...props}
+ favorites={preferences.favorites}
+ recent={preferences.recent}
+ loading={loading}
+ error={error}
+ refresh={refresh}
+ />
+ )
+}
+
+function ServerHistoryItems(props: HistoryItemsProps) {
+ const { locations, loading, error, refresh } = useServerDirectoryLocations()
+ return (
+ <HistoryItems
+ {...props}
+ favorites={locations?.favorites.map((entry) => entry.path) ?? []}
+ recent={locations?.recent.map((entry) => entry.path) ?? []}
+ loading={loading}
+ error={error}
+ refresh={refresh}
+ />
+ )
+}
+
+function HistoryItems({
+ currentPath,
+ onSelect,
+ popup,
+ favorites,
+ recent,
+ loading,
+ error,
+ refresh,
+}: HistoryItemsProps & {
+ favorites: string[]
+ recent: string[]
+ loading: boolean
+ error: string | null
+ refresh: () => unknown
+}) {
+ const { t } = useTranslation()
+ // An event can remove the focused history entry while this menu is open.
+ // Keep the next key inside the menu, including the parent submit shortcut.
+ useLayoutEffect(() => {
+ if (document.activeElement === document.body) popup.current?.focus()
+ })
+ const groups = [
+ { key: 'favorites', paths: favorites },
+ { key: 'recent', paths: recent },
+ ] as const
+
+ return (
+ <>
+ {groups.map(({ key, paths }) =>
+ paths.length > 0 ? (
+ <DropdownMenuGroup key={key}>
+ <DropdownMenuLabel className="text-xs text-muted-foreground">
+ {t(`directoryPreferences.${key}`)}
+ </DropdownMenuLabel>
+ {paths.map((path) => (
+ <DropdownMenuItem
+ key={path}
+ onClick={() => onSelect(path)}
+ label={path}
+ title={path}
+ aria-current={path === currentPath ? 'true' : undefined}
+ className="items-start text-xs"
+ >
+ <span className="size-4 shrink-0">
+ {path === currentPath && <Check aria-hidden="true" />}
+ </span>
+ <span className="min-w-0 whitespace-pre-wrap break-all">
+ {path}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ ) : null
+ )}
+ {loading && (
+ <div role="status" className="px-2 py-2 text-xs text-muted-foreground">
+ {t('directoryPreferences.loading')}
+ </div>
+ )}
+ {error && (
+ <>
+ <div role="alert" className="px-2 py-2 text-xs text-destructive">
+ {t(`directoryPreferences.errors.${error}`)}
+ </div>
+ <DropdownMenuItem closeOnClick={false} onClick={() => void refresh()}>
+ {t('directoryPreferences.retry')}
+ </DropdownMenuItem>
+ </>
+ )}
+ {!loading && !error && !favorites.length && !recent.length && (
+ <div className="px-2 py-2 text-xs text-muted-foreground">
+ {t('directoryPreferences.emptyHistory')}
+ </div>
+ )}
+ </>
+ )
+}
diff --git a/src/renderer/components/desktop-kit/directory-picker.test.tsx b/src/renderer/components/desktop-kit/directory-picker.test.tsx
index be6713fa..bc04be15 100644
--- a/src/renderer/components/desktop-kit/directory-picker.test.tsx
+++ b/src/renderer/components/desktop-kit/directory-picker.test.tsx
@@ -1,11 +1,27 @@
import '@testing-library/jest-dom/vitest'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import '@renderer/lib/i18n'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FormProvider, useForm } from 'react-hook-form'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { DirectoryPicker } from './directory-picker'
const pickSaveDirMock = vi.fn()
+const recordRecentMock = vi.fn().mockResolvedValue(undefined)
+vi.mock('@renderer/lib/directory-preferences', () => ({
+ recordRecentDirectory: (...args: unknown[]) => recordRecentMock(...args),
+}))
+vi.mock('./directory-history-menu', () => ({
+ DirectoryHistoryMenu: ({
+ onSelect,
+ }: {
+ onSelect: (path: string) => void
+ }) => (
+ <button type="button" onClick={() => onSelect('/recent ')}>
+ History
+ </button>
+ ),
+}))
vi.mock('@renderer/platform/services', () => ({
usePlatformServices: () => ({ pickSaveDir: pickSaveDirMock }),
}))
@@ -14,12 +30,27 @@ interface FormShape {
dir: string
}
-function Wrapper(props: { initial: string; variant: 'compact' | 'input' }) {
+function Wrapper(props: {
+ initial: string
+ variant: 'compact' | 'input'
+ showHistory?: boolean
+ recordRecent?: boolean
+ onPickingChange?: (picking: boolean) => void
+}) {
const form = useForm<FormShape>({ defaultValues: { dir: props.initial } })
return (
<FormProvider {...form}>
- <DirectoryPicker name="dir" variant={props.variant} />
+ <DirectoryPicker
+ name="dir"
+ variant={props.variant}
+ showHistory={props.showHistory}
+ recordRecent={props.recordRecent}
+ onPickingChange={props.onPickingChange}
+ />
<div data-testid="value">{form.watch('dir')}</div>
+ <div data-testid="dirty">
+ {String(form.formState.dirtyFields.dir ?? false)}
+ </div>
</FormProvider>
)
}
@@ -27,6 +58,7 @@ function Wrapper(props: { initial: string; variant: 'compact' | 'input' }) {
describe('<DirectoryPicker>', () => {
beforeEach(() => {
pickSaveDirMock.mockReset()
+ recordRecentMock.mockClear()
})
it('input variant renders input + browse button', () => {
@@ -49,6 +81,7 @@ describe('<DirectoryPicker>', () => {
await user.click(screen.getByRole('button', { name: /browse/i }))
expect(pickSaveDirMock).toHaveBeenCalled()
expect(screen.getByTestId('value')).toHaveTextContent('/picked')
+ expect(recordRecentMock).toHaveBeenCalledWith('/picked')
})
it('skips field update when picker returns null', async () => {
@@ -57,6 +90,37 @@ describe('<DirectoryPicker>', () => {
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: /browse/i }))
expect(screen.getByTestId('value')).toHaveTextContent('/keep')
+ expect(recordRecentMock).not.toHaveBeenCalled()
+ })
+
+ it('lets a batched settings form stage a selection without persisting recent history', async () => {
+ pickSaveDirMock.mockResolvedValueOnce('/draft')
+ render(<Wrapper initial="/original" variant="input" recordRecent={false} />)
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: /browse/i }))
+ expect(screen.getByTestId('value')).toHaveTextContent('/draft')
+ expect(screen.getByTestId('dirty')).toHaveTextContent('true')
+ expect(recordRecentMock).not.toHaveBeenCalled()
+ })
+
+ it('reports picker activity and ignores a result after its form unmounts', async () => {
+ let finish!: (path: string) => void
+ const activity = vi.fn()
+ pickSaveDirMock.mockImplementationOnce(
+ () =>
+ new Promise<string>((resolve) => {
+ finish = resolve
+ })
+ )
+ const view = render(
+ <Wrapper initial="/original" variant="input" onPickingChange={activity} />
+ )
+ fireEvent.click(screen.getByRole('button', { name: /browse/i }))
+ expect(activity).toHaveBeenCalledWith(true)
+ view.unmount()
+ await act(async () => finish('/late'))
+ expect(recordRecentMock).not.toHaveBeenCalled()
})
it('ignores repeated clicks while a picker request is pending', async () => {
@@ -84,4 +148,29 @@ describe('<DirectoryPicker>', () => {
fireEvent.click(button)
await waitFor(() => expect(pickSaveDirMock).toHaveBeenCalledTimes(2))
})
+
+ it('enables direct history only when requested and selection is dirty without recording', async () => {
+ const { rerender } = render(<Wrapper initial="/x" variant="compact" />)
+ expect(
+ screen.queryByRole('button', { name: 'History' })
+ ).not.toBeInTheDocument()
+ rerender(<Wrapper initial="/x" variant="compact" showHistory />)
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'History' }))
+ expect(screen.getByTestId('value').textContent).toBe('/recent ')
+ expect(screen.getByTestId('dirty')).toHaveTextContent('true')
+ expect(recordRecentMock).not.toHaveBeenCalled()
+ expect(pickSaveDirMock).not.toHaveBeenCalled()
+ })
+
+ it('does not wait for best-effort history persistence before updating the field', async () => {
+ recordRecentMock.mockImplementationOnce(() => new Promise(() => {}))
+ pickSaveDirMock.mockResolvedValueOnce('/picked ')
+ render(<Wrapper initial="/old" variant="input" />)
+ const browse = screen.getByRole('button', { name: /browse/i })
+ await userEvent.setup().click(browse)
+ expect(screen.getByTestId('value').textContent).toBe('/picked ')
+ expect(browse).toBeEnabled()
+ })
})
diff --git a/src/renderer/components/desktop-kit/directory-picker.tsx b/src/renderer/components/desktop-kit/directory-picker.tsx
index 726b9963..cdb7c3a7 100644
--- a/src/renderer/components/desktop-kit/directory-picker.tsx
+++ b/src/renderer/components/desktop-kit/directory-picker.tsx
@@ -1,8 +1,9 @@
import { Button } from '@renderer/components/ui/button'
import { Input } from '@renderer/components/ui/input'
+import { recordRecentDirectory } from '@renderer/lib/directory-preferences'
import { usePlatformServices } from '@renderer/platform/services'
import { Folder } from 'lucide-react'
-import { type ComponentProps, useRef, useState } from 'react'
+import { type ComponentProps, useEffect, useRef, useState } from 'react'
import {
type FieldPath,
type FieldValues,
@@ -10,6 +11,7 @@ import {
useWatch,
} from 'react-hook-form'
import { useTranslation } from 'react-i18next'
+import { DirectoryHistoryMenu } from './directory-history-menu'
export interface DirectoryPickerProps<TFields extends FieldValues> {
name: FieldPath<TFields>
@@ -18,6 +20,10 @@ export interface DirectoryPickerProps<TFields extends FieldValues> {
placeholder?: string
disabled?: boolean
inputProps?: ComponentProps<typeof Input>
+ showHistory?: boolean
+ recordRecent?: boolean
+ onPickingChange?: (picking: boolean) => void
+ allowFavoriteEditing?: boolean
}
export function DirectoryPicker<TFields extends FieldValues>({
@@ -27,9 +33,20 @@ export function DirectoryPicker<TFields extends FieldValues>({
placeholder,
disabled,
inputProps,
+ showHistory = false,
+ recordRecent = true,
+ onPickingChange,
+ allowFavoriteEditing = true,
}: DirectoryPickerProps<TFields>) {
const { t } = useTranslation()
const { pickSaveDir } = usePlatformServices()
+ const mounted = useRef(true)
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ }
+ }, [])
const { setValue, control } = useFormContext<TFields>()
const current = (useWatch({ control, name }) ?? '') as string
const pickInFlight = useRef(false)
@@ -41,49 +58,78 @@ export function DirectoryPicker<TFields extends FieldValues>({
pickInFlight.current = true
setIsPicking(true)
+ onPickingChange?.(true)
try {
- const picked = await pickSaveDir(current || undefined)
+ const picked = allowFavoriteEditing
+ ? await pickSaveDir(current || undefined)
+ : await pickSaveDir(current || undefined, {
+ allowFavoriteEditing: false,
+ })
+ if (!mounted.current) return
if (picked) {
setValue(name, picked as never, {
shouldValidate: true,
shouldDirty: true,
})
+ if (recordRecent) void recordRecentDirectory(picked)
}
} finally {
pickInFlight.current = false
- setIsPicking(false)
+ if (mounted.current) {
+ setIsPicking(false)
+ onPickingChange?.(false)
+ }
}
}
+ const history = showHistory ? (
+ <DirectoryHistoryMenu
+ currentPath={current}
+ disabled={pickerDisabled}
+ onSelect={(path) => {
+ setValue(name, path as never, {
+ shouldValidate: true,
+ shouldDirty: true,
+ })
+ }}
+ />
+ ) : null
+
if (variant === 'compact') {
return (
- <button
- type="button"
- onClick={handlePick}
- aria-label={t('settings.common.changeDirectory')}
- title={current || undefined}
- disabled={pickerDisabled}
- className="group flex w-full items-center gap-2.5 rounded-md border border-border bg-background px-3 py-2 text-left text-sm transition-colors hover:border-ring hover:bg-accent/30 disabled:opacity-50"
- >
- {prefixLabel && (
- <span className="shrink-0 text-xs text-muted-foreground">
- {prefixLabel}
- </span>
- )}
- {current ? (
- <span className="min-w-0 flex-1 truncate text-xs text-foreground [direction:rtl] [text-align:left]">
- {current}
- </span>
- ) : (
- <span className="min-w-0 flex-1 truncate text-xs italic text-muted-foreground">
- {placeholder ?? t('settings.common.directoryEmpty')}
- </span>
- )}
- <Folder
- className="h-4 w-4 shrink-0 text-muted-foreground"
- aria-hidden="true"
- />
- </button>
+ <div className="flex min-w-0 gap-2">
+ <button
+ type="button"
+ onClick={handlePick}
+ aria-label={t('settings.common.changeDirectory')}
+ title={current || undefined}
+ disabled={pickerDisabled}
+ className="group flex min-w-0 flex-1 items-center gap-2.5 rounded-md border border-border bg-background px-3 py-2 text-left text-sm transition-colors hover:border-ring hover:bg-accent/30 disabled:opacity-50"
+ >
+ {prefixLabel && (
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {prefixLabel}
+ </span>
+ )}
+ {current ? (
+ <span
+ dir="ltr"
+ className="min-w-0 flex-1 truncate text-left text-xs text-foreground"
+ >
+ {current}
+ </span>
+ ) : (
+ <span className="min-w-0 flex-1 truncate text-xs italic text-muted-foreground">
+ {placeholder ?? t('settings.common.directoryEmpty')}
+ </span>
+ )}
+ <Folder
+ className="h-4 w-4 shrink-0 text-muted-foreground"
+ aria-hidden="true"
+ />
+ </button>
+ {history}
+ </div>
)
}
@@ -93,10 +139,12 @@ export function DirectoryPicker<TFields extends FieldValues>({
{...inputProps}
name={name}
value={current}
+ dir="ltr"
+ title={current || undefined}
placeholder={placeholder}
readOnly
disabled={pickerDisabled}
- className="flex-1 text-xs [direction:rtl] [text-align:left] h-8"
+ className="h-8 min-w-0 flex-1 text-left text-xs"
/>
<Button
type="button"
@@ -108,6 +156,7 @@ export function DirectoryPicker<TFields extends FieldValues>({
<Folder className="mr-1 h-3 w-3" />
{t('settings.common.browse')}
</Button>
+ {history}
</div>
)
}
diff --git a/src/renderer/components/desktop-kit/virtual-list/types.ts b/src/renderer/components/desktop-kit/virtual-list/types.ts
index 831bc746..8e40bb8b 100644
--- a/src/renderer/components/desktop-kit/virtual-list/types.ts
+++ b/src/renderer/components/desktop-kit/virtual-list/types.ts
@@ -1,4 +1,4 @@
-import type { CSSProperties, ReactNode, RefObject } from 'react'
+import type { CSSProperties, HTMLAttributes, ReactNode, RefObject } from 'react'
export interface VirtualListProps<T> {
items: T[]
@@ -16,6 +16,12 @@ export interface VirtualListProps<T> {
renderEmpty?: () => ReactNode
className?: string
style?: CSSProperties
+ /** Keep the active descendant mounted outside the visible range. */
+ activeIndex?: number
+ containerProps?: Omit<
+ HTMLAttributes<HTMLDivElement>,
+ 'children' | 'className' | 'style'
+ >
}
export interface RowRenderProps<T> {
@@ -26,6 +32,7 @@ export interface RowRenderProps<T> {
export interface VirtualListHandle {
scrollToIndex: (index: number) => void
+ scrollToOffset: (offset: number) => void
getScrollOffset: () => number
getContainerRef: () => HTMLDivElement | null
}
diff --git a/src/renderer/components/desktop-kit/virtual-list/virtual-list.test.tsx b/src/renderer/components/desktop-kit/virtual-list/virtual-list.test.tsx
index 30f2aa68..1969aa8d 100644
--- a/src/renderer/components/desktop-kit/virtual-list/virtual-list.test.tsx
+++ b/src/renderer/components/desktop-kit/virtual-list/virtual-list.test.tsx
@@ -1,6 +1,6 @@
-import { render, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import { createRef } from 'react'
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import type { VirtualListHandle } from './types'
import { VirtualList } from './virtual-list'
@@ -73,4 +73,56 @@ describe('VirtualList', () => {
)
expect(scrollContainer).not.toBeNull()
})
+
+ it.each(['native', 'custom'] as const)(
+ 'retains active options and viewport semantics with %s scrollbars',
+ (scrollbar) => {
+ const height = vi
+ .spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
+ .mockReturnValue(200)
+ const width = vi
+ .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')
+ .mockReturnValue(400)
+ const { unmount } = render(
+ <VirtualList<TestItem>
+ items={makeItems(500)}
+ getId={(item) => item.id}
+ rowHeight={40}
+ activeIndex={0}
+ keepMountedIndex={499}
+ scrollbar={scrollbar}
+ containerProps={{
+ role: 'listbox',
+ tabIndex: 0,
+ 'aria-activedescendant': 'item-0',
+ }}
+ renderRow={({ item }) => (
+ <div
+ role="option"
+ tabIndex={-1}
+ aria-selected={item.id === 'item-0'}
+ id={item.id}
+ >
+ {item.label}
+ </div>
+ )}
+ />
+ )
+ const list = screen.getByRole('listbox')
+ expect(document.getElementById('item-0')).not.toBeNull()
+ expect(document.getElementById('item-499')).not.toBeNull()
+ expect(list.tabIndex).toBe(0)
+ if (scrollbar === 'custom')
+ expect(list.getAttribute('data-slot')).toBe('scroll-area-viewport')
+ fireEvent.scroll(list, { target: { scrollTop: 12_000 } })
+ expect(document.getElementById('item-0')).not.toBeNull()
+ expect(document.getElementById('item-499')).not.toBeNull()
+ expect(list.getAttribute('aria-activedescendant')).toBe('item-0')
+ expect(screen.getAllByRole('option').length).toBeLessThan(30)
+ expect(document.getElementById('item-300')).not.toBeNull()
+ unmount()
+ height.mockRestore()
+ width.mockRestore()
+ }
+ )
})
diff --git a/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx b/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
index 47c29b01..41cf9fab 100644
--- a/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
+++ b/src/renderer/components/desktop-kit/virtual-list/virtual-list.tsx
@@ -37,6 +37,8 @@ function VirtualListInner<T>(
renderEmpty,
className,
style,
+ activeIndex,
+ containerProps,
} = props
const internalRef = useRef<HTMLDivElement>(null)
@@ -49,18 +51,19 @@ function VirtualListInner<T>(
const rangeExtractor = useCallback(
(range: Range) => {
const indices = defaultRangeExtractor(range)
- if (
- keepMountedIndex !== undefined &&
- keepMountedIndex >= 0 &&
- keepMountedIndex < items.length &&
- !indices.includes(keepMountedIndex)
- ) {
- indices.push(keepMountedIndex)
- indices.sort((a, b) => a - b)
+ for (const index of [keepMountedIndex, activeIndex]) {
+ if (
+ index !== undefined &&
+ index >= 0 &&
+ index < items.length &&
+ !indices.includes(index)
+ ) {
+ indices.push(index)
+ }
}
- return indices
+ return indices.sort((a, b) => a - b)
},
- [keepMountedIndex, items.length]
+ [keepMountedIndex, activeIndex, items.length]
)
const virtualizer = useVirtualizer({
count: items.length,
@@ -80,6 +83,9 @@ function VirtualListInner<T>(
getScrollOffset() {
return virtualizer.scrollOffset ?? 0
},
+ scrollToOffset(offset: number) {
+ virtualizer.scrollToOffset(offset)
+ },
getContainerRef() {
return containerRef.current
},
@@ -133,6 +139,7 @@ function VirtualListInner<T>(
ref={containerRef}
data-testid="virtual-list-container"
tabIndex={-1}
+ {...containerProps}
className="relative"
>
<ScrollAreaContent style={{ minWidth: '100%' }}>
@@ -147,6 +154,7 @@ function VirtualListInner<T>(
return (
<div
+ {...containerProps}
ref={containerRef}
data-testid="virtual-list-container"
className={className}
diff --git a/src/renderer/components/file-list/file-list.tsx b/src/renderer/components/file-list/file-list.tsx
index a0cba363..bee8f6cc 100644
--- a/src/renderer/components/file-list/file-list.tsx
+++ b/src/renderer/components/file-list/file-list.tsx
@@ -11,6 +11,7 @@ interface FileListProps<T extends BaseFileRow = BaseFileRow> {
selectedIndices: number[]
onSelectionChange?: (indices: number[]) => void
readOnly?: boolean
+ scrollbar?: 'native' | 'custom'
/** Optional slot rendered in the sticky header's trailing area. */
headerSlot?: ReactNode
headerClassName?: string
@@ -23,6 +24,7 @@ export function FileList<T extends BaseFileRow = BaseFileRow>({
selectedIndices,
onSelectionChange,
readOnly = false,
+ scrollbar = 'native',
headerSlot,
headerClassName,
renderRowTrailing,
@@ -68,6 +70,7 @@ export function FileList<T extends BaseFileRow = BaseFileRow>({
return (
<VirtualList<T>
+ scrollbar={scrollbar}
items={files}
getId={(f) => String(f.index)}
rowHeight={32}
diff --git a/src/renderer/features/directory-preferences/directory-preferences-dialog.test.tsx b/src/renderer/features/directory-preferences/directory-preferences-dialog.test.tsx
new file mode 100644
index 00000000..8c8ad8d4
--- /dev/null
+++ b/src/renderer/features/directory-preferences/directory-preferences-dialog.test.tsx
@@ -0,0 +1,334 @@
+import {
+ generalSettingsSnapshot,
+ TEST_GENERAL_REVISION,
+} from '@test-utils/general-settings'
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import { transport } from '@renderer/lib/transport'
+import {
+ type PlatformServices,
+ PlatformServicesProvider,
+} from '@renderer/platform/services'
+import { Commands } from '@shared/protocol/commands'
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
+import { useState } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { DirectoryPreferencesDialog } from './directory-preferences-dialog'
+
+vi.mock('@renderer/lib/transport', () => ({ transport: { invoke: vi.fn() } }))
+const initial = {
+ favorites: ['/downloads/Movies ', '/missing'],
+ recent: ['/downloads/Music', '/stale/recent'],
+}
+const ok = (value = initial) => ({
+ ok: true,
+ value: generalSettingsSnapshot(value),
+})
+function platform(
+ pickSaveDir: PlatformServices['pickSaveDir'] = vi
+ .fn()
+ .mockResolvedValue(null),
+ kind: PlatformServices['kind'] = 'electron'
+): PlatformServices {
+ return {
+ kind,
+ pickSaveDir,
+ closeHost: vi.fn(),
+ readClipboard: vi.fn(),
+ openExternal: vi.fn(),
+ notify: vi.fn(),
+ }
+}
+function Harness({
+ services = platform(),
+ close = vi.fn(),
+}: {
+ services?: PlatformServices
+ close?: () => void
+}) {
+ const [open, setOpen] = useState(false)
+ return (
+ <PlatformServicesProvider services={services}>
+ <button type="button" onClick={() => setOpen(true)}>
+ Manage directories
+ </button>
+ <DirectoryPreferencesDialog
+ open={open}
+ onClose={() => {
+ close()
+ setOpen(false)
+ }}
+ />
+ </PlatformServicesProvider>
+ )
+}
+async function openManager(services = platform(), close = vi.fn()) {
+ const rendered = render(<Harness services={services} close={close} />)
+ const trigger = screen.getByRole('button', { name: 'Manage directories' })
+ trigger.focus()
+ fireEvent.click(trigger)
+ const manager = screen.getByRole('dialog', { name: 'Manage directories' })
+ await waitFor(() =>
+ expect(within(manager).getByRole('button', { name: 'Save' })).toBeEnabled()
+ )
+ return { ...rendered, trigger, manager, close }
+}
+const saves = () =>
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(([channel]) => channel === Commands.SaveGeneralSettings)
+beforeEach(() => {
+ vi.mocked(transport.invoke).mockReset().mockResolvedValue(ok())
+})
+afterEach(cleanup)
+
+describe('DirectoryPreferencesDialog draft', () => {
+ it.each(['electron', 'web'] as const)(
+ 'adds a favorite with %s Browse and persists only on Save',
+ async (kind) => {
+ const pick = vi.fn().mockResolvedValue('/chosen ')
+ const { close } = await openManager(platform(pick, kind))
+ fireEvent.click(screen.getByRole('button', { name: 'Add favorite' }))
+ await screen.findByTitle('/chosen ', { normalizer: (value) => value })
+ expect(pick).toHaveBeenCalledWith(undefined, {
+ allowFavoriteEditing: false,
+ })
+ expect(saves()).toEqual([])
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(close).toHaveBeenCalledTimes(1))
+ expect(saves()[0]?.[1]).toEqual({
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: {},
+ directories: {
+ addFavorites: ['/chosen '],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ })
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.some(
+ ([channel]) => channel === Commands.MutateDirectoryPreferences
+ )
+ ).toBe(false)
+ }
+ )
+
+ it('centers focus before draft removal and Cancel discards exact raw-path changes', async () => {
+ const { trigger } = await openManager()
+ const remove = screen.getByRole('button', {
+ name: 'Remove favorite /downloads/Movies',
+ })
+ remove.focus()
+ fireEvent.click(remove)
+ expect(screen.getByTestId('directory-preferences-section')).toHaveFocus()
+ expect(
+ screen.queryByTitle('/downloads/Movies ', {
+ normalizer: (value) => value,
+ })
+ ).toBeNull()
+ expect(saves()).toEqual([])
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ await waitFor(() => expect(trigger).toHaveFocus())
+ fireEvent.click(trigger)
+ expect(
+ await screen.findByTitle('/downloads/Movies ', {
+ normalizer: (value) => value,
+ })
+ ).toBeInTheDocument()
+ })
+
+ it('collapses recent folders by default and stages promotion, per-row removal and clear as deltas', async () => {
+ await openManager()
+ expect(
+ screen.queryByRole('button', {
+ name: 'Remove recent folder /stale/recent',
+ })
+ ).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: /Recent folders/ }))
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Add to favorites /downloads/Music' })
+ )
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Remove recent folder /stale/recent' })
+ )
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Clear recent folders' })
+ )
+ expect(saves()).toEqual([])
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(saves()).toHaveLength(1))
+ expect(saves()[0]?.[1]).toEqual({
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: {},
+ directories: {
+ addFavorites: ['/downloads/Music'],
+ removeFavorites: [],
+ removeRecent: ['/downloads/Music', '/stale/recent'],
+ },
+ })
+ })
+
+ it('retains a failed draft, reloads without losing edits, and saves only identities from its baseline', async () => {
+ const { close } = await openManager()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Remove favorite /missing' })
+ )
+ vi.mocked(transport.invoke).mockResolvedValueOnce({
+ ok: false,
+ error: { code: 'permissionDenied' },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await screen.findByRole('alert')
+ expect(close).not.toHaveBeenCalled()
+ expect(screen.queryByTitle('/missing')).toBeNull()
+ vi.mocked(transport.invoke).mockResolvedValueOnce(
+ ok({ ...initial, favorites: [...initial.favorites, '/remote-new'] })
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ await screen.findByTitle('/remote-new')
+ expect(screen.queryByTitle('/missing')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(close).toHaveBeenCalled())
+ expect(saves()[1]?.[1]).toEqual({
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: {},
+ directories: {
+ addFavorites: [],
+ removeFavorites: ['/missing'],
+ removeRecent: [],
+ },
+ })
+ })
+
+ it('contains parent shortcuts and keeps cancellation locked with stable focus during Save', async () => {
+ const { close, manager } = await openManager()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Remove favorite /missing' })
+ )
+ let release!: (value: unknown) => void
+ vi.mocked(transport.invoke).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve
+ })
+ )
+ const outer = vi.fn()
+ window.addEventListener('keydown', outer)
+ try {
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))
+ expect(screen.getByTestId('directory-preferences-content')).toHaveFocus()
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()
+ fireEvent.keyDown(document.activeElement as HTMLElement, {
+ key: 'Enter',
+ ctrlKey: true,
+ })
+ fireEvent.keyDown(document.activeElement as HTMLElement, {
+ key: 'Enter',
+ metaKey: true,
+ })
+ fireEvent.keyDown(document.activeElement as HTMLElement, {
+ key: 'Escape',
+ })
+ expect(outer).not.toHaveBeenCalled()
+ expect(close).not.toHaveBeenCalled()
+ expect(manager).toBeInTheDocument()
+ await waitFor(() => expect(release).toBeTypeOf('function'))
+ await act(async () => release(ok()))
+ await waitFor(() => expect(close).toHaveBeenCalledTimes(1))
+ } finally {
+ window.removeEventListener('keydown', outer)
+ }
+ })
+
+ it('rejects invalid initial results and cannot save an empty substitute baseline', async () => {
+ vi.mocked(transport.invoke).mockResolvedValueOnce({
+ ok: true,
+ value: { favorites: [], recent: [], unexpected: true },
+ })
+ render(<Harness />)
+ fireEvent.click(screen.getByRole('button', { name: 'Manage directories' }))
+ await screen.findByRole('alert')
+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ await screen.findByTitle('/missing')
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ expect(saves()).toEqual([])
+ })
+
+ it('cancels a real nested picker without altering the draft and restores Add favorite focus', async () => {
+ function NestedHarness() {
+ const [pickOpen, setPickOpen] = useState(false)
+ const [resolver, setResolver] = useState<
+ ((value: string | null) => void) | null
+ >(null)
+ const pickSaveDir = () =>
+ new Promise<string | null>((resolve) => {
+ setResolver(() => resolve)
+ setPickOpen(true)
+ })
+ return (
+ <>
+ <Harness services={platform(pickSaveDir)} />
+ <Dialog
+ open={pickOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ setPickOpen(false)
+ resolver?.(null)
+ }
+ }}
+ >
+ <DialogContent>
+ <DialogTitle>Choose a folder</DialogTitle>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+ }
+ render(<NestedHarness />)
+ fireEvent.click(screen.getByRole('button', { name: 'Manage directories' }))
+ const add = await screen.findByRole('button', { name: 'Add favorite' })
+ await waitFor(() => expect(add).toBeEnabled())
+ add.focus()
+ fireEvent.click(add)
+ const picker = screen.getByRole('dialog', { name: 'Choose a folder' })
+ fireEvent.keyDown(picker, { key: 'Escape' })
+ await waitFor(() => expect(add).toHaveFocus())
+ expect(
+ screen.getByRole('dialog', { name: 'Manage directories' })
+ ).toBeInTheDocument()
+ expect(saves()).toEqual([])
+ })
+
+ it('ignores a native picker result after its manager is unmounted', async () => {
+ let release!: (path: string | null) => void
+ const { unmount } = await openManager(
+ platform(
+ () =>
+ new Promise((resolve) => {
+ release = resolve
+ })
+ )
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Add favorite' }))
+ unmount()
+ await act(async () => release('/late'))
+ expect(saves()).toEqual([])
+ expect(vi.mocked(transport.invoke).mock.calls).toHaveLength(1)
+ })
+})
diff --git a/src/renderer/features/directory-preferences/directory-preferences-dialog.tsx b/src/renderer/features/directory-preferences/directory-preferences-dialog.tsx
new file mode 100644
index 00000000..6ac11e8b
--- /dev/null
+++ b/src/renderer/features/directory-preferences/directory-preferences-dialog.tsx
@@ -0,0 +1,134 @@
+import { Button } from '@renderer/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import { type KeyboardEvent, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ DirectoryPreferencesSection,
+ DirectoryPreferencesStatus,
+} from './directory-preferences-section'
+import { useDirectoryPreferencesDraft } from './use-directory-preferences-draft'
+
+export interface DirectoryPreferencesDialogProps {
+ open: boolean
+ onClose: () => void
+}
+
+export function DirectoryPreferencesDialog({
+ open,
+ onClose,
+}: DirectoryPreferencesDialogProps) {
+ return open ? <OpenDirectoryPreferencesDialog onClose={onClose} /> : null
+}
+
+function OpenDirectoryPreferencesDialog({ onClose }: { onClose: () => void }) {
+ const { t } = useTranslation()
+ const draft = useDirectoryPreferencesDraft()
+ const [picking, setPicking] = useState(false)
+ const contentRef = useRef<HTMLDivElement>(null)
+ const closed = useRef(false)
+ const busy = draft.saving || picking
+ const close = () => {
+ if (closed.current || busy) return
+ closed.current = true
+ onClose()
+ }
+ const keyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ event.stopPropagation()
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault()
+ return
+ }
+ const plain =
+ !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
+ if (plain && event.repeat && (event.key === 'Enter' || event.key === ' '))
+ event.preventDefault()
+ if (plain && event.key === 'Escape') {
+ event.preventDefault()
+ close()
+ }
+ }
+ const save = async () => {
+ if (busy || draft.loading || !draft.ready) return
+ contentRef.current?.focus({ preventScroll: true })
+ if (await draft.save()) close()
+ }
+ return (
+ <Dialog
+ open
+ disablePointerDismissal
+ onOpenChange={(open, details) => {
+ if (open) return
+ if (busy) details.cancel()
+ else close()
+ }}
+ >
+ <DialogContent
+ showCloseButton={false}
+ initialFocus={contentRef}
+ onKeyDown={keyDown}
+ onKeyUp={(event) => event.stopPropagation()}
+ className="flex max-h-[min(520px,calc(100dvh-2rem))] w-[calc(100%-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[600px]"
+ data-testid="directory-preferences-dialog"
+ >
+ <DialogHeader className="shrink-0 gap-2 border-b px-4 py-3">
+ <DialogTitle className="text-sm">
+ {t('directoryPreferences.title')}
+ </DialogTitle>
+ <DialogDescription className="text-xs">
+ {t('directoryPreferences.description')}
+ </DialogDescription>
+ </DialogHeader>
+ <div
+ ref={contentRef}
+ tabIndex={-1}
+ aria-busy={busy || draft.loading}
+ data-testid="directory-preferences-content"
+ className="min-h-0 flex-1 space-y-3 overflow-y-auto p-4 outline-none"
+ >
+ <DirectoryPreferencesStatus
+ loading={draft.loading}
+ error={draft.error}
+ disabled={busy}
+ onRetry={() => {
+ contentRef.current?.focus({ preventScroll: true })
+ void draft.refresh()
+ }}
+ />
+ <DirectoryPreferencesSection
+ preferences={draft.preferences}
+ onChange={draft.setPreferences}
+ disabled={draft.loading || busy || !draft.ready}
+ onPickingChange={setPicking}
+ />
+ </div>
+ <DialogFooter className="shrink-0 flex-row justify-end border-t px-4 py-3">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={busy}
+ onClick={close}
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ disabled={busy || draft.loading || !draft.ready}
+ onClick={() => void save()}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/renderer/features/directory-preferences/directory-preferences-section.tsx b/src/renderer/features/directory-preferences/directory-preferences-section.tsx
new file mode 100644
index 00000000..3e7f292b
--- /dev/null
+++ b/src/renderer/features/directory-preferences/directory-preferences-section.tsx
@@ -0,0 +1,305 @@
+import { Button } from '@renderer/components/ui/button'
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from '@renderer/components/ui/collapsible'
+import { usePlatformServices } from '@renderer/platform/services'
+import {
+ DIRECTORY_FAVORITES_LIMIT,
+ DIRECTORY_RECENT_LIMIT,
+ type DirectoryPreferences,
+} from '@shared/schemas/directory-preferences'
+import type { GeneralSettingsErrorCode } from '@shared/schemas/general-settings'
+import { ChevronRight, Folder, FolderPlus, Star, Trash2 } from 'lucide-react'
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export interface DirectoryPreferencesSectionProps {
+ preferences: DirectoryPreferences
+ onChange: (preferences: DirectoryPreferences) => void
+ disabled?: boolean
+ onPickingChange?: (picking: boolean) => void
+}
+
+export function DirectoryPreferencesStatus({
+ loading,
+ error,
+ disabled,
+ onRetry,
+}: {
+ loading: boolean
+ error: GeneralSettingsErrorCode | null
+ disabled?: boolean
+ onRetry: () => void
+}) {
+ const { t } = useTranslation()
+ return (
+ <>
+ {error && (
+ <div
+ role="alert"
+ className="flex items-center gap-2 rounded-md border border-destructive/30 p-2 text-xs"
+ >
+ <p className="min-w-0 flex-1 text-destructive">
+ {t(`directoryPreferences.errors.${error}`)}
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={disabled || loading}
+ onClick={onRetry}
+ >
+ {t('directoryPreferences.retry')}
+ </Button>
+ </div>
+ )}
+ {loading && (
+ <p role="status" className="text-xs text-muted-foreground">
+ {t('directoryPreferences.loading')}
+ </p>
+ )}
+ </>
+ )
+}
+
+export function DirectoryPreferencesSection({
+ preferences,
+ onChange,
+ disabled,
+ onPickingChange,
+}: DirectoryPreferencesSectionProps) {
+ const { t } = useTranslation()
+ const platform = usePlatformServices()
+ const [favoritesOpen, setFavoritesOpen] = useState(true)
+ const [recentOpen, setRecentOpen] = useState(false)
+ const [picking, setPicking] = useState(false)
+ const [pickerFailed, setPickerFailed] = useState(false)
+ const content = useRef<HTMLDivElement>(null)
+ const add = useRef<HTMLButtonElement>(null)
+ const pickInFlight = useRef(false)
+ const mounted = useRef(false)
+ const generation = useRef(0)
+ const restoreAddFocus = useRef(false)
+ const busy = disabled || picking
+ const full = preferences.favorites.length >= DIRECTORY_FAVORITES_LIMIT
+ const latest = useRef(preferences)
+ latest.current = preferences
+
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ generation.current++
+ }
+ }, [])
+ useLayoutEffect(() => {
+ if (!picking && restoreAddFocus.current) {
+ restoreAddFocus.current = false
+ if (add.current && !add.current.disabled)
+ add.current.focus({ preventScroll: true })
+ else content.current?.focus({ preventScroll: true })
+ }
+ }, [picking])
+
+ const change = (next: DirectoryPreferences) => {
+ content.current?.focus({ preventScroll: true })
+ onChange(next)
+ }
+ const addFavorite = async () => {
+ if (disabled || pickInFlight.current || full) return
+ const current = generation.current
+ pickInFlight.current = true
+ setPicking(true)
+ setPickerFailed(false)
+ onPickingChange?.(true)
+ try {
+ const path = await platform.pickSaveDir(undefined, {
+ allowFavoriteEditing: false,
+ })
+ if (!mounted.current || current !== generation.current) return
+ if (path !== null && !latest.current.favorites.includes(path)) {
+ change({
+ ...latest.current,
+ favorites: [...latest.current.favorites, path],
+ })
+ setFavoritesOpen(true)
+ }
+ } catch {
+ if (mounted.current && current === generation.current)
+ setPickerFailed(true)
+ } finally {
+ if (mounted.current && current === generation.current) {
+ pickInFlight.current = false
+ restoreAddFocus.current = true
+ setPicking(false)
+ onPickingChange?.(false)
+ }
+ }
+ }
+
+ const rows = (paths: string[], recent: boolean) =>
+ paths.length === 0 ? (
+ <p className="px-2 py-2 text-xs text-muted-foreground">
+ {t(
+ recent
+ ? 'directoryPreferences.emptyRecent'
+ : 'directoryPreferences.emptyFavorites'
+ )}
+ </p>
+ ) : (
+ <ul className="divide-y rounded-md border">
+ {paths.map((path) => {
+ const favorite = preferences.favorites.includes(path)
+ return (
+ <li key={path} className="flex items-center gap-2 px-2 py-1">
+ <Folder className="size-4 shrink-0 text-muted-foreground" />
+ <span
+ dir="ltr"
+ title={path}
+ className="min-w-0 flex-1 truncate text-xs whitespace-pre"
+ >
+ {path}
+ </span>
+ {recent && (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ disabled={busy || favorite || full}
+ aria-label={`${t(favorite ? 'directoryPreferences.alreadyFavorite' : 'directoryPreferences.favoriteRecent')} ${path}`}
+ title={t(
+ favorite
+ ? 'directoryPreferences.alreadyFavorite'
+ : 'directoryPreferences.favoriteRecent'
+ )}
+ onClick={() =>
+ change({
+ ...preferences,
+ favorites: [...preferences.favorites, path],
+ })
+ }
+ >
+ <Star className={favorite ? 'fill-current' : undefined} />
+ </Button>
+ )}
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ disabled={busy}
+ aria-label={`${t(recent ? 'directoryPreferences.removeRecent' : 'directoryPreferences.removeFavorite')} ${path}`}
+ title={t(
+ recent
+ ? 'directoryPreferences.removeRecent'
+ : 'directoryPreferences.removeFavorite'
+ )}
+ onClick={() =>
+ change(
+ recent
+ ? {
+ ...preferences,
+ recent: preferences.recent.filter(
+ (entry) => entry !== path
+ ),
+ }
+ : {
+ ...preferences,
+ favorites: preferences.favorites.filter(
+ (entry) => entry !== path
+ ),
+ }
+ )
+ }
+ >
+ <Trash2 />
+ </Button>
+ </li>
+ )
+ })}
+ </ul>
+ )
+
+ return (
+ <div
+ ref={content}
+ tabIndex={-1}
+ className="space-y-3 outline-none"
+ data-testid="directory-preferences-section"
+ >
+ {pickerFailed && (
+ <p role="alert" className="text-xs text-destructive">
+ {t('directoryPreferences.pickerFailed')}
+ </p>
+ )}
+ <Collapsible open={favoritesOpen} onOpenChange={setFavoritesOpen}>
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <CollapsibleTrigger
+ disabled={busy}
+ className="flex min-w-0 items-center gap-1 text-xs font-medium"
+ >
+ <ChevronRight
+ className={`size-3.5 shrink-0 ${favoritesOpen ? 'rotate-90' : ''}`}
+ />
+ {t('directoryPreferences.favorites')}
+ <span className="font-normal text-muted-foreground">
+ {preferences.favorites.length}/{DIRECTORY_FAVORITES_LIMIT}
+ </span>
+ </CollapsibleTrigger>
+ <Button
+ ref={add}
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={busy || full}
+ onClick={() => void addFavorite()}
+ >
+ <FolderPlus />
+ {t('directoryPreferences.addFavorite')}
+ </Button>
+ </div>
+ <CollapsibleContent>
+ {full && (
+ <p className="mb-2 text-xs text-muted-foreground">
+ {t('directoryPreferences.limitHint', {
+ count: DIRECTORY_FAVORITES_LIMIT,
+ })}
+ </p>
+ )}
+ {rows(preferences.favorites, false)}
+ </CollapsibleContent>
+ </Collapsible>
+ <Collapsible open={recentOpen} onOpenChange={setRecentOpen}>
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <CollapsibleTrigger
+ disabled={busy}
+ className="flex min-w-0 items-center gap-1 text-xs font-medium"
+ >
+ <ChevronRight
+ className={`size-3.5 shrink-0 ${recentOpen ? 'rotate-90' : ''}`}
+ />
+ {t('directoryPreferences.recent')}
+ <span className="font-normal text-muted-foreground">
+ {preferences.recent.length}/{DIRECTORY_RECENT_LIMIT}
+ </span>
+ </CollapsibleTrigger>
+ {recentOpen && (
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={busy || preferences.recent.length === 0}
+ onClick={() => change({ ...preferences, recent: [] })}
+ >
+ {t('directoryPreferences.clearRecent')}
+ </Button>
+ )}
+ </div>
+ <CollapsibleContent>
+ {rows(preferences.recent, true)}
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ )
+}
diff --git a/src/renderer/features/directory-preferences/use-directory-preferences-draft.test.tsx b/src/renderer/features/directory-preferences/use-directory-preferences-draft.test.tsx
new file mode 100644
index 00000000..fd54aeea
--- /dev/null
+++ b/src/renderer/features/directory-preferences/use-directory-preferences-draft.test.tsx
@@ -0,0 +1,305 @@
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type {
+ GeneralSettingsSnapshot,
+ SaveGeneralSettingsRequest,
+} from '@shared/schemas/general-settings'
+import { generalSettingsSnapshot } from '@test-utils/general-settings'
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import { StrictMode } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import {
+ DIRECTORY_DRAFT_TIMEOUT,
+ GENERAL_SETTINGS_SAVE_ATTEMPTS,
+ useDirectoryPreferencesDraft,
+} from './use-directory-preferences-draft'
+
+vi.mock('@renderer/lib/transport', () => ({ transport: { invoke: vi.fn() } }))
+const initial = { favorites: ['/old'], recent: ['/seen'] }
+const ok = (preferences = initial) => ({
+ ok: true as const,
+ value: generalSettingsSnapshot(preferences),
+})
+beforeEach(() => {
+ vi.mocked(transport.invoke).mockReset().mockResolvedValue(ok())
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+function host() {
+ let revision = 1
+ let snapshot = generalSettingsSnapshot(initial)
+ const bump = () => {
+ snapshot.revision = `00000000-0000-4000-8000-${String(++revision).padStart(12, '0')}`
+ }
+ const commit = (raw: unknown) => {
+ const request = raw as SaveGeneralSettingsRequest
+ if (request.expectedRevision !== snapshot.revision)
+ return {
+ ok: false as const,
+ error: { code: 'conflict' as const },
+ snapshot: structuredClone(snapshot),
+ }
+ const { app, directories } = request
+ snapshot.app = { ...snapshot.app, ...app }
+ snapshot.directoryPreferences = {
+ favorites: [
+ ...new Set([
+ ...snapshot.directoryPreferences.favorites.filter(
+ (p) => !directories.removeFavorites.includes(p)
+ ),
+ ...directories.addFavorites,
+ ]),
+ ],
+ recent: snapshot.directoryPreferences.recent.filter(
+ (p) => !directories.removeRecent.includes(p)
+ ),
+ }
+ bump()
+ return { ok: true as const, value: structuredClone(snapshot) }
+ }
+ vi.mocked(transport.invoke).mockImplementation(async (channel, request) =>
+ channel === Queries.GetGeneralSettingsDraft
+ ? { ok: true, value: structuredClone(snapshot) }
+ : commit(request)
+ )
+ return {
+ commit,
+ get: () => snapshot,
+ replace: (next: GeneralSettingsSnapshot) => {
+ snapshot = next
+ bump()
+ },
+ }
+}
+
+it('survives StrictMode replay and ignores the superseded initial snapshot', async () => {
+ let release!: (value: unknown) => void
+ vi.mocked(transport.invoke)
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve
+ })
+ )
+ .mockResolvedValueOnce(ok({ favorites: ['/latest'], recent: [] }))
+ const { result } = renderHook(useDirectoryPreferencesDraft, {
+ wrapper: StrictMode,
+ })
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ await act(async () => release(ok()))
+ expect(result.current.preferences.favorites).toEqual(['/latest'])
+})
+
+it('bounds initial reads and requires a valid snapshot before Save', async () => {
+ vi.useFakeTimers()
+ let release!: (value: unknown) => void
+ vi.mocked(transport.invoke).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve
+ })
+ )
+ const { result } = renderHook(useDirectoryPreferencesDraft)
+ await act(async () => vi.advanceTimersByTimeAsync(DIRECTORY_DRAFT_TIMEOUT))
+ expect(result.current.error).toBe('unavailable')
+ expect(await result.current.save()).toBe(false)
+ await act(async () => release(ok()))
+ expect(result.current.ready).toBe(false)
+ await act(async () => result.current.refresh())
+ expect(result.current.ready).toBe(true)
+})
+
+it('restores a deleted favorite after a committed reply was lost, preserving unrelated remote additions', async () => {
+ const h = host()
+ const { result } = renderHook(useDirectoryPreferencesDraft)
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ act(() =>
+ result.current.setPreferences({ favorites: [], recent: initial.recent })
+ )
+ vi.mocked(transport.invoke).mockImplementationOnce(
+ async (_channel, request) => {
+ h.commit(request)
+ throw new Error('reply lost')
+ }
+ )
+ await act(async () => expect(await result.current.save()).toBe(false))
+ h.replace({
+ ...h.get(),
+ directoryPreferences: {
+ favorites: ['/remote'],
+ recent: ['/new-use', '/seen'],
+ },
+ })
+ act(() => result.current.setPreferences(initial))
+ await act(async () => expect(await result.current.save()).toBe(true))
+ expect(h.get().directoryPreferences).toEqual({
+ favorites: ['/remote', '/old'],
+ recent: ['/new-use', '/seen'],
+ })
+})
+
+it('fences an original request still validating when a compensating no-op succeeds first', async () => {
+ const h = host()
+ const { result } = renderHook(useDirectoryPreferencesDraft)
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ act(() =>
+ result.current.setPreferences({ ...initial, favorites: ['/old', '/new'] })
+ )
+ let release!: () => void
+ let lateResult: unknown
+ vi.mocked(transport.invoke).mockImplementationOnce(
+ (_channel, request) =>
+ new Promise((resolve) => {
+ release = () => {
+ lateResult = h.commit(request)
+ resolve(lateResult)
+ }
+ })
+ )
+ vi.useFakeTimers()
+ let first!: Promise<boolean>
+ act(() => {
+ first = result.current.save()
+ })
+ await act(async () => vi.advanceTimersByTimeAsync(DIRECTORY_DRAFT_TIMEOUT))
+ expect(await first).toBe(false)
+ act(() => result.current.setPreferences(initial))
+ await act(async () => expect(await result.current.save()).toBe(true))
+ await act(async () => release())
+ expect(lateResult).toMatchObject({ ok: false, error: { code: 'conflict' } })
+ expect(h.get().directoryPreferences).toEqual(initial)
+ expect(result.current.preferences).toEqual(initial)
+})
+
+it('retains reverted submitted intent through Retry even when it equals the refreshed host value', async () => {
+ const h = host()
+ const { result } = renderHook(useDirectoryPreferencesDraft)
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ act(() =>
+ result.current.setPreferences({ ...initial, favorites: ['/old', '/new'] })
+ )
+ vi.mocked(transport.invoke).mockRejectedValueOnce(
+ new Error('unknown request')
+ )
+ await act(async () => result.current.save())
+ act(() => result.current.setPreferences(initial))
+ await act(async () => result.current.refresh())
+ const before = h.get().revision
+ await act(async () => expect(await result.current.save()).toBe(true))
+ expect(h.get().revision).not.toBe(before)
+ const request = vi
+ .mocked(transport.invoke)
+ .mock.calls.at(-1)?.[1] as SaveGeneralSettingsRequest
+ expect(request.directories).toEqual({
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ })
+})
+
+it('rebases explicit removals against a refreshed snapshot while keeping new remote rows', async () => {
+ const h = host()
+ const { result } = renderHook(useDirectoryPreferencesDraft)
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ act(() =>
+ result.current.setPreferences({ favorites: ['/local'], recent: [] })
+ )
+ h.replace({
+ ...h.get(),
+ directoryPreferences: {
+ favorites: ['/old', '/remote'],
+ recent: ['/new-use', '/seen'],
+ },
+ })
+ await act(async () => result.current.refresh())
+ expect(result.current.preferences).toEqual({
+ favorites: ['/remote', '/local'],
+ recent: ['/new-use'],
+ })
+ await act(async () => result.current.save())
+ expect(h.get().directoryPreferences).toEqual(result.current.preferences)
+})
+
+it('retries runtime fields after an acknowledged commit and restores an originally clean boolean', async () => {
+ const h = host()
+ let values = { ...h.get().app }
+ let dirty: SaveGeneralSettingsRequest['app'] = {}
+ const rebase = vi.fn((baseline, intent) => {
+ values = { ...baseline, ...intent }
+ dirty = {}
+ })
+ const { result } = renderHook(() =>
+ useDirectoryPreferencesDraft({
+ getAppDraft: () => ({ values, dirty }),
+ onAppRebase: rebase,
+ })
+ )
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ values.notifyOnError = false
+ dirty = { notifyOnError: false }
+ vi.mocked(transport.invoke).mockImplementationOnce(
+ async (_channel, request) => {
+ const saved = h.commit(request)
+ return {
+ ok: false,
+ error: { code: 'unavailable' },
+ snapshot: saved.ok ? saved.value : saved.snapshot,
+ }
+ }
+ )
+ await act(async () => expect(await result.current.save()).toBe(false))
+ expect(dirty).toEqual({})
+ // Even matching the known committed baseline must repeat the submitted field
+ // so its runtime effect can be reapplied.
+ await act(async () => expect(await result.current.save()).toBe(true))
+ expect(vi.mocked(transport.invoke).mock.calls.at(-1)?.[1]).toMatchObject({
+ app: { notifyOnError: false },
+ })
+ values.notifyOnError = true
+ dirty = { notifyOnError: true }
+ vi.mocked(transport.invoke).mockImplementationOnce(
+ async (_channel, request) => {
+ h.commit(request)
+ throw new Error('lost')
+ }
+ )
+ await act(async () => result.current.save())
+ values.notifyOnError = false
+ dirty = {}
+ await act(async () => expect(await result.current.save()).toBe(true))
+ expect(h.get().app.notifyOnError).toBe(false)
+})
+
+it('stops after bounded conflicts without discarding the current draft', async () => {
+ host()
+ const { result } = renderHook(useDirectoryPreferencesDraft)
+ await waitFor(() => expect(result.current.ready).toBe(true))
+ act(() =>
+ result.current.setPreferences({ favorites: ['/local'], recent: [] })
+ )
+ vi.mocked(transport.invoke).mockImplementation(async () => ({
+ ok: false,
+ error: { code: 'conflict' },
+ snapshot: generalSettingsSnapshot({
+ favorites: ['/old', '/remote'],
+ recent: ['/seen'],
+ }),
+ }))
+ await act(async () => expect(await result.current.save()).toBe(false))
+ expect(result.current.error).toBe('conflict')
+ expect(result.current.preferences).toEqual({
+ favorites: ['/remote', '/local'],
+ recent: [],
+ })
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(
+ ([channel]) => channel === Commands.SaveGeneralSettings
+ )
+ ).toHaveLength(GENERAL_SETTINGS_SAVE_ATTEMPTS)
+})
diff --git a/src/renderer/features/directory-preferences/use-directory-preferences-draft.ts b/src/renderer/features/directory-preferences/use-directory-preferences-draft.ts
new file mode 100644
index 00000000..7f011763
--- /dev/null
+++ b/src/renderer/features/directory-preferences/use-directory-preferences-draft.ts
@@ -0,0 +1,281 @@
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { DirectoryPreferences } from '@shared/schemas/directory-preferences'
+import {
+ type GeneralSettingsApp,
+ type GeneralSettingsErrorCode,
+ GeneralSettingsResultSchema,
+ type GeneralSettingsSnapshot,
+ type SaveGeneralSettingsRequest,
+} from '@shared/schemas/general-settings'
+import { useCallback, useEffect, useRef, useState } from 'react'
+
+export const DIRECTORY_DRAFT_TIMEOUT = 20_000
+export const GENERAL_SETTINGS_SAVE_ATTEMPTS = 3
+
+type AppPatch = SaveGeneralSettingsRequest['app']
+type AppKey = keyof GeneralSettingsApp
+interface AppDraft {
+ values: GeneralSettingsApp
+ dirty: AppPatch
+}
+interface Options {
+ getAppDraft?: () => AppDraft
+ onAppRebase?: (baseline: GeneralSettingsApp, intent: AppPatch) => void
+}
+
+export function directoryPreferenceEdits(
+ baseline: DirectoryPreferences,
+ draft: DirectoryPreferences
+): SaveGeneralSettingsRequest['directories'] {
+ return {
+ addFavorites: draft.favorites.filter(
+ (path) => !baseline.favorites.includes(path)
+ ),
+ removeFavorites: baseline.favorites.filter(
+ (path) => !draft.favorites.includes(path)
+ ),
+ removeRecent: baseline.recent.filter(
+ (path) => !draft.recent.includes(path)
+ ),
+ }
+}
+
+async function request(
+ channel:
+ | typeof Queries.GetGeneralSettingsDraft
+ | typeof Commands.SaveGeneralSettings,
+ args: unknown
+) {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ const value = await Promise.race([
+ Promise.resolve().then(() => transport.invoke(channel, args)),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error('General settings request timed out')),
+ DIRECTORY_DRAFT_TIMEOUT
+ )
+ }),
+ ])
+ return GeneralSettingsResultSchema.parse(value)
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+type State = {
+ baseline: GeneralSettingsSnapshot | null
+ preferences: DirectoryPreferences
+ loading: boolean
+ saving: boolean
+ error: GeneralSettingsErrorCode | null
+}
+type Intent = {
+ favorites: Map<string, boolean>
+ removeRecent: Set<string>
+ app: AppPatch
+}
+
+function applyDirectoryIntent(
+ authority: DirectoryPreferences,
+ intent: Intent
+): DirectoryPreferences {
+ return {
+ favorites: [
+ ...authority.favorites.filter(
+ (path) => intent.favorites.get(path) !== false
+ ),
+ ...[...intent.favorites]
+ .filter(
+ ([path, present]) => present && !authority.favorites.includes(path)
+ )
+ .map(([path]) => path),
+ ],
+ recent: authority.recent.filter((path) => !intent.removeRecent.has(path)),
+ }
+}
+
+/** A draft owns explicit intent; a queue-checked revision fences uncertain writes. */
+export function useDirectoryPreferencesDraft(options: Options = {}) {
+ const [state, setState] = useState<State>({
+ baseline: null,
+ preferences: { favorites: [], recent: [] },
+ loading: true,
+ saving: false,
+ error: null,
+ })
+ const latest = useRef(state)
+ const callbacks = useRef(options)
+ callbacks.current = options
+ const mounted = useRef(false)
+ const generation = useRef(0)
+ const saving = useRef(false)
+ // A reply can be lost after committing. Keep submitted keys even when the
+ // user restores their old values, and until a successful CAS fences the write.
+ const submitted = useRef({
+ favorites: new Set<string>(),
+ recent: new Set<string>(),
+ app: new Set<AppKey>(),
+ })
+ const update = useCallback((patch: Partial<State>) => {
+ latest.current = { ...latest.current, ...patch }
+ setState(latest.current)
+ }, [])
+ const captureIntent = useCallback((): Intent => {
+ const current = latest.current
+ const baseline = current.baseline?.directoryPreferences ?? {
+ favorites: [],
+ recent: [],
+ }
+ const edits = directoryPreferenceEdits(baseline, current.preferences)
+ const paths = new Set([
+ ...submitted.current.favorites,
+ ...edits.addFavorites,
+ ...edits.removeFavorites,
+ ])
+ const appDraft = callbacks.current.getAppDraft?.()
+ const app: AppPatch = { ...appDraft?.dirty }
+ if (appDraft) {
+ for (const key of submitted.current.app)
+ Object.assign(app, { [key]: appDraft.values[key] })
+ }
+ return {
+ favorites: new Map(
+ [...paths].map((path) => [
+ path,
+ current.preferences.favorites.includes(path),
+ ])
+ ),
+ removeRecent: new Set([
+ ...submitted.current.recent,
+ ...edits.removeRecent,
+ ]),
+ app,
+ }
+ }, [])
+ const rebase = useCallback(
+ (authority: GeneralSettingsSnapshot, intent: Intent) => {
+ update({
+ baseline: authority,
+ preferences: applyDirectoryIntent(
+ authority.directoryPreferences,
+ intent
+ ),
+ })
+ callbacks.current.onAppRebase?.(authority.app, intent.app)
+ },
+ [update]
+ )
+
+ const refresh = useCallback(async () => {
+ if (saving.current) return
+ const current = ++generation.current
+ const intent = captureIntent()
+ update({ loading: true, error: null })
+ try {
+ const result = await request(Queries.GetGeneralSettingsDraft, {})
+ if (!mounted.current || current !== generation.current) return
+ if (result.ok) rebase(result.value, intent)
+ else update({ error: result.error.code })
+ } catch {
+ if (mounted.current && current === generation.current)
+ update({ error: 'unavailable' })
+ } finally {
+ if (mounted.current && current === generation.current)
+ update({ loading: false })
+ }
+ }, [captureIntent, rebase, update])
+
+ useEffect(() => {
+ mounted.current = true
+ void refresh()
+ return () => {
+ mounted.current = false
+ generation.current++
+ }
+ }, [refresh])
+
+ const setPreferences = useCallback(
+ (preferences: DirectoryPreferences) => {
+ if (!saving.current) update({ preferences })
+ },
+ [update]
+ )
+
+ const save = async () => {
+ let authority = latest.current.baseline
+ if (!authority || latest.current.loading || saving.current) return false
+ const intent = captureIntent()
+ for (const path of intent.favorites.keys())
+ submitted.current.favorites.add(path)
+ for (const path of intent.removeRecent) submitted.current.recent.add(path)
+ for (const key of Object.keys(intent.app) as AppKey[])
+ submitted.current.app.add(key)
+ const current = ++generation.current
+ saving.current = true
+ update({ saving: true, error: null })
+ try {
+ for (
+ let attempt = 0;
+ attempt < GENERAL_SETTINGS_SAVE_ATTEMPTS;
+ attempt++
+ ) {
+ // Never short-circuit an empty delta: it must advance the host revision
+ // before a previously timed-out request is allowed to finish validation.
+ const result = await request(Commands.SaveGeneralSettings, {
+ expectedRevision: authority.revision,
+ app: intent.app,
+ directories: directoryPreferenceEdits(
+ authority.directoryPreferences,
+ applyDirectoryIntent(authority.directoryPreferences, intent)
+ ),
+ })
+ if (!mounted.current || current !== generation.current) return false
+ if (result.ok) {
+ submitted.current = {
+ favorites: new Set(),
+ recent: new Set(),
+ app: new Set(),
+ }
+ rebase(result.value, {
+ favorites: new Map(),
+ removeRecent: new Set(),
+ app: {},
+ })
+ return true
+ }
+ if (result.snapshot) {
+ authority = result.snapshot
+ rebase(authority, intent)
+ }
+ if (
+ result.error.code !== 'conflict' ||
+ !result.snapshot ||
+ attempt + 1 === GENERAL_SETTINGS_SAVE_ATTEMPTS
+ ) {
+ update({ error: result.error.code })
+ return false
+ }
+ }
+ } catch {
+ if (mounted.current && current === generation.current)
+ update({ error: 'unavailable' })
+ } finally {
+ if (mounted.current && current === generation.current) {
+ saving.current = false
+ update({ saving: false })
+ }
+ }
+ return false
+ }
+
+ return {
+ ...state,
+ ready: state.baseline !== null,
+ setPreferences,
+ refresh,
+ save,
+ }
+}
diff --git a/src/renderer/features/web-directory-picker/directory-picker-controller.test.ts b/src/renderer/features/web-directory-picker/directory-picker-controller.test.ts
new file mode 100644
index 00000000..a859a051
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/directory-picker-controller.test.ts
@@ -0,0 +1,969 @@
+import type { DirectoryPreferencesStore } from '@renderer/lib/directory-preferences'
+import type { Transport } from '@renderer/lib/transport/types'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ DIRECTORY_OPERATION_TIMEOUT,
+ type DirectoryListing,
+ DirectoryPickerController,
+} from './directory-picker-controller'
+import { DirectorySortPreferences } from './directory-sort'
+
+function deferred() {
+ let resolve!: (value: unknown) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<unknown>((yes, no) => {
+ resolve = yes
+ reject = no
+ })
+ return { promise, resolve, reject }
+}
+
+function listing(
+ path = '/downloads',
+ children = ['Movies', 'Music'],
+ parentPath: string | null = null
+): DirectoryListing {
+ return {
+ path,
+ parentPath,
+ breadcrumbs: [{ name: 'Downloads', path }],
+ entries: children.map((name) => ({ name, path: `${path}/${name}` })),
+ truncated: false,
+ canCreate: true,
+ }
+}
+
+const success = (value: unknown) => ({ ok: true, value })
+const failure = (code: string) => ({ ok: false, error: { code } })
+const flush = () => vi.advanceTimersByTimeAsync(0)
+const controllers: DirectoryPickerController[] = []
+
+function harness(defaultPath: string | undefined = '/downloads') {
+ const eventListeners = new Map<string, (payload: unknown) => void>()
+ const preferences = {
+ mutate: vi.fn<DirectoryPreferencesStore['mutate']>(async () => true),
+ getSnapshot: vi.fn<DirectoryPreferencesStore['getSnapshot']>(() => ({
+ preferences: { favorites: [], recent: [] },
+ loading: false,
+ error: null,
+ })),
+ }
+ const responses = new Map<string, unknown[]>()
+ const invoke = vi.fn<Transport['invoke']>(async (channel, ...args) => {
+ const queued = responses.get(channel)
+ if (queued?.length) return queued.shift()
+ if (channel === Queries.ListServerDirectoryLocations) {
+ return success({ common: [], favorites: [], recent: [] })
+ }
+ if (channel === Queries.ListAllowedSaveDirs) {
+ return {
+ defaultPath: '/downloads',
+ paths: [{ path: '/downloads' }, { path: '/archive' }],
+ allowCustom: false,
+ }
+ }
+ if (channel === Queries.ListServerDirectories) {
+ const path = (args[0] as { path: string }).path
+ if (path === '/downloads') return success(listing())
+ if (path === '/downloads/Movies') {
+ return success(listing(path, ['HD'], '/downloads'))
+ }
+ if (path === '/downloads/Music') {
+ return success(listing(path, [], '/downloads'))
+ }
+ if (path === '/archive') return success(listing(path, []))
+ return failure('notFound')
+ }
+ if (channel === Queries.ValidateServerDirectory) return success(args[0])
+ throw new Error(`Unexpected invocation: ${channel}`)
+ })
+ const finish = vi.fn<(value: string | null) => void>()
+ const controller = new DirectoryPickerController(
+ {
+ invoke,
+ on: (channel, listener) => {
+ eventListeners.set(channel, listener)
+ },
+ off: (channel, listener) => {
+ if (eventListeners.get(channel) === listener)
+ eventListeners.delete(channel)
+ },
+ },
+ defaultPath,
+ finish,
+ preferences,
+ new DirectorySortPreferences(() => ({ getItem: () => null, setItem() {} }))
+ )
+ controllers.push(controller)
+ return {
+ controller,
+ invoke,
+ finish,
+ preferences,
+ event(value: unknown) {
+ eventListeners.get(Events.DirectoryPreferencesChanged)?.(value)
+ },
+ queue(channel: string, ...values: unknown[]) {
+ responses.set(channel, [...(responses.get(channel) ?? []), ...values])
+ },
+ }
+}
+
+beforeEach(() => vi.useFakeTimers())
+afterEach(() => {
+ for (const controller of controllers.splice(0)) controller.dispose()
+ vi.useRealTimers()
+})
+
+describe('DirectoryPickerController', () => {
+ it('changes sorting locally, preserves selected identity and invalidates historical scroll offsets', async () => {
+ const h = harness()
+ await h.controller.start()
+ h.controller.select('/downloads/Music')
+ h.controller.setScrollOffset(800)
+ h.controller.navigate('/archive')
+ await flush()
+ const calls = h.invoke.mock.calls.length
+ const listing = h.controller.getSnapshot().listing
+ h.controller.changeSort({ by: 'name', direction: 'desc' })
+ expect(h.invoke).toHaveBeenCalledTimes(calls)
+ expect(h.controller.getSnapshot().listing).toBe(listing)
+ expect(
+ h.controller.getSnapshot().history.every((entry) => entry.offset === null)
+ ).toBe(true)
+ h.controller.history(-1)
+ await flush()
+ expect(h.controller.getSnapshot()).toMatchObject({
+ sort: { by: 'name', direction: 'desc' },
+ selected: '/downloads/Music',
+ restore: { offset: 0, reveal: '/downloads/Music' },
+ })
+ h.controller.changeSort({ by: 'modified', direction: 'asc' })
+ expect(h.controller.getSnapshot()).toMatchObject({
+ selected: '/downloads/Music',
+ restore: { offset: 0, reveal: '/downloads/Music' },
+ })
+ const snapshot = h.controller.getSnapshot()
+ h.controller.changeSort({ by: 'modified', direction: 'asc' })
+ expect(h.controller.getSnapshot()).toBe(snapshot)
+ })
+
+ it('ignores delayed sorting after disposal and while editing', async () => {
+ const h = harness()
+ await h.controller.start()
+ h.controller.editPath()
+ const editing = h.controller.getSnapshot()
+ h.controller.changeSort({ by: 'name', direction: 'desc' })
+ expect(h.controller.getSnapshot()).toBe(editing)
+ h.controller.cancelEditor()
+ h.controller.dispose()
+ const disposed = h.controller.getSnapshot()
+ h.controller.changeSort({ by: 'name', direction: 'desc' })
+ expect(h.controller.getSnapshot()).toBe(disposed)
+ })
+ it('keeps bootstrap roots navigable when optional locations fail', async () => {
+ const h = harness()
+ h.queue(Queries.ListServerDirectoryLocations, failure('unavailable'))
+ await h.controller.start()
+ expect(h.controller.getSnapshot().locations).toBeNull()
+ h.controller.navigateLocation('/archive')
+ await flush()
+ expect(h.controller.getSnapshot().listing?.path).toBe('/archive')
+ })
+ it('keeps retained locations display-only during refresh while ordinary navigation remains available', async () => {
+ const h = harness()
+ const locations = {
+ common: [{ kind: 'home', path: '/downloads/Movies' }],
+ favorites: [],
+ recent: [],
+ }
+ h.queue(Queries.ListServerDirectoryLocations, success(locations))
+ await h.controller.start()
+ const snapshot = h.controller.getSnapshot().locations
+ const pending = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, pending.promise)
+ h.event({ favorites: [], recent: [] })
+ expect(h.controller.getSnapshot().locations).toBe(snapshot)
+ expect(h.controller.getSnapshot().locationsLoading).toBe(true)
+ const listings = () =>
+ h.invoke.mock.calls.filter(
+ ([channel]) => channel === Queries.ListServerDirectories
+ )
+ const before = listings().length
+ h.controller.navigateLocation('/downloads/Movies')
+ await h.controller.toggleFavorite()
+ expect(listings()).toHaveLength(before)
+ expect(h.preferences.mutate).not.toHaveBeenCalled()
+ h.controller.navigate('/archive')
+ await flush()
+ expect(h.controller.getSnapshot().listing?.path).toBe('/archive')
+ pending.resolve(success(locations))
+ await flush()
+ h.controller.navigateLocation('/downloads/Movies')
+ await flush()
+ expect(h.controller.getSnapshot().listing?.path).toBe('/downloads/Movies')
+ })
+
+ it('reuses the authorization query triggered by this exact committed favorite snapshot', async () => {
+ const h = harness()
+ await h.controller.start()
+ const committed = { favorites: ['/downloads'], recent: [] }
+ h.preferences.mutate.mockImplementation(async (_action, onCommitted) => {
+ h.event(committed)
+ await flush()
+ onCommitted?.(committed)
+ return true
+ })
+ await h.controller.toggleFavorite()
+ expect(
+ h.invoke.mock.calls.filter(
+ ([channel]) => channel === Queries.ListServerDirectoryLocations
+ )
+ ).toHaveLength(2)
+ })
+
+ it('keeps browsing and confirmation independent of optional locations timeouts', async () => {
+ const h = harness()
+ h.queue(Queries.ListServerDirectoryLocations, new Promise(() => {}))
+ await h.controller.start()
+ expect(h.controller.getSnapshot()).toMatchObject({
+ busy: null,
+ locationsLoading: true,
+ listing: { path: '/downloads' },
+ })
+ h.controller.navigate('/archive')
+ await flush()
+ await vi.advanceTimersByTimeAsync(DIRECTORY_OPERATION_TIMEOUT)
+ expect(h.controller.getSnapshot()).toMatchObject({
+ busy: null,
+ locationsLoading: false,
+ locationsError: 'unavailable',
+ listing: { path: '/archive' },
+ })
+ h.controller.refreshLocations()
+ await flush()
+ expect(h.controller.getSnapshot().locationsError).toBeNull()
+ await h.controller.confirm()
+ expect(h.finish).toHaveBeenCalledExactlyOnceWith('/archive')
+ expect(h.preferences.mutate).not.toHaveBeenCalled()
+ })
+
+ it('invalidates pending locations immediately on preference events without invalidating navigation', async () => {
+ const h = harness()
+ const stale = deferred()
+ const fresh = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, stale.promise, fresh.promise)
+ await h.controller.start()
+ h.controller.navigate('/archive')
+ h.event({ favorites: [], recent: [] })
+ await flush()
+ stale.resolve(
+ success({
+ common: [],
+ favorites: [{ name: 'Old', path: '/old', sourcePaths: ['/old'] }],
+ recent: [],
+ })
+ )
+ await flush()
+ expect(h.controller.getSnapshot()).toMatchObject({
+ locations: null,
+ locationsLoading: true,
+ listing: { path: '/archive' },
+ })
+ fresh.resolve(success({ common: [], favorites: [], recent: [] }))
+ await flush()
+ expect(h.controller.getSnapshot().locations?.favorites).toEqual([])
+ })
+
+ it('favorites the browsed folder rather than its selected child and permits cancellation while pending', async () => {
+ const h = harness()
+ await h.controller.start()
+ h.controller.select('/downloads/Movies')
+ let complete!: (value: boolean) => void
+ h.preferences.mutate.mockReturnValueOnce(
+ new Promise((resolve) => {
+ complete = resolve
+ })
+ )
+ const action = h.controller.toggleFavorite()
+ await h.controller.toggleFavorite()
+ expect(h.preferences.mutate).toHaveBeenCalledExactlyOnceWith(
+ {
+ action: 'addFavorite',
+ path: '/downloads',
+ },
+ expect.any(Function)
+ )
+ expect(h.controller.getSnapshot().favoriteBusy).toBe(true)
+ h.controller.cancel()
+ complete(true)
+ await action
+ expect(h.finish).toHaveBeenCalledExactlyOnceWith(null)
+ expect(
+ h.invoke.mock.calls.filter(
+ ([channel]) => channel === Queries.ListServerDirectoryLocations
+ )
+ ).toHaveLength(1)
+ })
+
+ it.each(['/downloads', '/display-alias'])(
+ 'removes all saved identities of a canonical group while browsing %s',
+ async (path) => {
+ const h = harness(path)
+ const sourcePaths = ['/downloads', '/canonical/downloads']
+ h.queue(Queries.ListServerDirectories, success(listing(path)))
+ h.queue(
+ Queries.ListServerDirectoryLocations,
+ success({
+ common: [],
+ favorites: [
+ { name: 'Downloads', path: '/display-alias', sourcePaths },
+ ],
+ recent: [],
+ })
+ )
+ await h.controller.start()
+ expect(h.controller.currentFavorite?.sourcePaths).toEqual(sourcePaths)
+ await h.controller.toggleFavorite()
+ expect(h.preferences.mutate).toHaveBeenCalledExactlyOnceWith(
+ {
+ action: 'removeFavorite',
+ paths: sourcePaths,
+ },
+ expect.any(Function)
+ )
+ }
+ )
+
+ it('keeps a failed favorite mutation visible and excludes editor interactions', async () => {
+ const h = harness()
+ await h.controller.start()
+ h.controller.editPath()
+ await h.controller.toggleFavorite()
+ expect(h.preferences.mutate).not.toHaveBeenCalled()
+ h.controller.cancelEditor()
+ h.preferences.mutate.mockResolvedValueOnce(false)
+ h.preferences.getSnapshot.mockReturnValueOnce({
+ preferences: { favorites: [], recent: [] },
+ loading: false,
+ error: 'limitReached',
+ })
+ await h.controller.toggleFavorite()
+ expect(h.controller.getSnapshot()).toMatchObject({
+ favoriteBusy: false,
+ favoriteError: 'limitReached',
+ busy: null,
+ })
+ })
+
+ it('uses the initiating path and initially targets the current directory without selecting a child', async () => {
+ const { controller, invoke, finish } = harness('/downloads/Movies')
+ await controller.start()
+
+ expect(invoke.mock.calls).toEqual([
+ [Queries.ListServerDirectoryLocations, {}],
+ [Queries.ListAllowedSaveDirs],
+ [
+ Queries.ListServerDirectories,
+ { path: '/downloads/Movies', showHidden: false },
+ ],
+ ])
+ expect(controller.getSnapshot()).toMatchObject({
+ listing: { path: '/downloads/Movies' },
+ selected: null,
+ busy: null,
+ notice: null,
+ historyIndex: 0,
+ })
+ expect(controller.target).toBe('/downloads/Movies')
+ await controller.confirm()
+ expect(finish).toHaveBeenCalledExactlyOnceWith('/downloads/Movies')
+ })
+
+ it('explains fallback and tries the configured default before distinct allowed roots', async () => {
+ const { controller, invoke, queue } = harness('/missing')
+ queue(
+ Queries.ListServerDirectories,
+ failure('notFound'),
+ failure('permissionDenied'),
+ failure('notFound')
+ )
+ await controller.start()
+
+ expect(invoke.mock.calls.slice(2)).toEqual([
+ [Queries.ListServerDirectories, { path: '/missing', showHidden: false }],
+ [
+ Queries.ListServerDirectories,
+ { path: '/downloads', showHidden: false },
+ ],
+ [Queries.ListServerDirectories, { path: '/archive', showHidden: false }],
+ ])
+ expect(controller.getSnapshot()).toMatchObject({
+ listing: null,
+ error: 'notFound',
+ busy: null,
+ })
+
+ await controller.start()
+ expect(controller.getSnapshot()).toMatchObject({
+ listing: { path: '/downloads' },
+ notice: 'fallback',
+ })
+ })
+
+ it('treats only the empty string as a default sentinel and preserves literal path whitespace', async () => {
+ const { controller, invoke, queue } = harness(' ')
+ queue(Queries.ListServerDirectories, success(listing(' ', [])))
+ await controller.start()
+ expect(invoke).toHaveBeenLastCalledWith(Queries.ListServerDirectories, {
+ path: ' ',
+ showHidden: false,
+ })
+ expect(controller.target).toBe(' ')
+
+ const empty = harness('')
+ await empty.controller.start()
+ expect(empty.invoke).toHaveBeenLastCalledWith(
+ Queries.ListServerDirectories,
+ { path: '/downloads', showHidden: false }
+ )
+ })
+
+ it('rejects malformed bootstrap data and retries without accepting an arbitrary path', async () => {
+ const { controller, invoke, queue } = harness('/downloads')
+ queue(Queries.ListAllowedSaveDirs, {
+ defaultPath: '/downloads',
+ allowCustom: true,
+ })
+ await controller.start()
+ expect(controller.getSnapshot()).toMatchObject({
+ bootstrap: null,
+ listing: null,
+ busy: null,
+ error: 'unavailable',
+ })
+ await controller.confirm()
+ expect(invoke).toHaveBeenCalledTimes(2)
+ controller.refresh()
+ await flush()
+ expect(controller.target).toBe('/downloads')
+ })
+
+ it('restores selection and scroll through history, selects the departed child on Up, and drops a forward branch', async () => {
+ const { controller } = harness()
+ await controller.start()
+ controller.select('/downloads/Movies')
+ controller.setScrollOffset(144)
+ controller.refresh()
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ selected: '/downloads/Movies',
+ restore: { offset: 144, reveal: null },
+ })
+ controller.navigate('/downloads/Movies')
+ await flush()
+ controller.select('/downloads/Movies/HD')
+ controller.setScrollOffset(72)
+
+ controller.history(-1)
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ selected: '/downloads/Movies',
+ restore: { offset: 144, reveal: null },
+ })
+ controller.history(1)
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ selected: '/downloads/Movies/HD',
+ restore: { offset: 72, reveal: null },
+ })
+ controller.up()
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ listing: { path: '/downloads' },
+ selected: '/downloads/Movies',
+ restore: { reveal: '/downloads/Movies' },
+ })
+
+ controller.history(-1)
+ await flush()
+ controller.navigate('/archive')
+ await flush()
+ expect(controller.getSnapshot().history.map((entry) => entry.path)).toEqual(
+ ['/downloads', '/downloads/Movies', '/archive']
+ )
+ controller.history(1)
+ expect(controller.getSnapshot().busy).toBeNull()
+ })
+
+ it('keeps a coherent previous view on failed navigation and clears vanished history selections', async () => {
+ const { controller, queue } = harness()
+ await controller.start()
+ controller.select('/downloads/Movies')
+ const original = controller.getSnapshot().listing
+ controller.navigate('/missing')
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ listing: original,
+ selected: '/downloads/Movies',
+ error: 'notFound',
+ historyIndex: 0,
+ })
+
+ controller.navigate('/archive')
+ await flush()
+ queue(
+ Queries.ListServerDirectories,
+ success(listing('/downloads', ['Music']))
+ )
+ controller.history(-1)
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ selected: null,
+ restore: { reveal: null },
+ })
+ })
+
+ it('freezes validation target and every conflicting action until validation succeeds', async () => {
+ const { controller, invoke, finish, queue } = harness()
+ await controller.start()
+ controller.select('/downloads/Movies')
+ const validation = deferred()
+ queue(Queries.ValidateServerDirectory, validation.promise)
+ const pending = controller.confirm()
+ await flush()
+ controller.select('/downloads/Music')
+ controller.navigate('/archive')
+ controller.up()
+ controller.history(-1)
+ controller.filter(true)
+ controller.refresh()
+ controller.editPath()
+ controller.editName()
+ await controller.confirm()
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: 'validate',
+ selected: '/downloads/Movies',
+ editor: null,
+ showHidden: false,
+ })
+ expect(invoke).toHaveBeenCalledTimes(4)
+ validation.resolve(success({ path: '/downloads/Movies' }))
+ await pending
+ expect(finish).toHaveBeenCalledExactlyOnceWith('/downloads/Movies')
+ })
+
+ it('allows cancellation during validation and ignores its late response', async () => {
+ const { controller, finish, queue } = harness()
+ await controller.start()
+ const validation = deferred()
+ queue(Queries.ValidateServerDirectory, validation.promise)
+ const pending = controller.confirm()
+ await flush()
+ controller.cancel()
+ validation.resolve(success({ path: '/downloads' }))
+ await pending
+ expect(finish).toHaveBeenCalledExactlyOnceWith(null)
+ })
+
+ it('releases failed validation for correction without settling the picker', async () => {
+ const { controller, finish, queue } = harness()
+ await controller.start()
+ queue(Queries.ValidateServerDirectory, failure('permissionDenied'))
+ await controller.confirm()
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: null,
+ error: 'permissionDenied',
+ })
+ expect(finish).not.toHaveBeenCalled()
+ controller.select('/downloads/Music')
+ await controller.confirm()
+ expect(finish).toHaveBeenCalledExactlyOnceWith('/downloads/Music')
+ })
+
+ it('times out bootstrap at 20 seconds and ignores success after a retry has completed', async () => {
+ const { controller, queue } = harness()
+ const bootstrap = deferred()
+ queue(Queries.ListAllowedSaveDirs, bootstrap.promise)
+ const pending = controller.start()
+ await flush()
+ await vi.advanceTimersByTimeAsync(DIRECTORY_OPERATION_TIMEOUT - 1)
+ expect(controller.getSnapshot().busy).toBe('bootstrap')
+ await vi.advanceTimersByTimeAsync(1)
+ await pending
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: null,
+ error: 'unavailable',
+ })
+ await controller.start()
+ const recovered = controller.getSnapshot()
+ bootstrap.resolve({
+ paths: [{ path: '/old' }],
+ defaultPath: '/old',
+ allowCustom: true,
+ })
+ await flush()
+ expect(controller.getSnapshot()).toBe(recovered)
+ })
+
+ it('expires navigation and validation independently and rejects late successes', async () => {
+ const { controller, finish, queue } = harness()
+ await controller.start()
+ const navigation = deferred()
+ queue(Queries.ListServerDirectories, navigation.promise)
+ controller.navigate('/archive')
+ await flush()
+ await vi.advanceTimersByTimeAsync(DIRECTORY_OPERATION_TIMEOUT)
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: null,
+ error: 'unavailable',
+ listing: { path: '/downloads' },
+ })
+ navigation.resolve(success(listing('/archive', [])))
+ await flush()
+ expect(controller.target).toBe('/downloads')
+
+ const validation = deferred()
+ queue(Queries.ValidateServerDirectory, validation.promise)
+ const pending = controller.confirm()
+ await flush()
+ await vi.advanceTimersByTimeAsync(DIRECTORY_OPERATION_TIMEOUT)
+ await pending
+ controller.select('/downloads/Music')
+ validation.resolve(success({ path: '/downloads' }))
+ await flush()
+ expect(controller.target).toBe('/downloads/Music')
+ expect(finish).not.toHaveBeenCalled()
+ })
+
+ it('holds dismissal during creation, then blocks another creation in an unknown parent until refresh succeeds', async () => {
+ const { controller, invoke, finish, queue } = harness()
+ await controller.start()
+ const creation = deferred()
+ queue(Commands.CreateServerDirectory, creation.promise)
+ controller.editName()
+ controller.setEditorText('New folder')
+ controller.submitEditor()
+ controller.submitEditor()
+ await flush()
+ controller.cancel()
+ controller.cancelEditor()
+ controller.navigate('/archive')
+ expect(controller.getSnapshot().busy).toBe('create')
+ expect(finish).not.toHaveBeenCalled()
+ expect(
+ invoke.mock.calls.filter(
+ ([channel]) => channel === Commands.CreateServerDirectory
+ )
+ ).toHaveLength(1)
+
+ await vi.advanceTimersByTimeAsync(DIRECTORY_OPERATION_TIMEOUT)
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: null,
+ editor: null,
+ notice: 'unknownOutcome',
+ unknownParents: ['/downloads'],
+ })
+ const expired = controller.getSnapshot()
+ creation.resolve(
+ success({ name: 'New folder', path: '/downloads/New folder' })
+ )
+ await flush()
+ expect(controller.getSnapshot()).toBe(expired)
+ controller.editName()
+ expect(controller.getSnapshot().editor).toBeNull()
+
+ queue(Queries.ListServerDirectories, failure('unavailable'))
+ controller.refresh()
+ await flush()
+ controller.editName()
+ expect(controller.getSnapshot().editor).toBeNull()
+ controller.navigate('/archive')
+ await flush()
+ controller.editName()
+ expect(controller.getSnapshot().editor?.kind).toBe('name')
+ controller.cancelEditor()
+ controller.navigate('/downloads')
+ await flush()
+ controller.editName()
+ expect(controller.getSnapshot().editor).toBeNull()
+ controller.refresh()
+ await flush()
+ expect(controller.getSnapshot().unknownParents).toEqual([])
+ controller.editName()
+ expect(controller.getSnapshot().editor?.kind).toBe('name')
+ })
+
+ it.each(['transport', 'server', 'malformed'])(
+ 'treats %s creation ambiguity as unknown instead of exposing an automatic retry',
+ async (kind) => {
+ const { controller, queue } = harness()
+ await controller.start()
+ const reply = deferred()
+ queue(Commands.CreateServerDirectory, reply.promise)
+ controller.editName()
+ controller.setEditorText('New')
+ controller.submitEditor()
+ await flush()
+ if (kind === 'transport') reply.reject(new Error('Disconnected'))
+ else
+ reply.resolve(
+ kind === 'server' ? failure('creationOutcomeUnknown') : { ok: true }
+ )
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: null,
+ editor: null,
+ notice: 'unknownOutcome',
+ unknownParents: ['/downloads'],
+ })
+ controller.cancel()
+ }
+ )
+
+ it.each(['failed', 'capped'])(
+ 'preserves a known created child when its refresh is %s',
+ async (mode) => {
+ const { controller, invoke, queue } = harness()
+ await controller.start()
+ const child = { name: '.New ', path: '/downloads/.New ' }
+ queue(Commands.CreateServerDirectory, success(child))
+ queue(
+ Queries.ListServerDirectories,
+ mode === 'failed'
+ ? failure('permissionDenied')
+ : success({ ...listing(), truncated: true })
+ )
+ controller.editName()
+ controller.setEditorText(child.name)
+ controller.submitEditor()
+ await flush()
+ expect(invoke).toHaveBeenCalledWith(Commands.CreateServerDirectory, {
+ parentPath: '/downloads',
+ name: '.New ',
+ })
+ expect(invoke).toHaveBeenLastCalledWith(Queries.ListServerDirectories, {
+ path: '/downloads',
+ showHidden: true,
+ })
+ expect(controller.getSnapshot()).toMatchObject({
+ selected: child.path,
+ showHidden: true,
+ editor: null,
+ busy: null,
+ restore: { reveal: child.path },
+ })
+ expect(controller.getSnapshot().listing?.entries).toContainEqual(child)
+ expect(controller.getSnapshot().notice).toBe(
+ mode === 'failed' ? 'refreshAfterCreateFailed' : null
+ )
+ }
+ )
+
+ it('retains rejected creation text and parent so the user can correct the filename', async () => {
+ const { controller, invoke, queue } = harness()
+ await controller.start()
+ queue(
+ Commands.CreateServerDirectory,
+ failure('alreadyExists'),
+ success({ path: '/downloads/Other', name: 'Other' })
+ )
+ controller.editName()
+ controller.setEditorText('Movies')
+ controller.submitEditor()
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ busy: null,
+ editor: { kind: 'name', text: 'Movies', error: 'alreadyExists' },
+ listing: { path: '/downloads' },
+ })
+ controller.setEditorText('Other')
+ controller.submitEditor()
+ await flush()
+ expect(invoke).toHaveBeenCalledWith(Commands.CreateServerDirectory, {
+ parentPath: '/downloads',
+ name: 'Other',
+ })
+ expect(controller.target).toBe('/downloads/Other')
+ })
+
+ it('keeps a known child selected across later capped refreshes, then forgets it after a complete listing proves it vanished', async () => {
+ const { controller, queue } = harness()
+ await controller.start()
+ const child = { name: 'New', path: '/downloads/New' }
+ queue(Commands.CreateServerDirectory, success(child))
+ queue(
+ Queries.ListServerDirectories,
+ success({ ...listing(), truncated: true })
+ )
+ controller.editName()
+ controller.setEditorText(child.name)
+ controller.submitEditor()
+ await flush()
+
+ queue(
+ Queries.ListServerDirectories,
+ success({ ...listing(), truncated: true })
+ )
+ controller.refresh()
+ await flush()
+ expect(controller.getSnapshot().selected).toBe(child.path)
+ expect(controller.getSnapshot().listing?.entries).toContainEqual(child)
+
+ controller.refresh()
+ await flush()
+ expect(controller.getSnapshot().selected).toBeNull()
+ expect(controller.getSnapshot().listing?.entries).not.toContainEqual(child)
+ queue(
+ Queries.ListServerDirectories,
+ success({ ...listing(), truncated: true })
+ )
+ controller.refresh()
+ await flush()
+ expect(controller.getSnapshot().listing?.entries).not.toContainEqual(child)
+ })
+
+ it('commits hidden filtering atomically, keeps visible selections and preserves the old filter on failure', async () => {
+ const { controller, queue } = harness()
+ await controller.start()
+ controller.select('/downloads/Movies')
+ controller.setScrollOffset(88)
+ const filtered = deferred()
+ queue(Queries.ListServerDirectories, filtered.promise)
+ controller.filter(true)
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ showHidden: false,
+ selected: '/downloads/Movies',
+ busy: 'navigate',
+ })
+ filtered.resolve(
+ success(listing('/downloads', ['.hidden', 'Movies', 'Music']))
+ )
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ showHidden: true,
+ selected: '/downloads/Movies',
+ restore: { offset: 88 },
+ })
+ controller.select('/downloads/.hidden')
+ queue(Queries.ListServerDirectories, failure('unavailable'))
+ controller.filter(false)
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ showHidden: true,
+ selected: '/downloads/.hidden',
+ error: 'unavailable',
+ })
+ controller.filter(false)
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ showHidden: false,
+ selected: null,
+ })
+ })
+
+ it.each(['path', 'name'])(
+ 'locks conflicting controls while the %s editor is open without resetting text',
+ async (kind) => {
+ const { controller, invoke } = harness()
+ await controller.start()
+ if (kind === 'path') controller.editPath()
+ else controller.editName()
+ controller.setEditorText('Uncommitted text')
+ controller.editName()
+ controller.editPath()
+ controller.select('/downloads/Movies')
+ controller.navigate('/archive')
+ controller.up()
+ controller.history(-1)
+ controller.refresh()
+ controller.filter(true)
+ await controller.confirm()
+ expect(invoke).toHaveBeenCalledTimes(3)
+ expect(controller.getSnapshot()).toMatchObject({
+ editor: { kind, text: 'Uncommitted text' },
+ selected: null,
+ showHidden: false,
+ busy: null,
+ })
+ controller.cancelEditor()
+ expect(controller.getSnapshot().editor).toBeNull()
+ expect(controller.target).toBe('/downloads')
+ }
+ )
+
+ it('retains a failed path edit until explicit successful navigation closes it', async () => {
+ const { controller, finish } = harness()
+ await controller.start()
+ controller.editPath()
+ controller.setEditorText('/missing')
+ controller.submitEditor()
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ editor: { kind: 'path', text: '/missing', error: 'notFound' },
+ listing: { path: '/downloads' },
+ busy: null,
+ })
+ controller.setEditorText('/archive')
+ controller.submitEditor()
+ await flush()
+ expect(controller.getSnapshot()).toMatchObject({
+ editor: null,
+ listing: { path: '/archive' },
+ selected: null,
+ })
+ expect(finish).not.toHaveBeenCalled()
+ })
+
+ it('cancels a pending path edit and ignores its result after another navigation completes', async () => {
+ const { controller, queue } = harness()
+ await controller.start()
+ const navigation = deferred()
+ queue(Queries.ListServerDirectories, navigation.promise)
+ controller.editPath()
+ controller.setEditorText('/archive')
+ controller.submitEditor()
+ await flush()
+ expect(controller.getSnapshot().busy).toBe('navigate')
+ controller.cancelEditor()
+ expect(controller.getSnapshot()).toMatchObject({
+ editor: null,
+ busy: null,
+ listing: { path: '/downloads' },
+ })
+ controller.navigate('/downloads/Music')
+ await flush()
+ const current = controller.getSnapshot()
+ navigation.resolve(success(listing('/archive', [])))
+ await flush()
+ expect(controller.getSnapshot()).toBe(current)
+ expect(controller.target).toBe('/downloads/Music')
+ })
+
+ it('invalidates disposed session work without changing a new picker session or notifying old listeners', async () => {
+ const old = harness()
+ await old.controller.start()
+ const response = deferred()
+ old.queue(Queries.ListServerDirectories, response.promise)
+ old.controller.navigate('/archive')
+ await flush()
+ const listener = vi.fn()
+ old.controller.subscribe(listener)
+ const snapshot = old.controller.getSnapshot()
+ old.controller.dispose()
+ const current = harness('/downloads/Music')
+ await current.controller.start()
+ response.resolve(success(listing('/archive', [])))
+ await flush()
+ expect(old.controller.getSnapshot()).toBe(snapshot)
+ expect(listener).not.toHaveBeenCalled()
+ expect(old.finish).not.toHaveBeenCalled()
+ expect(current.controller.target).toBe('/downloads/Music')
+ await current.controller.confirm()
+ expect(current.finish).toHaveBeenCalledExactlyOnceWith('/downloads/Music')
+ })
+})
diff --git a/src/renderer/features/web-directory-picker/directory-picker-controller.ts b/src/renderer/features/web-directory-picker/directory-picker-controller.ts
new file mode 100644
index 00000000..9750ce3e
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/directory-picker-controller.ts
@@ -0,0 +1,645 @@
+import {
+ type DirectoryPreferencesStore,
+ directoryPreferences,
+ ServerDirectoryLocationsStore,
+} from '@renderer/lib/directory-preferences'
+import type { Transport } from '@renderer/lib/transport/types'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type {
+ DirectoryPreferences,
+ DirectoryPreferencesErrorCode,
+} from '@shared/schemas/directory-preferences'
+import {
+ type AllowedSaveDirs,
+ AllowedSaveDirsSchema,
+ CreateServerDirectoryResultSchema,
+ type DirectoryErrorCode,
+ type ListServerDirectoriesResult,
+ ListServerDirectoriesResultSchema,
+ type ServerDirectoryLocations,
+ ValidateServerDirectoryResultSchema,
+} from '@shared/schemas/server-directory'
+import type { z } from 'zod'
+import {
+ DEFAULT_DIRECTORY_SORT,
+ type DirectorySort,
+ type DirectorySortPreferences,
+ DirectorySortSchema,
+ directorySortPreferences,
+} from './directory-sort'
+
+export const DIRECTORY_OPERATION_TIMEOUT = 20_000
+export type DirectoryListing = Extract<
+ ListServerDirectoriesResult,
+ { ok: true }
+>['value']
+export type DirectoryEntry = DirectoryListing['entries'][number]
+type HistoryEntry = {
+ path: string
+ selected: string | null
+ offset: number | null
+}
+type Editor = {
+ kind: 'path' | 'name'
+ text: string
+ error: DirectoryErrorCode | null
+}
+export type PickerState = {
+ locations: ServerDirectoryLocations | null
+ locationsLoading: boolean
+ locationsError: DirectoryErrorCode | null
+ favoriteBusy: boolean
+ favoriteError: DirectoryPreferencesErrorCode | null
+ bootstrap: AllowedSaveDirs | null
+ listing: DirectoryListing | null
+ selected: string | null
+ showHidden: boolean
+ sort: DirectorySort
+ busy: 'bootstrap' | 'navigate' | 'create' | 'validate' | null
+ editor: Editor | null
+ error: DirectoryErrorCode | null
+ notice: 'fallback' | 'refreshAfterCreateFailed' | 'unknownOutcome' | null
+ history: HistoryEntry[]
+ historyIndex: number
+ restore: { revision: number; offset: number; reveal: string | null }
+ unknownParents: string[]
+}
+
+class DirectoryRequestError extends Error {
+ constructor(readonly code: DirectoryErrorCode) {
+ super(code)
+ }
+}
+
+type NavigateOptions = {
+ historyIndex?: number
+ selected?: string | null
+ offset?: number
+ refresh?: boolean
+ showHidden?: boolean
+ created?: DirectoryEntry
+ revealSelection?: boolean
+}
+
+/** One instance owns one bus request. Disposing invalidates every async continuation. */
+export class DirectoryPickerController {
+ private state: PickerState = {
+ locations: null,
+ locationsLoading: false,
+ locationsError: null,
+ favoriteBusy: false,
+ favoriteError: null,
+ bootstrap: null,
+ listing: null,
+ selected: null,
+ showHidden: false,
+ sort: DEFAULT_DIRECTORY_SORT,
+ busy: 'bootstrap',
+ editor: null,
+ error: null,
+ notice: null,
+ history: [],
+ historyIndex: -1,
+ restore: { revision: 0, offset: 0, reveal: null },
+ unknownParents: [],
+ }
+ private listeners = new Set<() => void>()
+ private live = true
+ private generation = 0
+ private pendingDeadlines = new Set<() => void>()
+ private scrollOffset = 0
+ private knownCreated = new Map<string, DirectoryEntry>()
+ private locationsStore: ServerDirectoryLocationsStore
+ private unsubscribeLocations?: () => void
+
+ constructor(
+ private readonly transport: Pick<Transport, 'invoke'> &
+ Partial<Pick<Transport, 'on' | 'off' | 'onConnectionChange'>>,
+ private readonly defaultPath: string | undefined,
+ private readonly finish: (value: string | null) => void,
+ private readonly preferences: Pick<
+ DirectoryPreferencesStore,
+ 'mutate' | 'getSnapshot'
+ > = directoryPreferences,
+ private readonly sortPreferences: DirectorySortPreferences = directorySortPreferences
+ ) {
+ this.state.sort = sortPreferences.get()
+ this.locationsStore = new ServerDirectoryLocationsStore(transport, {
+ retainWhileRefreshing: true,
+ })
+ }
+
+ getSnapshot = () => this.state
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener)
+ return () => {
+ this.listeners.delete(listener)
+ }
+ }
+ private update(patch: Partial<PickerState>) {
+ if (!this.live) return
+ if (
+ Object.entries(patch).every(([key, value]) =>
+ Object.is(this.state[key as keyof PickerState], value)
+ )
+ )
+ return
+ this.state = { ...this.state, ...patch }
+ for (const listener of this.listeners) listener()
+ }
+ dispose() {
+ this.live = false
+ this.generation++
+ for (const cancel of this.pendingDeadlines) cancel()
+ this.pendingDeadlines.clear()
+ this.unsubscribeLocations?.()
+ this.locationsStore.dispose()
+ }
+ private current(generation: number) {
+ return this.live && this.generation === generation
+ }
+
+ private request<T>(
+ channel: Parameters<Transport['invoke']>[0],
+ schema: z.ZodType<T>,
+ args?: unknown,
+ mutation = false
+ ): Promise<T> {
+ return new Promise((resolve, reject) => {
+ let settled = false
+ const done = (value: T | undefined, error?: unknown) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ this.pendingDeadlines.delete(cancel)
+ if (error) reject(error)
+ else resolve(value as T)
+ }
+ const cancel = () =>
+ done(
+ undefined,
+ new DirectoryRequestError(
+ mutation ? 'creationOutcomeUnknown' : 'unavailable'
+ )
+ )
+ const timer = setTimeout(cancel, DIRECTORY_OPERATION_TIMEOUT)
+ this.pendingDeadlines.add(cancel)
+ // Invocation and parsing share the deadline; neither late success nor failure is committed.
+ Promise.resolve()
+ .then(() =>
+ args === undefined
+ ? this.transport.invoke(channel)
+ : this.transport.invoke(channel, args)
+ )
+ .then((value) => done(schema.parse(value)))
+ .catch(() => cancel())
+ })
+ }
+ private errorCode(error: unknown): DirectoryErrorCode {
+ return error instanceof DirectoryRequestError ? error.code : 'unavailable'
+ }
+ private async list(path: string, showHidden: boolean) {
+ const result = await this.request(
+ Queries.ListServerDirectories,
+ ListServerDirectoriesResultSchema,
+ { path, showHidden }
+ )
+ if (!result.ok) throw new DirectoryRequestError(result.error.code)
+ return result.value
+ }
+
+ async start() {
+ if (!this.live) return
+ if (!this.unsubscribeLocations) {
+ this.unsubscribeLocations = this.locationsStore.subscribe(() => {
+ const { locations, loading, error } = this.locationsStore.getSnapshot()
+ this.update({
+ locations,
+ locationsLoading: loading,
+ locationsError: error,
+ })
+ })
+ }
+ const generation = ++this.generation
+ this.update({ busy: 'bootstrap', error: null })
+ try {
+ const bootstrap = await this.request(
+ Queries.ListAllowedSaveDirs,
+ AllowedSaveDirsSchema
+ )
+ if (!this.current(generation)) return
+ this.update({ bootstrap })
+ const candidates = [
+ ...new Set(
+ [
+ this.defaultPath,
+ bootstrap.defaultPath,
+ ...bootstrap.paths.map((root) => root.path),
+ ].filter((path): path is string => path !== undefined && path !== '')
+ ),
+ ]
+ let lastError: DirectoryErrorCode = 'invalidPath'
+ for (let index = 0; index < candidates.length; index++) {
+ try {
+ const listing = await this.list(candidates[index], false)
+ if (!this.current(generation)) return
+ this.commitListing(listing, {}, false)
+ if (index > 0) this.update({ notice: 'fallback' })
+ return
+ } catch (error) {
+ if (!this.current(generation)) return
+ lastError = this.errorCode(error)
+ }
+ }
+ this.update({ busy: null, error: lastError })
+ } catch (error) {
+ if (this.current(generation))
+ this.update({ busy: null, error: this.errorCode(error) })
+ }
+ }
+
+ get locked() {
+ return this.state.busy !== null || this.state.editor !== null
+ }
+ get target() {
+ return this.state.selected ?? this.state.listing?.path ?? null
+ }
+ get currentFavorite() {
+ const path = this.state.listing?.path
+ return this.state.locations?.favorites.find(
+ (entry) =>
+ path !== undefined &&
+ (entry.path === path || entry.sourcePaths.includes(path))
+ )
+ }
+ refreshLocations() {
+ void this.locationsStore.refresh()
+ }
+ async toggleFavorite() {
+ const path = this.state.listing?.path
+ if (
+ !this.live ||
+ this.locked ||
+ !path ||
+ !this.state.locations ||
+ this.state.locationsLoading ||
+ this.state.favoriteBusy
+ )
+ return
+ const favorite = this.currentFavorite
+ const revision = this.locationsStore.getRevision()
+ let committed: DirectoryPreferences | undefined
+ this.update({ favoriteBusy: true, favoriteError: null })
+ const success = await this.preferences.mutate(
+ favorite
+ ? { action: 'removeFavorite', paths: favorite.sourcePaths }
+ : { action: 'addFavorite', path },
+ (snapshot) => {
+ committed = snapshot
+ }
+ )
+ if (!this.live) return
+ // Only a locations query associated with this committed snapshot can cover
+ // the write. An unrelated client's event must not suppress this refresh.
+ await this.locationsStore.refreshAfterMutation(revision, committed)
+ if (!this.live) return
+ this.update({
+ favoriteBusy: false,
+ favoriteError: success
+ ? null
+ : (this.preferences.getSnapshot().error ?? 'unavailable'),
+ })
+ }
+ setScrollOffset(offset: number) {
+ this.scrollOffset = offset
+ }
+ select(path: string | null) {
+ if (
+ this.locked ||
+ (path !== null &&
+ !this.state.listing?.entries.some((entry) => entry.path === path))
+ )
+ return
+ this.update({ selected: path })
+ }
+ private commitListing(
+ listing: DirectoryListing,
+ options: NavigateOptions,
+ showHidden: boolean
+ ) {
+ const { state } = this
+ const known = this.knownCreated.get(listing.path)
+ if (
+ known &&
+ !listing.truncated &&
+ !options.created &&
+ (showHidden || !known.name.startsWith('.')) &&
+ !listing.entries.some((entry) => entry.path === known.path)
+ ) {
+ this.knownCreated.delete(listing.path)
+ }
+ if (
+ listing.truncated &&
+ known &&
+ (showHidden || !known.name.startsWith('.')) &&
+ !listing.entries.some((entry) => entry.path === known.path)
+ ) {
+ listing = { ...listing, entries: [known, ...listing.entries] }
+ }
+ if (
+ options.created &&
+ !listing.entries.some((entry) => entry.path === options.created?.path)
+ ) {
+ listing = { ...listing, entries: [options.created, ...listing.entries] }
+ }
+ const desired = options.created?.path ?? options.selected ?? null
+ const selected = listing.entries.some((entry) => entry.path === desired)
+ ? desired
+ : null
+ let history = state.history.map((entry, index) =>
+ index === state.historyIndex
+ ? { ...entry, selected: state.selected, offset: this.scrollOffset }
+ : entry
+ )
+ let historyIndex = state.historyIndex
+ if (options.historyIndex !== undefined) {
+ historyIndex = options.historyIndex
+ } else if (!options.refresh) {
+ history = history.slice(0, historyIndex + 1)
+ history.push({ path: listing.path, selected, offset: 0 })
+ historyIndex++
+ }
+ if (historyIndex >= 0)
+ history[historyIndex] = {
+ path: listing.path,
+ selected,
+ offset: options.offset ?? 0,
+ }
+ this.scrollOffset = options.offset ?? 0
+ this.update({
+ listing,
+ selected,
+ showHidden,
+ history,
+ historyIndex,
+ busy: null,
+ editor: null,
+ error: null,
+ notice: null,
+ unknownParents: options.refresh
+ ? state.unknownParents.filter((path) => path !== listing.path)
+ : state.unknownParents,
+ restore: {
+ revision: state.restore.revision + 1,
+ offset: this.scrollOffset,
+ reveal: options.revealSelection || options.created ? selected : null,
+ },
+ })
+ }
+ private async load(path: string, options: NavigateOptions = {}) {
+ const generation = ++this.generation
+ const showHidden = options.showHidden ?? this.state.showHidden
+ this.update({ busy: 'navigate', error: null })
+ try {
+ const listing = await this.list(path, showHidden)
+ if (!this.current(generation)) return
+ this.commitListing(listing, options, showHidden)
+ } catch (error) {
+ if (!this.current(generation)) return
+ const code = this.errorCode(error)
+ if (options.created && this.state.listing) {
+ const entries = this.state.listing.entries.filter(
+ (entry) => entry.path !== options.created?.path
+ )
+ this.update({
+ listing: {
+ ...this.state.listing,
+ entries: [options.created, ...entries],
+ },
+ selected: options.created.path,
+ busy: null,
+ editor: null,
+ showHidden,
+ error: code,
+ notice: 'refreshAfterCreateFailed',
+ restore: {
+ revision: this.state.restore.revision + 1,
+ offset: 0,
+ reveal: options.created.path,
+ },
+ })
+ } else {
+ this.update({
+ busy: null,
+ error: code,
+ editor: this.state.editor
+ ? { ...this.state.editor, error: code }
+ : null,
+ })
+ }
+ }
+ }
+ navigate(path: string) {
+ if (this.live && !this.locked) void this.load(path)
+ }
+ navigateLocation(path: string) {
+ if (this.state.bootstrap?.paths.some((entry) => entry.path === path)) {
+ this.navigate(path)
+ return
+ }
+ const locations = this.state.locations
+ if (!this.live || this.locked || this.state.locationsLoading || !locations)
+ return
+ const known = [
+ ...locations.common,
+ ...locations.favorites,
+ ...locations.recent,
+ ]
+ if (known.some((entry) => entry.path === path)) this.navigate(path)
+ }
+ up() {
+ if (!this.locked && this.state.listing?.parentPath)
+ void this.load(this.state.listing.parentPath, {
+ selected: this.state.listing.path,
+ revealSelection: true,
+ })
+ }
+ history(delta: -1 | 1) {
+ if (this.locked) return
+ const index = this.state.historyIndex + delta
+ const entry = this.state.history[index]
+ if (entry)
+ void this.load(entry.path, {
+ historyIndex: index,
+ selected: entry.selected,
+ offset: entry.offset ?? 0,
+ revealSelection: entry.offset === null,
+ })
+ }
+ changeSort(value: DirectorySort) {
+ if (!this.live || this.locked || !this.state.listing) return
+ const parsed = DirectorySortSchema.safeParse(value)
+ if (!parsed.success) return
+ const sort = parsed.data
+ if (
+ sort.by === this.state.sort.by &&
+ sort.direction === this.state.sort.direction
+ )
+ return
+ this.sortPreferences.set(sort)
+ this.scrollOffset = 0
+ this.update({
+ sort,
+ history: this.state.history.map((entry) => ({ ...entry, offset: null })),
+ restore: {
+ revision: this.state.restore.revision + 1,
+ offset: 0,
+ reveal: this.state.selected,
+ },
+ })
+ }
+ refresh() {
+ if (this.locked) return
+ if (!this.state.listing) {
+ void this.start()
+ return
+ }
+ void this.load(this.state.listing.path, {
+ refresh: true,
+ selected: this.state.selected,
+ offset: this.scrollOffset,
+ })
+ }
+ filter(showHidden: boolean) {
+ if (
+ !this.live ||
+ this.locked ||
+ !this.state.listing ||
+ showHidden === this.state.showHidden
+ )
+ return
+ void this.load(this.state.listing.path, {
+ refresh: true,
+ showHidden,
+ selected: this.state.selected,
+ offset: this.scrollOffset,
+ })
+ }
+ editPath() {
+ if (!this.locked && this.state.listing)
+ this.update({
+ editor: { kind: 'path', text: this.state.listing.path, error: null },
+ error: null,
+ })
+ }
+ editName() {
+ if (
+ this.locked ||
+ !this.state.listing?.canCreate ||
+ this.state.unknownParents.includes(this.state.listing.path)
+ )
+ return
+ this.update({
+ editor: { kind: 'name', text: '', error: null },
+ error: null,
+ })
+ }
+ setEditorText(text: string) {
+ if (!this.state.busy && this.state.editor)
+ this.update({ editor: { ...this.state.editor, text, error: null } })
+ }
+ cancelEditor() {
+ if (
+ this.state.editor &&
+ (this.state.busy === null ||
+ (this.state.editor.kind === 'path' && this.state.busy === 'navigate'))
+ ) {
+ this.generation++
+ this.update({ editor: null, error: null })
+ this.update({ busy: null })
+ }
+ }
+ submitEditor() {
+ if (this.state.busy || !this.state.editor) return
+ if (this.state.editor.kind === 'path') {
+ if (this.state.editor.text === '') {
+ this.update({ editor: { ...this.state.editor, error: 'invalidPath' } })
+ return
+ }
+ void this.load(this.state.editor.text)
+ } else void this.create()
+ }
+ private async create() {
+ const parentPath = this.state.listing?.path
+ const editor = this.state.editor
+ if (
+ !parentPath ||
+ editor?.kind !== 'name' ||
+ this.state.unknownParents.includes(parentPath)
+ )
+ return
+ if (editor.text === '') {
+ this.update({ editor: { ...editor, error: 'invalidName' } })
+ return
+ }
+ const generation = ++this.generation
+ this.update({ busy: 'create', error: null })
+ try {
+ const result = await this.request(
+ Commands.CreateServerDirectory,
+ CreateServerDirectoryResultSchema,
+ { parentPath, name: editor.text },
+ true
+ )
+ if (!this.current(generation)) return
+ if (!result.ok) throw new DirectoryRequestError(result.error.code)
+ this.knownCreated.set(parentPath, result.value)
+ this.update({ editor: null })
+ await this.load(parentPath, {
+ refresh: true,
+ created: result.value,
+ showHidden: this.state.showHidden || result.value.name.startsWith('.'),
+ })
+ } catch (error) {
+ if (!this.current(generation)) return
+ const code = this.errorCode(error)
+ if (code === 'creationOutcomeUnknown') {
+ this.update({
+ busy: null,
+ editor: null,
+ error: null,
+ notice: 'unknownOutcome',
+ unknownParents: [
+ ...new Set([...this.state.unknownParents, parentPath]),
+ ],
+ })
+ } else this.update({ busy: null, editor: { ...editor, error: code } })
+ }
+ }
+ async confirm() {
+ const target = this.target
+ if (this.locked || !target) return
+ const generation = ++this.generation
+ this.update({ busy: 'validate', error: null })
+ try {
+ const result = await this.request(
+ Queries.ValidateServerDirectory,
+ ValidateServerDirectoryResultSchema,
+ { path: target }
+ )
+ if (!this.current(generation) || this.target !== target) return
+ if (!result.ok) throw new DirectoryRequestError(result.error.code)
+ this.dispose()
+ this.finish(result.value.path)
+ } catch (error) {
+ if (this.current(generation))
+ this.update({ busy: null, error: this.errorCode(error) })
+ }
+ }
+ cancel() {
+ if (!this.live || this.state.busy === 'create') return
+ this.dispose()
+ this.finish(null)
+ }
+}
diff --git a/src/renderer/features/web-directory-picker/directory-sort.test.ts b/src/renderer/features/web-directory-picker/directory-sort.test.ts
new file mode 100644
index 00000000..e3e57ea6
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/directory-sort.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ DEFAULT_DIRECTORY_SORT,
+ DIRECTORY_SORT_STORAGE_KEY,
+ DirectorySortPreferences,
+ sortDirectoryEntries,
+} from './directory-sort'
+
+const entry = (name: string, modifiedAt?: number) => ({
+ name,
+ path: `/downloads/${name}`,
+ ...(modifiedAt === undefined ? {} : { modifiedAt }),
+})
+
+describe('directory sorting', () => {
+ it('sorts names naturally in both directions without changing entries or their source order', () => {
+ const entries = [entry('folder10'), entry('folder2'), entry('Folder2')]
+ const original = [...entries]
+ const ascending = sortDirectoryEntries(entries, {
+ by: 'name',
+ direction: 'asc',
+ })
+ expect(ascending.map((value) => value.name)).toEqual([
+ 'Folder2',
+ 'folder2',
+ 'folder10',
+ ])
+ expect(
+ sortDirectoryEntries(entries, { by: 'name', direction: 'desc' })
+ ).toEqual([...ascending].reverse())
+ expect(entries).toEqual(original)
+ expect(ascending[0]).toBe(entries[2])
+ })
+
+ it('orders finite timestamps with stable name ties and unknown values last in both directions', () => {
+ const entries = [
+ entry('unknown10'),
+ entry('zero', 0),
+ entry('old', -500),
+ entry('new10', 42.5),
+ entry('unknown2'),
+ entry('new2', 42.5),
+ ]
+ expect(
+ sortDirectoryEntries(entries, { by: 'modified', direction: 'asc' }).map(
+ (value) => value.name
+ )
+ ).toEqual(['old', 'zero', 'new2', 'new10', 'unknown2', 'unknown10'])
+ expect(
+ sortDirectoryEntries(entries, { by: 'modified', direction: 'desc' }).map(
+ (value) => value.name
+ )
+ ).toEqual(['new2', 'new10', 'zero', 'old', 'unknown2', 'unknown10'])
+ })
+
+ it('uses paths as a deterministic final tie breaker', () => {
+ const entries = [
+ { name: 'same', path: '/b' },
+ { name: 'same', path: '/a' },
+ ]
+ expect(sortDirectoryEntries(entries, DEFAULT_DIRECTORY_SORT)[0].path).toBe(
+ '/a'
+ )
+ })
+})
+
+describe('directory sort preferences', () => {
+ it.each([
+ null,
+ '{',
+ '{}',
+ '{"version":2,"by":"name","direction":"asc"}',
+ '{"version":1,"by":"size","direction":"asc"}',
+ '{"version":1,"by":"name","direction":"asc","path":"/secret"}',
+ ])('uses defaults for missing or invalid storage: %s', (value) => {
+ const storage = { getItem: () => value, setItem: vi.fn() }
+ expect(new DirectorySortPreferences(() => storage).get()).toEqual(
+ DEFAULT_DIRECTORY_SORT
+ )
+ })
+
+ it('remembers only the version and sorting fields across page instances', () => {
+ let raw: string | null = null
+ const storage = {
+ getItem: vi.fn(() => raw),
+ setItem: vi.fn((_key: string, value: string) => {
+ raw = value
+ }),
+ }
+ const store = new DirectorySortPreferences(() => storage)
+ store.set({ by: 'modified', direction: 'desc' })
+ expect(storage.setItem).toHaveBeenCalledWith(
+ DIRECTORY_SORT_STORAGE_KEY,
+ '{"version":1,"by":"modified","direction":"desc"}'
+ )
+ expect(new DirectorySortPreferences(() => storage).get()).toEqual({
+ by: 'modified',
+ direction: 'desc',
+ })
+ })
+
+ it('keeps memory authoritative after a denied write instead of rereading stale storage', () => {
+ const storage = {
+ getItem: vi.fn(() => '{"version":1,"by":"name","direction":"asc"}'),
+ setItem: () => {
+ throw new Error('Quota exceeded')
+ },
+ }
+ const store = new DirectorySortPreferences(() => storage)
+ expect(store.get()).toEqual(DEFAULT_DIRECTORY_SORT)
+ store.set({ by: 'modified', direction: 'desc' })
+ expect(store.get()).toEqual({ by: 'modified', direction: 'desc' })
+ expect(storage.getItem).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps page-local choices when storage access itself is denied', () => {
+ const store = new DirectorySortPreferences(() => {
+ throw new Error('Denied')
+ })
+ expect(store.get()).toEqual(DEFAULT_DIRECTORY_SORT)
+ store.set({ by: 'name', direction: 'desc' })
+ expect(store.get()).toEqual({ by: 'name', direction: 'desc' })
+ })
+})
diff --git a/src/renderer/features/web-directory-picker/directory-sort.ts b/src/renderer/features/web-directory-picker/directory-sort.ts
new file mode 100644
index 00000000..04747ee7
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/directory-sort.ts
@@ -0,0 +1,92 @@
+import type { ListServerDirectoriesResult } from '@shared/schemas/server-directory'
+import { z } from 'zod'
+
+export const DirectorySortSchema = z
+ .object({
+ by: z.enum(['name', 'modified']),
+ direction: z.enum(['asc', 'desc']),
+ })
+ .strict()
+export type DirectorySort = z.infer<typeof DirectorySortSchema>
+export const DEFAULT_DIRECTORY_SORT: DirectorySort = {
+ by: 'name',
+ direction: 'asc',
+}
+export const DIRECTORY_SORT_STORAGE_KEY = 'motrix.web-directory-picker.sort.v1'
+const StoredSortSchema = DirectorySortSchema.extend({
+ version: z.literal(1),
+}).strict()
+
+/** A failed storage write must not undo the current page's choice on reopen. */
+export class DirectorySortPreferences {
+ private current?: DirectorySort
+
+ constructor(
+ private readonly storage: () => Pick<Storage, 'getItem' | 'setItem'> = () =>
+ window.localStorage
+ ) {}
+
+ get(): DirectorySort {
+ if (this.current) return this.current
+ try {
+ const value = StoredSortSchema.safeParse(
+ JSON.parse(this.storage().getItem(DIRECTORY_SORT_STORAGE_KEY) ?? 'null')
+ )
+ if (value.success) {
+ const { by, direction } = value.data
+ this.current = { by, direction }
+ return this.current
+ }
+ } catch {
+ // Private mode or denied storage still supports page-local preferences.
+ }
+ this.current = { ...DEFAULT_DIRECTORY_SORT }
+ return this.current
+ }
+
+ set(sort: DirectorySort) {
+ const parsed = DirectorySortSchema.safeParse(sort)
+ if (!parsed.success) return
+ this.current = parsed.data
+ try {
+ this.storage().setItem(
+ DIRECTORY_SORT_STORAGE_KEY,
+ JSON.stringify({ version: 1, ...parsed.data })
+ )
+ } catch {
+ // The in-memory choice stays authoritative until this page closes.
+ }
+ }
+}
+
+export const directorySortPreferences = new DirectorySortPreferences()
+
+type Entry = Extract<
+ ListServerDirectoriesResult,
+ { ok: true }
+>['value']['entries'][number]
+const names = new Intl.Collator('en', { numeric: true, sensitivity: 'base' })
+const ordinal = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
+const compareName = (a: Entry, b: Entry) =>
+ names.compare(a.name, b.name) ||
+ ordinal(a.name, b.name) ||
+ ordinal(a.path, b.path)
+
+/** Sort a copy; cached host responses and entry identities stay untouched. */
+export function sortDirectoryEntries(
+ entries: Entry[],
+ sort: DirectorySort
+): Entry[] {
+ const direction = sort.direction === 'asc' ? 1 : -1
+ return [...entries].sort((a, b) => {
+ if (sort.by === 'name') return direction * compareName(a, b)
+ const aTime = a.modifiedAt
+ const bTime = b.modifiedAt
+ if (aTime === undefined) return bTime === undefined ? compareName(a, b) : 1
+ if (bTime === undefined) return -1
+ return (
+ direction * (aTime < bTime ? -1 : aTime > bTime ? 1 : 0) ||
+ compareName(a, b)
+ )
+ })
+}
diff --git a/src/renderer/features/web-directory-picker/web-directory-picker-dialog.test.tsx b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.test.tsx
new file mode 100644
index 00000000..1818b950
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.test.tsx
@@ -0,0 +1,710 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import { directoryPreferences } from '@renderer/lib/directory-preferences'
+import { transport } from '@renderer/lib/transport'
+import { __webPathPickerBus } from '@renderer/platform/web-services'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react'
+import {
+ forwardRef,
+ StrictMode,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { WebDirectoryPickerDialog } from './web-directory-picker-dialog'
+
+const { listRendered } = vi.hoisted(() => ({ listRendered: vi.fn() }))
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { platform: 'linux', invoke: vi.fn(), on: vi.fn(), off: vi.fn() },
+}))
+// Component tests isolate virtualization geometry; the browser harness exercises the real VirtualList.
+vi.mock('@renderer/components/desktop-kit/virtual-list/virtual-list', () => ({
+ VirtualList: forwardRef((props: Record<string, unknown>, ref) => {
+ listRendered()
+ const node = useRef<HTMLDivElement>(null)
+ useImperativeHandle(ref, () => ({
+ scrollToOffset() {},
+ scrollToIndex() {},
+ getScrollOffset: () => 0,
+ getContainerRef: () => node.current,
+ }))
+ const { items, renderRow, renderEmpty, containerProps, scrollRef } =
+ props as {
+ items: { path: string }[]
+ renderRow: (row: Record<string, unknown>) => React.ReactNode
+ renderEmpty: () => React.ReactNode
+ containerProps: React.HTMLAttributes<HTMLDivElement>
+ scrollRef: React.RefObject<HTMLDivElement | null>
+ }
+ return (
+ <div
+ {...containerProps}
+ ref={(element) => {
+ node.current = element
+ scrollRef.current = element
+ }}
+ >
+ {items.length
+ ? items.map((item, index) => (
+ <div key={item.path}>{renderRow({ item, index, style: {} })}</div>
+ ))
+ : renderEmpty()}
+ </div>
+ )
+ }),
+}))
+
+const directories = (path = '/downloads', names = ['Alpha', 'Beta']) => ({
+ ok: true,
+ value: {
+ path,
+ parentPath: path === '/downloads' ? null : '/downloads',
+ breadcrumbs: [
+ { name: 'downloads', path: '/downloads' },
+ ...(path === '/downloads'
+ ? []
+ : [{ name: path.split('/').at(-1) || '/', path }]),
+ ],
+ entries: names.map((name) => ({ name, path: `${path}/${name}` })),
+ truncated: false,
+ canCreate: true,
+ },
+})
+
+function Harness({ strict = false }: { strict?: boolean }) {
+ const [pending, setPending] = useState(false)
+ const [value, setValue] = useState('/downloads')
+ const tree = (
+ <>
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Parent</DialogTitle>
+ <button
+ type="button"
+ disabled={pending}
+ onClick={async () => {
+ setPending(true)
+ const path = await __webPathPickerBus.request({
+ defaultPath: value,
+ })
+ if (path) setValue(path)
+ setPending(false)
+ }}
+ >
+ Browse
+ </button>
+ <output data-testid="value">{value}</output>
+ </DialogContent>
+ </Dialog>
+ <WebDirectoryPickerDialog />
+ </>
+ )
+ return strict ? <StrictMode>{tree}</StrictMode> : tree
+}
+
+async function openPicker() {
+ const opener = screen.getByRole('button', { name: 'Browse' })
+ opener.focus()
+ fireEvent.click(opener)
+ await screen.findByRole('option', { name: 'Alpha' })
+ return { opener, list: screen.getByRole('listbox', { name: 'Folders' }) }
+}
+
+beforeEach(() => {
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'Win32',
+ })
+ vi.mocked(transport.invoke).mockImplementation(async (channel, payload) => {
+ if (channel === Queries.ListServerDirectoryLocations)
+ return { ok: true, value: { common: [], favorites: [], recent: [] } }
+ if (channel === Queries.ListAllowedSaveDirs)
+ return {
+ paths: [{ path: '/downloads' }],
+ defaultPath: '/downloads',
+ allowCustom: false,
+ }
+ if (channel === Queries.ListServerDirectories)
+ return directories((payload as { path: string }).path)
+ if (channel === Queries.ValidateServerDirectory)
+ return { ok: true, value: payload }
+ if (channel === Commands.CreateServerDirectory)
+ return { ok: false, error: { code: 'alreadyExists' } }
+ throw new Error('Unexpected channel')
+ })
+})
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ vi.clearAllMocks()
+})
+
+describe('WebDirectoryPickerDialog', () => {
+ it('edits the address background while preserving breadcrumb navigation and editor locking', async () => {
+ render(<Harness />)
+ const { list } = await openPicker()
+ fireEvent.doubleClick(screen.getByRole('option', { name: 'Alpha' }))
+ await waitFor(() =>
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads/Alpha'
+ )
+ )
+ const path = screen.getByRole('navigation', { name: 'Folder path' })
+ fireEvent.click(within(path).getByRole('button', { name: 'downloads' }))
+ await waitFor(() =>
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ /^\/downloads$/
+ )
+ )
+ expect(screen.queryByRole('textbox', { name: 'Folder path' })).toBeNull()
+
+ fireEvent.click(path)
+ const editor = screen.getByRole('textbox', { name: 'Folder path' })
+ expect(editor).toHaveValue('/downloads')
+ expect(editor).toHaveFocus()
+ fireEvent.keyDown(editor, { key: 'Escape' })
+ expect(list).toHaveFocus()
+
+ fireEvent.click(screen.getByRole('button', { name: 'New folder' }))
+ fireEvent.click(screen.getByRole('navigation', { name: 'Folder path' }))
+ expect(screen.getByRole('textbox', { name: 'Folder name' })).toHaveFocus()
+ expect(screen.queryByRole('textbox', { name: 'Folder path' })).toBeNull()
+ })
+
+ it('does not rerender directory rows for favorite updates or editor keystrokes', async () => {
+ let complete!: (value: boolean) => void
+ vi.spyOn(directoryPreferences, 'mutate').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve
+ })
+ )
+ render(<Harness />)
+ await openPicker()
+ const beforeFavorite = listRendered.mock.calls.length
+ fireEvent.click(screen.getByTestId('directory-picker-favorite'))
+ await act(async () => complete(true))
+ expect(listRendered).toHaveBeenCalledTimes(beforeFavorite)
+ fireEvent.click(screen.getByRole('button', { name: 'Go to folder' }))
+ const beforeTyping = listRendered.mock.calls.length
+ fireEvent.change(screen.getByRole('textbox', { name: 'Folder path' }), {
+ target: { value: '/downloads/new-path' },
+ })
+ expect(listRendered).toHaveBeenCalledTimes(beforeTyping)
+ })
+
+ it('groups native common places and saved paths, deduplicates roots, and retains semantic shortcuts', async () => {
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'MacIntel',
+ })
+ const original = vi.mocked(transport.invoke).getMockImplementation()!
+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) =>
+ channel === Queries.ListServerDirectoryLocations
+ ? Promise.resolve({
+ ok: true,
+ value: {
+ common: [
+ { kind: 'default', path: '/downloads' },
+ { kind: 'home', path: '/downloads' },
+ { kind: 'desktop', path: '/desktop' },
+ { kind: 'documents', path: '/documents' },
+ ],
+ favorites: [
+ {
+ name: 'Favorite',
+ path: '/favorite',
+ sourcePaths: ['/favorite'],
+ },
+ ],
+ recent: [
+ { name: 'Recent', path: '/recent', sourcePaths: ['/recent'] },
+ ],
+ },
+ })
+ : original(channel, ...args)
+ )
+ render(<Harness />)
+ const { list } = await openPicker()
+ const sidebar = screen.getByTestId('directory-picker-locations')
+ expect(within(sidebar).getByText('Common places')).toBeInTheDocument()
+ expect(
+ within(sidebar).getByRole('button', { name: 'Favorite' })
+ ).toBeInTheDocument()
+ expect(
+ within(sidebar).getByRole('button', { name: 'Recent' })
+ ).toBeInTheDocument()
+ expect(
+ within(sidebar)
+ .getAllByRole('button')
+ .filter((button) => button.title === '/downloads')
+ ).toHaveLength(1)
+ expect(
+ within(sidebar).queryByText('Allowed locations')
+ ).not.toBeInTheDocument()
+ expect(
+ within(sidebar).queryByRole('button', { name: 'Home' })
+ ).not.toBeInTheDocument()
+ const select = screen.getByRole('combobox', { name: 'Location' })
+ expect(select.querySelectorAll('optgroup')).toHaveLength(3)
+
+ fireEvent.keyDown(list, {
+ key: 'D',
+ metaKey: true,
+ shiftKey: true,
+ ctrlKey: true,
+ })
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads'
+ )
+ fireEvent.keyDown(list, { key: 'D', metaKey: true, shiftKey: true })
+ await waitFor(() =>
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/desktop'
+ )
+ )
+ fireEvent.keyDown(list, { key: 'H', metaKey: true, shiftKey: true })
+ await waitFor(() =>
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads'
+ )
+ )
+ fireEvent.keyDown(list, { key: 'O', metaKey: true, shiftKey: true })
+ await waitFor(() =>
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/documents'
+ )
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Go to folder' }))
+ const editor = screen.getByRole('textbox', { name: 'Folder path' })
+ fireEvent.keyDown(editor, { key: 'H', metaKey: true, shiftKey: true })
+ expect(editor).toHaveValue('/documents')
+ })
+
+ it('keeps focus on the favorite trigger while preventing duplicate mutations', async () => {
+ let complete!: (value: boolean) => void
+ vi.spyOn(directoryPreferences, 'mutate').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve
+ })
+ )
+ render(<Harness />)
+ await openPicker()
+ const star = screen.getByTestId('directory-picker-favorite')
+ star.focus()
+ fireEvent.click(star)
+ expect(star).toHaveAttribute('aria-disabled', 'true')
+ expect(star).toHaveFocus()
+ fireEvent.click(star)
+ expect(directoryPreferences.mutate).toHaveBeenCalledTimes(1)
+ const escaped = vi.fn()
+ document.addEventListener('keydown', escaped)
+ fireEvent.keyDown(document.activeElement!, { key: 'Enter', ctrlKey: true })
+ document.removeEventListener('keydown', escaped)
+ expect(escaped).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'Select folder' })).toBeEnabled()
+ await act(async () => complete(true))
+ })
+
+ it('restores a stable focus target when an event removes the focused saved location', async () => {
+ const original = vi.mocked(transport.invoke).getMockImplementation()!
+ let saved = true
+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) =>
+ channel === Queries.ListServerDirectoryLocations
+ ? Promise.resolve({
+ ok: true,
+ value: {
+ common: [],
+ recent: [],
+ favorites: saved
+ ? [
+ {
+ name: 'Favorite',
+ path: '/favorite',
+ sourcePaths: ['/favorite'],
+ },
+ ]
+ : [],
+ },
+ })
+ : original(channel, ...args)
+ )
+ render(<Harness />)
+ const { list } = await openPicker()
+ const favorite = screen.getByRole('button', { name: 'Favorite' })
+ favorite.focus()
+ saved = false
+ act(() => {
+ for (const [channel, listener] of vi.mocked(transport.on).mock.calls)
+ if (channel === Events.DirectoryPreferencesChanged)
+ listener({ favorites: [], recent: [] })
+ })
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: 'Favorite' })
+ ).not.toBeInTheDocument()
+ )
+ expect(list).toHaveFocus()
+ })
+
+ it.each(['location select', 'favorite star'])(
+ 'contains parent submit shortcuts when an event invalidates the focused %s',
+ async (control) => {
+ const original = vi.mocked(transport.invoke).getMockImplementation()!
+ let refresh = false
+ let complete!: (value: unknown) => void
+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) => {
+ if (channel === Queries.ListAllowedSaveDirs)
+ return Promise.resolve({
+ paths: [],
+ defaultPath: '/downloads',
+ allowCustom: true,
+ })
+ if (channel === Queries.ListServerDirectoryLocations)
+ return refresh
+ ? new Promise((resolve) => {
+ complete = resolve
+ })
+ : Promise.resolve({
+ ok: true,
+ value: {
+ common: [{ kind: 'home', path: '/downloads' }],
+ favorites: [],
+ recent: [],
+ },
+ })
+ return original(channel, ...args)
+ })
+ render(<Harness />)
+ await openPicker()
+ const focused =
+ control === 'location select'
+ ? screen.getByRole('combobox', { name: 'Location' })
+ : screen.getByTestId('directory-picker-favorite')
+ focused.focus()
+ refresh = true
+ act(() => {
+ for (const [channel, listener] of vi.mocked(transport.on).mock.calls)
+ if (channel === Events.DirectoryPreferencesChanged)
+ listener({ favorites: [], recent: [] })
+ })
+ expect(focused).toHaveFocus()
+ expect(focused).toBeInTheDocument()
+ expect(focused).toHaveAttribute('aria-disabled', 'true')
+ const escaped = vi.fn()
+ document.addEventListener('keydown', escaped)
+ fireEvent.keyDown(document.activeElement!, {
+ key: 'Enter',
+ ctrlKey: true,
+ })
+ document.removeEventListener('keydown', escaped)
+ expect(escaped).not.toHaveBeenCalled()
+ await waitFor(() => expect(complete).toBeDefined())
+ await act(async () =>
+ complete({ ok: true, value: { common: [], favorites: [], recent: [] } })
+ )
+ }
+ )
+
+ it('loads inside StrictMode without automatically selecting a child and restores the enabled opener', async () => {
+ render(<Harness strict />)
+ const { opener, list } = await openPicker()
+ expect(list).toHaveFocus()
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads'
+ )
+ expect(
+ within(list)
+ .getAllByRole('option')
+ .every((option) => option.getAttribute('aria-selected') === 'false')
+ ).toBe(true)
+ fireEvent.click(screen.getByRole('button', { name: 'Select folder' }))
+ await waitFor(() =>
+ expect(
+ screen.queryByTestId('web-directory-picker')
+ ).not.toBeInTheDocument()
+ )
+ await waitFor(() => expect(opener).toHaveFocus())
+ expect(opener).toBeEnabled()
+ expect(screen.getByRole('dialog', { name: 'Parent' })).toBeInTheDocument()
+ })
+
+ it('single clicks select and double clicks enter, with Up reselecting the departed folder', async () => {
+ render(<Harness />)
+ await openPicker()
+ fireEvent.click(screen.getByRole('option', { name: 'Beta' }))
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads/Beta'
+ )
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(
+ ([channel]) => channel === Queries.ListServerDirectories
+ )
+ ).toHaveLength(1)
+ fireEvent.doubleClick(screen.getByRole('option', { name: 'Beta' }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Up one level' })).toBeEnabled()
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Up one level' }))
+ await waitFor(() =>
+ expect(screen.getByRole('option', { name: 'Beta' })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ )
+ expect(screen.getByRole('button', { name: 'Up one level' })).toBeDisabled()
+ })
+
+ it('contains parent shortcuts and IME, and cancels the name editor before the modal', async () => {
+ render(<Harness />)
+ const { list } = await openPicker()
+ const parentShortcut = vi.fn()
+ document.addEventListener('keydown', parentShortcut)
+ window.addEventListener('keydown', parentShortcut)
+ fireEvent.keyDown(list, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyDown(list, { key: 'Enter', isComposing: true })
+ expect(parentShortcut).not.toHaveBeenCalled()
+ expect(screen.getByTestId('web-directory-picker')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'New folder' }))
+ const input = screen.getByRole('textbox', { name: 'Folder name' })
+ fireEvent.change(input, { target: { value: 'Existing' } })
+ expect(screen.getByRole('button', { name: 'Select folder' })).toBeDisabled()
+ fireEvent.keyDown(input, { key: 'Enter' })
+ await screen.findByRole('alert')
+ expect(input).toHaveValue('Existing')
+ expect(
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Create' }), {
+ key: 'Enter',
+ repeat: true,
+ })
+ ).toBe(false)
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(
+ ([channel]) => channel === Commands.CreateServerDirectory
+ )
+ ).toHaveLength(1)
+ fireEvent.keyDown(input, { key: 'Escape' })
+ expect(
+ screen.queryByRole('textbox', { name: 'Folder name' })
+ ).not.toBeInTheDocument()
+ expect(screen.getByTestId('web-directory-picker')).toBeInTheDocument()
+ fireEvent.keyDown(list, { key: 'Escape' })
+ await waitFor(() =>
+ expect(
+ screen.queryByTestId('web-directory-picker')
+ ).not.toBeInTheDocument()
+ )
+ expect(screen.getByRole('dialog', { name: 'Parent' })).toBeInTheDocument()
+ document.removeEventListener('keydown', parentShortcut)
+ window.removeEventListener('keydown', parentShortcut)
+ })
+
+ it('uses client Mac Return to confirm although the server reports Linux', async () => {
+ Object.defineProperty(navigator, 'platform', {
+ configurable: true,
+ value: 'MacIntel',
+ })
+ render(<Harness />)
+ const { list } = await openPicker()
+ fireEvent.keyDown(list, { key: 'ArrowDown' })
+ expect(screen.getByRole('option', { name: 'Alpha' })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ fireEvent.keyDown(list, { key: 'Enter' })
+ await waitFor(() =>
+ expect(screen.getByTestId('value')).toHaveTextContent('/downloads/Alpha')
+ )
+ })
+
+ it('matches shifted characters and spaces while keeping modifiers and IME out of typeahead', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100)
+ const original = vi.mocked(transport.invoke).getMockImplementation()
+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) =>
+ channel === Queries.ListServerDirectories
+ ? Promise.resolve(
+ directories('/downloads', [
+ 'Alpha',
+ '!Bang',
+ 'Folder 01',
+ 'Folder 12',
+ 'Movies',
+ 'Music',
+ ])
+ )
+ : original!(channel, ...args)
+ )
+ render(<Harness />)
+ const { list } = await openPicker()
+ const target = screen.getByTestId('directory-picker-target')
+ expect(fireEvent.keyDown(list, { key: ' ' })).toBe(false)
+ expect(target).toHaveTextContent(/^\/downloads$/)
+ fireEvent.keyDown(list, { key: 'M', shiftKey: true })
+ expect(target).toHaveTextContent('/downloads/Movies')
+
+ clock.mockReturnValue(1_000)
+ fireEvent.keyDown(list, { key: '!', shiftKey: true })
+ expect(target).toHaveTextContent('/downloads/!Bang')
+
+ clock.mockReturnValue(2_000)
+ for (const key of 'folder 12') fireEvent.keyDown(list, { key })
+ expect(target).toHaveTextContent('/downloads/Folder 12')
+
+ clock.mockReturnValue(3_000)
+ for (const modifiers of [
+ { ctrlKey: true },
+ { metaKey: true },
+ { altKey: true },
+ { isComposing: true },
+ { keyCode: 229 },
+ ]) {
+ fireEvent.keyDown(list, { key: 'M', shiftKey: true, ...modifiers })
+ }
+ fireEvent.keyDown(list, { key: 'ArrowDown', shiftKey: true })
+ expect(target).toHaveTextContent('/downloads/Folder 12')
+ expect(fireEvent.keyDown(list, { key: ' ' })).toBe(false)
+ expect(target).toHaveTextContent('/downloads/Folder 12')
+ fireEvent.keyDown(list, { key: 'a' })
+ expect(target).toHaveTextContent('/downloads/Alpha')
+ fireEvent.keyDown(list, { key: '/', shiftKey: true })
+ const pathEditor = screen.getByRole('textbox', { name: 'Folder path' })
+ expect(pathEditor).toHaveFocus()
+ fireEvent.keyDown(pathEditor, { key: 'Escape' })
+ expect(list).toHaveFocus()
+ fireEvent.keyDown(list, { key: '/' })
+ expect(screen.getByRole('textbox', { name: 'Folder path' })).toHaveFocus()
+ })
+
+ it('starts fresh typeahead immediately after entering a different folder', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(100)
+ try {
+ render(<Harness />)
+ const { list } = await openPicker()
+ fireEvent.keyDown(list, { key: 'a' })
+ fireEvent.keyDown(list, { key: 'l' })
+ fireEvent.keyDown(list, { key: 'Enter' })
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: 'Up one level' })
+ ).toBeEnabled()
+ )
+ fireEvent.keyDown(list, { key: 'b' })
+ expect(screen.getByRole('option', { name: 'Beta' })).toHaveAttribute(
+ 'aria-selected',
+ 'true'
+ )
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads/Alpha/Beta'
+ )
+ } finally {
+ clock.mockRestore()
+ }
+ })
+
+ it('does not let a superseded session restore focus behind the replacement', async () => {
+ render(<Harness />)
+ const { opener } = await openPicker()
+ let replacement: Promise<string | null> | undefined
+ act(() => {
+ replacement = __webPathPickerBus.request({
+ defaultPath: '/downloads/Beta',
+ })
+ })
+ await waitFor(() =>
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads/Beta'
+ )
+ )
+ await new Promise((resolve) => setTimeout(resolve, 80))
+ expect(opener).not.toHaveFocus()
+ expect(screen.getByRole('listbox', { name: 'Folders' })).toHaveFocus()
+ fireEvent.keyDown(screen.getByRole('listbox'), { key: 'Escape' })
+ await expect(replacement).resolves.toBeNull()
+ })
+
+ it('freezes pointer and keyboard targets during validation and ignores its result after cancellation', async () => {
+ const original = vi.mocked(transport.invoke).getMockImplementation()
+ let complete: ((value: unknown) => void) | undefined
+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) =>
+ channel === Queries.ValidateServerDirectory
+ ? new Promise((resolve) => {
+ complete = resolve
+ })
+ : original!(channel, ...args)
+ )
+ render(<Harness />)
+ const { list } = await openPicker()
+ fireEvent.click(screen.getByRole('option', { name: 'Alpha' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Select folder' }))
+ await waitFor(() => expect(complete).toBeDefined())
+ fireEvent.click(screen.getByRole('option', { name: 'Beta' }))
+ fireEvent.keyDown(list, { key: 'ArrowDown' })
+ expect(screen.getByTestId('directory-picker-target')).toHaveTextContent(
+ '/downloads/Alpha'
+ )
+ for (const name of [
+ 'Select folder',
+ 'New folder',
+ 'Go to folder',
+ 'Refresh',
+ ])
+ expect(screen.getByRole('button', { name })).toBeDisabled()
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ await act(async () => {
+ complete?.({ ok: true, value: { path: '/downloads/Alpha' } })
+ })
+ expect(screen.queryByTestId('web-directory-picker')).not.toBeInTheDocument()
+ expect(screen.getByTestId('value')).toHaveTextContent('/downloads')
+ })
+
+ it('settles a pending request if its host and parent unmount, without late focus restoration', async () => {
+ let pending: Promise<string | null> | undefined
+ const original = vi.mocked(transport.invoke).getMockImplementation()
+ let complete: ((value: unknown) => void) | undefined
+ vi.mocked(transport.invoke).mockImplementation((channel, ...args) =>
+ channel === Queries.ListServerDirectories
+ ? new Promise((resolve) => {
+ complete = resolve
+ })
+ : original!(channel, ...args)
+ )
+ const outside = document.createElement('button')
+ document.body.append(outside)
+ const view = render(<WebDirectoryPickerDialog />)
+ outside.focus()
+ act(() => {
+ pending = __webPathPickerBus.request({ defaultPath: '/downloads' })
+ })
+ await waitFor(() => expect(complete).toBeDefined())
+ view.unmount()
+ outside.remove()
+ await expect(pending).resolves.toBeNull()
+ await act(async () => {
+ complete?.(directories())
+ })
+ expect(screen.queryByTestId('web-directory-picker')).not.toBeInTheDocument()
+ })
+})
diff --git a/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
new file mode 100644
index 00000000..eb959fe4
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/web-directory-picker-dialog.tsx
@@ -0,0 +1,1212 @@
+import type { VirtualListHandle } from '@renderer/components/desktop-kit/virtual-list/types'
+import { VirtualList } from '@renderer/components/desktop-kit/virtual-list/virtual-list'
+import { Button } from '@renderer/components/ui/button'
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { Input } from '@renderer/components/ui/input'
+import { InputGroup } from '@renderer/components/ui/input-group'
+import {
+ ScrollArea,
+ ScrollAreaContent,
+ ScrollAreaViewport,
+ ScrollBar,
+} from '@renderer/components/ui/scroll-area'
+import { transport } from '@renderer/lib/transport'
+import { cn } from '@renderer/lib/utils'
+import {
+ __webPathPickerBus,
+ type PickRequest,
+} from '@renderer/platform/web-services'
+import {
+ ArrowUp,
+ ChevronLeft,
+ ChevronRight,
+ Folder,
+ Pencil,
+ RefreshCw,
+ SlidersHorizontal,
+ Star,
+ X,
+} from 'lucide-react'
+import {
+ type KeyboardEvent,
+ memo,
+ type RefObject,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ type DirectoryEntry,
+ DirectoryPickerController,
+} from './directory-picker-controller'
+import { type DirectorySort, sortDirectoryEntries } from './directory-sort'
+import './web-directory-picker.css'
+
+const ROW_HEIGHT = 32
+const EMPTY_ENTRIES: DirectoryEntry[] = []
+
+export function isMacClient() {
+ return /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent)
+}
+
+function validOpener(opener: HTMLElement | null): boolean {
+ return (
+ !!opener?.isConnected &&
+ !opener.matches(':disabled, [aria-disabled="true"]') &&
+ !opener.closest('[inert], [aria-hidden="true"]')
+ )
+}
+
+function restoreOpener(request: PickRequest) {
+ // The caller re-enables its Browse button when the promise settles.
+ let attempts = 0
+ const restore = () => {
+ if (!__webPathPickerBus.canRestoreFocus(request.id)) return
+ if (validOpener(request.opener))
+ request.opener?.focus({ preventScroll: true })
+ else if (request.opener?.isConnected && ++attempts < 8)
+ requestAnimationFrame(restore)
+ }
+ requestAnimationFrame(() => requestAnimationFrame(restore))
+}
+
+type Session = { request: PickRequest; controller: DirectoryPickerController }
+
+export function WebDirectoryPickerDialog() {
+ const [session, setSession] = useState<Session | null>(null)
+ const current = useRef<Session | null>(null)
+ useEffect(() => {
+ const unsubscribe = __webPathPickerBus.subscribe((request) => {
+ current.current?.controller.dispose()
+ const controller = new DirectoryPickerController(
+ transport,
+ request.defaultPath,
+ (value) => {
+ if (current.current?.request.id !== request.id) return
+ current.current = null
+ setSession(null)
+ __webPathPickerBus.resolve(request.id, value)
+ restoreOpener(request)
+ }
+ )
+ current.current = { request, controller }
+ setSession(current.current)
+ })
+ return () => {
+ current.current?.controller.dispose()
+ current.current = null
+ unsubscribe()
+ }
+ }, [])
+ return session ? (
+ <PickerSession key={session.request.id} {...session} />
+ ) : null
+}
+
+function PickerSession({ request, controller }: Session) {
+ const { t } = useTranslation()
+ const state = useSyncExternalStore(
+ controller.subscribe,
+ controller.getSnapshot
+ )
+ const listRef = useRef<HTMLDivElement>(null)
+ const virtualRef = useRef<VirtualListHandle>(null)
+ const editorRef = useRef<HTMLInputElement>(null)
+ const rootSidebarRef = useRef<HTMLElement>(null)
+ const rootSelectRef = useRef<HTMLSelectElement>(null)
+ const lastFocused = useRef<HTMLElement | null>(null)
+ const [viewOptionsOpen, setViewOptionsOpen] = useState(false)
+ const pendingView = useRef<
+ | { kind: 'hidden'; value: boolean }
+ | { kind: 'sort'; value: DirectorySort }
+ | null
+ >(null)
+ const id = useId()
+ const mac = isMacClient()
+ const typeahead = useRef({ text: '', time: 0 })
+ const rawEntries = state.listing?.entries ?? EMPTY_ENTRIES
+ const entries = useMemo(
+ () => sortDirectoryEntries(rawEntries, state.sort),
+ [rawEntries, state.sort]
+ )
+ const activeIndex = useMemo(
+ () => entries.findIndex((entry) => entry.path === state.selected),
+ [entries, state.selected]
+ )
+ const locked = state.busy !== null || state.editor !== null
+ const creating = state.busy === 'create'
+ const target = state.selected ?? state.listing?.path
+ const unknown =
+ !!state.listing && state.unknownParents.includes(state.listing.path)
+ const groups = useMemo(() => {
+ const seenCommon = new Set<string>()
+ const common = (state.locations?.common ?? []).filter((entry) => {
+ if (seenCommon.has(entry.path)) return false
+ seenCommon.add(entry.path)
+ return true
+ })
+ return [
+ {
+ id: 'common',
+ label: t('directoryPicker.places.common'),
+ items: common.map((entry) => ({
+ path: entry.path,
+ name: t(`directoryPicker.places.${entry.kind}`),
+ })),
+ },
+ {
+ id: 'allowed',
+ label: t('directoryPicker.places.allowed'),
+ items: (state.bootstrap?.paths ?? [])
+ .filter((entry) => !seenCommon.has(entry.path))
+ .map((entry) => ({ path: entry.path, name: entry.path })),
+ },
+ {
+ id: 'favorites',
+ label: t('directoryPreferences.favorites'),
+ items: state.locations?.favorites ?? [],
+ },
+ {
+ id: 'recent',
+ label: t('directoryPreferences.recent'),
+ items: state.locations?.recent ?? [],
+ },
+ ].filter((group) => group.items.length > 0)
+ }, [state.locations, state.bootstrap?.paths, t])
+ const activeLocation = useMemo(
+ () =>
+ groups
+ .flatMap((group) => group.items)
+ .sort((a, b) => b.path.length - a.path.length)
+ .find((entry) =>
+ state.listing?.breadcrumbs.some((crumb) => crumb.path === entry.path)
+ )?.path,
+ [groups, state.listing?.breadcrumbs]
+ )
+ const favorite = controller.currentFavorite
+ const locationPending = (path: string) =>
+ state.locationsLoading &&
+ !state.bootstrap?.paths.some((entry) => entry.path === path)
+
+ useEffect(() => {
+ if (typeof window.matchMedia !== 'function') return
+ const desktop = window.matchMedia('(min-width: 640px)')
+ const restoreVisibleFocus = () => {
+ const active = document.activeElement
+ const candidate =
+ active === document.body || active === document.documentElement
+ ? lastFocused.current
+ : active
+ if (
+ (!desktop.matches &&
+ candidate &&
+ rootSidebarRef.current?.contains(candidate)) ||
+ (desktop.matches &&
+ candidate === rootSelectRef.current &&
+ candidate !== null)
+ )
+ listRef.current?.focus({ preventScroll: true })
+ }
+ desktop.addEventListener('change', restoreVisibleFocus)
+ return () => desktop.removeEventListener('change', restoreVisibleFocus)
+ }, [])
+
+ const started = useRef(false)
+ useEffect(() => {
+ if (started.current) return
+ started.current = true
+ void controller.start()
+ }, [controller])
+ const editorKind = state.editor?.kind
+ const previousEditorKind = useRef(editorKind)
+ useLayoutEffect(() => {
+ // Disabling a focused control can move browser focus to body. Keep every
+ // pending operation inside the modal's keyboard boundary before paint.
+ if (state.busy) {
+ listRef.current?.focus({ preventScroll: true })
+ } else if (editorKind) {
+ editorRef.current?.focus()
+ if (previousEditorKind.current !== editorKind) editorRef.current?.select()
+ }
+ previousEditorKind.current = editorKind
+ }, [editorKind, state.busy])
+ useLayoutEffect(() => {
+ const previous = lastFocused.current
+ // Remote updates can remove the compact Location select or disable the
+ // favorite button without a local click. Reclaim focus before paint so a
+ // following submit shortcut stays inside this modal.
+ if (
+ previous &&
+ previous !== listRef.current &&
+ (!previous.isConnected || previous.matches(':disabled'))
+ )
+ listRef.current?.focus({ preventScroll: true })
+ })
+ const currentPath = state.listing?.path
+ useLayoutEffect(() => {
+ if (currentPath !== undefined) typeahead.current = { text: '', time: 0 }
+ }, [currentPath])
+ useEffect(() => {
+ if (state.restore.revision === 0) return
+ virtualRef.current?.scrollToOffset(state.restore.offset)
+ if (state.restore.reveal) {
+ const index = entries.findIndex(
+ (entry) => entry.path === state.restore.reveal
+ )
+ if (index >= 0) virtualRef.current?.scrollToIndex(index)
+ }
+ listRef.current?.focus({ preventScroll: true })
+ }, [state.restore, entries])
+
+ const cancelEditor = () => {
+ controller.cancelEditor()
+ listRef.current?.focus({ preventScroll: true })
+ }
+ const move = (index: number) => {
+ if (entries.length === 0) return
+ const next = Math.max(0, Math.min(entries.length - 1, index))
+ controller.select(entries[next].path)
+ virtualRef.current?.scrollToIndex(next)
+ }
+ const keyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ event.stopPropagation()
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault()
+ return
+ }
+ const plain =
+ !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
+ const meta =
+ event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey
+ const alt =
+ event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey
+ if (
+ plain &&
+ event.repeat &&
+ (event.key === 'Enter' || event.key === ' ') &&
+ (event.target as HTMLElement).closest('button')
+ ) {
+ event.preventDefault()
+ return
+ }
+ if (event.key === 'Escape' && plain) {
+ event.preventDefault()
+ if (event.repeat || creating) return
+ if (state.editor) cancelEditor()
+ else controller.cancel()
+ return
+ }
+ if (state.editor) {
+ if (
+ event.target === editorRef.current &&
+ event.key === 'Enter' &&
+ plain
+ ) {
+ event.preventDefault()
+ if (!event.repeat) controller.submitEditor()
+ }
+ return
+ }
+ if (locked) return
+ if (
+ mac &&
+ event.metaKey &&
+ event.shiftKey &&
+ !event.ctrlKey &&
+ !event.altKey &&
+ ['g', 'h', 'd', 'o'].includes(event.key.toLowerCase())
+ ) {
+ const key = event.key.toLowerCase()
+ if (key === 'g') {
+ event.preventDefault()
+ if (!event.repeat) controller.editPath()
+ } else {
+ const kind =
+ key === 'h' ? 'home' : key === 'd' ? 'desktop' : 'documents'
+ const location = state.locations?.common.find(
+ (entry) => entry.kind === kind
+ )
+ if (location && !state.locationsLoading) {
+ event.preventDefault()
+ if (!event.repeat) controller.navigateLocation(location.path)
+ }
+ }
+ return
+ }
+ if (event.target !== listRef.current) return
+ const page = Math.max(
+ 1,
+ Math.floor((listRef.current?.clientHeight ?? 256) / ROW_HEIGHT)
+ )
+ if (
+ plain &&
+ ['ArrowDown', 'ArrowUp', 'Home', 'End', 'PageDown', 'PageUp'].includes(
+ event.key
+ )
+ ) {
+ event.preventDefault()
+ if (event.key === 'ArrowDown') move(activeIndex < 0 ? 0 : activeIndex + 1)
+ else if (event.key === 'ArrowUp')
+ move(activeIndex < 0 ? entries.length - 1 : activeIndex - 1)
+ else if (event.key === 'Home') move(0)
+ else if (event.key === 'End') move(entries.length - 1)
+ else if (event.key === 'PageDown')
+ move(activeIndex < 0 ? 0 : activeIndex + page)
+ else move(activeIndex < 0 ? entries.length - 1 : activeIndex - page)
+ return
+ }
+ if (
+ (mac && meta && event.key === 'ArrowUp') ||
+ (!mac &&
+ ((alt && event.key === 'ArrowUp') ||
+ (plain && event.key === 'Backspace')))
+ ) {
+ event.preventDefault()
+ if (!event.repeat) controller.up()
+ } else if (
+ (mac && meta && event.key === 'ArrowDown') ||
+ (!mac && plain && event.key === 'Enter')
+ ) {
+ event.preventDefault()
+ if (!event.repeat && state.selected) controller.navigate(state.selected)
+ } else if (mac && plain && event.key === 'Enter') {
+ event.preventDefault()
+ if (!event.repeat) void controller.confirm()
+ } else if (
+ event.key === '/' &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.altKey
+ ) {
+ event.preventDefault()
+ if (!event.repeat) controller.editPath()
+ } else if (
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.altKey &&
+ event.key.length === 1
+ ) {
+ event.preventDefault()
+ const now = Date.now()
+ const character = event.key.toLocaleLowerCase()
+ const previous =
+ now - typeahead.current.time <= 700 ? typeahead.current.text : ''
+ // Space continues a filename prefix but does not start a list action.
+ if (character === ' ' && previous === '') return
+ const text =
+ previous && [...previous].every((value) => value === character)
+ ? character
+ : previous + character
+ typeahead.current = { text, time: now }
+ const start =
+ text.length === 1 ? activeIndex + 1 : Math.max(activeIndex, 0)
+ for (let offset = 0; offset < entries.length; offset++) {
+ const index = (start + offset) % entries.length
+ if (entries[index].name.toLocaleLowerCase().startsWith(text)) {
+ move(index)
+ break
+ }
+ }
+ }
+ }
+ const editor = state.editor
+ const editorError = editor?.error
+
+ return (
+ <Dialog
+ open
+ disablePointerDismissal
+ onOpenChange={(open, details) => {
+ if (open) return
+ if (creating) {
+ details.cancel()
+ return
+ }
+ if (details.reason === 'escape-key' && editor) {
+ details.cancel()
+ cancelEditor()
+ return
+ }
+ controller.cancel()
+ }}
+ >
+ <DialogContent
+ showCloseButton={false}
+ initialFocus={listRef}
+ finalFocus={() =>
+ __webPathPickerBus.canRestoreFocus(request.id)
+ ? validOpener(request.opener)
+ ? request.opener
+ : true
+ : false
+ }
+ onFocusCapture={(event) => {
+ lastFocused.current = event.target as HTMLElement
+ }}
+ onKeyDown={keyDown}
+ onKeyUp={(event) => event.stopPropagation()}
+ className="flex h-[500px] max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-[720px] flex-row gap-0 overflow-hidden p-0 sm:max-w-[720px]"
+ data-testid="web-directory-picker"
+ >
+ {groups.length > 0 && (
+ <ScrollArea
+ data-testid="directory-picker-locations"
+ className="hidden w-40 shrink-0 border-e bg-muted/40 sm:block"
+ >
+ <ScrollAreaViewport tabIndex={-1} className="focus-visible:ring-0">
+ <ScrollAreaContent>
+ <nav
+ ref={rootSidebarRef}
+ aria-label={t('directoryPicker.location')}
+ className="flex flex-col gap-2 p-2"
+ >
+ {groups.map((group) => (
+ <div
+ key={group.id}
+ data-directory-location-group={group.id}
+ >
+ <p className="px-2 pt-2 pb-1 text-[11px] font-medium text-muted-foreground">
+ {group.label}
+ </p>
+ {group.items.map((entry) => (
+ <Button
+ key={entry.path}
+ data-directory-location
+ variant="ghost"
+ size="sm"
+ className={cn(
+ 'w-full justify-start gap-2 px-2 text-xs',
+ activeLocation === entry.path &&
+ 'bg-accent text-accent-foreground'
+ )}
+ aria-disabled={locked || locationPending(entry.path)}
+ disabled={locked}
+ aria-label={entry.name}
+ aria-current={
+ activeLocation === entry.path
+ ? 'location'
+ : undefined
+ }
+ title={entry.path}
+ onClick={() =>
+ controller.navigateLocation(entry.path)
+ }
+ >
+ {group.id === 'favorites' ? (
+ <Star className="size-4 shrink-0 text-muted-foreground" />
+ ) : (
+ <Folder className="size-4 shrink-0 text-muted-foreground" />
+ )}
+ <span dir="ltr" className="truncate whitespace-pre">
+ {entry.name}
+ </span>
+ </Button>
+ ))}
+ </div>
+ ))}
+ </nav>
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar />
+ </ScrollArea>
+ )}
+ <div
+ data-testid="directory-picker-main"
+ className="directory-picker-pane flex min-w-0 flex-1 flex-col"
+ >
+ <div className="relative shrink-0 space-y-0.5 px-3 pt-3 pb-2 pe-11">
+ <DialogTitle className="text-[13px]">
+ {t('directoryPicker.title')}
+ </DialogTitle>
+ <DialogDescription className="sr-only">
+ {t('directoryPicker.description')}
+ </DialogDescription>
+ <DialogClose
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={creating}
+ aria-label={t('chrome.close')}
+ className="absolute top-2 right-2"
+ />
+ }
+ >
+ <X />
+ </DialogClose>
+ </div>
+ <div
+ data-testid="directory-picker-toolbar"
+ className="flex shrink-0 items-center gap-1 border-b px-3 pb-2"
+ >
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={editor?.kind === 'path' ? 'hidden' : undefined}
+ aria-label={t('directoryPicker.back')}
+ title={t('directoryPicker.back')}
+ disabled={locked || state.historyIndex <= 0}
+ onClick={() => controller.history(-1)}
+ >
+ <ChevronLeft />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={editor?.kind === 'path' ? 'hidden' : undefined}
+ aria-label={t('directoryPicker.forward')}
+ title={t('directoryPicker.forward')}
+ disabled={
+ locked || state.historyIndex >= state.history.length - 1
+ }
+ onClick={() => controller.history(1)}
+ >
+ <ChevronRight />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={editor?.kind === 'path' ? 'hidden' : undefined}
+ aria-label={t('directoryPicker.up')}
+ title={`${t('directoryPicker.up')} (${mac ? '⌘ ↑' : 'Alt ↑'})`}
+ disabled={locked || !state.listing?.parentPath}
+ onClick={() => controller.up()}
+ >
+ <ArrowUp />
+ </Button>
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ {editor?.kind === 'path' ? (
+ <>
+ <Input
+ ref={editorRef}
+ aria-label={t('directoryPicker.path')}
+ aria-invalid={!!editorError}
+ aria-describedby={
+ editorError ? `${id}-editor-error` : undefined
+ }
+ value={editor.text}
+ maxLength={4096}
+ disabled={!!state.busy}
+ onChange={(event) =>
+ controller.setEditorText(event.target.value)
+ }
+ dir="ltr"
+ className="h-8 min-w-0 flex-1"
+ />
+ <Button
+ size="sm"
+ disabled={!!state.busy}
+ onClick={() => controller.submitEditor()}
+ >
+ {t('directoryPicker.go')}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={creating}
+ onClick={cancelEditor}
+ >
+ {t('common.cancel')}
+ </Button>
+ </>
+ ) : (
+ <InputGroup
+ className="h-8 min-w-0 flex-1 gap-0.5 bg-background px-1 shadow-none"
+ onClick={(event) => {
+ if (
+ !locked &&
+ state.listing &&
+ !(event.target as HTMLElement).closest(
+ 'button, [data-slot="scroll-area-scrollbar"]'
+ )
+ )
+ controller.editPath()
+ }}
+ >
+ <ScrollArea className="h-7 min-w-0 flex-1">
+ <ScrollAreaViewport
+ tabIndex={-1}
+ className="focus-visible:ring-0"
+ >
+ <ScrollAreaContent>
+ <nav
+ aria-label={t('directoryPicker.path')}
+ dir="ltr"
+ className="flex min-w-max items-center gap-0.5"
+ >
+ {state.listing?.breadcrumbs.map((crumb, index) => (
+ <span
+ key={crumb.path}
+ className="flex shrink-0 items-center"
+ >
+ {index > 0 &&
+ state.listing?.breadcrumbs[index - 1]?.name !==
+ '/' && (
+ <span
+ aria-hidden
+ className="text-muted-foreground"
+ >
+ /
+ </span>
+ )}
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7 max-w-40 truncate px-1.5 text-xs focus-visible:ring-inset"
+ title={crumb.path}
+ disabled={locked}
+ onClick={() => controller.navigate(crumb.path)}
+ >
+ {crumb.name}
+ </Button>
+ </span>
+ ))}
+ {!state.listing && <span className="h-7" />}
+ </nav>
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar
+ orientation="horizontal"
+ className="h-1.5 p-px"
+ />
+ </ScrollArea>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t('directoryPicker.goToFolder')}
+ title={`${t('directoryPicker.goToFolder')} (${mac ? '⌘ ⇧ G /' : '/'})`}
+ disabled={locked || !state.listing}
+ className="size-6 shrink-0"
+ onClick={() => controller.editPath()}
+ >
+ <Pencil />
+ </Button>
+ </InputGroup>
+ )}
+ </div>
+ {request.allowFavoriteEditing !== false && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={editor?.kind === 'path' ? 'hidden' : undefined}
+ data-testid="directory-picker-favorite"
+ aria-label={t(
+ favorite
+ ? 'directoryPreferences.removeFavorite'
+ : 'directoryPreferences.addFavorite'
+ )}
+ title={t(
+ favorite
+ ? 'directoryPreferences.removeFavorite'
+ : 'directoryPreferences.addFavorite'
+ )}
+ aria-pressed={!!favorite}
+ disabled={locked || !state.listing || !state.locations}
+ aria-disabled={
+ locked ||
+ !state.listing ||
+ !state.locations ||
+ state.locationsLoading ||
+ state.favoriteBusy
+ }
+ aria-busy={state.favoriteBusy}
+ onClick={() => void controller.toggleFavorite()}
+ >
+ <Star className={favorite ? 'fill-current' : undefined} />
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={editor?.kind === 'path' ? 'hidden' : undefined}
+ aria-label={t('directoryPicker.refresh')}
+ title={t('directoryPicker.refresh')}
+ disabled={locked}
+ onClick={() => controller.refresh()}
+ >
+ <RefreshCw
+ className={
+ state.busy === 'navigate'
+ ? 'animate-spin motion-reduce:animate-none'
+ : undefined
+ }
+ />
+ </Button>
+ <DropdownMenu
+ open={viewOptionsOpen}
+ onOpenChange={(open) => {
+ if (open) pendingView.current = null
+ setViewOptionsOpen(open)
+ }}
+ onOpenChangeComplete={(open) => {
+ if (open || pendingView.current === null) return
+ const action = pendingView.current
+ pendingView.current = null
+ listRef.current?.focus({ preventScroll: true })
+ if (action.kind === 'hidden') controller.filter(action.value)
+ else {
+ typeahead.current = { text: '', time: 0 }
+ controller.changeSort(action.value)
+ }
+ }}
+ >
+ <DropdownMenuTrigger
+ render={<Button variant="ghost" size="icon-sm" />}
+ className={editor?.kind === 'path' ? 'hidden' : undefined}
+ disabled={locked || !state.listing}
+ aria-label={t('directoryPicker.viewOptions')}
+ title={t('directoryPicker.viewOptions')}
+ >
+ <SlidersHorizontal />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="min-w-40"
+ aria-label={t('directoryPicker.viewOptions')}
+ finalFocus={() => pendingView.current === null}
+ onKeyDownCapture={(event) => {
+ if (
+ event.key === 'Enter' &&
+ (event.ctrlKey || event.metaKey)
+ ) {
+ event.preventDefault()
+ event.stopPropagation()
+ }
+ }}
+ onKeyDown={(event) => event.stopPropagation()}
+ onKeyUp={(event) => event.stopPropagation()}
+ >
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="py-1 text-[11px] leading-4 text-muted-foreground">
+ {t('directoryPicker.sortBy')}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ aria-label={t('directoryPicker.sortBy')}
+ value={state.sort.by}
+ onValueChange={(value) => {
+ if (value !== 'name' && value !== 'modified') return
+ pendingView.current = {
+ kind: 'sort',
+ value: { ...state.sort, by: value },
+ }
+ setViewOptionsOpen(false)
+ }}
+ >
+ <DropdownMenuRadioItem
+ value="name"
+ className="py-1 text-xs leading-4"
+ closeOnClick
+ disabled={locked}
+ >
+ {t('directoryPicker.sortName')}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="modified"
+ className="py-1 text-xs leading-4"
+ closeOnClick
+ disabled={locked}
+ >
+ {t('directoryPicker.sortModified')}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel className="py-1 text-[11px] leading-4 text-muted-foreground">
+ {t('directoryPicker.sortOrder')}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ aria-label={t('directoryPicker.sortOrder')}
+ value={state.sort.direction}
+ onValueChange={(value) => {
+ if (value !== 'asc' && value !== 'desc') return
+ pendingView.current = {
+ kind: 'sort',
+ value: { ...state.sort, direction: value },
+ }
+ setViewOptionsOpen(false)
+ }}
+ >
+ <DropdownMenuRadioItem
+ value="asc"
+ className="py-1 text-xs leading-4"
+ closeOnClick
+ disabled={locked}
+ >
+ {t('directoryPicker.sortAscending')}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="desc"
+ className="py-1 text-xs leading-4"
+ closeOnClick
+ disabled={locked}
+ >
+ {t('directoryPicker.sortDescending')}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuCheckboxItem
+ className="py-1 text-xs leading-4"
+ checked={state.showHidden}
+ disabled={locked || !state.listing}
+ closeOnClick
+ onCheckedChange={(checked) => {
+ pendingView.current = { kind: 'hidden', value: checked }
+ setViewOptionsOpen(false)
+ }}
+ >
+ {t('directoryPicker.showHidden')}
+ </DropdownMenuCheckboxItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <ScrollArea className="min-h-0 flex-1">
+ <ScrollAreaViewport tabIndex={-1} className="focus-visible:ring-0">
+ <ScrollAreaContent className="flex h-full min-h-0 flex-col">
+ {groups.length > 0 && (
+ <div className="flex shrink-0 items-center gap-3 border-b px-3 py-1.5 sm:hidden">
+ <label className="flex min-w-0 flex-1 items-center gap-2 text-[11px] sm:hidden">
+ {t('directoryPicker.location')}
+ <select
+ ref={rootSelectRef}
+ aria-label={t('directoryPicker.location')}
+ disabled={locked}
+ aria-disabled={
+ locked ||
+ (state.locationsLoading &&
+ !state.bootstrap?.paths.length)
+ }
+ value={activeLocation ?? ''}
+ onChange={(event) =>
+ controller.navigateLocation(event.target.value)
+ }
+ className="h-6 min-w-0 flex-1 rounded border bg-background px-1"
+ dir="ltr"
+ >
+ <option value="" disabled>
+ —
+ </option>
+ {groups.map((group) => (
+ <optgroup key={group.id} label={group.label}>
+ {group.items.map((entry) => (
+ <option
+ key={entry.path}
+ value={entry.path}
+ disabled={locationPending(entry.path)}
+ >
+ {entry.name}
+ </option>
+ ))}
+ </optgroup>
+ ))}
+ </select>
+ </label>
+ </div>
+ )}
+ {state.locationsError && (
+ <div
+ role="status"
+ className="flex shrink-0 items-center gap-2 px-3 py-1 text-[11px] text-muted-foreground"
+ >
+ <p className="flex-1">
+ {t('directoryPicker.places.loadFailed')}
+ </p>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={state.locationsLoading}
+ onClick={() => {
+ listRef.current?.focus({ preventScroll: true })
+ controller.refreshLocations()
+ }}
+ >
+ {t('directoryPicker.retry')}
+ </Button>
+ </div>
+ )}
+ {state.favoriteError && (
+ <p
+ role="alert"
+ className="shrink-0 px-3 py-1 text-xs text-destructive"
+ >
+ {t(`directoryPreferences.errors.${state.favoriteError}`)}
+ </p>
+ )}
+ {editor?.kind === 'name' && (
+ <div className="shrink-0 space-y-2 border-b px-3 py-2">
+ <div className="flex items-center gap-2">
+ <Folder className="size-4 shrink-0 text-muted-foreground" />
+ <Input
+ ref={editorRef}
+ aria-label={t('directoryPicker.folderName')}
+ aria-invalid={!!editorError}
+ aria-describedby={`${id}-create-help${editorError ? ` ${id}-editor-error` : ''}`}
+ value={editor.text}
+ maxLength={255}
+ disabled={creating}
+ onChange={(event) =>
+ controller.setEditorText(event.target.value)
+ }
+ dir="ltr"
+ className="h-8 min-w-0 flex-1"
+ />
+ <Button
+ size="sm"
+ disabled={creating}
+ onClick={() => controller.submitEditor()}
+ >
+ {t('directoryPicker.create')}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={creating}
+ onClick={cancelEditor}
+ >
+ {t('common.cancel')}
+ </Button>
+ </div>
+ <p
+ id={`${id}-create-help`}
+ className="text-xs text-muted-foreground"
+ >
+ {t('directoryPicker.createHelp')}
+ </p>
+ </div>
+ )}
+ {editorError && (
+ <p
+ role="alert"
+ id={`${id}-editor-error`}
+ className="shrink-0 px-3 py-2 text-xs text-destructive"
+ >
+ {t(`directoryPicker.errors.${editorError}`)}
+ </p>
+ )}
+ {!editorError && state.error && (
+ <div
+ role="alert"
+ className="flex shrink-0 items-center gap-2 px-3 py-2 text-xs text-destructive"
+ >
+ <p className="flex-1">
+ {t(`directoryPicker.errors.${state.error}`)}
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={locked}
+ onClick={() => controller.refresh()}
+ >
+ {t('directoryPicker.retry')}
+ </Button>
+ </div>
+ )}
+ {(state.notice || unknown) && (
+ <p
+ role="status"
+ className="shrink-0 px-3 py-2 text-xs text-muted-foreground"
+ >
+ {t(
+ `directoryPicker.${unknown ? 'unknownOutcome' : (state.notice ?? 'unknownOutcome')}`,
+ { path: state.listing?.path }
+ )}
+ </p>
+ )}
+ {state.listing?.truncated && (
+ <p className="shrink-0 px-3 py-2 text-xs text-muted-foreground">
+ {t('directoryPicker.incomplete')}
+ </p>
+ )}
+ <DirectoryEntries
+ controller={controller}
+ entries={entries}
+ selected={state.selected}
+ busy={!!state.busy}
+ locked={locked}
+ hasListing={!!state.listing}
+ activeIndex={activeIndex}
+ id={id}
+ listRef={listRef}
+ virtualRef={virtualRef}
+ />
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar />
+ </ScrollArea>
+ <div className="flex min-w-0 shrink-0 items-start border-t px-3 pt-2 text-[11px]">
+ <ScrollArea className="directory-picker-target min-w-0 flex-1">
+ <ScrollAreaViewport
+ tabIndex={-1}
+ className="max-h-12 focus-visible:ring-0"
+ >
+ <ScrollAreaContent>
+ <output
+ aria-label={t('directoryPicker.selectedPath')}
+ dir="ltr"
+ className="block break-all whitespace-pre-wrap"
+ data-testid="directory-picker-target"
+ >
+ {target ?? '—'}
+ </output>
+ </ScrollAreaContent>
+ </ScrollAreaViewport>
+ <ScrollBar />
+ </ScrollArea>
+ </div>
+ <div
+ data-testid="directory-picker-actions"
+ className="flex shrink-0 flex-wrap items-center justify-between gap-2 px-3 pt-2 pb-3"
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={locked || !state.listing?.canCreate || unknown}
+ onClick={() => controller.editName()}
+ >
+ {t('directoryPicker.newFolder')}
+ </Button>
+ <div className="ms-auto flex shrink-0 gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={creating}
+ onClick={() => controller.cancel()}
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button
+ size="sm"
+ disabled={locked || !target}
+ onClick={() => void controller.confirm()}
+ >
+ {t('directoryPicker.selectFolder')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+// Location/favorite updates must not re-render the virtualizer or its rows.
+const DirectoryEntries = memo(function DirectoryEntries({
+ controller,
+ entries,
+ selected,
+ busy,
+ locked,
+ hasListing,
+ activeIndex,
+ id,
+ listRef,
+ virtualRef,
+}: {
+ controller: DirectoryPickerController
+ entries: DirectoryEntry[]
+ selected: string | null
+ busy: boolean
+ locked: boolean
+ hasListing: boolean
+ activeIndex: number
+ id: string
+ listRef: RefObject<HTMLDivElement | null>
+ virtualRef: RefObject<VirtualListHandle | null>
+}) {
+ const { t } = useTranslation()
+ return (
+ <VirtualList
+ ref={virtualRef}
+ scrollRef={listRef}
+ activeIndex={activeIndex}
+ items={entries}
+ getId={(entry) => entry.path}
+ rowHeight={ROW_HEIGHT}
+ scrollbar="custom"
+ className="directory-picker-list min-h-0 flex-1 bg-background outline-none"
+ containerProps={{
+ role: 'listbox',
+ tabIndex: 0,
+ 'aria-label': t('directoryPicker.folders'),
+ 'aria-activedescendant':
+ activeIndex >= 0 ? `${id}-option-${activeIndex}` : undefined,
+ 'aria-busy': !!busy,
+ 'aria-disabled': locked,
+ onScroll: (event) =>
+ controller.setScrollOffset(event.currentTarget.scrollTop),
+ onClick: (event) => {
+ if (!(event.target as HTMLElement).closest('[role="option"]'))
+ controller.select(null)
+ },
+ }}
+ renderEmpty={() => (
+ <p className="p-6 text-center text-xs text-muted-foreground">
+ {busy
+ ? t('directoryPicker.loading')
+ : hasListing
+ ? t('directoryPicker.empty')
+ : ''}
+ </p>
+ )}
+ renderRow={({ item, index, style }) => (
+ // biome-ignore lint/a11y/useKeyWithClickEvents: The owning listbox handles keyboard selection and retains DOM focus.
+ <div
+ id={`${id}-option-${index}`}
+ role="option"
+ aria-posinset={index + 1}
+ aria-setsize={entries.length}
+ aria-selected={selected === item.path}
+ aria-disabled={locked}
+ tabIndex={-1}
+ style={style}
+ title={item.name}
+ className={cn(
+ 'flex cursor-default items-center gap-2 px-3 text-sm select-none',
+ selected === item.path
+ ? 'bg-accent text-accent-foreground'
+ : 'hover:bg-accent/50',
+ locked && 'opacity-60'
+ )}
+ onMouseDown={(event) => {
+ event.preventDefault()
+ listRef.current?.focus({ preventScroll: true })
+ }}
+ onClick={() => controller.select(item.path)}
+ onDoubleClick={() => controller.navigate(item.path)}
+ >
+ <Folder
+ aria-hidden
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <span dir="ltr" className="truncate whitespace-pre">
+ {item.name}
+ </span>
+ </div>
+ )}
+ />
+ )
+})
diff --git a/src/renderer/features/web-directory-picker/web-directory-picker.css b/src/renderer/features/web-directory-picker/web-directory-picker.css
new file mode 100644
index 00000000..aed12a35
--- /dev/null
+++ b/src/renderer/features/web-directory-picker/web-directory-picker.css
@@ -0,0 +1,43 @@
+.directory-picker-pane {
+ --directory-picker-focus: #7388a3;
+}
+
+.directory-picker-list [role="listbox"] {
+ box-shadow: none;
+}
+
+.directory-picker-list
+ [role="listbox"]:focus-visible[aria-disabled="false"]
+ [role="option"][aria-selected="true"] {
+ outline: 2px solid var(--directory-picker-focus);
+ outline-offset: -2px;
+}
+
+.directory-picker-target {
+ position: relative;
+ padding-inline-start: 8px;
+}
+
+/* Keep the keyboard target visible when no child is selected or it is offscreen. */
+.directory-picker-pane:has(
+ .directory-picker-list [role="listbox"]:focus-visible[aria-disabled="false"]
+) .directory-picker-target::before {
+ content: "";
+ position: absolute;
+ inset-block: 2px;
+ inset-inline-start: 0;
+ width: 2px;
+ background: var(--directory-picker-focus);
+ forced-color-adjust: none;
+}
+
+.dark .directory-picker-pane {
+ --directory-picker-focus: #97aac4;
+}
+
+@media (forced-colors: active) {
+ .directory-picker-pane,
+ .dark .directory-picker-pane {
+ --directory-picker-focus: Highlight;
+ }
+}
diff --git a/src/renderer/lib/directory-preferences.test.ts b/src/renderer/lib/directory-preferences.test.ts
new file mode 100644
index 00000000..e3dd24e5
--- /dev/null
+++ b/src/renderer/lib/directory-preferences.test.ts
@@ -0,0 +1,648 @@
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import type { MutateDirectoryPreferencesRequest } from '@shared/schemas/directory-preferences'
+import { cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ DIRECTORY_PREFERENCES_TIMEOUT,
+ DirectoryPreferencesStore,
+ ServerDirectoryLocationsStore,
+ useServerDirectoryLocations,
+} from './directory-preferences'
+import { transport } from './transport'
+import type {
+ EventListener,
+ Transport,
+ TransportConnectionListener,
+} from './transport/types'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { invoke: vi.fn(), on: vi.fn(), off: vi.fn(), platform: 'web' },
+}))
+
+const success = (value: unknown) => ({ ok: true, value })
+const empty = { favorites: [], recent: [] }
+const saved = { favorites: ['/saved'], recent: ['/recent'] }
+const places = {
+ common: [
+ { kind: 'default', path: '/downloads' },
+ { kind: 'home', path: '/downloads' },
+ ],
+ favorites: [
+ { name: 'Saved', path: '/saved', sourcePaths: ['/real/saved', '/saved'] },
+ ],
+ recent: [],
+}
+const flush = () => vi.advanceTimersByTimeAsync(0)
+function deferred() {
+ let resolve!: (value: unknown) => void
+ let reject!: (error: unknown) => void
+ const promise = new Promise<unknown>((yes, no) => {
+ resolve = yes
+ reject = no
+ })
+ return { promise, resolve, reject }
+}
+
+const disposables: { dispose(): void }[] = []
+function harness() {
+ const callbacks = new Map<string, EventListener>()
+ let connection: TransportConnectionListener | undefined
+ const responses = new Map<string, unknown[]>()
+ const bridge = {
+ invoke: vi.fn<Transport['invoke']>(async (channel) => {
+ expect(callbacks.has(Events.DirectoryPreferencesChanged)).toBe(true)
+ const queue = responses.get(channel)
+ if (queue?.length) return queue.shift()
+ if (channel === Queries.ListServerDirectoryLocations)
+ return success(places)
+ return success(empty)
+ }),
+ on: vi.fn<Transport['on']>((channel, listener) => {
+ callbacks.set(channel, listener)
+ }),
+ off: vi.fn<Transport['off']>((channel, listener) => {
+ if (callbacks.get(channel) === listener) callbacks.delete(channel)
+ }),
+ onConnectionChange: vi.fn<NonNullable<Transport['onConnectionChange']>>(
+ (listener) => {
+ connection = listener
+ return () => {
+ connection = undefined
+ }
+ }
+ ),
+ }
+ const preferences = new DirectoryPreferencesStore(bridge)
+ disposables.push(preferences)
+ return {
+ bridge,
+ preferences,
+ locations(
+ options?: ConstructorParameters<typeof ServerDirectoryLocationsStore>[1]
+ ) {
+ const store = new ServerDirectoryLocationsStore(bridge, options)
+ disposables.push(store)
+ return store
+ },
+ queue(channel: string, ...values: unknown[]) {
+ responses.set(channel, [...(responses.get(channel) ?? []), ...values])
+ },
+ event(value: unknown) {
+ callbacks.get(Events.DirectoryPreferencesChanged)?.(value)
+ },
+ reconnect() {
+ connection?.({ state: 'connected' })
+ },
+ }
+}
+
+beforeEach(() => vi.useFakeTimers())
+afterEach(() => {
+ cleanup()
+ for (const disposable of disposables.splice(0)) disposable.dispose()
+ vi.clearAllMocks()
+ vi.useRealTimers()
+})
+
+describe('DirectoryPreferencesStore', () => {
+ it('preserves equal preference references and does not notify an unchanged event snapshot', async () => {
+ const h = harness()
+ const listener = vi.fn()
+ h.preferences.subscribe(listener)
+ await flush()
+ const snapshot = h.preferences.getSnapshot()
+ listener.mockClear()
+ h.event(structuredClone(empty))
+ expect(h.preferences.getSnapshot()).toBe(snapshot)
+ expect(listener).not.toHaveBeenCalled()
+ })
+
+ it('provides the actual committed response for refresh causality even after a newer event', async () => {
+ const h = harness()
+ const response = deferred()
+ h.queue(Commands.MutateDirectoryPreferences, response.promise)
+ const onCommitted = vi.fn()
+ const mutation = h.preferences.mutate(
+ { action: 'addFavorite', path: '/saved' },
+ onCommitted
+ )
+ await flush()
+ h.event(empty)
+ response.resolve(success(saved))
+ expect(await mutation).toBe(true)
+ expect(onCommitted).toHaveBeenCalledWith(saved)
+ expect(h.preferences.getSnapshot().preferences).toEqual(empty)
+ })
+
+ it('loads saved records on the first UI subscription even if background recording failed earlier', async () => {
+ const h = harness()
+ h.queue(Commands.MutateDirectoryPreferences, {
+ ok: false,
+ error: { code: 'permissionDenied' },
+ })
+ expect(
+ await h.preferences.mutate({ action: 'recordRecent', path: '/denied' })
+ ).toBe(false)
+ h.queue(Queries.GetDirectoryPreferences, success(saved))
+ h.preferences.subscribe(vi.fn())
+ await flush()
+ expect(h.preferences.getSnapshot()).toEqual({
+ preferences: saved,
+ loading: false,
+ error: null,
+ })
+ })
+
+ it('subscribes before reading and never overwrites a newer event with an older read', async () => {
+ const h = harness()
+ const response = deferred()
+ h.queue(Queries.GetDirectoryPreferences, response.promise)
+ h.preferences.subscribe(vi.fn())
+ await flush()
+ h.event(saved)
+ expect(h.preferences.getSnapshot()).toEqual({
+ preferences: saved,
+ loading: false,
+ error: null,
+ })
+ response.resolve(success(empty))
+ await flush()
+ expect(h.preferences.getSnapshot().preferences).toEqual(saved)
+ expect(h.bridge.invoke).toHaveBeenCalledExactlyOnceWith(
+ Queries.GetDirectoryPreferences,
+ {}
+ )
+ })
+
+ it('invalidates mutation-return snapshots on a newer removal event', async () => {
+ const h = harness()
+ await h.preferences.refresh()
+ const response = deferred()
+ h.queue(Commands.MutateDirectoryPreferences, response.promise)
+ const mutation = h.preferences.mutate({
+ action: 'addFavorite',
+ path: '/saved',
+ })
+ await flush()
+ h.event(empty)
+ response.resolve(success(saved))
+ expect(await mutation).toBe(true)
+ expect(h.preferences.getSnapshot()).toEqual({
+ preferences: empty,
+ loading: false,
+ error: null,
+ })
+ })
+
+ it('preserves literal paths and exposes a localized host failure without rejecting', async () => {
+ const h = harness()
+ h.queue(Commands.MutateDirectoryPreferences, {
+ ok: false,
+ error: { code: 'limitReached' },
+ })
+ await expect(
+ h.preferences.mutate({ action: 'addFavorite', path: '/ space ' })
+ ).resolves.toBe(false)
+ expect(h.bridge.invoke).toHaveBeenCalledWith(
+ Commands.MutateDirectoryPreferences,
+ { action: 'addFavorite', path: '/ space ' }
+ )
+ expect(h.preferences.getSnapshot()).toMatchObject({
+ error: 'limitReached',
+ loading: false,
+ })
+ })
+
+ it('rejects malformed action envelopes before transport', async () => {
+ const h = harness()
+ const invalid = {
+ action: 'clearRecent',
+ extra: true,
+ } as unknown as MutateDirectoryPreferencesRequest
+ expect(await h.preferences.mutate(invalid)).toBe(false)
+ expect(h.bridge.invoke).not.toHaveBeenCalled()
+ expect(h.preferences.getSnapshot().error).toBe('invalidPath')
+ })
+
+ it('treats a mutation timeout as unknown, refreshes authority, and never replays or accepts its late snapshot', async () => {
+ const h = harness()
+ await h.preferences.refresh()
+ const response = deferred()
+ h.queue(Commands.MutateDirectoryPreferences, response.promise)
+ h.queue(Queries.GetDirectoryPreferences, success(saved))
+ const mutation = h.preferences.mutate({
+ action: 'recordRecent',
+ path: '/recent',
+ })
+ await flush()
+ expect(h.preferences.getSnapshot().preferences).toEqual(empty)
+ await vi.advanceTimersByTimeAsync(DIRECTORY_PREFERENCES_TIMEOUT)
+ expect(await mutation).toBe(false)
+ expect(h.preferences.getSnapshot()).toEqual({
+ preferences: saved,
+ loading: false,
+ error: 'unavailable',
+ })
+ response.resolve(success(empty))
+ await flush()
+ expect(h.preferences.getSnapshot().preferences).toEqual(saved)
+ expect(
+ h.bridge.invoke.mock.calls.filter(
+ ([channel]) => channel === Commands.MutateDirectoryPreferences
+ )
+ ).toHaveLength(1)
+ expect(
+ h.bridge.invoke.mock.calls.filter(
+ ([channel]) => channel === Queries.GetDirectoryPreferences
+ )
+ ).toHaveLength(2)
+ })
+
+ it('bounds initial reads and recovers through an explicit refresh', async () => {
+ const h = harness()
+ h.queue(
+ Queries.GetDirectoryPreferences,
+ new Promise(() => {}),
+ success(saved)
+ )
+ const read = h.preferences.refresh()
+ await vi.advanceTimersByTimeAsync(DIRECTORY_PREFERENCES_TIMEOUT)
+ await read
+ expect(h.preferences.getSnapshot()).toMatchObject({
+ loading: false,
+ error: 'unavailable',
+ })
+ await h.preferences.refresh()
+ expect(h.preferences.getSnapshot()).toEqual({
+ preferences: saved,
+ loading: false,
+ error: null,
+ })
+ })
+
+ it('refreshes after reconnect and ignores the previous connection’s pending query', async () => {
+ const h = harness()
+ const response = deferred()
+ h.queue(Queries.GetDirectoryPreferences, response.promise, success(saved))
+ h.preferences.subscribe(vi.fn())
+ await flush()
+ h.reconnect()
+ await flush()
+ response.resolve(success(empty))
+ await flush()
+ expect(h.preferences.getSnapshot().preferences).toEqual(saved)
+ })
+
+ it('counts overlapping mutations without reviving an older successful snapshot', async () => {
+ const h = harness()
+ const first = deferred()
+ const second = deferred()
+ h.queue(Commands.MutateDirectoryPreferences, first.promise, second.promise)
+ const a = h.preferences.mutate({ action: 'addFavorite', path: '/saved' })
+ const b = h.preferences.mutate({ action: 'clearRecent' })
+ await flush()
+ second.resolve(success(empty))
+ expect(await b).toBe(true)
+ expect(h.preferences.getSnapshot().loading).toBe(true)
+ first.resolve(success(saved))
+ expect(await a).toBe(true)
+ expect(h.preferences.getSnapshot()).toEqual({
+ preferences: empty,
+ loading: false,
+ error: null,
+ })
+ })
+
+ it('removes the exact event callback on disposal and drops pending results', async () => {
+ const h = harness()
+ const response = deferred()
+ h.queue(Queries.GetDirectoryPreferences, response.promise)
+ const listener = vi.fn()
+ h.preferences.subscribe(listener)
+ await flush()
+ const callback = h.bridge.on.mock.calls[0][1]
+ h.preferences.dispose()
+ listener.mockClear()
+ response.resolve(success(saved))
+ h.event(saved)
+ h.reconnect()
+ await flush()
+ expect(listener).not.toHaveBeenCalled()
+ expect(h.bridge.off).toHaveBeenCalledWith(
+ Events.DirectoryPreferencesChanged,
+ callback
+ )
+ })
+})
+
+describe('ServerDirectoryLocationsStore', () => {
+ it('retains picker display data and shares unchanged groups while publishing each read phase once', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ const listener = vi.fn()
+ store.subscribe(listener)
+ await flush()
+ const before = store.getSnapshot().locations
+ const pending = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, pending.promise)
+ listener.mockClear()
+ h.event(saved)
+ expect(store.getSnapshot()).toMatchObject({
+ locations: before,
+ loading: true,
+ })
+ expect(store.getSnapshot().locations).toBe(before)
+ expect(listener).toHaveBeenCalledTimes(1)
+ const current = store.refresh()
+ const same = store.refresh()
+ expect(same).toBe(current)
+ pending.resolve(success(structuredClone(places)))
+ await current
+ expect(store.getSnapshot().locations).toBe(before)
+ expect(store.getSnapshot().loading).toBe(false)
+ expect(listener).toHaveBeenCalledTimes(2)
+ })
+
+ it.each([
+ { name: 'Saved', path: '/saved', sourcePaths: ['/saved'] },
+ { name: 'Renamed', path: '/saved', sourcePaths: ['/real/saved', '/saved'] },
+ { name: 'Saved', path: '/other', sourcePaths: ['/real/saved', '/saved'] },
+ ])(
+ 'updates a changed saved-location field without replacing unrelated groups: %j',
+ async (entry) => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ store.subscribe(vi.fn())
+ await flush()
+ const before = store.getSnapshot().locations
+ const next = { ...places, favorites: [entry] }
+ h.queue(Queries.ListServerDirectoryLocations, success(next))
+ await store.refresh()
+ expect(store.getSnapshot().locations?.common).toBe(before?.common)
+ expect(store.getSnapshot().locations?.recent).toBe(before?.recent)
+ expect(store.getSnapshot().locations?.favorites).not.toBe(
+ before?.favorites
+ )
+ expect(store.getSnapshot().locations?.favorites).toEqual(next.favorites)
+ }
+ )
+
+ it('does not reuse a common group when only a semantic shortcut kind changes', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ store.subscribe(vi.fn())
+ await flush()
+ const before = store.getSnapshot().locations
+ const next = {
+ ...places,
+ common: [{ kind: 'desktop', path: '/downloads' }, places.common[1]],
+ }
+ h.queue(Queries.ListServerDirectoryLocations, success(next))
+ await store.refresh()
+ expect(store.getSnapshot().locations?.common).not.toBe(before?.common)
+ expect(store.getSnapshot().locations?.common).toEqual(next.common)
+ expect(store.getSnapshot().locations?.favorites).toBe(before?.favorites)
+ })
+
+ it('reuses only the in-flight or applied authorization caused by this mutation’s matching event', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ store.subscribe(vi.fn())
+ await flush()
+ const revision = store.getRevision()
+ h.bridge.invoke.mockClear()
+ const pending = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, pending.promise)
+ h.event(saved)
+ await flush()
+ const fallback = store.refreshAfterMutation(revision, saved)
+ await flush()
+ expect(h.bridge.invoke).toHaveBeenCalledTimes(1)
+ pending.resolve(success(places))
+ await fallback
+ await store.refreshAfterMutation(revision, saved)
+ expect(h.bridge.invoke).toHaveBeenCalledTimes(1)
+ })
+
+ it('starts a post-commit read when another client’s unrelated event arrived before this mutation reply', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ store.subscribe(vi.fn())
+ await flush()
+ const revision = store.getRevision()
+ h.bridge.invoke.mockClear()
+ const old = deferred()
+ const fresh = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, old.promise, fresh.promise)
+ h.event(empty)
+ await flush()
+ const fallback = store.refreshAfterMutation(revision, saved)
+ await flush()
+ expect(h.bridge.invoke).toHaveBeenCalledTimes(2)
+ old.resolve(success({ common: [], favorites: [], recent: [] }))
+ await flush()
+ expect(store.getSnapshot().loading).toBe(true)
+ fresh.resolve(success(places))
+ await fallback
+ expect(store.getSnapshot().locations).toEqual(places)
+ })
+
+ it('does not reuse a pending pre-commit read or a matching event seen before the action began', async () => {
+ const h = harness()
+ const store = h.locations()
+ store.subscribe(vi.fn())
+ await flush()
+ h.event(saved)
+ await flush()
+ const revision = store.getRevision()
+ h.bridge.invoke.mockClear()
+ const old = deferred()
+ const fresh = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, old.promise, fresh.promise)
+ const preCommit = store.refresh()
+ await flush()
+ const fallback = store.refreshAfterMutation(revision, saved)
+ await flush()
+ expect(h.bridge.invoke).toHaveBeenCalledTimes(2)
+ old.resolve(success({ common: [], favorites: [], recent: [] }))
+ await preCommit
+ expect(store.getSnapshot().locations).toBeNull()
+ fresh.resolve(success(places))
+ await fallback
+ expect(store.getSnapshot().locations).toEqual(places)
+ })
+
+ it('rechecks unknown mutation outcomes without replaying the action and clears retained data on failure', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ store.subscribe(vi.fn())
+ await flush()
+ const revision = store.getRevision()
+ h.bridge.invoke.mockClear()
+ h.queue(
+ Queries.ListServerDirectoryLocations,
+ success({ common: places.common, favorites: [], recent: [] })
+ )
+ await store.refreshAfterMutation(revision)
+ expect(store.getSnapshot().locations?.favorites).toEqual([])
+ expect(h.bridge.invoke).toHaveBeenCalledExactlyOnceWith(
+ Queries.ListServerDirectoryLocations,
+ {}
+ )
+ h.queue(Queries.ListServerDirectoryLocations, {
+ ok: false,
+ error: { code: 'unavailable' },
+ })
+ await store.refresh()
+ expect(store.getSnapshot()).toEqual({
+ locations: null,
+ error: 'unavailable',
+ loading: false,
+ })
+ })
+
+ it('stops hidden-menu location IO, cancels late reads locally, and reauthorizes on reopen', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ const unsubscribe = store.subscribe(vi.fn())
+ await flush()
+ const pending = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, pending.promise)
+ const read = store.refresh()
+ await flush()
+ h.bridge.invoke.mockClear()
+ unsubscribe()
+ expect(store.getSnapshot()).toEqual({
+ locations: null,
+ loading: false,
+ error: null,
+ })
+ h.event(saved)
+ h.reconnect()
+ pending.resolve(success(places))
+ await read
+ await flush()
+ expect(h.bridge.invoke).not.toHaveBeenCalled()
+ expect(store.getSnapshot().locations).toBeNull()
+ store.subscribe(vi.fn())
+ expect(store.getSnapshot().locations).toBeNull()
+ await flush()
+ expect(h.bridge.invoke).toHaveBeenCalledExactlyOnceWith(
+ Queries.ListServerDirectoryLocations,
+ {}
+ )
+ })
+
+ it('avoids dispatching requests after immediate last-unsubscribe and coalesces synchronous event bursts', async () => {
+ const h = harness()
+ const store = h.locations()
+ const unsubscribe = store.subscribe(vi.fn())
+ unsubscribe()
+ await flush()
+ expect(h.bridge.invoke).not.toHaveBeenCalled()
+ store.subscribe(vi.fn())
+ await flush()
+ h.bridge.invoke.mockClear()
+ h.event(empty)
+ h.event(saved)
+ await flush()
+ expect(h.bridge.invoke).toHaveBeenCalledExactlyOnceWith(
+ Queries.ListServerDirectoryLocations,
+ {}
+ )
+ })
+
+ it('clears retained authorization immediately on reconnect', async () => {
+ const h = harness()
+ const store = h.locations({ retainWhileRefreshing: true })
+ store.subscribe(vi.fn())
+ await flush()
+ const pending = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, pending.promise)
+ h.reconnect()
+ expect(store.getSnapshot()).toMatchObject({
+ locations: null,
+ loading: true,
+ })
+ pending.resolve(success(places))
+ await flush()
+ expect(store.getSnapshot().locations).toEqual(places)
+ })
+
+ it('clears visible locations synchronously on an event and rejects all earlier responses', async () => {
+ const h = harness()
+ const store = h.locations()
+ store.subscribe(vi.fn())
+ await flush()
+ expect(store.getSnapshot().locations).toEqual(places)
+ const stale = deferred()
+ const fresh = deferred()
+ h.queue(Queries.ListServerDirectoryLocations, stale.promise, fresh.promise)
+ const oldRead = store.refresh()
+ await flush()
+ h.event(empty)
+ expect(store.getSnapshot().locations).toBeNull()
+ expect(store.getSnapshot().loading).toBe(true)
+ await flush()
+ stale.resolve(success(places))
+ await oldRead
+ expect(store.getSnapshot().locations).toBeNull()
+ fresh.resolve(success({ common: places.common, favorites: [], recent: [] }))
+ await flush()
+ expect(store.getSnapshot().locations?.favorites).toEqual([])
+ expect(store.getSnapshot().locations?.common).toHaveLength(2)
+ })
+
+ it('re-authorizes filesystem locations when the last menu consumer reopens', async () => {
+ const h = harness()
+ const store = h.locations()
+ const unsubscribe = store.subscribe(vi.fn())
+ await flush()
+ unsubscribe()
+ h.queue(
+ Queries.ListServerDirectoryLocations,
+ success({ common: [], favorites: [], recent: [] })
+ )
+ store.subscribe(vi.fn())
+ expect(store.getSnapshot().locations).toBeNull()
+ await flush()
+ expect(store.getSnapshot().locations?.favorites).toEqual([])
+ expect(h.bridge.invoke).toHaveBeenCalledTimes(2)
+ })
+
+ it('bounds optional locations requests, sanitizes malformed replies and supports retry', async () => {
+ const h = harness()
+ const store = h.locations()
+ h.queue(
+ Queries.ListServerDirectoryLocations,
+ new Promise(() => {}),
+ { ok: true, value: { ...places, secret: true } },
+ success(places)
+ )
+ const read = store.refresh()
+ await vi.advanceTimersByTimeAsync(DIRECTORY_PREFERENCES_TIMEOUT)
+ await read
+ expect(store.getSnapshot()).toEqual({
+ locations: null,
+ loading: false,
+ error: 'unavailable',
+ })
+ await store.refresh()
+ expect(store.getSnapshot().error).toBe('unavailable')
+ await store.refresh()
+ expect(store.getSnapshot()).toEqual({
+ locations: places,
+ loading: false,
+ error: null,
+ })
+ })
+
+ it('does not invoke a Server-only query for a disabled Desktop consumer', async () => {
+ const { result } = renderHook(() => useServerDirectoryLocations(false))
+ await flush()
+ expect(result.current.locations).toBeNull()
+ expect(transport.invoke).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/lib/directory-preferences.ts b/src/renderer/lib/directory-preferences.ts
new file mode 100644
index 00000000..7688fc70
--- /dev/null
+++ b/src/renderer/lib/directory-preferences.ts
@@ -0,0 +1,508 @@
+import { transport } from '@renderer/lib/transport'
+import type { Transport } from '@renderer/lib/transport/types'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import {
+ type DirectoryPreferences,
+ type DirectoryPreferencesErrorCode,
+ DirectoryPreferencesResultSchema,
+ DirectoryPreferencesSchema,
+ type MutateDirectoryPreferencesRequest,
+ MutateDirectoryPreferencesRequestSchema,
+} from '@shared/schemas/directory-preferences'
+import {
+ type DirectoryErrorCode,
+ ListServerDirectoryLocationsResultSchema,
+ type ServerDirectoryLocations,
+} from '@shared/schemas/server-directory'
+import { useSyncExternalStore } from 'react'
+import type { z } from 'zod'
+
+export const DIRECTORY_PREFERENCES_TIMEOUT = 20_000
+type DirectoryTransport = Pick<Transport, 'invoke'> &
+ Partial<Pick<Transport, 'on' | 'off' | 'onConnectionChange'>>
+
+class DirectoryPreferenceRequestError extends Error {
+ constructor(readonly timeout = false) {
+ super('Directory preferences request unavailable')
+ }
+}
+
+function request<T>(
+ bridge: DirectoryTransport,
+ channel: Parameters<Transport['invoke']>[0],
+ schema: z.ZodType<T>,
+ args: unknown,
+ signal?: AbortSignal
+): Promise<T> {
+ return new Promise((resolve, reject) => {
+ let settled = false
+ const finish = (value: T | undefined, error?: unknown) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', abort)
+ if (error) reject(error)
+ else resolve(value as T)
+ }
+ const abort = () => finish(undefined, new DirectoryPreferenceRequestError())
+ const timer = setTimeout(
+ () => finish(undefined, new DirectoryPreferenceRequestError(true)),
+ DIRECTORY_PREFERENCES_TIMEOUT
+ )
+ signal?.addEventListener('abort', abort, { once: true })
+ if (signal?.aborted) {
+ abort()
+ return
+ }
+ Promise.resolve()
+ .then(() => {
+ if (signal?.aborted) throw new DirectoryPreferenceRequestError()
+ return bridge.invoke(channel, args)
+ })
+ .then((value) => {
+ if (!settled) finish(schema.parse(value))
+ })
+ .catch(() => finish(undefined, new DirectoryPreferenceRequestError()))
+ })
+}
+
+function sharePaths(previous: string[], next: string[]): string[] {
+ return previous.length === next.length &&
+ previous.every((value, index) => value === next[index])
+ ? previous
+ : next
+}
+
+function sharePreferences(
+ previous: DirectoryPreferences,
+ next: DirectoryPreferences
+): DirectoryPreferences {
+ const favorites = sharePaths(previous.favorites, next.favorites)
+ const recent = sharePaths(previous.recent, next.recent)
+ return favorites === previous.favorites && recent === previous.recent
+ ? previous
+ : { favorites, recent }
+}
+
+function shareLocations(
+ previous: ServerDirectoryLocations | null,
+ next: ServerDirectoryLocations
+): ServerDirectoryLocations {
+ if (!previous) return next
+ const common =
+ previous.common.length === next.common.length &&
+ previous.common.every(
+ (entry, index) =>
+ entry.kind === next.common[index].kind &&
+ entry.path === next.common[index].path
+ )
+ ? previous.common
+ : next.common
+ const shareEntries = (
+ before: ServerDirectoryLocations['favorites'],
+ after: ServerDirectoryLocations['favorites']
+ ) => {
+ const entries = after.map((entry, index) => {
+ const old = before[index]
+ return old &&
+ old.name === entry.name &&
+ old.path === entry.path &&
+ sharePaths(old.sourcePaths, entry.sourcePaths) === old.sourcePaths
+ ? old
+ : entry
+ })
+ return before.length === entries.length &&
+ entries.every((entry, index) => entry === before[index])
+ ? before
+ : entries
+ }
+ const favorites = shareEntries(previous.favorites, next.favorites)
+ const recent = shareEntries(previous.recent, next.recent)
+ return common === previous.common &&
+ favorites === previous.favorites &&
+ recent === previous.recent
+ ? previous
+ : { common, favorites, recent }
+}
+
+type PreferencesState = {
+ preferences: DirectoryPreferences
+ loading: boolean
+ error: DirectoryPreferencesErrorCode | null
+}
+
+/** Host-owned data: this mirror never writes whole lists or uses browser storage. */
+export class DirectoryPreferencesStore {
+ private state: PreferencesState = {
+ preferences: { favorites: [], recent: [] },
+ loading: true,
+ error: null,
+ }
+ private listeners = new Set<() => void>()
+ private started = false
+ private disposed = false
+ private epoch = 0
+ private reading = false
+ private pendingMutations = 0
+ private disconnect?: () => void
+
+ constructor(private readonly bridge: DirectoryTransport) {}
+
+ getSnapshot = () => this.state
+ subscribe = (listener: () => void) => {
+ const firstSubscriber = this.listeners.size === 0
+ this.listeners.add(listener)
+ if (this.start() || firstSubscriber) void this.refresh()
+ return () => {
+ this.listeners.delete(listener)
+ }
+ }
+ private update(patch: Partial<PreferencesState>) {
+ if (this.disposed) return
+ const next = {
+ ...this.state,
+ ...patch,
+ preferences: patch.preferences
+ ? sharePreferences(this.state.preferences, patch.preferences)
+ : this.state.preferences,
+ }
+ if (
+ next.preferences === this.state.preferences &&
+ next.loading === this.state.loading &&
+ next.error === this.state.error
+ )
+ return
+ this.state = next
+ for (const listener of this.listeners) listener()
+ }
+ private changed = (payload: unknown) => {
+ this.epoch++
+ this.reading = false
+ const parsed = DirectoryPreferencesSchema.safeParse(payload)
+ if (parsed.success) {
+ this.update({
+ preferences: parsed.data,
+ error: null,
+ loading: this.pendingMutations > 0,
+ })
+ } else void this.refresh()
+ }
+ private start() {
+ if (this.started || this.disposed) return false
+ this.started = true
+ this.bridge.on?.(Events.DirectoryPreferencesChanged, this.changed)
+ this.disconnect = this.bridge.onConnectionChange?.(({ state }) => {
+ if (state === 'connected') void this.refresh()
+ })
+ return true
+ }
+ refresh = async (preserveError = false): Promise<void> => {
+ if (this.disposed) return
+ this.start()
+ const epoch = ++this.epoch
+ this.reading = true
+ this.update({ loading: true, ...(preserveError ? {} : { error: null }) })
+ try {
+ const result = await request(
+ this.bridge,
+ Queries.GetDirectoryPreferences,
+ DirectoryPreferencesResultSchema,
+ {}
+ )
+ if (this.disposed || epoch !== this.epoch) return
+ if (result.ok)
+ this.update({
+ preferences: result.value,
+ ...(preserveError ? {} : { error: null }),
+ })
+ else this.update({ error: result.error.code })
+ } catch {
+ if (!this.disposed && epoch === this.epoch)
+ this.update({ error: 'unavailable' })
+ } finally {
+ if (!this.disposed && epoch === this.epoch) {
+ this.reading = false
+ this.update({ loading: this.pendingMutations > 0 })
+ }
+ }
+ }
+ mutate = async (
+ action: MutateDirectoryPreferencesRequest,
+ onCommitted?: (preferences: DirectoryPreferences) => void
+ ): Promise<boolean> => {
+ if (this.disposed) return false
+ const parsed = MutateDirectoryPreferencesRequestSchema.safeParse(action)
+ if (!parsed.success) {
+ this.update({
+ error: 'invalidPath',
+ loading: this.reading || this.pendingMutations > 0,
+ })
+ return false
+ }
+ this.start()
+ const epoch = ++this.epoch
+ this.reading = false
+ this.pendingMutations++
+ this.update({ loading: true, error: null })
+ try {
+ const result = await request(
+ this.bridge,
+ Commands.MutateDirectoryPreferences,
+ DirectoryPreferencesResultSchema,
+ parsed.data
+ )
+ if (this.disposed) return false
+ if (epoch === this.epoch) {
+ this.update(
+ result.ok
+ ? { preferences: result.value, error: null }
+ : { error: result.error.code }
+ )
+ }
+ if (result.ok) onCommitted?.(result.value)
+ return result.ok
+ } catch {
+ if (this.disposed) return false
+ if (epoch === this.epoch) this.update({ error: 'unavailable' })
+ // A lost reply may follow a committed write. Read the host again without
+ // replaying the action or making an optimistic local change.
+ void this.refresh(true)
+ return false
+ } finally {
+ this.pendingMutations--
+ this.update({ loading: this.reading || this.pendingMutations > 0 })
+ }
+ }
+ dispose() {
+ this.disposed = true
+ this.epoch++
+ this.bridge.off?.(Events.DirectoryPreferencesChanged, this.changed)
+ this.disconnect?.()
+ this.listeners.clear()
+ }
+}
+
+type LocationsState = {
+ locations: ServerDirectoryLocations | null
+ loading: boolean
+ error: DirectoryErrorCode | null
+}
+const EMPTY_LOCATIONS: LocationsState = {
+ locations: null,
+ loading: false,
+ error: null,
+}
+
+export interface ServerDirectoryLocationsOptions {
+ /** Display only: consumers must disable saved-location actions while loading. */
+ retainWhileRefreshing?: boolean
+}
+
+type LocationsEvent = { revision: number; fingerprint: string }
+type LocationsRequest = {
+ epoch: number
+ event: LocationsEvent | undefined
+ controller: AbortController
+ promise: Promise<void>
+}
+
+/** Optional authorized locations have a deadline and epoch separate from browsing. */
+export class ServerDirectoryLocationsStore {
+ private state: LocationsState = EMPTY_LOCATIONS
+ private listeners = new Set<() => void>()
+ private started = false
+ private disposed = false
+ private epoch = 0
+ private revision = 0
+ private latestEvent?: LocationsEvent
+ private pending?: LocationsRequest
+ private applied?: { epoch: number; event: LocationsEvent | undefined }
+ private disconnect?: () => void
+
+ constructor(
+ private readonly bridge: DirectoryTransport,
+ private readonly options: ServerDirectoryLocationsOptions = {}
+ ) {}
+
+ getSnapshot = () => this.state
+ getRevision = () => this.revision
+ subscribe = (listener: () => void) => {
+ const firstSubscriber = this.listeners.size === 0
+ this.listeners.add(listener)
+ if (firstSubscriber) {
+ this.start()
+ // Reopening requires a fresh authorization, even with a retained cache.
+ this.invalidate()
+ void this.startRead(true)
+ }
+ return () => {
+ this.listeners.delete(listener)
+ if (this.listeners.size === 0) this.stop()
+ }
+ }
+ private update(patch: Partial<LocationsState>) {
+ if (this.disposed) return
+ const next = {
+ ...this.state,
+ ...patch,
+ locations: patch.locations
+ ? shareLocations(this.state.locations, patch.locations)
+ : patch.locations === null
+ ? null
+ : this.state.locations,
+ }
+ if (
+ next.locations === this.state.locations &&
+ next.loading === this.state.loading &&
+ next.error === this.state.error
+ )
+ return
+ this.state = next
+ for (const listener of this.listeners) listener()
+ }
+ private invalidate() {
+ this.revision++
+ this.epoch++
+ this.pending?.controller.abort()
+ this.pending = undefined
+ this.applied = undefined
+ }
+ private changed = (payload: unknown) => {
+ this.invalidate()
+ const parsed = DirectoryPreferencesSchema.safeParse(payload)
+ this.latestEvent = parsed.success
+ ? { revision: this.revision, fingerprint: JSON.stringify(parsed.data) }
+ : undefined
+ if (this.listeners.size > 0) void this.refresh()
+ else this.update({ locations: null, loading: false, error: null })
+ }
+ private start() {
+ if (this.started || this.disposed) return
+ this.started = true
+ this.bridge.on?.(Events.DirectoryPreferencesChanged, this.changed)
+ this.disconnect = this.bridge.onConnectionChange?.(({ state }) => {
+ if (state !== 'connected') return
+ this.invalidate()
+ this.latestEvent = undefined
+ if (this.listeners.size > 0) void this.startRead(true)
+ else this.update({ locations: null, loading: false, error: null })
+ })
+ }
+ private stop() {
+ this.started = false
+ this.bridge.off?.(Events.DirectoryPreferencesChanged, this.changed)
+ this.disconnect?.()
+ this.disconnect = undefined
+ this.invalidate()
+ this.latestEvent = undefined
+ this.update({ locations: null, loading: false, error: null })
+ }
+ /** Only an authorization read caused by this committed snapshot replaces the fallback. */
+ refreshAfterMutation = (
+ since: number,
+ committed?: DirectoryPreferences
+ ): Promise<void> => {
+ if (this.disposed) return Promise.resolve()
+ const event = this.latestEvent
+ const read = this.pending ?? this.applied
+ if (
+ committed &&
+ event &&
+ event.revision > since &&
+ event.fingerprint === JSON.stringify(committed) &&
+ read?.epoch === this.epoch &&
+ read.event === event
+ )
+ return this.pending?.promise ?? Promise.resolve()
+ // A different client's event or a pre-commit read cannot certify this action.
+ // Unknown mutation outcomes also need an authoritative read without replay.
+ this.invalidate()
+ return this.refresh()
+ }
+ refresh = (): Promise<void> =>
+ this.startRead(!this.options.retainWhileRefreshing)
+ private startRead(clear: boolean): Promise<void> {
+ if (this.disposed) return Promise.resolve()
+ if (this.pending?.epoch === this.epoch) return this.pending.promise
+ this.start()
+ const pending: LocationsRequest = {
+ epoch: ++this.epoch,
+ event: this.latestEvent,
+ controller: new AbortController(),
+ promise: Promise.resolve(),
+ }
+ this.pending = pending
+ this.update({
+ loading: true,
+ error: null,
+ ...(clear ? { locations: null } : {}),
+ })
+ pending.promise = this.read(pending)
+ return pending.promise
+ }
+ private async read(pending: LocationsRequest): Promise<void> {
+ try {
+ const result = await request(
+ this.bridge,
+ Queries.ListServerDirectoryLocations,
+ ListServerDirectoryLocationsResultSchema,
+ {},
+ pending.controller.signal
+ )
+ if (this.disposed || pending.epoch !== this.epoch) return
+ this.pending = undefined
+ this.applied = result.ok
+ ? { epoch: pending.epoch, event: pending.event }
+ : undefined
+ this.update(
+ result.ok
+ ? { locations: result.value, error: null, loading: false }
+ : { locations: null, error: result.error.code, loading: false }
+ )
+ } catch {
+ if (!this.disposed && pending.epoch === this.epoch) {
+ this.pending = undefined
+ this.applied = undefined
+ this.update({ locations: null, error: 'unavailable', loading: false })
+ }
+ }
+ }
+ dispose() {
+ this.disposed = true
+ this.stop()
+ this.listeners.clear()
+ }
+}
+
+export const directoryPreferences = new DirectoryPreferencesStore(transport)
+export const serverDirectoryLocations = new ServerDirectoryLocationsStore(
+ transport
+)
+
+export function useDirectoryPreferences() {
+ const snapshot = useSyncExternalStore(
+ directoryPreferences.subscribe,
+ directoryPreferences.getSnapshot
+ )
+ return {
+ ...snapshot,
+ refresh: directoryPreferences.refresh,
+ mutate: directoryPreferences.mutate,
+ }
+}
+
+const subscribeDisabled = () => () => {}
+const getDisabledLocations = () => EMPTY_LOCATIONS
+export function useServerDirectoryLocations(enabled = true) {
+ const snapshot = useSyncExternalStore(
+ enabled ? serverDirectoryLocations.subscribe : subscribeDisabled,
+ enabled ? serverDirectoryLocations.getSnapshot : getDisabledLocations
+ )
+ return { ...snapshot, refresh: serverDirectoryLocations.refresh }
+}
+
+export async function recordRecentDirectory(path: string): Promise<void> {
+ await directoryPreferences.mutate({ action: 'recordRecent', path })
+}
diff --git a/src/renderer/platform/services.tsx b/src/renderer/platform/services.tsx
index ad6ec872..7896388e 100644
--- a/src/renderer/platform/services.tsx
+++ b/src/renderer/platform/services.tsx
@@ -12,7 +12,13 @@ export interface PluginInstallFileCapability {
export interface PlatformServices {
readonly kind: 'electron' | 'web'
readonly pluginInstallFile?: PluginInstallFileCapability
- pickSaveDir(defaultPath?: string): Promise<string | null>
+ pickSaveDir(
+ defaultPath?: string,
+ options?: {
+ /** Draft forms keep application favorites behind their own Save boundary. */
+ allowFavoriteEditing?: boolean
+ }
+ ): Promise<string | null>
closeHost(options?: {
showMain?: boolean
/**
diff --git a/src/renderer/platform/web-services.test.ts b/src/renderer/platform/web-services.test.ts
index 58fef2e8..8f241fcc 100644
--- a/src/renderer/platform/web-services.test.ts
+++ b/src/renderer/platform/web-services.test.ts
@@ -1,5 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { __webPathPickerBus, createWebServices } from './web-services'
+import {
+ __webPathPickerBus,
+ createWebServices,
+ PathPickerBus,
+} from './web-services'
describe('createWebServices', () => {
let services: ReturnType<typeof createWebServices>
@@ -14,17 +18,40 @@ describe('createWebServices', () => {
it('pickSaveDir emits on bus and resolves on response', async () => {
const spy = vi.fn()
- __webPathPickerBus.subscribe(spy)
+ const unsubscribe = __webPathPickerBus.subscribe(spy)
const pending = services.pickSaveDir('/prev')
- expect(spy).toHaveBeenCalledWith({ defaultPath: '/prev' })
- __webPathPickerBus.resolve('/selected')
+ expect(spy).toHaveBeenCalledWith(
+ expect.objectContaining({ defaultPath: '/prev', id: expect.any(Number) })
+ )
+ __webPathPickerBus.resolve(spy.mock.calls[0][0].id, '/selected')
expect(await pending).toBe('/selected')
+ unsubscribe()
})
it('pickSaveDir resolves null on cancel', async () => {
+ const spy = vi.fn()
+ const unsubscribe = __webPathPickerBus.subscribe(spy)
const pending = services.pickSaveDir()
- __webPathPickerBus.resolve(null)
+ __webPathPickerBus.resolve(spy.mock.calls[0][0].id, null)
expect(await pending).toBeNull()
+ unsubscribe()
+ })
+
+ it('carries the draft form boundary into the Web picker request', async () => {
+ const listener = vi.fn()
+ const unsubscribe = __webPathPickerBus.subscribe(listener)
+ const pending = services.pickSaveDir('/draft', {
+ allowFavoriteEditing: false,
+ })
+ expect(listener).toHaveBeenCalledWith(
+ expect.objectContaining({
+ defaultPath: '/draft',
+ allowFavoriteEditing: false,
+ })
+ )
+ __webPathPickerBus.resolve(listener.mock.calls[0][0].id, null)
+ await expect(pending).resolves.toBeNull()
+ unsubscribe()
})
it('readClipboard returns empty on permission denial', async () => {
@@ -82,3 +109,41 @@ describe('createWebServices', () => {
).rejects.toThrow('Plugin upload failed (413)')
})
})
+
+describe('PathPickerBus session ownership', () => {
+ it('settles a no-host request without leaving a pending promise', async () => {
+ await expect(new PathPickerBus().request({})).resolves.toBeNull()
+ })
+
+ it('rejects stale resolution and focus restoration after supersession', async () => {
+ const bus = new PathPickerBus()
+ const listener = vi.fn()
+ const unsubscribe = bus.subscribe(listener)
+ const a = bus.request({ defaultPath: '/a' })
+ const aId = listener.mock.calls[0][0].id
+ const b = bus.request({ defaultPath: '/b' })
+ const bId = listener.mock.calls[1][0].id
+ await expect(a).resolves.toBeNull()
+ bus.resolve(aId, '/stale')
+ expect(bus.canRestoreFocus(aId)).toBe(false)
+ expect(bus.canRestoreFocus(bId)).toBe(false)
+ bus.resolve(bId, '/b')
+ await expect(b).resolves.toBe('/b')
+ expect(bus.canRestoreFocus(bId)).toBe(true)
+ unsubscribe()
+ })
+
+ it('captures the opener synchronously and settles when the host unmounts', async () => {
+ const bus = new PathPickerBus()
+ const opener = document.createElement('button')
+ document.body.append(opener)
+ opener.focus()
+ const listener = vi.fn()
+ const unsubscribe = bus.subscribe(listener)
+ const pending = bus.request({})
+ expect(listener.mock.calls[0][0].opener).toBe(opener)
+ unsubscribe()
+ await expect(pending).resolves.toBeNull()
+ opener.remove()
+ })
+})
diff --git a/src/renderer/platform/web-services.ts b/src/renderer/platform/web-services.ts
index 83b034a1..b8792f26 100644
--- a/src/renderer/platform/web-services.ts
+++ b/src/renderer/platform/web-services.ts
@@ -4,35 +4,60 @@ import type { PlatformServices } from './services'
const SHA256_RE = /^[0-9a-f]{64}$/
-type PickRequest = { defaultPath?: string }
+export type PickRequest = {
+ id: number
+ defaultPath?: string
+ allowFavoriteEditing?: boolean
+ opener: HTMLElement | null
+}
type PickListener = (req: PickRequest) => void
-class PathPickerBus {
+export class PathPickerBus {
private listeners: Set<PickListener> = new Set()
- private pending: ((v: string | null) => void) | null = null
+ private pending: { id: number; resolve: (v: string | null) => void } | null =
+ null
+ private latestId = 0
subscribe(cb: PickListener): () => void {
this.listeners.add(cb)
- return () => this.listeners.delete(cb)
+ return () => {
+ this.listeners.delete(cb)
+ if (this.listeners.size === 0 && this.pending)
+ this.resolve(this.pending.id, null)
+ }
}
- request(req: PickRequest): Promise<string | null> {
+ request(req: {
+ defaultPath?: string
+ allowFavoriteEditing?: boolean
+ }): Promise<string | null> {
+ const id = ++this.latestId
+ const opener =
+ typeof document !== 'undefined' &&
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
if (this.pending) {
- this.pending(null)
+ this.pending.resolve(null)
this.pending = null
}
+ if (this.listeners.size === 0) return Promise.resolve(null)
return new Promise((resolve) => {
- this.pending = resolve
- for (const l of this.listeners) l(req)
+ this.pending = { id, resolve }
+ for (const l of this.listeners) l({ ...req, id, opener })
})
}
- resolve(value: string | null): void {
- if (this.pending) {
- this.pending(value)
+ resolve(id: number, value: string | null): void {
+ if (this.pending?.id === id) {
+ this.pending.resolve(value)
this.pending = null
}
}
+
+ canRestoreFocus(id: number): boolean {
+ return this.latestId === id && this.pending === null
+ }
}
// Exported for the DialogHost to subscribe; also for tests.
@@ -96,8 +121,8 @@ export function createWebServices(
},
},
- pickSaveDir(defaultPath) {
- return __webPathPickerBus.request({ defaultPath })
+ pickSaveDir(defaultPath, options) {
+ return __webPathPickerBus.request({ defaultPath, ...options })
},
closeHost() {
diff --git a/src/renderer/routes/settings/cards/general-dialog.test.tsx b/src/renderer/routes/settings/cards/general-dialog.test.tsx
index 70c44ef2..1bf91cbc 100644
--- a/src/renderer/routes/settings/cards/general-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.test.tsx
@@ -1,8 +1,13 @@
+import type { SaveGeneralSettingsRequest } from '@shared/schemas/general-settings'
+import {
+ generalSettingsSnapshot,
+ TEST_GENERAL_REVISION,
+} from '@test-utils/general-settings'
import '@renderer/lib/i18n'
import '@testing-library/jest-dom/vitest'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
-import { render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -12,15 +17,16 @@ const transportMock = vi.hoisted(() => ({
on: vi.fn(),
off: vi.fn(),
platform: 'darwin' as NodeJS.Platform | 'web',
+ pickSaveDir: vi.fn(),
}))
vi.mock('@renderer/lib/transport', () => ({
transport: transportMock,
}))
-const { pickSaveDir } = vi.hoisted(() => ({ pickSaveDir: vi.fn() }))
+const pickSaveDir = transportMock.pickSaveDir
vi.mock('@renderer/platform/services', () => ({
- usePlatformServices: () => ({ pickSaveDir }),
+ usePlatformServices: () => ({ pickSaveDir: transportMock.pickSaveDir }),
}))
import { transport } from '@renderer/lib/transport'
@@ -50,18 +56,184 @@ const SETTINGS_FIXTURE = {
},
}
+const generalResult = (
+ preferences = { favorites: [] as string[], recent: [] as string[] },
+ app = SETTINGS_FIXTURE.app
+) => ({ ok: true, value: generalSettingsSnapshot(preferences, app) })
+
beforeEach(() => {
vi.stubGlobal('ResizeObserver', MockResizeObserver)
transportMock.platform = 'darwin'
+ transportMock.pickSaveDir.mockReset().mockResolvedValue(null)
vi.mocked(transport.invoke).mockReset()
vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
- if (channel === Queries.GetSettings) return SETTINGS_FIXTURE
- return { saved: true, requiresRestart: false, changedRestartKeys: [] }
+ if (channel === Queries.GetGeneralSettingsDraft) return generalResult()
+ return generalResult()
})
})
describe('<GeneralDialog>', () => {
- it('hydrates from GetSettings', async () => {
+ it('keeps failed initial settings controls disabled and focuses a stable element before Retry', async () => {
+ let attempts = 0
+ let release!: (value: unknown) => void
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel !== Queries.GetGeneralSettingsDraft) return generalResult()
+ if (++attempts === 1) throw new Error('offline')
+ return new Promise((resolve) => {
+ release = resolve
+ })
+ })
+ render(
+ <GeneralDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.general.title"
+ descKey="settings.cards.general.desc"
+ />
+ )
+ await screen.findByRole('alert')
+ const toggle = screen.getByRole('switch', { name: /notify on failure/i })
+ const original = toggle.getAttribute('aria-checked')
+ await userEvent.click(toggle)
+ expect(toggle).toHaveAttribute('aria-checked', original)
+ const retry = screen.getByRole('button', { name: 'Retry' })
+ retry.focus()
+ await userEvent.click(retry)
+ expect(screen.getByRole('dialog')).toContainElement(
+ document.activeElement as HTMLElement
+ )
+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ await act(async () => release(generalResult()))
+ await screen.findByDisplayValue('/Users/me/Downloads')
+ })
+
+ it.each(['Cancel', 'Save'])(
+ 'keeps directory edits and the default Browse selection in the same %s session',
+ async (action) => {
+ const preferences = { favorites: ['/saved '], recent: ['/recent'] }
+ vi.mocked(transport.invoke).mockImplementation(async (channel) =>
+ channel === Queries.GetGeneralSettingsDraft
+ ? generalResult(preferences)
+ : generalResult(preferences)
+ )
+ transportMock.pickSaveDir.mockResolvedValue('/new-default')
+ const onClose = vi.fn()
+ render(
+ <GeneralDialog
+ open
+ onClose={onClose}
+ labelKey="settings.cards.general.title"
+ descKey="settings.cards.general.desc"
+ />
+ )
+ await screen.findByRole('button', { name: 'Remove favorite /saved' })
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Remove favorite /saved' })
+ )
+ await userEvent.click(
+ screen.getByRole('switch', { name: /notify on failure/i })
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Browse…' }))
+ await screen.findByDisplayValue('/new-default')
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.every(
+ ([channel]) => channel === Queries.GetGeneralSettingsDraft
+ )
+ ).toBe(true)
+ await userEvent.click(screen.getByRole('button', { name: action }))
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
+ if (action === 'Save') {
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveGeneralSettings,
+ {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { defaultSaveDir: '/new-default', notifyOnError: false },
+ directories: {
+ addFavorites: [],
+ removeFavorites: ['/saved '],
+ removeRecent: [],
+ },
+ }
+ )
+ } else {
+ expect(vi.mocked(transport.invoke).mock.calls).toHaveLength(1)
+ }
+ }
+ )
+
+ it('locks Save, Cancel and Escape while default-directory Browse is pending', async () => {
+ let release!: (path: string | null) => void
+ transportMock.pickSaveDir.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ release = resolve
+ })
+ )
+ const onClose = vi.fn()
+ render(
+ <GeneralDialog
+ open
+ onClose={onClose}
+ labelKey="settings.cards.general.title"
+ descKey="settings.cards.general.desc"
+ />
+ )
+ await screen.findByDisplayValue('/Users/me/Downloads')
+ await userEvent.click(screen.getByRole('button', { name: 'Browse…' }))
+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
+ expect(onClose).not.toHaveBeenCalled()
+ await act(async () => release(null))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled()
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('retains dirty app fields and directory rows after an atomic Save failure', async () => {
+ vi.mocked(transport.invoke).mockImplementation(async (channel) => {
+ if (channel === Queries.GetGeneralSettingsDraft)
+ return generalResult({ favorites: ['/saved'], recent: [] })
+ return { ok: false, error: { code: 'permissionDenied' } }
+ })
+ const onClose = vi.fn()
+ render(
+ <GeneralDialog
+ open
+ onClose={onClose}
+ labelKey="settings.cards.general.title"
+ descKey="settings.cards.general.desc"
+ />
+ )
+ await screen.findByRole('button', { name: 'Remove favorite /saved' })
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Remove favorite /saved' })
+ )
+ await userEvent.click(
+ screen.getByRole('switch', { name: /notify on failure/i })
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }))
+ await screen.findByRole('alert')
+ expect(onClose).not.toHaveBeenCalled()
+ expect(
+ screen.getByRole('switch', { name: /notify on failure/i })
+ ).not.toBeChecked()
+ expect(screen.queryByTitle('/saved')).toBeNull()
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }))
+ expect(
+ vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(
+ ([channel]) => channel === Commands.SaveGeneralSettings
+ )
+ ).toHaveLength(2)
+ })
+
+ it('hydrates General fields and directories from one snapshot', async () => {
render(
<GeneralDialog
open
@@ -87,9 +259,18 @@ describe('<GeneralDialog>', () => {
await userEvent.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
- app: { warnBeforeQuit: false },
- })
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveGeneralSettings,
+ {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { warnBeforeQuit: false },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ }
+ )
})
})
@@ -123,9 +304,18 @@ describe('<GeneralDialog>', () => {
await userEvent.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
- app: { notifyOnError: false },
- })
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveGeneralSettings,
+ {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { notifyOnError: false },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ }
+ )
})
})
@@ -139,9 +329,18 @@ describe('<GeneralDialog>', () => {
await userEvent.click(screen.getByRole('button', { name: /save/i }))
await waitFor(() => {
- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
- app: { autofillClipboardLinks: false },
- })
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveGeneralSettings,
+ {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { autofillClipboardLinks: false },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ }
+ )
})
})
@@ -160,9 +359,18 @@ describe('<GeneralDialog>', () => {
const switches = screen.getAllByRole('switch')
await user.click(switches[0]) // toggle launchAtStartup
await user.click(screen.getByRole('button', { name: /save/i }))
- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
- app: { launchAtStartup: true },
- })
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveGeneralSettings,
+ {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { launchAtStartup: true },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ }
+ )
expect(onClose).toHaveBeenCalled()
})
})
@@ -179,19 +387,21 @@ it('enables the login window preference with auto-launch and saves both dirty fi
expect(toggle).not.toHaveAttribute('aria-disabled', 'true')
await userEvent.click(toggle)
await userEvent.click(screen.getByRole('button', { name: /save/i }))
- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.SaveGeneralSettings, {
+ expectedRevision: TEST_GENERAL_REVISION,
app: { launchAtStartup: true, showMainWindowAtLogin: true },
+ directories: { addFavorites: [], removeFavorites: [], removeRecent: [] },
})
})
it('asks for a download folder and clears the error after browsing', async () => {
vi.mocked(transport.invoke).mockImplementation(async (channel: string) => {
- if (channel === Queries.GetSettings)
- return {
- ...SETTINGS_FIXTURE,
- app: { ...SETTINGS_FIXTURE.app, defaultSaveDir: '' },
- }
- return { saved: true }
+ if (channel === Queries.GetGeneralSettingsDraft)
+ return generalResult(undefined, {
+ ...SETTINGS_FIXTURE.app,
+ defaultSaveDir: '',
+ })
+ return generalResult()
})
pickSaveDir.mockResolvedValue('/Downloads')
const onClose = vi.fn()
@@ -208,9 +418,84 @@ it('asks for a download folder and clears the error after browsing', async () =>
await screen.findByDisplayValue('/Downloads')
await user.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() =>
- expect(transport.invoke).toHaveBeenCalledWith(Commands.UpdateSettings, {
- app: { defaultSaveDir: '/Downloads' },
- })
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveGeneralSettings,
+ {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { defaultSaveDir: '/Downloads' },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ }
+ )
)
expect(onClose).toHaveBeenCalledOnce()
})
+
+it.each([false, true])(
+ 'saves a boolean restored to its original clean value after a lost committed response (refresh=%s)',
+ async (refresh) => {
+ let host = generalSettingsSnapshot(undefined, SETTINGS_FIXTURE.app)
+ let first = true
+ vi.mocked(transport.invoke).mockImplementation(async (channel, raw) => {
+ if (channel === Queries.GetGeneralSettingsDraft)
+ return { ok: true, value: structuredClone(host) }
+ const request = raw as SaveGeneralSettingsRequest
+ if (request.expectedRevision !== host.revision)
+ return {
+ ok: false,
+ error: { code: 'conflict' },
+ snapshot: structuredClone(host),
+ }
+ host = {
+ ...host,
+ app: { ...host.app, ...request.app },
+ revision: '00000000-0000-4000-8000-000000000002',
+ }
+ if (first) {
+ first = false
+ host.app.autofillClipboardLinks = false // An unrelated client's committed edit.
+ throw new Error('response lost after commit')
+ }
+ return { ok: true, value: structuredClone(host) }
+ })
+ const close = vi.fn()
+ render(<GeneralDialog open onClose={close} labelKey="" descKey="" />)
+ await screen.findByDisplayValue('/Users/me/Downloads')
+ const user = userEvent.setup()
+ const notification = screen.getByRole('switch', {
+ name: /notify on failure/i,
+ })
+ await user.click(notification)
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ await screen.findByRole('alert')
+ expect(host.app.notifyOnError).toBe(false)
+ expect(close).not.toHaveBeenCalled()
+ await user.click(notification) // RHF dirty=false against the original true baseline.
+ if (refresh) {
+ await user.click(screen.getByRole('button', { name: 'Retry' }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
+ )
+ }
+ await user.click(screen.getByRole('button', { name: 'Save' }))
+ await waitFor(() => expect(close).toHaveBeenCalledOnce())
+ expect(host.app.notifyOnError).toBe(true)
+ expect(host.app.autofillClipboardLinks).toBe(false)
+ expect(
+ screen.getByRole('switch', { name: /autofill link from clipboard/i })
+ ).not.toBeChecked()
+ const saves = vi
+ .mocked(transport.invoke)
+ .mock.calls.filter(
+ ([channel]) => channel === Commands.SaveGeneralSettings
+ )
+ expect(saves.at(-1)?.[1]).toMatchObject({ app: { notifyOnError: true } })
+ const finalRequest = saves.at(-1)?.[1] as
+ | SaveGeneralSettingsRequest
+ | undefined
+ expect(finalRequest?.app).toEqual({ notifyOnError: true })
+ }
+)
diff --git a/src/renderer/routes/settings/cards/general-dialog.tsx b/src/renderer/routes/settings/cards/general-dialog.tsx
index 2cd57e41..95c64dfe 100644
--- a/src/renderer/routes/settings/cards/general-dialog.tsx
+++ b/src/renderer/routes/settings/cards/general-dialog.tsx
@@ -24,27 +24,21 @@ import {
useFormField,
} from '@renderer/components/ui/form'
import { Switch } from '@renderer/components/ui/switch'
+import {
+ DirectoryPreferencesSection,
+ DirectoryPreferencesStatus,
+} from '@renderer/features/directory-preferences/directory-preferences-section'
+import { useDirectoryPreferencesDraft } from '@renderer/features/directory-preferences/use-directory-preferences-draft'
import { pickDirty } from '@renderer/lib/form-utils'
import { transport } from '@renderer/lib/transport'
-import { Commands } from '@shared/protocol/commands'
-import { Queries } from '@shared/protocol/queries'
import { DEFAULT_APP_SETTINGS } from '@shared/schemas'
-import type { AppSettings, MotrixAppSettings } from '@shared/types/settings'
-import { type ComponentProps, useEffect } from 'react'
+import type { GeneralSettingsApp } from '@shared/schemas/general-settings'
+import { type ComponentProps, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { SettingsCardDialogProps } from './card-types'
import { generalFormSchema } from './settings-form-schemas'
-type GeneralFields = Pick<
- MotrixAppSettings,
- | 'launchAtStartup'
- | 'showMainWindowAtLogin'
- | 'defaultSaveDir'
- | 'notifyOnComplete'
- | 'notifyOnError'
- | 'autofillClipboardLinks'
- | 'warnBeforeQuit'
->
+type GeneralFields = GeneralSettingsApp
// Source of truth: src/shared/schemas/app-settings.ts (DEFAULT_APP_SETTINGS).
// Defaults are sourced from the schema; the renderer mirrors the subset of
@@ -68,48 +62,45 @@ export function GeneralDialog({
const { t } = useTranslation()
const isWeb = transport.platform === 'web'
const form = useSettingsForm<GeneralFields>(generalFormSchema, DEFAULTS)
+ const directories = useDirectoryPreferencesDraft({
+ getAppDraft: () => ({
+ values: form.getValues(),
+ dirty: pickDirty(form.getValues(), form.formState.dirtyFields) ?? {},
+ }),
+ onAppRebase: (baseline, intent) => {
+ form.reset(baseline)
+ for (const key of Object.keys(intent) as (keyof GeneralFields)[]) {
+ const value = intent[key]
+ if (value !== undefined)
+ form.setValue(key, value, { shouldDirty: true })
+ }
+ },
+ })
+ const contentRef = useRef<HTMLDivElement>(null)
+ const [defaultPicking, setDefaultPicking] = useState(false)
+ const [favoritePicking, setFavoritePicking] = useState(false)
+ const busy = directories.saving || defaultPicking || favoritePicking
+ const fieldsDisabled =
+ directories.saving || directories.loading || !directories.ready
+ const close = () => {
+ if (!busy) onClose()
+ }
- // biome-ignore lint/correctness/useExhaustiveDependencies: form is stable across renders; this is a mount-only fetch
- useEffect(() => {
- let cancelled = false
- transport
- .invoke(Queries.GetSettings)
- .then((data) => {
- if (cancelled) return
- const all = data as AppSettings
- if (all?.app) {
- form.reset({
- launchAtStartup: all.app.launchAtStartup,
- showMainWindowAtLogin: all.app.showMainWindowAtLogin,
- defaultSaveDir: all.app.defaultSaveDir,
- notifyOnComplete: all.app.notifyOnComplete,
- notifyOnError: all.app.notifyOnError,
- autofillClipboardLinks: all.app.autofillClipboardLinks,
- warnBeforeQuit: all.app.warnBeforeQuit,
- })
- }
- })
- .catch(() => {
- /* keep defaults */
- })
- return () => {
- cancelled = true
- }
- }, [])
-
- const onSubmit = useSettingsSubmit(form, async (values) => {
- const dirty = pickDirty(values, form.formState.dirtyFields)
- if (!dirty) {
- onClose()
- return
- }
- const patch = { app: dirty }
- await transport.invoke(Commands.UpdateSettings, patch)
- onClose()
+ const onSubmit = useSettingsSubmit(form, async () => {
+ if (busy || directories.loading || !directories.ready) return
+ contentRef.current?.focus({ preventScroll: true })
+ if (await directories.save()) onClose()
})
return (
- <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
+ <Dialog
+ open={open}
+ onOpenChange={(v, details) => {
+ if (v) return
+ if (busy) details.cancel()
+ else close()
+ }}
+ >
<DialogContent
className="flex max-h-[85vh] flex-col gap-0 p-0 sm:max-w-[700px]"
initialFocus={false}
@@ -119,25 +110,137 @@ export function GeneralDialog({
<DialogDescription>{t(descKey)}</DialogDescription>
</DialogHeader>
- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-4">
+ <div
+ ref={contentRef}
+ tabIndex={-1}
+ className="min-h-0 flex-1 overflow-y-auto px-6 py-4 outline-none"
+ >
+ <DirectoryPreferencesStatus
+ loading={directories.loading}
+ error={directories.error}
+ disabled={busy}
+ onRetry={() => {
+ contentRef.current?.focus({ preventScroll: true })
+ void directories.refresh()
+ }}
+ />
+
<Form {...form}>
- <form className="space-y-4" noValidate onSubmit={onSubmit}>
- {!isWeb && (
+ <form noValidate onSubmit={onSubmit}>
+ <fieldset className="min-w-0 space-y-4" disabled={fieldsDisabled}>
+ {!isWeb && (
+ <FormField
+ control={form.control}
+ name="launchAtStartup"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.launchAtStartup')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.launchAtStartupDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ disabled={fieldsDisabled}
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ )}
+
+ {!isWeb && (
+ <FormField
+ control={form.control}
+ name="showMainWindowAtLogin"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.showMainWindowAtLogin')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.showMainWindowAtLoginDesc', {
+ mode: t(
+ transport.platform === 'darwin'
+ ? 'settings.appearance.runModeTray'
+ : 'settings.appearance.runModeTrayDesktop'
+ ),
+ })}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ disabled={
+ fieldsDisabled || !form.watch('launchAtStartup')
+ }
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ )}
+
+ <FormField
+ control={form.control}
+ name="defaultSaveDir"
+ render={({ field }) => (
+ <FormItem className="space-y-2">
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.defaultSaveDir')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.defaultSaveDirDesc')}
+ </FormDescription>
+ </div>
+ <SettingsDirectoryPicker
+ inputProps={{ ref: field.ref, onBlur: field.onBlur }}
+ recordRecent={false}
+ allowFavoriteEditing={false}
+ disabled={directories.saving || favoritePicking}
+ onPickingChange={setDefaultPicking}
+ />
+ <FormMessage className="basis-full text-xs" />
+ </FormItem>
+ )}
+ />
+
+ <div className="space-y-3 border-b pb-4">
+ <p className="text-xs text-muted-foreground">
+ {t('directoryPreferences.sectionDescription')}
+ </p>
+ <DirectoryPreferencesSection
+ preferences={directories.preferences}
+ onChange={directories.setPreferences}
+ disabled={busy || directories.loading || !directories.ready}
+ onPickingChange={setFavoritePicking}
+ />
+ </div>
+
<FormField
control={form.control}
- name="launchAtStartup"
+ name="autofillClipboardLinks"
render={({ field }) => (
<SettingsFormRow>
<div className="space-y-1">
<FormLabel>
- {t('settings.general.launchAtStartup')}
+ {t('settings.general.autofillClipboardLinks')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.general.launchAtStartupDesc')}
+ {t('settings.general.autofillClipboardLinksDesc')}
</FormDescription>
</div>
<FormControl>
<Switch
+ disabled={fieldsDisabled}
checked={field.value}
onCheckedChange={field.onChange}
/>
@@ -145,31 +248,23 @@ export function GeneralDialog({
</SettingsFormRow>
)}
/>
- )}
- {!isWeb && (
<FormField
control={form.control}
- name="showMainWindowAtLogin"
+ name="notifyOnComplete"
render={({ field }) => (
<SettingsFormRow>
<div className="space-y-1">
<FormLabel>
- {t('settings.general.showMainWindowAtLogin')}
+ {t('settings.general.notifyOnComplete')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.general.showMainWindowAtLoginDesc', {
- mode: t(
- transport.platform === 'darwin'
- ? 'settings.appearance.runModeTray'
- : 'settings.appearance.runModeTrayDesktop'
- ),
- })}
+ {t('settings.general.notifyOnCompleteDesc')}
</FormDescription>
</div>
<FormControl>
<Switch
- disabled={!form.watch('launchAtStartup')}
+ disabled={fieldsDisabled}
checked={field.value}
onCheckedChange={field.onChange}
/>
@@ -177,114 +272,23 @@ export function GeneralDialog({
</SettingsFormRow>
)}
/>
- )}
-
- <FormField
- control={form.control}
- name="defaultSaveDir"
- render={({ field }) => (
- <FormItem className="space-y-2">
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.defaultSaveDir')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.defaultSaveDirDesc')}
- </FormDescription>
- </div>
- <SettingsDirectoryPicker
- inputProps={{ ref: field.ref, onBlur: field.onBlur }}
- />
- <FormMessage className="basis-full text-xs" />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="autofillClipboardLinks"
- render={({ field }) => (
- <SettingsFormRow>
- <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>
- </SettingsFormRow>
- )}
- />
-
- <FormField
- control={form.control}
- name="notifyOnComplete"
- render={({ field }) => (
- <SettingsFormRow>
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.notifyOnComplete')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.notifyOnCompleteDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </SettingsFormRow>
- )}
- />
- <FormField
- control={form.control}
- name="notifyOnError"
- render={({ field }) => (
- <SettingsFormRow>
- <div className="space-y-1">
- <FormLabel>
- {t('settings.general.notifyOnError')}
- </FormLabel>
- <FormDescription className="text-xs">
- {t('settings.general.notifyOnErrorDesc')}
- </FormDescription>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </SettingsFormRow>
- )}
- />
-
- {!isWeb && (
<FormField
control={form.control}
- name="warnBeforeQuit"
+ name="notifyOnError"
render={({ field }) => (
<SettingsFormRow>
<div className="space-y-1">
<FormLabel>
- {t('settings.general.warnBeforeQuit')}
+ {t('settings.general.notifyOnError')}
</FormLabel>
<FormDescription className="text-xs">
- {t('settings.general.warnBeforeQuitDesc')}
+ {t('settings.general.notifyOnErrorDesc')}
</FormDescription>
</div>
<FormControl>
<Switch
+ disabled={fieldsDisabled}
checked={field.value}
onCheckedChange={field.onChange}
/>
@@ -292,7 +296,33 @@ export function GeneralDialog({
</SettingsFormRow>
)}
/>
- )}
+
+ {!isWeb && (
+ <FormField
+ control={form.control}
+ name="warnBeforeQuit"
+ render={({ field }) => (
+ <SettingsFormRow>
+ <div className="space-y-1">
+ <FormLabel>
+ {t('settings.general.warnBeforeQuit')}
+ </FormLabel>
+ <FormDescription className="text-xs">
+ {t('settings.general.warnBeforeQuitDesc')}
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ disabled={fieldsDisabled}
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </SettingsFormRow>
+ )}
+ />
+ )}
+ </fieldset>
</form>
</Form>
</div>
@@ -303,14 +333,25 @@ export function GeneralDialog({
{form.formState.errors.root.save.message}
</p>
)}
- <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy}
+ onClick={close}
+ >
{t('common.cancel')}
</Button>
<Button
type="button"
size="sm"
onClick={onSubmit}
- disabled={form.formState.isSubmitting}
+ disabled={
+ form.formState.isSubmitting ||
+ busy ||
+ directories.loading ||
+ !directories.ready
+ }
>
{t('common.save')}
</Button>
@@ -322,10 +363,12 @@ export function GeneralDialog({
function SettingsDirectoryPicker({
inputProps,
-}: Pick<ComponentProps<typeof DirectoryPicker>, 'inputProps'>) {
+ ...props
+}: Omit<ComponentProps<typeof DirectoryPicker>, 'name'>) {
const { formItemId, formMessageId, formDescriptionId, error } = useFormField()
return (
<DirectoryPicker
+ {...props}
name="defaultSaveDir"
inputProps={{
...inputProps,
diff --git a/src/server/download-path-policy.test.ts b/src/server/download-path-policy.test.ts
index db8b0926..d66ffa93 100644
--- a/src/server/download-path-policy.test.ts
+++ b/src/server/download-path-policy.test.ts
@@ -1,7 +1,17 @@
-import { chmod, mkdir, mkdtemp, realpath, rm, symlink } from 'node:fs/promises'
+import filesystem, {
+ chmod,
+ mkdir,
+ mkdtemp,
+ realpath,
+ rm,
+ stat,
+ symlink,
+ utimes,
+} from 'node:fs/promises'
+import { syncBuiltinESMExports } from 'node:module'
import os from 'node:os'
import path from 'node:path'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
createServerDownloadPathPolicy,
resolveServerDefaultSaveDir,
@@ -16,6 +26,8 @@ async function tempRoot(): Promise<string> {
}
afterEach(async () => {
+ vi.restoreAllMocks()
+ syncBuiltinESMExports()
await Promise.all(
roots.splice(0).map(async (root) => {
await chmod(root, 0o700).catch(() => undefined)
@@ -45,6 +57,104 @@ describe('resolveServerDefaultSaveDir', () => {
})
describe('ServerDownloadPathPolicy', () => {
+ it('reuses the single authorization stat for the authorized symlink target modification time', async () => {
+ const root = await tempRoot()
+ const observed = vi.spyOn(filesystem, 'stat')
+ syncBuiltinESMExports()
+ vi.resetModules()
+ const { createServerDownloadPathPolicy: createPolicy } = await import(
+ './download-path-policy'
+ )
+ const policy = await createPolicy({
+ defaultSaveDir: root,
+ allowedSaveDirsValue: root,
+ })
+ const target = path.join(root, 'target')
+ const alias = path.join(root, 'alias')
+ await mkdir(target)
+ await symlink(target, alias)
+ await utimes(target, new Date(1700000000123), new Date(1700000000123))
+ const expected = await stat(target)
+ observed.mockClear()
+ expect(await policy.authorizeDirectory(alias)).toEqual({
+ path: alias,
+ canonicalPath: await realpath(target),
+ rootPath: root,
+ modifiedAt: expected.mtimeMs,
+ })
+ expect(observed).toHaveBeenCalledExactlyOnceWith(await realpath(target))
+ })
+
+ it.each([Number.NaN, Infinity, -Infinity])(
+ 'omits nonfinite metadata without weakening the directory check: %s',
+ async (mtimeMs) => {
+ const root = await tempRoot()
+ const observed = vi.spyOn(filesystem, 'stat')
+ syncBuiltinESMExports()
+ vi.resetModules()
+ const { createServerDownloadPathPolicy: createPolicy } = await import(
+ './download-path-policy'
+ )
+ const policy = await createPolicy({
+ defaultSaveDir: root,
+ })
+ const info = await stat(root)
+ Object.defineProperty(info, 'mtimeMs', { value: mtimeMs })
+ observed.mockClear().mockResolvedValueOnce(info)
+ const authorized = await policy.authorizeDirectory(root)
+ expect(authorized).not.toHaveProperty('modifiedAt')
+ expect(observed).toHaveBeenCalledExactlyOnceWith(await realpath(root))
+ }
+ )
+
+ it('authorizes canonical aliases only within their configured resolved subtree, including restart defaults', async () => {
+ const root = await tempRoot()
+ const canonicalRoot = path.join(root, 'real')
+ const alias = path.join(root, 'alias')
+ await mkdir(canonicalRoot)
+ await symlink(canonicalRoot, alias)
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: alias,
+ allowedSaveDirsValue: alias,
+ })
+ const prepared = await policy.prepareSaveDir(path.join(alias, 'child'))
+ expect(await policy.authorizeDirectory(prepared)).toEqual({
+ path: path.join(alias, 'child'),
+ canonicalPath: prepared,
+ rootPath: alias,
+ modifiedAt: expect.any(Number),
+ })
+ const restarted = await createServerDownloadPathPolicy({
+ defaultSaveDir: prepared,
+ allowedSaveDirsValue: alias,
+ })
+ expect(await restarted.prepareSaveDir(undefined)).toBe(prepared)
+ await expect(restarted.authorizeDirectory(root)).rejects.toMatchObject({
+ directoryCode: 'outsideRoots',
+ })
+ const outside = path.join(root, 'outside')
+ await mkdir(outside)
+ await symlink(outside, path.join(canonicalRoot, 'escape'))
+ await expect(
+ restarted.authorizeDirectory(path.join(canonicalRoot, 'escape'))
+ ).rejects.toMatchObject({ directoryCode: 'outsideRoots' })
+ })
+
+ it('does not treat whitespace-only literal requests as the default sentinel', async () => {
+ const root = await tempRoot()
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: root,
+ })
+ await expect(policy.prepareSaveDir(' ')).rejects.toThrow(
+ 'must be an absolute path'
+ )
+ expect(await policy.prepareSaveDir('')).toBe(await realpath(root))
+ const missing = path.join(root, 'absent')
+ await expect(policy.authorizeDirectory(missing)).rejects.toMatchObject({
+ code: 'ENOENT',
+ })
+ await expect(realpath(missing)).rejects.toMatchObject({ code: 'ENOENT' })
+ })
it('creates and prepares the default and allowed roots', async () => {
const root = await tempRoot()
const downloads = path.join(root, 'downloads')
diff --git a/src/server/download-path-policy.ts b/src/server/download-path-policy.ts
index 87aae6eb..f5958999 100644
--- a/src/server/download-path-policy.ts
+++ b/src/server/download-path-policy.ts
@@ -1,6 +1,7 @@
import { lstat, mkdir, open, realpath, stat, unlink } from 'node:fs/promises'
import path from 'node:path'
import { AppError, ErrorCode } from '@shared/errors'
+import type { DirectoryErrorCode } from '@shared/schemas/server-directory'
interface DownloadPathEnvironment {
MOTRIX_DEFAULT_SAVE_DIR?: string
@@ -15,6 +16,23 @@ export interface ServerDownloadPathPolicyOptions {
export interface ServerDownloadPathPolicy {
readonly allowedSaveDirs: readonly string[]
prepareSaveDir(requested: string | undefined): Promise<string>
+ authorizeDirectory(requested: string): Promise<AuthorizedServerDirectory>
+}
+
+export interface AuthorizedServerDirectory {
+ path: string
+ canonicalPath: string
+ rootPath: string
+ modifiedAt?: number
+}
+
+export class DirectoryAuthorizationError extends AppError {
+ constructor(
+ readonly directoryCode: DirectoryErrorCode,
+ message: string
+ ) {
+ super(ErrorCode.TaskCreateFailed, message)
+ }
}
interface AllowedRoot {
@@ -33,14 +51,13 @@ function pathIsInside(root: string, candidate: string): boolean {
}
function absolutePath(value: string, label: string): string {
- const trimmed = value.trim()
- if (!trimmed || !path.isAbsolute(trimmed)) {
+ if (!value || !path.isAbsolute(value) || value.includes('\0')) {
throw new AppError(
ErrorCode.SettingsInvalid,
`${label} must be an absolute path`
)
}
- return path.resolve(trimmed)
+ return path.resolve(value)
}
function parseAllowedSaveDirs(
@@ -52,7 +69,7 @@ function parseAllowedSaveDirs(
const roots: string[] = []
for (const raw of value.split(delimiter)) {
if (!raw.trim()) continue
- const root = absolutePath(raw, 'MOTRIX_ALLOWED_SAVE_DIRS entry')
+ const root = absolutePath(raw.trim(), 'MOTRIX_ALLOWED_SAVE_DIRS entry')
if (!seen.has(root)) {
seen.add(root)
roots.push(root)
@@ -123,42 +140,93 @@ class DownloadPathPolicy implements ServerDownloadPathPolicy {
this.allowedSaveDirs = allowedRoots.map((root) => root.configured)
}
- async prepareSaveDir(requested: string | undefined): Promise<string> {
- const raw = requested?.trim() || this.defaultSaveDir
- const candidate = absolutePath(raw, 'Save directory')
- const matchingRoots = this.allowedRoots.filter((root) =>
+ private resolveCandidate(requested: string): {
+ candidate: string
+ matchingRoots: AllowedRoot[]
+ } {
+ let candidate = absolutePath(requested, 'Save directory')
+ let matchingRoots = this.allowedRoots.filter((root) =>
pathIsInside(root.configured, candidate)
)
+ // Older settings persist canonical paths. Map only a canonical subtree of
+ // a configured root back to its logical alias, then repeat both checks.
+ if (this.allowedRoots.length > 0 && matchingRoots.length === 0) {
+ const alias = this.allowedRoots
+ .filter((root) => pathIsInside(root.canonical, candidate))
+ .sort((a, b) => b.canonical.length - a.canonical.length)[0]
+ if (alias) {
+ candidate = path.join(
+ alias.configured,
+ path.relative(alias.canonical, candidate)
+ )
+ matchingRoots = this.allowedRoots.filter((root) =>
+ pathIsInside(root.configured, candidate)
+ )
+ }
+ }
if (this.allowedRoots.length > 0 && matchingRoots.length === 0) {
- throw pathFailure(
+ throw new DirectoryAuthorizationError(
+ 'outsideRoots',
`Save directory is outside MOTRIX_ALLOWED_SAVE_DIRS: ${candidate}`
)
}
+ return { candidate, matchingRoots }
+ }
+
+ private checkCanonical(
+ candidate: string,
+ canonical: string,
+ roots: readonly AllowedRoot[]
+ ): AllowedRoot | undefined {
+ const matching = roots
+ .filter((root) => pathIsInside(root.canonical, canonical))
+ .sort((a, b) => b.configured.length - a.configured.length)
+ if (roots.length > 0 && matching.length === 0) {
+ throw new DirectoryAuthorizationError(
+ 'outsideRoots',
+ `Save directory resolves outside the allowed root: ${candidate}`
+ )
+ }
+ return matching[0]
+ }
+
+ async authorizeDirectory(
+ requested: string
+ ): Promise<AuthorizedServerDirectory> {
+ const { candidate, matchingRoots } = this.resolveCandidate(requested)
+ const canonical = await realpath(candidate)
+ const root = this.checkCanonical(candidate, canonical, matchingRoots)
+ const info = await stat(canonical)
+ if (!info.isDirectory()) {
+ throw new DirectoryAuthorizationError(
+ 'notDirectory',
+ 'Save directory is not a directory'
+ )
+ }
+ return {
+ path: candidate,
+ canonicalPath: canonical,
+ rootPath: root?.configured ?? path.parse(candidate).root,
+ ...(Number.isFinite(info.mtimeMs) ? { modifiedAt: info.mtimeMs } : {}),
+ }
+ }
+
+ async prepareSaveDir(requested: string | undefined): Promise<string> {
+ const raw =
+ requested === undefined || requested === ''
+ ? this.defaultSaveDir
+ : requested
+ const { candidate, matchingRoots } = this.resolveCandidate(raw)
if (matchingRoots.length > 0) {
const ancestor = await deepestExistingAncestor(candidate)
const canonicalAncestor = await realpath(ancestor)
- if (
- !matchingRoots.some((root) =>
- pathIsInside(root.canonical, canonicalAncestor)
- )
- ) {
- throw pathFailure(
- `Save directory resolves outside the allowed root: ${candidate}`
- )
- }
+ this.checkCanonical(candidate, canonicalAncestor, matchingRoots)
}
await ensureDirectory(candidate)
const canonical = await realpath(candidate)
- if (
- matchingRoots.length > 0 &&
- !matchingRoots.some((root) => pathIsInside(root.canonical, canonical))
- ) {
- throw pathFailure(
- `Save directory resolves outside the allowed root: ${candidate}`
- )
- }
+ this.checkCanonical(candidate, canonical, matchingRoots)
await ensureWritable(canonical)
return canonical
}
@@ -187,16 +255,6 @@ export async function createServerDownloadPathPolicy(
options.allowedSaveDirsValue,
options.pathDelimiter ?? path.delimiter
)
- if (
- configuredRoots.length > 0 &&
- !configuredRoots.some((root) => pathIsInside(root, defaultSaveDir))
- ) {
- throw new AppError(
- ErrorCode.SettingsInvalid,
- 'MOTRIX_DEFAULT_SAVE_DIR must be inside MOTRIX_ALLOWED_SAVE_DIRS'
- )
- }
-
const allowedRoots: AllowedRoot[] = []
for (const configured of configuredRoots) {
await ensureDirectory(configured)
@@ -206,6 +264,20 @@ export async function createServerDownloadPathPolicy(
}
const policy = new DownloadPathPolicy(defaultSaveDir, allowedRoots)
- await policy.prepareSaveDir(defaultSaveDir)
+ try {
+ await policy.prepareSaveDir(defaultSaveDir)
+ } catch (error) {
+ if (
+ error instanceof DirectoryAuthorizationError &&
+ error.directoryCode === 'outsideRoots'
+ ) {
+ throw new AppError(
+ ErrorCode.SettingsInvalid,
+ 'MOTRIX_DEFAULT_SAVE_DIR must be inside MOTRIX_ALLOWED_SAVE_DIRS',
+ error
+ )
+ }
+ throw error
+ }
return policy
}
diff --git a/src/server/http/app.ts b/src/server/http/app.ts
index 8b25ff03..54c1dc7d 100644
--- a/src/server/http/app.ts
+++ b/src/server/http/app.ts
@@ -2,6 +2,7 @@ import type { EventBus } from '@core/events/event-bus'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
import fastifyStatic from '@fastify/static'
import websocket from '@fastify/websocket'
+import { Commands } from '@shared/protocol/commands'
import {
assertTaskInspectorActivityArguments,
makeProtocolFailure,
@@ -14,6 +15,14 @@ import type {
QueryHandlerMap,
} from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import { DirectoryPreferencesResultSchema } from '@shared/schemas/directory-preferences'
+import { GeneralSettingsResultSchema } from '@shared/schemas/general-settings'
+import {
+ CreateServerDirectoryResultSchema,
+ ListServerDirectoriesResultSchema,
+ ListServerDirectoryLocationsResultSchema,
+ ValidateServerDirectoryResultSchema,
+} from '@shared/schemas/server-directory'
import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspector-activity'
import { torrentRpcBodyLimitSchema } from '@shared/schemas/torrent-request-limits'
import Fastify, { type FastifyInstance, type FastifyReply } from 'fastify'
@@ -28,6 +37,51 @@ import {
export { RPC_BODY_LIMIT_BYTES } from './torrent-command-routes'
+const directoryResultSchemas = {
+ [Commands.MutateDirectoryPreferences]: DirectoryPreferencesResultSchema,
+ [Commands.SaveGeneralSettings]: GeneralSettingsResultSchema,
+ [Queries.GetGeneralSettingsDraft]: GeneralSettingsResultSchema,
+ [Queries.GetDirectoryPreferences]: DirectoryPreferencesResultSchema,
+ [Queries.ListServerDirectoryLocations]:
+ ListServerDirectoryLocationsResultSchema,
+ [Commands.CreateServerDirectory]: CreateServerDirectoryResultSchema,
+ [Queries.ListServerDirectories]: ListServerDirectoriesResultSchema,
+ [Queries.ValidateServerDirectory]: ValidateServerDirectoryResultSchema,
+}
+
+async function directoryRpc(
+ channel: string,
+ body: unknown,
+ handler: Handler
+): Promise<unknown> {
+ const schema =
+ directoryResultSchemas[channel as keyof typeof directoryResultSchemas]
+ const args =
+ typeof body === 'object' && body !== null && 'args' in body
+ ? body.args
+ : undefined
+ if (
+ !Array.isArray(args) ||
+ args.length !== 1 ||
+ Object.keys(body as object).some((key) => key !== 'args')
+ ) {
+ return { ok: false, error: { code: 'invalidPath' } }
+ }
+ try {
+ return schema.parse(await handler(args[0]))
+ } catch {
+ return {
+ ok: false,
+ error: {
+ code:
+ channel === Commands.CreateServerDirectory
+ ? 'creationOutcomeUnknown'
+ : 'unavailable',
+ },
+ }
+ }
+}
+
export interface AppOptions {
/** Torrent-only RPC budget; defaults to 8 MiB, configurable from 2 to 64 MiB. */
torrentBodyLimitBytes?: number
@@ -92,6 +146,13 @@ export async function createApp(
const handler =
commands[channel as keyof typeof commands] ?? bridgeCommands[channel]
if (!handler) return reply.code(404).send({ error: 'unknown channel' })
+ if (
+ channel === Commands.CreateServerDirectory ||
+ channel === Commands.MutateDirectoryPreferences ||
+ channel === Commands.SaveGeneralSettings
+ ) {
+ return directoryRpc(channel, req.body, handler)
+ }
try {
return await handler(...(req.body?.args ?? []))
} catch (err) {
@@ -121,6 +182,15 @@ export async function createApp(
queries[req.params.channel as keyof typeof queries] ??
bridgeQueries[req.params.channel]
if (!handler) return reply.code(404).send({ error: 'unknown channel' })
+ if (
+ req.params.channel === Queries.ListServerDirectories ||
+ req.params.channel === Queries.ValidateServerDirectory ||
+ req.params.channel === Queries.GetDirectoryPreferences ||
+ req.params.channel === Queries.GetGeneralSettingsDraft ||
+ req.params.channel === Queries.ListServerDirectoryLocations
+ ) {
+ return directoryRpc(req.params.channel, req.body, handler)
+ }
try {
const args = req.body?.args
if (usesSharedEnvelope) {
diff --git a/src/server/http/server-directory.test.ts b/src/server/http/server-directory.test.ts
new file mode 100644
index 00000000..d22ab900
--- /dev/null
+++ b/src/server/http/server-directory.test.ts
@@ -0,0 +1,335 @@
+import {
+ type access,
+ mkdir,
+ mkdtemp,
+ opendir,
+ readdir,
+ rm,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { AppError, ErrorCode } from '@shared/errors'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import {
+ generalSettingsSnapshot,
+ TEST_GENERAL_REVISION,
+} from '@test-utils/general-settings'
+import type { FastifyInstance } from 'fastify'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createServerDownloadPathPolicy } from '../download-path-policy'
+import { ServerDirectoryService } from '../server-directory-service'
+import { createApp } from './app'
+
+const TOKEN = 'directory-test-owner'
+const capabilities = [
+ { kind: 'query', channel: Queries.ListServerDirectories },
+ { kind: 'query', channel: Queries.ValidateServerDirectory },
+ { kind: 'command', channel: Commands.CreateServerDirectory },
+] as const
+
+describe('authenticated directory RPC', () => {
+ let app: FastifyInstance
+ let root: string
+ let service: ServerDirectoryService
+ let cookie: string
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'motrix-directory-rpc-'))
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: root,
+ allowedSaveDirsValue: root,
+ })
+ service = new ServerDirectoryService(policy)
+ app = await createApp({
+ operatorAuth: { operatorToken: TOKEN },
+ queryHandlers: {
+ [Queries.ListServerDirectories]: (request: unknown) =>
+ service.list(request),
+ [Queries.ValidateServerDirectory]: (request: unknown) =>
+ service.validate(request),
+ },
+ commandHandlers: {
+ [Commands.CreateServerDirectory]: (request: unknown) =>
+ service.create(request),
+ },
+ })
+ const login = await app.inject({
+ method: 'POST',
+ url: '/rpc/auth/login',
+ payload: { token: TOKEN },
+ })
+ cookie = (login.headers['set-cookie'] as string).split(';')[0]
+ })
+ afterEach(async () => {
+ vi.restoreAllMocks()
+ await app.close()
+ await rm(root, { recursive: true, force: true })
+ })
+
+ const requestFor = (channel: string, root: string) =>
+ channel === Commands.CreateServerDirectory
+ ? { parentPath: root, name: 'new' }
+ : { path: root }
+
+ it.each(capabilities)(
+ 'gates $channel against anonymous and cross-origin requests and accepts same-origin sessions',
+ async ({ kind, channel }) => {
+ const request = {
+ method: 'POST' as const,
+ url: `/rpc/${kind}/${encodeURIComponent(channel)}`,
+ payload: { args: [requestFor(channel, root)] },
+ }
+ expect((await app.inject(request)).statusCode).toBe(401)
+ expect(
+ (
+ await app.inject({
+ ...request,
+ headers: {
+ cookie,
+ host: 'nas.local',
+ origin: 'https://attacker.example',
+ },
+ })
+ ).statusCode
+ ).toBe(403)
+ expect(await readdir(root)).toEqual([])
+ const response = await app.inject({
+ ...request,
+ headers: { cookie, host: 'nas.local', origin: 'http://nas.local' },
+ })
+ expect(response.statusCode).toBe(200)
+ expect(response.headers['cache-control']).toContain('no-store')
+ expect(response.json()).toMatchObject({
+ ok: true,
+ value: {
+ path:
+ channel === Commands.CreateServerDirectory
+ ? path.join(root, 'new')
+ : root,
+ },
+ })
+ }
+ )
+
+ it.each(capabilities)(
+ 'sanitizes malformed arguments for $channel before dispatch',
+ async ({ kind, channel }) => {
+ const spy = vi.spyOn(
+ service,
+ channel === Commands.CreateServerDirectory
+ ? 'create'
+ : channel === Queries.ListServerDirectories
+ ? 'list'
+ : 'validate'
+ )
+ for (const payload of [
+ {},
+ { args: {} },
+ { args: [] },
+ { args: [requestFor(channel, root), {}] },
+ { args: [requestFor(channel, root)], extra: true },
+ ]) {
+ const response = await app.inject({
+ method: 'POST',
+ url: `/rpc/${kind}/${encodeURIComponent(channel)}`,
+ headers: { cookie },
+ payload,
+ })
+ expect(response.statusCode).toBe(200)
+ expect(response.json()).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ }
+ expect(spy).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(capabilities)(
+ 'sanitizes thrown AppErrors and malformed results for $channel',
+ async ({ kind, channel }) => {
+ const method =
+ channel === Commands.CreateServerDirectory
+ ? 'create'
+ : channel === Queries.ListServerDirectories
+ ? 'list'
+ : 'validate'
+ const spy = vi.spyOn(service, method)
+ const request = {
+ method: 'POST' as const,
+ url: `/rpc/${kind}/${encodeURIComponent(channel)}`,
+ headers: { cookie },
+ payload: { args: [requestFor(channel, root)] },
+ }
+ const expected = {
+ ok: false,
+ error: {
+ code:
+ channel === Commands.CreateServerDirectory
+ ? 'creationOutcomeUnknown'
+ : 'unavailable',
+ },
+ }
+ spy.mockRejectedValueOnce(
+ new AppError(ErrorCode.TaskCreateFailed, '/private/sensitive-path')
+ )
+ expect((await app.inject(request)).json()).toEqual(expected)
+ spy.mockResolvedValueOnce({
+ ok: true,
+ value: { private: '/private/sensitive-path' },
+ } as never)
+ expect((await app.inject(request)).json()).toEqual(expected)
+ }
+ )
+
+ it('returns strict schema errors and permission failures through the real service without raw details', async () => {
+ const response = await app.inject({
+ method: 'POST',
+ url: `/rpc/query/${encodeURIComponent(Queries.ListServerDirectories)}`,
+ headers: { cookie },
+ payload: { args: [{ path: root, unknown: true }] },
+ })
+ expect(response.json()).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: root,
+ allowedSaveDirsValue: root,
+ })
+ service = new ServerDirectoryService(policy, {
+ access: vi.fn<typeof access>().mockRejectedValue(
+ Object.assign(new Error('/private/permission-details'), {
+ code: 'EROFS',
+ })
+ ),
+ mkdir,
+ opendir,
+ })
+ const denied = await app.inject({
+ method: 'POST',
+ url: `/rpc/query/${encodeURIComponent(Queries.ValidateServerDirectory)}`,
+ headers: { cookie },
+ payload: { args: [{ path: root }] },
+ })
+ expect(denied.json()).toEqual({
+ ok: false,
+ error: { code: 'permissionDenied' },
+ })
+ })
+})
+
+describe('directory preferences RPC boundary', () => {
+ const capabilities = [
+ {
+ kind: 'command',
+ channel: Commands.SaveGeneralSettings,
+ request: {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: {},
+ directories: {
+ addFavorites: [],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ },
+ value: generalSettingsSnapshot(),
+ },
+ {
+ kind: 'query',
+ channel: Queries.GetGeneralSettingsDraft,
+ request: {},
+ value: generalSettingsSnapshot(),
+ },
+ {
+ kind: 'query',
+ channel: Queries.GetDirectoryPreferences,
+ request: {},
+ value: { favorites: ['/saved'], recent: ['/stale'] },
+ },
+ {
+ kind: 'query',
+ channel: Queries.ListServerDirectoryLocations,
+ request: {},
+ value: { common: [], favorites: [], recent: [] },
+ },
+ {
+ kind: 'command',
+ channel: Commands.MutateDirectoryPreferences,
+ request: { action: 'clearRecent' },
+ value: { favorites: [], recent: [] },
+ },
+ ] as const
+
+ it.each(capabilities)(
+ 'authenticates, checks Origin, prevents caching and sanitizes $channel envelopes',
+ async ({ kind, channel, request, value }) => {
+ const handler = vi.fn(
+ async (_request: unknown): Promise<unknown> => ({ ok: true, value })
+ )
+ const app = await createApp({
+ operatorAuth: { operatorToken: TOKEN },
+ commandHandlers: kind === 'command' ? { [channel]: handler } : {},
+ queryHandlers: kind === 'query' ? { [channel]: handler } : {},
+ })
+ try {
+ const base = {
+ method: 'POST' as const,
+ url: `/rpc/${kind}/${encodeURIComponent(channel)}`,
+ payload: { args: [request] },
+ }
+ expect((await app.inject(base)).statusCode).toBe(401)
+ expect(handler).not.toHaveBeenCalled()
+ const login = await app.inject({
+ method: 'POST',
+ url: '/rpc/auth/login',
+ payload: { token: TOKEN },
+ })
+ const cookie = (login.headers['set-cookie'] as string).split(';')[0]
+ expect(
+ (
+ await app.inject({
+ ...base,
+ headers: {
+ cookie,
+ host: 'nas.local',
+ origin: 'https://attacker.example',
+ },
+ })
+ ).statusCode
+ ).toBe(403)
+ expect(handler).not.toHaveBeenCalled()
+ const response = await app.inject({ ...base, headers: { cookie } })
+ expect(response.statusCode).toBe(200)
+ expect(response.headers['cache-control']).toContain('no-store')
+ expect(response.json()).toEqual({ ok: true, value })
+ handler.mockClear()
+ for (const payload of [
+ {},
+ { args: [] },
+ { args: [request, {}] },
+ { args: [request], extra: true },
+ ]) {
+ expect(
+ (await app.inject({ ...base, headers: { cookie }, payload })).json()
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ }
+ expect(handler).not.toHaveBeenCalled()
+ handler.mockRejectedValueOnce(new Error('/private/secret'))
+ expect(
+ (await app.inject({ ...base, headers: { cookie } })).json()
+ ).toEqual({ ok: false, error: { code: 'unavailable' } })
+ handler.mockResolvedValueOnce({
+ ok: true,
+ value,
+ secret: 'do not forward',
+ })
+ expect(
+ (await app.inject({ ...base, headers: { cookie } })).json()
+ ).toEqual({ ok: false, error: { code: 'unavailable' } })
+ } finally {
+ await app.close()
+ }
+ }
+ )
+})
diff --git a/src/server/index.ts b/src/server/index.ts
index df43c409..f0b0c5ea 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -177,6 +177,7 @@ import { registerPluginUploadRoute } from './routes/plugin-uploads'
import { registerTasksBulkRoutes } from './routes/tasks-bulk'
import { prepareServerRuntimeDirectories } from './runtime-directories'
import { serverHealthSnapshot } from './runtime-health'
+import { ServerDirectoryService } from './server-directory-service'
import {
createServerExitCoordinator,
createServerShutdown,
@@ -329,6 +330,15 @@ async function main() {
byteUnitSystem: updated.app.byteUnitSystem,
})
}
+ if (
+ JSON.stringify(old.app.directoryPreferences) !==
+ JSON.stringify(updated.app.directoryPreferences)
+ ) {
+ eventBus.emit(
+ Events.DirectoryPreferencesChanged,
+ structuredClone(updated.app.directoryPreferences)
+ )
+ }
if (old.app.reduceMotion !== updated.app.reduceMotion) {
eventBus.emit(Events.ReducedMotionChanged, {
reduceMotion: updated.app.reduceMotion,
@@ -1099,7 +1109,9 @@ async function main() {
)
// ─── HTTP App ─────────────────────────────────────────────────
+ const serverDirectoryService = new ServerDirectoryService(downloadPathPolicy)
const commandHandlers = buildServerCommandHandlers({
+ serverDirectoryService,
supervisor,
settingsManager,
geoipManager: activeGeoipManager,
@@ -1181,6 +1193,7 @@ async function main() {
])
}
const queryHandlers = buildServerQueryHandlers({
+ serverDirectoryService,
taskManager,
statsAggregator,
speedHistoryStore,
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index e037611a..8d2b6ca4 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -1,3 +1,6 @@
+import { mkdir, mkdtemp, realpath, rm, symlink } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
import { NOOP_TASK_ACTIVITY_RECORDER } from '@core/activity'
import type { Aria2RpcClient } from '@core/engine/aria2/aria2-rpc-client'
import type { EngineAdapter } from '@core/engine/engine-adapter'
@@ -23,6 +26,7 @@ import type { MagnetTracker } from '@core/torrent/magnet-tracker'
import type { TrackerManager } from '@core/tracker'
import { Commands } from '@shared/protocol/commands'
import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
import {
TaskInstancePhase,
TaskKind,
@@ -32,9 +36,12 @@ import {
} from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createServerDownloadPathPolicy } from '../download-path-policy'
import type { ServerPluginInstallService } from '../plugin/install-service'
+import { ServerDirectoryService } from '../server-directory-service'
import type { ServerCommandContext } from './commands'
import { buildServerCommandHandlers } from './commands'
+import { buildServerQueryHandlers } from './queries'
const PROXY_OFF = {
enabled: false,
@@ -177,6 +184,11 @@ function makeFakeCtx() {
downloadPathPolicy: {
allowedSaveDirs: ['/downloads'],
prepareSaveDir: vi.fn(async (requested: string) => requested),
+ authorizeDirectory: vi.fn(),
+ },
+ serverDirectoryService: {
+ create: vi.fn(),
+ resolvePreferenceDirectory: vi.fn(async (value: string) => value),
},
}
}
@@ -216,6 +228,302 @@ function makeSettings(
}
describe('server Commands.UpdateSettings', () => {
+ it('uses Server path policy before one General commit and does not apply partial fields on an outside-root destination', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-server-general-'))
+ try {
+ const allowed = path.join(root, 'allowed')
+ const outside = path.join(root, 'outside')
+ await mkdir(outside)
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: allowed,
+ allowedSaveDirsValue: allowed,
+ })
+ const destination = path.join(allowed, 'destination')
+ await mkdir(destination)
+ const manager = new SettingsManager(path.join(root, 'settings.json'), {
+ defaultSaveDir: allowed,
+ })
+ await manager.load()
+ const ctx = {
+ ...makeFakeCtx(),
+ settingsManager: manager,
+ downloadPathPolicy: policy,
+ serverDirectoryService: new ServerDirectoryService(policy),
+ }
+ const save = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )[Commands.SaveGeneralSettings]
+ expect(
+ await save?.({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { defaultSaveDir: destination, notifyOnComplete: false },
+ directories: {
+ addFavorites: [destination],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ })
+ ).toMatchObject({
+ ok: true,
+ value: {
+ directoryPreferences: { favorites: [destination], recent: [] },
+ },
+ })
+ expect(manager.getApp()).toMatchObject({
+ defaultSaveDir: await realpath(destination),
+ notifyOnComplete: false,
+ })
+ expect(
+ ctx.supervisor.applyDefaultSaveDir
+ ).toHaveBeenCalledExactlyOnceWith(await realpath(destination))
+ vi.mocked(ctx.supervisor.applyDefaultSaveDir).mockClear()
+ const before = structuredClone(manager.getApp())
+ expect(
+ await save?.({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { defaultSaveDir: outside, notifyOnComplete: true },
+ directories: {
+ addFavorites: [],
+ removeFavorites: [destination],
+ removeRecent: [],
+ },
+ })
+ ).toEqual({ ok: false, error: { code: 'outsideRoots' } })
+ expect(
+ await save?.({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { notifyOnComplete: true },
+ directories: {
+ addFavorites: [outside],
+ removeFavorites: [destination],
+ removeRecent: [],
+ },
+ })
+ ).toEqual({ ok: false, error: { code: 'outsideRoots' } })
+ expect(manager.getApp()).toEqual(before)
+ expect(ctx.supervisor.applyDefaultSaveDir).not.toHaveBeenCalled()
+ const authorize = vi.spyOn(
+ ctx.serverDirectoryService,
+ 'resolvePreferenceDirectory'
+ )
+ expect(
+ await save?.({
+ expectedRevision: manager.getGeneralSettingsSnapshot().revision,
+ app: { defaultSaveDir: destination, extra: true },
+ directories: {
+ addFavorites: [destination],
+ removeFavorites: [],
+ removeRecent: [],
+ },
+ })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(authorize).not.toHaveBeenCalled()
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('preserves latest queue preferences against stale/invalid app patches through Server handlers', async () => {
+ const root = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-server-preferences-')
+ )
+ try {
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: root,
+ allowedSaveDirsValue: root,
+ })
+ const manager = new SettingsManager(path.join(root, 'settings.json'), {
+ defaultSaveDir: root,
+ })
+ await manager.load()
+ const staleApp = manager.getApp()
+ const ctx = {
+ ...makeFakeCtx(),
+ settingsManager: manager,
+ downloadPathPolicy: policy,
+ serverDirectoryService: new ServerDirectoryService(policy),
+ }
+ const handlers = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )
+ expect(
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'addFavorite',
+ path: root,
+ })
+ ).toEqual({ ok: true, value: { favorites: [root], recent: [] } })
+ await handlers[Commands.UpdateSettings]?.({
+ app: { ...staleApp, theme: 'dark' },
+ })
+ await handlers[Commands.UpdateSettings]?.({
+ app: {
+ directoryPreferences: { corrupt: true },
+ notifyOnComplete: false,
+ },
+ })
+ expect(manager.getApp()).toMatchObject({
+ theme: 'dark',
+ notifyOnComplete: false,
+ directoryPreferences: { favorites: [root], recent: [] },
+ })
+ const queries = buildServerQueryHandlers(
+ ctx as unknown as Parameters<typeof buildServerQueryHandlers>[0]
+ )
+ expect(await queries[Queries.GetDirectoryPreferences]?.({})).toEqual({
+ ok: true,
+ value: { favorites: [root], recent: [] },
+ })
+ expect(
+ await queries[Queries.ListServerDirectoryLocations]?.({})
+ ).toMatchObject({
+ ok: true,
+ value: { favorites: [{ path: root, sourcePaths: [root] }] },
+ })
+ expect(
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'recordRecent',
+ path: path.dirname(root),
+ })
+ ).toEqual({ ok: false, error: { code: 'outsideRoots' } })
+ expect(
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'removeFavorite',
+ paths: [root],
+ })
+ ).toEqual({ ok: true, value: { favorites: [], recent: [] } })
+ const target = path.join(root, 'target')
+ const alias = path.join(root, 'alias')
+ await mkdir(target)
+ await symlink(target, alias)
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'addFavorite',
+ path: alias,
+ })
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'addFavorite',
+ path: target,
+ })
+ expect(
+ await queries[Queries.ListServerDirectoryLocations]?.({})
+ ).toMatchObject({
+ ok: true,
+ value: { favorites: [{ path: alias, sourcePaths: [alias, target] }] },
+ })
+ expect(
+ await handlers[Commands.MutateDirectoryPreferences]?.({
+ action: 'removeFavorite',
+ paths: [alias, target],
+ })
+ ).toEqual({ ok: true, value: { favorites: [], recent: [] } })
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('round-trips selected root/internal aliases and whitespace through real settings Apply, reload, bootstrap and default preparation', async () => {
+ const temporary = await mkdtemp(
+ path.join(os.tmpdir(), 'motrix-picker-settings-')
+ )
+ try {
+ const realRoot = path.join(temporary, 'real')
+ const alias = path.join(temporary, 'alias')
+ await mkdir(realRoot)
+ await symlink(realRoot, alias)
+ await mkdir(path.join(realRoot, 'target'))
+ await symlink(
+ path.join(realRoot, 'target'),
+ path.join(realRoot, 'internal')
+ )
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: alias,
+ allowedSaveDirsValue: alias,
+ })
+ const service = new ServerDirectoryService(policy)
+ const settingsPath = path.join(temporary, 'settings.json')
+ const manager = new SettingsManager(settingsPath, {
+ defaultSaveDir: alias,
+ })
+ await manager.load()
+ const ctx = {
+ ...makeFakeCtx(),
+ downloadPathPolicy: policy,
+ serverDirectoryService: service,
+ settingsManager: manager,
+ }
+ const handlers = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )
+ for (const name of process.platform === 'win32'
+ ? ['Movies']
+ : ['Movies', 'Movies ', ' ']) {
+ const logical = path.join(alias, 'internal', name)
+ expect(
+ (
+ await service.create({
+ parentPath: path.join(alias, 'internal'),
+ name,
+ })
+ ).ok
+ ).toBe(true)
+ expect(await service.validate({ path: logical })).toEqual({
+ ok: true,
+ value: { path: logical },
+ })
+ await handlers[Commands.UpdateSettings]?.({
+ app: { defaultSaveDir: logical },
+ })
+ const canonical = await realpath(logical)
+ expect(manager.getApp().defaultSaveDir).toBe(canonical)
+ const reloaded = new SettingsManager(settingsPath, {
+ defaultSaveDir: alias,
+ })
+ await reloaded.load()
+ expect(reloaded.getApp().defaultSaveDir).toBe(canonical)
+ const queries = buildServerQueryHandlers({
+ ...ctx,
+ settingsManager: reloaded,
+ } as unknown as Parameters<typeof buildServerQueryHandlers>[0])
+ const bootstrap = await queries[Queries.ListAllowedSaveDirs]?.()
+ expect(bootstrap).toMatchObject({
+ defaultPath: canonical,
+ paths: [{ path: alias }],
+ })
+ expect(await service.validate({ path: canonical })).toEqual({
+ ok: true,
+ value: { path: path.join(alias, 'target', name) },
+ })
+ const restarted = await createServerDownloadPathPolicy({
+ defaultSaveDir: reloaded.getApp().defaultSaveDir,
+ allowedSaveDirsValue: alias,
+ })
+ expect(await restarted.prepareSaveDir('')).toBe(canonical)
+ expect(
+ await policy.prepareSaveDir(reloaded.getApp().defaultSaveDir)
+ ).toBe(canonical)
+ }
+ await expect(
+ policy.prepareSaveDir(path.join(temporary, 'outside'))
+ ).rejects.toThrow('outside MOTRIX_ALLOWED_SAVE_DIRS')
+ } finally {
+ await rm(temporary, { recursive: true, force: true })
+ }
+ })
+
+ it('delegates folder creation to the directory service', async () => {
+ const ctx = makeFakeCtx()
+ const request = { parentPath: '/downloads', name: 'new' }
+ const result = { ok: true, value: { path: '/downloads/new', name: 'new' } }
+ ctx.serverDirectoryService.create.mockResolvedValue(result)
+ const handlers = buildServerCommandHandlers(
+ ctx as unknown as ServerCommandContext
+ )
+ expect(await handlers[Commands.CreateServerDirectory]?.(request)).toEqual(
+ result
+ )
+ expect(ctx.serverDirectoryService.create).toHaveBeenCalledExactlyOnceWith(
+ request
+ )
+ })
it('does not invoke proxyApplier when proxy unchanged', async () => {
const ctx = makeFakeCtx()
const settings = makeSettings(PROXY_OFF)
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 334b8fe0..1cbdcfd8 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -28,6 +28,8 @@ import {
} from '@core/proxy/applied-download-proxy-policy'
import type { MotrixDatabase } from '@core/session/motrix-database'
import type { SessionManager } from '@core/session/session-manager'
+import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'
+import { createSaveGeneralSettingsHandler } from '@core/settings/general-settings'
import type { SettingsManager } from '@core/settings/settings-manager'
import {
clearStoppedTasks,
@@ -90,6 +92,7 @@ import { z } from 'zod'
import type { ServerDownloadPathPolicy } from '../download-path-policy'
import type { ServerPluginInstallService } from '../plugin/install-service'
import type { createServerProxyApplier } from '../proxy/wiring'
+import type { ServerDirectoryService } from '../server-directory-service'
export interface ServerCommandContext {
supervisor: EngineSupervisor
@@ -163,6 +166,10 @@ export interface ServerCommandContext {
publishTaskUpdate: TaskActionDeps['publishTaskUpdate']
publishTaskUpdateNow: TaskActionDeps['publishTaskUpdateNow']
downloadPathPolicy: ServerDownloadPathPolicy
+ serverDirectoryService: Pick<
+ ServerDirectoryService,
+ 'create' | 'resolvePreferenceDirectory'
+ >
}
export function buildServerCommandHandlers(
@@ -361,6 +368,8 @@ export function buildServerCommandHandlers(
expectedPid: z.number().int().positive().optional(),
})
return {
+ [Commands.CreateServerDirectory]: async (request: unknown) =>
+ ctx.serverDirectoryService.create(request),
[Commands.SetDisclaimerLanguage]: async (payload: unknown) => {
const language = supportedLocaleSchema.parse(payload)
await settingsManager.setDisclaimerLanguage(language)
@@ -660,6 +669,31 @@ export function buildServerCommandHandlers(
return supervisor.recover(engineRecoverySchema.parse(payload))
},
+ [Commands.MutateDirectoryPreferences]: createDirectoryPreferencesHandlers(
+ settingsManager,
+ (value) => ctx.serverDirectoryService.resolvePreferenceDirectory(value)
+ ).mutate,
+
+ [Commands.SaveGeneralSettings]: createSaveGeneralSettingsHandler(
+ settingsManager,
+ {
+ resolveFavorite: (value) =>
+ ctx.serverDirectoryService.resolvePreferenceDirectory(value),
+ resolveDefaultDirectory: async (value) => {
+ const existing =
+ await ctx.serverDirectoryService.resolvePreferenceDirectory(value)
+ return downloadPathPolicy.prepareSaveDir(existing)
+ },
+ applySavedApp: async (patch) => {
+ if (patch.defaultSaveDir !== undefined) {
+ await supervisor.applyDefaultSaveDir(
+ settingsManager.getApp().defaultSaveDir
+ )
+ }
+ },
+ }
+ ),
+
[Commands.UpdateSettings]: async (partial: unknown) => {
const saveDirPatch = z
.object({
diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.ts
index a36d5139..378d0be8 100644
--- a/src/server/ipc/queries.test.ts
+++ b/src/server/ipc/queries.test.ts
@@ -7,6 +7,7 @@ import { NotificationCenter } from '@core/notifications/notification-center'
import { MotrixDatabase } from '@core/session/motrix-database'
import { ErrorCode } from '@shared/errors'
import { Queries } from '@shared/protocol/queries'
+import { generalSettingsSnapshot } from '@test-utils/general-settings'
import { makeDownloadTask } from '@test-utils/task'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { buildServerQueryHandlers, type ServerQueryContext } from './queries'
@@ -152,7 +153,9 @@ function makeCtx(over: Record<string, unknown> = {}) {
downloadPathPolicy: {
allowedSaveDirs: [],
prepareSaveDir: vi.fn(),
+ authorizeDirectory: vi.fn(),
},
+ serverDirectoryService: { list: vi.fn(), validate: vi.fn() },
environment: {},
...over,
}
@@ -168,6 +171,30 @@ describe('buildServerQueryHandlers — allowed save directories', () => {
expect(ctx.trackerManager.getSyncStatus).toHaveBeenCalledOnce()
})
+ it('delegates readonly directory requests to the service', async () => {
+ const service = {
+ list: vi
+ .fn()
+ .mockResolvedValue({ ok: false, error: { code: 'outsideRoots' } }),
+ validate: vi
+ .fn()
+ .mockResolvedValue({ ok: true, value: { path: '/downloads' } }),
+ }
+ const handlers = buildServerQueryHandlers(
+ makeCtx({ serverDirectoryService: service }) as never
+ )
+ const request = { path: '/downloads' }
+ expect(await handlers[Queries.ListServerDirectories]?.(request)).toEqual({
+ ok: false,
+ error: { code: 'outsideRoots' },
+ })
+ expect(await handlers[Queries.ValidateServerDirectory]?.(request)).toEqual({
+ ok: true,
+ value: { path: '/downloads' },
+ })
+ expect(service.list).toHaveBeenCalledExactlyOnceWith(request)
+ expect(service.validate).toHaveBeenCalledExactlyOnceWith(request)
+ })
it('reports the proxy inherited by the Server process', async () => {
const handlers = buildServerQueryHandlers(
makeCtx({
@@ -670,3 +697,47 @@ describe('buildServerQueryHandlers — GetTaskInspectorActivity parity', () => {
})
})
})
+
+describe('directory location query validation', () => {
+ it('returns one General draft snapshot and validates before reading it', async () => {
+ const snapshot = generalSettingsSnapshot({
+ favorites: ['/saved'],
+ recent: [],
+ })
+ const getGeneralSettingsSnapshot = vi.fn(() => snapshot)
+ const handlers = buildServerQueryHandlers({
+ settingsManager: { getGeneralSettingsSnapshot },
+ } as unknown as ServerQueryContext)
+ expect(
+ await handlers[Queries.GetGeneralSettingsDraft]?.({ extra: true })
+ ).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ expect(getGeneralSettingsSnapshot).not.toHaveBeenCalled()
+ expect(await handlers[Queries.GetGeneralSettingsDraft]?.({})).toEqual({
+ ok: true,
+ value: snapshot,
+ })
+ expect(getGeneralSettingsSnapshot).toHaveBeenCalledOnce()
+ })
+
+ it('rejects invalid requests before reading settings or discovering filesystem locations', async () => {
+ const getApp = vi.fn()
+ const locations = vi.fn()
+ const handlers = buildServerQueryHandlers({
+ settingsManager: { getApp },
+ serverDirectoryService: { locations },
+ } as unknown as ServerQueryContext)
+ expect(
+ await handlers[Queries.ListServerDirectoryLocations]?.({
+ favorites: ['/outside'],
+ })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(
+ await handlers[Queries.GetDirectoryPreferences]?.({ path: '/outside' })
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(getApp).not.toHaveBeenCalled()
+ expect(locations).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index 01c5ddd4..88f06037 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -20,6 +20,8 @@ import {
import type { RegistryClient } from '@core/plugin/registry/registry-client'
import { parseProxyEnvironment } from '@core/proxy/system-proxy'
import type { MotrixDatabase } from '@core/session/motrix-database'
+import { createDirectoryPreferencesHandlers } from '@core/settings/directory-preferences'
+import { createGetGeneralSettingsDraftHandler } from '@core/settings/general-settings'
import type { SettingsManager } from '@core/settings/settings-manager'
import type { SpeedLimitController } from '@core/speed-limit/speed-limit-controller'
import type {
@@ -36,6 +38,7 @@ import type { TaskManager } from '@core/task/task-manager'
import type { TrackerManager } from '@core/tracker'
import type { QueryHandlerMap } from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import { ListServerDirectoryLocationsRequestSchema } from '@shared/schemas/server-directory'
import type { AppUpdateState } from '@shared/types/app-update'
import type { AppImageIntegrationView } from '@shared/types/appimage-integration'
import {
@@ -49,6 +52,7 @@ import type { GetTransferStatsParams } from '@shared/types/stats'
import type { GetTaskActivityParams } from '@shared/types/task-activity'
import type { ServerDownloadPathPolicy } from '../download-path-policy'
import { makeServerFfmpegDetect } from '../plugin/ffmpeg-detect-server'
+import type { ServerDirectoryService } from '../server-directory-service'
const UNSUPPORTED_WEB_CLI_STATUS: CliToolStatus = {
phase: CliToolPhase.ManualOnly,
@@ -119,6 +123,10 @@ export interface ServerQueryContext {
userDataDir: string
speedLimitController: SpeedLimitController
downloadPathPolicy: ServerDownloadPathPolicy
+ serverDirectoryService: Pick<
+ ServerDirectoryService,
+ 'list' | 'validate' | 'locations'
+ >
environment: NodeJS.ProcessEnv
}
@@ -158,6 +166,21 @@ export function buildServerQueryHandlers(
})
return {
+ [Queries.ListServerDirectoryLocations]: async (request: unknown) => {
+ if (
+ !ListServerDirectoryLocationsRequestSchema.safeParse(request).success
+ ) {
+ return { ok: false, error: { code: 'invalidPath' } }
+ }
+ return ctx.serverDirectoryService.locations(
+ request,
+ settingsManager.getApp()
+ )
+ },
+ [Queries.ListServerDirectories]: async (request: unknown) =>
+ ctx.serverDirectoryService.list(request),
+ [Queries.ValidateServerDirectory]: async (request: unknown) =>
+ ctx.serverDirectoryService.validate(request),
[Queries.GetDisclaimerState]: async () => ({
language: settingsManager.getApp().language,
}),
@@ -224,6 +247,11 @@ export function buildServerQueryHandlers(
[Queries.GetNatDiagnostic]: async () => null,
+ [Queries.GetGeneralSettingsDraft]:
+ createGetGeneralSettingsDraftHandler(settingsManager),
+ [Queries.GetDirectoryPreferences]:
+ createDirectoryPreferencesHandlers(settingsManager).get,
+
[Queries.GetSettings]: async () => settingsManager.get(),
[Queries.GetGeoIPStatus]: createGetGeoIPStatusHandler({ geoipManager }),
diff --git a/src/server/server-directory-service.test.ts b/src/server/server-directory-service.test.ts
new file mode 100644
index 00000000..03c6be87
--- /dev/null
+++ b/src/server/server-directory-service.test.ts
@@ -0,0 +1,640 @@
+import { constants, type Dir, type Dirent } from 'node:fs'
+import {
+ access,
+ chmod,
+ mkdir,
+ mkdtemp,
+ opendir,
+ readdir,
+ realpath,
+ rm,
+ stat,
+ symlink,
+ utimes,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createServerDownloadPathPolicy } from './download-path-policy'
+import { ServerDirectoryService } from './server-directory-service'
+
+const temporary: string[] = []
+async function fixture(unrestricted = false) {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-directory-'))
+ temporary.push(root)
+ const downloads = path.join(root, 'downloads')
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: downloads,
+ allowedSaveDirsValue: unrestricted ? undefined : downloads,
+ })
+ return {
+ root,
+ downloads,
+ policy,
+ service: new ServerDirectoryService(policy),
+ }
+}
+afterEach(async () => {
+ vi.restoreAllMocks()
+ await Promise.all(
+ temporary
+ .splice(0)
+ .map((root) => rm(root, { recursive: true, force: true }))
+ )
+})
+
+describe('ServerDirectoryService', () => {
+ it('lists only immediate authorized directories with deterministic natural order and hidden filter', async () => {
+ const { root, downloads, service } = await fixture()
+ await Promise.all(
+ ['folder10', 'folder2', '.hidden', 'outer/nested'].map((name) =>
+ mkdir(path.join(downloads, name), { recursive: true })
+ )
+ )
+ await writeFile(path.join(downloads, 'file'), '')
+ await mkdir(path.join(root, 'outside'))
+ await symlink(path.join(root, 'outside'), path.join(downloads, 'escape'))
+ await symlink(
+ path.join(downloads, 'missing'),
+ path.join(downloads, 'broken')
+ )
+ const result = await service.list({ path: downloads })
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ path: downloads,
+ parentPath: null,
+ breadcrumbs: [{ name: 'downloads', path: downloads }],
+ entries: ['folder2', 'folder10', 'outer'].map((name) => ({
+ name,
+ path: path.join(downloads, name),
+ modifiedAt: expect.any(Number),
+ })),
+ truncated: false,
+ canCreate: true,
+ },
+ })
+ const hidden = await service.list({ path: downloads, showHidden: true })
+ expect(
+ hidden.ok && hidden.value.entries.map((entry) => entry.name)
+ ).toContain('.hidden')
+ expect(
+ await service.list({ path: path.join(downloads, 'escape') })
+ ).toEqual({ ok: false, error: { code: 'outsideRoots' } })
+ })
+
+ it('returns authorized target modification times only on listing entries', async () => {
+ const { downloads, service } = await fixture()
+ const target = path.join(downloads, 'target')
+ const alias = path.join(downloads, 'alias')
+ await mkdir(target)
+ await symlink(target, alias)
+ await utimes(target, new Date(1700000000123), new Date(1700000000123))
+ const expected = (await stat(target)).mtimeMs
+ const result = await service.list({ path: downloads })
+ expect(result).toMatchObject({
+ ok: true,
+ value: {
+ entries: [
+ { name: 'alias', path: alias, modifiedAt: expected },
+ { name: 'target', path: target, modifiedAt: expected },
+ ],
+ },
+ })
+ expect(result.ok && result.value.breadcrumbs).toEqual([
+ { name: 'downloads', path: downloads },
+ ])
+ expect(
+ await service.create({ parentPath: downloads, name: 'new' })
+ ).toEqual({
+ ok: true,
+ value: { name: 'new', path: path.join(downloads, 'new') },
+ })
+ const locations = await service.locations(
+ {},
+ {
+ defaultSaveDir: downloads,
+ directoryPreferences: { favorites: [alias], recent: [target] },
+ }
+ )
+ expect(locations.ok).toBe(true)
+ if (locations.ok) {
+ for (const group of Object.values(locations.value))
+ for (const entry of group)
+ expect(entry).not.toHaveProperty('modifiedAt')
+ }
+ })
+
+ it.each([undefined, Number.NaN, Infinity, -Infinity])(
+ 'keeps children with unavailable metadata selectable: %s',
+ async (modifiedAt) => {
+ const { downloads, policy } = await fixture()
+ const childPath = path.join(downloads, 'child')
+ await mkdir(childPath)
+ const authorize = policy.authorizeDirectory.bind(policy)
+ vi.spyOn(policy, 'authorizeDirectory').mockImplementation(
+ async (candidate) => {
+ const result = await authorize(candidate)
+ if (candidate === childPath) return { ...result, modifiedAt }
+ return result
+ }
+ )
+ const result = await new ServerDirectoryService(policy).list({
+ path: downloads,
+ })
+ expect(result.ok && result.value.entries).toEqual([
+ { name: 'child', path: childPath },
+ ])
+ }
+ )
+
+ it('skips cyclic child links while keeping direct access to the cycle unavailable', async () => {
+ const { downloads, service } = await fixture()
+ const visible = path.join(downloads, 'visible')
+ const cycle = path.join(downloads, 'cycle')
+ await mkdir(visible)
+ await symlink('cycle', cycle)
+
+ expect(await service.list({ path: downloads })).toMatchObject({
+ ok: true,
+ value: {
+ entries: [{ name: 'visible', path: visible }],
+ truncated: false,
+ },
+ })
+ const unavailable = { ok: false, error: { code: 'unavailable' } }
+ expect(await service.list({ path: cycle })).toEqual(unavailable)
+ expect(await service.validate({ path: cycle })).toEqual(unavailable)
+ expect(await service.create({ parentPath: cycle, name: 'child' })).toEqual(
+ unavailable
+ )
+ })
+
+ it('skips an overlong child link target without hiding siblings or accepting direct access', async () => {
+ const { downloads, service } = await fixture()
+ const visible = path.join(downloads, 'visible')
+ const broken = path.join(downloads, 'broken')
+ await mkdir(visible)
+ await symlink('x'.repeat(256), broken)
+
+ expect(await service.list({ path: downloads })).toMatchObject({
+ ok: true,
+ value: {
+ entries: [{ name: 'visible', path: visible }],
+ truncated: false,
+ },
+ })
+ const tooLarge = { ok: false, error: { code: 'tooLarge' } }
+ expect(await service.list({ path: broken })).toEqual(tooLarge)
+ expect(await service.validate({ path: broken })).toEqual(tooLarge)
+ expect(await service.create({ parentPath: broken, name: 'child' })).toEqual(
+ tooLarge
+ )
+ })
+
+ it('browses and validates without prepare, mkdir or write probes, including missing and invalid paths', async () => {
+ const { downloads, policy } = await fixture()
+ const prepare = vi.spyOn(policy, 'prepareSaveDir')
+ const create = vi.fn(mkdir)
+ const service = new ServerDirectoryService(policy, {
+ access,
+ mkdir: create as typeof mkdir,
+ opendir,
+ })
+ expect((await service.list({ path: downloads })).ok).toBe(true)
+ expect(await service.validate({ path: downloads })).toEqual({
+ ok: true,
+ value: { path: downloads },
+ })
+ expect(
+ await service.validate({ path: path.join(downloads, 'missing') })
+ ).toEqual({ ok: false, error: { code: 'notFound' } })
+ expect(await service.list({ path: 'relative' })).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ expect(await service.validate({ path: `${downloads}\0` })).toEqual({
+ ok: false,
+ error: { code: 'invalidPath' },
+ })
+ await writeFile(path.join(downloads, 'file'), '')
+ expect(await service.list({ path: path.join(downloads, 'file') })).toEqual({
+ ok: false,
+ error: { code: 'notDirectory' },
+ })
+ expect(prepare).not.toHaveBeenCalled()
+ expect(create).not.toHaveBeenCalled()
+ expect(await readdir(downloads)).toEqual(['file'])
+ })
+
+ it('uses deepest logical root boundaries and unrestricted filesystem roots', async () => {
+ const { root, downloads } = await fixture()
+ const nested = path.join(downloads, 'nested')
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: downloads,
+ allowedSaveDirsValue: [downloads, nested].join(path.delimiter),
+ })
+ const service = new ServerDirectoryService(policy)
+ expect(await service.list({ path: nested })).toMatchObject({
+ ok: true,
+ value: {
+ parentPath: null,
+ breadcrumbs: [{ name: 'nested', path: nested }],
+ },
+ })
+ const unrestricted = await createServerDownloadPathPolicy({
+ defaultSaveDir: downloads,
+ })
+ expect(
+ await new ServerDirectoryService(unrestricted).list({ path: root })
+ ).toMatchObject({
+ ok: true,
+ value: {
+ parentPath: path.dirname(root),
+ breadcrumbs: expect.arrayContaining([
+ { name: path.parse(root).root, path: path.parse(root).root },
+ ]),
+ },
+ })
+ })
+
+ it('keeps configured root and internal aliases, while canonical values round-trip', async () => {
+ const { root, downloads } = await fixture()
+ const alias = path.join(root, 'alias')
+ await symlink(downloads, alias)
+ await mkdir(path.join(downloads, 'real-child'))
+ await symlink(
+ path.join(downloads, 'real-child'),
+ path.join(downloads, 'internal')
+ )
+ const policy = await createServerDownloadPathPolicy({
+ defaultSaveDir: alias,
+ allowedSaveDirsValue: alias,
+ })
+ const service = new ServerDirectoryService(policy)
+ const logical = path.join(alias, 'internal')
+ expect(await service.validate({ path: logical })).toEqual({
+ ok: true,
+ value: { path: logical },
+ })
+ const prepared = await policy.prepareSaveDir(logical)
+ expect(prepared).toBe(await realpath(logical))
+ expect(await service.validate({ path: prepared })).toEqual({
+ ok: true,
+ value: { path: path.join(alias, 'real-child') },
+ })
+ expect(await policy.prepareSaveDir(prepared)).toBe(prepared)
+ expect(await service.create({ parentPath: logical, name: 'new' })).toEqual({
+ ok: true,
+ value: { path: path.join(logical, 'new'), name: 'new' },
+ })
+ })
+
+ it('creates exactly one persistent child, preserving legal POSIX whitespace identity', async () => {
+ const { downloads, policy, service } = await fixture()
+ for (const name of process.platform === 'win32'
+ ? ['Movies']
+ : ['Movies', 'Movies ', ' ']) {
+ const child = path.join(downloads, name)
+ expect(await service.create({ parentPath: downloads, name })).toEqual({
+ ok: true,
+ value: { path: child, name },
+ })
+ expect(await service.validate({ path: child })).toEqual({
+ ok: true,
+ value: { path: child },
+ })
+ expect(await policy.prepareSaveDir(child)).toBe(await realpath(child))
+ expect(await service.create({ parentPath: downloads, name })).toEqual({
+ ok: false,
+ error: { code: 'alreadyExists' },
+ })
+ }
+ expect(
+ await service.create({
+ parentPath: path.join(downloads, 'missing'),
+ name: 'child',
+ })
+ ).toEqual({ ok: false, error: { code: 'notFound' } })
+ expect(await readdir(downloads)).not.toContain('missing')
+ })
+
+ it.each([
+ '',
+ '.',
+ '..',
+ '../escape',
+ 'a/b',
+ 'a\\b',
+ 'a\0b',
+ 'a\nb',
+ 'x'.repeat(256),
+ ])('rejects non-filename input %j', async (name) => {
+ const { downloads, service } = await fixture()
+ expect(await service.create({ parentPath: downloads, name })).toEqual({
+ ok: false,
+ error: { code: 'invalidName' },
+ })
+ expect(await readdir(downloads)).toEqual([])
+ })
+
+ it('rejects Windows forbidden names on a Windows host before touching the filesystem', async () => {
+ const { downloads, service } = await fixture()
+ vi.stubGlobal(
+ 'process',
+ Object.create(process, { platform: { value: 'win32' } })
+ )
+ try {
+ for (const name of [
+ 'CON',
+ 'nul.txt',
+ 'COM1.log',
+ 'LPT9',
+ 'COM¹.txt',
+ 'folder ',
+ 'folder.',
+ 'a:b',
+ 'a*',
+ 'a?',
+ 'a|',
+ 'a"',
+ 'a<',
+ 'a>',
+ ]) {
+ expect(await service.create({ parentPath: downloads, name })).toEqual({
+ ok: false,
+ error: { code: 'invalidName' },
+ })
+ }
+ expect(await readdir(downloads)).toEqual([])
+ } finally {
+ vi.unstubAllGlobals()
+ }
+ })
+
+ it('does not create through an escaping parent symlink', async () => {
+ const { root, downloads, service } = await fixture()
+ const outside = path.join(root, 'outside')
+ await mkdir(outside)
+ await symlink(outside, path.join(downloads, 'escape'))
+ expect(
+ await service.create({
+ parentPath: path.join(downloads, 'escape'),
+ name: 'new',
+ })
+ ).toEqual({ ok: false, error: { code: 'outsideRoots' } })
+ expect(await readdir(outside)).toEqual([])
+ })
+
+ it('reports advisory permissions and does not claim validation can write', async () => {
+ const { downloads, policy } = await fixture()
+ const denied = Object.assign(new Error('secret permission detail'), {
+ code: 'EACCES',
+ })
+ const create = vi.fn(mkdir)
+ const service = new ServerDirectoryService(policy, {
+ access: vi.fn(async (candidate, mode) => {
+ if ((mode ?? 0) & constants.W_OK) throw denied
+ return access(candidate, mode)
+ }),
+ mkdir: create as typeof mkdir,
+ opendir,
+ })
+ expect(await service.list({ path: downloads })).toMatchObject({
+ ok: true,
+ value: { canCreate: false },
+ })
+ expect(await service.validate({ path: downloads })).toEqual({
+ ok: false,
+ error: { code: 'permissionDenied' },
+ })
+ expect(
+ await service.create({ parentPath: downloads, name: 'new' })
+ ).toEqual({ ok: false, error: { code: 'permissionDenied' } })
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('sanitizes actual OS permission failures', async () => {
+ const { downloads, service } = await fixture()
+ await chmod(downloads, 0o000)
+ try {
+ expect(await service.list({ path: downloads })).toEqual({
+ ok: false,
+ error: { code: 'permissionDenied' },
+ })
+ } finally {
+ await chmod(downloads, 0o700)
+ }
+ })
+
+ it('returns unknown outcome after successful mkdir whose post-check fails, and never deletes it', async () => {
+ const { downloads, policy } = await fixture()
+ const original = policy.authorizeDirectory.bind(policy)
+ vi.spyOn(policy, 'authorizeDirectory').mockImplementation(
+ async (candidate) => {
+ if (candidate === path.join(downloads, 'new'))
+ throw Object.assign(new Error('private detail'), { code: 'EIO' })
+ return original(candidate)
+ }
+ )
+ const service = new ServerDirectoryService(policy)
+ expect(
+ await service.create({ parentPath: downloads, name: 'new' })
+ ).toEqual({ ok: false, error: { code: 'creationOutcomeUnknown' } })
+ expect((await stat(path.join(downloads, 'new'))).isDirectory()).toBe(true)
+ })
+
+ it.each([
+ { directory: false, limit: 10000 },
+ { directory: true, limit: 2000 },
+ ])(
+ 'bounds scan and result work and closes capped handles: %j',
+ async ({ directory, limit }) => {
+ const { downloads, policy } = await fixture()
+ const authorize = vi.spyOn(policy, 'authorizeDirectory')
+ const parent = await policy.authorizeDirectory(downloads)
+ authorize.mockImplementation(async (candidate) => ({
+ ...parent,
+ path: candidate,
+ }))
+ const read = vi.fn(
+ async () =>
+ ({
+ name: `folder${read.mock.calls.length}`,
+ isDirectory: () => directory,
+ isSymbolicLink: () => false,
+ }) as Dirent
+ )
+ const close = vi.fn(async () => undefined)
+ const service = new ServerDirectoryService(policy, {
+ access,
+ mkdir,
+ opendir: vi.fn(
+ async () => ({ read, close }) as unknown as Dir
+ ) as typeof opendir,
+ })
+ const result = await service.list({ path: downloads })
+ expect(result).toMatchObject({ ok: true, value: { truncated: true } })
+ expect(read).toHaveBeenCalledTimes(limit)
+ expect(close).toHaveBeenCalledOnce()
+ expect(result.ok && result.value.entries.length).toBe(
+ directory ? 2000 : 0
+ )
+ }
+ )
+
+ it('closes handles when reading fails and sanitizes the filesystem error', async () => {
+ const { downloads, policy } = await fixture()
+ const close = vi.fn(async () => undefined)
+ const service = new ServerDirectoryService(policy, {
+ access,
+ mkdir,
+ opendir: vi.fn(
+ async () =>
+ ({
+ read: vi.fn().mockRejectedValue(new Error('private detail')),
+ close,
+ }) as unknown as Dir
+ ) as typeof opendir,
+ })
+ expect(await service.list({ path: downloads })).toEqual({
+ ok: false,
+ error: { code: 'unavailable' },
+ })
+ expect(close).toHaveBeenCalledOnce()
+ })
+})
+
+describe('ServerDirectoryService locations', () => {
+ it('discovers existing unrestricted common places without creating missing directories and preserves semantic duplicates', async () => {
+ const { root, policy, downloads } = await fixture(true)
+ await mkdir(path.join(root, 'Desktop'))
+ await mkdir(path.join(root, 'Downloads'), { recursive: true })
+ const fs = {
+ access: vi.fn(access),
+ mkdir: vi.fn(mkdir) as typeof mkdir,
+ opendir,
+ }
+ const service = new ServerDirectoryService(policy, fs, () => root)
+ const result = await service.locations(
+ {},
+ {
+ defaultSaveDir: root,
+ directoryPreferences: { favorites: [], recent: [] },
+ }
+ )
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ common: [
+ { kind: 'default', path: root },
+ { kind: 'home', path: root },
+ { kind: 'desktop', path: path.join(root, 'Desktop') },
+ { kind: 'downloads', path: path.join(root, 'Downloads') },
+ { kind: 'root', path: path.parse(root).root },
+ ],
+ favorites: [],
+ recent: [],
+ },
+ })
+ expect(fs.mkdir).not.toHaveBeenCalled()
+ expect(await readdir(root)).toEqual(
+ expect.arrayContaining(['Desktop', path.basename(downloads)])
+ )
+ expect(await readdir(root)).not.toContain('Documents')
+ expect(
+ fs.access.mock.calls.every(
+ ([, mode]) => mode === (constants.R_OK | constants.X_OK)
+ )
+ ).toBe(true)
+ })
+
+ it('filters inaccessible/outside/stale records and canonically groups all saved identities into authorized aliases', async () => {
+ const { root, downloads, policy } = await fixture()
+ const target = path.join(downloads, 'target')
+ const alias = path.join(downloads, 'alias')
+ const outside = path.join(root, 'outside')
+ await mkdir(target)
+ await mkdir(outside)
+ await symlink(target, alias)
+ await symlink(outside, path.join(downloads, 'escape'))
+ const canonical = await realpath(target)
+ const preferences = {
+ favorites: [
+ alias,
+ canonical,
+ outside,
+ path.join(downloads, 'escape'),
+ path.join(downloads, 'missing'),
+ ],
+ recent: [canonical],
+ }
+ const service = new ServerDirectoryService(
+ policy,
+ { access, mkdir, opendir },
+ () => root
+ )
+ const result = await service.locations(
+ {},
+ { defaultSaveDir: downloads, directoryPreferences: preferences }
+ )
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ common: [{ kind: 'default', path: downloads }],
+ favorites: [
+ { name: 'alias', path: alias, sourcePaths: [alias, canonical] },
+ ],
+ recent: [{ name: 'alias', path: alias, sourcePaths: [canonical] }],
+ },
+ })
+ expect(preferences.favorites).toHaveLength(5)
+ const denied = new ServerDirectoryService(
+ policy,
+ {
+ access: vi
+ .fn()
+ .mockRejectedValue(
+ Object.assign(new Error('secret'), { code: 'EACCES' })
+ ),
+ mkdir,
+ opendir,
+ },
+ () => root
+ )
+ expect(
+ await denied.locations(
+ {},
+ { defaultSaveDir: downloads, directoryPreferences: preferences }
+ )
+ ).toEqual({ ok: true, value: { common: [], favorites: [], recent: [] } })
+ })
+
+ it('rejects client-supplied location arrays before discovery and validates saved additions readonly', async () => {
+ const { downloads, policy } = await fixture()
+ const authorize = vi.spyOn(policy, 'authorizeDirectory')
+ const fs = {
+ access: vi.fn(access),
+ mkdir: vi.fn(mkdir) as typeof mkdir,
+ opendir,
+ }
+ const service = new ServerDirectoryService(policy, fs)
+ expect(
+ await service.locations(
+ { favorites: [downloads] },
+ {
+ defaultSaveDir: downloads,
+ directoryPreferences: { favorites: [], recent: [] },
+ }
+ )
+ ).toEqual({ ok: false, error: { code: 'invalidPath' } })
+ expect(authorize).not.toHaveBeenCalled()
+ expect(await service.resolvePreferenceDirectory(downloads)).toBe(downloads)
+ expect(fs.access).toHaveBeenCalledWith(
+ await realpath(downloads),
+ constants.R_OK | constants.X_OK
+ )
+ expect(fs.mkdir).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/server/server-directory-service.ts b/src/server/server-directory-service.ts
new file mode 100644
index 00000000..52ef47ea
--- /dev/null
+++ b/src/server/server-directory-service.ts
@@ -0,0 +1,337 @@
+import { constants } from 'node:fs'
+import { access, mkdir, opendir } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import path from 'node:path'
+import { AppError } from '@shared/errors'
+import {
+ CreateServerDirectoryRequestSchema,
+ type CreateServerDirectoryResult,
+ CreateServerDirectoryResultSchema,
+ type DirectoryErrorCode,
+ ListServerDirectoriesRequestSchema,
+ type ListServerDirectoriesResult,
+ ListServerDirectoriesResultSchema,
+ ListServerDirectoryLocationsRequestSchema,
+ type ListServerDirectoryLocationsResult,
+ ListServerDirectoryLocationsResultSchema,
+ SERVER_DIRECTORY_ENTRY_LIMIT,
+ SERVER_DIRECTORY_PATH_LIMIT,
+ SERVER_DIRECTORY_SCAN_LIMIT,
+ type ServerDirectoryLocations,
+ ValidateServerDirectoryRequestSchema,
+ type ValidateServerDirectoryResult,
+ ValidateServerDirectoryResultSchema,
+} from '@shared/schemas/server-directory'
+import type { MotrixAppSettings } from '@shared/types/settings'
+import {
+ type AuthorizedServerDirectory,
+ DirectoryAuthorizationError,
+ type ServerDownloadPathPolicy,
+} from './download-path-policy'
+
+const filesystem = { access, mkdir, opendir }
+
+function errorCode(error: unknown): DirectoryErrorCode {
+ if (error instanceof DirectoryAuthorizationError) return error.directoryCode
+ if (error instanceof AppError) return 'invalidPath'
+ switch ((error as NodeJS.ErrnoException | null)?.code) {
+ case 'ENOENT':
+ return 'notFound'
+ case 'ENOTDIR':
+ return 'notDirectory'
+ case 'EPERM':
+ case 'EROFS':
+ case 'EACCES':
+ return 'permissionDenied'
+ case 'EEXIST':
+ return 'alreadyExists'
+ case 'ENAMETOOLONG':
+ return 'tooLarge'
+ case 'EINVAL':
+ return 'invalidPath'
+ default:
+ return 'unavailable'
+ }
+}
+
+function failure(code: DirectoryErrorCode) {
+ return { ok: false as const, error: { code } }
+}
+
+function validName(name: string): boolean {
+ if (
+ name === '.' ||
+ name === '..' ||
+ /[/\\]/u.test(name) ||
+ Array.from(name).some(
+ (character) =>
+ character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127
+ )
+ )
+ return false
+ if (process.platform !== 'win32') return true
+ return !(
+ /[<>:"|?*]/u.test(name) ||
+ /[. ]$/u.test(name) ||
+ /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(name)
+ )
+}
+
+function navigation(directory: AuthorizedServerDirectory) {
+ const breadcrumbs = [
+ {
+ name: path.basename(directory.rootPath) || directory.rootPath,
+ path: directory.rootPath,
+ },
+ ]
+ const suffix = path.relative(directory.rootPath, directory.path)
+ let current = directory.rootPath
+ for (const name of suffix ? suffix.split(path.sep) : []) {
+ current = path.join(current, name)
+ breadcrumbs.push({ name, path: current })
+ }
+ return {
+ breadcrumbs,
+ parentPath: suffix === '' ? null : path.dirname(directory.path),
+ }
+}
+
+/** Read operations never prepare directories or create write probes. */
+export class ServerDirectoryService {
+ constructor(
+ private readonly policy: ServerDownloadPathPolicy,
+ private readonly fs: typeof filesystem = filesystem,
+ private readonly homeDirectory: () => string = homedir
+ ) {}
+
+ async resolvePreferenceDirectory(value: string): Promise<string> {
+ if (!path.isAbsolute(value) || value.includes('\0')) {
+ throw new DirectoryAuthorizationError('invalidPath', 'Invalid directory')
+ }
+ const directory = await this.policy.authorizeDirectory(value)
+ await this.fs.access(
+ directory.canonicalPath,
+ constants.R_OK | constants.X_OK
+ )
+ return directory.path
+ }
+
+ async locations(
+ raw: unknown,
+ settings: Pick<MotrixAppSettings, 'defaultSaveDir' | 'directoryPreferences'>
+ ): Promise<ListServerDirectoryLocationsResult> {
+ if (!ListServerDirectoryLocationsRequestSchema.safeParse(raw).success)
+ return failure('invalidPath')
+ try {
+ const home = this.homeDirectory()
+ const value: ServerDirectoryLocations = {
+ common: [],
+ favorites: [],
+ recent: [],
+ }
+ const candidates: ServerDirectoryLocations['common'] = [
+ { kind: 'default', path: settings.defaultSaveDir },
+ { kind: 'home', path: home },
+ { kind: 'desktop', path: path.join(home, 'Desktop') },
+ { kind: 'documents', path: path.join(home, 'Documents') },
+ { kind: 'downloads', path: path.join(home, 'Downloads') },
+ { kind: 'root', path: path.parse(settings.defaultSaveDir).root },
+ ]
+ const aliases = new Map<string, string>()
+ const authorize = async (candidate: string) => {
+ if (!candidate || candidate.length > SERVER_DIRECTORY_PATH_LIMIT)
+ return null
+ try {
+ const directory = await this.policy.authorizeDirectory(candidate)
+ await this.fs.access(
+ directory.canonicalPath,
+ constants.R_OK | constants.X_OK
+ )
+ const logical = aliases.get(directory.canonicalPath) ?? directory.path
+ aliases.set(directory.canonicalPath, logical)
+ return { canonical: directory.canonicalPath, path: logical }
+ } catch {
+ // Discovery never removes saved records or creates unavailable places.
+ return null
+ }
+ }
+ for (const candidate of candidates) {
+ const directory = await authorize(candidate.path)
+ if (directory)
+ value.common.push({ kind: candidate.kind, path: directory.path })
+ }
+ for (const section of ['favorites', 'recent'] as const) {
+ const groups = new Map<
+ string,
+ ServerDirectoryLocations[typeof section][number]
+ >()
+ for (const saved of settings.directoryPreferences[section]) {
+ const directory = await authorize(saved)
+ if (!directory) continue
+ const existing = groups.get(directory.canonical)
+ if (existing) {
+ if (!existing.sourcePaths.includes(saved))
+ existing.sourcePaths.push(saved)
+ } else {
+ const location = {
+ name: path.basename(directory.path) || directory.path,
+ path: directory.path,
+ sourcePaths: [saved],
+ }
+ groups.set(directory.canonical, location)
+ value[section].push(location)
+ }
+ }
+ }
+ return ListServerDirectoryLocationsResultSchema.parse({ ok: true, value })
+ } catch {
+ return failure('unavailable')
+ }
+ }
+
+ private async writable(
+ directory: AuthorizedServerDirectory
+ ): Promise<boolean> {
+ try {
+ await this.fs.access(
+ directory.canonicalPath,
+ constants.W_OK | constants.X_OK
+ )
+ return true
+ } catch (error) {
+ if (errorCode(error) === 'permissionDenied') return false
+ throw error
+ }
+ }
+
+ async list(raw: unknown): Promise<ListServerDirectoriesResult> {
+ const request = ListServerDirectoriesRequestSchema.safeParse(raw)
+ if (!request.success) return failure('invalidPath')
+ try {
+ const directory = await this.policy.authorizeDirectory(request.data.path)
+ await this.fs.access(
+ directory.canonicalPath,
+ constants.R_OK | constants.X_OK
+ )
+ const entries: Extract<
+ ListServerDirectoriesResult,
+ { ok: true }
+ >['value']['entries'] = []
+ const handle = await this.fs.opendir(directory.canonicalPath)
+ let scanned = 0
+ let truncated = false
+ try {
+ while (
+ scanned < SERVER_DIRECTORY_SCAN_LIMIT &&
+ entries.length < SERVER_DIRECTORY_ENTRY_LIMIT
+ ) {
+ const entry = await handle.read()
+ if (!entry) break
+ scanned++
+ if (!request.data.showHidden && entry.name.startsWith('.')) continue
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
+ const childPath = path.join(directory.path, entry.name)
+ if (childPath.length > SERVER_DIRECTORY_PATH_LIMIT) {
+ truncated = true
+ continue
+ }
+ try {
+ const child = await this.policy.authorizeDirectory(childPath)
+ entries.push({
+ name: entry.name,
+ path: child.path,
+ ...(Number.isFinite(child.modifiedAt)
+ ? { modifiedAt: child.modifiedAt }
+ : {}),
+ })
+ } catch (error) {
+ // An unresolvable child link must not hide its healthy siblings.
+ // Direct requests still fail through the outer error boundary.
+ const code = (error as NodeJS.ErrnoException | null)?.code
+ if (code === 'ELOOP' || code === 'ENAMETOOLONG') continue
+ if (
+ ![
+ 'outsideRoots',
+ 'notFound',
+ 'notDirectory',
+ 'permissionDenied',
+ ].includes(errorCode(error))
+ )
+ throw error
+ }
+ }
+ truncated ||=
+ scanned === SERVER_DIRECTORY_SCAN_LIMIT ||
+ entries.length === SERVER_DIRECTORY_ENTRY_LIMIT
+ } finally {
+ await handle.close()
+ }
+ entries.sort(
+ (a, b) =>
+ a.name.localeCompare(b.name, 'en', {
+ numeric: true,
+ sensitivity: 'base',
+ }) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
+ )
+ return ListServerDirectoriesResultSchema.parse({
+ ok: true,
+ value: {
+ path: directory.path,
+ ...navigation(directory),
+ entries,
+ truncated,
+ canCreate: await this.writable(directory),
+ },
+ })
+ } catch (error) {
+ return failure(errorCode(error))
+ }
+ }
+
+ async validate(raw: unknown): Promise<ValidateServerDirectoryResult> {
+ const request = ValidateServerDirectoryRequestSchema.safeParse(raw)
+ if (!request.success) return failure('invalidPath')
+ try {
+ const directory = await this.policy.authorizeDirectory(request.data.path)
+ if (!(await this.writable(directory))) return failure('permissionDenied')
+ return ValidateServerDirectoryResultSchema.parse({
+ ok: true,
+ value: { path: directory.path },
+ })
+ } catch (error) {
+ return failure(errorCode(error))
+ }
+ }
+
+ async create(raw: unknown): Promise<CreateServerDirectoryResult> {
+ const request = CreateServerDirectoryRequestSchema.safeParse(raw)
+ if (!request.success)
+ return failure(
+ request.error.issues.some((issue) => issue.path[0] === 'name')
+ ? 'invalidName'
+ : 'invalidPath'
+ )
+ if (!validName(request.data.name)) return failure('invalidName')
+ let created = false
+ try {
+ const parent = await this.policy.authorizeDirectory(
+ request.data.parentPath
+ )
+ const childPath = path.join(parent.path, request.data.name)
+ if (childPath.length > SERVER_DIRECTORY_PATH_LIMIT)
+ return failure('tooLarge')
+ if (!(await this.writable(parent))) return failure('permissionDenied')
+ await this.fs.mkdir(childPath, { recursive: false })
+ created = true
+ const child = await this.policy.authorizeDirectory(childPath)
+ return CreateServerDirectoryResultSchema.parse({
+ ok: true,
+ value: { path: child.path, name: request.data.name },
+ })
+ } catch (error) {
+ // A completed mkdir is persistent even if its post-check cannot certify
+ // the result. Never remove a path that could have changed concurrently.
+ return failure(created ? 'creationOutcomeUnknown' : errorCode(error))
+ }
+ }
+}
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index f4060586..1e774967 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -2421,5 +2421,98 @@
"discardTitle": "Discard this task draft?",
"discardDescription": "Your unsaved links, torrent selection, and settings will be discarded.",
"discardConfirm": "Discard"
+ },
+ "directoryPicker": {
+ "title": "Select server folder",
+ "description": "Paths are on the server (inside the container when using Docker).",
+ "back": "Back",
+ "forward": "Forward",
+ "up": "Up one level",
+ "refresh": "Refresh",
+ "goToFolder": "Go to folder",
+ "location": "Location",
+ "viewOptions": "View options",
+ "sortBy": "Sort by",
+ "sortName": "Name",
+ "sortModified": "Date modified",
+ "sortOrder": "Order",
+ "sortAscending": "Ascending",
+ "sortDescending": "Descending",
+ "showHidden": "Show hidden folders",
+ "folders": "Folders",
+ "loading": "Loading folders…",
+ "empty": "No subfolders",
+ "incomplete": "Only part of this folder is shown. Enter an exact path to reach another folder.",
+ "selectFolder": "Select folder",
+ "selectedPath": "Selected folder",
+ "path": "Folder path",
+ "go": "Go",
+ "newFolder": "New folder",
+ "folderName": "Folder name",
+ "create": "Create",
+ "createHelp": "Created folders remain on the server if you cancel selection.",
+ "fallback": "The requested folder is unavailable. Showing {{path}}.",
+ "refreshAfterCreateFailed": "The folder was created, but the list could not be refreshed.",
+ "unknownOutcome": "Creation could not be confirmed. Refresh to check before creating another folder here.",
+ "retry": "Retry",
+ "errors": {
+ "invalidPath": "Enter a valid absolute folder path.",
+ "outsideRoots": "This folder is outside the allowed locations.",
+ "notFound": "This folder no longer exists.",
+ "notDirectory": "This path is not a folder.",
+ "permissionDenied": "You do not have permission to use this folder.",
+ "alreadyExists": "A file or folder with this name already exists.",
+ "invalidName": "Enter a valid folder name.",
+ "tooLarge": "This path or folder name is too long.",
+ "unavailable": "The server could not complete this request. Try again.",
+ "creationOutcomeUnknown": "Creation could not be confirmed. Refresh to check before creating another folder here."
+ },
+ "places": {
+ "common": "Common places",
+ "allowed": "Allowed locations",
+ "default": "Default folder",
+ "home": "Home",
+ "desktop": "Desktop",
+ "documents": "Documents",
+ "downloads": "Downloads",
+ "root": "File system",
+ "loadFailed": "Some folder locations couldn’t be loaded."
+ }
+ },
+ "directoryPreferences": {
+ "sectionDescription": "Choose favorite folders and manage recent download locations.",
+ "manage": "Manage directories",
+ "manageDescription": "Choose favorite folders and manage recent folders.",
+ "title": "Manage directories",
+ "description": "Changes apply when you save. Removing a record does not delete folders or downloads.",
+ "favorites": "Favorite folders",
+ "recent": "Recent folders",
+ "addFavorite": "Add favorite",
+ "removeFavorite": "Remove favorite",
+ "favoriteRecent": "Add to favorites",
+ "removeRecent": "Remove recent folder",
+ "clearRecent": "Clear recent folders",
+ "emptyFavorites": "No favorite folders",
+ "emptyRecent": "No recent folders",
+ "loading": "Loading directories…",
+ "retry": "Retry",
+ "limitHint": "You can save up to {{count}} favorite folders.",
+ "pickerFailed": "The folder picker could not be opened. Try again.",
+ "close": "Close",
+ "history": "Directory history",
+ "emptyHistory": "No favorite or recent folders yet",
+ "errors": {
+ "conflict": "Settings changed in another window. Review your changes and save again.",
+ "invalidPath": "Enter a valid absolute folder path.",
+ "outsideRoots": "This folder is outside the allowed locations.",
+ "notFound": "This folder no longer exists.",
+ "notDirectory": "This path is not a folder.",
+ "permissionDenied": "You do not have permission to use this folder.",
+ "tooLarge": "This folder path is too long.",
+ "unavailable": "Directory records could not be updated. Refresh to check their current state.",
+ "limitReached": "The favorite folder limit has been reached. Remove a favorite before adding another."
+ },
+ "manageAction": "Manage",
+ "alreadyFavorite": "Already in favorites"
}
}
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index cf3b4662..dcd83db5 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -2400,5 +2400,98 @@
"discardTitle": "丢弃此任务草稿?",
"discardDescription": "未保存的链接、种子选择和设置将被丢弃。",
"discardConfirm": "丢弃"
+ },
+ "directoryPicker": {
+ "title": "选择服务器文件夹",
+ "description": "路径位于服务器上;使用 Docker 时为容器内路径。",
+ "back": "后退",
+ "forward": "前进",
+ "up": "上一级",
+ "refresh": "刷新",
+ "goToFolder": "前往文件夹",
+ "location": "位置",
+ "viewOptions": "视图选项",
+ "sortBy": "排序依据",
+ "sortName": "名称",
+ "sortModified": "修改时间",
+ "sortOrder": "顺序",
+ "sortAscending": "升序",
+ "sortDescending": "降序",
+ "showHidden": "显示隐藏文件夹",
+ "folders": "文件夹",
+ "loading": "正在加载文件夹…",
+ "empty": "没有子文件夹",
+ "incomplete": "当前仅显示部分文件夹。可输入完整路径前往其他文件夹。",
+ "selectFolder": "选择文件夹",
+ "selectedPath": "所选文件夹",
+ "path": "文件夹路径",
+ "go": "前往",
+ "newFolder": "新建文件夹",
+ "folderName": "文件夹名称",
+ "create": "创建",
+ "createHelp": "取消选择后,已创建的文件夹仍会保留在服务器上。",
+ "fallback": "请求的文件夹不可用,正在显示 {{path}}。",
+ "refreshAfterCreateFailed": "文件夹已创建,但未能刷新列表。",
+ "unknownOutcome": "无法确认文件夹是否已创建。请先刷新检查,再在此处创建其他文件夹。",
+ "retry": "重试",
+ "errors": {
+ "invalidPath": "请输入有效的文件夹绝对路径。",
+ "outsideRoots": "此文件夹不在允许的位置范围内。",
+ "notFound": "此文件夹已不存在。",
+ "notDirectory": "此路径不是文件夹。",
+ "permissionDenied": "你没有使用此文件夹的权限。",
+ "alreadyExists": "已存在同名文件或文件夹。",
+ "invalidName": "请输入有效的文件夹名称。",
+ "tooLarge": "路径或文件夹名称过长。",
+ "unavailable": "服务器未能完成请求,请重试。",
+ "creationOutcomeUnknown": "无法确认文件夹是否已创建。请先刷新检查,再在此处创建其他文件夹。"
+ },
+ "places": {
+ "common": "常用位置",
+ "allowed": "允许的位置",
+ "default": "默认目录",
+ "home": "主目录",
+ "desktop": "桌面",
+ "documents": "文稿",
+ "downloads": "下载",
+ "root": "文件系统",
+ "loadFailed": "部分目录位置未能加载。"
+ }
+ },
+ "directoryPreferences": {
+ "sectionDescription": "设置常用目录并管理最近使用的下载目录。",
+ "manage": "管理目录",
+ "manageDescription": "设置常用目录,管理最近使用的目录。",
+ "title": "管理目录",
+ "description": "更改将在保存后生效。移除记录不会删除文件夹或下载任务。",
+ "favorites": "常用目录",
+ "recent": "最近使用",
+ "addFavorite": "添加常用目录",
+ "removeFavorite": "移除常用目录",
+ "favoriteRecent": "添加到常用目录",
+ "removeRecent": "删除最近记录",
+ "clearRecent": "清空最近记录",
+ "emptyFavorites": "暂无常用目录",
+ "emptyRecent": "暂无最近记录",
+ "loading": "正在加载目录…",
+ "retry": "重试",
+ "limitHint": "最多可保存 {{count}} 个常用目录。",
+ "pickerFailed": "无法打开文件夹选择器,请重试。",
+ "close": "关闭",
+ "history": "目录历史",
+ "emptyHistory": "暂无常用目录或最近记录",
+ "errors": {
+ "conflict": "设置已在其他窗口中更改。请检查当前修改后再次保存。",
+ "invalidPath": "请输入有效的文件夹绝对路径。",
+ "outsideRoots": "此文件夹不在允许的位置内。",
+ "notFound": "此文件夹已不存在。",
+ "notDirectory": "此路径不是文件夹。",
+ "permissionDenied": "没有权限使用此文件夹。",
+ "tooLarge": "此文件夹路径过长。",
+ "unavailable": "无法更新目录记录,请刷新确认当前状态。",
+ "limitReached": "常用目录已达上限,请先移除一个再添加。"
+ },
+ "manageAction": "管理",
+ "alreadyFavorite": "已在常用目录中"
}
}
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index ab2d45c8..188cb2b6 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -2400,5 +2400,98 @@
"discardTitle": "捨棄此任務草稿?",
"discardDescription": "未儲存的連結、種子選擇與設定將被捨棄。",
"discardConfirm": "捨棄"
+ },
+ "directoryPicker": {
+ "title": "選擇伺服器資料夾",
+ "description": "路徑位於伺服器上;使用 Docker 時為容器內路徑。",
+ "back": "上一頁",
+ "forward": "下一頁",
+ "up": "上一層",
+ "refresh": "重新整理",
+ "goToFolder": "前往資料夾",
+ "location": "位置",
+ "viewOptions": "檢視選項",
+ "sortBy": "排序依據",
+ "sortName": "名稱",
+ "sortModified": "修改時間",
+ "sortOrder": "順序",
+ "sortAscending": "遞增",
+ "sortDescending": "遞減",
+ "showHidden": "顯示隱藏資料夾",
+ "folders": "資料夾",
+ "loading": "正在載入資料夾…",
+ "empty": "沒有子資料夾",
+ "incomplete": "目前僅顯示部分資料夾。可輸入完整路徑前往其他資料夾。",
+ "selectFolder": "選擇資料夾",
+ "selectedPath": "所選資料夾",
+ "path": "資料夾路徑",
+ "go": "前往",
+ "newFolder": "新增資料夾",
+ "folderName": "資料夾名稱",
+ "create": "建立",
+ "createHelp": "取消選擇後,已建立的資料夾仍會保留在伺服器上。",
+ "fallback": "要求的資料夾無法使用,目前顯示 {{path}}。",
+ "refreshAfterCreateFailed": "資料夾已建立,但無法重新整理清單。",
+ "unknownOutcome": "無法確認資料夾是否已建立。請先重新整理確認,再在此處建立其他資料夾。",
+ "retry": "重試",
+ "errors": {
+ "invalidPath": "請輸入有效的資料夾絕對路徑。",
+ "outsideRoots": "此資料夾不在允許的位置範圍內。",
+ "notFound": "此資料夾已不存在。",
+ "notDirectory": "此路徑不是資料夾。",
+ "permissionDenied": "你沒有使用此資料夾的權限。",
+ "alreadyExists": "已存在同名檔案或資料夾。",
+ "invalidName": "請輸入有效的資料夾名稱。",
+ "tooLarge": "路徑或資料夾名稱過長。",
+ "unavailable": "伺服器無法完成要求,請再試一次。",
+ "creationOutcomeUnknown": "無法確認資料夾是否已建立。請先重新整理確認,再在此處建立其他資料夾。"
+ },
+ "places": {
+ "common": "常用位置",
+ "allowed": "允許的位置",
+ "default": "預設目錄",
+ "home": "個人資料夾",
+ "desktop": "桌面",
+ "documents": "文件",
+ "downloads": "下載",
+ "root": "檔案系統",
+ "loadFailed": "部分目錄位置無法載入。"
+ }
+ },
+ "directoryPreferences": {
+ "sectionDescription": "設定常用資料夾並管理最近使用的下載位置。",
+ "manage": "管理目錄",
+ "manageDescription": "設定常用目錄,管理最近使用的目錄。",
+ "title": "管理目錄",
+ "description": "變更將在儲存後生效。移除記錄不會刪除資料夾或下載任務。",
+ "favorites": "常用目錄",
+ "recent": "最近使用",
+ "addFavorite": "新增常用目錄",
+ "removeFavorite": "移除常用目錄",
+ "favoriteRecent": "加入常用目錄",
+ "removeRecent": "刪除最近記錄",
+ "clearRecent": "清空最近記錄",
+ "emptyFavorites": "尚無常用目錄",
+ "emptyRecent": "尚無最近記錄",
+ "loading": "正在載入目錄…",
+ "retry": "重試",
+ "limitHint": "最多可儲存 {{count}} 個常用目錄。",
+ "pickerFailed": "無法開啟資料夾選擇器,請重試。",
+ "close": "關閉",
+ "history": "目錄歷史",
+ "emptyHistory": "尚無常用目錄或最近記錄",
+ "errors": {
+ "conflict": "設定已在其他視窗中變更。請檢查目前修改後再次儲存。",
+ "invalidPath": "請輸入有效的資料夾絕對路徑。",
+ "outsideRoots": "此資料夾不在允許的位置內。",
+ "notFound": "此資料夾已不存在。",
+ "notDirectory": "此路徑不是資料夾。",
+ "permissionDenied": "沒有權限使用此資料夾。",
+ "tooLarge": "此資料夾路徑過長。",
+ "unavailable": "無法更新目錄記錄,請重新整理以確認目前狀態。",
+ "limitReached": "常用目錄已達上限,請先移除一個再新增。"
+ },
+ "manageAction": "管理",
+ "alreadyFavorite": "已在常用目錄中"
}
}
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 67e58484..d79d732f 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -21,6 +21,8 @@ export const Commands = {
RetryTasks: 'command:retryTasks',
StopSeedingTasks: 'command:stopSeedingTasks',
SetSelectedFiles: 'command:setSelectedFiles',
+ MutateDirectoryPreferences: 'command:mutateDirectoryPreferences',
+ SaveGeneralSettings: 'command:saveGeneralSettings',
UpdateSettings: 'command:updateSettings',
AcceptDisclaimer: 'command:acceptDisclaimer',
DeclineDisclaimer: 'command:declineDisclaimer',
@@ -83,6 +85,7 @@ export const Commands = {
SetTaskBtTracker: 'command:setTaskBtTracker',
// Window
PickSaveDir: 'command:pickSaveDir',
+ CreateServerDirectory: 'command:createServerDirectory',
ResizeWindow: 'command:resizeWindow',
OpenExternal: 'command:openExternal',
RequestDefaultTorrentHandler: 'command:requestDefaultTorrentHandler',
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index 4799dd61..9685e747 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -34,6 +34,7 @@ export const Events = {
TorrentQueueSizeChanged: 'event:torrentQueueSizeChanged',
AppCrash: 'event:appCrash',
AppError: 'event:appError',
+ DirectoryPreferencesChanged: 'event:directoryPreferencesChanged',
SettingsChanged: 'event:settingsChanged',
// Payload: { reduceMotion: boolean }. Full settings remain host-internal.
ReducedMotionChanged: 'event:reducedMotionChanged',
diff --git a/src/shared/protocol/forwardable-events.test.ts b/src/shared/protocol/forwardable-events.test.ts
index 13fed243..57a2ffd8 100644
--- a/src/shared/protocol/forwardable-events.test.ts
+++ b/src/shared/protocol/forwardable-events.test.ts
@@ -9,6 +9,7 @@ describe('ForwardableEvents', () => {
expect(ForwardableEvents).toContain(Events.LiquidGlassChanged)
expect(ForwardableEvents).toContain(Events.ByteUnitSystemChanged)
expect(ForwardableEvents).not.toContain(Events.SettingsChanged)
+ expect(ForwardableEvents).toContain(Events.DirectoryPreferencesChanged)
})
it('contains TaskUpdated', () => {
@@ -24,7 +25,7 @@ describe('ForwardableEvents', () => {
})
it('has the expected number of forwardable events', () => {
- expect(ForwardableEvents).toHaveLength(55)
+ expect(ForwardableEvents).toHaveLength(56)
})
it('includes the bridge approval events (web-shell pairing)', () => {
diff --git a/src/shared/protocol/forwardable-events.ts b/src/shared/protocol/forwardable-events.ts
index b5f24669..369c34a7 100644
--- a/src/shared/protocol/forwardable-events.ts
+++ b/src/shared/protocol/forwardable-events.ts
@@ -44,6 +44,7 @@ export const ForwardableEvents = [
Events.ReducedMotionChanged,
Events.LiquidGlassChanged,
Events.ByteUnitSystemChanged,
+ Events.DirectoryPreferencesChanged,
Events.PluginConfigChanged,
Events.PluginGrantsChanged,
Events.PluginEvicted,
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index cc088cab..51ab8abb 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -5,6 +5,9 @@ export const Queries = {
GetStats: 'query:getStats',
GetTaskSpeedHistory: 'query:getTaskSpeedHistory',
GetTaskInspectorActivity: 'query:getTaskInspectorActivity',
+ GetGeneralSettingsDraft: 'query:getGeneralSettingsDraft',
+ GetDirectoryPreferences: 'query:getDirectoryPreferences',
+ ListServerDirectoryLocations: 'query:listServerDirectoryLocations',
GetSettings: 'query:getSettings',
GetUpdateState: 'query:getUpdateState',
GetSystemProxy: 'query:getSystemProxy',
@@ -55,6 +58,8 @@ export const Queries = {
GetTaskBtTracker: 'query:getTaskBtTracker',
// Save directory allowlist (web degradation, electron returns unrestricted)
ListAllowedSaveDirs: 'query:listAllowedSaveDirs',
+ ListServerDirectories: 'query:listServerDirectories',
+ ValidateServerDirectory: 'query:validateServerDirectory',
// GeoIP
GetGeoIPStatus: 'query:getGeoIPStatus',
// FFmpeg detection
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index 284b249d..bbc9ff78 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -6,6 +6,7 @@ import {
byteUnitSystemSchema,
DEFAULT_BYTE_UNIT_PREFERENCE,
} from './byte-unit-system'
+import { DirectoryPreferencesSchema } from './directory-preferences'
import { supportedLocaleSchema } from './locale'
import { settingsInputObject } from './settings-input'
@@ -30,6 +31,10 @@ export const appSettingsSchema = z.object({
// absolute platform download directory on first load. The renderer never
// observes '' because settings are loaded before the UI mounts.
defaultSaveDir: z.string().catch(''),
+ directoryPreferences: DirectoryPreferencesSchema.catch({
+ favorites: [],
+ recent: [],
+ }),
notifyOnComplete: z.boolean().catch(true),
notifyOnError: z.boolean().catch(true),
autofillClipboardLinks: z.boolean().catch(true),
diff --git a/src/shared/schemas/directory-preferences.test.ts b/src/shared/schemas/directory-preferences.test.ts
new file mode 100644
index 00000000..063a71f5
--- /dev/null
+++ b/src/shared/schemas/directory-preferences.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest'
+import {
+ DirectoryPreferencesResultSchema,
+ DirectoryPreferencesSchema,
+ GetDirectoryPreferencesRequestSchema,
+ MutateDirectoryPreferencesRequestSchema,
+} from './directory-preferences'
+import {
+ ListServerDirectoryLocationsRequestSchema,
+ ListServerDirectoryLocationsResultSchema,
+} from './server-directory'
+
+describe('directory preference contracts', () => {
+ it.each([
+ {},
+ { action: 'addFavorite', path: '' },
+ { action: 'addFavorite', path: '/ok', extra: true },
+ { action: 'clearRecent', paths: ['/x'] },
+ { action: 'removeFavorite', paths: [] },
+ { action: 'removeRecent', paths: Array(11).fill('/x') },
+ { action: 'removeFavorite', paths: Array(21).fill('/x') },
+ ])('rejects malformed mutations %j', (request) => {
+ expect(
+ MutateDirectoryPreferencesRequestSchema.safeParse(request).success
+ ).toBe(false)
+ })
+ it('bounds persisted records and preserves literal whitespace', () => {
+ expect(
+ DirectoryPreferencesSchema.parse({ favorites: ['/ '], recent: [] })
+ .favorites
+ ).toEqual(['/ '])
+ expect(
+ DirectoryPreferencesSchema.safeParse({
+ favorites: Array(21).fill('/x'),
+ recent: [],
+ }).success
+ ).toBe(false)
+ expect(
+ DirectoryPreferencesSchema.safeParse({
+ favorites: [],
+ recent: Array(11).fill('/x'),
+ }).success
+ ).toBe(false)
+ })
+ it('uses strict empty query requests and sanitized results', () => {
+ for (const schema of [
+ GetDirectoryPreferencesRequestSchema,
+ ListServerDirectoryLocationsRequestSchema,
+ ]) {
+ expect(schema.safeParse({}).success).toBe(true)
+ expect(schema.safeParse({ path: '/secret' }).success).toBe(false)
+ expect(schema.safeParse(undefined).success).toBe(false)
+ }
+ for (const schema of [
+ DirectoryPreferencesResultSchema,
+ ListServerDirectoryLocationsResultSchema,
+ ]) {
+ expect(
+ schema.safeParse({
+ ok: false,
+ error: { code: 'unavailable', message: '/secret' },
+ }).success
+ ).toBe(false)
+ }
+ })
+})
diff --git a/src/shared/schemas/directory-preferences.ts b/src/shared/schemas/directory-preferences.ts
new file mode 100644
index 00000000..5ba10054
--- /dev/null
+++ b/src/shared/schemas/directory-preferences.ts
@@ -0,0 +1,63 @@
+import { z } from 'zod'
+
+export const DIRECTORY_FAVORITES_LIMIT = 20
+export const DIRECTORY_RECENT_LIMIT = 10
+export const DIRECTORY_PREFERENCES_PATH_LIMIT = 4096
+
+const savedPath = z.string().min(1).max(DIRECTORY_PREFERENCES_PATH_LIMIT)
+export const DirectoryPreferencesSchema = z
+ .object({
+ favorites: z.array(savedPath).max(DIRECTORY_FAVORITES_LIMIT),
+ recent: z.array(savedPath).max(DIRECTORY_RECENT_LIMIT),
+ })
+ .strict()
+export const DirectoryPreferencesErrorCodeSchema = z.enum([
+ 'invalidPath',
+ 'outsideRoots',
+ 'notFound',
+ 'notDirectory',
+ 'permissionDenied',
+ 'tooLarge',
+ 'unavailable',
+ 'limitReached',
+])
+export const DirectoryPreferencesResultSchema = z.discriminatedUnion('ok', [
+ z.object({ ok: z.literal(true), value: DirectoryPreferencesSchema }).strict(),
+ z
+ .object({
+ ok: z.literal(false),
+ error: z.object({ code: DirectoryPreferencesErrorCodeSchema }).strict(),
+ })
+ .strict(),
+])
+export const GetDirectoryPreferencesRequestSchema = z.object({}).strict()
+export const MutateDirectoryPreferencesRequestSchema = z.discriminatedUnion(
+ 'action',
+ [
+ z.object({ action: z.literal('addFavorite'), path: savedPath }).strict(),
+ z.object({ action: z.literal('recordRecent'), path: savedPath }).strict(),
+ z
+ .object({
+ action: z.literal('removeFavorite'),
+ paths: z.array(savedPath).min(1).max(DIRECTORY_FAVORITES_LIMIT),
+ })
+ .strict(),
+ z
+ .object({
+ action: z.literal('removeRecent'),
+ paths: z.array(savedPath).min(1).max(DIRECTORY_RECENT_LIMIT),
+ })
+ .strict(),
+ z.object({ action: z.literal('clearRecent') }).strict(),
+ ]
+)
+export type DirectoryPreferences = z.infer<typeof DirectoryPreferencesSchema>
+export type DirectoryPreferencesResult = z.infer<
+ typeof DirectoryPreferencesResultSchema
+>
+export type DirectoryPreferencesErrorCode = z.infer<
+ typeof DirectoryPreferencesErrorCodeSchema
+>
+export type MutateDirectoryPreferencesRequest = z.infer<
+ typeof MutateDirectoryPreferencesRequestSchema
+>
diff --git a/src/shared/schemas/general-settings.test.ts b/src/shared/schemas/general-settings.test.ts
new file mode 100644
index 00000000..e8948750
--- /dev/null
+++ b/src/shared/schemas/general-settings.test.ts
@@ -0,0 +1,66 @@
+import { TEST_GENERAL_REVISION } from '@test-utils/general-settings'
+import { describe, expect, it } from 'vitest'
+import { SaveGeneralSettingsRequestSchema } from './general-settings'
+
+const directories = { addFavorites: [], removeFavorites: [], removeRecent: [] }
+
+describe('SaveGeneralSettingsRequestSchema', () => {
+ it('accepts dirty General fields and exact literal directory deltas', () => {
+ const request = {
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: { defaultSaveDir: '/saved ', notifyOnError: false },
+ directories: {
+ ...directories,
+ addFavorites: ['/favorite '],
+ removeRecent: ['/old '],
+ },
+ }
+ expect(SaveGeneralSettingsRequestSchema.parse(request)).toEqual(request)
+ expect(
+ SaveGeneralSettingsRequestSchema.parse({
+ expectedRevision: TEST_GENERAL_REVISION,
+ app: {},
+ directories,
+ })
+ ).toEqual({ expectedRevision: TEST_GENERAL_REVISION, app: {}, directories })
+ })
+
+ it.each([
+ {},
+ { expectedRevision: undefined, app: {}, directories },
+ { expectedRevision: 'not-a-revision', app: {}, directories },
+ { app: {}, directories, extra: true },
+ { app: { theme: 'dark' }, directories },
+ {
+ app: { directoryPreferences: { favorites: [], recent: [] } },
+ directories,
+ },
+ { app: { notifyOnError: 'false' }, directories },
+ { app: { notifyOnError: undefined }, directories },
+ { app: { defaultSaveDir: '' }, directories },
+ { app: {}, directories: { ...directories, clearRecent: true } },
+ {
+ app: {},
+ directories: { ...directories, addFavorites: Array(21).fill('/a') },
+ },
+ {
+ app: {},
+ directories: { ...directories, removeFavorites: Array(21).fill('/a') },
+ },
+ {
+ app: {},
+ directories: { ...directories, removeRecent: Array(11).fill('/a') },
+ },
+ {
+ app: {},
+ directories: { ...directories, addFavorites: ['a'.repeat(4097)] },
+ },
+ ])('rejects malformed or excessive request %j', (request) => {
+ expect(
+ SaveGeneralSettingsRequestSchema.safeParse({
+ expectedRevision: TEST_GENERAL_REVISION,
+ ...request,
+ }).success
+ ).toBe(false)
+ })
+})
diff --git a/src/shared/schemas/general-settings.ts b/src/shared/schemas/general-settings.ts
new file mode 100644
index 00000000..9b7f324a
--- /dev/null
+++ b/src/shared/schemas/general-settings.ts
@@ -0,0 +1,76 @@
+import { z } from 'zod'
+import {
+ DIRECTORY_FAVORITES_LIMIT,
+ DIRECTORY_PREFERENCES_PATH_LIMIT,
+ DIRECTORY_RECENT_LIMIT,
+ DirectoryPreferencesErrorCodeSchema,
+ DirectoryPreferencesSchema,
+} from './directory-preferences'
+
+const directoryPath = z.string().min(1).max(DIRECTORY_PREFERENCES_PATH_LIMIT)
+
+export const GeneralSettingsAppSchema = z.object({
+ launchAtStartup: z.boolean(),
+ showMainWindowAtLogin: z.boolean(),
+ defaultSaveDir: z.string(),
+ notifyOnComplete: z.boolean(),
+ notifyOnError: z.boolean(),
+ autofillClipboardLinks: z.boolean(),
+ warnBeforeQuit: z.boolean(),
+})
+export const GeneralSettingsSnapshotSchema = z
+ .object({
+ revision: z.string().uuid(),
+ app: GeneralSettingsAppSchema,
+ directoryPreferences: DirectoryPreferencesSchema,
+ })
+ .strict()
+export const GeneralSettingsErrorCodeSchema = z.enum([
+ ...DirectoryPreferencesErrorCodeSchema.options,
+ 'conflict',
+])
+export const GeneralSettingsResultSchema = z.discriminatedUnion('ok', [
+ z
+ .object({ ok: z.literal(true), value: GeneralSettingsSnapshotSchema })
+ .strict(),
+ z
+ .object({
+ ok: z.literal(false),
+ error: z.object({ code: GeneralSettingsErrorCodeSchema }).strict(),
+ // Conflicts expose current authority; effect failures expose the committed
+ // snapshot so a caller never mistakes a saved value for its old baseline.
+ snapshot: GeneralSettingsSnapshotSchema.optional(),
+ })
+ .strict(),
+])
+export const GetGeneralSettingsDraftRequestSchema = z.object({}).strict()
+export const SaveGeneralSettingsRequestSchema = z
+ .object({
+ expectedRevision: z.string().uuid(),
+ app: GeneralSettingsAppSchema.partial()
+ .extend({ defaultSaveDir: directoryPath.optional() })
+ .strict()
+ .refine((patch) =>
+ Object.values(patch).every((value) => value !== undefined)
+ ),
+ directories: z
+ .object({
+ addFavorites: z.array(directoryPath).max(DIRECTORY_FAVORITES_LIMIT),
+ removeFavorites: z.array(directoryPath).max(DIRECTORY_FAVORITES_LIMIT),
+ removeRecent: z.array(directoryPath).max(DIRECTORY_RECENT_LIMIT),
+ })
+ .strict(),
+ })
+ .strict()
+
+export type GeneralSettingsApp = z.infer<typeof GeneralSettingsAppSchema>
+export type GeneralSettingsSnapshot = z.infer<
+ typeof GeneralSettingsSnapshotSchema
+>
+export type GeneralSettingsResult = z.infer<typeof GeneralSettingsResultSchema>
+export type GeneralSettingsErrorCode = z.infer<
+ typeof GeneralSettingsErrorCodeSchema
+>
+export type SaveGeneralSettingsRequest = z.infer<
+ typeof SaveGeneralSettingsRequestSchema
+>
diff --git a/src/shared/schemas/server-directory.test.ts b/src/shared/schemas/server-directory.test.ts
new file mode 100644
index 00000000..9617d29f
--- /dev/null
+++ b/src/shared/schemas/server-directory.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from 'vitest'
+import {
+ AllowedSaveDirsSchema,
+ CreateServerDirectoryRequestSchema,
+ CreateServerDirectoryResultSchema,
+ ListServerDirectoriesRequestSchema,
+ ListServerDirectoriesResultSchema,
+ ServerDirectoryLocationsSchema,
+ ValidateServerDirectoryRequestSchema,
+} from './server-directory'
+
+describe('server directory contracts', () => {
+ const listing = {
+ ok: true,
+ value: {
+ path: '/',
+ parentPath: null,
+ breadcrumbs: [{ name: '/', path: '/' }],
+ entries: [{ name: 'folder', path: '/folder' }],
+ truncated: false,
+ canCreate: true,
+ },
+ }
+ it.each([undefined, 0, -1000, 1700000000123.5])(
+ 'accepts optional finite listing timestamps: %s',
+ (modifiedAt) => {
+ const result = {
+ ...listing,
+ value: {
+ ...listing.value,
+ entries: [
+ {
+ ...listing.value.entries[0],
+ ...(modifiedAt === undefined ? {} : { modifiedAt }),
+ },
+ ],
+ },
+ }
+ expect(ListServerDirectoriesResultSchema.parse(result)).toEqual(result)
+ }
+ )
+ it.each([Number.NaN, Infinity, -Infinity, null, '1000'])(
+ 'rejects invalid listing timestamps: %s',
+ (modifiedAt) => {
+ expect(
+ ListServerDirectoriesResultSchema.safeParse({
+ ...listing,
+ value: {
+ ...listing.value,
+ entries: [{ ...listing.value.entries[0], modifiedAt }],
+ },
+ }).success
+ ).toBe(false)
+ }
+ )
+ it('keeps timestamps out of breadcrumbs, create results and saved locations', () => {
+ const entry = { name: 'folder', path: '/folder', modifiedAt: 1000 }
+ expect(
+ ListServerDirectoriesResultSchema.safeParse({
+ ...listing,
+ value: { ...listing.value, breadcrumbs: [entry] },
+ }).success
+ ).toBe(false)
+ expect(
+ CreateServerDirectoryResultSchema.safeParse({ ok: true, value: entry })
+ .success
+ ).toBe(false)
+ expect(
+ ServerDirectoryLocationsSchema.safeParse({
+ common: [],
+ favorites: [{ ...entry, sourcePaths: ['/folder'] }],
+ recent: [],
+ }).success
+ ).toBe(false)
+ expect(
+ ServerDirectoryLocationsSchema.safeParse({
+ common: [{ kind: 'default', path: '/folder', modifiedAt: 1000 }],
+ favorites: [],
+ recent: [],
+ }).success
+ ).toBe(false)
+ })
+ it.each([
+ undefined,
+ {},
+ { path: '' },
+ { path: '/a', extra: true },
+ { path: 'x'.repeat(4097) },
+ { path: '/a', showHidden: 'yes' },
+ ])('rejects malformed list request %j', (request) => {
+ expect(ListServerDirectoriesRequestSchema.safeParse(request).success).toBe(
+ false
+ )
+ })
+ it('preserves literal whitespace without allowing unbounded or unknown fields', () => {
+ expect(
+ CreateServerDirectoryRequestSchema.parse({ parentPath: '/a ', name: ' ' })
+ ).toEqual({ parentPath: '/a ', name: ' ' })
+ expect(
+ CreateServerDirectoryRequestSchema.safeParse({
+ parentPath: '/a',
+ name: 'x'.repeat(256),
+ }).success
+ ).toBe(false)
+ expect(
+ ValidateServerDirectoryRequestSchema.safeParse({
+ path: '/a',
+ extra: true,
+ }).success
+ ).toBe(false)
+ })
+ it('parses only bounded result envelopes without raw error details', () => {
+ expect(
+ CreateServerDirectoryResultSchema.parse({
+ ok: false,
+ error: { code: 'creationOutcomeUnknown' },
+ })
+ ).toEqual({ ok: false, error: { code: 'creationOutcomeUnknown' } })
+ expect(
+ CreateServerDirectoryResultSchema.safeParse({
+ ok: false,
+ error: { code: 'unavailable', message: '/private/secret' },
+ }).success
+ ).toBe(false)
+ expect(
+ ListServerDirectoriesResultSchema.safeParse({
+ ok: true,
+ value: {
+ path: '/',
+ parentPath: null,
+ breadcrumbs: [{ name: '/', path: '/' }],
+ entries: Array.from({ length: 2001 }, () => ({
+ name: 'a',
+ path: '/a',
+ })),
+ truncated: true,
+ canCreate: false,
+ },
+ }).success
+ ).toBe(false)
+ expect(
+ AllowedSaveDirsSchema.parse({
+ paths: [{ path: '/a' }],
+ defaultPath: '/a ',
+ allowCustom: false,
+ }).defaultPath
+ ).toBe('/a ')
+ })
+})
diff --git a/src/shared/schemas/server-directory.ts b/src/shared/schemas/server-directory.ts
new file mode 100644
index 00000000..b4bef41e
--- /dev/null
+++ b/src/shared/schemas/server-directory.ts
@@ -0,0 +1,165 @@
+import { z } from 'zod'
+import {
+ DIRECTORY_FAVORITES_LIMIT,
+ DIRECTORY_RECENT_LIMIT,
+} from './directory-preferences'
+
+export const SERVER_DIRECTORY_PATH_LIMIT = 4096
+export const SERVER_DIRECTORY_NAME_LIMIT = 255
+export const SERVER_DIRECTORY_SCAN_LIMIT = 10000
+export const SERVER_DIRECTORY_ENTRY_LIMIT = 2000
+
+export const DirectoryErrorCodeSchema = z.enum([
+ 'invalidPath',
+ 'outsideRoots',
+ 'notFound',
+ 'notDirectory',
+ 'permissionDenied',
+ 'alreadyExists',
+ 'invalidName',
+ 'tooLarge',
+ 'unavailable',
+ 'creationOutcomeUnknown',
+])
+export type DirectoryErrorCode = z.infer<typeof DirectoryErrorCodeSchema>
+
+const DirectoryPathSchema = z.string().min(1).max(SERVER_DIRECTORY_PATH_LIMIT)
+const DirectoryEntrySchema = z
+ .object({
+ name: z.string().min(1).max(SERVER_DIRECTORY_PATH_LIMIT),
+ path: DirectoryPathSchema,
+ })
+ .strict()
+const ListedDirectoryEntrySchema = DirectoryEntrySchema.extend({
+ modifiedAt: z.number().finite().optional(),
+}).strict()
+const DirectoryFailureSchema = z
+ .object({
+ ok: z.literal(false),
+ error: z.object({ code: DirectoryErrorCodeSchema }).strict(),
+ })
+ .strict()
+
+export const ListServerDirectoriesRequestSchema = z
+ .object({ path: DirectoryPathSchema, showHidden: z.boolean().optional() })
+ .strict()
+export const ListServerDirectoriesResultSchema = z.discriminatedUnion('ok', [
+ z
+ .object({
+ ok: z.literal(true),
+ value: z
+ .object({
+ path: DirectoryPathSchema,
+ parentPath: DirectoryPathSchema.nullable(),
+ breadcrumbs: z
+ .array(DirectoryEntrySchema)
+ .min(1)
+ .max(SERVER_DIRECTORY_PATH_LIMIT),
+ entries: z
+ .array(ListedDirectoryEntrySchema)
+ .max(SERVER_DIRECTORY_ENTRY_LIMIT),
+ truncated: z.boolean(),
+ canCreate: z.boolean(),
+ })
+ .strict(),
+ })
+ .strict(),
+ DirectoryFailureSchema,
+])
+export const ValidateServerDirectoryRequestSchema = z
+ .object({ path: DirectoryPathSchema })
+ .strict()
+export const ValidateServerDirectoryResultSchema = z.discriminatedUnion('ok', [
+ z
+ .object({
+ ok: z.literal(true),
+ value: z.object({ path: DirectoryPathSchema }).strict(),
+ })
+ .strict(),
+ DirectoryFailureSchema,
+])
+export const CreateServerDirectoryRequestSchema = z
+ .object({
+ parentPath: DirectoryPathSchema,
+ name: z.string().min(1).max(SERVER_DIRECTORY_NAME_LIMIT),
+ })
+ .strict()
+export const CreateServerDirectoryResultSchema = z.discriminatedUnion('ok', [
+ z.object({ ok: z.literal(true), value: DirectoryEntrySchema }).strict(),
+ DirectoryFailureSchema,
+])
+export const AllowedSaveDirsSchema = z
+ .object({
+ paths: z.array(z.object({ path: DirectoryPathSchema }).strict()),
+ defaultPath: z.string().max(SERVER_DIRECTORY_PATH_LIMIT),
+ allowCustom: z.boolean(),
+ })
+ .strict()
+
+export type ListServerDirectoriesRequest = z.infer<
+ typeof ListServerDirectoriesRequestSchema
+>
+export type ListServerDirectoriesResult = z.infer<
+ typeof ListServerDirectoriesResultSchema
+>
+export type ValidateServerDirectoryRequest = z.infer<
+ typeof ValidateServerDirectoryRequestSchema
+>
+export type ValidateServerDirectoryResult = z.infer<
+ typeof ValidateServerDirectoryResultSchema
+>
+export type CreateServerDirectoryRequest = z.infer<
+ typeof CreateServerDirectoryRequestSchema
+>
+export type CreateServerDirectoryResult = z.infer<
+ typeof CreateServerDirectoryResultSchema
+>
+export type AllowedSaveDirs = z.infer<typeof AllowedSaveDirsSchema>
+
+const SavedDirectoryLocationSchema = DirectoryEntrySchema.extend({
+ sourcePaths: z
+ .array(DirectoryPathSchema)
+ .min(1)
+ .max(DIRECTORY_FAVORITES_LIMIT),
+}).strict()
+export const ServerDirectoryLocationsSchema = z
+ .object({
+ common: z
+ .array(
+ z
+ .object({
+ kind: z.enum([
+ 'default',
+ 'home',
+ 'desktop',
+ 'documents',
+ 'downloads',
+ 'root',
+ ]),
+ path: DirectoryPathSchema,
+ })
+ .strict()
+ )
+ .max(6),
+ favorites: z
+ .array(SavedDirectoryLocationSchema)
+ .max(DIRECTORY_FAVORITES_LIMIT),
+ recent: z.array(SavedDirectoryLocationSchema).max(DIRECTORY_RECENT_LIMIT),
+ })
+ .strict()
+export const ListServerDirectoryLocationsRequestSchema = z.object({}).strict()
+export const ListServerDirectoryLocationsResultSchema = z.discriminatedUnion(
+ 'ok',
+ [
+ z
+ .object({ ok: z.literal(true), value: ServerDirectoryLocationsSchema })
+ .strict(),
+ DirectoryFailureSchema,
+ ]
+)
+export type ServerDirectoryLocations = z.infer<
+ typeof ServerDirectoryLocationsSchema
+>
+export type ListServerDirectoryLocationsResult = z.infer<
+ typeof ListServerDirectoryLocationsResultSchema
+>
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index 1b00205b..c2f4767a 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -3,6 +3,7 @@ import type { RunMode } from '../constants'
import type { EnginePerformanceProfile } from '../constants/engine-performance-profiles'
import type { SupportedLocale } from '../constants/locales'
import type { BridgeSettings } from '../schemas/bridge-settings'
+import type { DirectoryPreferences } from '../schemas/directory-preferences'
import type { GeoIPSettings } from './geoip'
import type { PluginSettings } from './plugin'
import type { TrackerSource } from './tracker'
@@ -220,6 +221,7 @@ export interface MotrixAppSettings {
reduceMotion: boolean
byteUnitSystem: ByteUnitPreference
language: SupportedLocale
+ directoryPreferences: DirectoryPreferences
defaultSaveDir: string
notifyOnComplete: boolean
notifyOnError: boolean
diff --git a/src/test-utils/general-settings.ts b/src/test-utils/general-settings.ts
new file mode 100644
index 00000000..1998b726
--- /dev/null
+++ b/src/test-utils/general-settings.ts
@@ -0,0 +1,24 @@
+import { DEFAULT_APP_SETTINGS } from '@shared/schemas/app-settings'
+import type { DirectoryPreferences } from '@shared/schemas/directory-preferences'
+import {
+ type GeneralSettingsApp,
+ GeneralSettingsAppSchema,
+ type GeneralSettingsSnapshot,
+} from '@shared/schemas/general-settings'
+
+export const TEST_GENERAL_REVISION = '00000000-0000-4000-8000-000000000001'
+export function generalSettingsSnapshot(
+ directoryPreferences: DirectoryPreferences = { favorites: [], recent: [] },
+ app: Partial<GeneralSettingsApp> = {},
+ revision = TEST_GENERAL_REVISION
+): GeneralSettingsSnapshot {
+ return {
+ revision,
+ app: GeneralSettingsAppSchema.parse({
+ ...DEFAULT_APP_SETTINGS,
+ defaultSaveDir: '/downloads',
+ ...app,
+ }),
+ directoryPreferences,
+ }
+}