A full-featured download manager.
docs: add public Claude and Codex contributor guidance
Dr_rOotbbe78b1d5550
diff --git a/.claude/rules/architecture.md b/.claude/rules/architecture.mdnew file mode 100644index 00000000..a11fd47f--- /dev/null+++ b/.claude/rules/architecture.md@@ -0,0 +1,59 @@+---+description: Architecture boundaries for the shared desktop and server app+paths: ["src/**/*.ts", "src/**/*.tsx", "scripts/check-boundaries.mjs"]+---++# Architecture++Motrix keeps its product core host-neutral so it can run behind either the+Electron shell or the Node server and remain replaceable by a future engine.++## Layer Matrix++| Directory | Role | Allowed dependencies |+|-----------|------|----------------------|+| `src/renderer/` | Electron/browser frontend | `@shared/`, renderer-local modules |+| `src/core/` | Host-neutral product core | `@shared/`, host-neutral Node/external libraries |+| `src/main/` | Electron shell and IPC | `@core/`, `@shared/`, Electron |+| `src/preload/` | Electron bridge | pure `@shared/` protocol values/types, Electron |+| `src/server/` | Node/Docker shell | `@core/`, `@shared/`, server libraries |+| `src/shared/` | Cross-layer contracts | pure schemas, constants, data, and utilities only |++## Hard Boundaries++- `src/core/` never imports Electron or `src/main/`.+- `src/renderer/` never imports `src/core/`, `src/main/`, or `src/server/`.+- `src/server/` never imports Electron or `src/main/`.+- `src/shared/` never imports an application layer and contains no IO, timers,+ network access, Electron APIs, or Node-specific APIs.+- Production code never imports `src/test-utils/`; generated builtin plugin+ output is never used as source.++`pnpm run check:boundaries` is the automated baseline, but changed imports+must also be reviewed against the matrix because not every exception is+machine-enforced.++## Dual Transport Contract++The same renderer-facing transport contract serves both hosts:++```text+Electron: renderer -> ElectronTransport -> preload -> main IPC -> core+Browser: renderer -> HttpWsTransport -> server RPC/events -> core+```++Renderer command/query/event traffic uses `@renderer/lib/transport`. Direct+`window.motrix` access is limited to the Electron transport and narrowly scoped+Electron platform adapters; feature code stays behind those abstractions.+Events return through the selected shell and transport, so renderer state must+not depend on a host-specific channel.++All channel names come from `src/shared/protocol/`. Use `Commands`, `Queries`,+`Events`, and their `Bridge*` counterparts instead of raw strings.++## Engine Adapter++Product-level code targets `EngineAdapter` in+`src/core/engine/engine-adapter.ts`, never aria2 RPC types directly. Concrete+engines translate at the adapter boundary. `EngineSupervisor` is the sole+owner of engine start, stop, and restart lifecycle.diff --git a/.claude/rules/bridge.md b/.claude/rules/bridge.mdnew file mode 100644index 00000000..b45b94c7--- /dev/null+++ b/.claude/rules/bridge.md@@ -0,0 +1,97 @@+---+description: MDXP bridge lifecycle, authorization, transports, and protocol boundaries+paths: ["src/core/bridge/**", "src/core/bridge-receiver/**", "src/main/bridge/**", "src/server/bridge/**", "src/shared/protocol/bridge.ts", "src/shared/config/native-messaging-extensions.json", "packages/native-host/**", "package.json"]+---++# Bridge (MDXP / JSON-RPC 2.0)++The bridge uses JSON-RPC 2.0 over WebSocket and HTTP. The+[`@motrix/mdxp`](https://github.com/motrixapp/mdxp) package is the source of+truth for wire schemas, method constants, types, errors, and connection+behavior; its version comes from `package.json`. Do not recreate MDXP schemas,+numeric error codes, or the removed legacy frame protocol in this repository.+Import `ErrorCodes` and `makeMdxpError` from the package.++## Pairing and session lifecycle++- Extension WebSockets use `/pair?nonce=...` for first-time pairing and+ `/v1?token=...` for authenticated reconnects. Valid MDXP clients make+ `motrix/initialize` their first request on either route.+- `WebSocketBridgeServer` always owns and registers `motrix/initialize`.+ Shell-provided download handlers are registered separately and must be wired+ before `server.start()`; never expose a listener with incomplete handlers.+- Authorization and readiness are different states. A `/pair` connection is+ unauthorized until initialize completes an approved pairing; `/v1` is+ authorized when its token passes the upgrade gate. On extension WebSockets,+ all control-plane and download methods other than initialize and+ `system/ping` use `authorizedDispatch`; unary HTTP separately requires its+ bearer-token and agent-facing gates.+- A connection becomes ready only after the peer sends the+ `motrix/initialized` notification. Providers passed to+ `UrlResolutionService` must filter to ready connections before sending+ server-initiated `url/probe` or `url/resolve` requests.+- The connection close handler removes its own current session and disposes the+ connection. Do not mutate the server's session map from feature code.++Pair nonces are one-shot, expire after 60 seconds, and are consumed only by+`/pair`. Never persist them. `endpoint.json` contains discovery information and+a separate local CLI bearer token; the native host obtains a fresh nonce from+`GET /nonce`.++## Dispatch and transport exposure++`MdxpDispatcher` owns request-schema `safeParse` validation and returns+`InvalidParams`; handlers and `BridgeReceiver` receive typed data and enforce+business rules only. Keep `@core/bridge/` transport-neutral: the only production+file there allowed to import `ws` is `web-socket-bridge-server.ts`. Other files+use `WebSocketLike` from `web-socket-message-stream.ts`.++For every new MDXP method:++1. Define and publish its schema and method constant in the MDXP repository,+ then bump the published dependency here. Never commit a machine-local+ `link:` or `file:` dependency.+2. Register the schema and typed handler in the dispatcher. Use+ `setHandlers()` only for shell-supplied extension methods; shared+ control-plane methods belong in `registerReadHandlers` or+ `registerWriteHandlers`.+3. Choose and test exposure explicitly: unary HTTP, extension WebSocket, or+ both. Do not assume dispatcher registration exposes every transport.+4. For client notifications, register `conn.onNotification`. For outbound+ notifications, publish through `BridgeEventBus` and let the shell call+ `conn.sendNotification(Notifications.*, params)`. For outbound requests,+ use a domain service and pass a `CancellationToken` when work is cancellable.++Paired extensions may use the WebSocket control plane for `task/list`,+`task/get`, `task/pause`, `task/resume`, `task/remove`, `stats/get`, and+`engine/status`; keep the `dispatcher.has()` and authorization gates.+`download/add` is unary-only, while extensions submit through+`download/submit`. Renderer-only plural task commands must not enter MDXP.+Unary `/mdxp` admits only methods marked agent-facing; dispatcher registration+must not make extension handshake or submit methods reachable over HTTP.+Authenticated SSE streams must close when their pairing token is revoked.++Renderer-initiated URL resolution enters main through `BridgeQueries.*`; main+then sends MDXP `url/probe` / `url/resolve` requests to ready extensions. Use+the shared channel constants. For cancellation, renderer supplies a request ID,+main owns its `CancellationTokenSource`, and the matching cancel query aborts it.++## Native Messaging host++`packages/native-host/` is a standalone Rust executable spawned by Chromium or+Firefox. It reads only the endpoint port, calls loopback `GET /nonce`, and+returns `{ action: 'requestPair', port, nonce }`. It must not expose the local+CLI token or depend on system Node.js or Electron. Production extension IDs+come from `src/shared/config/native-messaging-extensions.json`; development IDs+may be added only through `MOTRIX_DEV_TRUSTED_EXTENSIONS` and must never ship as+production defaults.++## Verification++Run the global gate in `commit-and-quality.md`, then the scoped bridge checks;+do not encode a fixed test count:++```bash+pnpm exec biome check src/core/bridge/ src/core/bridge-receiver/ src/main/bridge/ src/server/bridge/+pnpm exec vitest run src/core/bridge/ src/core/bridge-receiver/ src/main/bridge/ src/server/bridge/+```diff --git a/.claude/rules/code-style.md b/.claude/rules/code-style.mdnew file mode 100644index 00000000..5c61f51c--- /dev/null+++ b/.claude/rules/code-style.md@@ -0,0 +1,40 @@+---+description: TypeScript naming, import, alias, and schema conventions+paths: ["src/**/*.ts", "src/**/*.tsx", "src/**/*.css", "*.config.ts"]+---++# Code Style++Biome owns formatting and general lint rules; do not duplicate its settings+here. The conventions below cover repository-specific boundaries.++## Naming++- JavaScript, TypeScript, TSX, and stylesheet files use `kebab-case`.+- Conventional qualifiers remain lowercase: `.test`, `.spec`, `.e2e`,+ `.integration`, `.darwin`, and `.win32`.+- Exported classes and React components remain PascalCase even though their+ filenames are kebab-case.+- Rust and Python use `snake_case`; Cargo binary entrypoints may use+ kebab-case to match the executable name.+- Run `pnpm run check:file-names` after adding or renaming files.++## Imports and Aliases++- Use `import type` for type-only imports and `node:` for Node builtins.+- Prefer the configured alias over a deep relative import; local sibling or+ parent imports may remain relative.+- Alias availability is target-specific. Application builds expose+ `@shared`, `@core`, `@renderer`, and `@main` as appropriate; server targets+ may expose `@server`, and tests may expose `@test-utils`.+- Do not assume aliases cross targets: Vitest intentionally has no `@main`,+ and the QuickJS worker exposes only `@shared` and `@core`. Check the target's+ TypeScript and Vite configuration before using an alias.++## Shared Runtime Contracts++Use Zod from `zod` for untrusted external data and cross-layer payloads. A+shared schema is the source of truth for its runtime constraints, inferred+type, and defaults; do not create parallel interfaces or hand-written+validators for the same contract. Pure cross-layer schemas belong in+`src/shared/schemas/`; host-specific validation stays in its owning layer.diff --git a/.claude/rules/commit-and-quality.md b/.claude/rules/commit-and-quality.mdnew file mode 100644index 00000000..ffbdb392--- /dev/null+++ b/.claude/rules/commit-and-quality.md@@ -0,0 +1,49 @@+---+description: Required commit gate and change-specific validation+---++# Commit & Quality Gate++## Required for Every Commit++Run all three commands and fix failures before committing:++```bash+pnpm run check:boundaries+pnpm exec biome check src/+pnpm exec tsc --noEmit+```++`check:boundaries` is an automated baseline, not a complete architecture+proof. Review changed imports against `architecture.md` as well.++Stage only the intended files or hunks, then inspect `git diff --staged` and+run `git diff --cached --check`. Do not hide failures because a CI job is+non-blocking.++## Change-Specific Checks++Run every check that matches the change:++- Behavior or logic: focused tests with `pnpm exec vitest run <test-path>`;+ use `pnpm test` for broad cross-cutting changes.+- Browser/Electron user flows: `pnpm test:e2e` when the affected flow has E2E+ coverage.+- Locale resources or i18n behavior: `pnpm run check:i18n`.+- Added or renamed files: `pnpm run check:file-names`.+- Plugin manifest contracts or `@motrix/plugin-manifest-schema`:+ `pnpm run check:schema-parity`.+- Dependencies, bundled assets, or license metadata:+ `pnpm run check:third-party-notices`.+- Native host Rust:+ ```bash+ cargo fmt --manifest-path packages/native-host/Cargo.toml --all -- --check+ cargo clippy --manifest-path packages/native-host/Cargo.toml --all-targets --locked -- -D warnings+ cargo test --manifest-path packages/native-host/Cargo.toml --locked --all-targets+ ```+- Packaging or release code: run the focused tests under `tests/scripts/` and+ the relevant verifier. Follow workflow-supplied arguments for checks such as+ `check:update-artifacts`.++Use `pnpm exec biome check --write src/` only for reviewed, auto-fixable+issues; re-run the required gate afterward.diff --git a/.claude/rules/domain-model.md b/.claude/rules/domain-model.mdnew file mode 100644index 00000000..50b04c81--- /dev/null+++ b/.claude/rules/domain-model.md@@ -0,0 +1,40 @@+---+description: Engine-neutral domain aggregates, validation, defaults, and errors+paths: ["src/shared/**", "src/core/**"]+---++# Domain Model++## Engine-Neutral Aggregates++Product-level code never exposes aria2 raw types or naming. Aria2 values are+translated at the engine adapter boundary into the aggregates in+`src/shared/types/`:++- `DownloadTask`, `TaskStatus`, and `TaskType` describe task identity and+ lifecycle; `BtExtension` carries BitTorrent-only details.+- `EngineState` and `EngineFeatureReport` describe engine lifecycle and+ detected capabilities without binding consumers to an RPC implementation.+- `AppSettings` is the persisted aggregate; `EngineSettings` and+ `MotrixAppSettings` separate engine-facing and application-facing concerns.+- `GlobalStats` is the cross-engine aggregate used by UI and protocol layers.++Keep managers and stores engine-neutral (`<Domain>Manager`, `<Domain>Store`).+Engine-specific conversion and RPC fields stay under the concrete adapter.++## Schemas and Defaults++- Cross-layer runtime schemas live in `src/shared/schemas/`; core may compose+ them but must not duplicate their constraints.+- Settings schemas use `.catch(safeDefault)` for recoverable persisted values.+- Derive aggregate defaults from the schema, for example+ `const DEFAULTS = schema.parse({})`, so validation and defaults cannot drift.+- Error codes used by settings validation follow+ `settings.{namespace}.{field}` for localization.++## Errors++Use `AppError` and `ErrorCode` from `@shared/errors` for domain failures that+cross a service, transport, or UI boundary. Raw `Error` remains appropriate+for low-level implementation failures that are caught and translated before+leaving their owning layer.diff --git a/.claude/rules/electron-vite.md b/.claude/rules/electron-vite.mdnew file mode 100644index 00000000..d381b99e--- /dev/null+++ b/.claude/rules/electron-vite.md@@ -0,0 +1,62 @@+---+description: Build outputs, Electron loading policy, pnpm scripts, and native ABI boundaries+paths: ["electron-builder.json", "pnpm-workspace.yaml", "package.json", "Dockerfile", "vite.*.config.ts", "scripts/dev.mjs", "scripts/postinstall.mjs", "scripts/ensure-native-abi.mjs", "scripts/native-binary-target.mjs", "scripts/stage-*-app.mjs", "scripts/verify-*-package.mjs", "scripts/before-*-*.mjs", "src/main/index.ts", "src/main/window/renderer-url-policy*", "src/main/window/window-manager*", "src/preload/**"]+---++# Electron + Vite++## Required Artifacts++| Target | Output |+|--------|--------|+| Electron main | `dist/main/index.cjs` |+| preload | `dist/preload/preload.cjs` |+| QuickJS worker | `dist/core/plugin/host/quick-js-worker.cjs` |+| Electron renderer | `dist/renderer/` |+| Node server and CLI | `dist/server/index.mjs`, `dist/server/motrix-admin.mjs` |+| browser renderer | `dist/renderer-web/` |++Because `package.json` declares `"type": "module"`, main, preload, and worker+outputs must remain `.cjs`; server outputs remain `.mjs`. The package `main`+field must match the main artifact. Build entries sharing an output directory+must have unique basenames, and every consuming `build:*` flow must produce+the entries it packages.++## Preload and Renderer URL Policy++At runtime `__dirname` is `dist/main/`, so the preload path is:++```ts+path.join(__dirname, '../preload/preload.cjs')+```++Renaming or moving either artifact requires updating this path. Pass+`VITE_DEV_SERVER_URL` once to `initializeRendererUrlPolicy()` and load every+renderer window through `rendererUrlPolicy.loadWindow(win, route)`. Do not add+feature-local `loadURL()` or `loadFile()` calls that bypass its loopback-origin+and packaged-file checks.++## pnpm and Native ABI++- Project pnpm settings belong in `pnpm-workspace.yaml`. Keep `nodeLinker:+ hoisted` unless the Electron packaging smoke job proves isolated linking+ works.+- Install-script permission is controlled by pnpm 11 `allowBuilds`. Keep+ `electron` allowed: its install script supplies the runtime and license+ payload required by packaging and legal checks.+- Native modules such as `better-sqlite3` must match the active ABI. Tests use+ the Node ABI; Electron and E2E use the Electron ABI. Preserve the+ `ensure-native-abi.mjs` hooks when changing test or start scripts.+- `postinstall.mjs` independently controls Electron rebuild and aria2 fetch+ through `MOTRIX_SKIP_ELECTRON_REBUILD` and `MOTRIX_SKIP_ENGINE_FETCH`.+ Skipping one must never imply skipping the other.+- If Electron or a native dependency changes, rebuild for the intended target+ and exercise the corresponding Node and Electron paths.++## Server Docker Boundary++The server image uses system aria2 and skips both Electron rebuild and engine+fetch. `stage-server-app.mjs` selects one target-platform `better-sqlite3`+prebuild, and `verify-server-package.mjs` verifies the staged payload. The+runtime image intentionally has no pnpm or build toolchain; never rely on a+runtime native rebuild.diff --git a/.claude/rules/git-workflow.md b/.claude/rules/git-workflow.mdnew file mode 100644index 00000000..7ff32f13--- /dev/null+++ b/.claude/rules/git-workflow.md@@ -0,0 +1,61 @@+---+description: Git commit, branch, PR, merge, and release policy+---++# Git Workflow++## Commits++Use Conventional Commits in English:++```text+<type>(<optional-scope>): <imperative summary>+```++Allowed types are `feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `chore`,+`ci`, and `style`. Keep the summary lowercase, without a period, and under 72+characters. Add a body for non-obvious rationale and a+`BREAKING CHANGE: ...` footer when applicable.++Do not add AI attribution or co-author trailers automatically. Preserve+trailers explicitly supplied by a contributor or required by legal policy.+Follow `commit-and-quality.md` before creating a commit.++## Branches and Pull Requests++- `main` is the protected active branch; `master` is frozen legacy code. Never+ target or merge Turbo work into `master`.+- Branch from current `main`. Use+ `<type>/<snake_case_topic>_<YYYYMMDD>`, optionally placing an issue number+ before the topic.+- Never push directly or force-push to `main`. All changes use PRs.+- Rebase a private feature branch onto `main` before review. Never rebase+ `main` or a branch shared with other contributors.+- After a rebase, update only your own feature branch with+ `git push --force-with-lease`; never use an unconditional force push.+- Keep a PR focused. Its title follows Conventional Commits; its description+ explains what, why, and how the change was verified.+- Squash merge feature PRs by default. Use a regular merge only when a release,+ hotfix, or intentionally structured refactor needs commit-level history.+- Delete merged branches.++## Release Safety++The checked-in workflows and scripts are the release authority; do not replace+them with local publishing steps.++- Set `package.json` to strict SemVer, then create a protected+ `v<package-version>` tag whose commit is on `main`. The tag and package+ versions must match; only stable and `beta` channels are supported.+- A tag push triggers `.github/workflows/release.yml`. Publishing is allowed+ only after its platform builds, isolated signing jobs, signature/package+ verification, artifact assembly, and update-artifact validation succeed.+ Manual dispatch validates the build path but does not sign or publish.+- Do not manually upload release files, reuse unverified artifacts, bypass+ protected environments, weaken signing-input isolation, or overwrite an+ existing immutable container tag.+- Protected tags publish one verified amd64/arm64 Snap build set to+ `latest/edge`. Promote those exact revisions with `snap-promote.yml` from+ protected `main`; never rebuild during promotion. Stable rejects prereleases.+- If a release gate fails, fix the source or workflow and run the complete+ gated path again. Do not publish a partial platform set.diff --git a/.claude/rules/i18n.md b/.claude/rules/i18n.mdnew file mode 100644index 00000000..bd7cbbc1--- /dev/null+++ b/.claude/rules/i18n.md@@ -0,0 +1,66 @@+---+description: Internationalization contracts for renderer/main strings and locale resources+paths: ["src/renderer/**/*.ts", "src/renderer/**/*.tsx", "src/main/**/*.ts", "src/core/i18n/**", "src/core/plugin/plugin-registry*", "src/core/plugin/capabilities/i18n*", "src/core/plugin/manifest/i18n-resolve*", "src/server/index.ts", "src/server/operator-admin*.ts", "src/shared/constants/locales*.ts", "src/shared/schemas/locale*.ts", "src/shared/i18n-resources.ts", "src/shared/locales/*.json", "scripts/check-i18n.mjs", "tests/scripts/check-i18n.test.ts"]+---++# Internationalization++Every user-visible application or operator string must use i18next; do not+hardcode UI labels, messages, notifications, dialogs, or CLI output. Renderer+components use `react-i18next`; Electron main uses the initialized instance+from `src/main/lib/i18n.ts`; the server operator CLI creates an isolated+instance from shared resources. Keep `t` in React hook dependency arrays.+Route host-wide locale changes through `LocaleCoordinator`: serialize changes,+skip stale revisions, reconcile late targets, and publish `LocaleChanged` only+after the current apply succeeds. Keep plugin-registry and capability-host+locale changes transactional, including rollback on failure.++## Resource contract++- `src/shared/locales/en-US.json` is the key-shape source of truth. Add every+ logical key to every locale registered in `SUPPORTED_LOCALES`; never update+ only a subset.+- `src/shared/i18n-resources.ts` statically and exhaustively registers those+ locale files. New languages also require a catalog entry in+ `src/shared/constants/locales.ts` and a matching JSON resource.+- Every translation leaf is a string. Keep readable locale files as UTF-8;+ avoid unnecessary `\uXXXX` escapes.+- Preserve the exact `{{placeholder}}` set across every locale and every plural+ variant.+- Plural keys use i18next category suffixes. Supply every cardinal category+ returned by `Intl.PluralRules(locale)`; `_zero` is the only permitted extra+ category because i18next treats it as an exact-zero override.++## Namespaces++Keys follow the feature that owns them and use camelCase leaves; descriptions+normally pair `name` with `nameDesc`.++- Settings grid cards: `settings.cards.<card>.*`+- Settings dialogs/pages: `settings.<dialog>.*`+- BitTorrent settings and tracker defaults: `settings.bittorrent.*`+- Tracker management: `trackers.effective.*`, `trackers.blacklist.*`,+ `trackers.combobox.*`, and `trackers.sync.*`++Extend the relevant namespace rather than creating a parallel spelling or+placing tracker UI under settings merely because trackers are configurable.++## Marketplace locale independence++Application locales and registry listing locales are separate contracts.+`SupportedLocale` must not constrain `listing.defaultLocale` or keys in the+registry's open BCP 47 `listing.localizations` map. Resolve marketplace display+and search text with the vendored registry resolver; do not use+`resolveSupportedLocale` or infer sibling regions such as `zh-TW -> zh-CN`.++## Verification++Run `pnpm run check:i18n` after any locale, catalog, placeholder, plural, or+resource-registration change. It verifies file/catalog parity, logical key+coverage, plural categories, string leaves, and placeholder parity. Its tests+must use temporary fixtures and never rewrite real locale files. Tests that+render translated components load the real renderer initialization with:++```ts+import '@renderer/lib/i18n'+```diff --git a/.claude/rules/language-and-docs.md b/.claude/rules/language-and-docs.mdnew file mode 100644index 00000000..a5bbd1b5--- /dev/null+++ b/.claude/rules/language-and-docs.md@@ -0,0 +1,32 @@+---+description: Language, bilingual public docs, and private-context boundaries+---++# Language & Documentation++## Language++- Code, comments, commits, PR titles, branches, file names, and identifiers are+ English.+- Respond to users in the language they use.++## Public Documentation++- New end-user guides and documents with an existing translated counterpart+ ship as English `<name>.md` and Chinese `<name>.zh-CN.md` pairs.+- Governance files, generated artifacts, and subtree/developer READMEs may stay+ single-language unless maintainers establish a pair.+- When editing one file in a pair, update the other in the same change. Keep+ headings, commands, paths, and code samples aligned while writing idiomatic+ prose in each language.+- `docs/` contains reviewed public artifacts, not private design material.++## Public/Private Boundary++- Machine-specific agent context belongs in ignored `CLAUDE.local.md`.+- Never commit private plans, prompts, handoffs, credentials, private+ application or vault names, or absolute local paths.+- Public contribution workflows must work from a normal checkout without a+ private account, application, or adjacent repository.+- Rewrite private source material as a standalone public artifact and review+ it before committing.diff --git a/.claude/rules/panel-layout.md b/.claude/rules/panel-layout.mdnew file mode 100644index 00000000..4a8fd844--- /dev/null+++ b/.claude/rules/panel-layout.md@@ -0,0 +1,48 @@+---+description: Height-chain and sticky-scroll rules for panels inside SidebarInset+paths: ["src/renderer/routes/**/*.tsx", "src/renderer/layouts/app-layout*.tsx", "src/renderer/components/ui/sidebar*.tsx", "src/renderer/components/desktop-kit/panel/**", "src/renderer/components/settings-kit/**/*.tsx"]+---++# Panel Layout++Pages inside `SidebarInset` stay within the viewport. The document and panel+shell do not scroll; the innermost data region owns scrolling.++## Height chain++Every flex ancestor between the viewport clamp and the data region must allow+its child to shrink:++```text+SidebarProvider h-svh overflow-hidden+ SidebarInset flex-1 min-h-0 overflow-hidden+ PanelShell h-full flex flex-col+ content flex-1 min-h-0 flex flex-col+ Tabs flex-1 min-h-0 flex flex-col+ list shrink-0+ content flex min-h-0 flex-1+ panel flex min-h-0 flex-1 flex-col+ fixed regions shrink-0+ data region flex min-h-0 flex-1 overflow-auto+```++`flex-1` without `min-h-0` is insufficient because the default intrinsic+minimum height lets content grow the page.++## Scrolling and sticky content++- The chain has exactly one `overflow-auto`: the leaf data region. Ancestors+ use `overflow-hidden` where a clamp is needed; do not make `PanelShell`,+ `Tabs`, or `TabsContent` a competing scroller.+- Non-scrolling headers, filters, summaries, tab lists, and footers use+ `shrink-0`.+- A sticky column header is the first child inside the scroll region so+ `sticky top-0` resolves against the intended scroller.+- Sticky content needs an opaque background, `z-10`, and `border-b`; a separate+ separator sibling scrolls away and does not preserve the boundary.+- Under tabs, keep `TabsContent` as `flex min-h-0 flex-1` and its panel as+ `flex min-h-0 flex-1 flex-col` so both axes remain bounded.++When changing a panel, verify that the page has no document scrollbar, only the+data region scrolls, sticky headers remain readable, and the inset/footer stay+visible at short viewport heights.diff --git a/.claude/rules/plugin-registry.md b/.claude/rules/plugin-registry.mdnew file mode 100644index 00000000..b6f658c8--- /dev/null+++ b/.claude/rules/plugin-registry.md@@ -0,0 +1,48 @@+---+description: Plugin registry wire, locale, query, consent, and install contracts+paths: ["src/shared/schemas/registry*", "src/core/plugin/registry/**", "src/core/plugin/install/**", "src/core/plugin/manifest/parse*", "src/renderer/routes/plugins/**", "src/main/platform/protocol-manager*", "src/main/ipc/queries.ts", "src/main/ipc/commands.ts", "src/server/ipc/queries.ts", "src/server/plugin/install-service.ts"]+---++# Plugin Registry++The app consumes the registry v2 wire contract published at+`https://dl.motrix.app/registry/plugins.json`. The external registry repository+owns the source schema; this app vendors a tolerant schema, listing resolver,+fixture, and conformance corpus.++## Wire and Conformance++- Published v2 evolution is additive-only. Never rename, retype, or remove a+ field. Coordinate schema changes across the registry publisher, this app,+ and website, including the byte-identical fixture and all conformance+ channels.+- Parse registry data with the vendored Zod schema. Unknown additive fields+ and category slugs remain wire-valid; narrow them only at presentation+ boundaries. Invalid responses preserve the last-good cache rather than+ crashing marketplace UI.+- `listing.defaultLocale` and the open `listing.localizations` map use the+ registry BCP 47 profile independently of the app's `SupportedLocale`.+ Resolve display/search text through the shared field-level resolver and do+ not infer sibling regions such as `zh-TW -> zh-CN`.++## Install and Consent++- Allowlist the initial HTTPS package URL. Accept redirects only with bounded+ streaming, then verify final size and the registry SHA-256 before parsing+ the manifest.+- Parsed manifest `id`, `version`, and `engines.motrix` must equal the registry+ entry. Its required, optional, and host permissions must each be a subset of+ the corresponding registry preview. Any mismatch aborts installation, and+ grants always derive from the parsed manifest.+- Reserved publisher namespaces remain unavailable to community manifests.+ Incompatible entries remain viewable but not installable.+- `motrix://plugins/<id>` is navigation-only. It must not encode or trigger an+ install; every installation requires the in-app consent flow.++## Query Contract++Both Electron and server handlers expose+`Queries.ListRegistryPlugins` / `Queries.GetRegistryPlugin`, delegate to the+same `RegistryClient` semantics, and return compatibility information. Keep+these shared query payloads host-independent; do not create renderer- or+shell-specific mirrors or raw channel names.diff --git a/.claude/rules/plugins.md b/.claude/rules/plugins.mdnew file mode 100644index 00000000..5dddf12f--- /dev/null+++ b/.claude/rules/plugins.md@@ -0,0 +1,61 @@+---+description: Plugin core, sandbox, capability, builtin, and schema boundaries+paths: ["src/core/plugin/**", "src/main/plugin/**", "src/server/plugin/**", "src/renderer/routes/plugins/**", "scripts/fetch-builtins.mjs", "scripts/builtins.lock.json", "scripts/builtins-signing.pub.pem", "vite.worker.config.ts", "Dockerfile"]+---++# Plugins++## Core and Shell Ownership++`src/core/plugin/` owns host-neutral plugin state, policy, manifest/install+logic, capabilities, and sandbox orchestration. Electron adapters and assembly+live in `src/main/plugin/`; Node/Docker equivalents live in+`src/server/plugin/`. Never import a shell into core.++Every shell integration and host-specific capability must be wired and tested+in both capability hosts. Keep a single core implementation when behavior is+host-neutral; differences such as Electron notifications remain adapters.++## QuickJS Sandbox++Guest code executes in the separate QuickJS worker built from+`src/core/plugin/host/quick-js-worker.ts` to+`dist/core/plugin/host/quick-js-worker.cjs` for both Electron and server+bundles. Its Vite target exposes only `@shared` and `@core`; never expose or+import `@main`, `@server`, `@renderer`, Electron, or another host API.++Guest access to host behavior must cross the typed capability bridge, which+owns dispatch classification plus phase and permission checks. Hook circuit+policy stays in the hook orchestrator and circuit-breaker modules. When adding+a capability:++1. define its core contract and bridge classification/dispatch tests;+2. wire and test it in both Electron and server capability hosts;+3. add the manifest permission and run schema parity checks.++## Builtin Supply Chain++Builtin source lives outside this repository and is consumed only as pinned,+signed `.moext` releases. `fetch-builtins.mjs` must verify the lockfile+SHA-256, detached Ed25519 signature against the pinned public key, and lock+record before unpacking. Never trust release metadata as the digest source or+weaken verification to handle an unavailable artifact.++Server builds must carry verified seeds into the runtime image and set+`MOTRIX_BUILTIN_PLUGIN_DIR`; otherwise a missing directory is tolerated and+the image silently starts without builtins. Container builtin updates require+a new image rather than an in-place sync.++## Manifest Schema Parity++`src/core/plugin/manifest/schema.ts` remains a pure re-export of the published+`@motrix/plugin-manifest-schema`. Do not maintain a second host schema. After+changing manifest contracts or bumping the schema package, run:++```bash+pnpm run check:schema-parity+```++Builtin seeds belong in `dist/builtin-plugins/`, verified archives in+`dist/builtin-moext/`, and only the QuickJS worker in+`dist/core/plugin/host/`.diff --git a/.claude/rules/renderer.md b/.claude/rules/renderer.mdnew file mode 100644index 00000000..eb92f150--- /dev/null+++ b/.claude/rules/renderer.md@@ -0,0 +1,74 @@+---+description: Renderer component, transport, settings-form, and responsive conventions+paths: ["src/renderer/**/*.tsx", "src/renderer/**/*.ts", "src/renderer/**/*.css"]+---++# Renderer++## Component boundaries++Use the existing three layers:++1. `src/renderer/components/ui/` contains minimally adapted shadcn primitives.+2. `src/renderer/components/desktop-kit/` contains desktop interaction and+ layout wrappers such as panels, sidebars, selection, and virtual lists.+3. `src/renderer/components/settings-kit/` contains reusable settings controls+ and restart/configuration helpers.++Feature-specific composition stays with its route. Do not move domain behavior+into `ui/`, and do not bypass an existing desktop/settings wrapper by cloning it.++## State and transport++- Renderer code never imports `@core/`, `@main/`, or `@server/`. Use the+ singleton renderer transport with shared `Commands`, `Queries`, `Events`, and+ `Bridge*` constants; never raw channel strings.+- UI-only state belongs in component state or a feature-local external store.+ Core state comes from `transport.invoke(...)`; renderer mirrors are caches,+ not an independent source of truth.+- Subscribe through `transport.on()` and remove the same callback with+ `transport.off()` during cleanup. For event-backed mirrors, subscribe before+ taking the initial snapshot, guard stale async results, and refresh after+ transport reconnects so events cannot be lost across the snapshot gap.+- Coalesce, throttle, or select narrowly from high-frequency event streams to+ avoid whole-page rerenders. Use the virtual-list layer for large task/data+ collections.++## Settings forms++Settings dialogs use shadcn form components with `react-hook-form`. Reuse schemas+and defaults from `src/shared/schemas/`; use `zodResolver` when the form owns a+matching schema. Composite controls may normalize input locally and rely on the+shared/core commit-boundary schema, but must not duplicate its validation or+create renderer-only contract mirrors.++- Boolean settings use `Switch`; reserve `Checkbox` for multi-select lists.+- Dialog and batched forms persist only on Apply/submit through+ `transport.invoke(Commands.UpdateSettings, patch)`. Build the patch from dirty+ fields and preserve top-level namespaces such as `engine`, `app`, and+ `speedLimit`; never send unchanged keys accidentally.+- A standalone setting may auto-save a focused patch only when immediate save+ is explicit in that control's UX. Updating local form state does not by itself+ authorize persistence.+- Disable Apply while `formState.isSubmitting` to prevent duplicate writes.++Settings dialogs use the repository's compact density:++- `FormItem`: `flex items-start justify-between gap-4`; label/description column:+ `space-y-1`; `FormDescription`: `text-xs`.+- Every `DialogFooter` button uses `size="sm"`. Editable dialogs show Cancel+ (`outline`) then Apply (`type="submit"`); read-only dialogs show one Close.+- Follow `routes/settings/cards/downloads-dialog.tsx` and+ `advanced-dialog.tsx` when adding or restructuring a form.++## Compact headers and failure surfaces++Headers enter compact mode below `md` or when `sidebar-wrapper` is collapsed.+For style-only changes use the `compact-header:` variant defined in+`src/renderer/styles/globals.css`; do not duplicate the underlying media and+group selectors. For structural JSX changes use `useCompactHeader()` from+`components/desktop-kit/hooks/use-compact-header.ts`.++Add an Error Boundary when a new page or panel owns an independent failure+surface. Keep the boundary close enough that unrelated navigation and controls+remain usable.diff --git a/.gitignore b/.gitignoreindex 166e8971..60b8be0a 100644--- a/.gitignore+++ b/.gitignore@@ -134,6 +134,8 @@ dist-test/.claude/settings.local.json.claude/worktrees/.claude/projects/+# Personal per-machine Claude instructions+CLAUDE.local.md# Superpowers brainstorming / visual companion artifacts.superpowers/diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 00000000..1fd6c5da--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,18 @@+# AGENTS.md++Claude Code rules are the canonical agent guidance for this repository. Codex+inherits them instead of maintaining a second copy.++Before inspecting or changing files, read:++1. `CLAUDE.md`.+2. Every `.claude/rules/*.md` file without `paths` frontmatter.+3. Every rule whose `paths` patterns match the files being inspected or+ changed.++If the scope expands, load the newly matching rules before continuing. Do not+load unrelated path-scoped rules by default.++Conflicts resolve in this order: current user instructions, this file,+`CLAUDE.md`, matching `.claude/rules/*.md`, then default agent behavior.+Update the canonical Claude rules rather than duplicating guidance here.diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 00000000..4f68d748--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,58 @@+# CLAUDE.md++## Project++Motrix Turbo is an Electron and Node/Web download manager. Keep `src/core/`+host-neutral so it can be reused by both shells and replaced independently.++Development happens on **`main`**. The frozen **`master`** branch is the legacy+Electron 22/Vue 2 application. Branch from and target PRs at `main`, never+`master`.++## Core Commands++```bash+pnpm start # Electron development runner+pnpm start:server # Built Node/Web server+pnpm test # Vitest suite+pnpm exec vitest run <test-path> # Focused test+pnpm run lint # Biome over the repository+pnpm exec tsc --noEmit # Type-check+pnpm build # Desktop production build+pnpm build:server # Node/Web production build+pnpm test:e2e # Playwright suite+```++Use `pnpm exec`, not `npx`. The authoritative commit gate is+`.claude/rules/commit-and-quality.md`.++## Architecture Boundaries++1. `src/core/` never imports `electron` or `src/main/`.+2. `src/renderer/` never imports `src/core/`, `src/main/`, or `src/server/`;+ use `@renderer/lib/transport` with shared protocol constants.+3. `src/shared/` contains pure cross-layer contracts and descriptive runtime+ data only: no IO, timers, network, Electron, or Node-specific APIs.+4. Use `Commands`, `Queries`, `Events`, and their `Bridge*` counterparts from+ `src/shared/protocol/`; never use raw transport channel strings.++## Rule Routing++Rules without `paths` frontmatter are global. Load path-scoped rules only when+their patterns match the files under inspection or modification.++| Rule | Scope |+|---|---|+| `commit-and-quality.md` | Required checks and conditional validation |+| `git-workflow.md` | Commits, branches, PRs, and releases |+| `language-and-docs.md` | Language and public/private documentation |+| `architecture.md` | Layer boundaries and transport flow |+| `electron-vite.md` | Build, packaging, native ABI, and pnpm |+| `code-style.md` | TypeScript, React, CSS, and file naming |+| `renderer.md` | Renderer state, components, forms, and transport |+| `panel-layout.md` | Viewport height and scrolling layout |+| `i18n.md` | Locale catalogs and user-visible strings |+| `domain-model.md` | Shared domain types, validation, and errors |+| `plugins.md` | Plugin sandbox, capabilities, and builtins |+| `plugin-registry.md` | Registry compatibility and install integrity |+| `bridge.md` | MDXP pairing, dispatch, and transports |