Skip to content

A full-featured download manager.

feat(server): add logo menu and configurable torrent limits (#2146)

Dr_rOot259d6785f546
diff --git a/compose.named-volumes.yaml b/compose.named-volumes.yaml
index 420e50c1..8a924036 100644
--- a/compose.named-volumes.yaml
+++ b/compose.named-volumes.yaml
@@ -19,6 +19,7 @@ services:
MOTRIX_DEFAULT_SAVE_DIR: /downloads
MOTRIX_ALLOWED_SAVE_DIRS: /downloads
MOTRIX_ARIA2_RPC_LISTEN_ALL: "${MOTRIX_ARIA2_RPC_LISTEN_ALL:-false}"
+ MOTRIX_TORRENT_BODY_LIMIT_MIB: "${MOTRIX_TORRENT_BODY_LIMIT_MIB:-8}"
MOTRIX_MDXP_HOST: 0.0.0.0
MOTRIX_MDXP_PORT: 16801
MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-}"
diff --git a/compose.yaml b/compose.yaml
index 9d58329f..13e1c69d 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -19,6 +19,7 @@ services:
MOTRIX_DEFAULT_SAVE_DIR: /downloads
MOTRIX_ALLOWED_SAVE_DIRS: /downloads
MOTRIX_ARIA2_RPC_LISTEN_ALL: "${MOTRIX_ARIA2_RPC_LISTEN_ALL:-false}"
+ MOTRIX_TORRENT_BODY_LIMIT_MIB: "${MOTRIX_TORRENT_BODY_LIMIT_MIB:-8}"
MOTRIX_MDXP_HOST: 0.0.0.0
MOTRIX_MDXP_PORT: 16801
MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-}"
diff --git a/docs/docker-server.md b/docs/docker-server.md
index 899a8c9e..8317a300 100644
--- a/docs/docker-server.md
+++ b/docs/docker-server.md
@@ -199,6 +199,38 @@ engine. It is also not TLS-protected, so never publish it directly to the
public Internet. Prefer a private Docker network, host loopback, VPN, or
another authenticated encrypted tunnel.
+### Torrent upload size
+
+Torrent creation requests accept **8 MiB** by default. Set
+`MOTRIX_TORRENT_BODY_LIMIT_MIB` to an integer from **2 to 64** and restart the
+server when larger metainfo files are needed. For example, with either supplied
+Compose file:
+
+```bash
+export MOTRIX_TORRENT_BODY_LIMIT_MIB=16
+docker compose -f compose.yaml up -d --wait
+```
+
+This counts the complete UTF-8 JSON request, including Base64 and options;
+an 8 MiB request holds slightly less than 6 MiB of original `.torrent` bytes.
+The larger budget applies only to torrent payloads sent to
+`/rpc/command/command:createTask` and `/rpc/command/command:addTorrentTask`.
+Other RPC requests retain their 2 MiB limit. Oversized requests return HTTP 413.
+At most two large or unknown-length torrent requests are admitted concurrently;
+additional requests return HTTP 429. Request reception has a 120-second timeout.
+
+Motrix starts its managed aria2 with the same `--rpc-max-request-size` budget.
+An independently managed engine or reverse proxy needs a matching limit; for
+Nginx, set [`client_max_body_size 16m;`](https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size)
+in the `server` or `location` block serving the Web API when using the example
+above. MDXP and plugin package upload limits are independent of this setting.
+
+These are product resource limits, not torrent format requirements:
+[BEP 3](https://www.bittorrent.org/beps/bep_0003.html) and
+[BEP 52](https://www.bittorrent.org/beps/bep_0052.html) do not specify a universal
+metainfo file size ceiling. The existing parser still caps Base64 at 50 MiB
+(37.5 MiB of original bytes), even with the 64 MiB request setting.
+
### Reverse proxy on the Docker host
The included [`compose.reverse-proxy.env`](../compose.reverse-proxy.env) binds
@@ -394,6 +426,36 @@ not publish MDXP, and forwarding only 16801 does not serve the approval UI.
These protections must not be implemented by disabling pairing; remote
CLI/agent and browser-Extension pairing remain operator-approved workflows.
+## Logo menu in the Web UI
+
+Open the **Motrix** logo at the upper left for About, Settings, Task, Help,
+and **Sign out**. Narrow screens show one menu level at a time; use **Back**,
+Left Arrow, or Escape to return to the parent level.
+
+- **New Task** opens links; **New BitTorrent Task** opens the torrent form.
+ **Open Torrent File** reads `.torrent` files from the device running your
+ browser, supports multiple files, and lets you review each before submitting.
+ The download destination is a path on the Server. See [torrent upload
+ size](#torrent-upload-size) for the configurable request limit.
+- Pause, resume, remove, and queue commands apply to the committed selection
+ in the current filtered downloads list. **Select all tasks** includes rows
+ outside the visible viewport. Changing the selection or filter cancels a
+ pending selection command.
+- **Pause All** and **Resume All** affect the whole instance. **Clear stopped
+ task records** confirms the current completed, error, and removed records
+ and keeps downloaded files. Newly stopped tasks are left for a later clear.
+- Closing an edited task form asks before discarding the draft. A submission
+ in progress keeps its form open. Temporary disconnections preserve drafts
+ and disable remote task commands until a fresh connection and snapshot return.
+- **Sign out** is shown for browser cookie sessions. Confirmation ends that
+ session in all tabs sharing its cookie and clears their private UI state.
+ Server downloads continue; independent browser sessions and Bearer clients
+ stay connected. Network failures alone do not sign you out.
+
+Browser shortcuts such as Ctrl/Cmd+N, L, O, and B keep their browser behavior.
+Task selection and removal shortcuts operate only within the focused downloads
+list, and text inputs retain their editing shortcuts.
+
## Download paths and plugins
The image defaults are:
@@ -564,6 +626,7 @@ uses this ownership record and the already-bound Web listener as one proof.
| `MOTRIX_OPERATOR_TOKEN` | generated file | Operator control-plane credential |
| `MOTRIX_SECRETS_SEED` | generated lockbox | 64-hex-character plugin secret key |
| `MOTRIX_ARIA2_RPC_LISTEN_ALL` | `false` | Opt in to an authenticated all-interface aria2 RPC listener; Docker port publication is still separate |
+| `MOTRIX_TORRENT_BODY_LIMIT_MIB` | `8` | Torrent JSON request limit in MiB; integer 2–64, also applied to managed aria2 RPC; restart required |
| `MOTRIX_WEB_BIND_IP` | Compose: `0.0.0.0` | Host address publishing Web port 8080; falls back through `MOTRIX_BIND_IP` |
| `MOTRIX_MDXP_BIND_IP` | Compose: `0.0.0.0` | Host address publishing MDXP port 16801; falls back through `MOTRIX_BIND_IP` |
| `MOTRIX_BIND_IP` | Compose: `0.0.0.0` | Backward-compatible shared host-publish fallback |
diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.md
index 21de3044..f2f28624 100644
--- a/docs/docker-server.zh-CN.md
+++ b/docs/docker-server.zh-CN.md
@@ -181,6 +181,36 @@ docker compose -f compose.yaml -f compose.aria2-rpc.yaml up -d --wait
切勿直接发布到公网;优先使用私有 Docker network、宿主 loopback、VPN 或其他带
鉴权的加密 tunnel。
+### 种子上传大小
+
+种子创建请求默认允许 **8 MiB**。需要上传更大的种子元数据时,可将
+`MOTRIX_TORRENT_BODY_LIMIT_MIB` 设为 **2 到 64** 之间的整数,然后重启服务。
+仓库提供的两份 Compose 文件都支持此参数,例如:
+
+```bash
+export MOTRIX_TORRENT_BODY_LIMIT_MIB=16
+docker compose -f compose.yaml up -d --wait
+```
+
+此限制计算完整 UTF-8 JSON 请求的大小,包含 Base64 和选项;8 MiB 请求能容纳的原始
+`.torrent` 文件略小于 6 MiB。放宽后的限制仅适用于
+`/rpc/command/command:createTask` 和 `/rpc/command/command:addTorrentTask`
+中的种子载荷,其他 RPC 请求仍限 2 MiB。超限请求返回 HTTP 413。
+服务最多同时接收两个大请求或长度未知的种子请求,额外请求返回 HTTP 429。
+请求接收超时为 120 秒。
+
+Motrix 启动受管 aria2 时会设置相同的 `--rpc-max-request-size` 上限。
+独立管理的引擎或反向代理也需要配置匹配的限制;使用上面的配置时,在 Nginx 代理 Web API 的
+`server` 或 `location` 块中设置
+[`client_max_body_size 16m;`](https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size)。
+MDXP 与插件包上传限制不受此参数影响。
+
+这些数值是产品的资源限制,不是种子格式要求:
+[BEP 3](https://www.bittorrent.org/beps/bep_0003.html) 和
+[BEP 52](https://www.bittorrent.org/beps/bep_0052.html) 没有规定统一的种子元数据文件
+大小上限。即使请求上限设为 64 MiB,现有解析器仍将 Base64 限制在 50 MiB
+(对应 37.5 MiB 原始文件)。
+
### 运行在 Docker 宿主上的反向代理
仓库提供的 [`compose.reverse-proxy.env`](../compose.reverse-proxy.env) 会把两个已发布的
@@ -348,6 +378,28 @@ origin,并保留 cookie、Authorization header 和流式响应。MDXP 是独
MDXP,只转发 16801 也不会提供审批界面。不应通过禁用配对来实现这些保护;远程
CLI/agent 与浏览器扩展配对都仍然需要 operator 审批。
+## Web 界面的 Logo 菜单
+
+点击左上角的 **Motrix** Logo,可打开关于、设置、任务、帮助和**退出登录**。
+窄屏一次显示一级菜单;点击**返回**、按左方向键或 Escape 可返回上一级。
+
+- **新建任务**打开链接表单,**新建 BT 任务**打开种子表单。
+ **打开种子文件**读取浏览器所在设备上的 `.torrent` 文件,支持多选,
+ 提交前可逐个检查。下载保存路径属于 Server。请求体大小可配置,
+ 详见本文的种子上传大小说明。
+- 暂停、继续、移除和队列调整作用于当前筛选列表中已确认的选择。
+ **全选任务**包含视口外的行;选择或筛选变化会取消尚未执行的选择操作。
+- **全部暂停**和**全部继续**作用于整个实例。**清理已停止任务记录**会确认
+ 当前已完成、出错和已移除的记录,并保留下载文件。随后才停止的任务留待下次清理。
+- 关闭已编辑的任务表单前会确认是否丢弃草稿;提交过程中表单保持打开。
+ 暂时断线会保留草稿,远程任务操作在连接恢复并取得新快照后重新可用。
+- 浏览器使用 Cookie 会话时显示**退出登录**。确认后,共享该 Cookie 的标签页
+ 会一起退出并清除私有界面状态。Server 上的下载继续运行,独立浏览器会话和
+ Bearer 客户端不受影响。单纯的网络故障不会导致退出登录。
+
+Ctrl/Cmd+N、L、O、B 等浏览器快捷键保持原有用途。任务全选和移除快捷键
+仅在下载列表获得焦点时生效,文本输入框保留正常的编辑快捷键。
+
## 下载路径与插件
镜像默认值如下:
@@ -503,6 +555,7 @@ bridge lock 的恢复会把该 ownership 记录与已绑定的 Web listener 共
| `MOTRIX_OPERATOR_TOKEN` | 自动生成文件 | operator 控制面凭据 |
| `MOTRIX_SECRETS_SEED` | 自动生成 lockbox | 64 位十六进制插件 secret 密钥 |
| `MOTRIX_ARIA2_RPC_LISTEN_ALL` | `false` | 显式开启带鉴权、面向所有接口的 aria2 RPC listener;Docker 端口发布仍需单独配置 |
+| `MOTRIX_TORRENT_BODY_LIMIT_MIB` | `8` | 种子 JSON 请求上限,单位 MiB,取值为 2–64 的整数;同步用于受管 aria2 RPC,重启后生效 |
| `MOTRIX_WEB_BIND_IP` | Compose:`0.0.0.0` | 发布 Web 8080 端口的宿主地址;通过 `MOTRIX_BIND_IP` fallback |
| `MOTRIX_MDXP_BIND_IP` | Compose:`0.0.0.0` | 发布 MDXP 16801 端口的宿主地址;通过 `MOTRIX_BIND_IP` fallback |
| `MOTRIX_BIND_IP` | Compose:`0.0.0.0` | 向后兼容的共享宿主发布 fallback |
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.ts
index 390e8f64..3e7fdc20 100644
--- a/src/core/engine/aria2/aria2-config-builder.test.ts
+++ b/src/core/engine/aria2/aria2-config-builder.test.ts
@@ -257,6 +257,29 @@ describe('Aria2ConfigBuilder', () => {
})
describe('buildArgs', () => {
+ it.each([8, 64])(
+ 'uses the configured server RPC budget of %s MiB',
+ (mib) => {
+ builder = new Aria2ConfigBuilder(
+ '/app/extra/aria2.conf',
+ '/home/user/.config/motrix',
+ {
+ rpcMaxRequestSizeBytes: mib * 1024 * 1024,
+ }
+ )
+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, false, null, {
+ download: 0,
+ upload: 0,
+ })
+ const requestLimitIndex = args.indexOf(`--rpc-max-request-size=${mib}M`)
+ expect(requestLimitIndex).toBeGreaterThan(
+ args.findIndex((arg) => arg.startsWith('--conf-path='))
+ )
+ expect(requestLimitIndex).toBeGreaterThan(
+ args.findIndex((arg) => arg.startsWith('--max-concurrent-downloads='))
+ )
+ }
+ )
it('builds args array with default settings', () => {
const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {
download: 0,
diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.ts
index 4a23a34e..4c0a0e49 100644
--- a/src/core/engine/aria2/aria2-config-builder.ts
+++ b/src/core/engine/aria2/aria2-config-builder.ts
@@ -6,12 +6,15 @@ import {
stripAria2ProxyCredentials,
} from '@core/proxy/aria2-proxy-routing'
import type { Aria2ProxyOptions } from '@core/proxy/serializers'
+import { torrentRpcBodyLimitSchema } from '@shared/schemas/torrent-request-limits'
import type { EngineSettings } from '@shared/types/settings'
import writeFileAtomic from 'write-file-atomic'
import { dnsModeToAsyncDns } from './dns-fallback'
export interface Aria2ConfigBuilderOptions {
rpcListenAll?: boolean
+ /** Server HTTP and engine RPC must use the same torrent upload budget. */
+ rpcMaxRequestSizeBytes?: number
}
export class Aria2ConfigBuilder {
@@ -21,6 +24,7 @@ export class Aria2ConfigBuilder {
private readonly dhtFilePath: string
private readonly dht6FilePath: string
private readonly rpcListenAll: boolean
+ private readonly rpcMaxRequestSizeBytes?: number
private configuredInputFile = false
private runtimeConfPath: string
@@ -36,6 +40,10 @@ export class Aria2ConfigBuilder {
this.dhtFilePath = path.join(userConfigDir, 'dht.dat')
this.dht6FilePath = path.join(userConfigDir, 'dht6.dat')
this.rpcListenAll = options.rpcListenAll ?? false
+ this.rpcMaxRequestSizeBytes =
+ options.rpcMaxRequestSizeBytes === undefined
+ ? undefined
+ : torrentRpcBodyLimitSchema.parse(options.rpcMaxRequestSizeBytes)
}
async ensureUserConfig(): Promise<string> {
@@ -263,6 +271,11 @@ export class Aria2ConfigBuilder {
)
// ── L1 product-contract invariants — DO NOT REMOVE without spec change ──
+ if (this.rpcMaxRequestSizeBytes !== undefined) {
+ args.push(
+ `--rpc-max-request-size=${this.rpcMaxRequestSizeBytes / (1024 * 1024)}M`
+ )
+ }
args.push(
'--bt-save-metadata=true',
'--bt-metadata-only=false',
diff --git a/src/core/task/actions/clear-stopped-tasks.test.ts b/src/core/task/actions/clear-stopped-tasks.test.ts
index 594a9e45..f586c983 100644
--- a/src/core/task/actions/clear-stopped-tasks.test.ts
+++ b/src/core/task/actions/clear-stopped-tasks.test.ts
@@ -96,6 +96,23 @@ function createDeps(initial: readonly DownloadTask[]) {
}
describe('clearStoppedTasks', () => {
+ it('clears only frozen candidate IDs, preserving newly stopped tasks and files', async () => {
+ const { deps, tasks } = createDeps([
+ task('first', TaskStatus.Completed),
+ task('later', TaskStatus.Completed),
+ task('finalizing', TaskStatus.Finalizing),
+ ])
+ expect(await clearStoppedTasks(deps, ['first', 'finalizing'])).toEqual({
+ succeeded: ['first'],
+ failed: [],
+ })
+ expect([...tasks.keys()]).toEqual(['later', 'finalizing'])
+ expect(deps.adapter.removeDownloadResults).toHaveBeenCalledWith([
+ 'gid-first',
+ ])
+ expect(deps.db.deleteTasks).toHaveBeenCalledWith(['first'])
+ })
+
it('deletes Completed, Error, and Removed while retaining active tasks', async () => {
const { deps, tasks } = createDeps([
task('active', TaskStatus.Downloading),
diff --git a/src/core/task/actions/clear-stopped-tasks.ts b/src/core/task/actions/clear-stopped-tasks.ts
index 27adcbb3..bb2e034d 100644
--- a/src/core/task/actions/clear-stopped-tasks.ts
+++ b/src/core/task/actions/clear-stopped-tasks.ts
@@ -54,9 +54,17 @@ function snapshotCandidates(tasks: readonly DownloadTask[]): Candidate[] {
}
export async function clearStoppedTasks(
- deps: ClearStoppedTasksDeps
-): Promise<void> {
- const candidates = snapshotCandidates(deps.taskManager.getAll())
+ deps: ClearStoppedTasksDeps,
+ taskIds?: readonly string[]
+): Promise<{
+ succeeded: string[]
+ failed: { taskId: string; reason: string }[]
+}> {
+ const allowed = taskIds ? new Set(taskIds) : null
+ const candidates = snapshotCandidates(
+ deps.taskManager.getAll().filter((task) => !allowed || allowed.has(task.id))
+ )
+ const succeeded: string[] = []
const cleaned: Candidate[] = []
// One engine round-trip for every gid of every candidate, flattened in
@@ -141,6 +149,7 @@ export async function clearStoppedTasks(
} else {
deleteParents()
}
+ succeeded.push(...ids)
deps.publishTaskUpdateNow()
return ids.length
})
@@ -153,4 +162,14 @@ export async function clearStoppedTasks(
{ candidateCount: candidates.length, count },
'clearStoppedTasks removed terminal tasks'
)
+ const removed = new Set(succeeded)
+ return {
+ succeeded,
+ failed: candidates
+ .filter((c) => !removed.has(c.id))
+ .map((c) => ({
+ taskId: c.id,
+ reason: 'Task changed or engine cleanup failed',
+ })),
+ }
}
diff --git a/src/main/commands/context-schema.ts b/src/main/commands/context-schema.ts
index 0c2d9168..fd9254c6 100644
--- a/src/main/commands/context-schema.ts
+++ b/src/main/commands/context-schema.ts
@@ -2,6 +2,12 @@ import { TaskStatus } from '@shared/types/task'
import { z } from 'zod'
export const MenuContextPatchSchema = z.object({
+ selectedTaskIds: z.array(z.string().min(1)).optional(),
+ selectedTaskGeneration: z.number().int().nonnegative().optional(),
+ selectedCanPause: z.boolean().optional(),
+ selectedCanResume: z.boolean().optional(),
+ selectedCanRemove: z.boolean().optional(),
+ selectedCanMove: z.boolean().optional(),
selectedTaskId: z.string().nullable().optional(),
selectedTaskStatus: z.enum(TaskStatus).nullable().optional(),
selectedTaskAtTop: z.boolean().optional(),
diff --git a/src/main/commands/definitions/task.commands.test.ts b/src/main/commands/definitions/task.commands.test.ts
index eea7ad76..57633e93 100644
--- a/src/main/commands/definitions/task.commands.test.ts
+++ b/src/main/commands/definitions/task.commands.test.ts
@@ -48,43 +48,44 @@ describe('task commands', () => {
expect(send).toHaveBeenCalledTimes(2)
})
- it('wires Clear Stopped to the shared persistence coordinator', async () => {
+ it('requests a renderer confirmation before clearing records', async () => {
const registry = new CommandRegistry()
- const taskManager = { marker: 'task-manager' }
- const adapter = { marker: 'adapter' }
- const motrixDatabase = { marker: 'database' }
- const taskPersistence = {
- runExclusivePersistence: vi.fn(),
- }
- const eventBus = { marker: 'event-bus' }
- const log = {
- error: vi.fn(),
- info: vi.fn(),
- warn: vi.fn(),
- }
+ const send = vi.fn()
const deps = {
- taskManager,
- adapter,
- motrixDatabase,
- taskPersistence,
- eventBus,
- log,
+ windowManager: { get: vi.fn(() => ({ webContents: { send } })) },
} as unknown as CommandDeps
registerTaskCommands(registry, deps)
-
await registry.execute(CommandIds.TaskClearStopped, undefined, {
menuContext: { ...DEFAULT_MENU_CONTEXT, hasStoppedTasks: true },
deps,
})
-
- expect(actionMocks.clearStoppedTasks).toHaveBeenCalledOnce()
- expect(actionMocks.clearStoppedTasks).toHaveBeenCalledWith({
- taskManager,
- adapter,
- db: motrixDatabase,
- taskPersistence,
- eventBus,
- log,
+ expect(send).toHaveBeenCalledWith(Events.RendererTaskMenuRequested, {
+ commandId: CommandIds.TaskClearStopped,
+ taskIds: [],
+ generation: 0,
+ })
+ expect(actionMocks.clearStoppedTasks).not.toHaveBeenCalled()
+ })
+ it('sends the committed multi-selection without removing tasks in the main menu callback', async () => {
+ const registry = new CommandRegistry()
+ const send = vi.fn()
+ const deps = {
+ windowManager: { get: vi.fn(() => ({ webContents: { send } })) },
+ } as unknown as CommandDeps
+ registerTaskCommands(registry, deps)
+ await registry.execute(CommandIds.TaskDelete, undefined, {
+ menuContext: {
+ ...DEFAULT_MENU_CONTEXT,
+ selectedTaskIds: ['one', 'two'],
+ selectedTaskGeneration: 7,
+ selectedCanRemove: true,
+ },
+ deps,
+ })
+ expect(send).toHaveBeenCalledWith(Events.RendererTaskMenuRequested, {
+ commandId: CommandIds.TaskDelete,
+ taskIds: ['one', 'two'],
+ generation: 7,
})
})
})
diff --git a/src/main/commands/definitions/task.commands.ts b/src/main/commands/definitions/task.commands.ts
index 5c3de979..c4200112 100644
--- a/src/main/commands/definitions/task.commands.ts
+++ b/src/main/commands/definitions/task.commands.ts
@@ -1,18 +1,9 @@
-import {
- clearStoppedTasks,
- moveTask,
- pauseAllTasks,
- pauseTask,
- removeTask,
- resumeAllTasks,
- resumeTask,
-} from '@core/task/actions'
+import { pauseAllTasks, resumeAllTasks } from '@core/task/actions'
import { CommandIds } from '@shared/commands-catalog'
import { Events } from '@shared/protocol/events'
-import { TaskStatus } from '@shared/types/task'
import type { CommandRegistry } from '../command-registry'
import type { CommandDeps } from '../types'
-import { and, ctxEq, ctxIn, ctxTrue, not } from '../when'
+import { ctxTrue } from '../when'
export function registerTaskCommands(
registry: CommandRegistry,
@@ -49,82 +40,29 @@ export function registerTaskCommands(
},
})
- registry.register({
- id: CommandIds.TaskPause,
- title: 'menu.task.pauseTask',
- precondition: and(
- ctxTrue('taskSelected'),
- ctxIn('selectedTaskStatus', [
- TaskStatus.Downloading,
- TaskStatus.FetchingMetadata,
- ])
- ),
- run: async ({ deps, menuContext }) => {
- const id = menuContext.selectedTaskId
- if (!id) return
- await pauseTask(id, deps)
- },
- })
-
- registry.register({
- id: CommandIds.TaskResume,
- title: 'menu.task.resumeTask',
- precondition: and(
- ctxTrue('taskSelected'),
- ctxEq('selectedTaskStatus', TaskStatus.Paused)
- ),
- run: async ({ deps, menuContext }) => {
- const id = menuContext.selectedTaskId
- if (!id) return
- await resumeTask(id, deps)
- },
- })
-
- registry.register({
- id: CommandIds.TaskDelete,
- title: 'menu.task.deleteTask',
- precondition: ctxTrue('taskSelected'),
- run: async ({ deps, menuContext }) => {
- const id = menuContext.selectedTaskId
- if (!id) return
- // Menu/palette delete defaults to keeping files on disk; the
- // renderer-side delete dialog (Task 19) will surface the
- // `deleteWithFiles=true` path when the user explicitly opts in.
- await removeTask(
- id,
- { deleteWithFiles: false },
- { ...deps, db: deps.motrixDatabase }
- )
- },
- })
-
- registry.register({
- id: CommandIds.TaskMoveUp,
- title: 'menu.task.moveTaskUp',
- precondition: and(
- ctxTrue('taskSelected'),
- not(ctxTrue('selectedTaskAtTop'))
- ),
- run: async ({ deps, menuContext }) => {
- const id = menuContext.selectedTaskId
- if (!id) return
- await moveTask(id, 'up', deps)
- },
- })
-
- registry.register({
- id: CommandIds.TaskMoveDown,
- title: 'menu.task.moveTaskDown',
- precondition: and(
- ctxTrue('taskSelected'),
- not(ctxTrue('selectedTaskAtBottom'))
- ),
- run: async ({ deps, menuContext }) => {
- const id = menuContext.selectedTaskId
- if (!id) return
- await moveTask(id, 'down', deps)
- },
- })
+ const selectionCommands = [
+ [CommandIds.TaskPause, 'menu.task.pauseTask', 'selectedCanPause'],
+ [CommandIds.TaskResume, 'menu.task.resumeTask', 'selectedCanResume'],
+ [CommandIds.TaskDelete, 'menu.task.deleteTask', 'selectedCanRemove'],
+ [CommandIds.TaskMoveUp, 'menu.task.moveTaskUp', 'selectedCanMove'],
+ [CommandIds.TaskMoveDown, 'menu.task.moveTaskDown', 'selectedCanMove'],
+ ] as const
+ for (const [id, title, predicate] of selectionCommands) {
+ registry.register({
+ id,
+ title,
+ precondition: (context) => context[predicate] === true,
+ run: ({ deps, menuContext }) => {
+ deps.windowManager
+ .get('main')
+ ?.webContents.send(Events.RendererTaskMenuRequested, {
+ commandId: id,
+ taskIds: menuContext.selectedTaskIds ?? [],
+ generation: menuContext.selectedTaskGeneration ?? 0,
+ })
+ },
+ })
+ }
registry.register({
id: CommandIds.TaskPauseAll,
@@ -158,18 +96,14 @@ export function registerTaskCommands(
id: CommandIds.TaskClearStopped,
title: 'menu.task.clearRecentTasks',
precondition: ctxTrue('hasStoppedTasks'),
- run: async ({ deps }) => {
- await clearStoppedTasks({
- taskManager: deps.taskManager,
- adapter: deps.adapter,
- db: deps.motrixDatabase,
- taskPersistence: deps.taskPersistence,
- eventBus: deps.eventBus,
- log: deps.log,
- deleteParentTasks: deps.deleteParentTasks,
- runTaskMutation: deps.runTaskMutation,
- publishTaskUpdateNow: deps.publishTaskUpdateNow,
- })
+ run: ({ deps, menuContext }) => {
+ deps.windowManager
+ .get('main')
+ ?.webContents.send(Events.RendererTaskMenuRequested, {
+ commandId: CommandIds.TaskClearStopped,
+ taskIds: [],
+ generation: menuContext.selectedTaskGeneration ?? 0,
+ })
},
})
}
diff --git a/src/main/commands/menu-context.ts b/src/main/commands/menu-context.ts
index d419a196..376b3d32 100644
--- a/src/main/commands/menu-context.ts
+++ b/src/main/commands/menu-context.ts
@@ -4,6 +4,12 @@ import type { MenuContext } from '@shared/types/menu-context'
export const DEFAULT_MENU_CONTEXT: MenuContext = {
platform: process.platform as MenuContext['platform'],
locale: DEFAULT_LOCALE,
+ selectedTaskIds: [],
+ selectedTaskGeneration: 0,
+ selectedCanPause: false,
+ selectedCanResume: false,
+ selectedCanRemove: false,
+ selectedCanMove: false,
selectedTaskId: null,
selectedTaskStatus: null,
selectedTaskAtTop: false,
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 2a46b82e..b0b14e0f 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -42,9 +42,12 @@ import type { MotrixDatabase } from '@core/session/motrix-database'
import type { SessionManager } from '@core/session/session-manager'
import type { SettingsManager } from '@core/settings/settings-manager'
import {
+ clearStoppedTasks,
+ pauseAllTasks,
pauseTask,
reAddTask,
removeTask,
+ resumeAllTasks,
resumeTask,
runBulkTaskAction,
stopSeedingTask,
@@ -674,6 +677,13 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
[Commands.MoveTasks]: async (rawPayload: unknown) =>
moveTasks(moveTasksPayloadSchema.parse(rawPayload), pauseResumeDeps),
+ [Commands.PauseAllTasks]: async () =>
+ toBulkTaskCommandResult(await pauseAllTasks(pauseResumeDeps)),
+ [Commands.ResumeAllTasks]: async () =>
+ toBulkTaskCommandResult(await resumeAllTasks(pauseResumeDeps)),
+ [Commands.ClearStoppedTasks]: async (rawPayload: unknown) =>
+ clearStoppedTasks(removeDeps, taskIdsPayloadSchema.parse(rawPayload)),
+
[Commands.PauseTasks]: async (rawPayload: unknown) => {
const taskIds = taskIdsPayloadSchema.parse(rawPayload)
return toBulkTaskCommandResult(
diff --git a/src/main/menu/contributions/shared.ts b/src/main/menu/contributions/shared.ts
index 76ff291b..42c55c16 100644
--- a/src/main/menu/contributions/shared.ts
+++ b/src/main/menu/contributions/shared.ts
@@ -1,118 +1,23 @@
-import { CommandIds } from '@shared/commands-catalog'
+import { PRODUCT_MENU_ITEMS } from '@shared/application-menu-catalog'
import { MenuIds, MenuItemIds } from '../menu-ids'
import type { MenuRegistry } from '../menu-registry'
export function contributeSharedMenubar(menuReg: MenuRegistry): void {
- // Task menu
- menuReg.appendItem({
- id: MenuItemIds.TaskNew,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '1_new',
- order: 10,
- commandId: CommandIds.TaskNew,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskNewBt,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '1_new',
- order: 20,
- commandId: CommandIds.TaskNewBt,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskOpenFile,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '1_new',
- order: 30,
- commandId: CommandIds.TaskOpenFile,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskList,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '2_primary',
- order: 10,
- commandId: CommandIds.NavigateTaskList,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskPause,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '2_primary',
- order: 20,
- commandId: CommandIds.TaskPause,
- contextBinding: 'selectedTask',
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskResume,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '2_primary',
- order: 30,
- commandId: CommandIds.TaskResume,
- contextBinding: 'selectedTask',
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskDelete,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '2_primary',
- order: 40,
- commandId: CommandIds.TaskDelete,
- contextBinding: 'selectedTask',
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskMoveUp,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '2_primary',
- order: 50,
- commandId: CommandIds.TaskMoveUp,
- contextBinding: 'selectedTask',
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskMoveDown,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '2_primary',
- order: 60,
- commandId: CommandIds.TaskMoveDown,
- contextBinding: 'selectedTask',
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskPauseAll,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '3_bulk',
- order: 10,
- commandId: CommandIds.TaskPauseAll,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskResumeAll,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '3_bulk',
- order: 20,
- commandId: CommandIds.TaskResumeAll,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskSelectAll,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '3_bulk',
- order: 30,
- commandId: CommandIds.TaskSelectAll,
- })
- menuReg.appendItem({
- id: MenuItemIds.TaskClearStopped,
- type: 'normal',
- menuId: MenuIds.MenubarTask,
- group: '4_clear',
- order: 10,
- commandId: CommandIds.TaskClearStopped,
- })
+ for (const item of PRODUCT_MENU_ITEMS) {
+ if (item.section === 'app') continue
+ menuReg.appendItem({
+ id: item.id,
+ type: 'normal',
+ menuId:
+ item.section === 'task' ? MenuIds.MenubarTask : MenuIds.MenubarHelp,
+ group: item.group,
+ order: item.order,
+ commandId: item.commandId,
+ ...(item.scope === 'selection'
+ ? { contextBinding: 'selectedTask' as const }
+ : {}),
+ })
+ }
// Edit menu (all roles)
menuReg.appendItem({
@@ -217,39 +122,6 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
visible: false,
})
- // Help menu
- menuReg.appendItem({
- id: MenuItemIds.HelpWebsite,
- type: 'normal',
- menuId: MenuIds.MenubarHelp,
- group: '1_links',
- order: 10,
- commandId: CommandIds.HelpOpenWebsite,
- })
- menuReg.appendItem({
- id: MenuItemIds.HelpManual,
- type: 'normal',
- menuId: MenuIds.MenubarHelp,
- group: '1_links',
- order: 20,
- commandId: CommandIds.HelpOpenManual,
- })
- menuReg.appendItem({
- id: MenuItemIds.HelpChangelog,
- type: 'normal',
- menuId: MenuIds.MenubarHelp,
- group: '1_links',
- order: 30,
- commandId: CommandIds.HelpOpenChangelog,
- })
- menuReg.appendItem({
- id: MenuItemIds.HelpReportProblem,
- type: 'normal',
- menuId: MenuIds.MenubarHelp,
- group: '2_report',
- order: 10,
- commandId: CommandIds.HelpReportProblem,
- })
menuReg.appendItem({
id: MenuItemIds.HelpToggleDevTools,
type: 'normal',
diff --git a/src/main/menu/menu-manager.ts b/src/main/menu/menu-manager.ts
index 3d1c3db5..4329c7c8 100644
--- a/src/main/menu/menu-manager.ts
+++ b/src/main/menu/menu-manager.ts
@@ -193,7 +193,10 @@ export class MenuManager {
}
if (
definition.contextBinding === 'selectedTask' &&
- request.selectedTaskId !== this.deps.contextStore.get().selectedTaskId
+ (request.selectedTaskId !== this.deps.contextStore.get().selectedTaskId ||
+ (request.selectedTaskGeneration !== undefined &&
+ request.selectedTaskGeneration !==
+ this.deps.contextStore.get().selectedTaskGeneration))
) {
throw new Error('Application menu command context is stale')
}
diff --git a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
index 90b7cf5d..78508d58 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.test.tsx
@@ -37,12 +37,14 @@ vi.mock('@renderer/components/add-task/add-task-form', () => ({
onAdvancedOpenChange: _onAdvancedOpenChange,
presentation,
defaultValues,
+ onDraftStateChange,
}: {
onSubmitSuccess?: (gid: string) => void
onCancel: () => void
onAdvancedOpenChange?: (expanded: boolean) => void
presentation?: 'dialog' | 'window'
defaultValues?: Partial<AddTaskFormValues>
+ onDraftStateChange?: (dirty: boolean, busy: boolean) => void
}) => {
// Like react-hook-form, defaults are read on mount, not on every render.
const [initialValues] = useState(defaultValues)
@@ -55,6 +57,12 @@ vi.mock('@renderer/components/add-task/add-task-form', () => ({
<button type="button" onClick={() => onSubmitSuccess?.('gid-1')}>
stub-submit
</button>
+ <button type="button" onClick={() => onDraftStateChange?.(true, false)}>
+ stub-edit
+ </button>
+ <button type="button" onClick={() => onDraftStateChange?.(true, true)}>
+ stub-busy
+ </button>
<button type="button" onClick={onCancel}>
stub-cancel
</button>
@@ -83,6 +91,30 @@ function renderWithRouter() {
}
describe('AddTaskDialogHost', () => {
+ it('preserves edited drafts until discard is confirmed', () => {
+ useAddTaskDialogStore.getState().openWith({ tab: 'links' })
+ renderWithRouter()
+ fireEvent.click(screen.getByText('stub-edit'))
+ fireEvent.click(screen.getByText('stub-cancel'))
+ expect(useAddTaskDialogStore.getState().open).toBe(true)
+ expect(
+ screen.getByRole('dialog', { name: 'Discard this task draft?' })
+ ).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Discard' }))
+ expect(useAddTaskDialogStore.getState().open).toBe(false)
+ })
+ it('keeps an in-flight form open and rejects replacement requests', () => {
+ useAddTaskDialogStore.getState().openWith({ tab: 'links', urls: 'draft' })
+ renderWithRouter()
+ fireEvent.click(screen.getByText('stub-busy'))
+ fireEvent.click(screen.getByText('stub-cancel'))
+ act(() => useAddTaskDialogStore.getState().openWith({ tab: 'torrent' }))
+ expect(useAddTaskDialogStore.getState().prefill?.tab).toBe('links')
+ expect(useAddTaskDialogStore.getState().open).toBe(true)
+ expect(
+ screen.queryByRole('dialog', { name: 'Discard this task draft?' })
+ ).toBeNull()
+ })
it('closes only the matching picker when the background service accepts it', () => {
useAddTaskDialogStore
.getState()
@@ -100,7 +132,7 @@ describe('AddTaskDialogHost', () => {
expect(useAddTaskDialogStore.getState().open).toBe(false)
})
- it('hydrates a replacement form while the dialog is already open', () => {
+ it('preserves the current draft when another open request arrives', () => {
useAddTaskDialogStore
.getState()
.openWith({ tab: 'links', urls: 'https://example.com/a' })
@@ -110,8 +142,10 @@ describe('AddTaskDialogHost', () => {
.getState()
.openWith({ tab: 'torrent', existingTaskId: 'ready-2' })
})
- expect(screen.getByTestId('initial-values')).toHaveTextContent('ready-2')
expect(screen.getByTestId('initial-values')).not.toHaveTextContent(
+ 'ready-2'
+ )
+ expect(screen.getByTestId('initial-values')).toHaveTextContent(
'https://example.com/a'
)
})
@@ -120,6 +154,7 @@ describe('AddTaskDialogHost', () => {
useAddTaskDialogStore.getState().openWith({ tab: 'links' })
renderWithRouter()
const oldSubmission = submitSuccessRef.current
+ act(() => useAddTaskDialogStore.getState().close())
act(() => {
useAddTaskDialogStore
.getState()
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 a083f91c..6c3cff25 100644
--- a/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
+++ b/src/renderer/components/add-task-dialog/add-task-dialog-host.tsx
@@ -9,6 +9,7 @@ import {
} 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 { showMagnetFileSelection } from '@renderer/lib/open-magnet-file-selection'
import { transport } from '@renderer/lib/transport'
import { PlatformServicesProvider } from '@renderer/platform/services'
@@ -41,9 +42,27 @@ export function AddTaskDialogHost() {
const { t } = useTranslation()
const open = useAddTaskDialogStore((s) => s.open)
const revision = useAddTaskDialogStore((s) => s.revision)
+ const torrentFiles = useAddTaskDialogStore((s) => s.torrentFiles)
+ const [draft, setDraft] = useState({ dirty: false, busy: false })
+ const [discard, setDiscard] = useState(false)
+ const onDraftStateChange = useCallback(
+ (dirty: boolean, busy: boolean) => setDraft({ dirty, busy }),
+ []
+ )
const prefill = useAddTaskDialogStore((s) => s.prefill)
const openWith = useAddTaskDialogStore((s) => s.openWith)
const close = useAddTaskDialogStore((s) => s.close)
+ const requestClose = useCallback(() => {
+ if (draft.busy) return
+ if (draft.dirty) setDiscard(true)
+ else close()
+ }, [draft, close])
+ useEffect(() => {
+ if (!open) {
+ setDraft({ dirty: false, busy: false })
+ setDiscard(false)
+ }
+ }, [open])
const navigate = useNavigate()
const dialogRef = useRef<HTMLDivElement>(null)
const {
@@ -85,9 +104,9 @@ export function AddTaskDialogHost() {
// Register the web close handler so webServices.closeHost() works.
useEffect(() => {
- __setWebCloseHandler(() => useAddTaskDialogStore.getState().close())
+ __setWebCloseHandler(requestClose)
return () => __setWebCloseHandler(null)
- }, [])
+ }, [requestClose])
// Global event subscription — even when Dialog is closed.
useEffect(() => {
@@ -142,7 +161,7 @@ export function AddTaskDialogHost() {
return (
<>
- <Dialog open={open} onOpenChange={(v) => !v && close()}>
+ <Dialog open={open} onOpenChange={(v) => !v && requestClose()}>
<DialogContent
ref={dialogRef}
showCloseButton={false}
@@ -162,14 +181,17 @@ export function AddTaskDialogHost() {
<AddTaskForm
key={revision}
defaultValues={prefill}
+ initialTorrentFiles={torrentFiles}
+ onDraftStateChange={onDraftStateChange}
onSubmitSuccess={onSubmitSuccess}
- onCancel={close}
+ onCancel={requestClose}
onAdvancedOpenChange={onAdvancedOpenChange}
presentation="dialog"
subscribeEvents={false}
/>
</PlatformServicesProvider>
<DialogClose
+ disabled={draft.busy}
aria-label={t('chrome.close')}
className="app-no-drag absolute top-3.5 right-3.5 flex size-7 shrink-0 items-center justify-center rounded-md border-0 bg-transparent text-foreground outline-none transition-colors [&>svg]:opacity-65 hover:bg-accent hover:text-accent-foreground hover:[&>svg]:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:[&>svg]:opacity-90 dark:hover:bg-accent/50"
>
@@ -177,6 +199,20 @@ export function AddTaskDialogHost() {
</DialogClose>
</DialogContent>
</Dialog>
+ <MenuConfirmation
+ request={
+ discard
+ ? {
+ kind: 'discard',
+ run: async () => {
+ setDiscard(false)
+ close()
+ },
+ }
+ : null
+ }
+ close={() => setDiscard(false)}
+ />
<WebPathPickerDialog />
</>
)
diff --git a/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts b/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts
index f5500109..d16f1542 100644
--- a/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts
+++ b/src/renderer/components/add-task-dialog/use-add-task-dialog-store.ts
@@ -1,3 +1,5 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
+import type { ParsedTorrentFile } from '@renderer/lib/parse-torrent-file'
import type { AddTaskFormValues } from '@shared/schemas/add-task'
import { create } from 'zustand'
@@ -8,8 +10,12 @@ type DeepPartial<T> = {
interface AddTaskDialogState {
open: boolean
revision: number
+ torrentFiles?: ParsedTorrentFile[]
prefill: DeepPartial<AddTaskFormValues> | undefined
- openWith: (prefill?: DeepPartial<AddTaskFormValues>) => void
+ openWith: (
+ prefill?: DeepPartial<AddTaskFormValues>,
+ torrentFiles?: ParsedTorrentFile[]
+ ) => void
close: () => void
}
@@ -17,12 +23,19 @@ export const useAddTaskDialogStore = create<AddTaskDialogState>((set) => ({
open: false,
revision: 0,
prefill: undefined,
- openWith: (prefill) =>
- set((state) => ({ open: true, prefill, revision: state.revision + 1 })),
+ openWith: (prefill, torrentFiles) =>
+ set((state) =>
+ state.open
+ ? state
+ : { open: true, prefill, torrentFiles, revision: state.revision + 1 }
+ ),
close: () =>
set((state) => ({
open: false,
prefill: undefined,
+ torrentFiles: undefined,
revision: state.revision + 1,
})),
}))
+
+onOperatorSessionLost(() => useAddTaskDialogStore.getState().close())
diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsx
index 23caa2d3..785542c6 100644
--- a/src/renderer/components/add-task/add-task-form.tsx
+++ b/src/renderer/components/add-task/add-task-form.tsx
@@ -54,6 +54,8 @@ import {
} from './use-external-hydration'
interface AddTaskFormProps {
+ initialTorrentFiles?: ParsedTorrentFile[]
+ onDraftStateChange?: (dirty: boolean, busy: boolean) => void
defaultValues?: DeepPartial<AddTaskFormValues>
onSubmitSuccess?: (taskId: string) => void
onCancel: () => void
@@ -84,6 +86,8 @@ function taskCreateFailureReason(error: unknown): string | null {
export function AddTaskForm({
defaultValues,
+ initialTorrentFiles,
+ onDraftStateChange,
onSubmitSuccess,
onCancel,
onAdvancedOpenChange,
@@ -111,6 +115,14 @@ export function AddTaskForm({
defaultValues: { ...BASE_DEFAULTS, ...defaultValues } as AddTaskFormValues,
})
+ const dirty = form.formState.isDirty
+ useEffect(() => {
+ onDraftStateChange?.(
+ dirty,
+ submitting || batchSubmitting || advancingTorrent
+ )
+ }, [dirty, submitting, batchSubmitting, advancingTorrent, onDraftStateChange])
+
const openHydrationRequest = useRef(0)
// Refresh open-scoped settings for each actual open. The desktop add-task
@@ -217,6 +229,12 @@ export function AddTaskForm({
[]
)
+ useEffect(() => {
+ if (!initialTorrentFiles?.length) return
+ hydrateLocalTorrent(initialTorrentFiles[0])
+ handleLocalTorrentFilesLoaded(initialTorrentFiles)
+ }, [initialTorrentFiles, hydrateLocalTorrent, handleLocalTorrentFilesLoaded])
+
useExternalHydration(
form,
subscribeEvents,
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
index c60794c4..8e350eef 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
@@ -38,6 +38,7 @@ export function PanelShell({
<div className="relative flex h-full flex-col">
{/* PanelShell header */}
<header
+ data-slot="panel-shell-header"
className={cn(
// Standard headers retain the 36px clearance below window controls.
// A 36px action row and 8px bottom padding make an 80px header.
diff --git a/src/renderer/components/operator-unlock-gate.test.tsx b/src/renderer/components/operator-unlock-gate.test.tsx
index befa71a2..5a9f7e93 100644
--- a/src/renderer/components/operator-unlock-gate.test.tsx
+++ b/src/renderer/components/operator-unlock-gate.test.tsx
@@ -1,62 +1,78 @@
import '@renderer/lib/i18n'
-import { fireEvent, render, screen } from '@testing-library/react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { useOperatorSession } from '@renderer/lib/operator-auth'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { OperatorUnlockGate } from './operator-unlock-gate'
-const { transportMock, statusMock, loginMock } = vi.hoisted(() => ({
- transportMock: { platform: 'web' as 'web' | 'electron' },
- statusMock: vi.fn<() => Promise<boolean>>(),
- loginMock: vi.fn<(t: string) => Promise<boolean>>(),
+const { transportMock } = vi.hoisted(() => ({
+ transportMock: { platform: 'web' as string },
}))
-
vi.mock('@renderer/lib/transport', () => ({ transport: transportMock }))
-vi.mock('@renderer/lib/operator-auth', () => ({
- getOperatorStatus: statusMock,
- operatorLogin: loginMock,
-}))
-
-import { OperatorUnlockGate } from './operator-unlock-gate'
-
+const fetchMock = vi.fn()
+const reply = (authed: boolean) =>
+ new Response(
+ JSON.stringify({
+ authed,
+ mode: authed ? 'cookie' : 'unauthenticated',
+ canLogout: authed,
+ })
+ )
const child = <div data-testid="app">APP</div>
-
-describe('OperatorUnlockGate', () => {
- beforeEach(() => {
- transportMock.platform = 'web'
- statusMock.mockReset()
- loginMock.mockReset()
+beforeEach(() => {
+ transportMock.platform = 'web'
+ useOperatorSession.setState({
+ state: 'checking',
+ status: null,
+ epoch: useOperatorSession.getState().epoch + 1,
})
-
- it('renders children directly on the desktop build (no /rpc)', () => {
- transportMock.platform = 'electron'
+ vi.stubGlobal('fetch', fetchMock)
+ fetchMock.mockReset()
+})
+afterEach(() => vi.unstubAllGlobals())
+describe('OperatorUnlockGate', () => {
+ it('bypasses HTTP authentication on desktop', () => {
+ transportMock.platform = 'darwin'
render(<OperatorUnlockGate>{child}</OperatorUnlockGate>)
expect(screen.getByTestId('app')).toBeTruthy()
- expect(statusMock).not.toHaveBeenCalled()
+ expect(fetchMock).not.toHaveBeenCalled()
})
-
- it('renders children when already authed (web)', async () => {
- statusMock.mockResolvedValue(true)
+ it('renders children for an authenticated cookie', async () => {
+ fetchMock.mockResolvedValue(reply(true))
render(<OperatorUnlockGate>{child}</OperatorUnlockGate>)
expect(await screen.findByTestId('app')).toBeTruthy()
})
-
- it('shows the unlock form when locked, then renders children after unlock', async () => {
- statusMock.mockResolvedValue(false)
- loginMock.mockResolvedValue(true)
+ it('exchanges a token and checks the resulting session', async () => {
+ fetchMock
+ .mockResolvedValueOnce(reply(false))
+ .mockResolvedValueOnce(new Response('{}'))
+ .mockResolvedValueOnce(reply(true))
render(<OperatorUnlockGate>{child}</OperatorUnlockGate>)
- const input = await screen.findByPlaceholderText('Operator token')
- fireEvent.change(input, { target: { value: 'machine-token' } })
+ fireEvent.change(await screen.findByPlaceholderText('Operator token'), {
+ target: { value: 'machine-token' },
+ })
fireEvent.click(screen.getByRole('button', { name: 'Unlock' }))
expect(await screen.findByTestId('app')).toBeTruthy()
- expect(loginMock).toHaveBeenCalledWith('machine-token')
+ expect(fetchMock.mock.calls[1][1].body).toBe(
+ JSON.stringify({ token: 'machine-token' })
+ )
})
-
- it('shows an error and stays locked when the token is rejected', async () => {
- statusMock.mockResolvedValue(false)
- loginMock.mockResolvedValue(false)
+ it('keeps rejected credentials locked', async () => {
+ fetchMock
+ .mockResolvedValueOnce(reply(false))
+ .mockResolvedValueOnce(new Response('{}', { status: 401 }))
render(<OperatorUnlockGate>{child}</OperatorUnlockGate>)
- const input = await screen.findByPlaceholderText('Operator token')
- fireEvent.change(input, { target: { value: 'bad' } })
+ fireEvent.change(await screen.findByPlaceholderText('Operator token'), {
+ target: { value: 'bad' },
+ })
fireEvent.click(screen.getByRole('button', { name: 'Unlock' }))
expect(await screen.findByText(/Invalid operator token/)).toBeTruthy()
- expect(screen.queryByTestId('app')).toBeNull()
+ })
+ it('offers retry for an unreachable server without pretending the session was revoked', async () => {
+ fetchMock
+ .mockRejectedValueOnce(new TypeError('offline'))
+ .mockResolvedValueOnce(reply(true))
+ render(<OperatorUnlockGate>{child}</OperatorUnlockGate>)
+ fireEvent.click(await screen.findByRole('button', { name: 'Retry' }))
+ await waitFor(() => expect(screen.getByTestId('app')).toBeTruthy())
})
})
diff --git a/src/renderer/components/operator-unlock-gate.tsx b/src/renderer/components/operator-unlock-gate.tsx
index 254f13b3..df5645d6 100644
--- a/src/renderer/components/operator-unlock-gate.tsx
+++ b/src/renderer/components/operator-unlock-gate.tsx
@@ -1,5 +1,10 @@
import { Button } from '@renderer/components/ui/button'
-import { getOperatorStatus, operatorLogin } from '@renderer/lib/operator-auth'
+import {
+ operatorLogin,
+ refreshOperatorSession,
+ useOperatorSession,
+ watchOperatorSession,
+} from '@renderer/lib/operator-auth'
import { transport } from '@renderer/lib/transport'
import { type FormEvent, type ReactNode, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -14,27 +19,30 @@ export function OperatorUnlockGate({ children }: { children: ReactNode }) {
return <WebGate>{children}</WebGate>
}
-type GateState = 'checking' | 'locked' | 'unlocked'
-
function WebGate({ children }: { children: ReactNode }) {
const { t } = useTranslation()
- const [state, setState] = useState<GateState>('checking')
+ const state = useOperatorSession((s) => s.state)
const [token, setToken] = useState('')
const [error, setError] = useState(false)
const [busy, setBusy] = useState(false)
useEffect(() => {
- let cancelled = false
- void getOperatorStatus().then((ok) => {
- if (!cancelled) setState(ok ? 'unlocked' : 'locked')
- })
- return () => {
- cancelled = true
- }
+ void refreshOperatorSession()
+ return watchOperatorSession()
}, [])
if (state === 'checking') return null
- if (state === 'unlocked') return <>{children}</>
+ if (state === 'unavailable')
+ return (
+ <div className="flex h-svh flex-col items-center justify-center gap-4">
+ <p>{t('applicationMenu.serverUnavailable')}</p>
+ <Button onClick={() => void refreshOperatorSession()}>
+ {t('applicationMenu.retry')}
+ </Button>
+ </div>
+ )
+ if (state === 'authenticated' || state === 'logging-out')
+ return <>{children}</>
const onSubmit = async (e: FormEvent) => {
e.preventDefault()
@@ -43,7 +51,7 @@ function WebGate({ children }: { children: ReactNode }) {
setError(false)
const ok = await operatorLogin(token.trim())
setBusy(false)
- if (ok) setState('unlocked')
+ if (ok) setToken('')
else setError(true)
}
diff --git a/src/renderer/components/ui/sidebar.tsx b/src/renderer/components/ui/sidebar.tsx
index d868c783..49f013bd 100644
--- a/src/renderer/components/ui/sidebar.tsx
+++ b/src/renderer/components/ui/sidebar.tsx
@@ -98,7 +98,19 @@ function SidebarProvider({
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
+ if (__MOTRIX_TARGET__ === 'web') return
const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.defaultPrevented ||
+ event.repeat ||
+ event.isComposing ||
+ (event.target instanceof Element &&
+ event.target.closest(
+ 'input, textarea, select, [contenteditable="true"]'
+ )) ||
+ document.querySelector('[role="dialog"], [role="menu"]')
+ )
+ return
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
diff --git a/src/renderer/components/window-chrome/motrix-logo.tsx b/src/renderer/components/window-chrome/motrix-logo.tsx
new file mode 100644
index 00000000..36159c7a
--- /dev/null
+++ b/src/renderer/components/window-chrome/motrix-logo.tsx
@@ -0,0 +1,24 @@
+import { ChevronDown } from 'lucide-react'
+
+export function MotrixLogo() {
+ return (
+ <>
+ <span
+ aria-hidden="true"
+ data-slot="motrix-menu-logo"
+ className="h-2.5 w-11 shrink-0 bg-foreground"
+ style={{
+ maskImage: 'url("./mo-logo.svg")',
+ maskPosition: 'center',
+ maskRepeat: 'no-repeat',
+ maskSize: 'contain',
+ WebkitMaskImage: 'url("./mo-logo.svg")',
+ WebkitMaskPosition: 'center',
+ WebkitMaskRepeat: 'no-repeat',
+ WebkitMaskSize: 'contain',
+ }}
+ />
+ <ChevronDown aria-hidden="true" className="size-3 shrink-0" />
+ </>
+ )
+}
diff --git a/src/renderer/components/window-chrome/motrix-menu-button.test.tsx b/src/renderer/components/window-chrome/motrix-menu-button.test.tsx
index 8b79e00e..e1034b26 100644
--- a/src/renderer/components/window-chrome/motrix-menu-button.test.tsx
+++ b/src/renderer/components/window-chrome/motrix-menu-button.test.tsx
@@ -21,6 +21,14 @@ vi.mock('@renderer/lib/transport', () => ({
},
}))
+vi.mock('@renderer/features/application-menu/task-context', () => ({
+ captureTaskMenuIntent: () => ({
+ generation: 0,
+ ids: [],
+ selection: new Set(),
+ }),
+}))
+
vi.mock('@renderer/hooks/use-application-menu', () => ({
useApplicationMenu: mocks.useApplicationMenu,
}))
@@ -241,6 +249,7 @@ describe('MotrixMenuButton', () => {
itemId: 'app.about',
revision: 7,
trigger: 'menu',
+ selectedTaskGeneration: 0,
selectedTaskId: null,
modifiers: { alt: true, control: true, meta: false, shift: true },
})
diff --git a/src/renderer/components/window-chrome/motrix-menu-button.tsx b/src/renderer/components/window-chrome/motrix-menu-button.tsx
index f9cd44b1..ff53c541 100644
--- a/src/renderer/components/window-chrome/motrix-menu-button.tsx
+++ b/src/renderer/components/window-chrome/motrix-menu-button.tsx
@@ -13,6 +13,8 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@renderer/components/ui/dropdown-menu'
+import { captureTaskMenuIntent } from '@renderer/features/application-menu/task-context'
+import { WebMenuButton } from '@renderer/features/application-menu/web-menu-button'
import { useApplicationMenu } from '@renderer/hooks/use-application-menu'
import { useSelectedTask } from '@renderer/hooks/use-selected-task'
import { transport } from '@renderer/lib/transport'
@@ -20,13 +22,16 @@ import type {
ApplicationMenuNode,
ExecuteApplicationMenuItemRequest,
} from '@shared/schemas/application-menu'
-import { ChevronDown } from 'lucide-react'
+import { ArrowLeft, ChevronRight } from 'lucide-react'
import {
type MouseEvent as ReactMouseEvent,
type ReactNode,
+ useEffect,
useRef,
+ useState,
} from 'react'
import { useTranslation } from 'react-i18next'
+import { MotrixLogo } from './motrix-logo'
type RendererMenuPlatform = 'darwin' | 'win32' | 'linux'
@@ -52,8 +57,6 @@ const ACCELERATOR_LABELS: Readonly<Record<string, string>> = {
shift: 'Shift',
}
-const MOTRIX_LOGO_MASK = 'url("./mo-logo.svg")'
-
export function formatMenuAccelerator(accelerator: string): string {
return accelerator
.split('+')
@@ -77,6 +80,7 @@ function modifiersFromEvent(
}
interface MenuTreeProps {
+ enterSubmenu?: (item: ApplicationMenuNode) => void
items: ApplicationMenuNode[]
queueExecution: (
item: ApplicationMenuNode,
@@ -122,7 +126,7 @@ function RadioItems({
)
}
-function MenuTree({ items, queueExecution }: MenuTreeProps) {
+function MenuTree({ items, queueExecution, enterSubmenu }: MenuTreeProps) {
const visibleItems = items.filter((item) => item.visible)
const rendered: ReactNode[] = []
@@ -157,6 +161,20 @@ function MenuTree({ items, queueExecution }: MenuTreeProps) {
continue
}
+ if (item.type === 'submenu' && enterSubmenu) {
+ rendered.push(
+ <DropdownMenuItem
+ key={item.id}
+ closeOnClick={false}
+ disabled={!item.enabled}
+ onClick={() => enterSubmenu(item)}
+ >
+ <ItemLabel item={item} />
+ <ChevronRight className="ms-auto size-3" />
+ </DropdownMenuItem>
+ )
+ continue
+ }
if (item.type === 'submenu') {
const hasVisibleChildren = item.children?.some((child) => child.visible)
rendered.push(
@@ -166,7 +184,10 @@ function MenuTree({ items, queueExecution }: MenuTreeProps) {
>
<ItemLabel item={item} />
</DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="app-no-drag">
+ <DropdownMenuSubContent
+ data-menu-density="compact"
+ className="application-menu app-no-drag"
+ >
<MenuTree
items={item.children ?? []}
queueExecution={queueExecution}
@@ -209,7 +230,24 @@ function MenuTree({ items, queueExecution }: MenuTreeProps) {
function ElectronMotrixMenuButton() {
const { t } = useTranslation()
const { snapshot, refresh, executeItem } = useApplicationMenu()
+ const [open, setOpen] = useState(false)
+ const [narrow, setNarrow] = useState(
+ () => window.matchMedia?.('(width < 640px)').matches ?? false
+ )
+ const [stack, setStack] = useState<ApplicationMenuNode[]>([])
+ const contentRef = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ if (!open || !narrow || !stack.length) return
+ const frame = requestAnimationFrame(() =>
+ contentRef.current
+ ?.querySelector<HTMLElement>('[role="menuitem"]')
+ ?.focus()
+ )
+ return () => cancelAnimationFrame(frame)
+ }, [open, narrow, stack])
const selectedTaskId = useSelectedTask().task?.id ?? null
+ const selectionAtOpen = useRef(captureTaskMenuIntent())
+ const actionGeneration = useRef(0)
const triggerRef = useRef<HTMLButtonElement | null>(null)
const previousFocusRef = useRef<HTMLElement | null>(null)
const focusCapturedForOpenRef = useRef(false)
@@ -218,12 +256,43 @@ function ElectronMotrixMenuButton() {
null
)
+ useEffect(() => {
+ if (!window.matchMedia) return
+ const small = window.matchMedia('(width < 640px)')
+ const mobile = window.matchMedia('(width < 768px)')
+ const cancel = () => {
+ actionGeneration.current++
+ pendingExecution.current = null
+ restoreFocusRef.current = false
+ setOpen(false)
+ setStack([])
+ setNarrow(small.matches)
+ }
+ const hide = () => {
+ if (document.visibilityState === 'hidden') cancel()
+ }
+ small.addEventListener('change', cancel)
+ mobile.addEventListener('change', cancel)
+ const blur = (event: FocusEvent) => {
+ if (event.target === window) cancel()
+ }
+ window.addEventListener('blur', blur)
+ document.addEventListener('visibilitychange', hide)
+ return () => {
+ small.removeEventListener('change', cancel)
+ mobile.removeEventListener('change', cancel)
+ window.removeEventListener('blur', blur)
+ document.removeEventListener('visibilitychange', hide)
+ }
+ }, [])
+
const queueExecution: MenuTreeProps['queueExecution'] = (item, event) => {
if (!snapshot) return
pendingExecution.current = {
itemId: item.id,
revision: snapshot.revision,
trigger: 'menu',
+ selectedTaskGeneration: selectionAtOpen.current.generation,
selectedTaskId,
modifiers: modifiersFromEvent(event),
}
@@ -236,18 +305,40 @@ function ElectronMotrixMenuButton() {
// Keep the Escape decision available until FloatingFocusManager unmounts;
// its return-focus cleanup runs after this completion callback.
if (!request) return
- const previousFocus = previousFocusRef.current
- const focusTarget = previousFocus?.isConnected
- ? previousFocus
- : triggerRef.current
- focusTarget?.focus({ preventScroll: true })
+ const current = actionGeneration.current
restoreFocusRef.current = false
- void executeItem(request)
+ requestAnimationFrame(() => {
+ if (current !== actionGeneration.current) return
+ const previousFocus = previousFocusRef.current
+ const focusTarget =
+ previousFocus?.isConnected &&
+ !previousFocus.closest('[inert], [aria-hidden="true"]')
+ ? previousFocus
+ : triggerRef.current
+ focusTarget?.focus({ preventScroll: true })
+ void executeItem(request)
+ })
}
return (
<DropdownMenu
+ open={open}
onOpenChange={(open, eventDetails) => {
+ if (
+ !open &&
+ eventDetails.reason === 'escape-key' &&
+ narrow &&
+ stack.length
+ ) {
+ eventDetails.cancel()
+ setStack((items) => items.slice(0, -1))
+ return
+ }
+ setOpen(open)
+ if (open) {
+ actionGeneration.current++
+ setStack([])
+ }
if (!open) {
restoreFocusRef.current = shouldRestoreMenuFocus(eventDetails.reason)
return
@@ -262,6 +353,7 @@ function ElectronMotrixMenuButton() {
: null
}
focusCapturedForOpenRef.current = false
+ selectionAtOpen.current = captureTaskMenuIntent()
void refresh()
}}
onOpenChangeComplete={executeAfterFocusRestore}
@@ -300,26 +392,20 @@ function ElectronMotrixMenuButton() {
/>
}
>
- <span
- aria-hidden="true"
- data-slot="motrix-menu-logo"
- className="h-2.5 w-11 shrink-0 bg-foreground"
- style={{
- maskImage: MOTRIX_LOGO_MASK,
- maskPosition: 'center',
- maskRepeat: 'no-repeat',
- maskSize: 'contain',
- WebkitMaskImage: MOTRIX_LOGO_MASK,
- WebkitMaskPosition: 'center',
- WebkitMaskRepeat: 'no-repeat',
- WebkitMaskSize: 'contain',
- }}
- />
- <ChevronDown aria-hidden="true" className="size-3 shrink-0" />
+ <MotrixLogo />
</DropdownMenuTrigger>
<DropdownMenuContent
+ ref={contentRef}
align="start"
- className="app-no-drag min-w-56"
+ onKeyDownCapture={(event) => {
+ if (narrow && stack.length && event.key === 'ArrowLeft') {
+ event.preventDefault()
+ event.stopPropagation()
+ setStack((items) => items.slice(0, -1))
+ }
+ }}
+ data-menu-density="compact"
+ className="application-menu app-no-drag"
finalFocus={() => {
if (!restoreFocusRef.current) return false
return previousFocusRef.current?.isConnected
@@ -327,8 +413,27 @@ function ElectronMotrixMenuButton() {
: true
}}
>
+ {narrow && stack.length > 0 && (
+ <>
+ <DropdownMenuItem
+ closeOnClick={false}
+ onClick={() => setStack((items) => items.slice(0, -1))}
+ >
+ <ArrowLeft className="size-3" />
+ {t('applicationMenu.back')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
<MenuTree
- items={snapshot?.items ?? []}
+ enterSubmenu={
+ narrow ? (item) => setStack((items) => [...items, item]) : undefined
+ }
+ items={
+ narrow && stack.length
+ ? (stack.at(-1)?.children ?? [])
+ : (snapshot?.items ?? [])
+ }
queueExecution={queueExecution}
/>
</DropdownMenuContent>
@@ -337,10 +442,10 @@ function ElectronMotrixMenuButton() {
}
/**
- * Platform gate deliberately lives outside the hook-owning component: web and
- * macOS use their native menus and never subscribe to the renderer menu IPC.
+ * Browser product actions and Electron native-menu IPC have separate adapters.
*/
export function MotrixMenuButton() {
+ if (__MOTRIX_TARGET__ === 'web') return <WebMenuButton />
const platform = rendererMenuPlatform()
if (!platform) return null
return <ElectronMotrixMenuButton />
diff --git a/src/renderer/components/window-chrome/window-chrome.tsx b/src/renderer/components/window-chrome/window-chrome.tsx
index f8c6c573..5c7e8cbf 100644
--- a/src/renderer/components/window-chrome/window-chrome.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.tsx
@@ -191,7 +191,7 @@ export function WindowChrome({
!previewDesktopControls &&
!windowState.fullscreen
const offsetStartActionsForDesktopMenu =
- showDesktopControls && leading != null && actionsPosition === 'start'
+ leading != null && actionsPosition === 'start'
const containerStyle: React.CSSProperties = {
height: DESKTOP_WINDOW_CHROME_HEIGHT,
diff --git a/src/renderer/features/application-menu/application-menu.css b/src/renderer/features/application-menu/application-menu.css
new file mode 100644
index 00000000..32dd3d49
--- /dev/null
+++ b/src/renderer/features/application-menu/application-menu.css
@@ -0,0 +1,20 @@
+.application-menu {
+ min-width: min(224px, calc(100vw - 16px));
+ max-width: min(320px, calc(100vw - 16px));
+ max-height: min(var(--available-height), calc(100dvh - 16px));
+ overflow-y: auto;
+ overscroll-behavior: contain;
+}
+@media (pointer: coarse) {
+ .application-menu[data-menu-density="compact"] [role^="menuitem"] {
+ min-height: 40px;
+ }
+ .window-chrome [data-slot="motrix-menu-trigger"],
+ .window-chrome [data-slot="window-chrome-actions"] button {
+ min-height: 40px;
+ min-width: 40px;
+ }
+ .window-chrome [data-slot="window-chrome-actions"] {
+ gap: 4px;
+ }
+}
diff --git a/src/renderer/features/application-menu/desktop-menu-actions.tsx b/src/renderer/features/application-menu/desktop-menu-actions.tsx
new file mode 100644
index 00000000..d3f23de9
--- /dev/null
+++ b/src/renderer/features/application-menu/desktop-menu-actions.tsx
@@ -0,0 +1,76 @@
+import { useIpcEvent } from '@renderer/hooks/use-ipc-event'
+import { getTaskListSnapshot } from '@renderer/hooks/use-task-list'
+import { transport } from '@renderer/lib/transport'
+import { type CommandId, CommandIds } from '@shared/commands-catalog'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { rendererTaskMenuRequestSchema } from '@shared/schemas/application-menu'
+import {
+ type BulkTaskCommandResult,
+ isStoppedTaskStatus,
+} from '@shared/types/task-actions'
+import { useEffect, useState } from 'react'
+import {
+ MenuConfirmation,
+ type MenuConfirmationRequest,
+} from './menu-confirmation'
+import {
+ captureTaskMenuIntent,
+ startMenuConnection,
+ type TaskMenuIntent,
+ taskWritesAvailable,
+} from './task-context'
+import { useMenuCommand } from './use-menu-command'
+
+export function DesktopMenuActions() {
+ const [pending, setPending] = useState<{
+ intent: TaskMenuIntent
+ id: CommandId
+ } | null>(null)
+ const [confirmation, setConfirmation] =
+ useState<MenuConfirmationRequest | null>(null)
+ useEffect(startMenuConnection, [])
+ const confirmClear = () => {
+ const ids = getTaskListSnapshot()
+ .tasks.filter((task) => isStoppedTaskStatus(task.status))
+ .map((task) => task.id)
+ if (!ids.length) return
+ setConfirmation({
+ kind: 'clear',
+ count: ids.length,
+ run: async () => {
+ if (!taskWritesAvailable()) throw new Error('Task snapshot unavailable')
+ const result = (await transport.invoke(
+ Commands.ClearStoppedTasks,
+ ids
+ )) as BulkTaskCommandResult
+ if (result.failed.length) throw new Error('Some records were retained')
+ },
+ })
+ }
+ const execute = useMenuCommand(pending?.intent, confirmClear)
+ useIpcEvent(Events.RendererTaskMenuRequested, (...args) => {
+ const parsed = rendererTaskMenuRequestSchema.safeParse(args[0])
+ if (!parsed.success || document.querySelector('[role="dialog"]')) return
+ const intent = captureTaskMenuIntent()
+ const request = parsed.data
+ if (
+ request.commandId !== CommandIds.TaskClearStopped &&
+ (request.generation !== intent.generation ||
+ JSON.stringify(request.taskIds) !== JSON.stringify(intent.ids))
+ )
+ return
+ setPending({ intent, id: request.commandId })
+ })
+ useEffect(() => {
+ if (!pending) return
+ setPending(null)
+ void execute(pending.id)
+ }, [pending, execute])
+ return (
+ <MenuConfirmation
+ request={confirmation}
+ close={() => setConfirmation(null)}
+ />
+ )
+}
diff --git a/src/renderer/features/application-menu/menu-confirmation.tsx b/src/renderer/features/application-menu/menu-confirmation.tsx
new file mode 100644
index 00000000..93a7960f
--- /dev/null
+++ b/src/renderer/features/application-menu/menu-confirmation.tsx
@@ -0,0 +1,88 @@
+import { Button } from '@renderer/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/components/ui/dialog'
+import { useOperatorSession } from '@renderer/lib/operator-auth'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+export interface MenuConfirmationRequest {
+ kind: 'clear' | 'logout' | 'discard'
+ count?: number
+ run: () => Promise<void>
+}
+export function MenuConfirmation({
+ request,
+ close,
+}: {
+ request: MenuConfirmationRequest | null
+ close: () => void
+}) {
+ const { t } = useTranslation()
+ const [busy, setBusy] = useState(false)
+ const [failed, setFailed] = useState(false)
+ const pending = useRef(false)
+ const cancel = useRef<HTMLButtonElement>(null)
+ const session = useOperatorSession((state) => state.state)
+ const confirm = async () => {
+ if (pending.current || !request || session === 'logging-out') return
+ pending.current = true
+ setBusy(true)
+ setFailed(false)
+ try {
+ await request.run()
+ close()
+ } catch {
+ setFailed(true)
+ } finally {
+ pending.current = false
+ setBusy(false)
+ }
+ }
+ return (
+ <Dialog
+ open={request !== null}
+ onOpenChange={(open) => {
+ if (!open && !busy) {
+ close()
+ setFailed(false)
+ }
+ }}
+ >
+ <DialogContent initialFocus={cancel} showCloseButton={!busy}>
+ <DialogHeader>
+ <DialogTitle>
+ {t(`applicationMenu.${request?.kind ?? 'clear'}Title`, {
+ count: request?.count,
+ })}
+ </DialogTitle>
+ <DialogDescription>
+ {t(`applicationMenu.${request?.kind ?? 'clear'}Description`)}
+ </DialogDescription>
+ </DialogHeader>
+ {failed && (
+ <p role="alert" className="text-destructive">
+ {t('applicationMenu.actionFailed')}
+ </p>
+ )}
+ <DialogFooter>
+ <Button ref={cancel} variant="ghost" disabled={busy} onClick={close}>
+ {t('panel.downloads.action.cancel')}
+ </Button>
+ <Button
+ variant="destructive"
+ disabled={busy}
+ onClick={() => void confirm()}
+ >
+ {t(`applicationMenu.${request?.kind ?? 'clear'}Confirm`)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/renderer/features/application-menu/navigation-focus.tsx b/src/renderer/features/application-menu/navigation-focus.tsx
new file mode 100644
index 00000000..293803ed
--- /dev/null
+++ b/src/renderer/features/application-menu/navigation-focus.tsx
@@ -0,0 +1,21 @@
+import { useEffect } from 'react'
+import { useLocation } from 'react-router'
+
+let destination: string | null = null
+export function requestMenuNavigationFocus(path: string): void {
+ destination = path
+}
+export function MenuNavigationFocus() {
+ const location = useLocation()
+ useEffect(() => {
+ if (!destination || location.pathname !== destination) return
+ destination = null
+ const target = document.querySelector<HTMLElement>(
+ '[data-downloads-grid], [role="dialog"] h2, main h1'
+ )
+ if (!target || target.closest('[inert]')) return
+ if (!target.hasAttribute('tabindex')) target.tabIndex = -1
+ target.focus({ preventScroll: true })
+ }, [location.pathname])
+ return null
+}
diff --git a/src/renderer/features/application-menu/task-context.test.ts b/src/renderer/features/application-menu/task-context.test.ts
new file mode 100644
index 00000000..8f621de7
--- /dev/null
+++ b/src/renderer/features/application-menu/task-context.test.ts
@@ -0,0 +1,124 @@
+import { useOperatorSession } from '@renderer/lib/operator-auth'
+import { useDownloadsSelection } from '@renderer/routes/downloads/store'
+import { CommandIds } from '@shared/commands-catalog'
+import { TaskStatus } from '@shared/types/task'
+import { makeDownloadTask } from '@test-utils/task'
+import { act, renderHook } from '@testing-library/react'
+import { useSyncExternalStore } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import {
+ captureTaskMenuIntent,
+ menuActionEnabled,
+ menuContextPatch,
+ menuContextSignature,
+ registerDownloadsMenuContext,
+ selectAllDownloads,
+ selectedMenuTasks,
+ startMenuConnection,
+ subscribeMenuContext,
+ validTaskMenuIntent,
+} from './task-context'
+
+const mocks = vi.hoisted(() => ({
+ snapshot: { tasks: [] as unknown[], status: 'ready', hasReadySnapshot: true },
+ listeners: new Set<() => void>(),
+}))
+vi.mock('@renderer/hooks/use-task-list', () => ({
+ getTaskListSnapshot: () => mocks.snapshot,
+ subscribeTaskList: (fn: () => void) => {
+ mocks.listeners.add(fn)
+ return () => mocks.listeners.delete(fn)
+ },
+}))
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ platform: 'web',
+ getConnectionState: () => 'connected',
+ invoke: vi.fn().mockResolvedValue({ state: 'ready' }),
+ on: vi.fn(),
+ off: vi.fn(),
+ },
+}))
+let dispose: () => void
+let connection: () => void
+beforeEach(async () => {
+ mocks.snapshot = { tasks: [], status: 'ready', hasReadySnapshot: true }
+ useDownloadsSelection.getState().setItems([])
+ useOperatorSession.setState({ state: 'authenticated' })
+ dispose = registerDownloadsMenuContext(vi.fn(), 'all')
+ connection = startMenuConnection()
+ await Promise.resolve()
+})
+afterEach(() => {
+ dispose()
+ connection()
+})
+it('freezes only committed selection and cancels when selection changes', () => {
+ const tasks = [
+ makeDownloadTask({ id: 'one', status: TaskStatus.Paused }),
+ makeDownloadTask({ id: 'two', status: TaskStatus.Downloading }),
+ ]
+ mocks.snapshot.tasks = tasks
+ useDownloadsSelection.getState().setItems(tasks)
+ useDownloadsSelection.getState().select('one')
+ const intent = captureTaskMenuIntent()
+ expect(menuActionEnabled(CommandIds.TaskResume, intent)).toBe(true)
+ expect(selectedMenuTasks(intent).map((task) => task.id)).toEqual(['one'])
+ useDownloadsSelection.getState().select('two')
+ expect(validTaskMenuIntent(intent)).toBe(false)
+ expect(menuActionEnabled(CommandIds.TaskResume, intent)).toBe(false)
+})
+it('selects all filtered tasks including virtual offscreen items and excludes Finalizing from remove', () => {
+ const tasks = Array.from({ length: 10_000 }, (_, index) =>
+ makeDownloadTask({ id: String(index), status: TaskStatus.Finalizing })
+ )
+ mocks.snapshot.tasks = tasks
+ useDownloadsSelection.getState().setItems(tasks.slice(0, 500))
+ selectAllDownloads()
+ expect(captureTaskMenuIntent().ids).toHaveLength(500)
+ expect(menuActionEnabled(CommandIds.TaskDelete)).toBe(false)
+})
+it('keeps local actions available while a fresh task snapshot is unavailable', () => {
+ mocks.snapshot.status = 'loading'
+ expect(menuActionEnabled(CommandIds.TaskNew)).toBe(true)
+ expect(menuActionEnabled(CommandIds.TaskPauseAll)).toBe(false)
+})
+it('does not commit menu renders for progress-only updates in a 10,000 task list', () => {
+ const tasks = Array.from({ length: 10_000 }, (_, index) =>
+ makeDownloadTask({ id: String(index), status: TaskStatus.Downloading })
+ )
+ mocks.snapshot.tasks = tasks
+ useDownloadsSelection.getState().setItems(tasks)
+ useDownloadsSelection.getState().select('1')
+ const intent = captureTaskMenuIntent()
+ let renders = 0
+ renderHook(() => {
+ useSyncExternalStore(subscribeMenuContext, () =>
+ menuContextSignature(intent)
+ )
+ renders++
+ })
+ const baseline = renders
+ for (let tick = 0; tick < 10; tick++)
+ act(() => {
+ mocks.snapshot.tasks = tasks.map((task) => ({
+ ...task,
+ downloadedBytes: tick * 100,
+ }))
+ for (const listener of mocks.listeners) listener()
+ })
+ expect(renders).toBe(baseline)
+})
+
+it('keeps the primary native task aligned with the filtered list order', () => {
+ const one = makeDownloadTask({ id: 'one', status: TaskStatus.Paused })
+ const two = makeDownloadTask({ id: 'two', status: TaskStatus.Downloading })
+ mocks.snapshot.tasks = [one, two]
+ useDownloadsSelection.getState().setItems([two, one])
+ selectAllDownloads()
+ expect(menuContextPatch()).toMatchObject({
+ selectedTaskId: 'two',
+ selectedTaskStatus: TaskStatus.Downloading,
+ selectedTaskIds: ['two', 'one'],
+ })
+})
diff --git a/src/renderer/features/application-menu/task-context.ts b/src/renderer/features/application-menu/task-context.ts
new file mode 100644
index 00000000..d596cd7b
--- /dev/null
+++ b/src/renderer/features/application-menu/task-context.ts
@@ -0,0 +1,220 @@
+import {
+ getTaskListSnapshot,
+ subscribeTaskList,
+} from '@renderer/hooks/use-task-list'
+import {
+ onOperatorSessionLost,
+ useOperatorSession,
+} from '@renderer/lib/operator-auth'
+import { transport } from '@renderer/lib/transport'
+import { useDownloadsSelection } from '@renderer/routes/downloads/store'
+import { PRODUCT_MENU_ITEMS } from '@shared/application-menu-catalog'
+import { type CommandId, CommandIds } from '@shared/commands-catalog'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import { EngineState, type EngineStatusSnapshot } from '@shared/types/engine'
+import {
+ canMoveInQueue,
+ canPause,
+ canRemove,
+ canResume,
+ isStoppedTaskStatus,
+} from '@shared/types/task-actions'
+
+let list: { focus: () => void; generation: number; filterKey: string } | null =
+ null
+let generation = 0
+let selectionIdentity = useDownloadsSelection.getState().committedSelectedIds
+useDownloadsSelection.subscribe((state) => {
+ if (state.committedSelectedIds !== selectionIdentity) {
+ selectionIdentity = state.committedSelectedIds
+ generation++
+ }
+})
+const listeners = new Set<() => void>()
+const publish = () => {
+ for (const listener of listeners) listener()
+}
+let connected = transport.platform !== 'web'
+let engineReady = false
+
+export function registerDownloadsMenuContext(
+ focus: () => void,
+ filterKey = ''
+): () => void {
+ const current = { focus, generation: ++generation, filterKey }
+ list = current
+ publish()
+ return () => {
+ if (list === current) {
+ list = null
+ generation++
+ publish()
+ }
+ }
+}
+export interface TaskMenuIntent {
+ generation: number
+ selection: ReadonlySet<string>
+ ids: readonly string[]
+}
+export function captureTaskMenuIntent(): TaskMenuIntent {
+ const state = useDownloadsSelection.getState()
+ return {
+ generation,
+ selection: state.committedSelectedIds,
+ ids: list
+ ? state.items
+ .filter((task) => state.committedSelectedIds.has(task.id))
+ .map((task) => task.id)
+ : [],
+ }
+}
+export function validTaskMenuIntent(intent: TaskMenuIntent): boolean {
+ return (
+ list !== null &&
+ intent.generation === generation &&
+ intent.selection === useDownloadsSelection.getState().committedSelectedIds
+ )
+}
+export function selectedMenuTasks(intent?: TaskMenuIntent) {
+ const captured = intent ?? captureTaskMenuIntent()
+ if (!validTaskMenuIntent(captured)) return []
+ const ids = new Set(captured.ids)
+ return getTaskListSnapshot().tasks.filter((task) => ids.has(task.id))
+}
+export function focusDownloadsList(): void {
+ list?.focus()
+}
+export function selectAllDownloads(): void {
+ if (!list) return
+ useDownloadsSelection.getState().selectAll()
+ window.getSelection()?.removeAllRanges()
+ list.focus()
+}
+export function taskWritesAvailable(): boolean {
+ return (
+ connected &&
+ engineReady &&
+ getTaskListSnapshot().status === 'ready' &&
+ (transport.platform !== 'web' ||
+ useOperatorSession.getState().state === 'authenticated')
+ )
+}
+export function menuActionEnabled(
+ id: CommandId,
+ intent?: TaskMenuIntent
+): boolean {
+ const tasks = getTaskListSnapshot().tasks
+ if (id === CommandIds.TaskSelectAll)
+ return list !== null && useDownloadsSelection.getState().items.length > 0
+ const item = PRODUCT_MENU_ITEMS.find((item) => item.commandId === id)
+ if (!item || item.scope === 'local')
+ return (
+ transport.platform !== 'web' ||
+ useOperatorSession.getState().state === 'authenticated'
+ )
+ if (!taskWritesAvailable()) return false
+ if (id === CommandIds.TaskPauseAll) return tasks.some(canPause)
+ if (id === CommandIds.TaskResumeAll) return tasks.some(canResume)
+ if (id === CommandIds.TaskClearStopped)
+ return tasks.some((task) => isStoppedTaskStatus(task.status))
+ const selected = selectedMenuTasks(intent)
+ if (id === CommandIds.TaskPause) return selected.some(canPause)
+ if (id === CommandIds.TaskResume) return selected.some(canResume)
+ if (id === CommandIds.TaskDelete) return selected.some(canRemove)
+ if (id === CommandIds.TaskMoveUp || id === CommandIds.TaskMoveDown)
+ return selected.some(canMoveInQueue)
+ return false
+}
+
+/** Only semantic changes notify React: progress frames do not rebuild the menu. */
+export function subscribeMenuContext(listener: () => void): () => void {
+ const detachTasks = subscribeTaskList(listener)
+ const detachSelection = useDownloadsSelection.subscribe(listener)
+ const detachAuth = useOperatorSession.subscribe(listener)
+ listeners.add(listener)
+ return () => {
+ detachTasks()
+ detachSelection()
+ detachAuth()
+ listeners.delete(listener)
+ }
+}
+export function menuContextSignature(intent?: TaskMenuIntent): string {
+ return PRODUCT_MENU_ITEMS.map((item) =>
+ menuActionEnabled(item.commandId, intent) ? '1' : '0'
+ ).join('')
+}
+export function startMenuConnection(): () => void {
+ connected =
+ transport.platform !== 'web' ||
+ transport.getConnectionState?.() === 'connected'
+ let epoch = 0
+ let disposed = false
+ const refreshEngine = async () => {
+ const current = ++epoch
+ try {
+ const result = (await transport.invoke(
+ Queries.GetEngineStatus
+ )) as EngineStatusSnapshot
+ if (!disposed && current === epoch) {
+ engineReady = result.state === EngineState.Ready
+ publish()
+ }
+ } catch {
+ if (current === epoch) {
+ engineReady = false
+ publish()
+ }
+ }
+ }
+ const onEngine = (...args: unknown[]) => {
+ epoch++
+ engineReady = args[0] === EngineState.Ready
+ publish()
+ }
+ const detach = transport.onConnectionChange?.((event) => {
+ connected = event.state === 'connected'
+ engineReady = false
+ epoch++
+ publish()
+ if (connected) void refreshEngine()
+ })
+ transport.on(Events.EngineStateChanged, onEngine)
+ void refreshEngine()
+ return () => {
+ disposed = true
+ epoch++
+ detach?.()
+ transport.off(Events.EngineStateChanged, onEngine)
+ }
+}
+onOperatorSessionLost(() => {
+ useDownloadsSelection.getState().clearSelection()
+ useDownloadsSelection.getState().setItems([])
+ connected = false
+ engineReady = false
+ publish()
+})
+
+export function menuContextPatch() {
+ const intent = captureTaskMenuIntent()
+ const tasks = selectedMenuTasks(intent)
+ const primary = tasks.find((task) => task.id === intent.ids[0])
+ return {
+ selectedTaskIds: intent.ids,
+ selectedTaskGeneration: intent.generation,
+ selectedTaskId: primary?.id ?? null,
+ selectedTaskStatus: primary?.status ?? null,
+ selectedTaskAtTop: false,
+ selectedTaskAtBottom: false,
+ selectedCanPause: menuActionEnabled(CommandIds.TaskPause, intent),
+ selectedCanResume: menuActionEnabled(CommandIds.TaskResume, intent),
+ selectedCanRemove: menuActionEnabled(CommandIds.TaskDelete, intent),
+ selectedCanMove: menuActionEnabled(CommandIds.TaskMoveUp, intent),
+ hasAnyActiveTask: menuActionEnabled(CommandIds.TaskPauseAll),
+ hasAnyPausedTask: menuActionEnabled(CommandIds.TaskResumeAll),
+ hasStoppedTasks: menuActionEnabled(CommandIds.TaskClearStopped),
+ }
+}
diff --git a/src/renderer/features/application-menu/use-menu-command.ts b/src/renderer/features/application-menu/use-menu-command.ts
new file mode 100644
index 00000000..3d2f5a7f
--- /dev/null
+++ b/src/renderer/features/application-menu/use-menu-command.ts
@@ -0,0 +1,94 @@
+import { toast } from '@renderer/components/ui/toast'
+import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
+import { transport } from '@renderer/lib/transport'
+import { useTaskActions } from '@renderer/routes/downloads/inspector/use-task-actions'
+import { type CommandId, CommandIds } from '@shared/commands-catalog'
+import { Commands } from '@shared/protocol/commands'
+import type { BulkTaskCommandResult } from '@shared/types/task-actions'
+import { useTranslation } from 'react-i18next'
+import { useLocation, useNavigate } from 'react-router'
+import { requestMenuNavigationFocus } from './navigation-focus'
+import {
+ focusDownloadsList,
+ menuActionEnabled,
+ selectAllDownloads,
+ selectedMenuTasks,
+ type TaskMenuIntent,
+} from './task-context'
+
+export function useMenuCommand(
+ intent: TaskMenuIntent | undefined,
+ confirmClear: () => void
+) {
+ const actions = useTaskActions(selectedMenuTasks(intent))
+ const navigate = useNavigate()
+ const location = useLocation()
+ const { t } = useTranslation()
+ return async (id: CommandId) => {
+ if (!menuActionEnabled(id, intent)) return
+ try {
+ switch (id) {
+ case CommandIds.AppShowAbout:
+ requestMenuNavigationFocus('/settings/about')
+ navigate('/settings/about')
+ return
+ case CommandIds.AppOpenPreferences:
+ requestMenuNavigationFocus('/settings')
+ navigate('/settings')
+ return
+ case CommandIds.TaskNew:
+ await openAddTaskDialog({ tab: 'links' })
+ return
+ case CommandIds.TaskNewBt:
+ await openAddTaskDialog({ tab: 'torrent' })
+ return
+ case CommandIds.NavigateTaskList:
+ if (!location.pathname.startsWith('/downloads')) {
+ requestMenuNavigationFocus('/downloads/all')
+ navigate('/downloads/all')
+ } else focusDownloadsList()
+ return
+ case CommandIds.TaskSelectAll:
+ selectAllDownloads()
+ return
+ case CommandIds.TaskPause:
+ await actions.onPause()
+ return
+ case CommandIds.TaskResume:
+ await actions.onResume()
+ return
+ case CommandIds.TaskDelete:
+ actions.onRemove()
+ return
+ case CommandIds.TaskMoveUp:
+ await actions.onMove('up')
+ return
+ case CommandIds.TaskMoveDown:
+ await actions.onMove('down')
+ return
+ case CommandIds.TaskClearStopped:
+ confirmClear()
+ return
+ case CommandIds.TaskPauseAll:
+ case CommandIds.TaskResumeAll: {
+ const result = (await transport.invoke(
+ id === CommandIds.TaskPauseAll
+ ? Commands.PauseAllTasks
+ : Commands.ResumeAllTasks
+ )) as BulkTaskCommandResult
+ if (result.failed.length)
+ toast.add({
+ title: t('panel.downloads.action.batchPartial', {
+ ok: result.succeeded.length,
+ failed: result.failed.length,
+ }),
+ type: 'warning',
+ })
+ return
+ }
+ }
+ } catch {
+ toast.add({ title: t('applicationMenu.actionFailed'), type: 'error' })
+ }
+ }
+}
diff --git a/src/renderer/features/application-menu/web-menu-button.test.tsx b/src/renderer/features/application-menu/web-menu-button.test.tsx
new file mode 100644
index 00000000..f26145cb
--- /dev/null
+++ b/src/renderer/features/application-menu/web-menu-button.test.tsx
@@ -0,0 +1,155 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'
+import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
+import { useOperatorSession } from '@renderer/lib/operator-auth'
+import { readTorrentFile } from '@renderer/lib/parse-torrent-file'
+import { transport } from '@renderer/lib/transport'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { MemoryRouter } from 'react-router'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { WebMenuButton } from './web-menu-button'
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { platform: 'web', invoke: vi.fn(), on: vi.fn(), off: vi.fn() },
+}))
+vi.mock('@renderer/lib/open-add-task-dialog', () => ({
+ openAddTaskDialog: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@renderer/lib/parse-torrent-file', () => ({
+ readTorrentFile: vi.fn(),
+}))
+vi.mock('./task-context', () => ({
+ captureTaskMenuIntent: () => ({
+ ids: [],
+ generation: 0,
+ selection: new Set(),
+ }),
+ focusDownloadsList: vi.fn(),
+ selectAllDownloads: vi.fn(),
+ selectedMenuTasks: () => [],
+ subscribeMenuContext: () => () => {},
+ menuContextSignature: () => 'stable',
+ menuActionEnabled: () => true,
+ taskWritesAvailable: () => true,
+ startMenuConnection: () => () => {},
+}))
+function mount(narrow = false) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn(() => ({
+ matches: narrow,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ }))
+ )
+ return render(
+ <MemoryRouter>
+ <WebMenuButton />
+ </MemoryRouter>
+ )
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ useAddTaskDialogStore.getState().close()
+ useOperatorSession.setState({
+ state: 'authenticated',
+ status: { authed: true, mode: 'cookie', canLogout: true },
+ })
+ HTMLElement.prototype.scrollIntoView = vi.fn()
+ HTMLElement.prototype.hasPointerCapture = () => false
+})
+afterEach(() => vi.unstubAllGlobals())
+it('renders browser product entries without desktop IPC or reserved accelerators', async () => {
+ mount()
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await screen.findByRole('menu')
+ expect(screen.getByRole('menuitem', { name: 'About Motrix' })).toBeVisible()
+ expect(screen.getByRole('menuitem', { name: 'Sign out…' })).toBeVisible()
+ expect(screen.queryByText(/Quit|Check for Updates|DevTools/)).toBeNull()
+ expect(transport.invoke).not.toHaveBeenCalled()
+})
+it('opens the links form once after the menu closes', async () => {
+ mount(true)
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await screen.findByRole('menu')
+ await user.click(screen.getByRole('menuitem', { name: 'Task' }))
+ await user.click(screen.getByRole('menuitem', { name: 'New Task…' }))
+ await waitFor(() =>
+ expect(openAddTaskDialog).toHaveBeenCalledExactlyOnceWith({ tab: 'links' })
+ )
+ expect(screen.queryByRole('menu')).toBeNull()
+})
+it('uses a one-level stack below 640px and Escape returns before closing', async () => {
+ mount(true)
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await screen.findByRole('menu')
+ await user.click(screen.getByRole('menuitem', { name: 'Task' }))
+ expect(screen.getAllByRole('menu')).toHaveLength(1)
+ expect(screen.getByRole('menuitem', { name: 'Back' })).toBeVisible()
+ await user.keyboard('{Escape}')
+ expect(screen.getByRole('menuitem', { name: 'About Motrix' })).toBeVisible()
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull())
+})
+it('uses real anchors for help and hides logout for unrestricted access', async () => {
+ useOperatorSession.setState({
+ status: { authed: true, mode: 'unrestricted', canLogout: false },
+ })
+ mount(true)
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await screen.findByRole('menu')
+ expect(screen.queryByRole('menuitem', { name: 'Sign out…' })).toBeNull()
+ await user.click(screen.getByRole('menuitem', { name: 'Help' }))
+ for (const link of screen
+ .getAllByRole('menuitem')
+ .filter((element) => element.tagName === 'A')) {
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer')
+ }
+ expect(
+ screen.getAllByRole('menuitem').filter((element) => element.tagName === 'A')
+ ).toHaveLength(4)
+})
+it('activates the browser file input synchronously and passes all parsed files to the form', async () => {
+ mount(true)
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await screen.findByRole('menu')
+ await user.click(screen.getByRole('menuitem', { name: 'Task' }))
+ const input = screen.getByLabelText('Open Torrent File…') as HTMLInputElement
+ const click = vi.spyOn(input, 'click')
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Open Torrent File…' }))
+ expect(click).toHaveBeenCalledOnce()
+ const parsed = {
+ name: 'test.torrent',
+ base64: 'base64',
+ meta: {
+ name: 'test',
+ infoHash: 'a'.repeat(40),
+ totalSize: 1,
+ comment: null,
+ isPrivate: false,
+ files: [{ index: 0, path: 'test', size: 1, extension: '' }],
+ },
+ }
+ vi.mocked(readTorrentFile).mockResolvedValue(parsed)
+ fireEvent.change(input, {
+ target: {
+ files: [
+ new File(['one'], 'one.torrent'),
+ new File(['two'], 'two.torrent'),
+ ],
+ },
+ })
+ await waitFor(() =>
+ expect(useAddTaskDialogStore.getState().torrentFiles).toHaveLength(2)
+ )
+ expect(useAddTaskDialogStore.getState().prefill).toEqual({ tab: 'torrent' })
+ expect(input.value).toBe('')
+})
diff --git a/src/renderer/features/application-menu/web-menu-button.tsx b/src/renderer/features/application-menu/web-menu-button.tsx
new file mode 100644
index 00000000..688dcdf1
--- /dev/null
+++ b/src/renderer/features/application-menu/web-menu-button.tsx
@@ -0,0 +1,444 @@
+import './application-menu.css'
+import { useAddTaskDialogStore } from '@renderer/components/add-task-dialog/use-add-task-dialog-store'
+import { Button } from '@renderer/components/ui/button'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { toast } from '@renderer/components/ui/toast'
+import { MotrixLogo } from '@renderer/components/window-chrome/motrix-logo'
+import { getTaskListSnapshot } from '@renderer/hooks/use-task-list'
+import { operatorLogout, useOperatorSession } from '@renderer/lib/operator-auth'
+import {
+ type ParsedTorrentFile,
+ readTorrentFile,
+} from '@renderer/lib/parse-torrent-file'
+import { transport } from '@renderer/lib/transport'
+import {
+ PRODUCT_MENU_ITEMS,
+ PRODUCT_MENU_LINKS,
+ type ProductMenuItem,
+} from '@shared/application-menu-catalog'
+import { type CommandId, CommandIds } from '@shared/commands-catalog'
+import { Commands } from '@shared/protocol/commands'
+import {
+ type BulkTaskCommandResult,
+ isStoppedTaskStatus,
+} from '@shared/types/task-actions'
+import { ArrowLeft, ChevronRight } from 'lucide-react'
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+import { useLocation } from 'react-router'
+import {
+ MenuConfirmation,
+ type MenuConfirmationRequest,
+} from './menu-confirmation'
+import {
+ captureTaskMenuIntent,
+ focusDownloadsList,
+ menuActionEnabled,
+ menuContextSignature,
+ startMenuConnection,
+ subscribeMenuContext,
+ type TaskMenuIntent,
+ taskWritesAvailable,
+} from './task-context'
+import { useMenuCommand } from './use-menu-command'
+
+function usableFocus(element: HTMLElement | null): element is HTMLElement {
+ return (
+ !!element?.isConnected &&
+ !element.closest('[inert], [aria-hidden="true"]') &&
+ element.getClientRects().length > 0
+ )
+}
+
+export function WebMenuButton() {
+ const { t } = useTranslation()
+ const location = useLocation()
+ const [open, setOpen] = useState(false)
+ const [narrow, setNarrow] = useState(
+ () => window.matchMedia?.('(width < 640px)').matches ?? false
+ )
+ const [level, setLevel] = useState<'task' | 'help' | null>(null)
+ const [intent, setIntent] = useState<TaskMenuIntent>()
+ const [confirmation, setConfirmation] =
+ useState<MenuConfirmationRequest | null>(null)
+ const canLogout = useOperatorSession((s) => s.status?.canLogout === true)
+ const content = useRef<HTMLDivElement>(null)
+ const trigger = useRef<HTMLButtonElement>(null)
+ const input = useRef<HTMLInputElement>(null)
+ const source = useRef<HTMLElement | null>(null)
+ const pending = useRef<CommandId | 'logout' | null>(null)
+ const generation = useRef(0)
+ const closingComplete = useRef(true)
+ const restore = useRef(false)
+ const picker = useRef<{
+ generation: number
+ epoch: number
+ route: string
+ revision: number
+ files?: ParsedTorrentFile[]
+ } | null>(null)
+ const route = `${location.pathname}${location.search}`
+ const routeRef = useRef(route)
+ routeRef.current = route
+ useSyncExternalStore(subscribeMenuContext, () => menuContextSignature(intent))
+ useEffect(startMenuConnection, [])
+ useEffect(() => {
+ if (!open || !narrow || !level) return
+ const frame = requestAnimationFrame(() =>
+ content.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus()
+ )
+ return () => cancelAnimationFrame(frame)
+ }, [open, narrow, level])
+ useEffect(() => {
+ const element = input.current
+ const cancel = () => {
+ picker.current = null
+ }
+ element?.addEventListener('cancel', cancel)
+ return () => element?.removeEventListener('cancel', cancel)
+ }, [])
+
+ const cancelPending = useCallback(() => {
+ generation.current++
+ pending.current = null
+ picker.current = null
+ restore.current = false
+ setOpen(false)
+ }, [])
+ useEffect(() => {
+ routeRef.current = route
+ cancelPending()
+ }, [route, cancelPending])
+ useEffect(() => {
+ if (!window.matchMedia) return
+ const small = window.matchMedia('(width < 640px)')
+ const mobile = window.matchMedia('(width < 768px)')
+ const resize = () => {
+ cancelPending()
+ setNarrow(small.matches)
+ setLevel(null)
+ }
+ const blur = (event: FocusEvent) => {
+ if (event.target === window && !picker.current) cancelPending()
+ }
+ const hide = () => {
+ if (document.visibilityState === 'hidden') cancelPending()
+ }
+ small.addEventListener('change', resize)
+ mobile.addEventListener('change', resize)
+ window.addEventListener('blur', blur)
+ document.addEventListener('visibilitychange', hide)
+ return () => {
+ small.removeEventListener('change', resize)
+ mobile.removeEventListener('change', resize)
+ window.removeEventListener('blur', blur)
+ document.removeEventListener('visibilitychange', hide)
+ }
+ }, [cancelPending])
+
+ const restoreSource = () => {
+ if (usableFocus(source.current))
+ source.current.focus({ preventScroll: true })
+ else if (document.querySelector('[data-downloads-grid]'))
+ focusDownloadsList()
+ else trigger.current?.focus({ preventScroll: true })
+ }
+ const confirmClear = () => {
+ const ids = getTaskListSnapshot()
+ .tasks.filter((task) => isStoppedTaskStatus(task.status))
+ .map((task) => task.id)
+ if (!ids.length) return
+ setConfirmation({
+ kind: 'clear',
+ count: ids.length,
+ run: async () => {
+ if (!taskWritesAvailable()) throw new Error('Task snapshot unavailable')
+ const result = (await transport.invoke(
+ Commands.ClearStoppedTasks,
+ ids
+ )) as BulkTaskCommandResult
+ if (result.failed.length)
+ throw new Error('Some task records were retained')
+ },
+ })
+ }
+ const execute = useMenuCommand(intent, confirmClear)
+ const deliverFiles = () => {
+ const request = picker.current
+ if (!request?.files || !closingComplete.current) return
+ requestAnimationFrame(() => {
+ if (picker.current !== request) return
+ picker.current = null
+ const dialog = useAddTaskDialogStore.getState()
+ if (
+ request.generation !== generation.current ||
+ request.epoch !== useOperatorSession.getState().epoch ||
+ request.route !== routeRef.current ||
+ request.revision !== dialog.revision ||
+ dialog.open ||
+ useOperatorSession.getState().state !== 'authenticated'
+ )
+ return
+ restoreSource()
+ restore.current = false
+ dialog.openWith({ tab: 'torrent' }, request.files)
+ })
+ }
+ const chooseFiles = () => {
+ picker.current = {
+ generation: generation.current,
+ epoch: useOperatorSession.getState().epoch,
+ route: routeRef.current,
+ revision: useAddTaskDialogStore.getState().revision,
+ }
+ // Must run in the menu item's trusted activation, before the close animation.
+ input.current?.click()
+ }
+ const queue = (id: CommandId) => {
+ if (!menuActionEnabled(id, intent)) return
+ if (id === CommandIds.TaskOpenFile) chooseFiles()
+ else pending.current = id
+ }
+ const renderItems = (section: ProductMenuItem['section']): ReactNode[] => {
+ const result: ReactNode[] = []
+ let group = ''
+ for (const item of PRODUCT_MENU_ITEMS.filter(
+ (item) => item.section === section
+ )) {
+ if (group && group !== item.group && section !== 'app')
+ result.push(<DropdownMenuSeparator key={`separator-${item.group}`} />)
+ group = item.group
+ const href = PRODUCT_MENU_LINKS[item.commandId]
+ result.push(
+ <DropdownMenuItem
+ key={item.id}
+ id={item.id}
+ disabled={!menuActionEnabled(item.commandId, intent)}
+ render={
+ href ? (
+ <a
+ aria-label={t(item.title)}
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t(item.title)}
+ </a>
+ ) : undefined
+ }
+ onClick={() => {
+ if (!href) queue(item.commandId)
+ }}
+ >
+ {t(item.title)}
+ </DropdownMenuItem>
+ )
+ }
+ return result
+ }
+ const submenu = (section: 'task' | 'help') =>
+ narrow ? (
+ <DropdownMenuItem
+ key={section}
+ closeOnClick={false}
+ onClick={() => setLevel(section)}
+ >
+ {t(`menu.${section}.title`)}
+ <ChevronRight className="ms-auto size-3" />
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuSub key={section}>
+ <DropdownMenuSubTrigger>
+ {t(`menu.${section}.title`)}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ data-menu-density="compact"
+ className="application-menu app-no-drag"
+ >
+ {renderItems(section)}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )
+
+ return (
+ <>
+ <DropdownMenu
+ open={open}
+ onOpenChange={(next, details) => {
+ if (!next && details.reason === 'escape-key' && narrow && level) {
+ details.cancel()
+ setLevel(null)
+ return
+ }
+ if (next) {
+ generation.current++
+ pending.current = null
+ picker.current = null
+ closingComplete.current = false
+ restore.current = false
+ setIntent(captureTaskMenuIntent())
+ setLevel(null)
+ } else
+ restore.current =
+ details.reason === 'escape-key' || details.reason === 'item-press'
+ setOpen(next)
+ }}
+ onOpenChangeComplete={(next) => {
+ if (next) return
+ closingComplete.current = true
+ const command = pending.current
+ pending.current = null
+ if (command) {
+ const current = generation.current
+ restore.current = false
+ // Let the closing menu's focus manager unmount before mounting a dialog.
+ requestAnimationFrame(() => {
+ if (generation.current !== current) return
+ restoreSource()
+ if (command === 'logout')
+ setConfirmation({ kind: 'logout', run: operatorLogout })
+ else void execute(command)
+ })
+ }
+ deliverFiles()
+ }}
+ >
+ <DropdownMenuTrigger
+ ref={trigger}
+ data-slot="motrix-menu-trigger"
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ aria-label={t('menu.app.title')}
+ className="app-no-drag h-7 w-[72px] gap-1 bg-transparent pl-2 pr-1 hover:bg-accent"
+ onPointerDownCapture={() => {
+ source.current =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
+ }}
+ onKeyDownCapture={() => {
+ source.current =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
+ }}
+ />
+ }
+ >
+ <MotrixLogo />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ ref={content}
+ align="start"
+ data-menu-density="compact"
+ className="application-menu app-no-drag"
+ finalFocus={() =>
+ restore.current && usableFocus(source.current)
+ ? source.current
+ : restore.current
+ ? trigger.current
+ : false
+ }
+ onKeyDownCapture={(event) => {
+ if (level && event.key === 'ArrowLeft') {
+ event.preventDefault()
+ event.stopPropagation()
+ setLevel(null)
+ }
+ }}
+ >
+ {level ? (
+ <>
+ <DropdownMenuItem
+ closeOnClick={false}
+ onClick={() => setLevel(null)}
+ >
+ <ArrowLeft className="size-3" />
+ {t('applicationMenu.back')}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ {renderItems(level)}
+ </>
+ ) : (
+ <>
+ {renderItems('app')}
+ <DropdownMenuSeparator />
+ {submenu('task')}
+ {submenu('help')}
+ {canLogout && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => {
+ pending.current = 'logout'
+ }}
+ >
+ {t('applicationMenu.signOut')}
+ </DropdownMenuItem>
+ </>
+ )}
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <input
+ ref={input}
+ type="file"
+ accept=".torrent"
+ multiple
+ className="hidden"
+ aria-label={t('menu.task.openFile')}
+ onChange={(event) => {
+ const files = Array.from(event.target.files ?? [])
+ event.target.value = ''
+ const request = picker.current
+ if (!request || !files.length) {
+ picker.current = null
+ return
+ }
+ void (async () => {
+ const parsed: ParsedTorrentFile[] = []
+ for (const file of files) {
+ if (picker.current !== request) return
+ try {
+ parsed.push(await readTorrentFile(file))
+ } catch {
+ toast.add({ title: t('task.add.parseFailed'), type: 'error' })
+ }
+ }
+ if (picker.current !== request) return
+ if (!parsed.length) {
+ picker.current = null
+ return
+ }
+ request.files = parsed
+ deliverFiles()
+ })()
+ }}
+ />
+ <MenuConfirmation
+ request={confirmation}
+ close={() => setConfirmation(null)}
+ />
+ </>
+ )
+}
diff --git a/src/renderer/hooks/use-global-speed-history.ts b/src/renderer/hooks/use-global-speed-history.ts
index 30c9701a..0b645246 100644
--- a/src/renderer/hooks/use-global-speed-history.ts
+++ b/src/renderer/hooks/use-global-speed-history.ts
@@ -1,3 +1,4 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
// src/renderer/hooks/use-global-speed-history.ts
import { transport } from '@renderer/lib/transport'
import { Events } from '@shared/protocol/events'
@@ -19,6 +20,7 @@ const MOCK_UPLOAD_BPS = [
let store: readonly SpeedPoint[] = []
const listeners = new Set<() => void>()
+let sessionEpoch = 0
let initialized = false
let initializing = false
let pendingTail: SpeedPoint[] = []
@@ -63,10 +65,12 @@ function onStatsEvent(...args: unknown[]) {
function initialize() {
if (initialized || initializing) return
initializing = true
+ const epoch = sessionEpoch
transport.on(Events.StatsUpdated, onStatsEvent)
void transport
.invoke(Queries.GetSpeedHistory, { limit: MAX_POINTS })
.then((data) => {
+ if (epoch !== sessionEpoch) return
const seed = data as readonly SpeedPoint[]
const base =
seed.length === 0 && pendingTail.length === 0 && shouldUseWebMock()
@@ -80,6 +84,7 @@ function initialize() {
notify()
})
.catch(() => {
+ if (epoch !== sessionEpoch) return
if (shouldUseWebMock()) {
store = createMockSpeedHistory()
initialized = true
@@ -118,3 +123,13 @@ export function __resetGlobalSpeedHistoryStoreForTests(): void {
initializing = false
pendingTail = []
}
+
+onOperatorSessionLost(() => {
+ sessionEpoch++
+ transport.off(Events.StatsUpdated, onStatsEvent)
+ store = []
+ pendingTail = []
+ initialized = false
+ initializing = false
+ notify()
+})
diff --git a/src/renderer/hooks/use-menu-context-sync.test.ts b/src/renderer/hooks/use-menu-context-sync.test.ts
index 639f67fa..325a015c 100644
--- a/src/renderer/hooks/use-menu-context-sync.test.ts
+++ b/src/renderer/hooks/use-menu-context-sync.test.ts
@@ -20,19 +20,16 @@ vi.mock('@renderer/lib/transport', () => ({
transport: transportMock,
}))
-vi.mock('./use-selected-task', () => ({
- useSelectedTask: () => ({
- task: hookState.task,
- atTop: hookState.atTop,
- atBottom: hookState.atBottom,
- }),
-}))
-
-vi.mock('./use-task-list', () => ({
- useTaskList: () => ({
- hasAnyActive: hookState.hasAnyActive,
- hasAnyPaused: hookState.hasAnyPaused,
- hasStopped: hookState.hasStopped,
+vi.mock('@renderer/features/application-menu/task-context', () => ({
+ subscribeMenuContext: () => () => {},
+ menuContextPatch: () => ({
+ selectedTaskId: hookState.task?.id ?? null,
+ selectedTaskStatus: hookState.task?.status ?? null,
+ selectedTaskAtTop: hookState.atTop,
+ selectedTaskAtBottom: hookState.atBottom,
+ hasAnyActiveTask: hookState.hasAnyActive,
+ hasAnyPausedTask: hookState.hasAnyPaused,
+ hasStoppedTasks: hookState.hasStopped,
}),
}))
diff --git a/src/renderer/hooks/use-menu-context-sync.ts b/src/renderer/hooks/use-menu-context-sync.ts
index dd038244..49afb1c5 100644
--- a/src/renderer/hooks/use-menu-context-sync.ts
+++ b/src/renderer/hooks/use-menu-context-sync.ts
@@ -1,10 +1,12 @@
+import {
+ menuContextPatch,
+ subscribeMenuContext,
+} from '@renderer/features/application-menu/task-context'
import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import type { MenuContext } from '@shared/types/menu-context'
-import { useEffect, useRef } from 'react'
+import { useEffect, useRef, useSyncExternalStore } from 'react'
import { useCurrentRoute } from './use-current-route'
-import { useSelectedTask } from './use-selected-task'
-import { useTaskList } from './use-task-list'
type Patch = Partial<MenuContext>
@@ -14,7 +16,7 @@ function diff(prev: Patch, next: Patch): Patch {
const out: Patch = {}
let changed = false
for (const key of Object.keys(next) as (keyof MenuContext)[]) {
- if (prev[key] !== next[key]) {
+ if (JSON.stringify(prev[key]) !== JSON.stringify(next[key])) {
;(out as Record<string, unknown>)[key] = next[key]
changed = true
}
@@ -28,8 +30,9 @@ function diff(prev: Patch, next: Patch): Patch {
* so the whole effect body is tree-shaken out of the bundle).
*/
export function useMenuContextSync(): void {
- const selected = useSelectedTask()
- const list = useTaskList()
+ const signature = useSyncExternalStore(subscribeMenuContext, () =>
+ JSON.stringify(menuContextPatch())
+ )
const route = useCurrentRoute()
const acknowledged = useRef<Patch>({})
const desired = useRef<Patch>({})
@@ -94,15 +97,9 @@ export function useMenuContextSync(): void {
if (__MOTRIX_TARGET__ !== 'electron') return
desired.current = {
- selectedTaskId: selected.task?.id ?? null,
- selectedTaskStatus: selected.task?.status ?? null,
- selectedTaskAtTop: selected.atTop,
- selectedTaskAtBottom: selected.atBottom,
- hasAnyActiveTask: list.hasAnyActive,
- hasAnyPausedTask: list.hasAnyPaused,
- hasStoppedTasks: list.hasStopped,
+ ...JSON.parse(signature),
currentRoute: route,
}
drainOutbox.current()
- }, [selected, list, route])
+ }, [signature, route])
}
diff --git a/src/renderer/hooks/use-selected-task.ts b/src/renderer/hooks/use-selected-task.ts
index 20abcc45..ca145816 100644
--- a/src/renderer/hooks/use-selected-task.ts
+++ b/src/renderer/hooks/use-selected-task.ts
@@ -1,4 +1,6 @@
+import { useDownloadsSelection } from '@renderer/routes/downloads/store'
import type { DownloadTask } from '@shared/types/task'
+import { useMemo } from 'react'
export interface SelectedTaskSnapshot {
task: DownloadTask | null
@@ -6,19 +8,18 @@ export interface SelectedTaskSnapshot {
atBottom: boolean
}
-const NONE: SelectedTaskSnapshot = {
- task: null,
- atTop: false,
- atBottom: false,
-}
-
-/**
- * Returns the currently-selected download task.
- * Today the renderer has no task-list UI or selection store, so this
- * always returns the "none" snapshot. Wire the real selection source
- * in (or alongside) the download-list UI work; when done, this hook's
- * contract (task + atTop + atBottom) is what useMenuContextSync consumes.
- */
export function useSelectedTask(): SelectedTaskSnapshot {
- return NONE
+ const signature = useDownloadsSelection((state) => {
+ const task = state.items.find((task) =>
+ state.committedSelectedIds.has(task.id)
+ )
+ return JSON.stringify([task?.id, task?.status])
+ })
+ return useMemo(() => {
+ const [id] = JSON.parse(signature)
+ const task =
+ useDownloadsSelection.getState().items.find((task) => task.id === id) ??
+ null
+ return { task, atTop: false, atBottom: false }
+ }, [signature])
}
diff --git a/src/renderer/hooks/use-speed-limit-state.ts b/src/renderer/hooks/use-speed-limit-state.ts
index ef08cc89..3f5985df 100644
--- a/src/renderer/hooks/use-speed-limit-state.ts
+++ b/src/renderer/hooks/use-speed-limit-state.ts
@@ -1,3 +1,4 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
import { transport } from '@renderer/lib/transport'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
@@ -66,3 +67,7 @@ export function useSpeedLimitState(): SpeedLimitStateView {
return state
}
+
+onOperatorSessionLost(() => {
+ cachedState = null
+})
diff --git a/src/renderer/hooks/use-task-activity.ts b/src/renderer/hooks/use-task-activity.ts
index 27756f11..c5fcc779 100644
--- a/src/renderer/hooks/use-task-activity.ts
+++ b/src/renderer/hooks/use-task-activity.ts
@@ -1,3 +1,4 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
import { transport } from '@renderer/lib/transport'
import { buildActivityDayBoundaries } from '@renderer/routes/dashboard/activity/activity-calendar-model'
import { Events } from '@shared/protocol/events'
@@ -484,3 +485,12 @@ export function __resetTaskActivityStoreForTests(): void {
rangeEnvironment = buildRangeEnvironment()
state = Object.freeze({ status: 'loading', retry })
}
+
+onOperatorSessionLost(() => {
+ cancelDeferredTeardown()
+ detach()
+ rangeEpoch++
+ activitySnapshot = null
+ activitySnapshotRangeSignature = null
+ publish({ status: 'loading', retry }, true)
+})
diff --git a/src/renderer/hooks/use-task-list.ts b/src/renderer/hooks/use-task-list.ts
index 0773bee6..7347a489 100644
--- a/src/renderer/hooks/use-task-list.ts
+++ b/src/renderer/hooks/use-task-list.ts
@@ -1,3 +1,4 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
import { transport } from '@renderer/lib/transport'
import { Events } from '@shared/protocol/events'
import { Queries } from '@shared/protocol/queries'
@@ -300,7 +301,11 @@ function attachListeners(): void {
// guard discard every response except the last one's, which may fail.
detachConnectionListener =
transport.onConnectionChange?.((event) => {
- if (event.state !== 'connected') return
+ publish({ status: 'loading' })
+ if (event.state !== 'connected') {
+ dataGeneration += 1
+ return
+ }
resetResyncRetry()
dataGeneration += 1
legacyRefreshRequested = true
@@ -335,7 +340,7 @@ function scheduleDeferredTeardown(): void {
}, 0)
}
-function subscribe(listener: StoreListener): () => void {
+export function subscribeTaskList(listener: StoreListener): () => void {
cancelDeferredTeardown()
subscribers.add(listener)
attachListeners()
@@ -346,14 +351,18 @@ function subscribe(listener: StoreListener): () => void {
}
}
-function getSnapshot(): TaskListAggregates {
+export function getTaskListSnapshot(): TaskListAggregates {
return snapshot
}
-const getServerSnapshot = getSnapshot
+const getServerSnapshot = getTaskListSnapshot
export function useTaskList(): TaskListAggregates {
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
+ return useSyncExternalStore(
+ subscribeTaskList,
+ getTaskListSnapshot,
+ getServerSnapshot
+ )
}
/** Internal: tests only. Resets the module-level external store. */
@@ -370,3 +379,12 @@ export function __resetTaskListStoreForTests(): void {
resetResyncRetry()
snapshot = createSnapshot(EMPTY_TASKS, 'loading', false, 0)
}
+
+/** Clear privileged cached data when the operator session is confirmed lost. */
+export function clearTaskListSession(): void {
+ cancelDeferredTeardown()
+ detachListeners()
+ dataGeneration += 1
+ publish({ tasks: EMPTY_TASKS, status: 'loading', hasReadySnapshot: false })
+}
+onOperatorSessionLost(clearTaskListSession)
diff --git a/src/renderer/index.tsx b/src/renderer/index.tsx
index 1fadb190..e9dd722c 100644
--- a/src/renderer/index.tsx
+++ b/src/renderer/index.tsx
@@ -77,7 +77,7 @@ function Root({
}
async function startRenderer(rootContainer: HTMLElement): Promise<void> {
- await bootstrapRendererLocale(windowId)
+ if (transport.platform !== 'web') await bootstrapRendererLocale(windowId)
const root = createRoot(rootContainer)
if (windowId === 'add-task') {
@@ -98,11 +98,11 @@ async function startRenderer(rootContainer: HTMLElement): Promise<void> {
)
} else {
root.render(
- <Root>
- <OperatorUnlockGate>
+ <OperatorUnlockGate>
+ <Root>
<RouterProvider router={router} />
- </OperatorUnlockGate>
- </Root>
+ </Root>
+ </OperatorUnlockGate>
)
}
}
diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsx
index ca358cb7..57d4ae78 100644
--- a/src/renderer/layouts/app-layout.tsx
+++ b/src/renderer/layouts/app-layout.tsx
@@ -7,6 +7,8 @@ import { AddTaskTriggerButton } from '@renderer/components/window-chrome/add-tas
import { MotrixMenuButton } from '@renderer/components/window-chrome/motrix-menu-button'
import { SidebarTriggerButton } from '@renderer/components/window-chrome/sidebar-trigger-button'
import { WindowChrome } from '@renderer/components/window-chrome/window-chrome'
+import { DesktopMenuActions } from '@renderer/features/application-menu/desktop-menu-actions'
+import { MenuNavigationFocus } from '@renderer/features/application-menu/navigation-focus'
import { EngineDiagnosticsDialogHost } from '@renderer/features/engine-diagnostics/engine-diagnostics-dialog'
import { useEngineRestartRequiredToast } from '@renderer/hooks/use-engine-restart-required-toast'
import { useIpcEvent } from '@renderer/hooks/use-ipc-event'
@@ -18,17 +20,20 @@ import { electronServices } from '@renderer/platform/electron-services'
import { PlatformServicesProvider } from '@renderer/platform/services'
import { webServices } from '@renderer/platform/web-services'
import type { RouteHandle } from '@renderer/router-types'
+import { RemoveTasksDialogHost } from '@renderer/routes/downloads/inspector/remove-tasks-dialog-host'
import { usePairRequestPrompts } from '@renderer/routes/settings/cards/integration/use-pair-request-prompts'
-import { useShortcuts } from '@renderer/shortcuts/use-shortcuts'
import { Events } from '@shared/protocol/events'
import { Outlet, useMatches, useNavigate } from 'react-router'
const platformServices =
__MOTRIX_TARGET__ === 'electron' ? electronServices : webServices
-export function AppLayout() {
+function DesktopMenuContext() {
useMenuContextSync()
- useShortcuts()
+ return <DesktopMenuActions />
+}
+
+export function AppLayout() {
useToastEvents()
usePairRequestPrompts()
useEngineRestartRequiredToast()
@@ -55,6 +60,7 @@ export function AppLayout() {
<SidebarProvider
className={cn(
'h-svh overflow-hidden bg-sidebar',
+ __MOTRIX_TARGET__ === 'web' && 'web-window-chrome',
__MOTRIX_TARGET__ === 'electron' && 'electron-window-chrome',
__MOTRIX_TARGET__ === 'electron' &&
__MOTRIX_PREVIEW_MAC_MENU__ &&
@@ -92,6 +98,9 @@ export function AppLayout() {
<Outlet />
</SidebarInset>
</SidebarProvider>
+ {__MOTRIX_TARGET__ === 'electron' && <DesktopMenuContext />}
+ <MenuNavigationFocus />
+ <RemoveTasksDialogHost />
<EngineDiagnosticsDialogHost />
{__MOTRIX_TARGET__ === 'web' && <AddTaskDialogHost />}
</PlatformServicesProvider>
diff --git a/src/renderer/lib/open-magnet-file-selection.test.ts b/src/renderer/lib/open-magnet-file-selection.test.ts
index 6483dabc..8a269732 100644
--- a/src/renderer/lib/open-magnet-file-selection.test.ts
+++ b/src/renderer/lib/open-magnet-file-selection.test.ts
@@ -54,9 +54,9 @@ describe('openMagnetFileSelection', () => {
it('does not reset edits if the matching selection is already displayed', async () => {
showMagnetFileSelection(selection)
- useAddTaskDialogStore
- .getState()
- .openWith({ existingTaskId: 'ready', tab: 'torrent', selectedFiles: [1] })
+ useAddTaskDialogStore.setState({
+ prefill: { existingTaskId: 'ready', tab: 'torrent', selectedFiles: [1] },
+ })
const revision = useAddTaskDialogStore.getState().revision
await openMagnetFileSelection('ready')
expect(useAddTaskDialogStore.getState().revision).toBe(revision)
diff --git a/src/renderer/lib/operator-auth.test.ts b/src/renderer/lib/operator-auth.test.ts
new file mode 100644
index 00000000..382234a6
--- /dev/null
+++ b/src/renderer/lib/operator-auth.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import {
+ operatorLogin,
+ operatorLogout,
+ refreshOperatorSession,
+ useOperatorSession,
+} from './operator-auth'
+
+const fetchMock = vi.fn()
+const authed = () =>
+ new Response(
+ JSON.stringify({ authed: true, mode: 'cookie', canLogout: true })
+ )
+const locked = () =>
+ new Response(
+ JSON.stringify({ authed: false, mode: 'unauthenticated', canLogout: false })
+ )
+beforeEach(() => {
+ fetchMock.mockReset()
+ vi.stubGlobal('fetch', fetchMock)
+ useOperatorSession.setState({
+ state: 'authenticated',
+ status: { authed: true, mode: 'cookie', canLogout: true },
+ epoch: useOperatorSession.getState().epoch + 1,
+ })
+})
+afterEach(() => vi.unstubAllGlobals())
+it('preserves authentication on network failure and forbidden responses', async () => {
+ fetchMock
+ .mockRejectedValueOnce(new TypeError('offline'))
+ .mockResolvedValueOnce(new Response('', { status: 403 }))
+ await refreshOperatorSession()
+ await refreshOperatorSession()
+ expect(useOperatorSession.getState().state).toBe('authenticated')
+})
+it('ignores an old status response after a successful new login', async () => {
+ let resolve!: (response: Response) => void
+ fetchMock
+ .mockImplementationOnce(
+ () =>
+ new Promise<Response>((done) => {
+ resolve = done
+ })
+ )
+ .mockResolvedValueOnce(new Response('{}'))
+ .mockResolvedValueOnce(authed())
+ const old = refreshOperatorSession()
+ expect(await operatorLogin('token')).toBe(true)
+ resolve(locked())
+ await old
+ expect(useOperatorSession.getState().state).toBe('authenticated')
+})
+it('checks the server instead of trusting a stale cross-tab hint', async () => {
+ fetchMock.mockResolvedValueOnce(authed())
+ await refreshOperatorSession()
+ expect(useOperatorSession.getState().state).toBe('authenticated')
+})
+it('does not retry logout or fake successful logout after a network failure', async () => {
+ fetchMock
+ .mockRejectedValueOnce(new TypeError('offline'))
+ .mockResolvedValueOnce(authed())
+ await expect(operatorLogout()).rejects.toThrow('offline')
+ expect(
+ fetchMock.mock.calls.filter(([, options]) => options.method === 'POST')
+ ).toHaveLength(1)
+ expect(useOperatorSession.getState().state).toBe('authenticated')
+})
+it('blocks mutations during logout and locks only after confirmation', async () => {
+ let resolve!: (response: Response) => void
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<Response>((done) => {
+ resolve = done
+ })
+ )
+ const logout = operatorLogout()
+ expect(useOperatorSession.getState().state).toBe('logging-out')
+ resolve(new Response('{}'))
+ await logout
+ expect(useOperatorSession.getState().state).toBe('locked')
+})
diff --git a/src/renderer/lib/operator-auth.ts b/src/renderer/lib/operator-auth.ts
index d570a471..1cae79ad 100644
--- a/src/renderer/lib/operator-auth.ts
+++ b/src/renderer/lib/operator-auth.ts
@@ -1,30 +1,116 @@
-/**
- * Operator-auth client for the server (web) build (Spec 9). The web UI is the
- * operator control plane; it authenticates to `/rpc` with the machine-owner
- * operator token, exchanged once for an httpOnly session cookie the browser
- * then sends automatically. These helpers talk to the `/rpc/auth/*` endpoints
- * directly (not through the RPC command/query transport). Desktop never calls
- * them (it uses IPC).
- */
+import {
+ type OperatorStatus,
+ operatorStatusSchema,
+} from '@shared/schemas/operator-auth'
+import { create } from 'zustand'
const base = globalThis.location?.origin ?? ''
+type SessionState =
+ | 'checking'
+ | 'authenticated'
+ | 'locked'
+ | 'unavailable'
+ | 'logging-out'
+interface OperatorSession {
+ state: SessionState
+ status: OperatorStatus | null
+ epoch: number
+}
+export const useOperatorSession = create<OperatorSession>(() => ({
+ state: 'checking',
+ status: null,
+ epoch: 0,
+}))
+const resetters = new Set<() => void>()
+export function onOperatorSessionLost(reset: () => void): () => void {
+ resetters.add(reset)
+ return () => {
+ resetters.delete(reset)
+ }
+}
+let statusRequest = 0
+let hints: BroadcastChannel | null = null
-export async function getOperatorStatus(): Promise<boolean> {
+function locked(): void {
+ useOperatorSession.setState((s) => ({
+ state: 'locked',
+ status: null,
+ epoch: s.epoch + 1,
+ }))
+ for (const reset of resetters) {
+ try {
+ reset()
+ } catch {
+ /* One cache must not prevent other session cleanup. */
+ }
+ }
+}
+
+/** Responses are scoped to the login generation; a late 401 cannot evict a new login. */
+export async function refreshOperatorSession(
+ expectedEpoch = useOperatorSession.getState().epoch
+): Promise<void> {
+ if (
+ expectedEpoch !== useOperatorSession.getState().epoch ||
+ useOperatorSession.getState().state === 'logging-out'
+ )
+ return
+ const request = ++statusRequest
try {
const res = await fetch(`${base}/rpc/auth/status`, {
credentials: 'same-origin',
+ cache: 'no-store',
})
- if (!res.ok) return false
- const body = (await res.json()) as { authed?: boolean }
- return body.authed === true
+ if (!res.ok) throw new Error(`auth status ${res.status}`)
+ const status = operatorStatusSchema.parse(await res.json())
+ if (
+ request !== statusRequest ||
+ expectedEpoch !== useOperatorSession.getState().epoch
+ )
+ return
+ if (!status.authed) locked()
+ else useOperatorSession.setState({ state: 'authenticated', status })
} catch {
- return false
+ if (
+ request !== statusRequest ||
+ expectedEpoch !== useOperatorSession.getState().epoch
+ )
+ return
+ // An unavailable server is not evidence that its cookie has been revoked.
+ if (!useOperatorSession.getState().status?.authed)
+ useOperatorSession.setState({ state: 'unavailable' })
}
}
-/** Exchange the machine-owner token for a session cookie. Returns true on
- * success; the cookie is set httpOnly by the server (never seen by JS). */
+export function watchOperatorSession(): () => void {
+ const check = () => {
+ if (document.visibilityState === 'visible') void refreshOperatorSession()
+ }
+ if (typeof BroadcastChannel !== 'undefined') {
+ hints = new BroadcastChannel('motrix-operator-session')
+ hints.onmessage = () => {
+ void refreshOperatorSession()
+ }
+ }
+ window.addEventListener('focus', check)
+ document.addEventListener('visibilitychange', check)
+ return () => {
+ hints?.close()
+ hints = null
+ window.removeEventListener('focus', check)
+ document.removeEventListener('visibilitychange', check)
+ }
+}
+
+export async function getOperatorStatus(): Promise<boolean> {
+ await refreshOperatorSession()
+ return useOperatorSession.getState().state === 'authenticated'
+}
+
export async function operatorLogin(token: string): Promise<boolean> {
+ const epoch = useOperatorSession.getState().epoch + 1
+ statusRequest += 1
+ useOperatorSession.setState({ epoch })
try {
const res = await fetch(`${base}/rpc/auth/login`, {
method: 'POST',
@@ -32,8 +118,35 @@ export async function operatorLogin(token: string): Promise<boolean> {
credentials: 'same-origin',
body: JSON.stringify({ token }),
})
- return res.ok
+ if (!res.ok || epoch !== useOperatorSession.getState().epoch) return false
+ await refreshOperatorSession(epoch)
+ hints?.postMessage('changed')
+ return useOperatorSession.getState().state === 'authenticated'
} catch {
return false
}
}
+
+export async function operatorLogout(): Promise<void> {
+ const previous = useOperatorSession.getState()
+ if (!previous.status?.canLogout || previous.state !== 'authenticated') return
+ statusRequest += 1
+ useOperatorSession.setState({
+ state: 'logging-out',
+ epoch: previous.epoch + 1,
+ })
+ try {
+ const res = await fetch(`${base}/rpc/auth/logout`, {
+ method: 'POST',
+ credentials: 'same-origin',
+ })
+ if (!res.ok && res.status !== 401) throw new Error(`logout ${res.status}`)
+ locked()
+ hints?.postMessage('changed')
+ } catch (error) {
+ useOperatorSession.setState({ state: 'authenticated' })
+ // Do not retry a mutation. A status check resolves an ambiguous response.
+ void refreshOperatorSession()
+ throw error
+ }
+}
diff --git a/src/renderer/lib/parse-torrent-file.test.ts b/src/renderer/lib/parse-torrent-file.test.ts
new file mode 100644
index 00000000..a163aa11
--- /dev/null
+++ b/src/renderer/lib/parse-torrent-file.test.ts
@@ -0,0 +1,46 @@
+// @vitest-environment node
+
+import { readFileSync } from 'node:fs'
+import { MAX_TORRENT_FILE_SIZE } from '@shared/lib/torrent-meta'
+import { describe, expect, it, vi } from 'vitest'
+import { parseTorrentFile, readTorrentFile } from './parse-torrent-file'
+
+describe('browser torrent file reading', () => {
+ it('rejects an oversized File before reading or encoding it', async () => {
+ const file = new File([], 'large.torrent')
+ Object.defineProperty(file, 'size', { value: MAX_TORRENT_FILE_SIZE + 1 })
+ const read = vi.spyOn(file, 'arrayBuffer')
+ await expect(readTorrentFile(file)).rejects.toThrow(
+ 'Torrent file is too large'
+ )
+ expect(read).not.toHaveBeenCalled()
+ })
+
+ it('also bounds bytes passed directly to the parser', async () => {
+ await expect(
+ parseTorrentFile(new Uint8Array(MAX_TORRENT_FILE_SIZE + 1))
+ ).rejects.toThrow('Torrent file is too large')
+ })
+
+ it('preserves the original file bytes in the submitted Base64', async () => {
+ const bytes = readFileSync(
+ new URL('../../core/torrent/__fixtures__/test.torrent', import.meta.url)
+ )
+ const result = await readTorrentFile(new File([bytes], 'test.torrent'))
+ expect(result.base64).toBe(bytes.toString('base64'))
+ expect(result.meta.name).toBe('test-torrent')
+ expect(result.meta.files).toHaveLength(3)
+ })
+
+ it('validates metainfo before allocating its Base64 representation', async () => {
+ const encode = vi.spyOn(globalThis, 'btoa')
+ try {
+ await expect(
+ readTorrentFile(new File(['invalid'], 'bad.torrent'))
+ ).rejects.toThrow()
+ expect(encode).not.toHaveBeenCalled()
+ } finally {
+ encode.mockRestore()
+ }
+ })
+})
diff --git a/src/renderer/lib/parse-torrent-file.ts b/src/renderer/lib/parse-torrent-file.ts
index 5c554b09..9a8581b0 100644
--- a/src/renderer/lib/parse-torrent-file.ts
+++ b/src/renderer/lib/parse-torrent-file.ts
@@ -1,5 +1,6 @@
import {
MAX_TORRENT_BASE64_SIZE,
+ MAX_TORRENT_FILE_SIZE,
projectTorrentMeta,
} from '@shared/lib/torrent-meta'
import type { TorrentMeta } from '@shared/types/torrent'
@@ -35,10 +36,14 @@ export async function parseTorrentFile(
}
export async function readTorrentFile(file: File): Promise<ParsedTorrentFile> {
+ if (file.size > MAX_TORRENT_FILE_SIZE) {
+ throw new Error('Torrent file is too large')
+ }
const bytes = new Uint8Array(await file.arrayBuffer())
+ const meta = await parseTorrentFile(bytes)
return {
name: file.name,
base64: bytesToBase64(bytes),
- meta: await parseTorrentFile(bytes),
+ meta,
}
}
diff --git a/src/renderer/lib/transport/http-ws.ts b/src/renderer/lib/transport/http-ws.ts
index f67ce3e3..b8e63125 100644
--- a/src/renderer/lib/transport/http-ws.ts
+++ b/src/renderer/lib/transport/http-ws.ts
@@ -1,3 +1,7 @@
+import {
+ refreshOperatorSession,
+ useOperatorSession,
+} from '@renderer/lib/operator-auth'
import { ErrorCode } from '@shared/errors'
import { BridgeCommands, BridgeQueries } from '@shared/protocol/bridge'
import {
@@ -58,6 +62,14 @@ export class HttpWsTransport implements Transport {
this.WSCtor =
opts.WebSocketCtor ??
(typeof WebSocket !== 'undefined' ? WebSocket : undefined)
+ useOperatorSession.subscribe((state, previous) => {
+ if (state.state === 'locked') this.stopSocket()
+ else if (
+ state.state === 'authenticated' &&
+ previous.state !== 'authenticated'
+ )
+ this.ensureSocket()
+ })
this.reconnectDelaysMs =
opts.reconnectDelaysMs?.length === 0
? [0]
@@ -65,6 +77,9 @@ export class HttpWsTransport implements Transport {
}
async invoke(channel: AnyChannel, ...args: unknown[]): Promise<unknown> {
+ const session = useOperatorSession.getState()
+ if (session.state === 'locked' || session.state === 'logging-out')
+ throw new Error('Operator session is locked')
const kind = rpcKindFor(channel)
const isInspectorActivity = channel === Queries.GetTaskInspectorActivity
const res = await this.fetchFn(
@@ -78,6 +93,7 @@ export class HttpWsTransport implements Transport {
body: JSON.stringify({ args }),
}
)
+ if (res.status === 401) void refreshOperatorSession(session.epoch)
if (!res.ok) {
if (isInspectorActivity) {
throw new TransportError(
@@ -111,6 +127,10 @@ export class HttpWsTransport implements Transport {
if (!this.hasEventListeners()) this.stopSocket()
}
+ getConnectionState(): TransportConnectionState {
+ return this.connectionState
+ }
+
onConnectionChange(cb: TransportConnectionListener): () => void {
this.connectionListeners.add(cb)
return () => {
@@ -126,6 +146,8 @@ export class HttpWsTransport implements Transport {
private ensureSocket(): void {
if (
+ useOperatorSession.getState().state === 'locked' ||
+ useOperatorSession.getState().state === 'logging-out' ||
this.socket ||
this.reconnectTimer !== null ||
!this.WSCtor ||
@@ -163,6 +185,7 @@ export class HttpWsTransport implements Transport {
if (!this.isCurrentSocket(socket, epoch)) return
this.socket = null
this.publishConnectionState('disconnected')
+ void refreshOperatorSession()
this.scheduleReconnect()
})
}
diff --git a/src/renderer/lib/transport/types.ts b/src/renderer/lib/transport/types.ts
index 3abd3047..a6994944 100644
--- a/src/renderer/lib/transport/types.ts
+++ b/src/renderer/lib/transport/types.ts
@@ -26,6 +26,7 @@ export interface Transport {
* Optional because Electron IPC has no renderer-owned connection lifecycle.
* Web transports return an unsubscribe function.
*/
+ getConnectionState?(): TransportConnectionState
onConnectionChange?(cb: TransportConnectionListener): () => void
platform: NodeJS.Platform | 'web'
}
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog-host.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog-host.tsx
new file mode 100644
index 00000000..2611e6e1
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog-host.tsx
@@ -0,0 +1,21 @@
+import { RemoveTasksDialog } from './remove-tasks-dialog'
+import { useRemoveTasksStore } from './remove-tasks-store'
+import { useTaskActions } from './use-task-actions'
+
+const EMPTY = [] as const
+export function RemoveTasksDialogHost() {
+ const state = useRemoveTasksStore()
+ const actions = useTaskActions(EMPTY)
+ return (
+ <RemoveTasksDialog
+ open={state.open}
+ busy={state.busy}
+ selected={state.targets}
+ preCheckDeleteFiles={state.preCheckDeleteFiles}
+ onOpenChange={(open) => {
+ if (!open) actions.closeRemoveDialog()
+ }}
+ onConfirm={(deleteFiles) => void actions.confirmRemove(deleteFiles)}
+ />
+ )
+}
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
index e9e6cb02..0d9c0d4c 100644
--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx
@@ -12,11 +12,12 @@ import { useByteFormat } from '@renderer/hooks/use-byte-format'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
import { AlertTriangle } from 'lucide-react'
-import { useEffect, useId, useState } from 'react'
+import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
export interface RemoveTasksDialogProps {
open: boolean
+ busy?: boolean
selected: readonly DownloadTask[]
preCheckDeleteFiles: boolean
onOpenChange: (open: boolean) => void
@@ -81,6 +82,7 @@ function estimateDiskUsage(selected: readonly DownloadTask[]): number {
export function RemoveTasksDialog({
open,
+ busy = false,
selected,
preCheckDeleteFiles,
onOpenChange,
@@ -90,6 +92,7 @@ export function RemoveTasksDialog({
const { t } = useTranslation()
const checkboxId = useId()
+ const cancelRef = useRef<HTMLButtonElement>(null)
// Deleting files is always an explicit opt-in (or the Shift shortcut via
// preCheckDeleteFiles) — even Error/Queued selections may hold partial
// data on disk, so no task status ever pre-checks the box.
@@ -105,13 +108,19 @@ export function RemoveTasksDialog({
const title = buildTitle(selected, t)
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!busy) onOpenChange(next)
+ }}
+ >
+ <DialogContent initialFocus={cancelRef} showCloseButton={!busy}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<div className="flex items-center gap-2 text-sm">
<Checkbox
+ disabled={busy}
id={checkboxId}
checked={deleteFiles}
onCheckedChange={(v) => setDeleteFiles(Boolean(v))}
@@ -131,12 +140,19 @@ export function RemoveTasksDialog({
</div>
)}
<DialogFooter>
- <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
+ <Button
+ ref={cancelRef}
+ disabled={busy}
+ size="sm"
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ >
{t('panel.downloads.action.cancel')}
</Button>
<Button
size="sm"
variant="destructive"
+ disabled={busy || selected.length === 0}
onClick={() => onConfirm(deleteFiles)}
>
{t('panel.downloads.action.remove')}
diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-store.ts b/src/renderer/routes/downloads/inspector/remove-tasks-store.ts
new file mode 100644
index 00000000..6595e022
--- /dev/null
+++ b/src/renderer/routes/downloads/inspector/remove-tasks-store.ts
@@ -0,0 +1,19 @@
+import { onOperatorSessionLost } from '@renderer/lib/operator-auth'
+import type { DownloadTask } from '@shared/types/task'
+import { create } from 'zustand'
+
+export const useRemoveTasksStore = create<{
+ open: boolean
+ preCheckDeleteFiles: boolean
+ targets: readonly DownloadTask[]
+ busy: boolean
+}>(() => ({
+ open: false,
+ preCheckDeleteFiles: false,
+ targets: [],
+ busy: false,
+}))
+
+onOperatorSessionLost(() =>
+ useRemoveTasksStore.setState({ open: false, targets: [], busy: false })
+)
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
index bdf1536a..c5ef4182 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.test.tsx
@@ -1,9 +1,29 @@
+import { RemoveTasksDialogHost } from '@renderer/routes/downloads/inspector/remove-tasks-dialog-host'
+import { useRemoveTasksStore } from '@renderer/routes/downloads/inspector/remove-tasks-store'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import {
+ fireEvent,
+ render as renderBase,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import type { ReactElement } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+function render(element: ReactElement) {
+ return renderBase(
+ <>
+ <RemoveTasksDialogHost />
+ {element}
+ </>
+ )
+}
+beforeEach(() =>
+ useRemoveTasksStore.setState({ open: false, targets: [], busy: false })
+)
+
vi.mock('@renderer/lib/transport', () => ({
transport: { invoke: vi.fn().mockResolvedValue({ ok: true }) },
}))
diff --git a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
index a2661442..fbddf653 100644
--- a/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
+++ b/src/renderer/routes/downloads/inspector/task-inspector-action-bar.tsx
@@ -25,7 +25,6 @@ import type React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { canRevealTaskFolder } from './can-reveal-task-folder'
-import { RemoveTasksDialog } from './remove-tasks-dialog'
import { copyTaskUrls } from './task-copy-url'
import { useTaskActions } from './use-task-actions'
@@ -214,166 +213,154 @@ export function TaskInspectorActionBar({
}
return (
- <>
- <div className="flex shrink-0 items-center gap-2 border-b border-border/50 px-4 py-2">
- {actions.pauseCount > 0 && (
- <CountedButton
- label={t('panel.downloads.action.pause')}
- total={actions.total}
- count={actions.pauseCount}
- tooltipSingle={t('panel.downloads.action.pause')}
- tooltipBatch={t('panel.downloads.action.pauseTooltipBatch', {
- n: actions.pauseCount,
- total: actions.total,
- })}
- icon={<Pause />}
- onClick={() => void actions.onPause()}
- />
- )}
- {actions.resumeCount > 0 && (
- <CountedButton
- label={t('panel.downloads.action.resume')}
- total={actions.total}
- count={actions.resumeCount}
- tooltipSingle={t('panel.downloads.action.resume')}
- tooltipBatch={t('panel.downloads.action.resumeTooltipBatch', {
- n: actions.resumeCount,
- total: actions.total,
- })}
- icon={<Play className={rtlMirror} />}
- onClick={() => void actions.onResume()}
- />
- )}
- {actions.retryCount > 0 && (
- <CountedButton
- label={t('panel.downloads.action.retry')}
- total={actions.total}
- count={actions.retryCount}
- tooltipSingle={
- alt && actions.total === 1
- ? t('panel.downloads.action.retryWithDialog')
- : t('panel.downloads.action.retry')
- }
- tooltipBatch={t('panel.downloads.action.retryTooltipBatch', {
- n: actions.retryCount,
- total: actions.total,
- })}
- icon={<Repeat2 />}
- onClick={(e) => void actions.onRetry({ alt: e.altKey })}
- />
- )}
- {actions.reseedCount > 0 && (
- <CountedButton
- label={t('panel.downloads.action.reseed')}
- total={actions.total}
- count={actions.reseedCount}
- tooltipSingle={
- alt && actions.total === 1
- ? t('panel.downloads.action.retryWithDialog')
- : t('panel.downloads.action.reseed')
- }
- tooltipBatch={t('panel.downloads.action.reseedTooltipBatch', {
- n: actions.reseedCount,
- total: actions.total,
- })}
- icon={<RadioTower />}
- onClick={(e) => void actions.onReseed({ alt: e.altKey })}
- />
- )}
- {actions.stopSeedingCount > 0 && (
- <CountedButton
- label={t('panel.downloads.action.stopSeeding')}
- total={actions.total}
- count={actions.stopSeedingCount}
- tooltipSingle={t('panel.downloads.action.stopSeeding')}
- tooltipBatch={t('panel.downloads.action.stopSeedingTooltipBatch', {
- n: actions.stopSeedingCount,
- total: actions.total,
- })}
- icon={<Square />}
- onClick={() => void actions.onStopSeeding()}
- />
- )}
+ <div className="flex shrink-0 items-center gap-2 border-b border-border/50 px-4 py-2">
+ {actions.pauseCount > 0 && (
+ <CountedButton
+ label={t('panel.downloads.action.pause')}
+ total={actions.total}
+ count={actions.pauseCount}
+ tooltipSingle={t('panel.downloads.action.pause')}
+ tooltipBatch={t('panel.downloads.action.pauseTooltipBatch', {
+ n: actions.pauseCount,
+ total: actions.total,
+ })}
+ icon={<Pause />}
+ onClick={() => void actions.onPause()}
+ />
+ )}
+ {actions.resumeCount > 0 && (
+ <CountedButton
+ label={t('panel.downloads.action.resume')}
+ total={actions.total}
+ count={actions.resumeCount}
+ tooltipSingle={t('panel.downloads.action.resume')}
+ tooltipBatch={t('panel.downloads.action.resumeTooltipBatch', {
+ n: actions.resumeCount,
+ total: actions.total,
+ })}
+ icon={<Play className={rtlMirror} />}
+ onClick={() => void actions.onResume()}
+ />
+ )}
+ {actions.retryCount > 0 && (
+ <CountedButton
+ label={t('panel.downloads.action.retry')}
+ total={actions.total}
+ count={actions.retryCount}
+ tooltipSingle={
+ alt && actions.total === 1
+ ? t('panel.downloads.action.retryWithDialog')
+ : t('panel.downloads.action.retry')
+ }
+ tooltipBatch={t('panel.downloads.action.retryTooltipBatch', {
+ n: actions.retryCount,
+ total: actions.total,
+ })}
+ icon={<Repeat2 />}
+ onClick={(e) => void actions.onRetry({ alt: e.altKey })}
+ />
+ )}
+ {actions.reseedCount > 0 && (
+ <CountedButton
+ label={t('panel.downloads.action.reseed')}
+ total={actions.total}
+ count={actions.reseedCount}
+ tooltipSingle={
+ alt && actions.total === 1
+ ? t('panel.downloads.action.retryWithDialog')
+ : t('panel.downloads.action.reseed')
+ }
+ tooltipBatch={t('panel.downloads.action.reseedTooltipBatch', {
+ n: actions.reseedCount,
+ total: actions.total,
+ })}
+ icon={<RadioTower />}
+ onClick={(e) => void actions.onReseed({ alt: e.altKey })}
+ />
+ )}
+ {actions.stopSeedingCount > 0 && (
+ <CountedButton
+ label={t('panel.downloads.action.stopSeeding')}
+ total={actions.total}
+ count={actions.stopSeedingCount}
+ tooltipSingle={t('panel.downloads.action.stopSeeding')}
+ tooltipBatch={t('panel.downloads.action.stopSeedingTooltipBatch', {
+ n: actions.stopSeedingCount,
+ total: actions.total,
+ })}
+ icon={<Square />}
+ onClick={() => void actions.onStopSeeding()}
+ />
+ )}
- {single && single.status === TaskStatus.MetadataReady && (
- <MagnetFileSelectionButton task={single} />
- )}
+ {single && single.status === TaskStatus.MetadataReady && (
+ <MagnetFileSelectionButton task={single} />
+ )}
- {single &&
- __MOTRIX_TARGET__ === 'electron' &&
- canOpenTaskFile(single) && <OpenTaskFileButton task={single} />}
- {single &&
- __MOTRIX_TARGET__ === 'electron' &&
- canRevealTaskFolder(single) && (
- <Button
- size="xs"
- variant="outline"
- onClick={() =>
- transport.invoke(Commands.RevealInFolder, {
- taskId: single.id,
- })
- }
- >
- <FolderOpen />
- {t('panel.downloads.action.openFolder')}
- </Button>
- )}
- {single && (
- <CopyButton
+ {single &&
+ __MOTRIX_TARGET__ === 'electron' &&
+ canOpenTaskFile(single) && <OpenTaskFileButton task={single} />}
+ {single &&
+ __MOTRIX_TARGET__ === 'electron' &&
+ canRevealTaskFolder(single) && (
+ <Button
size="xs"
variant="outline"
onClick={() =>
- copyTaskUrl(single, () =>
- toast.add({
- title: t('panel.downloads.action.copyUrlFailed'),
- type: 'error',
- })
- )
+ transport.invoke(Commands.RevealInFolder, {
+ taskId: single.id,
+ })
}
>
- {t('panel.downloads.action.copyUrl')}
- </CopyButton>
+ <FolderOpen />
+ {t('panel.downloads.action.openFolder')}
+ </Button>
)}
-
- <CountedButton
- label={t('panel.downloads.action.remove')}
- total={actions.total}
- count={actions.removeCount}
- tooltipSingle={
- shift
- ? t('panel.downloads.action.removeWithFilesShift')
- : t('panel.downloads.action.remove')
+ {single && (
+ <CopyButton
+ size="xs"
+ variant="outline"
+ onClick={() =>
+ copyTaskUrl(single, () =>
+ toast.add({
+ title: t('panel.downloads.action.copyUrlFailed'),
+ type: 'error',
+ })
+ )
}
- tooltipBatch={t('panel.downloads.action.removeTooltipBatch', {
- n: actions.removeCount,
- total: actions.total,
- })}
- icon={<Trash2 />}
- destructive
- onClick={(e) => actions.onRemove({ shift: e.shiftKey })}
- />
-
- {resizeHandle}
- <Button
- size="icon-xs"
- variant="ghost"
- className="ms-auto"
- aria-label={t('common.close')}
- onClick={onClose}
>
- <ChevronDown />
- </Button>
- </div>
+ {t('panel.downloads.action.copyUrl')}
+ </CopyButton>
+ )}
- <RemoveTasksDialog
- open={actions.removeDialog.open}
- selected={actions.removeTargets}
- preCheckDeleteFiles={actions.removeDialog.preCheckDeleteFiles}
- onOpenChange={(open) => {
- if (!open) actions.closeRemoveDialog()
- }}
- onConfirm={(deleteFiles) => void actions.confirmRemove(deleteFiles)}
+ <CountedButton
+ label={t('panel.downloads.action.remove')}
+ total={actions.total}
+ count={actions.removeCount}
+ tooltipSingle={
+ shift
+ ? t('panel.downloads.action.removeWithFilesShift')
+ : t('panel.downloads.action.remove')
+ }
+ tooltipBatch={t('panel.downloads.action.removeTooltipBatch', {
+ n: actions.removeCount,
+ total: actions.total,
+ })}
+ icon={<Trash2 />}
+ destructive
+ onClick={(e) => actions.onRemove({ shift: e.shiftKey })}
/>
- </>
+
+ {resizeHandle}
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ className="ms-auto"
+ aria-label={t('common.close')}
+ onClick={onClose}
+ >
+ <ChevronDown />
+ </Button>
+ </div>
)
}
diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.ts b/src/renderer/routes/downloads/inspector/use-task-actions.ts
index 9d6316f3..73b3cac6 100644
--- a/src/renderer/routes/downloads/inspector/use-task-actions.ts
+++ b/src/renderer/routes/downloads/inspector/use-task-actions.ts
@@ -1,4 +1,6 @@
import { toast } from '@renderer/components/ui/toast'
+import { taskWritesAvailable } from '@renderer/features/application-menu/task-context'
+import { getTaskListSnapshot } from '@renderer/hooks/use-task-list'
import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { transport } from '@renderer/lib/transport'
import { type CommandChannel, Commands } from '@shared/protocol/commands'
@@ -22,6 +24,7 @@ import {
} from '@shared/types/task-actions'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useRemoveTasksStore } from './remove-tasks-store'
export interface RemoveDialogState {
open: boolean
@@ -157,18 +160,20 @@ export interface TaskActionsState {
confirmRemove: (deleteFiles: boolean) => Promise<void>
}
+function resolveLatest(targets: readonly DownloadTask[]) {
+ const snapshot = getTaskListSnapshot()
+ if (!snapshot.hasReadySnapshot) return targets
+ const ids = new Set(targets.map((task) => task.id))
+ return snapshot.tasks.filter((task) => ids.has(task.id))
+}
+
export function useTaskActions(
selected: readonly DownloadTask[]
): TaskActionsState {
const { t } = useTranslation()
const [moving, setMoving] = useState(false)
- const [removeDialog, setRemoveDialog] = useState<RemoveDialogState>({
- open: false,
- preCheckDeleteFiles: false,
- })
- const [removeTargets, setRemoveTargets] = useState<readonly DownloadTask[]>(
- []
- )
+ const removeDialog = useRemoveTasksStore()
+ const removeTargets = removeDialog.targets
const counts = useMemo(() => {
let pauseCount = 0
@@ -224,9 +229,16 @@ export function useTaskActions(
[t]
)
+ const readyToWrite = useCallback(() => {
+ if (transport.platform !== 'web' || taskWritesAvailable()) return true
+ toast.add({ title: t('applicationMenu.actionFailed'), type: 'error' })
+ return false
+ }, [t])
+
const dispatchSubset = useCallback(
async (cmd: CommandChannel, predicate: (task: DownloadTask) => boolean) => {
- const targets = selected.filter(predicate)
+ if (!readyToWrite()) return
+ const targets = resolveLatest(selected).filter(predicate)
if (targets.length === 0) return
const results = await invokeBulk(
cmd,
@@ -235,7 +247,7 @@ export function useTaskActions(
)
reportPartial(results)
},
- [selected, reportPartial]
+ [selected, reportPartial, readyToWrite]
)
const onPause = useCallback(
@@ -250,7 +262,8 @@ export function useTaskActions(
const onMove = useCallback(
async (direction: MoveTasksPayload['direction']) => {
- const targets = selected.filter(canMoveInQueue)
+ if (!readyToWrite()) return
+ const targets = resolveLatest(selected).filter(canMoveInQueue)
if (moving || !targets.length) return
setMoving(true)
try {
@@ -294,7 +307,7 @@ export function useTaskActions(
setMoving(false)
}
},
- [selected, moving, reportPartial, t]
+ [selected, moving, reportPartial, t, readyToWrite]
)
const onStopSeeding = useCallback(
@@ -352,32 +365,48 @@ export function useTaskActions(
const onRemove = useCallback(
(modifier?: { shift: boolean }) => {
- setRemoveTargets([...selected])
- setRemoveDialog({
+ if (useRemoveTasksStore.getState().busy || !readyToWrite()) return
+ const targets = resolveLatest(selected).filter(canRemove)
+ if (!targets.length) return
+ useRemoveTasksStore.setState({
+ targets,
open: true,
preCheckDeleteFiles: modifier?.shift ?? false,
})
},
- [selected]
+ [selected, readyToWrite]
)
const closeRemoveDialog = useCallback(() => {
- setRemoveDialog({ open: false, preCheckDeleteFiles: false })
+ if (!useRemoveTasksStore.getState().busy)
+ useRemoveTasksStore.setState({
+ open: false,
+ preCheckDeleteFiles: false,
+ targets: [],
+ })
}, [])
const confirmRemove = useCallback(
async (deleteFiles: boolean) => {
- const targets = removeTargets.filter(canRemove)
+ if (useRemoveTasksStore.getState().busy || !readyToWrite()) return
+ useRemoveTasksStore.setState({ busy: true })
+ const targets = resolveLatest(removeTargets).filter(canRemove)
if (targets.length > 0) {
const results = await invokeBulk(Commands.RemoveTasks, targets, {
taskIds: targets.map((task) => task.id),
deleteWithFiles: deleteFiles,
})
+ if (useRemoveTasksStore.getState().targets !== removeTargets) return
reportPartial(results)
}
- setRemoveDialog({ open: false, preCheckDeleteFiles: false })
+ useRemoveTasksStore.setState({
+ open: false,
+ preCheckDeleteFiles: false,
+ targets: [],
+ busy: false,
+ })
},
- [removeTargets, reportPartial]
+ [removeTargets, reportPartial, readyToWrite]
)
return {
diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsx
index a8ae0fa3..a616bd2f 100644
--- a/src/renderer/routes/downloads/task-actions-menu.test.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx
@@ -1,3 +1,7 @@
+import { RemoveTasksDialogHost } from '@renderer/routes/downloads/inspector/remove-tasks-dialog-host'
+import { useRemoveTasksStore } from '@renderer/routes/downloads/inspector/remove-tasks-store'
+import { render as renderBase } from '@testing-library/react'
+import type { ReactElement } from 'react'
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import { createSelectionStore } from '@renderer/components/desktop-kit/selection/create-selection-store'
@@ -10,12 +14,24 @@ import { Commands } from '@shared/protocol/commands'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TaskActionsMenu } from './task-actions-menu'
import { useDownloadsView } from './view-preferences'
+function render(element: ReactElement) {
+ return renderBase(
+ <>
+ <RemoveTasksDialogHost />
+ {element}
+ </>
+ )
+}
+beforeEach(() =>
+ useRemoveTasksStore.setState({ open: false, targets: [], busy: false })
+)
+
vi.mock('@renderer/lib/transport', () => ({
transport: {
invoke: vi.fn().mockResolvedValue({ failed: [] }),
diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsx
index e7989e27..d360abe0 100644
--- a/src/renderer/routes/downloads/task-actions-menu.tsx
+++ b/src/renderer/routes/downloads/task-actions-menu.tsx
@@ -38,7 +38,6 @@ import {
import { useTranslation } from 'react-i18next'
import { DownloadsToolbarButton } from './downloads-toolbar-button'
import { canRevealTaskFolder } from './inspector/can-reveal-task-folder'
-import { RemoveTasksDialog } from './inspector/remove-tasks-dialog'
import { copyTaskUrls } from './inspector/task-copy-url'
import { taskErrorReport } from './inspector/task-error-report'
import { useTaskActions } from './inspector/use-task-actions'
@@ -427,58 +426,9 @@ export function TaskActionsMenu({
<DropdownMenuGroup>{group.content}</DropdownMenuGroup>
</Fragment>
))
- const dialog = (
- <RemoveTasksDialog
- open={actions.removeDialog.open}
- selected={actions.removeTargets}
- preCheckDeleteFiles={actions.removeDialog.preCheckDeleteFiles}
- onOpenChange={(open) => {
- if (!open) actions.closeRemoveDialog()
- }}
- onConfirm={(deleteFiles) => void actions.confirmRemove(deleteFiles)}
- />
- )
if (children)
return (
- <>
- <ContextMenu
- open={menuOpen}
- onOpenChange={(open) => {
- if (open) prepare()
- else setTargetIds(null)
- setMenuOpen(open)
- }}
- >
- <ContextMenuTrigger
- render={children}
- onKeyDownCapture={handleShortcut}
- onCopyCapture={handleCopy}
- onContextMenuCapture={(event) => {
- const row = (event.target as Element).closest<HTMLElement>(
- '[data-task-id]'
- )
- if (!row?.dataset.taskId) return
- const state = selection.getState()
- if (!state.selectedIds.has(row.dataset.taskId))
- state.select(row.dataset.taskId)
- state.focus(row.dataset.taskId)
- prepare()
- }}
- />
- <ContextMenuContent
- onKeyDownCapture={handleShortcut}
- onCopyCapture={handleCopy}
- className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
- >
- {items}
- </ContextMenuContent>
- </ContextMenu>
- {dialog}
- </>
- )
- return (
- <>
- <DropdownMenu
+ <ContextMenu
open={menuOpen}
onOpenChange={(open) => {
if (open) prepare()
@@ -486,30 +436,62 @@ export function TaskActionsMenu({
setMenuOpen(open)
}}
>
- <DropdownMenuTrigger
+ <ContextMenuTrigger
+ render={children}
onKeyDownCapture={handleShortcut}
onCopyCapture={handleCopy}
- render={
- <DownloadsToolbarButton
- aria-label={t('panel.downloads.view.taskActions')}
- title={t('panel.downloads.view.taskActions')}
- ref={triggerRef}
- />
- }
- >
- <Ellipsis className="size-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent
+ onContextMenuCapture={(event) => {
+ const row = (event.target as Element).closest<HTMLElement>(
+ '[data-task-id]'
+ )
+ if (!row?.dataset.taskId) return
+ const state = selection.getState()
+ if (!state.selectedIds.has(row.dataset.taskId))
+ state.select(row.dataset.taskId)
+ state.focus(row.dataset.taskId)
+ prepare()
+ }}
+ />
+ <ContextMenuContent
onKeyDownCapture={handleShortcut}
onCopyCapture={handleCopy}
- align="end"
- data-menu-density="compact"
className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
>
{items}
- </DropdownMenuContent>
- </DropdownMenu>
- {dialog}
- </>
+ </ContextMenuContent>
+ </ContextMenu>
+ )
+ return (
+ <DropdownMenu
+ open={menuOpen}
+ onOpenChange={(open) => {
+ if (open) prepare()
+ else setTargetIds(null)
+ setMenuOpen(open)
+ }}
+ >
+ <DropdownMenuTrigger
+ onKeyDownCapture={handleShortcut}
+ onCopyCapture={handleCopy}
+ render={
+ <DownloadsToolbarButton
+ aria-label={t('panel.downloads.view.taskActions')}
+ title={t('panel.downloads.view.taskActions')}
+ ref={triggerRef}
+ />
+ }
+ >
+ <Ellipsis className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ onKeyDownCapture={handleShortcut}
+ onCopyCapture={handleCopy}
+ align="end"
+ data-menu-density="compact"
+ className="w-max min-w-48 max-w-[min(18rem,var(--available-width))]"
+ >
+ {items}
+ </DropdownMenuContent>
+ </DropdownMenu>
)
}
diff --git a/src/renderer/routes/downloads/task-list-panel.tsx b/src/renderer/routes/downloads/task-list-panel.tsx
index 1b32eadb..1977386d 100644
--- a/src/renderer/routes/downloads/task-list-panel.tsx
+++ b/src/renderer/routes/downloads/task-list-panel.tsx
@@ -1,3 +1,4 @@
+import { registerDownloadsMenuContext } from '@renderer/features/application-menu/task-context'
import './downloads-list.css'
import { useSelectableList } from '@renderer/components/desktop-kit/hooks/use-selectable-list'
import { MarqueeOverlay } from '@renderer/components/desktop-kit/marquee-selection/marquee-overlay'
@@ -61,6 +62,14 @@ export function TaskListPanel({
})
}, [tasks, sorted, frozenIds])
const gridRef = useRef<HTMLDivElement>(null)
+ useEffect(
+ () =>
+ registerDownloadsMenuContext(
+ () => gridRef.current?.focus({ preventScroll: true }),
+ `${filter}:${search}`
+ ),
+ [filter, search]
+ )
const [active, setActive] = useState(false)
const pointerFocus = useRef(false)
const [keyboardFocus, setKeyboardFocus] = useState(false)
@@ -90,6 +99,7 @@ export function TaskListPanel({
: state.items[state.focusedIndex]?.id
)
useIpcEvent(Events.TaskSelectAll, () => {
+ if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
selection.getState().selectAll()
window.getSelection()?.removeAllRanges()
pointerFocus.current = true
diff --git a/src/renderer/routes/downloads/task-menu-shortcuts.test.ts b/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
index 689b14e4..594f11c6 100644
--- a/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
+++ b/src/renderer/routes/downloads/task-menu-shortcuts.test.ts
@@ -18,10 +18,7 @@ describe('task menu shortcuts', () => {
it('uses Ctrl and Delete on Windows/Linux, and the web new-task override on Mac', () => {
expect(taskMenuShortcuts(false, true).copyUrl.label).toBe('Ctrl+C')
expect(taskMenuShortcuts(false, true).remove.label).toBe('Delete')
- expect(taskMenuShortcuts(true, false).newTask).toMatchObject({
- label: '⌃N',
- aria: 'Control+N',
- })
+ expect(taskMenuShortcuts(true, false).newTask).toBeNull()
})
it('matches exact modifiers and never treats bare macOS Backspace as Remove', () => {
const event = {
diff --git a/src/renderer/routes/settings/cards/about-dialog.tsx b/src/renderer/routes/settings/cards/about-dialog.tsx
index f0500aaf..0e4f105f 100644
--- a/src/renderer/routes/settings/cards/about-dialog.tsx
+++ b/src/renderer/routes/settings/cards/about-dialog.tsx
@@ -8,6 +8,7 @@ import {
DialogTitle,
} from '@renderer/components/ui/dialog'
import { EXTERNAL_URLS } from '@shared/external-urls'
+import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { AppUpdateSection, shouldShowAppUpdate } from './app-update-section'
import { AutomaticUpdateSetting } from './automatic-update-setting'
@@ -40,6 +41,7 @@ export function AboutDialog({
descKey,
}: SettingsCardDialogProps) {
const { t } = useTranslation()
+ const heading = useRef<HTMLHeadingElement>(null)
const metadata = __MOTRIX_APP_METADATA__
const showUpdates = shouldShowAppUpdate(__MOTRIX_TARGET__)
@@ -47,7 +49,7 @@ export function AboutDialog({
<Dialog open={open} onOpenChange={(value) => !value && onClose()}>
<DialogContent
className="flex max-h-[calc(100svh-2rem)] flex-col gap-0 overflow-hidden rounded-2xl border-border/70 bg-background/95 p-0 shadow-2xl backdrop-blur-xl sm:max-w-[700px]"
- initialFocus={false}
+ initialFocus={heading}
showCloseButton={false}
>
<DialogHeader className="sr-only">
@@ -70,6 +72,8 @@ export function AboutDialog({
<div className="flex flex-wrap items-baseline gap-x-2.5 gap-y-0.5">
<h2
id="about-product-name"
+ ref={heading}
+ tabIndex={-1}
className="text-[1.35rem] leading-tight font-semibold tracking-[-0.018em]"
>
{metadata.name}
diff --git a/src/renderer/shortcuts/executor.test.ts b/src/renderer/shortcuts/executor.test.ts
deleted file mode 100644
index a5550233..00000000
--- a/src/renderer/shortcuts/executor.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { type CommandId, CommandIds } from '@shared/commands-catalog'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { executeCommand } from './executor'
-
-describe('executeCommand', () => {
- const fetchMock = vi.fn()
- let warnSpy: ReturnType<typeof vi.spyOn>
-
- beforeEach(() => {
- window.location.hash = ''
- fetchMock.mockReset()
- fetchMock.mockResolvedValue({ ok: true, status: 204 })
- vi.stubGlobal('fetch', fetchMock)
- warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
- })
-
- afterEach(() => {
- vi.unstubAllGlobals()
- warnSpy.mockRestore()
- })
-
- it.each([
- [CommandIds.NavigateTaskList, '#/downloads'],
- [CommandIds.AppOpenPreferences, '#/settings'],
- [CommandIds.TaskNew, '#/downloads?addTask=url'],
- ])('navigates %s to %s', async (command, hash) => {
- await executeCommand(command)
- expect(window.location.hash).toBe(hash)
- expect(fetchMock).not.toHaveBeenCalled()
- })
-
- it.each([
- [CommandIds.TaskPauseAll, '/api/tasks/pause-all'],
- [CommandIds.TaskResumeAll, '/api/tasks/resume-all'],
- ])(
- 'posts %s through the authenticated control plane',
- async (command, path) => {
- await executeCommand(command)
-
- expect(fetchMock).toHaveBeenCalledWith(path, {
- method: 'POST',
- credentials: 'same-origin',
- })
- }
- )
-
- it('warns when the control-plane request fails', async () => {
- fetchMock.mockResolvedValueOnce({ ok: false, status: 503 })
-
- await executeCommand(CommandIds.TaskPauseAll)
-
- expect(warnSpy).toHaveBeenCalledWith(
- '[shortcuts] /api/tasks/pause-all -> 503'
- )
- })
-
- it('warns when a command has no web implementation', async () => {
- const unsupported = CommandIds.AppShowAbout as CommandId
-
- await executeCommand(unsupported)
-
- expect(warnSpy).toHaveBeenCalledWith(
- "[shortcuts] command 'motrix.app.showAbout' has no web executor"
- )
- })
-})
diff --git a/src/renderer/shortcuts/executor.ts b/src/renderer/shortcuts/executor.ts
deleted file mode 100644
index bf6bcbaa..00000000
--- a/src/renderer/shortcuts/executor.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { type CommandId, CommandIds } from '@shared/commands-catalog'
-
-async function post(path: string): Promise<void> {
- // The /api control-plane routes require the operator session cookie (Spec 9);
- // same-origin is the fetch default but be explicit.
- const res = await fetch(path, { method: 'POST', credentials: 'same-origin' })
- if (!res.ok) {
- console.warn(`[shortcuts] ${path} -> ${res.status}`)
- }
-}
-
-export async function executeCommand(id: CommandId): Promise<void> {
- switch (id) {
- case CommandIds.NavigateTaskList:
- window.location.hash = '#/downloads'
- return
- case CommandIds.AppOpenPreferences:
- window.location.hash = '#/settings'
- return
- case CommandIds.TaskNew:
- window.location.hash = '#/downloads?addTask=url'
- return
- case CommandIds.TaskPauseAll:
- await post('/api/tasks/pause-all')
- return
- case CommandIds.TaskResumeAll:
- await post('/api/tasks/resume-all')
- return
- default:
- console.warn(`[shortcuts] command '${id}' has no web executor`)
- }
-}
diff --git a/src/renderer/shortcuts/use-shortcuts.ts b/src/renderer/shortcuts/use-shortcuts.ts
deleted file mode 100644
index a14fdaf9..00000000
--- a/src/renderer/shortcuts/use-shortcuts.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { DEFAULT_KEYBINDINGS } from '@shared/keybindings-catalog'
-import { useEffect } from 'react'
-import { executeCommand } from './executor'
-import { isTyping, matchesAccelerator } from './match'
-
-export function useShortcuts(): void {
- useEffect(() => {
- if (__MOTRIX_TARGET__ === 'electron') return
-
- const bindings = DEFAULT_KEYBINDINGS.filter(
- (k) => k.webAccelerator !== null
- ).map((k) => ({
- commandId: k.commandId,
- accelerator: k.webAccelerator ?? k.accelerator,
- }))
-
- const handler = (e: KeyboardEvent): void => {
- if (isTyping(e.target)) return
- for (const b of bindings) {
- if (matchesAccelerator(e, b.accelerator)) {
- e.preventDefault()
- void executeCommand(b.commandId)
- return
- }
- }
- }
-
- document.addEventListener('keydown', handler)
- return () => document.removeEventListener('keydown', handler)
- }, [])
-}
diff --git a/src/renderer/styles/globals.css b/src/renderer/styles/globals.css
index e7b3a55c..ce5bbb90 100644
--- a/src/renderer/styles/globals.css
+++ b/src/renderer/styles/globals.css
@@ -674,3 +674,25 @@ html[data-reduced-motion="true"] *::after {
scroll-behavior: auto !important;
}
/* biome-ignore-end lint/complexity/noImportantStyles: The accessibility preference overrides inline timings and animation utilities. */
+
+/* Browser chrome includes the same Logo and primary controls as desktop. */
+.web-window-chrome {
+ --window-chrome-safe-area-leading: 160px;
+ --window-chrome-safe-area-trailing: 24px;
+}
+
+@media (width < 640px) {
+ .web-window-chrome [data-slot="panel-shell-header"],
+ .electron-window-chrome [data-slot="panel-shell-header"] {
+ padding-block-start: 44px;
+ padding-inline: 16px;
+ flex-wrap: wrap;
+ gap: 8px;
+ }
+}
+@media (pointer: coarse) and (width < 640px) {
+ .web-window-chrome [data-slot="panel-shell-header"],
+ .electron-window-chrome [data-slot="panel-shell-header"] {
+ padding-block-start: 56px;
+ }
+}
diff --git a/src/server/environment.test.ts b/src/server/environment.test.ts
index db2f0b21..537aab17 100644
--- a/src/server/environment.test.ts
+++ b/src/server/environment.test.ts
@@ -1,5 +1,31 @@
import { describe, expect, it } from 'vitest'
-import { parseServerBoolean, parseServerPort } from './environment'
+import {
+ parseServerBoolean,
+ parseServerPort,
+ parseTorrentBodyLimit,
+} from './environment'
+
+describe('parseTorrentBodyLimit', () => {
+ it.each([undefined, '', ' '])('defaults to 8 MiB for %s', (value) => {
+ expect(parseTorrentBodyLimit(value)).toBe(8 * 1024 * 1024)
+ })
+
+ it.each(['2', '16', ' 64 '])(
+ 'accepts a configured budget of %s MiB',
+ (value) => {
+ expect(parseTorrentBodyLimit(value)).toBe(Number(value) * 1024 * 1024)
+ }
+ )
+
+ it.each(['0', '-1', '1', '65', '2.5', 'NaN', 'Infinity', '16M', 'no'])(
+ 'rejects invalid configuration %s',
+ (value) => {
+ expect(() => parseTorrentBodyLimit(value)).toThrow(
+ 'MOTRIX_TORRENT_BODY_LIMIT_MIB'
+ )
+ }
+ )
+})
describe('parseServerBoolean', () => {
it('uses the fallback when the variable is unset or blank', () => {
diff --git a/src/server/environment.ts b/src/server/environment.ts
index 2b1ae2df..74334b96 100644
--- a/src/server/environment.ts
+++ b/src/server/environment.ts
@@ -1,3 +1,5 @@
+import { torrentRpcBodyLimitSchema } from '@shared/schemas/torrent-request-limits'
+
export function parseServerBoolean(
value: string | undefined,
name: string,
@@ -24,3 +26,17 @@ export function parseServerPort(
}
return port
}
+
+export function parseTorrentBodyLimit(value: string | undefined): number {
+ const parsed = torrentRpcBodyLimitSchema.safeParse(
+ value === undefined || value.trim() === ''
+ ? undefined
+ : Number(value) * 1024 * 1024
+ )
+ if (!parsed.success) {
+ throw new Error(
+ 'MOTRIX_TORRENT_BODY_LIMIT_MIB must be an integer between 2 and 64'
+ )
+ }
+ return parsed.data
+}
diff --git a/src/server/http/app.ts b/src/server/http/app.ts
index 6f05a4fb..8b25ff03 100644
--- a/src/server/http/app.ts
+++ b/src/server/http/app.ts
@@ -15,14 +15,22 @@ import type {
} from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspector-activity'
-import Fastify, { type FastifyInstance } from 'fastify'
+import { torrentRpcBodyLimitSchema } from '@shared/schemas/torrent-request-limits'
+import Fastify, { type FastifyInstance, type FastifyReply } from 'fastify'
import { bindEventBroadcaster } from './events'
import { type OperatorAuthOptions, registerOperatorAuth } from './operator-auth'
import { ServiceUnavailableError } from './service-unavailable-error'
+import {
+ type CommandRequest,
+ RPC_BODY_LIMIT_BYTES,
+ registerTorrentCommandRoutes,
+} from './torrent-command-routes'
-export const RPC_BODY_LIMIT_BYTES = 2 * 1024 * 1024
+export { RPC_BODY_LIMIT_BYTES } from './torrent-command-routes'
export interface AppOptions {
+ /** Torrent-only RPC budget; defaults to 8 MiB, configurable from 2 to 64 MiB. */
+ torrentBodyLimitBytes?: number
commandHandlers?: CommandHandlerMap
queryHandlers?: QueryHandlerMap
/**
@@ -51,11 +59,21 @@ export async function createApp(
const app = Fastify({
logger: false,
bodyLimit: RPC_BODY_LIMIT_BYTES,
+ requestTimeout: 120_000,
})
// Register the deny-by-default operator gate FIRST so its onRequest hook runs
// before every route (including /api/* added by the caller post-createApp and
// the /rpc/events WS upgrade).
- if (opts.operatorAuth) registerOperatorAuth(app, opts.operatorAuth)
+ const operatorSessions = opts.operatorAuth
+ ? registerOperatorAuth(app, opts.operatorAuth)
+ : undefined
+ if (!operatorSessions) {
+ app.get('/rpc/auth/status', async () => ({
+ authed: true,
+ mode: 'unrestricted',
+ canLogout: false,
+ }))
+ }
const commands = opts.commandHandlers ?? {}
const queries = opts.queryHandlers ?? {}
const bridgeCommands = opts.bridgeCommandHandlers ?? {}
@@ -66,22 +84,32 @@ export async function createApp(
return reply.code(health.ok ? 200 : 503).send(health)
})
+ const dispatchCommand = async (
+ channel: string,
+ req: CommandRequest,
+ reply: FastifyReply
+ ) => {
+ const handler =
+ commands[channel as keyof typeof commands] ?? bridgeCommands[channel]
+ if (!handler) return reply.code(404).send({ error: 'unknown channel' })
+ try {
+ return await handler(...(req.body?.args ?? []))
+ } catch (err) {
+ req.log.error({ err }, 'command handler failed')
+ return reply
+ .code(err instanceof ServiceUnavailableError ? 503 : 500)
+ .send({ error: (err as Error).message })
+ }
+ }
+
+ await registerTorrentCommandRoutes(
+ app,
+ dispatchCommand,
+ torrentRpcBodyLimitSchema.parse(opts.torrentBodyLimitBytes)
+ )
app.post<{ Params: { channel: string }; Body: { args?: unknown[] } }>(
'/rpc/command/:channel',
- async (req, reply) => {
- const handler =
- commands[req.params.channel as keyof typeof commands] ??
- bridgeCommands[req.params.channel]
- if (!handler) return reply.code(404).send({ error: 'unknown channel' })
- try {
- return await handler(...(req.body?.args ?? []))
- } catch (err) {
- req.log.error({ err }, 'command handler failed')
- return reply
- .code(err instanceof ServiceUnavailableError ? 503 : 500)
- .send({ error: (err as Error).message })
- }
- }
+ (req, reply) => dispatchCommand(req.params.channel, req, reply)
)
app.post<{ Params: { channel: string }; Body: { args?: unknown[] } }>(
@@ -128,9 +156,13 @@ export async function createApp(
app.addHook('onClose', async () => unsubscribePluginLogs())
}
await app.register(websocket)
- app.get('/rpc/events', { websocket: true }, (socket) => {
- broadcaster.register(socket)
- const cleanup = () => broadcaster.unregister(socket)
+ app.get('/rpc/events', { websocket: true }, (socket, request) => {
+ const session = operatorSessions?.bindSocket(request, socket)
+ broadcaster.register(socket, session?.eligible)
+ const cleanup = () => {
+ broadcaster.unregister(socket)
+ session?.dispose()
+ }
socket.on('close', cleanup)
socket.on('error', cleanup)
})
diff --git a/src/server/http/events.ts b/src/server/http/events.ts
index 315c5bb6..a81d09a5 100644
--- a/src/server/http/events.ts
+++ b/src/server/http/events.ts
@@ -6,7 +6,7 @@ interface SocketLike {
}
export function bindEventBroadcaster(bus: EventBus) {
- const sockets = new Set<SocketLike>()
+ const sockets = new Map<SocketLike, () => boolean>()
subscribeForwardableEvents(bus, (channel, args) => {
broadcast(channel, args)
@@ -15,7 +15,11 @@ export function bindEventBroadcaster(bus: EventBus) {
function broadcast(channel: string, args: unknown[]): void {
if (sockets.size === 0) return
const frame = JSON.stringify({ channel, args })
- for (const s of sockets) {
+ for (const [s, eligible] of sockets) {
+ if (!eligible()) {
+ sockets.delete(s)
+ continue
+ }
try {
s.send(frame)
} catch {
@@ -26,7 +30,8 @@ export function bindEventBroadcaster(bus: EventBus) {
return {
broadcast,
- register: (s: SocketLike) => sockets.add(s),
+ register: (s: SocketLike, eligible: () => boolean = () => true) =>
+ sockets.set(s, eligible),
unregister: (s: SocketLike) => sockets.delete(s),
count: () => sockets.size,
}
diff --git a/src/server/http/operator-auth.test.ts b/src/server/http/operator-auth.test.ts
index 4a2f5bd2..1a851e4a 100644
--- a/src/server/http/operator-auth.test.ts
+++ b/src/server/http/operator-auth.test.ts
@@ -58,7 +58,11 @@ describe('operator auth gate', () => {
).toBe(200)
const status = await app.inject({ method: 'GET', url: '/rpc/auth/status' })
expect(status.statusCode).toBe(200)
- expect(status.json()).toEqual({ authed: false })
+ expect(status.json()).toEqual({
+ authed: false,
+ mode: 'unauthenticated',
+ canLogout: false,
+ })
})
it('rejects login with a wrong token', async () => {
@@ -93,7 +97,11 @@ describe('operator auth gate', () => {
url: '/rpc/auth/status',
headers: { cookie },
})
- expect(status.json()).toEqual({ authed: true })
+ expect(status.json()).toEqual({
+ authed: true,
+ mode: 'cookie',
+ canLogout: true,
+ })
})
it('accepts a Bearer operator token (host-script path)', async () => {
diff --git a/src/server/http/operator-auth.ts b/src/server/http/operator-auth.ts
index 0c0705fb..54587417 100644
--- a/src/server/http/operator-auth.ts
+++ b/src/server/http/operator-auth.ts
@@ -1,4 +1,5 @@
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
+import type { OperatorStatus } from '@shared/schemas/operator-auth'
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
/**
@@ -156,24 +157,45 @@ function isPublic(method: string, url: string): boolean {
return false
}
+interface SessionSocket {
+ close(code: number, reason: string): void
+}
+
+export interface OperatorSessionPolicy {
+ bindSocket(
+ req: FastifyRequest,
+ socket: SessionSocket
+ ): {
+ eligible: () => boolean
+ dispose: () => void
+ }
+}
+
export function registerOperatorAuth(
app: FastifyInstance,
opts: OperatorAuthOptions
-): void {
+): OperatorSessionPolicy {
const now = opts.now ?? Date.now
const publicOrigin = configuredPublicOrigin(opts.publicUrl)
const sessions = new Map<string, number>() // sessionId -> expiresAt
+ const sessionSockets = new Map<string, Set<SessionSocket>>()
+ const revoke = (id: string): void => {
+ sessions.delete(id)
+ const sockets = sessionSockets.get(id)
+ sessionSockets.delete(id)
+ for (const socket of sockets ?? []) socket.close(4401, 'Session expired')
+ }
let failedLogins: number[] = [] // timestamps of FAILED attempts only
- const validSession = (id: string | undefined): boolean => {
+ const validSession = (id: string | undefined, renew = true): boolean => {
if (!id) return false
const exp = sessions.get(id)
if (!exp) return false
- if (now() > exp) {
- sessions.delete(id)
+ if (now() >= exp) {
+ revoke(id)
return false
}
- sessions.set(id, now() + SESSION_TTL_MS) // sliding renewal
+ if (renew) sessions.set(id, now() + SESSION_TTL_MS)
return true
}
@@ -260,17 +282,45 @@ export function registerOperatorAuth(
}
)
- app.get('/rpc/auth/status', async (req) => ({
- authed: authenticate(req) !== null,
- }))
+ app.get('/rpc/auth/status', async (req): Promise<OperatorStatus> => {
+ const mode = authenticate(req)
+ return {
+ authed: mode !== null,
+ mode: mode ?? 'unauthenticated',
+ canLogout: mode === 'cookie',
+ }
+ })
app.post('/rpc/auth/logout', async (req, reply) => {
const id = parseCookies(req.headers.cookie)[COOKIE]
- if (id) sessions.delete(id)
+ if (authenticate(req) === 'cookie' && id) revoke(id)
reply.header(
'set-cookie',
`${COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`
)
return { ok: true }
})
+
+ return {
+ bindSocket(req, socket) {
+ const mode = authenticate(req)
+ const id =
+ mode === 'cookie' ? parseCookies(req.headers.cookie)[COOKIE] : undefined
+ if (id) {
+ const sockets = sessionSockets.get(id) ?? new Set<SessionSocket>()
+ sockets.add(socket)
+ sessionSockets.set(id, sockets)
+ }
+ return {
+ eligible: () =>
+ mode === 'bearer' || (mode === 'cookie' && validSession(id, false)),
+ dispose: () => {
+ if (!id) return
+ const sockets = sessionSockets.get(id)
+ sockets?.delete(socket)
+ if (sockets?.size === 0) sessionSockets.delete(id)
+ },
+ }
+ },
+ }
}
diff --git a/src/server/http/rpc-ws-auth.test.ts b/src/server/http/rpc-ws-auth.test.ts
index 048638af..cc5b3659 100644
--- a/src/server/http/rpc-ws-auth.test.ts
+++ b/src/server/http/rpc-ws-auth.test.ts
@@ -12,13 +12,16 @@ describe('/rpc/events WebSocket auth', () => {
let app: FastifyInstance
let bus: EventBus
let port: number
+ let now: number
beforeEach(async () => {
+ now = 1_000
bus = new EventBus()
app = await createApp({
eventBus: bus,
operatorAuth: {
operatorToken: TOKEN,
+ now: () => now,
publicUrl: 'https://motrix.example/operator',
},
})
@@ -84,4 +87,54 @@ describe('/rpc/events WebSocket auth', () => {
expect(ws.readyState).toBe(WebSocket.OPEN)
ws.close()
})
+ it('revokes every socket owned by the logged-out cookie before further broadcasts', async () => {
+ const session = await cookie()
+ const sockets = await Promise.all([
+ connect({ cookie: session, origin: 'https://motrix.example' }),
+ connect({ cookie: session, origin: 'https://motrix.example' }),
+ ])
+ const independent = await connect({
+ cookie: await cookie(),
+ origin: 'https://motrix.example',
+ })
+ const bearer = await connect({ authorization: `Bearer ${TOKEN}` })
+ const received: string[] = []
+ for (const ws of sockets)
+ ws.on('message', (data) => received.push(String(data)))
+ const closed = sockets.map(
+ (ws) => new Promise<number>((resolve) => ws.once('close', resolve))
+ )
+ await app.inject({
+ method: 'POST',
+ url: '/rpc/auth/logout',
+ headers: { cookie: session },
+ })
+ const unaffected = [independent, bearer].map(
+ (ws) => new Promise<unknown>((resolve) => ws.once('message', resolve))
+ )
+ bus.emit(Events.TaskUpdated, { id: 'after-logout' })
+ expect(await Promise.all(closed)).toEqual([4401, 4401])
+ await Promise.all(unaffected)
+ expect(received).toEqual([])
+ independent.close()
+ bearer.close()
+ })
+
+ it('does not renew the cookie on broadcasts and suppresses the first expired frame', async () => {
+ const ws = await connect({
+ cookie: await cookie(),
+ origin: 'https://motrix.example',
+ })
+ now += 6 * 24 * 60 * 60 * 1000
+ const first = new Promise<unknown>((resolve) => ws.once('message', resolve))
+ bus.emit(Events.TaskUpdated, { id: 'still-valid' })
+ await first
+ const received: string[] = []
+ ws.on('message', (data) => received.push(String(data)))
+ const closed = new Promise<number>((resolve) => ws.once('close', resolve))
+ now += 24 * 60 * 60 * 1000
+ bus.emit(Events.TaskUpdated, { id: 'expired' })
+ expect(await closed).toBe(4401)
+ expect(received).toEqual([])
+ })
})
diff --git a/src/server/http/torrent-command-routes.test.ts b/src/server/http/torrent-command-routes.test.ts
new file mode 100644
index 00000000..cfe491c3
--- /dev/null
+++ b/src/server/http/torrent-command-routes.test.ts
@@ -0,0 +1,305 @@
+// @vitest-environment node
+
+import { PassThrough, Readable } from 'node:stream'
+import {
+ MAX_TORRENT_BASE64_SIZE,
+ MAX_TORRENT_RPC_BODY_LIMIT_BYTES,
+} from '@shared/lib/torrent-meta'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import Fastify, { type FastifyInstance } from 'fastify'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createApp, RPC_BODY_LIMIT_BYTES } from './app'
+import { registerTorrentCommandRoutes } from './torrent-command-routes'
+
+function torrentBody(base64 = 'YQ==') {
+ return {
+ args: [
+ {
+ type: 'bt',
+ payload: { kind: 'torrent-base64', base64 },
+ selectedFiles: [0],
+ saveDir: '/downloads',
+ },
+ ],
+ }
+}
+
+const createUrl = `/rpc/command/${encodeURIComponent(Commands.CreateTask)}`
+const jsonHeaders = { 'content-type': 'application/json' }
+
+describe('torrent RPC request budgets', () => {
+ let app: FastifyInstance
+ afterEach(async () => {
+ await app?.close()
+ })
+
+ it.each([Commands.CreateTask, Commands.AddTorrentTask])(
+ 'accepts large torrents at the exact %s route, including encoded colons',
+ async (channel) => {
+ const handler = vi.fn(async () => ({ ok: true }))
+ app = await createApp({ commandHandlers: { [channel]: handler } })
+ const base64 = 'A'.repeat(3 * 1024 * 1024)
+ const payload =
+ channel === Commands.CreateTask
+ ? torrentBody(base64)
+ : { args: [{ base64, selectedFiles: [0], saveDir: '/downloads' }] }
+ for (const route of [
+ channel,
+ encodeURIComponent(channel),
+ encodeURIComponent(channel).replace('%3A', '%3a'),
+ ]) {
+ const res = await app.inject({
+ method: 'POST',
+ url: `/rpc/command/${route}`,
+ payload,
+ })
+ expect(res.statusCode).toBe(200)
+ }
+ expect(handler).toHaveBeenCalledTimes(3)
+ const res = await app.inject({
+ method: 'POST',
+ url: `/rpc/command/${channel}Other`,
+ payload,
+ })
+ expect(res.statusCode).toBe(413)
+ }
+ )
+
+ it('accepts the parser Base64 limit plus its envelope and rejects overflow before dispatch', async () => {
+ const handler = vi.fn(async () => ({ ok: true }))
+ app = await createApp({
+ torrentBodyLimitBytes: MAX_TORRENT_RPC_BODY_LIMIT_BYTES,
+ commandHandlers: { [Commands.CreateTask]: handler },
+ })
+ for (const extra of [0, 4]) {
+ const res = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ payload: torrentBody('A'.repeat(MAX_TORRENT_BASE64_SIZE + extra)),
+ })
+ expect(res.statusCode).toBe(extra === 0 ? 200 : 413)
+ }
+ expect(handler).toHaveBeenCalledOnce()
+ })
+
+ it.each([
+ { mib: 8, chunked: false },
+ { mib: 8, chunked: true },
+ { mib: 16, chunked: false },
+ { mib: 64, chunked: true },
+ ])(
+ 'enforces the inclusive $mib MiB wire limit (chunked: $chunked)',
+ async ({ mib, chunked }) => {
+ // Padding exercises the whole wire budget independently of the 50 MiB
+ // Base64 constraint. Stream chunks keep the unknown-length path covered.
+ const handler = vi.fn(async () => ({ ok: true }))
+ app = await createApp({
+ torrentBodyLimitBytes: mib === 8 ? undefined : mib * 1024 * 1024,
+ commandHandlers: { [Commands.CreateTask]: handler },
+ })
+ const json = JSON.stringify(torrentBody())
+ for (const extra of [0, 1]) {
+ const padding = mib * 1024 * 1024 - Buffer.byteLength(json) + extra
+ function* chunks() {
+ yield json
+ for (let left = padding; left > 0; left -= 64 * 1024) {
+ yield ' '.repeat(Math.min(left, 64 * 1024))
+ }
+ }
+ const res = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ headers: jsonHeaders,
+ payload: chunked
+ ? Readable.from(chunks())
+ : json + ' '.repeat(padding),
+ })
+ expect(res.statusCode).toBe(extra === 0 ? 200 : 413)
+ }
+ expect(handler).toHaveBeenCalledOnce()
+ }
+ )
+
+ it.each([
+ { type: 'http', uris: ['https://example.com/file'] },
+ { type: 'bt', payload: { kind: 'magnet', uri: 'magnet:?xt=test' } },
+ ])(
+ 'retains 2 MiB for $type requests on CreateTask, counting UTF-8 bytes',
+ async (request) => {
+ const handler = vi.fn(async () => ({ ok: true }))
+ app = await createApp({
+ commandHandlers: { [Commands.CreateTask]: handler },
+ })
+ const payload = JSON.stringify({
+ args: [{ ...request, saveDir: '种'.repeat(800_000) }],
+ })
+ expect(payload.length).toBeLessThan(RPC_BODY_LIMIT_BYTES)
+ const res = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ headers: jsonHeaders,
+ payload: Readable.from([payload]),
+ })
+ expect(res.statusCode).toBe(413)
+ expect(handler).not.toHaveBeenCalled()
+ }
+ )
+
+ it('counts whitespace in ordinary CreateTask requests with no Content-Length', async () => {
+ app = await createApp({
+ commandHandlers: { [Commands.CreateTask]: async () => ({ ok: true }) },
+ })
+ const json = JSON.stringify({ args: [{ type: 'http' }] })
+ for (const extra of [0, 1]) {
+ const res = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ headers: jsonHeaders,
+ payload: Readable.from([
+ json,
+ ' '.repeat(RPC_BODY_LIMIT_BYTES - json.length + extra),
+ ]),
+ })
+ expect(res.statusCode).toBe(extra === 0 ? 200 : 413)
+ }
+ })
+
+ it('keeps generic commands, queries and bridge calls at 2 MiB', async () => {
+ app = await createApp()
+ for (const url of [
+ `/rpc/command/${Commands.UpdateSettings}`,
+ `/rpc/query/${Queries.ListTasks}`,
+ '/rpc/command/bridge:submit',
+ ]) {
+ const res = await app.inject({
+ method: 'POST',
+ url,
+ payload: torrentBody('A'.repeat(RPC_BODY_LIMIT_BYTES)),
+ })
+ expect(res.statusCode).toBe(413)
+ }
+ })
+
+ it('checks operator authentication before reading a large torrent body', async () => {
+ const handler = vi.fn(async () => ({ ok: true }))
+ app = await createApp({
+ commandHandlers: { [Commands.CreateTask]: handler },
+ operatorAuth: { operatorToken: 'test-operator' },
+ })
+ const payload = torrentBody('A'.repeat(3 * 1024 * 1024))
+ const denied = await app.inject({ method: 'POST', url: createUrl, payload })
+ expect(denied.statusCode).toBe(401)
+ const allowed = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ payload,
+ headers: { authorization: 'Bearer test-operator' },
+ })
+ expect(allowed.statusCode).toBe(200)
+ expect(handler).toHaveBeenCalledOnce()
+ })
+
+ it('bounds large requests across both torrent routes and releases slots after completion', async () => {
+ let finish!: () => void
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ const handler = vi.fn(async () => {
+ await pending
+ return { ok: true }
+ })
+ app = await createApp({
+ commandHandlers: {
+ [Commands.CreateTask]: handler,
+ [Commands.AddTorrentTask]: handler,
+ [Commands.PauseTasks]: async () => ({ ok: true }),
+ },
+ })
+ const payload = torrentBody('A'.repeat(3 * 1024 * 1024))
+ const first = app
+ .inject({ method: 'POST', url: createUrl, payload })
+ .then((res) => res)
+ const second = app
+ .inject({
+ method: 'POST',
+ url: `/rpc/command/${Commands.AddTorrentTask}`,
+ payload: { args: [{ base64: 'A'.repeat(3 * 1024 * 1024) }] },
+ })
+ .then((res) => res)
+ try {
+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2))
+ const busy = await app.inject({ method: 'POST', url: createUrl, payload })
+ expect(busy.statusCode).toBe(429)
+ const small = await app.inject({
+ method: 'POST',
+ url: `/rpc/command/${Commands.PauseTasks}`,
+ payload: { args: [[]] },
+ })
+ expect(small.statusCode).toBe(200)
+ } finally {
+ finish()
+ await Promise.all([first, second])
+ }
+ expect(
+ (await app.inject({ method: 'POST', url: createUrl, payload })).statusCode
+ ).toBe(200)
+ })
+
+ it('releases admission slots when a client aborts before its body finishes', async () => {
+ let bodyStarted!: () => void
+ app = Fastify({ bodyLimit: RPC_BODY_LIMIT_BYTES })
+ app.addHook('preParsing', (_request, _reply, payload, done) => {
+ bodyStarted()
+ done(null, payload)
+ })
+ const dispatch = vi.fn(async () => ({ ok: true }))
+ await registerTorrentCommandRoutes(app, dispatch, 8 * 1024 * 1024)
+ for (let index = 0; index < 3; index++) {
+ const started = new Promise<void>((resolve) => {
+ bodyStarted = resolve
+ })
+ const controller = new AbortController()
+ const payload = new PassThrough()
+ const pending = app
+ .inject({
+ method: 'POST',
+ url: createUrl,
+ headers: jsonHeaders,
+ payload,
+ signal: controller.signal,
+ })
+ .catch(() => undefined)
+ await started
+ controller.abort()
+ payload.destroy()
+ await pending
+ }
+ expect(dispatch).not.toHaveBeenCalled()
+ const res = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ payload: torrentBody('A'.repeat(3 * 1024 * 1024)),
+ })
+ expect(res.statusCode).toBe(200)
+ })
+
+ it('releases unknown-length slots on parse failure, unsupported media, and missing handlers', async () => {
+ app = await createApp()
+ for (let index = 0; index < 3; index++) {
+ for (const [payload, headers, status] of [
+ ['{', jsonHeaders, 400],
+ ['{}', { 'content-type': 'text/plain' }, 415],
+ [JSON.stringify(torrentBody()), jsonHeaders, 404],
+ ] as const) {
+ const res = await app.inject({
+ method: 'POST',
+ url: createUrl,
+ headers,
+ payload: Readable.from([payload]),
+ })
+ expect(res.statusCode).toBe(status)
+ }
+ }
+ })
+})
diff --git a/src/server/http/torrent-command-routes.ts b/src/server/http/torrent-command-routes.ts
new file mode 100644
index 00000000..62ccf706
--- /dev/null
+++ b/src/server/http/torrent-command-routes.ts
@@ -0,0 +1,133 @@
+import { MAX_TORRENT_BASE64_SIZE } from '@shared/lib/torrent-meta'
+import { Commands } from '@shared/protocol/commands'
+import {
+ errorCodes,
+ type FastifyInstance,
+ type FastifyReply,
+ type FastifyRequest,
+} from 'fastify'
+import { z } from 'zod'
+
+export const RPC_BODY_LIMIT_BYTES = 2 * 1024 * 1024
+const MAX_LARGE_REQUESTS = 2
+
+export type CommandRequest = FastifyRequest<{
+ Body: { args?: unknown[] }
+}>
+
+// These identify which requests need the larger transport budget. Complete
+// task validation remains in the command handler and shared task schema.
+const createTorrentEnvelope = z.object({
+ args: z.tuple([
+ z.object({
+ type: z.literal('bt'),
+ payload: z.object({
+ kind: z.literal('torrent-base64'),
+ base64: z.string(),
+ }),
+ }),
+ ]),
+})
+const addTorrentEnvelope = z.object({
+ args: z.tuple([z.object({ base64: z.string() })]),
+})
+
+export async function registerTorrentCommandRoutes(
+ app: FastifyInstance,
+ dispatch: (
+ channel: string,
+ request: CommandRequest,
+ reply: FastifyReply
+ ) => Promise<unknown>,
+ bodyLimitBytes: number
+): Promise<void> {
+ await app.register(async (routes) => {
+ const bodySizes = new WeakMap<FastifyRequest, number>()
+ const releases = new WeakMap<FastifyRequest, () => void>()
+ const processing = new WeakSet<FastifyRequest>()
+ let activeLargeRequests = 0
+
+ // Keep Fastify's JSON parsing/prototype protection, recording actual wire
+ // bytes before decoding (including whitespace and multibyte text).
+ const parseJson = routes.getDefaultJsonParser('error', 'error')
+ routes.removeAllContentTypeParsers()
+ routes.addContentTypeParser<Buffer>(
+ 'application/json',
+ { parseAs: 'buffer' },
+ (request, body, done) => {
+ bodySizes.set(request, body.byteLength)
+ parseJson(request, body.toString('utf8'), done)
+ }
+ )
+
+ routes.addHook('onRequest', async (request, reply) => {
+ const contentLength = request.headers['content-length']
+ if (
+ contentLength !== undefined &&
+ Number(contentLength) <= RPC_BODY_LIMIT_BYTES
+ ) {
+ return
+ }
+ if (activeLargeRequests >= MAX_LARGE_REQUESTS) {
+ return reply
+ .code(429)
+ .send({ error: 'Too many large torrent requests' })
+ }
+ activeLargeRequests += 1
+ const onClose = () => {
+ // A disconnected client must not free a slot while its command still
+ // owns the parsed torrent. The handler's finally releases that slot.
+ if (!processing.has(request)) release()
+ }
+ const release = () => {
+ if (!releases.delete(request)) return
+ activeLargeRequests -= 1
+ reply.raw.off('close', onClose)
+ }
+ releases.set(request, release)
+ reply.raw.once('close', onClose)
+ })
+ routes.addHook('onResponse', async (request) => {
+ releases.get(request)?.()
+ })
+ routes.addHook('onError', async (request) => {
+ releases.get(request)?.()
+ })
+ routes.addHook('onRequestAbort', async (request) => {
+ releases.get(request)?.()
+ })
+
+ // Match only these two decoded channel names. Static colon routes do
+ // not match the percent-encoded colons sent by HttpWsTransport.
+ const channels = [Commands.CreateTask, Commands.AddTorrentTask].join('|')
+ routes.post<{ Params: { channel: string }; Body: { args?: unknown[] } }>(
+ `/rpc/command/:channel(^(?:${channels})$)`,
+ {
+ bodyLimit: bodyLimitBytes,
+ preValidation: async (request, reply) => {
+ const base64 =
+ request.params.channel === Commands.CreateTask
+ ? createTorrentEnvelope.safeParse(request.body).data?.args[0]
+ .payload.base64
+ : addTorrentEnvelope.safeParse(request.body).data?.args[0].base64
+ if (
+ (base64 === undefined &&
+ (bodySizes.get(request) ?? 0) > RPC_BODY_LIMIT_BYTES) ||
+ (base64 !== undefined && base64.length > MAX_TORRENT_BASE64_SIZE)
+ ) {
+ return reply.send(new errorCodes.FST_ERR_CTP_BODY_TOO_LARGE())
+ }
+ },
+ },
+ async (request, reply) => {
+ processing.add(request)
+ try {
+ return await dispatch(request.params.channel, request, reply)
+ } finally {
+ processing.delete(request)
+ releases.get(request)?.()
+ }
+ }
+ )
+ })
+}
diff --git a/src/server/http/torrent-upload.integration.test.ts b/src/server/http/torrent-upload.integration.test.ts
new file mode 100644
index 00000000..95084b78
--- /dev/null
+++ b/src/server/http/torrent-upload.integration.test.ts
@@ -0,0 +1,195 @@
+// @vitest-environment node
+
+import { createHash } from 'node:crypto'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'
+import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'
+import { TorrentParser } from '@core/torrent/torrent-parser'
+import { Commands } from '@shared/protocol/commands'
+import { taskCreateRequestSchema } from '@shared/schemas/add-task'
+import {
+ type Aria2Handle,
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ connectAdapter,
+ spawnAria2ForTest,
+} from '@test-utils/aria2'
+import type { FastifyInstance } from 'fastify'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { parseTorrentBodyLimit } from '../environment'
+import { createApp } from './app'
+
+// A valid BEP 3 torrent with a large comment exercises upload transport
+// limits without allocating a large payload file or contacting public peers.
+function largeTorrent(commentBytes: number): Buffer {
+ return Buffer.concat([
+ Buffer.from(`d7:comment${commentBytes}:`),
+ Buffer.alloc(commentBytes, 'a'),
+ Buffer.from(
+ '4:infod6:lengthi1e4:name11:fixture.bin12:piece lengthi16384e6:pieces20:'
+ ),
+ createHash('sha1').update('x').digest(),
+ Buffer.from('7:privatei1eee'),
+ ])
+}
+
+it.skipIf(!canBindLoopbackTcp())(
+ 'holds admission until a command finishes after its client disconnects',
+ async () => {
+ let finish!: () => void
+ const pending = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ const handler = vi.fn(async () => {
+ await pending
+ return { ok: true }
+ })
+ const app = await createApp({
+ commandHandlers: { [Commands.CreateTask]: handler },
+ })
+ let clientClosed!: () => void
+ const closed = new Promise<void>((resolve) => {
+ clientClosed = resolve
+ })
+ app.server.on('request', (request, response) => {
+ if (request.headers['x-test-abort']) response.once('close', clientClosed)
+ })
+ const address = await app.listen({ port: 0, host: '127.0.0.1' })
+ const controller = new AbortController()
+ const send = (abort = false) =>
+ fetch(
+ `${address}/rpc/command/${encodeURIComponent(Commands.CreateTask)}`,
+ {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(abort ? { 'x-test-abort': '1' } : {}),
+ },
+ signal: abort ? controller.signal : undefined,
+ body: JSON.stringify({
+ args: [
+ {
+ type: 'bt',
+ payload: {
+ kind: 'torrent-base64',
+ base64: 'A'.repeat(3 * 1024 * 1024),
+ },
+ },
+ ],
+ }),
+ }
+ )
+ const first = send(true).catch(() => undefined)
+ const second = send()
+ try {
+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2))
+ controller.abort()
+ await closed
+ const busy = await send()
+ expect(busy.status).toBe(429)
+ await busy.arrayBuffer()
+ finish()
+ const response = await second
+ await response.arrayBuffer()
+ const accepted = await send()
+ expect(accepted.status).toBe(200)
+ await accepted.arrayBuffer()
+ } finally {
+ finish()
+ await Promise.allSettled([first, second])
+ await app.close()
+ }
+ }
+)
+
+describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
+ 'server torrent upload to real aria2',
+ () => {
+ let baseDir: string
+ let handle: Aria2Handle
+ let disconnect: (() => void) | undefined
+ let app: FastifyInstance
+
+ afterEach(async () => {
+ await app?.close()
+ disconnect?.()
+ await handle?.kill()
+ if (baseDir) await rm(baseDir, { recursive: true, force: true })
+ })
+
+ it.each([
+ { configured: undefined, rawMiB: 3 },
+ { configured: '16', rawMiB: 8 },
+ ])(
+ 'submits a $rawMiB MiB torrent with limit $configured',
+ async ({ configured, rawMiB }) => {
+ baseDir = await mkdtemp(path.join(tmpdir(), 'motrix-torrent-upload-'))
+ const limit = parseTorrentBodyLimit(configured)
+ const builder = new Aria2ConfigBuilder('', baseDir, {
+ rpcMaxRequestSizeBytes: limit,
+ })
+ const args = builder.buildArgs(
+ DEFAULT_ENGINE_SETTINGS,
+ false,
+ null,
+ { download: 0, upload: 0 },
+ baseDir
+ )
+ handle = await spawnAria2ForTest({
+ baseDir,
+ extraArgs: [
+ '--rpc-max-request-size=2M',
+ ...args.filter((arg) => arg.startsWith('--rpc-max-request-size=')),
+ '--bt-enable-lpd=false',
+ '--enable-dht6=false',
+ ],
+ })
+ const wired = await connectAdapter(handle)
+ disconnect = wired.disconnect
+ const parser = new TorrentParser()
+ app = await createApp({
+ torrentBodyLimitBytes: limit,
+ commandHandlers: {
+ [Commands.CreateTask]: async (input: unknown) => {
+ const task = taskCreateRequestSchema.parse(input)
+ if (task.type !== 'bt' || task.payload.kind !== 'torrent-base64')
+ throw new Error('Expected a torrent')
+ const meta = await parser.parse(task.payload.base64)
+ const gid = await wired.rpc.addTorrent(task.payload.base64, [], {
+ dir: baseDir,
+ pause: 'true',
+ })
+ return { gid, infoHash: meta.infoHash }
+ },
+ },
+ })
+ const bytes = largeTorrent(rawMiB * 1024 * 1024)
+ const response = await app.inject({
+ method: 'POST',
+ url: `/rpc/command/${encodeURIComponent(Commands.CreateTask)}`,
+ payload: {
+ args: [
+ {
+ type: 'bt',
+ payload: {
+ kind: 'torrent-base64',
+ base64: bytes.toString('base64'),
+ },
+ selectedFiles: [0],
+ saveDir: baseDir,
+ },
+ ],
+ },
+ })
+ expect(response.statusCode).toBe(200)
+ const result = response.json<{ gid: string; infoHash: string }>()
+ const status = await wired.rpc.tellStatus(result.gid)
+ expect(status.infoHash).toBe(result.infoHash)
+ expect(status.status).toBe('paused')
+ },
+ 20_000
+ )
+ }
+)
diff --git a/src/server/index.ts b/src/server/index.ts
index 32de2c2d..df43c409 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -150,7 +150,11 @@ import {
createServerDownloadPathPolicy,
resolveServerDefaultSaveDir,
} from './download-path-policy'
-import { parseServerBoolean, parseServerPort } from './environment'
+import {
+ parseServerBoolean,
+ parseServerPort,
+ parseTorrentBodyLimit,
+} from './environment'
import { createApp } from './http/app'
import { buildServerCommandHandlers } from './ipc/commands'
import { buildServerQueryHandlers } from './ipc/queries'
@@ -188,6 +192,9 @@ async function main() {
// ─── Logger ───────────────────────────────────────────────────
initLogger(pino({ level: process.env.LOG_LEVEL ?? 'info' }))
const log = getLogger('server')
+ const torrentBodyLimitBytes = parseTorrentBodyLimit(
+ process.env.MOTRIX_TORRENT_BODY_LIMIT_MIB
+ )
// ─── Platform ─────────────────────────────────────────────────
const platform = createNodePlatformServices()
@@ -446,6 +453,7 @@ async function main() {
process.env.MOTRIX_ARIA2_RPC_LISTEN_ALL,
'MOTRIX_ARIA2_RPC_LISTEN_ALL'
),
+ rpcMaxRequestSizeBytes: torrentBodyLimitBytes,
}
)
const trustStore = new Aria2TrustStore(platform.userDataDir)
@@ -1217,6 +1225,7 @@ async function main() {
)
const app = await createApp({
+ torrentBodyLimitBytes,
commandHandlers,
queryHandlers,
bridgeCommandHandlers: bridgeManager.bridgeCommandHandlers,
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index c05273ea..334b8fe0 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -30,9 +30,12 @@ import type { MotrixDatabase } from '@core/session/motrix-database'
import type { SessionManager } from '@core/session/session-manager'
import type { SettingsManager } from '@core/settings/settings-manager'
import {
+ clearStoppedTasks,
+ pauseAllTasks,
pauseTask,
reAddTask,
removeTask,
+ resumeAllTasks,
resumeTask,
runBulkTaskAction,
stopSeedingTask,
@@ -560,6 +563,13 @@ export function buildServerCommandHandlers(
[Commands.MoveTasks]: async (rawPayload: unknown) =>
moveTasks(moveTasksPayloadSchema.parse(rawPayload), pauseResumeDeps),
+ [Commands.PauseAllTasks]: async () =>
+ toBulkTaskCommandResult(await pauseAllTasks(pauseResumeDeps)),
+ [Commands.ResumeAllTasks]: async () =>
+ toBulkTaskCommandResult(await resumeAllTasks(pauseResumeDeps)),
+ [Commands.ClearStoppedTasks]: async (rawPayload: unknown) =>
+ clearStoppedTasks(removeDeps, taskIdsPayloadSchema.parse(rawPayload)),
+
[Commands.PauseTasks]: async (rawPayload: unknown) => {
const taskIds = taskIdsPayloadSchema.parse(rawPayload)
return toBulkTaskCommandResult(
diff --git a/src/shared/application-menu-catalog.ts b/src/shared/application-menu-catalog.ts
new file mode 100644
index 00000000..5621446c
--- /dev/null
+++ b/src/shared/application-menu-catalog.ts
@@ -0,0 +1,193 @@
+import { type CommandId, CommandIds } from './commands-catalog'
+import { EXTERNAL_URLS } from './external-urls'
+
+export interface ProductMenuItem {
+ id: string
+ commandId: CommandId
+ title: string
+ section: 'app' | 'task' | 'help'
+ group: string
+ order: number
+ scope: 'local' | 'selection' | 'list' | 'instance'
+}
+
+/** Product actions shared by native menus and the browser application menu. */
+export const PRODUCT_MENU_ITEMS: readonly ProductMenuItem[] = [
+ {
+ id: 'menubar.app.about',
+ commandId: CommandIds.AppShowAbout,
+ title: 'menu.app.about',
+ section: 'app',
+ group: '1_about',
+ order: 10,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.app.preferences',
+ commandId: CommandIds.AppOpenPreferences,
+ title: 'menu.app.preferences',
+ section: 'app',
+ group: '2_prefs',
+ order: 10,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.task.new',
+ commandId: CommandIds.TaskNew,
+ title: 'menu.task.newTask',
+ section: 'task',
+ group: '1_new',
+ order: 10,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.task.newBt',
+ commandId: CommandIds.TaskNewBt,
+ title: 'menu.task.newBtTask',
+ section: 'task',
+ group: '1_new',
+ order: 20,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.task.openFile',
+ commandId: CommandIds.TaskOpenFile,
+ title: 'menu.task.openFile',
+ section: 'task',
+ group: '1_new',
+ order: 30,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.task.list',
+ commandId: CommandIds.NavigateTaskList,
+ title: 'menu.task.taskList',
+ section: 'task',
+ group: '2_primary',
+ order: 10,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.task.pause',
+ commandId: CommandIds.TaskPause,
+ title: 'menu.task.pauseTask',
+ section: 'task',
+ group: '2_primary',
+ order: 20,
+ scope: 'selection',
+ },
+ {
+ id: 'menubar.task.resume',
+ commandId: CommandIds.TaskResume,
+ title: 'menu.task.resumeTask',
+ section: 'task',
+ group: '2_primary',
+ order: 30,
+ scope: 'selection',
+ },
+ {
+ id: 'menubar.task.delete',
+ commandId: CommandIds.TaskDelete,
+ title: 'menu.task.deleteTask',
+ section: 'task',
+ group: '2_primary',
+ order: 40,
+ scope: 'selection',
+ },
+ {
+ id: 'menubar.task.moveUp',
+ commandId: CommandIds.TaskMoveUp,
+ title: 'menu.task.moveTaskUp',
+ section: 'task',
+ group: '2_primary',
+ order: 50,
+ scope: 'selection',
+ },
+ {
+ id: 'menubar.task.moveDown',
+ commandId: CommandIds.TaskMoveDown,
+ title: 'menu.task.moveTaskDown',
+ section: 'task',
+ group: '2_primary',
+ order: 60,
+ scope: 'selection',
+ },
+ {
+ id: 'menubar.task.pauseAll',
+ commandId: CommandIds.TaskPauseAll,
+ title: 'menu.task.pauseAllTask',
+ section: 'task',
+ group: '3_bulk',
+ order: 10,
+ scope: 'instance',
+ },
+ {
+ id: 'menubar.task.resumeAll',
+ commandId: CommandIds.TaskResumeAll,
+ title: 'menu.task.resumeAllTask',
+ section: 'task',
+ group: '3_bulk',
+ order: 20,
+ scope: 'instance',
+ },
+ {
+ id: 'menubar.task.selectAll',
+ commandId: CommandIds.TaskSelectAll,
+ title: 'menu.task.selectAllTask',
+ section: 'task',
+ group: '3_bulk',
+ order: 30,
+ scope: 'list',
+ },
+ {
+ id: 'menubar.task.clearStopped',
+ commandId: CommandIds.TaskClearStopped,
+ title: 'menu.task.clearRecentTasks',
+ section: 'task',
+ group: '4_clear',
+ order: 10,
+ scope: 'instance',
+ },
+ {
+ id: 'menubar.help.website',
+ commandId: CommandIds.HelpOpenWebsite,
+ title: 'menu.help.officialWebsite',
+ section: 'help',
+ group: '1_links',
+ order: 10,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.help.manual',
+ commandId: CommandIds.HelpOpenManual,
+ title: 'menu.help.manual',
+ section: 'help',
+ group: '1_links',
+ order: 20,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.help.changelog',
+ commandId: CommandIds.HelpOpenChangelog,
+ title: 'menu.help.changelog',
+ section: 'help',
+ group: '1_links',
+ order: 30,
+ scope: 'local',
+ },
+ {
+ id: 'menubar.help.reportProblem',
+ commandId: CommandIds.HelpReportProblem,
+ title: 'menu.help.reportProblem',
+ section: 'help',
+ group: '2_report',
+ order: 10,
+ scope: 'local',
+ },
+]
+export const PRODUCT_MENU_LINKS: Partial<Record<CommandId, string>> = {
+ [CommandIds.HelpOpenWebsite]: EXTERNAL_URLS.motrix.home,
+ [CommandIds.HelpOpenManual]: EXTERNAL_URLS.motrix.manual.home,
+ [CommandIds.HelpOpenChangelog]: EXTERNAL_URLS.motrix.changelog,
+ [CommandIds.HelpReportProblem]: EXTERNAL_URLS.github.issues,
+}
diff --git a/src/shared/keybindings-catalog.ts b/src/shared/keybindings-catalog.ts
index 62451122..48b19a1e 100644
--- a/src/shared/keybindings-catalog.ts
+++ b/src/shared/keybindings-catalog.ts
@@ -25,16 +25,17 @@ export const DEFAULT_KEYBINDINGS: readonly KeybindingEntry[] = [
{
accelerator: 'CommandOrControl+,',
commandId: CommandIds.AppOpenPreferences,
+ webAccelerator: null,
},
{
accelerator: 'CommandOrControl+N',
commandId: CommandIds.TaskNew,
- webAccelerator: 'Control+N',
+ webAccelerator: null,
},
{
accelerator: 'CommandOrControl+Shift+N',
commandId: CommandIds.TaskNewBt,
- webAccelerator: 'Control+Shift+N',
+ webAccelerator: null,
},
{
accelerator: 'CommandOrControl+O',
@@ -44,14 +45,17 @@ export const DEFAULT_KEYBINDINGS: readonly KeybindingEntry[] = [
{
accelerator: 'CommandOrControl+L',
commandId: CommandIds.NavigateTaskList,
+ webAccelerator: null,
},
{
accelerator: 'CommandOrControl+Shift+P',
commandId: CommandIds.TaskPauseAll,
+ webAccelerator: null,
},
{
accelerator: 'CommandOrControl+Shift+R',
commandId: CommandIds.TaskResumeAll,
+ webAccelerator: null,
},
{
accelerator: 'CommandOrControl+M',
diff --git a/src/shared/lib/torrent-meta.ts b/src/shared/lib/torrent-meta.ts
index bea789a1..11e0ce06 100644
--- a/src/shared/lib/torrent-meta.ts
+++ b/src/shared/lib/torrent-meta.ts
@@ -1,6 +1,12 @@
import type { TorrentMeta } from '@shared/types/torrent'
+// Product limits, not BitTorrent protocol limits. BEP 3/52 do not impose a
+// universal metainfo file size cap. Base64 expands each 3 bytes to 4 characters.
export const MAX_TORRENT_BASE64_SIZE = 50 * 1024 * 1024
+export const MAX_TORRENT_FILE_SIZE = (MAX_TORRENT_BASE64_SIZE / 4) * 3
+// Leave room for the JSON envelope, selected files and per-task options.
+export const DEFAULT_TORRENT_RPC_BODY_LIMIT_BYTES = 8 * 1024 * 1024
+export const MAX_TORRENT_RPC_BODY_LIMIT_BYTES = 64 * 1024 * 1024
export interface ParsedTorrentMetaInput {
name?: string
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index c3af4c1b..f4060586 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1848,13 +1848,13 @@
"taskList": "Task List",
"pauseTask": "Pause",
"resumeTask": "Resume",
- "deleteTask": "Delete",
- "moveTaskUp": "Move Up",
- "moveTaskDown": "Move Down",
+ "deleteTask": "Remove tasks…",
+ "moveTaskUp": "Move up in queue",
+ "moveTaskDown": "Move down in queue",
"pauseAllTask": "Pause All",
"resumeAllTask": "Resume All",
- "selectAllTask": "Select All",
- "clearRecentTasks": "Clear Recent"
+ "selectAllTask": "Select all tasks",
+ "clearRecentTasks": "Clear stopped task records…"
},
"edit": {
"title": "Edit",
@@ -2405,5 +2405,21 @@
"rowUnreadAria": "{{title}} (unread)",
"toastRegionAria": "Notifications"
}
+ },
+ "applicationMenu": {
+ "signOut": "Sign out…",
+ "back": "Back",
+ "serverUnavailable": "The server is unavailable. Your session has not been signed out.",
+ "retry": "Retry",
+ "actionFailed": "The action could not be completed. Check the connection and try again.",
+ "clearTitle": "Clear stopped task records?",
+ "clearDescription": "Remove completed, failed, and removed task records captured when this dialog opened. Downloaded files stay on disk.",
+ "clearConfirm": "Clear records",
+ "logoutTitle": "Sign out of this server?",
+ "logoutDescription": "This signs out other tabs using the same browser session. Downloads continue on the server. Unsaved input in those tabs will be discarded.",
+ "logoutConfirm": "Sign out",
+ "discardTitle": "Discard this task draft?",
+ "discardDescription": "Your unsaved links, torrent selection, and settings will be discarded.",
+ "discardConfirm": "Discard"
}
}
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 52d78784..cf3b4662 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1826,13 +1826,13 @@
"taskList": "任务列表",
"pauseTask": "暂停",
"resumeTask": "继续",
- "deleteTask": "删除",
- "moveTaskUp": "上移",
- "moveTaskDown": "下移",
+ "deleteTask": "移除任务…",
+ "moveTaskUp": "在队列中上移",
+ "moveTaskDown": "在队列中下移",
"pauseAllTask": "全部暂停",
"resumeAllTask": "全部继续",
- "selectAllTask": "全选",
- "clearRecentTasks": "清除最近任务"
+ "selectAllTask": "全选任务",
+ "clearRecentTasks": "清空已停止的任务记录…"
},
"edit": {
"title": "编辑",
@@ -2384,5 +2384,21 @@
"rowUnreadAria": "{{title}}(未读)",
"toastRegionAria": "通知"
}
+ },
+ "applicationMenu": {
+ "signOut": "退出登录…",
+ "back": "返回",
+ "serverUnavailable": "暂时无法连接服务器。当前会话尚未退出。",
+ "retry": "重试",
+ "actionFailed": "操作未完成,请检查连接后重试。",
+ "clearTitle": "清空已停止的任务记录?",
+ "clearDescription": "清除此对话框打开时已完成、失败或移除的任务记录,保留磁盘上的下载文件。",
+ "clearConfirm": "清空记录",
+ "logoutTitle": "退出此服务器?",
+ "logoutDescription": "使用同一浏览器会话的其他标签页也会退出。服务器上的下载会继续,这些标签页中未保存的输入将被丢弃。",
+ "logoutConfirm": "退出登录",
+ "discardTitle": "丢弃此任务草稿?",
+ "discardDescription": "未保存的链接、种子选择和设置将被丢弃。",
+ "discardConfirm": "丢弃"
}
}
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index ffdfc09d..ab2d45c8 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1834,13 +1834,13 @@
"taskList": "任務清單",
"pauseTask": "暫停",
"resumeTask": "繼續",
- "deleteTask": "刪除",
- "moveTaskUp": "上移",
- "moveTaskDown": "下移",
+ "deleteTask": "移除任務…",
+ "moveTaskUp": "在佇列中上移",
+ "moveTaskDown": "在佇列中下移",
"pauseAllTask": "全部暫停",
"resumeAllTask": "全部繼續",
- "selectAllTask": "全選",
- "clearRecentTasks": "清除最近項目"
+ "selectAllTask": "全選任務",
+ "clearRecentTasks": "清空已停止的任務記錄…"
},
"edit": {
"title": "編輯",
@@ -2384,5 +2384,21 @@
"grant": "允許"
}
}
+ },
+ "applicationMenu": {
+ "signOut": "登出…",
+ "back": "返回",
+ "serverUnavailable": "暫時無法連線至伺服器。目前工作階段尚未登出。",
+ "retry": "重試",
+ "actionFailed": "操作未完成,請檢查連線後重試。",
+ "clearTitle": "清空已停止的任務記錄?",
+ "clearDescription": "清除此對話框開啟時已完成、失敗或移除的任務記錄,保留磁碟上的下載檔案。",
+ "clearConfirm": "清空記錄",
+ "logoutTitle": "登出此伺服器?",
+ "logoutDescription": "使用同一瀏覽器工作階段的其他分頁也會登出。伺服器上的下載會繼續,這些分頁中未儲存的輸入將被捨棄。",
+ "logoutConfirm": "登出",
+ "discardTitle": "捨棄此任務草稿?",
+ "discardDescription": "未儲存的連結、種子選擇與設定將被捨棄。",
+ "discardConfirm": "捨棄"
}
}
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index cd94b609..67e58484 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -8,6 +8,9 @@ export const Commands = {
// renderer request per multi-select action instead of one per task.
// Renderer-IPC only — deliberately NOT MDXP methods; extensions and the
// CLI keep driving the singular task/* wire methods.
+ PauseAllTasks: 'command:pauseAllTasks',
+ ResumeAllTasks: 'command:resumeAllTasks',
+ ClearStoppedTasks: 'command:clearStoppedTasks',
PauseTasks: 'command:pauseTasks',
ResumeTasks: 'command:resumeTasks',
MoveTasks: 'command:moveTasks',
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index 1dae1385..4799dd61 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -113,6 +113,7 @@ export const Events = {
// Payload: EngineCompatibilityWarningPayload. Internal shell signal; the
// resulting durable NotificationAdded event is what reaches renderers.
EngineCompatibilityWarning: 'event:engineCompatibilityWarning',
+ RendererTaskMenuRequested: 'event:rendererTaskMenuRequested',
ApplicationMenuChanged: 'event:applicationMenuChanged',
// No payload; only the main window's current Downloads list handles this.
// Sent directly by the desktop shell, never through the core event bus.
diff --git a/src/shared/schemas/add-task.test.ts b/src/shared/schemas/add-task.test.ts
index c1003725..a4342711 100644
--- a/src/shared/schemas/add-task.test.ts
+++ b/src/shared/schemas/add-task.test.ts
@@ -102,6 +102,20 @@ describe('addTaskFormSchema', () => {
})
describe('taskCreateRequestSchema', () => {
+ it('rejects oversized Base64 at the shared command boundary', () => {
+ const result = taskCreateRequestSchema.safeParse({
+ type: 'bt',
+ payload: {
+ kind: 'torrent-base64',
+ base64: 'A'.repeat(50 * 1024 * 1024 + 4),
+ },
+ selectedFiles: [0],
+ saveDir: '/d',
+ })
+ expect(result.success).toBe(false)
+ if (!result.success)
+ expect(result.error.issues[0].path).toEqual(['payload', 'base64'])
+ })
it('accepts minimal http request', () => {
const result = taskCreateRequestSchema.safeParse({
type: 'http',
diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.ts
index 618d448e..57733885 100644
--- a/src/shared/schemas/add-task.ts
+++ b/src/shared/schemas/add-task.ts
@@ -1,3 +1,4 @@
+import { MAX_TORRENT_BASE64_SIZE } from '@shared/lib/torrent-meta'
import { z } from 'zod'
const torrentFileSchema = z.object({
@@ -85,7 +86,10 @@ const btTaskRequestSchema = z
.object({
type: z.literal('bt'),
payload: z.discriminatedUnion('kind', [
- z.object({ kind: z.literal('torrent-base64'), base64: z.string() }),
+ z.object({
+ kind: z.literal('torrent-base64'),
+ base64: z.string().max(MAX_TORRENT_BASE64_SIZE),
+ }),
z.object({
kind: z.literal('magnet'),
uri: z.string().startsWith('magnet:?'),
diff --git a/src/shared/schemas/application-menu.ts b/src/shared/schemas/application-menu.ts
index afc7a5af..553ed043 100644
--- a/src/shared/schemas/application-menu.ts
+++ b/src/shared/schemas/application-menu.ts
@@ -1,4 +1,5 @@
import { z } from 'zod'
+import { CommandIds } from '../commands-catalog'
export const applicationMenuNodeTypeSchema = z.enum([
'normal',
@@ -83,6 +84,7 @@ export const executeApplicationMenuItemRequestSchema = z
itemId: menuItemIdSchema,
revision: z.number().int().nonnegative(),
trigger: z.literal('menu'),
+ selectedTaskGeneration: z.number().int().nonnegative().optional(),
selectedTaskId: z.string().min(1).nullable(),
modifiers: applicationMenuModifiersSchema.optional(),
})
@@ -91,3 +93,18 @@ export const executeApplicationMenuItemRequestSchema = z
export type ExecuteApplicationMenuItemRequest = z.infer<
typeof executeApplicationMenuItemRequestSchema
>
+
+export const rendererTaskMenuRequestSchema = z
+ .object({
+ commandId: z.enum([
+ CommandIds.TaskPause,
+ CommandIds.TaskResume,
+ CommandIds.TaskDelete,
+ CommandIds.TaskMoveUp,
+ CommandIds.TaskMoveDown,
+ CommandIds.TaskClearStopped,
+ ]),
+ taskIds: z.array(z.string().min(1)),
+ generation: z.number().int().nonnegative(),
+ })
+ .strict()
diff --git a/src/shared/schemas/operator-auth.ts b/src/shared/schemas/operator-auth.ts
new file mode 100644
index 00000000..8019233a
--- /dev/null
+++ b/src/shared/schemas/operator-auth.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod'
+
+export const operatorStatusSchema = z.object({
+ authed: z.boolean(),
+ mode: z.enum(['cookie', 'bearer', 'unrestricted', 'unauthenticated']),
+ canLogout: z.boolean(),
+})
+
+export type OperatorStatus = z.infer<typeof operatorStatusSchema>
diff --git a/src/shared/schemas/torrent-request-limits.ts b/src/shared/schemas/torrent-request-limits.ts
new file mode 100644
index 00000000..9836c3d1
--- /dev/null
+++ b/src/shared/schemas/torrent-request-limits.ts
@@ -0,0 +1,13 @@
+import {
+ DEFAULT_TORRENT_RPC_BODY_LIMIT_BYTES,
+ MAX_TORRENT_RPC_BODY_LIMIT_BYTES,
+} from '@shared/lib/torrent-meta'
+import { z } from 'zod'
+
+export const torrentRpcBodyLimitSchema = z
+ .number()
+ .int()
+ .min(2 * 1024 * 1024)
+ .max(MAX_TORRENT_RPC_BODY_LIMIT_BYTES)
+ .multipleOf(1024 * 1024)
+ .default(DEFAULT_TORRENT_RPC_BODY_LIMIT_BYTES)
diff --git a/src/shared/types/menu-context.ts b/src/shared/types/menu-context.ts
index 99bf417f..aa233252 100644
--- a/src/shared/types/menu-context.ts
+++ b/src/shared/types/menu-context.ts
@@ -14,6 +14,14 @@ export interface MenuContext {
platform: 'darwin' | 'win32' | 'linux'
locale: SupportedLocale
+ // Committed Downloads selection; predicates exclude transient marquee state.
+ selectedTaskIds?: readonly string[]
+ selectedTaskGeneration?: number
+ selectedCanPause?: boolean
+ selectedCanResume?: boolean
+ selectedCanRemove?: boolean
+ selectedCanMove?: boolean
+
// Selected task
selectedTaskId: string | null
selectedTaskStatus: TaskStatus | null
diff --git a/tests/scripts/compose-server.test.ts b/tests/scripts/compose-server.test.ts
index df624483..a90092a9 100644
--- a/tests/scripts/compose-server.test.ts
+++ b/tests/scripts/compose-server.test.ts
@@ -70,6 +70,9 @@ describe('NAS-importable Compose contract', () => {
MOTRIX_ALLOWED_SAVE_DIRS: '/downloads',
MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: ALLOW_INSECURE_OPERATOR_HTTP,
MOTRIX_ARIA2_RPC_LISTEN_ALL: ARIA2_RPC_LISTEN_ALL,
+ MOTRIX_TORRENT_BODY_LIMIT_MIB: interpolation(
+ 'MOTRIX_TORRENT_BODY_LIMIT_MIB:-8'
+ ),
MOTRIX_DATA_DIR: '/data',
MOTRIX_DEFAULT_SAVE_DIR: '/downloads',
MOTRIX_MDXP_HOST: '0.0.0.0',