The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
docs: Agent
XiaoYouChRd0a4e1d5902a
diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 00000000..5cd96c94--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1,95 @@+# CLAUDE.md++## 思想(宪法——遇到下面任何规则没覆盖的场景,回到这里判断)++- **Simple is better than complex.** (Zen)+- **Flat is better than nested.** (Zen) — 函数优于类、内联优于跳转、三行重复优于过早抽象+- **Explicit is better than implicit.** (Zen) — 依赖显式传入、配置显式注入、不靠模块级全局状态做隐式耦合+- **Readability counts.** (Zen) — 代码被读 > 被写。从业务角度命名,不用生僻词;「注释只写 Why」的前提是代码本身能说明 What+- **Signal-driven actors.** — Service 拥有私有状态,对外通信仅通过信号;Service 不持 View 引用(View 持 Service 引用以 connect 信号是允许的)+- **YAGNI — trust internals, validate at boundaries.** — 不写 hypothetical 防御,删除胜于注释掉,不留向后兼容别名+- **If the implementation is hard to explain, it's a bad idea.** (Zen) — 解释起来绕的设计,多半是错的++## 命名++- 类名 PascalCase,函数和变量 camelCase+- 函数名用动词前缀(PowerShell 风格):`taskService.add()`、`featureService.parse()`+- 选短词、常见词,第一次读代码的人也能看懂+- 类名提供了上下文后,去掉冗余名词:`taskService.add()` 不写 `addTask()`+- 名词锁定到 CONTEXT.md,不用近义词:`task` 不写 `download`,`name` 不写 `title`+- 不用 `_` 前缀标记模块内部函数——模块边界本身就是封装+- Actor 以它拥有的业务概念命名,禁用 manager、controller、coordinator、provider、repository、facade、pipeline、context+- 布尔值用 `is*` / `has*` / `can*` / `should*` 前缀+- 信号 `{noun}{PastParticiple}`(`taskAdded`、`speedChanged`);类名已提供上下文时可只用 `{PastParticiple}`。槽 `_on{Noun}{PastParticiple}`+- 名词查找用名词形式:`taskById(id)`、`categoryById(id)`。`find*` 留给磁盘/PATH 搜索+- 文件系统词:`folder`(确定是目录)、`file`(确定是文件)、`path`(可能是文件或目录)++## 动词表++封闭词汇表——函数名只能从这里选动词。选不出说明职责不清或 seam 错了。++| 动词 | 语义 |+|---|---|+| `load` | 读取本地持久化数据或资源。非 fetch |+| `save` | 持久化应用状态 |+| `fetch` | 一次网络请求获取数据。非 load |+| `probe` | 查询能力或元数据,不创建任务 |+| `parse` | 将文本/协议输出转为应用对象 |+| `match` | 判断候选是否符合规则 |+| `find` | 搜索本地磁盘或 PATH |+| `build` | 从已知数据纯构造,无副作用。非 create |+| `create` | 创建真实资源(spawn、allocate、connect)。非 build |+| `to*` | 转换表示:`toSafeFilename`、`toPosixPath` |+| `set` | 赋值本地状态,调用者提供最终值。非 update |+| `update` | 从调用者输入重算状态。非 refresh |+| `refresh` | 自发重查,无调用者输入。非 update |+| `add` | 添加业务对象 |+| `start` / `pause` / `stop` | 开始执行 / 用户可见暂停 / 停止当前执行 |+| `resume` | 启动恢复 |+| `remove` | 从内存/模型/UI 脱离,不删磁盘。非 delete |+| `delete` | 从磁盘或持久记录破坏性删除。非 remove |+| `clear` | 清空集合、输入、选择或缓存 |+| `mount` / `unmount` | 创建/回收进出视口的懒管理控件 |+| `flush` | 将缓冲状态写入磁盘 |+| `cancel` | 放弃异步工作,不删记录 |+| `open` / `close` | 打开/关闭文件、URL、socket、dialog |+| `reveal` | 在文件管理器中显示 |+| `run` | 执行当前 actor 拥有的工作流步骤 |+| `supervise` | worker 内部监管器:采样进度、存恢复数据 |+| `install` | 将运行时或二进制放到磁盘 |+| `send` | 向另一系统推送数据,单向无响应 |+| `request` | 请求另一 actor 执行动作 |+| `on*` | Qt slot、信号反应、事件反应 |++## 四阶段 `__init__`++QWidget / QDialog 子类统一使用四阶段初始化:++```python+def __init__(self, parent=None):+ super().__init__(parent)+ self._initWidget() # 创建和配置子控件,不连接信号+ self._initLayout() # 组装布局:margins、spacing、addWidget+ self._bind() # 连接信号到槽,所有控件已存在+```++## 反模式(看到就改)++**违反 Flat is better than nested:**+- 只做 if/elif 分发的包装函数 → 让调用方直接调对应函数+- 把类嵌在方法里但不用闭包 → 提升为模块级+- 类名已提供上下文时函数名还重复名词 → 砍掉名词++**违反 Explicit is better than implicit:**+- 模块级 `global` 可变状态伪装成单例 → 提升为类,或 frozen dataclass 显式注入+- 用 dict 传结构化数据 → 用 dataclass+- 传整个对象但只用其中一个方法 → 传 callable,依赖保持最窄++**违反 YAGNI:**+- 多处文档描述同一个事实 → 一个事实一个位置,其余用链接++**违反 Simple is better than complex:**+- 把不属于本模块职责的逻辑混进来"顺手做了" → 保持单一职责++**违反 Readability counts:**+- 注释或文档复述代码已经说明的事 → 删掉,代码自己说 Whatdiff --git a/CONTEXT.md b/CONTEXT.mdindex eccf9535..81b133e8 100644--- a/CONTEXT.md+++ b/CONTEXT.md@@ -1,746 +1,133 @@-# Ghost Downloader Context+# Ghost Downloader-Ghost Downloader is a task-based downloader built with PySide6. It runs on-desktop (Windows, macOS, Linux) and Android from a shared business engine, with-a browser extension that captures resources and sends them to the desktop app.+基于 PySide6 的多协议下载器。桌面端(Windows、macOS、Linux)和 Android 共享同一业务引擎,浏览器扩展捕获资源并发送到桌面应用。## Language-### Domain nouns+### 任务**Task**:-A user-visible download item stored by the app.--**Task Run**:-The current execution of a Task inside the download loop.--**Task Queue**:-The internal waiting/running set that limits concurrent Task Runs.--**Task Service**:-The app actor that owns user-visible Task workflow: add, pause, delete,-redownload, edit, resumeSaved, stop. The single public door for all task-actions. Internally holds Task Store and Task Queue — neither is public.--**Task Store**:-The internal part of Task Service that holds live Task objects and persists-Task Records to `tasks.jsonl`. Not a public actor.--**Task Record**:-The durable stored form of a Task, one JSON line in `tasks.jsonl`.--**Saved Tasks**:-Task Records loaded from a previous app run that may need to start again.--**Coroutine Runner**:-The app actor that owns the background asyncio loop and Qt callback delivery.-Knows nothing about Task.--**Speed Meter**:-Aggregate download speed monitor. Download engines feed bytes via-`addSpeed(byteCount)`; HTTP/FTP also `await waitForSpeedLimit()` to honor-the global limit. Emits `speedChanged(bytesPerSecond)` once per second only-while bytes are flowing — its timer starts on the first `addSpeed` and stops-itself on the first idle tick.-_Avoid_: globalSpeed mutable, View-owned timer--**Task Step**:-One executable step inside a Task. A Task may have one or many steps. Step-owns `run()` directly — there is no separate Worker class.--**Subworker**:-A split transfer unit for one byte-range chunk inside an HTTP or FTP step.--**Pausable**:-A Task is pausable while its running Step can resume from a breakpoint (for-transfers, whether the server honours byte-range requests). Pausability is-derived from resumability at the moment it is read — never stored as separate-state, because a Step may only learn its resumability after it was created.+用户可见的下载项。拥有 Name(成品文件的基本名)和 Output Folder(下载目标目录)。+单文件任务的最终路径为 Output Folder / Name;多文件任务为包含各文件的目录。+五个状态:WAITING(排队等待)、RUNNING(正在下载)、PAUSED(用户暂停)、COMPLETED(已完成)、FAILED(失败)。+持久化为 Task Record;应用启动时从上次运行加载的 Task Record 称为 Saved Tasks。+_Avoid_: download、job;Name 不叫 title 或 filename;Output Folder 不叫 directory**Task Files**:-The files and temporary progress state produced by a Task.-_Avoid_: confusing with **Selectable File** (the checkable unit below)--**Selectable File**:-One checkable download unit inside a multi-file Task — a repository file, a-playlist video, a multi-part page, or a torrent file. Identified by a stable-index that never changes with selection.+一个 Task 产生的下载文件和分片临时文件。+_Avoid_: 与 Selectable File 混淆-**File Selection**:-Which Selectable Files a Task should download, expressed as flags on the-files. Changing selection never creates or destroys Steps and is allowed in-every Task status; deselected files keep their partial progress.--**Revive**:-A completed Task returning to downloading because newly selected files have-pending work. Reviving clears the completion timestamp and starts the Task-automatically.+**Pausable**:+Task 的可暂停性,派生属性。取决于当前运行 Step 是否能从断点恢复+(对传输类 Step,取决于服务器是否支持 byte-range)。**Task Error**:-A business exception raised by Step.run() with a user-facing English message-template and format parameters. `TaskError("Server returned error ({status})",-status=403)`. Task.run() is the single catch point.+任务执行过程中的已知失败——服务器错误、磁盘空间不足、运行时未安装等。+携带用户可见的消息模板(同时作为 i18n key)和格式化参数。Task 有单一错误边界。+失败后 Step 上记录 Step Error(message + params),仅运行时存在,不持久化。-**Step Error**:-A frozen value object stored on `step.error` (runtime only, not serialized).-Carries `message` (English template, also the i18n key) and `params` (format-values). `str(stepError)` returns the formatted English fallback.+### 文件选择-**Name**:-The basename of a Task's finished file, for example `video.mp4`.-_Avoid_: title, filename (keep `filename` only at the raw browser/protocol seam)+**Selectable File**:+多文件 Task 内的一个可勾选下载单元——仓库文件、播放列表视频、多分 P 页面或种子文件。+通过稳定索引标识,索引不随选择变化。改变选择不创建或销毁 Step,任何 Task 状态下都允许;+取消选择的文件保留部分进度。+_Avoid_: 与 Task Files 混淆-**Output Folder**:-The folder a Task downloads into.+**Revive**:+已完成的 Task 因新选中的文件有待下载工作而回到下载状态。+清除完成时间戳并自动启动 Task。仅对 COMPLETED 状态的 Task 生效。-**Output Path**:-The full path of a Task's finished output. For single-file Tasks, equals-`outputFolder / name`; for multi-file Tasks (HuggingFace, Bilibili multi-P),-a directory containing the individual files.+### 任务创建**Task Options**:-The app-owned options used to parse, create, or edit a Task. Frozen dataclass-with subtypes: ResourceTaskOptions, PageTaskOptions, MergeTaskOptions,-BinaryInstallOptions.-_Avoid_: payload (keep only at raw transport seams)+用于解析、创建或编辑 Task 的应用层选项。+四种来源:浏览器 Resource、页面媒体、合并请求、二进制安装。+_Avoid_: payload(仅在原始传输 seam 使用)**Task Parser**:-A FeaturePack-provided capability that turns Task Options into a Task.-Declares a `priority` and a `match(options)` predicate.+FeaturePack 提供的能力,将 Task Options 转为 Task。+声明优先级和匹配规则;高优先级的 Parser 先检查。**Task Draft**:-Unconfirmed task state before the user confirms it. Owns in-flight parses and-late completion. Task Service does not understand draft state.--**Draft Item**:-One URL entry inside a Task Draft, tracking its parse state and result.--**Feature Service**:-The app actor that owns pack discovery, parser priority routing, and pack-lifecycle. `parse(options)` iterates all parsers sorted by priority and calls-the first match.--**FeaturePack**:-A plugin bundle under `features/*_pack`; it may provide task parsers, cards,-file types, binary runtimes, pages, or settings. Declares capabilities; the-app integrates them.--**Pack Page**:-A navigation page contributed by a FeaturePack.--**Binary Runtime**:-An external executable family that a pack can probe or provide an install task-for. Concrete implementations: M3U8Runtime, FFmpegRuntime, YouTubeRuntime.+用户确认前的未确认任务状态。内含一个或多个 Draft Item,每个 Draft Item 跟踪一条 URL,+处于三个状态之一:Parsing(解析中)、Resolved(解析成功,持有 Task)、Failed(解析失败)。+用户确认时尚在解析的 item 会在后台等待解析完成后自动提交(延迟确认)。+Task Service 不理解 draft 状态。+_Avoid_: pending task、unconfirmed task**Resource**:-A downloadable thing captured by the browser extension.+浏览器扩展捕获的可下载物。由 Browser Service 接收后转换为 Task Options 进入任务创建流程。+_Avoid_: 与泛义"资源"混淆-**App Entry**:-The top-level script that composes process startup for one platform.+### 任务执行-**App Stop Flow**:-The function connected to Qt quit that stops app-owned actors in order.--**Settings**:-App-wide user configuration: the Settings page and `cfg`.-_Avoid_: options (options are per-Task input, not app config)--**Category**:-Download classification and target folder rule. CategoryService matches-file extensions to categories and resolves download folders.--**Client**:-A wreq HTTP client with optional TLS fingerprint emulation. `buildClient()`-is the factory; `toEmulation()` resolves a profile string to a wreq Emulation.--**Signal Bus**:-Process-level event bus with exactly four signals: `activationRequested`,-`openFileRequested`, `exceptionCaught`, `updateAvailable`. No task or-business signals — those live on Task Service and Speed Meter.--**Plan**:-A "do X after all tasks complete" intent: shutdown, restart, sleep, or open file.--### Verb vocabulary--These verbs have specific meanings in this project.--**load**: read app-local persisted data or local resources.-_Not_: fetch (network), read (raw I/O)--**save**: persist durable app state or progress/cache data.--**fetch**: one network request to retrieve data.-_Not_: load (local), probe (metadata only)--**probe**: ask for capability or metadata without creating a task.--**parse**: convert seam text, payload, or protocol output to app objects.--**match**: decide whether a candidate fits a rule.--**find**: search local disk or a real search space.--**build**: pure construction from known data, no side effects.-_Not_: create (has side effects)--**create**: create a real resource with side effects (spawn, allocate, connect).--**to\***: convert representation. `toSafeFilename`, `toPosixPath`.--**set**: assign local object or widget state directly.--**update**: recompute state from caller-provided inputs.-_Not_: refresh (self-initiated)--**refresh**: self-initiated re-query; no caller input needed.-_Not_: update (caller-provided)--**add**: add a business object. `taskService.add(task)`.--**start / pause / stop**: start execution, user-visible pause, stop current-execution only.--**resume**: startup recovery. `taskService.resumeSaved()`.--**remove**: detach from memory, model, config, or UI. No disk deletion.-_Not_: delete (destructive)--**delete**: destructive deletion from disk or durable records.-_Not_: remove (non-destructive), cleanup (vague)--**clear**: empty a collection, input, selection, or cache.--**mount / unmount**: create or retire a lazily-managed widget as it enters or-leaves the viewport. Unmounting may defer actual destruction until safe.-_Not_: remove (model detach), delete (destructive)--**flush**: write buffered store state to disk. `flushSoon`, `flushNow`.--**cancel**: abandon async work without deleting records.--**open / close**: open or close file, folder, URL, socket, session, dialog.--**reveal**: reveal or select a file or folder in the OS file manager.--**on\***: Qt slot, signal reaction, event reaction.+**Task Run**:+Task 在下载循环中的当前执行。一个 Task 同时只有零或一个活跃的 Task Run。+Task Run 按待完成 Step 的顺序迭代 Task Step。+_Avoid_: execution、session-**run**: execute a workflow step owned by the current actor.+**Task Step**:+Task 内的一个可执行步骤。一个 Task 可能有一个或多个 Step。+_Avoid_: stage、phase、action-**supervise**: worker-internal supervisor that samples progress, saves resume-data, and coordinates subworkers.+**Subworker**:+HTTP 或 FTP Step 内的一个分片传输单元,负责一个 byte-range 区间。+_Avoid_: worker、thread、chunk-**install**: place a runtime or binary on disk.+### 应用角色-**send**: push data or notification to another system. One-way, no response-expected. `sendNotification`, `sendResult`.+**Task Service**:+拥有用户可见任务工作流的唯一公共入口:add、start、pause、delete、+redownload、edit、setCategory、applySelection、resumeSaved、stop。+_Avoid_: 直接操作 Task 的状态转换-**request**: ask another actor or system to perform an action.-`requestPairing`, `requestIgnoreBatteryOptimizations`.+**Feature Service**:+拥有 pack 发现、parser 优先级路由和 pack 生命周期。+将 Task Options 路由到匹配的 Parser。若无 parser match,失败;+此失败发生在 Task 创建之前,不属于 Task Error。-### File-system words+**FeaturePack**:+插件包。可提供 task parser、card、file type、binary runtime、page 或 setting group。+_Avoid_: module、extension-**folder**: the value is definitely a folder. `outputFolder`, `installFolder`.-**file**: the value is definitely a file. `outputFile`, `decryptionKeyFile`.-**path**: the value may be a file or folder. `outputPath`, `binaryPath`.-_Avoid_: `directory` in project-owned names (only when mirroring an external API).+**Binary Runtime**:+FeaturePack 可探测或提供安装任务的外部可执行文件家族。-### Boolean names+**Browser Service**:+浏览器扩展的协议适配器:接收扩展消息,翻译为 Task Service 动词,返回结果。-Booleans are named with `is*`, `has*`, `can*`, or `should*` prefixes.-_Avoid_: bare adjectives (`available`), action-looking booleans (`enableX`),-third-person verbs (`supportsX`).+**Clipboard Listener**:+剪贴板监听器。监控剪贴板变化,过滤出 URL 后发出通知。-### Signal names+**Category**:+下载分类和目标目录规则。将文件扩展名匹配到分类并解析下载目录。+_Avoid_: group、tag、type-Signal names follow `{noun}{PastParticiple}`: `taskAdded`, `speedChanged`,-`pairRequested`, `parseSucceeded`. A signal is a fact that already happened,-not a command to do something. Slots mirror the signal:-`_on{Noun}{PastParticiple}` — `_onTaskAdded`, `_onSpeedChanged`.+**Coroutine Runner**:+运行异步工作并桥接回 UI 线程的应用 actor。对 Task 一无所知。-### Noun-returning lookups+**Speed Meter**:+全局下载速度监视器。下载引擎喂入字节数据,聚合后每秒发出速度变更通知。+同时提供全局限速门控。-For simple key or list lookup, use noun form: `taskById(taskId)`,-`resourceByUrl(url)`, `categoryById(categoryId)`.-_Avoid_: `find*` for in-memory lookup (keep `find*` for disk/PATH search).+**Signal Bus**:+进程级事件总线。只承载跨模块的应用级事件,不承载任务或业务信号——那些在各自的 Service 上。-## Relationships+**Client**:+带可选 TLS 指纹模拟的 HTTP 客户端。-- A **Task Draft** contains one or more **Draft Items** before the user- confirms them. Each Draft Item tracks a URL, its parse state, and- optionally a parsed Task.-- **Task Options** are parsed by a **Task Parser** into a **Task**.- `featureService.parse(options)` iterates parsers by priority; the first- `match(options)` wins.-- A **FeaturePack** is the plugin bundle that may provide one or more- **Task Parsers**, cards, file types, runtimes, or pages.-- A **Task** has one durable **Task Record** in `tasks.jsonl`.-- **Task Service** internally holds **Task Store** and **Task Queue**; neither- is public. Task Service resumes **Saved Tasks**; a View does not.-- A **Coroutine Runner** runs generic async work and delivers callbacks back to- Qt.-- A **Task** may have zero or one active **Task Run**.-- A **Task Run** iterates **Task Steps** sequentially via `pendingSteps()`.- Each Step owns its own `run()`.-- A browser **Resource** can become **Resource Task Options** via- `toResourceTaskOptions()` in the extension. A page-media handoff becomes- **Page Task Options** or **Merge Task Options**.-- **Category Service** matches file extensions to categories and resolves- download folders. Task Service auto-categorizes on add.+**Plan**:+"所有任务完成后做 X" 的意图:关机、重启、休眠或打开文件。-### Parser routing--`featureService.parse(options)` iterates parsers in ascending priority order;-the first `match(options)` wins. Specific parsers have low priority numbers-and are checked first; HttpParser (100) is the fallback, checked last.--| Parser | Priority | Match condition |-|---|---|---|-| ED2kParser | 45 | `ed2k://` scheme |-| BilibiliParser | 50 | Bilibili domain |-| InstallParser | 55 | `isinstance(options, BinaryInstallOptions)` |-| MergeParser | 60 | `isinstance(options, MergeTaskOptions)` |-| YouTubeParser | 70 | YouTube domain |-| M3U8Parser | 80 | `.m3u8`/`.mpd` in URL or local manifest |-| TorrentParser | 85 | `magnet:` scheme or `.torrent` local file |-| HuggingFaceParser | 85 | HuggingFace domain |-| GitHubParser | 90 | GitHub file URL + proxy configured |-| FtpParser | 95 | `ftp`/`ftps` scheme |-| HttpParser | 100 | any `http`/`https` URL (fallback) |--Delegation patterns:-- **GitHubParser** rewrites URL through proxy, then calls- `featureService.parse(replace(options, url=proxiedUrl))`. No recursion:- proxied URL is not a GitHub host.-- **MergeParser** calls `featureService.parse(options.video)` and- `featureService.parse(options.audio)` to parse sub-resources. Both route- through the priority chain.-- **InstallParser** delegates the download through- `featureService.parse(TaskOptions(url=...))` so GitHubParser mirrors it.--## Ownership rules--**`task.status` has a single writer.** Task Service writes it for queue-transitions (WAITING/RUNNING/PAUSED); the Step writes it for terminal outcomes-(COMPLETED/FAILED). Views only read it to render.--**Task Service** is the single public door. It internally holds Task Store-and Task Queue. No caller reaches either directly.--| State | Internal owner |-|---|---|-| Live Task objects | Task Store (inside Task Service) |-| Durable Task Records (`tasks.jsonl`) | Task Store (inside Task Service) |-| Category default folder, duplicate-name policy | Task Store (in `add`) |-| Waiting order | Task Queue (inside Task Service) |-| Running runs + cancel handles | Task Queue (inside Task Service) |-| Slot limit | Task Queue (inside Task Service) |-| File disappearance watch | Task Service (QFileSystemWatcher) |--**Task lifecycle signals are emitted by Task Service:**-`taskAdded(Task)`, `taskRemoved(taskId)`, `taskStarted(Task)`,-`taskPaused(Task)`, `taskCompleted(Task)`, `taskFailed(Task)`,-`tasksAllCompleted()`.--**Speed Meter** owns aggregate download speed — separate from task-orchestration. Download engines feed it bytes; it emits `speedChanged` per-second only while bytes are flowing.--**Views collect user intent and render state.** They call Task Service-directly (`taskService.pause(task)`, `taskService.delete(task, ...)`). They-do not own task lifecycle decisions, persist records, or manage the download-loop. Services hold no View references; Views connect to service signals.--**Browser Service** is a protocol adapter: receive WebSocket messages, translate-to Task Service verbs, send results back. It holds no MainWindow reference.-View connection is purely via signals bound in the entry script.--**Dependency direction** (leaf → top):--```-coroutineRunner knows nothing about Task-speedMeter knows nothing about Task; fed bytes by download engines-taskService uses coroutineRunner; internally holds TaskStore + TaskQueue-featureService holds packs + parsers; parse() returns Task-taskDraft uses coroutineRunner + featureService-browserService uses taskService + featureService; emits signals for View-categoryService standalone; taskService calls matchByName on add-View / Entry binds everything; connects signals-```--## Module topology--### Service layer--All business services are platform-agnostic module singletons:--| Service | Owns | Signals |-|---|---|---|-| `coroutineRunner` | asyncio event loop on QThread, callback delivery | — |-| `speedMeter` | byte accumulator, 1s timer, speed limit gate | `speedChanged(int)` |-| `taskService` | TaskStore + TaskQueue, file watcher, flush timer | `taskAdded`, `taskRemoved`, `taskStarted`, `taskPaused`, `taskCompleted`, `taskFailed`, `tasksAllCompleted`, `fileDisappeared`, `diskSpaceInsufficient` |-| `featureService` | pack list, sorted parser list, packByPackId map | — |-| `browserService` | WebSocket server, client sessions, snapshot timer | `pairRequested`, `taskDraftRequested`, `extensionUpdated`, `connectionChanged` |-| `categoryService` | category rules (persisted in cfg) | `categoriesChanged` |-| `clipboardListener` | clipboard monitoring, URL filtering | `urlsDetected(list)` |-| `runtimeStatusService` | async version probing for BinaryRuntime | `statusChanged(RuntimeStatus)` |-| `plan` | post-completion intent (shutdown/restart/open) | — |--### FeaturePack system--Each pack under `features/*_pack/` declares capabilities via methods on its-`FeaturePack` subclass. `featureService.load()` discovers packs from-`manifest.toml` files, topologically sorts by dependencies, then imports them.--Pack capabilities: `parsers()`, `taskCard()`, `draftCard()`, `optionCards()`,-`editCards()`, `fileTypes()`, `pages()`, `settingGroups()`, `start()`, `stop()`.--Module singletons created at import time (configs, runtimes, services, actors)-do not read `cfg` values at construction — they use lazy properties. `qconfig.load`-happens before `featureService.load`.--Notable pack-level actors:-- `bilibiliAccount` — module singleton for Bilibili login/cookie state;- the sole gateway to the current cookie.-- `btSession` — module singleton wrapping the libtorrent session; lazy open- on first BTTask.run(); emits `alertReceived` for broadcast+filter routing.-- `trackerService` — tracker source fetch + cache + merge.-- `ffmpegRuntime`, `m3u8Runtime`, `youTubeRuntime` — BinaryRuntime singletons.--### View layer--**MainWindow** owns a `TaskDraft` service instance and a lazy-`TaskDraftDialog`. It does not own task lifecycle — it binds-`draft.taskConfirmed → taskService.add`, which is the only task-creation path.--**TaskPage** subscribes to `taskService.*` signals for card lifecycle. Lazy-virtual scroll: `_liveCards` dict (viewport-only cards, created on enter,-destroyed on leave), `_displayOrder` list, `_selectedIds` set (selection state-lifted from cards). Three-layer refresh: `_refreshList` (filter+sort) →-`_refreshViewport` (mount/unmount/position visible cards) →-`_refreshVisibleCards` (periodic repaint for progress text). Band selection-via `BandSelector` event filter on scrollWidget; Delete key shortcut in-selection mode.--**TaskDraftDialog** receives a `TaskDraft` in its constructor. It debounces URL-changes, delegates parsing to `TaskDraft`, and renders draft cards from-`featureService.draftCard()`.--**SettingPage** adds pack settings via `featureService.settingGroups(parent)`.--### Browser Extension--Service worker with four bridge singletons:--**desktopBridge**: WebSocket connection to desktop BrowserService. Protocol v3:-`hello` → `hello_ack` → `subscribe_tasks` → `task_snapshot` push. Request/-response via `requestId` correlation. Reconnects on close (2.5s timer + 1-min-alarm fallback). Offline tasks queue in `taskQueue` (storage.session) and flush-on reconnect.--**resourceBridge**: captures from three sources: `webRequest.onResponseStarted`-(network), `webRequest.onSendHeaders` (header snapshots), `runtime.onMessage`-cat-catch `addMedia` (page). Owns `ResourceCache` (pure in-memory, no chrome-deps, unit-testable). Uses `download-spec.ts` for `toResourceTaskOptions()`.--**mediaBridge**: media playback control. `buildPanelState()` polls cat-catch-content script for video state. `runAction()` sends commands. Owns-`mediaSnapshot` as single source of truth.--**featureBridge**: per-tab feature toggles (recorder, webrtc, mobileUserAgent,-etc.). Persists to `storage.local`; reconciles against live tabs on load.--**Page Media** (content script side, four lifecycle layers):-- L1 — MSE Probe (MAIN world, `document_start`): intercepts- `SourceBuffer.appendBuffer` to correlate fetch URLs → MSE buffer appends.-- L2 — Attribution Engine (ISOLATED world, `document_start`): attributes- network URLs to playing `<video>` elements via timing correlation.-- L3 — Download Button (ISOLATED world, `document_idle`): standalone IIFE,- finds active media, on click asks L2 to resolve → sends to background →- resourceBridge dispatches to desktop.-- L4 — Resolution Strategies (no lifecycle, pure functions): per-site dispatch- (YouTube, X, Douyin, generic). Strategies cannot reach back into the- attribution engine.--**Popup Protocol**: typed union `PopupCommand = StateCommand | ActionCommand`.-Exhaustive switch in `runPopupCommand()` — compile-time complete.--## App lifecycle--### Desktop startup (`Ghost-Downloader-3.py`)--```-setupEnvironment():- setupHiddenSubprocess (win32)- import resources- patchFluentLabelThemeChanged- qconfig.load(configPath, cfg)--startApp(application, isSilent):- sys.excepthook → signalBus.exceptionCaught- loadEngine(application) → translator + coroutineRunner.start- MainWindow()- splash (if not silent)- loadPacks() → featureService.load + PackConfig.load- window.setupPacks()- startEngine() → speedMeter bind + resumeSaved + featureService.start- bind signalBus, browserService, clipboardListener, tray/dock- bindNotifications(completed, diskSpace)- checkUpdateAtStartup()- application.aboutToQuit.connect(stopEngine)-```--Shared startup functions live in `app/startup.py`: `loadEngine`, `loadPacks`,-`startEngine`, `bindNotifications`, `checkUpdateAtStartup`, `stopEngine`.--### Desktop shutdown--```-stopEngine():- taskService.stop() # pause all running/waiting- taskService.flush() # write store to disk- browserService.stop() # close WebSocket server- aria2RpcServer.stop()- featureService.stop() # pack.stop() on each- coroutineRunner.stop() # cancel all, stop asyncio loop-```--### Android differences--Same engine, different cockpit. `MobileMainWindow` is an independent QWidget-(not a subclass of desktop MainWindow). `MobileTaskPage` subclasses desktop-`TaskPage` for filter/sort/virtual-scroll reuse — overrides only interaction-(touch, layout). Cards use an MRO mixin swap for overflow menu and long-press.--Mobile-specific: `KeepAlive` (foreground service + wake lock), Android-notifications, auto-approve browser pairing (no dialog), silent task add-(no draft dialog), share intent handling.--`patches.py` is a contained workaround layer for PySide6-on-Android quirks:-EGL single-surface (popups must be child widgets), broken QSvgPlugin,-content:// URIs, narrow-screen reflow.--Shutdown is identical to desktop.--## Code shape--### Naming conventions--Functions and methods use `camelCase`. Classes use `PascalCase`. Constants use-`UPPER_SNAKE_CASE`. Object-private attributes and class-internal helpers start-with `_`. Module-level classes and constants do not add `_`.--Function names combine one verb from the verb vocabulary above with one-concrete business noun: `taskService.add(task)`,-`featureService.parse(options)`, `browserService.stop()`. No verbs outside the-vocabulary appear in app-owned code — if none of the existing verbs fit, the-function's responsibility is unclear and the seam is wrong, not the vocabulary.--### Word choice--Names use short, common English words that a first-time reader understands-without a dictionary: `task`, `step`, `name`, `folder`, `speed`, `draft`.-Rare or academic words are replaced with plain equivalents: `sanitize` →-`toSafeFilename`, `normalize` → `toProxySite`, `orchestrate` → `run`.-When a shorter word means the same thing, the shorter word wins: `add` over-`insert`, `stop` over `terminate`.--Names describe what the actor owns in the domain, not its structural role.-Actors are named `taskService`, `speedMeter`, `categoryService` — generic-structural nouns like `manager`, `controller`, `coordinator`, `provider`,-`repository`, `facade`, `pipeline`, and `context` are absent because each-actor is named for the business concept it owns. A new noun represents a real-domain concept; introducing a noun just to make an awkward helper sound nicer-is a sign the helper belongs on an existing actor.--A forced long name (`removeTaskRecordAndDeleteFiles`) is a sign the function-owns two responsibilities. Better seams make names short:-`taskService.delete(task, shouldDeleteFiles)`.--### Comments--Code carries no comments and no docstrings by default. A well-named function-with typed parameters explains what it does; comments that restate the code-compete for the reader's attention without adding information. Comments earn-their place only when they explain **why** — a hidden constraint, a workaround-for a specific bug, or behavior that would surprise a reader. If removing a-comment would not confuse a future reader, the comment is not written.--### Inlining--This codebase prefers inlined code over shallow extractions. A function earns-extraction when it is called from two or more sites, or when it exceeds ~15-lines with a single clear duty and a return type that is a single named type-(not a tuple or dict). One-line wrappers, single-caller helpers under 5 lines,-and trivial delegations are inlined at their call site. Three similar lines of-obvious code are kept inline rather than extracted into a function whose-interface is as complex as its body — the extraction adds a jump without-reducing knowledge for the caller.--### Deepening--"Deeper module" in this project means less call-site knowledge, not more-architecture nouns. Refactors in this codebase have been subtractive:-workflows moved behind existing actors before new actors were created;-reach-through plumbing deleted; new modules introduced only when the same-business rule was already spreading across multiple callers. New seams were-earned by deleting knowledge from call sites, not by drawing boxes.--### Four-phase `__init__`--QWidget and QDialog subclasses follow a four-phase `__init__`:--```python-def __init__(self, parent=None):- super().__init__(parent)- self._initWidget()- self._initLayout()- self._bind()-```--Each phase has a single responsibility:--`_initWidget()` — create and configure child widgets. Set initial property-values, default text, icons, size policies. No signal connections — the widgets-are inert at this point, so setting state does not trigger any reactions.--`_initLayout()` — assemble layouts and add widgets. Only layout code: margins,-spacing, stretch factors, addWidget/addLayout calls.--`_bind()` — connect signals to slots. All widgets exist and are laid out, so-it is safe to connect. Slots triggered here can safely reference any sibling-widget.--This separation exists because Qt signals fire immediately on connect if the-current widget state already matches the signal condition. Connecting in-`_initWidget` before sibling widgets exist leads to slot calls that reference-widgets not yet created.--### Responsibility layers--```-View (app/view/)- Renders state and collects user intent.- Calls service methods: taskService.pause(task), taskService.delete(task, ...).- Connects to service signals for refresh: taskService.taskAdded → _onTaskAdded.- Does not own task lifecycle, persist records, run downloads, or manage the- event loop.--Service (app/services/)- Signal-driven actors with private state. The single source of truth for the- state they own. Emit signals when state changes.- Do not import from app/view/. Do not hold QWidget references. Do not show- dialogs or InfoBars.--FeaturePack (features/*_pack/)- Declare capabilities (parsers, cards, runtimes). Provide pack-specific- business logic (download step implementation, protocol handling).- Do not import from app/view/ except for card classes returned by taskCard /- draftCard / optionCards. Do not reach into Task Service internals.--Platform (app/platform/)- OS-specific adapters: file association, run at login, hidden subprocess,- notifications, Android keepalive. Thin wrappers with no business logic.--Entry (Ghost-Downloader-3.py, android/main.py)- Composition root. Creates services and views, binds signals, defines- shutdown order. Platform-specific wiring lives here, not in services or views.-```--When a View method grows long because it orchestrates multiple service calls,-the orchestration belongs behind a service method — the View calls one verb,-the service owns the ordering. This is how `taskService.redownload(task)`-replaced multi-step card code that called stop + delete files + reset + start.--## Task execution--### Step iteration, error boundary, and cancellation--`Task.run()` iterates `pendingSteps()` sequentially — sorts steps by index,-skips COMPLETED, yields remaining while `self.status == RUNNING`. No protocol-overrides `Task.run()` — it is the universal error boundary:--- `TaskError` → `step.setError(StepError(str(e), e.params))` — user-facing-- `Exception` → `step.setError(StepError("Unexpected error: {detail}"))` — generic wrapper, detail from `str(e)`-- `CancelledError` → passes through (BaseException in Python 3.11+), no error set--Steps raise `TaskError` for known business errors. Steps that use `TaskGroup`-catch `ExceptionGroup` internally and convert protocol exceptions to `TaskError`-before they reach `Task.run()`. Steps never call `setError` directly.--Error messages are English templates (also serving as i18n keys). The View-translates at render time via `QCoreApplication.translate("TaskErrors", msg)`.-Pack-specific `error_catalog.py` files hold `QT_TRANSLATE_NOOP` markers for-`lupdate` extraction; they are never imported at runtime.--**Cancellation**: `taskService.pause(task)` → `coroutineRunner.cancel(workId)` →-`asyncio.Task.cancel()` → `CancelledError` into running step. Each protocol-handles cleanup: HTTP/FTP preserve `.ghd` progress for resume; M3U8/yt-dlp-terminate subprocess; BT saves resume data and removes torrent from session.--### Split transfer (HTTP/FTP)--HTTP and FTP use the same subworker pattern: divide file into byte ranges,-launch concurrent subworkers (each sends range requests and `pwrite`s at-position), run a 1s `_supervise()` loop that saves `.ghd` progress and-calculates speed. `_autoSpeedUp()` adds subworkers after stable-speed sampling.-`_reassignSubworker()` splits the slowest remaining range when a subworker-finishes. On resume, `_loadRecord()` restores subworker positions from `.ghd`.--FTP differs: each subworker opens its own FTP connection; uses manual-`asyncio.wait(FIRST_EXCEPTION)` instead of TaskGroup for dynamic subworker-addition.--### CLI subprocess steps--M3U8, yt-dlp, and FFmpeg launch external processes and parse stdout for-progress. M3U8 uses N_m3u8DL-RE with regex progress parsing (VOD segments,-live elapsed). yt-dlp uses `--progress-template` for machine-readable output-and `--print after_move:__GD3_FINAL__%(filepath)s` for final file detection.-FFmpeg merge is a 3-step task: download video + download audio + stream-copy-merge with `out_time_us` progress parsing.--### Serialization--`Task.toDict()` walks dataclass fields where `f.repr == True`; fields with-`repr=False` (like subworkers, runtime state) are excluded. `Task.fromDict()`-uses `Task._registry` (populated by `__init_subclass__`) to reconstruct the-correct Task/Step subclass. Unknown fields are silently dropped for forward-compatibility.--Runtime state lives as plain instance attributes (not dataclass fields),-initialized in `run()`, never serialized.+**Settings**:+应用级用户配置。+_Avoid_: options(options 是每个 Task 的输入,不是应用配置)## Example dialogue-> **Dev:** "When the user presses pause, are we deleting the Task?"-> **Domain expert:** "No. Pause stops the Task Run. The Task Record and Task-> Files stay."--> **Dev:** "When the user presses redownload, do we create a new Task?"-> **Domain expert:** "No. Redownload stops the Task Run, deletes Task Files,-> resets the same Task, and starts a new Task Run."--## Flagged ambiguities--- `payload` was used for raw protocol data, dialog options, and FeaturePack- input. Resolved: keep `payload` at raw seams; use **Task Options** inside- the app.-- `title` was used as the final product name of a Task. Resolved: a Task owns- a **name**, not a UI title.-- `createTask` was used for starting or enqueuing a Task Run. Resolved:- creation of a durable Task and starting a Task Run are separate concepts.-- `removeTask` was used for both View removal and durable deletion. Resolved:- removing a Task Record and deleting Task Files are separate steps.-- `resumeMemorizedTasks` lived on TaskPage. Resolved: startup recovery is Task- Service work; the View only refreshes through signals.-- `aboutToQuit` connected several services directly. Resolved: each App Entry- connects one App Stop Flow so shutdown order is explicit.-- `resolve*` was widely used for functions that fetched, parsed, searched, and- built in unclear combination. Resolved: use the specific verb that names the- actual operation (load, fetch, probe, parse, build, select, or a- noun-returning method).-- `fileSize == 0` means both "size unknown" (`SpecialFileSize.UNKNOWN`) and a- legitimately empty file — the model cannot tell them apart. Unresolved;- existing code works around it (`updateStatus` backfills only when- `receivedBytes > 0`; the HTTP probe treats sizes 0 and 1 as pseudo-unknown).+> **Dev:** "用户按暂停时,我们删除 Task 吗?"+> **Domain expert:** "不。Pause 停止 Task Run。Task Record 和 Task Files 保留。"++> **Dev:** "用户按重新下载时,我们创建新 Task 吗?"+> **Domain expert:** "不。Redownload 停止 Task Run、删除 Task Files、重置同一个 Task、启动新的 Task Run。"diff --git a/browser_extension/CONTEXT.md b/browser_extension/CONTEXT.mdnew file mode 100644index 00000000..bb12a13a--- /dev/null+++ b/browser_extension/CONTEXT.md@@ -0,0 +1,123 @@+# Ghost Downloader Browser Extension++Chromium / Firefox 浏览器扩展。捕获页面中的可下载资源,通过持久连接发送到桌面应用。++与桌面应用共享 **Resource** 和 **Task Options** 的定义(见根目录 CONTEXT.md)。++## Language++### 上游依赖++**cat-catch**:+嵌入的第三方开源扩展,提供三个能力面:+DOM 媒体发现(addMedia 通道)、媒体播放控制(getVideoState 协议)、功能脚本库(recorder、webrtc 等)。+MSE Probe 参照 cat-catch 重写为独立实现,只发信号不缓存数据。+_Avoid_: 把 cat-catch 功能与自研 Page Media 系统混为一谈++### 桌面连接++**Desktop Bridge**:+与桌面 Browser Service 的持久连接。支持断线自动重连和离线排队。+离线期间下载请求排入 Task Queue,重连后自动 flush。+_Avoid_: desktop connection、socket++**Pairing**:+Desktop Bridge 建立连接前的授权流程。用户在桌面端确认授权后,扩展获得连接凭证。++**Task Queue**:+扩展侧的离线发送队列。Desktop Bridge 不可达时缓存下载请求,重连后逐条发送。+_Avoid_: 与桌面应用的 Task Queue 混淆——这里是扩展侧的离线缓冲++**Connection State**:+Desktop Bridge 的连接状态:missing\_token、connecting、authenticating、+connected、unauthorized、disconnected。Popup UI 据此显示连接指示器。++**Task Summary**:+桌面推送的任务摘要。扩展不拥有 Task,只拥有 Task Summary 作为任务状态的只读视图。++### 资源捕获++**Resource Bridge**:+资源捕获器。从网络请求和页面脚本(cat-catch)两个途径捕获可下载资源,+缓存到 Resource Cache 后转换为桌面可理解的 Task Options。+_Avoid_: resource manager++**Resource Cache**:+已捕获资源的内存缓存。同时保存 Header Snapshot——网络请求的请求头快照,+让桌面端能复用浏览器的认证凭据下载需要登录的资源。+_Avoid_: resource store、resource map++### 页面媒体++**Page Media**:+Content script 侧的媒体检测和归因系统。检测页面中正在播放的媒体,将网络 URL+归因到具体的 video 元素,为用户提供下载按钮。由四个协作层组成:+MSE Probe → Attribution Engine → Download Button,Resolution Strategy 提供按站点的解析逻辑。+同一个 URL 可能同时存在于 Resource Cache(作为 Resource)和 Attribution Engine+(作为 Video Session 的归因 URL)。Popup 资源面板走 Resource 路径,Download Button 走 Page Media 路径。++**MSE Probe**:+观察浏览器媒体流内部机制,将事件通过 Attribution Signal 报告给 Attribution Engine。+拦截对象 URL 创建、缓冲区添加、数据追加和网络请求,+以建立"哪个网络请求喂了哪个播放器"的关联。++**Attribution Signal**:+MSE Probe 与 Attribution Engine 之间的跨执行环境通信通道。+两者运行在不同的脚本隔离环境中,Signal 是唯一桥接机制。++**Attribution Engine**:+将网络 URL 归因到播放中的 video 元素。核心数据模型是 Video Session。+使用 Attribution Tier 判断归因置信度,使用 Attribution Ledger 仲裁 URL 所有权争议。++**Video Session**:+Attribution Engine 中一个 video 元素的生命周期追踪单元。+状态:inert → armed → ready → waiting → resolving → dispatched / failed / refused。+追踪归因到该视频的所有 URL。+_Avoid_: video tracker、media session++**Attribution Tier**:+归因置信度分级。决定 URL 归属的优先级——从最高置信(缓冲追加确认)+到最低(唯一 session 兜底)。高 tier 可以从低 tier 夺取 URL 所有权。++**Attribution Ledger**:+跨 session 的 URL 所有权账本。仲裁多个 Video Session 争抢同一 URL 的情况+(如预加载场景中多个视频共享相同的 CDN URL)。++**Download Button**:+悬浮在活跃媒体上的下载按钮。点击时请求 Attribution Engine 解析,+获取 Resolution 后发送到 Resource Bridge 转发给桌面。++**Resolution Strategy**:+按站点分发的下载解析逻辑(YouTube、X、Douyin、Instagram、generic)。+纯函数,不能回调 Attribution Engine。输出 Resolution。++**Resolution**:+Resolution Strategy 的输出。三种结果:+selection(下载决定)、pending(等待更多信息)、refused(拒绝处理)。++**Selection**:+Resolution 中的下载决定。四种形态:+single(单文件)、stream(流媒体段)、merge(视频+音频合并)、external(交给桌面端外部工具处理)。++### 媒体控制++**Media Bridge**:+媒体播放控制。通过 cat-catch content script 获取视频播放状态和发送控制命令。+Media Snapshot 是单一真相源。++**Media Snapshot**:+当前 tab 的媒体播放状态快照。包含播放列表、当前索引、播放/暂停状态。+消除多数据源的状态分裂。++### 功能开关++**Feature Bridge**:+每个 tab 的功能开关管理。开关分两类:动态注入型(切换后立即生效)+和需要刷新型(切换后需重新加载页面)。持久化到本地存储;加载时与活跃 tab 列表调和。++### Popup 通信++**Popup Protocol**:+Popup 与 background 之间的类型化通信协议。+命令分两类:StateCommand(查询状态)和 ActionCommand(执行动作)。+_Avoid_: popup API、popup bridge