diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d3bf95..37a6975 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,12 +19,18 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: targets: aarch64-apple-darwin,x86_64-apple-darwin + components: rustfmt, clippy - run: pnpm install --frozen-lockfile - run: pnpm mac:drag-bridge - run: pnpm check + - run: pnpm test - run: pnpm build + - run: cargo fmt --check + working-directory: src-tauri - run: cargo test --lib working-directory: src-tauri + - run: cargo clippy --all-targets -- -D warnings + working-directory: src-tauri - run: pnpm tauri build --target universal-apple-darwin --debug --bundles app env: RUSTUP_TOOLCHAIN: stable @@ -41,18 +47,21 @@ jobs: node-version: 22 cache: pnpm - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt - run: pnpm install --frozen-lockfile - run: pnpm check + - run: pnpm test - run: pnpm build - - run: cargo check + - run: cargo fmt --check + working-directory: src-tauri + - run: cargo test --lib working-directory: src-tauri - run: pnpm tauri build --debug --no-bundle - # The Linux paths (grim, wf-recorder, x11grab, Poppler) are the only ones with no - # build or test job today, so nothing in the repository has ever compiled them. - # Ubuntu's desktop runner carries the GTK and WebKit packages Tauri needs, which a - # macOS machine cannot provide; `scripts/linux/Dockerfile` is the same dependency set - # for building the packages off CI. + # Linux compiles and runs the same TypeScript/Rust tests. Runtime capture still + # needs a real Wayland/X11 desktop; `scripts/linux/Dockerfile` carries the same + # dependency set for building the packages outside this workflow. linux: runs-on: ubuntu-22.04 steps: @@ -65,6 +74,8 @@ jobs: node-version: 22 cache: pnpm - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt - name: Install Tauri system dependencies run: | sudo apt-get update @@ -73,7 +84,10 @@ jobs: libayatana-appindicator3-dev librsvg2-dev patchelf - run: pnpm install --frozen-lockfile - run: pnpm check + - run: pnpm test - run: pnpm build + - run: cargo fmt --check + working-directory: src-tauri - run: cargo test --lib working-directory: src-tauri # Bundles deb and AppImage, so this is also the Linux release artifact that diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..fe81706 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,141 @@ +# Contributing to Shift + +Shift is a Tauri 2 desktop application: React/TypeScript renderers talk to a Rust +command layer, with native macOS, Windows and Linux adapters underneath. Changes +should stay local to the behaviour being fixed; the regression ledger in +[`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) records paths that must +not be simplified back into earlier failures. + +## Prerequisites + +- Node.js 22 (the CI baseline) and pnpm 8 or newer. The repository has no + `packageManager` pin, so use an installed pnpm rather than assuming Corepack + selects one. +- Current stable Rust and Cargo; the CI workflow tracks the stable channel. +- macOS: macOS 13 or newer and the Xcode Command Line Tools for the Swift + sidecars. +- Windows: Visual Studio Build Tools with the Desktop development with C++ + workload, WebView2, and the Tauri prerequisites. See + [`docs/BUILD_WINDOWS.md`](docs/BUILD_WINDOWS.md). +- Linux: the GTK/WebKit/AppIndicator packages listed in + [`.github/workflows/ci.yml`](.github/workflows/ci.yml), plus `grim`, + `gnome-screenshot`, `wf-recorder` and FFmpeg for the optional capture paths. + +## Local setup + +```bash +pnpm install +pnpm prepare:ocr +pnpm mac:drag-bridge # macOS only +pnpm tauri dev +``` + +`pnpm prepare:ocr` refreshes the tracked Tesseract WASM and language assets +under `public/tesseract/`. They are committed so a clean checkout can build and +run OCR offline. Do not delete or replace them with remote downloads. + +## Required checks + +Run the checks from the repository root unless a command says otherwise: + +```bash +pnpm check +pnpm test +pnpm build + +cd src-tauri +cargo fmt --check +cargo test --lib +cargo clippy --all-targets -- -D warnings +cd .. + +git diff --check +``` + +The two network-dependent Rust tests are ignored by default: + +- `share::tests::two_copies_on_one_machine_discover_each_other` binds the shared + discovery port. +- `update::tests::the_configured_feed_parses_and_downloads` reaches the update + feed. + +Run the first explicitly when working on discovery, and the second only with a +feed you are willing to download from: + +```bash +cd src-tauri +cargo test share:: -- --ignored --nocapture +SHIFT_UPDATE_URL="" cargo test --lib update:: -- --ignored +``` + +## What CI covers + +[`.github/workflows/ci.yml`](.github/workflows/ci.yml) defines macOS, Windows and +Linux jobs. They run type checks, TypeScript tests, Rust formatting and Rust +unit tests; macOS also runs Clippy and a universal app build. Nothing in this +repository proves that the current hosting forge has a runner configured. +Link an actual run before describing CI as passing. + +## Change rules + +- Keep the source file untouched. Every operation writes a new result through + the collision-safe naming helpers. +- Where the interface maps a backend failure, use a stable code such as + `errTextTooLarge` or `share-timeout`; user wording belongs in `src/i18n.ts`. + Add both English and Simplified Chinese. Raw third-party diagnostics may pass + through unchanged. +- Use `messageFrom()` for unknown errors and `tLive()` for listeners that are + registered once and must follow later language changes. +- Preserve protocol compatibility. LAN beacons and transfer headers may gain + defaulted fields, but existing field meanings must not change. Update + manifests are `schema: 1`; reject unsupported schemas instead of guessing. +- Treat downloaded installers and LAN input as untrusted. Do not interpolate + paths into shell or batch text, and do not trust a declared file size without + enforcing it while copying. +- Resource limits belong at the point where bytes are read or decoded, not only + in the UI. The editor currently caps text at 8 MiB, image files at 64 MiB and + decoded images at 40 megapixels; document any new unbounded path or add a + limit. +- Do not edit generated output in `dist/`, `src-tauri/target/`, `artifacts/`, or + generated icons. Change the source and the build script that produces them. + +## Documentation changes + +User-visible behaviour changes require matching updates in both +[`README.md`](README.md) and [`README.zh-CN.md`](README.zh-CN.md). Architecture +changes belong in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md); observable +behaviour and limits belong in [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md); +trust-boundary changes belong in [`docs/SECURITY.md`](docs/SECURITY.md). + +If a change alters discovery, conversion dependencies, update handoff or macOS +packaging, append the reason, evidence and any commit reference to +`docs/ENGINEERING-NOTES.md` rather than leaving the next contributor to +rediscover it. + +## Manual checks + +Unit tests cannot prove gesture handling, OS permissions, installer behaviour or +cross-machine discovery. Before a release, complete the relevant matrix: + +- macOS: first launch, Screen Recording and Files & Folders permissions, area + and full-screen capture, editor save and copy, drag-to-ring, LAN receive. +- Windows: installer, firewall prompt, drag-to-ring threshold, WebView2 file + drag paths, recording with FFmpeg, LAN receive. +- Linux: build package, `grim` / `gnome-screenshot`, Wayland `wf-recorder`, + X11 FFmpeg fallback, Poppler-dependent paths. +- Updates: install the previous release and run the in-app handoff once on each + shipped platform. On Windows this requires real Windows hardware. + +Record which checks were run and which were not. Do not replace an unavailable +hardware check with a compile result. + +## Release work + +The release process, signing key handling and channel verification are in +[`docs/RELEASE.md`](docs/RELEASE.md). A release key must never enter the +repository, logs or issue attachments. Use `scripts/release-key.py` with the key +outside the working tree. + +Do not commit generated artifacts or publish a `releases` branch unless the +task explicitly asks for it. + diff --git a/README.md b/README.md index 10625af..6eb47a1 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # Shift -**A radial file workspace for macOS and Windows. Drag a file, release over a wedge, and the conversion happens on your machine.** +**A radial file workspace for macOS and Windows. Drag a file, release over a wedge, and the conversion happens on your machine.** Linux is a source-build target, not a shipped release. **Language:** English · [简体中文](README.zh-CN.md) Shift puts file conversion, screenshot, screen recording, annotation, and bilingual OCR behind one radial menu that appears wherever you drop a file. No uploads, no account, no cloud round-trip — every byte is processed locally. -Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour live behind per-platform adapters, so the radial menu, editor, and format catalogue are identical everywhere. +Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour live behind per-platform adapters, so the radial menu, editor, and format catalogue are shared wherever the platform provides the underlying gesture. --- @@ -29,6 +29,7 @@ Built on Tauri 2, Rust, React and TypeScript. Native capture and drag behaviour - [Platform status](#platform-status) - [Build from source](#build-from-source) - [Architecture](#architecture) +- [Documentation](#documentation) - [Repository layout](#repository-layout) - [Privacy](#privacy) - [Known limitations](#known-limitations) @@ -160,7 +161,7 @@ The tool ring (`Option + Shift` while dragging). These are one-gesture operation | Mono | audio | `.m4a`, ` (mono)` | Downmix to single-channel 128k AAC | | Plain | document | `.txt` | Plain-text dump via Pandoc | | OCR | image, PDF | `.txt`, ` (OCR)` | See [OCR](#ocr) | -| Edit / Annotate / Redact / Add BG | image | — | Opens the editor with the matching tool preselected | +| Edit / Annotate / Redact / Add BG | image | — | Opens the image editor; choose the annotation tool from its toolbar | | Open · Reveal | any file | — | Hands off to the system default app or file manager | ## Compression, naming, cancellation @@ -197,7 +198,7 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page | Tool | Behaviour | | --- | --- | -| Rectangle, Arrow, Highlight, Text | Freehand placement, colour and weight per annotation | +| Rectangle, Arrow, Highlight, Text | Freehand placement; each tool has a fixed colour and line width | | Redact | Solid black bar, burnt into the output — not an overlay | | Pixelate | Real mosaic sampling of the region underneath, not a translucent fill | | Blur | Gaussian blur of the region, clipped to the shape you drew | @@ -210,7 +211,7 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page | Save copy / Copy | New file with a suffix, or straight to the clipboard | | Pin | Floats the image as an always-on-top window with copy and close | -**Editor.** Images open the annotator; video opens a player; `txt` `md` `csv` `tsv` `html` `htm` open as editable text. Every editor host has Copy, Save As, Open, Reveal in Folder, OCR and Copy Text. +**Editor.** Images open the annotator; video opens a player; `txt` `md` `csv` `tsv` `html` `htm` open as read-only text previews. Copy, Save As, Open and Reveal are available for every kind. OCR, Copy Text and Pin appear for images only; text is not edited in place. The editor refuses text over 8 MB and images over 64 MB or 40 megapixels, and reports the limit instead of loading them. ## Capture history library @@ -297,9 +298,9 @@ A new macOS machine installs **`Shift-0.1.11-macOS-universal.dmg`**: builds are The update channel is this repository: a `releases` branch holding the installers plus `shift-update.json`, which names each artifact, its size and its SHA256. The feed URL is derived from the git remote at build time - Gitea, GitHub and GitLab forms are known, and `SHIFT_UPDATE_URL` overrides it - so no update service has to be deployed anywhere. -Once a day at startup, and on demand from Settings -> **Updates**, Shift reads the manifest, compares versions with semver rules including prereleases, and offers a download. A downloaded installer is checked twice before it can be installed: exact byte length, then a recomputed SHA256 that must match the manifest. A mismatch deletes the file and says so, so nothing half-downloaded launches. Publishing is one command, `scripts/publish-release.sh`, and `docs/RELEASE.md` covers the manifest format, the flags, and the difference between the integrity the hash proves and the authenticity a signed manifest adds (`--key` plus a key baked in with `SHIFT_UPDATE_PUBKEY`). +Once a day at startup, and on demand from Settings -> **Updates**, Shift reads the manifest, compares versions with semver rules including prereleases, and offers a download. A downloaded installer must match the manifest's exact byte length and recomputed SHA256, and both checks run again immediately before the handoff that installs it. A mismatch deletes the file and reports the error, so a truncated or replaced installer never launches. **Discard** removes the downloaded installer as well as the status. Publishing is one command, `scripts/publish-release.sh`, and `docs/RELEASE.md` covers the manifest format, the flags, and the difference between the integrity the hash proves and the authenticity a signed manifest adds (`--key` plus a key baked in with `SHIFT_UPDATE_PUBKEY`). -**Install & relaunch** finishes the update without leaving the app. macOS replaces its own `.app` bundle from the downloaded disk image and Windows runs the same installer silently, both from a helper script that starts once Shift has quit and then opens the new copy - so a conversion is interrupted, but nothing is left half-installed and a failed swap reopens the copy you had. The tab states your operating system, architecture, running version and the feed it reads above everything else, so one screenshot explains any report about an update. +**Install & relaunch** finishes the update without leaving the app. macOS replaces its own `.app` bundle from the downloaded disk image and Windows runs the same installer silently, both from a helper script that starts once Shift has quit and then opens the new copy - so a conversion is interrupted, but nothing is left half-installed and a failed swap reopens the copy you had. The helper receives its paths as process arguments; they are never interpolated into the shell or batch script. The tab states your operating system, architecture, running version and the feed it reads above everything else, so one screenshot explains any report about an update. ## External dependencies @@ -420,6 +421,17 @@ OCR: Tesseract.js WASM + bundled eng/chi_sim, in-process, offline The radial hit-test is pure geometry — one polar calculation shared by native pointer events, webview hover, and the Windows drop payload — so ring behaviour does not drift between platforms. +## Documentation + +- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) — process/window model, module boundaries, event and data flows. +- [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md) — product behaviour, output naming, platform differences and acceptance criteria. +- [`docs/SECURITY.md`](docs/SECURITY.md) — trust boundaries, update integrity, LAN-transfer limits and residual risks. +- [`CONTRIBUTING.md`](CONTRIBUTING.md) — development setup, test gates and release checks. +- [`docs/README.md`](docs/README.md) — index of every technical and release document. +- [`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) — regression ledger for paths that must not be simplified back into earlier failures. +- [`docs/RELEASE.md`](docs/RELEASE.md) — release channel, signing and update handoff. +- [`docs/ROADMAP.md`](docs/ROADMAP.md) and [`docs/MOBILE.md`](docs/MOBILE.md) — future work and the mobile plan. + ## Repository layout ```text @@ -431,23 +443,21 @@ native/macos/ Swift sidecars: drag bridge, PDF renderer, doc renderer, compiled into src-tauri/binaries/ by pnpm mac:drag-bridge scripts/ OCR staging, macOS sidecars, Windows installer, release build, manifest publish and manifest signing -public/tesseract/ WASM core + traineddata, generated, not committed +public/tesseract/ WASM core + traineddata; refreshed by pnpm prepare:ocr and + tracked so a clean checkout builds and runs OCR offline assets/ app icon source src-tauri/icons/ generated app icons per platform -docs/ Windows build guide, release/update channel, engineering regression - ledger, roadmap, mobile plan -scripts/linux/ Dockerfile that builds the Linux deb/AppImage off CI +docs/ architecture, behaviour specification, security model, release + guide, engineering ledger, roadmap and mobile plan +scripts/linux/ Dockerfile that builds Linux deb/AppImage packages .github/workflows/ CI definitions for macOS, Windows and Linux (see Contributing) -FileFlipper/ separate companion project, its own repository ``` ## Privacy Shift makes no internet requests for anything it does to your files. They are read, converted, and written locally; OCR runs in-process against bundled models; the history library is a local file. Nothing is uploaded, and nothing is collected. -Two paths touch the network, and neither carries file content unless you ask: the **update check** fetches a manifest over HTTPS at most once a day - and an installer only when you press the button - while **Send to a device** talks to your local network alone. - -The one exception is opt-in by usage: **Send to a device** talks to your local network only — UDP beacons on `239.255.77.88:47888` plus a direct TCP connection between the two machines, carrying the machine name so each side can label the other. It is inert until you open that picker or another Shift sends you a file. +Two paths touch the network, and neither carries file content unless you explicitly start that feature. The **update check** fetches a manifest over HTTPS at most once a day; it downloads an installer only when you press the button. **Send to a device** uses UDP beacons on `239.255.77.88:47888` and a direct TCP connection only to the machine you choose (or from another Shift that offers you a file). Discovery is silent while sharing is disabled, and a transfer begins only after the receiver accepts. LAN traffic is not authenticated or encrypted; [`docs/SECURITY.md`](docs/SECURITY.md) describes that boundary. ## Known limitations @@ -456,13 +466,15 @@ The one exception is opt-in by usage: **Send to a device** talks to your local n - `.doc`, `.pages`, `.ppt`, `.key` and `.numbers` are recognised but not parsed — export to DOCX/PPTX/XLSX first. - HEIC/HEIF/AVIF are read through the system decoder, so conversion and the pixel tools both accept them. Neither format can be written on this path, so a pixel tool applied to one produces a PNG; AVIF is not an export target at all. - PDF compression resamples embedded images to at most 1440 px as q60 JPEG. It deliberately skips anything it cannot prove it can round-trip — masks, indexed or CMYK colour, JPX/JBIG2/CCITT — so exotic scans may still resist shrinking. -- Windows recording and media conversion require `ffmpeg` on `PATH`. On Linux media conversion also requires it, area recording needs `wf-recorder` under Wayland and `ffmpeg` under X11, and neither path is exercised by the forge this repository is hosted on, so treat Linux capture as build-verified only. +- Windows recording and media conversion require `ffmpeg` on `PATH`. On Linux media conversion also requires it, area recording needs `wf-recorder` under Wayland and `ffmpeg` under X11. Those runtime paths are not exercised by the macOS development host, so treat Linux capture as build-verified until checked on real hardware. - Linux is a build target, not a shipped product: no deb or AppImage is published, so the update channel carries no `linux` key and a Linux build finds nothing to download. `scripts/linux/Dockerfile` and the `linux` job in CI remain the recipe for anyone who wants one. - Dragging a library row out uses the webview's file-URL drag support. It is the standard `text/uri-list` payload with a `file://` entry plus the plain path, and it needs a gesture-level check on each platform; until then, **Send**, **Reveal** and the row's own buttons are the guaranteed paths for handing a file over. Dropping a row back onto Shift is checked: one gesture reports through the DOM, the native webview drop, or both, and the `landed` flag in `MainWindow.tsx` lets only the first through — the invariants are in `docs/ENGINEERING-NOTES.md`. - LAN sharing needs a network that allows peer traffic. Multicast is skipped by some guest and corporate Wi-Fi; those networks still work over the broadcast and unicast fallbacks, but two copies cannot meet across a router that isolates clients. The discovery invariants, permission checks and regression matrix are in `docs/ENGINEERING-NOTES.md`. - On Windows only one Shift copy per machine can hold the discovery port, so extra instances do not appear as peers. -- Windows and Linux paths are compile-verified here, and the forge hosting this repository runs no Actions, so nothing is ever built by CI on your behalf. Gesture-level QA needs real Windows and Linux hardware. +- Windows and Linux paths are compile-verified here and covered by the repository's CI definition where a runner is available; gesture-level QA still needs real Windows and Linux hardware. - Signing identity changes on macOS may require re-approving Screen Recording and Accessibility. +- LAN sharing has no authentication or encryption. An accepted transfer proves only that you accepted an offer, not who sent it; use the feature on trusted networks. +- Office ZIP/XML parsing and PDF rendering still lack one shared resource quota across every codec and external renderer. Editor previews are bounded, but unusually large or adversarial documents should be treated as untrusted input. Roadmap: `docs/ROADMAP.md`. @@ -502,9 +514,9 @@ Quit from the tray and delete the app. Nothing is written outside your output fo ## Contributing -Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`. Adding a tool is one id in the right list in `src/lib/radialOrder.ts`, its label, its icon in `WEDGE_ICONS`, and one match arm in `executeAction` - the ring renders the same catalogue, so it appears with no other registration. Run `pnpm check`, `pnpm test`, `pnpm build` and `cargo test --lib` before pushing. +Adding a format is one entry in `conversionFormats` in `src/lib/conversionFormats.ts`, its matrix test, and its handling in `perform_action` in `src-tauri/src/files.rs`. Adding a tool is one id in the right list in `src/lib/radialOrder.ts`, its label, its icon in `WEDGE_ICONS`, and one match arm in `executeAction` - the ring renders the same catalogue, so it appears with no other registration. The full pre-push sequence is `pnpm check`, `pnpm test`, `pnpm build`, `cargo fmt --check`, `cargo test --lib`, `cargo clippy --all-targets -- -D warnings` and `git diff --check`; [`CONTRIBUTING.md`](CONTRIBUTING.md) has the platform setup and manual matrix. -`.github/workflows/ci.yml` carries macOS, Windows and Linux jobs, but **the forge hosting this repository has no Actions runner**, so those jobs are definitions rather than a live guarantee: nothing is built until a GitHub mirror, a Forgejo Actions instance, or a contributor runs them. The four commands above are what CI would run, plus `pnpm tauri build` per platform; `scripts/linux/Dockerfile` builds the Linux packages on a plain Docker host. +`.github/workflows/ci.yml` defines macOS, Windows and Linux jobs. The workflow runs type checks, TypeScript tests, Rust formatting and tests on every job, plus Clippy and a universal macOS app build. Whether the current forge executes it depends on whether that forge has a runner configured; a local run remains the release gate, and no CI result should be inferred without a linked log. Full setup and the pre-push checklist are in [`CONTRIBUTING.md`](CONTRIBUTING.md). **Forks and derivative works are welcome.** You may use, modify, redistribute, and build on this code commercially, provided you keep the copyright notice and the LICENSE file. diff --git a/README.zh-CN.md b/README.zh-CN.md index 389c289..6e67385 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,12 +1,12 @@ # Shift -**面向 macOS 与 Windows 的环形文件工作台。拖住文件,松开在某个扇区上,转换就在你自己的机器上完成。** +**面向 macOS 与 Windows 的环形文件工作台。拖住文件,松开在某个扇区上,转换就在你自己的机器上完成。** Linux 是可从源码构建的目标,不是已发布产品。 **语言:** [English](README.md) · **简体中文** Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部收进一个环形菜单,它出现在你放下文件的地方。不上传、不注册、不经云端中转——每一个字节都在本地处理。 -基于 Tauri 2、Rust、React 与 TypeScript 构建。原生截屏与拖拽行为封装在各平台适配器之后,因此环形菜单、编辑器与格式目录在所有平台上完全一致。 +基于 Tauri 2、Rust、React 与 TypeScript 构建。原生截屏与拖拽行为封装在各平台适配器之后,因此只要平台提供对应手势,环形菜单、编辑器与格式目录就保持一致。 --- @@ -29,6 +29,7 @@ Shift 把文件格式转换、截图、录屏、标注、中英双语 OCR 全部 - [平台支持情况](#平台支持情况) - [从源码构建](#从源码构建) - [架构](#架构) +- [技术文档](#技术文档) - [仓库结构](#仓库结构) - [隐私](#隐私) - [已知限制](#已知限制) @@ -160,7 +161,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普 | 单声道 | 音频 | `.m4a`,` (mono)` | 下混为单声道 128k AAC | | 纯文本 | 文档 | `.txt` | 通过 Pandoc 导出纯文本 | | 文字识别 | 图片、PDF | `.txt`,` (OCR)` | 见 [OCR](#ocr) | -| 编辑 / 标注 / 打码 / 加背景 | 图片 | — | 打开编辑器并预选对应工具 | +| 编辑 / 标注 / 打码 / 加背景 | 图片 | — | 打开图片编辑器,在工具栏中自行选择标注工具 | | 打开 · 在文件夹中显示 | 任意文件 | — | 交由系统默认应用或文件管理器 | ## 压缩、命名与取消 @@ -197,7 +198,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001 | 工具 | 行为 | | --- | --- | -| 矩形、箭头、高亮、文字 | 自由绘制,每条标注可单独设置颜色与粗细 | +| 矩形、箭头、高亮、文字 | 自由绘制;每种工具使用固定配色与线宽 | | 打码 | 实心黑色遮挡条,直接烧入输出图像——不是覆盖层 | | 马赛克 | 对下方区域做真实采样降采样,不是半透明填充 | | 模糊 | 对区域做真正的高斯模糊,并按绘制形状裁切 | @@ -210,7 +211,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001 | 保存副本 / 复制 | 另存为带后缀的新文件,或直接写入剪贴板 | | 钉在屏幕上 | 将图片浮为置顶窗口,带复制与关闭按钮 | -**编辑器。** 图片打开标注画布;视频打开播放器;`txt` `md` `csv` `tsv` `html` `htm` 以可编辑文本打开。每个编辑器都提供复制、另存为、打开、在文件夹中显示、文字识别与复制文字。 +**编辑器。** 图片打开标注画布;视频打开播放器;`txt` `md` `csv` `tsv` `html` `htm` 以**只读文本预览**打开。所有类型都提供复制、另存为、打开与在文件夹中显示;文字识别、复制文字与钉图只出现在图片编辑器中。文本不会在应用内就地编辑。文本超过 8 MB,或图片超过 64 MB / 4000 万像素时,编辑器会报告上限而不是加载。 ## 截图历史库 @@ -299,9 +300,9 @@ Shift 会持续维护局域网内其他 Shift 实例的列表,并据此提供 更新通道就是这个仓库:一条 `releases` 分支保存安装包以及 `shift-update.json` 清单,清单写明每个安装包的名称、体积与 SHA256。更新源地址在构建时由 git 远端推导——已适配 Gitea、GitHub、GitLab 三种形式,也可用 `SHIFT_UPDATE_URL` 覆盖——因此无需额外部署任何更新服务。 -Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。下载完成的安装包在安装前要通过两道校验:字节数完全一致,以及重新计算的 SHA256 与清单一致。任一不符即删除文件并明确报错,因此半成品永远不会被启动。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。 +Shift 每天启动时检查一次(也可在设置 → **软件更新** 中手动检查),读取清单、按含预发布规则的 semver 比较版本,然后提供下载。下载完成的安装包必须与清单的体积和重新计算的 SHA256 一致,而且这两项会在交接给安装脚本前**再次校验**。任一不符即删除文件并明确报错,因此半成品或被替换的安装包永远不会启动。点击「丢弃」会同时删除已下载的安装包和状态。发布只需一条命令 `scripts/publish-release.sh`;`docs/RELEASE.md` 说明清单格式、参数,以及可选的 ed25519 清单签名——签名用来证明清单的来源,而不只是下载内容与清单一致。 -**「安装并重启」让你在应用内完成升级**:macOS 会用下载好的磁盘镜像替换自己的 `.app`,Windows 会静默运行同一个安装程序,两者都由一个在 Shift 退出后才启动的辅助脚本执行,完成后自动打开新版本——正在进行的转换会被中断,但不会装到一半卡住,替换失败也会重新打开原来的版本。该标签页最上方依次显示本机系统、架构、当前版本与更新源,截一张图就能说明升级问题出在哪里。 +**「安装并重启」让你在应用内完成升级**:macOS 会用下载好的磁盘镜像替换自己的 `.app`,Windows 会静默运行同一个安装程序,两者都由一个在 Shift 退出后才启动的辅助脚本执行,完成后自动打开新版本——正在进行的转换会被中断,但不会装到一半卡住,替换失败也会重新打开原来的版本。辅助脚本通过进程参数接收路径,路径不会被拼接进 shell 或批处理脚本文本。该标签页最上方依次显示本机系统、架构、当前版本与更新源,截一张图就能说明升级问题出在哪里。 ## 外部依赖 @@ -410,6 +411,17 @@ OCR:Tesseract.js WASM + 内置 eng/chi_sim,进程内运行,完全离线 环形菜单的命中判定是纯几何计算——同一套极角运算同时服务于原生指针事件、webview 悬停与 Windows 的拖放数据,因此圆环行为不会在各平台之间产生偏差。 +## 技术文档 + +- [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) —— 进程/窗口模型、模块边界、事件与数据流。 +- [`docs/SPECIFICATION.md`](docs/SPECIFICATION.md) —— 产品行为规范、输出命名、平台差异与验收标准。 +- [`docs/SECURITY.md`](docs/SECURITY.md) —— 信任边界、更新完整性、局域网传输限制与剩余风险。 +- [`CONTRIBUTING.md`](CONTRIBUTING.md) —— 开发环境、测试门禁与发布前检查。 +- [`docs/README.md`](docs/README.md) —— 全部技术与发布文档的索引。 +- [`docs/ENGINEERING-NOTES.md`](docs/ENGINEERING-NOTES.md) —— 不允许退回到旧故障的工程回归台账。 +- [`docs/RELEASE.md`](docs/RELEASE.md) —— 发布通道、签名与更新交接。 +- [`docs/ROADMAP.md`](docs/ROADMAP.md) 与 [`docs/MOBILE.md`](docs/MOBILE.md) —— 后续计划与移动端方案。 + ## 仓库结构 ```text @@ -421,20 +433,20 @@ native/macos/ Swift 伴生进程:拖拽桥、PDF 渲染器、文档渲 由 pnpm mac:drag-bridge 编译进 src-tauri/binaries/ scripts/ OCR 资源准备、macOS 伴生进程、Windows 安装器、发布构建、 清单发布与清单签名 -public/tesseract/ WASM 内核与语言模型,构建生成,不提交 +public/tesseract/ WASM 内核与语言模型;由 pnpm prepare:ocr 刷新, + 已纳入仓库以保证干净检出可离线构建并离线 OCR assets/ 应用图标源文件 src-tauri/icons/ 各平台生成的应用图标 -docs/ Windows 构建指南、发布与更新通道、工程回归台账、路线图、移动端规划 -scripts/linux/ 在 CI 之外构建 Linux deb/AppImage 的 Dockerfile +docs/ 架构、行为规范、安全模型、发布指南、工程回归台账、路线图与移动端规划 +scripts/linux/ 构建 Linux deb/AppImage 的 Dockerfile .github/workflows/ macOS、Windows、Linux 的 CI 定义(见「参与贡献」) -FileFlipper/ 独立姊妹项目,拥有自己的仓库 ``` ## 隐私 Shift 对文件做的任何处理都不会发起互联网请求。文件在本地读取、转换、写回;OCR 在进程内基于内置模型运行;截图历史库只是一个本地文件。既不上传,也不收集。 -只有两条路径会接触网络,且默认都不携带文件内容:**更新检查**每天最多通过 HTTPS 拉取一次清单(只有你按下按钮时才下载安装包);而**发送到设备** 只与本地网络通信——`239.255.77.88:47888` 上的 UDP 广播,加上两台电脑之间的直连 TCP,其中携带机器名称以便双方互相标注。在你打开该面板、或有另一台 Shift 向你发送文件之前,它不会有任何动作。 +只有两条路径会接触网络,且只有你主动使用时才会携带文件内容:**更新检查**每天最多通过 HTTPS 拉取一次清单,只有你按下按钮时才下载安装包;**发送到设备**只在本地网络使用 `239.255.77.88:47888` 上的 UDP 信标和你所选设备之间的直连 TCP(或有另一台 Shift 主动向你发送文件)。分享关闭时发现不会启动,传输必须经接收方确认后才开始。局域网流量没有身份认证,也没有加密;该边界详见 [`docs/SECURITY.md`](docs/SECURITY.md)。 ## 已知限制 @@ -443,13 +455,15 @@ Shift 对文件做的任何处理都不会发起互联网请求。文件在本 - `.doc`、`.pages`、`.ppt`、`.key`、`.numbers` 可识别但不解析——请先导出为 DOCX/PPTX/XLSX。 - HEIC/HEIF/AVIF 可由系统解码器读取,格式转换与像素类工具都能直接使用。只是这两种格式无法经由该路径写出,因此对它们执行像素类工具时会输出 PNG;AVIF 仍不提供为导出目标。 - PDF 压缩会把内嵌图片降采样到最长边 1440 px、q60 JPEG。凡是不能确认可安全往返的内容都会原样保留——蒙版、索引色/CMYK、JPX/JBIG2/CCITT——因此部分特殊扫描件仍难以压缩。 -- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。Linux 的音视频转换同样需要它,区域录屏在 Wayland 下需要 `wf-recorder`、在 X11 下需要 `ffmpeg`;本仓库所在的代码托管平台不会执行这些路径,因此 Linux 的截图能力只能算「可编译」而非「已验证」。 +- Windows 的录屏与音视频转换要求 `PATH` 中存在 `ffmpeg`。Linux 的音视频转换同样需要它,区域录屏在 Wayland 下需要 `wf-recorder`、在 X11 下需要 `ffmpeg`。这些运行路径尚未在 macOS 开发机上实际验证,因此 Linux 截图能力在真机确认前只能算「可编译」。 - Linux 是「可构建」而非「已发布」:不提供 deb 或 AppImage,更新通道里也没有 `linux` 键,因此 Linux 构建检查更新时会得到「没有对应产物」。想要自己动手的人,可照 `scripts/linux/Dockerfile` 或 CI 里的 `linux` 任务来做。 - 把历史库的某一行拖出去依赖 Webview 对 file URL 拖拽的支持。载荷使用标准的 `text/uri-list`(内含 `file://` 条目)并附带纯文本路径,仍需在每个平台上做手势级验证;在此之前,**发送**、**在文件夹中显示**以及行内按钮是交付文件的确定路径。 - 局域网分享依赖允许点对点流量的网络。部分访客网络与企业 Wi-Fi 会丢弃组播;这些网络仍可经由广播与单播回退路径工作,但若路由器隔离了客户端,两个实例便无法相遇。发现机制的不可回退约束、权限排查与回归矩阵见 `docs/ENGINEERING-NOTES.md`。 - Windows 上每台电脑只有一个 Shift 实例能占用发现端口,因此额外实例不会出现在设备列表中。 -- Windows 与 Linux 代码路径在本机通过编译验证,而托管本仓库的平台并不运行 Actions,因此 CI 不会替你构建任何东西;手势层面的验证仍需真实 Windows 与 Linux 设备。 +- Windows 与 Linux 代码路径在本机通过编译验证,并在有执行器的托管平台上由仓库内的 CI 定义覆盖;手势层面的验证仍需真实 Windows 与 Linux 设备。 - macOS 上签名身份变化后,可能需要重新授予「屏幕录制」与「辅助功能」权限。 +- 局域网分享没有认证与加密。接受一次传输只能证明你同意了这次请求,不能证明发送者身份;请只在可信网络使用。 +- Office ZIP/XML 解析与 PDF 渲染尚未在所有编解码器和外部渲染器之间共享同一份资源配额。编辑器预览已有上限,但异常巨大或恶意的文档仍应按不可信输入处理。 路线图见 `docs/ROADMAP.md`。 @@ -489,9 +503,9 @@ Shift 对文件做的任何处理都不会发起互联网请求。文件在本 ## 参与贡献 -新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `src/lib/radialOrder.ts` 的对应列表中加入 id、补上文案、在 `WEDGE_ICONS` 中加入图标,再在 `executeAction` 中加一个分支——圆环渲染的就是同一份目录,因此无需别处注册即可出现。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build` 与 `cargo test --lib`。 +新增一种格式 = 在 `src/lib/conversionFormats.ts` 的 `conversionFormats` 中加一项、补充对应矩阵测试,并在 `src-tauri/src/files.rs` 的 `perform_action` 中加对应处理;新增一个工具 = 在 `src/lib/radialOrder.ts` 的对应列表中加入 id、补上文案、在 `WEDGE_ICONS` 中加入图标,再在 `executeAction` 中加一个分支——圆环渲染的就是同一份目录,因此无需别处注册即可出现。推送前请运行 `pnpm check`、`pnpm test`、`pnpm build`、`cargo fmt --check`、`cargo test --lib`、`cargo clippy --all-targets -- -D warnings` 与 `git diff --check`;平台环境与手工验收矩阵见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。 -`.github/workflows/ci.yml` 内含 macOS、Windows、Linux 三个任务,但**本仓库所在的托管平台没有 Actions 执行器**,因此这些任务目前只是定义、而非实时保障:只有镜像到 GitHub、接入 Forgejo Actions,或由贡献者本地执行时才会真正构建。CI 会执行的就是上面这四条命令,外加各平台的 `pnpm tauri build`;Linux 安装包可在普通 Docker 主机上用 `scripts/linux/Dockerfile` 构建。 +`.github/workflows/ci.yml` 定义了 macOS、Windows、Linux 三个任务。每个任务都会运行类型检查、TypeScript 测试、Rust 格式检查与单元测试;macOS 任务还运行 Clippy 和通用应用构建。当前托管平台是否真正执行这些任务,取决于它是否配置了执行器;本地运行仍是发布门禁,没有链接到实际日志时不得声称 CI 已通过。完整环境与推送前检查见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。 **欢迎二次开发。** 你可以免费使用、修改、再发布本代码,也可用于商业项目,只需保留原版权声明与 LICENSE 文件。 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..8c078d5 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,223 @@ +# Architecture + +Shift is a single locally running desktop process. There is no application +backend, account service or cloud database. Rust owns native work, durable +state and process boundaries; React owns presentation and transient interaction +state. + +This document describes the current shape. Behavioural requirements live in +[`SPECIFICATION.md`](SPECIFICATION.md), security boundaries in +[`SECURITY.md`](SECURITY.md), and historical failure constraints in +[`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md). + +## Process and window model + +The Tauri process hosts one webview asset bundle. `src/App.tsx` selects one of +eight view kinds from the `view` query parameter: + +| View | Window label | Responsibility | +| --- | --- | --- | +| `main` | `main` | File picker, drop targets, recent library, settings, first-run checks | +| `radial` | `radial` | Transparent always-on-top format/tool ring | +| `capture` | `capture` | Frozen-screen overlay and area selection | +| `recorder` | `recorder` | Recording timer and stop control | +| `editor` | `editor` | Image annotation, video player, read-only text preview, OCR | +| `result-card` | `result-*` | Post-capture actions; one window per capture | +| `share-notice` | `share-*` | Incoming-transfer consent card | +| `pin` | `pin` | Always-on-top image reference | + +Closing the main, editor, radial or pin window hides it rather than exiting the +app. Tray and global-shortcut actions can bring these surfaces back. A second +instance is routed to the existing copy by `tauri-plugin-single-instance`; only +one process owns the global shortcuts and, on Windows, the shared discovery +port. + +## State ownership + +Rust-owned runtime state is registered as managed Tauri state: + +- `AppState`: capture session, recording child, editor session, radial drag + context, native drag bridge process and capture-window restoration list. +- `ShareState`: local beacon, bounded peer table, pending consent offers, + accepted batch windows and the discovery enabled flag. +- `HistoryState`: the in-memory recent-file list, persisted to + `app_data_dir/history.json`. +- `UpdateState`: last update status and whether the last signature check + passed. + +Settings are persisted as one JSON read-modify-write document at +`app_config_dir/settings.json`. Writes use a process-wide mutex and an atomic +replace (temporary file then rename). History is a convenience cache: its write +is a single replace and a corrupt or missing file falls back to an empty list. + +Frontend state is not authoritative for file output, history, downloads or +editing results. A renderer can be hidden and recreated; durable state remains +in Rust or on disk. + +## Module boundaries + +| Module | Owns | +| --- | --- | +| `files.rs` | Extension classification, previews, conversion/tool catalogue execution, collision-safe output names, editor data commands, external process helpers | +| `pdf.rs` | PDF merge/split/rotate/text/render/compress and PDF-to-DOCX packaging | +| `office.rs` | DOCX image-page extraction, PPTX text/tables and spreadsheet parsing | +| `markdown.rs` | Bundled Markdown-to-HTML fallback | +| `capture.rs` | Screen permission checks, monitor selection, screenshot capture, crop and result handoff | +| `recording.rs` | `screencapture`, FFmpeg and `wf-recorder` backends, stop/finalization | +| `drag_bridge.rs` | Native drag detection, ring mode and radial context | +| `editor.rs` | Editor session and pinned-image window state | +| `history.rs` | Recent-file merge, capacity, pinning, persistence and events | +| `settings.rs` | Settings schema, output directories, write checks, app language | +| `share.rs` | LAN discovery, peer table, SHSF transfer protocol and consent | +| `update.rs` | Manifest fetch/parse/signature, download, integrity gate and installer handoff | +| `result_card.rs` | Post-capture card lifecycle and auto-close | +| `runtime.rs` | External component detection and installation instructions | +| `process.rs` | Spawn helper that suppresses console windows on Windows | + +`pdf.rs`, `office.rs` and `markdown.rs` deliberately have no Tauri window +management. They operate on paths and values so they can be tested without a +live app handle. + +## Core data flows + +### File action + +1. A drag, picker or recent row chooses one action and one or more source paths. +2. `RadialMenu.tsx` calls `perform_file_action` with a generated `jobId`. +3. Rust runs `files::perform_action` off the UI thread. +4. Progress may arrive as `app://file-action-progress`; completion arrives as + `app://file-action-finished` with either an `ActionOutcome` or an error code. +5. New paths are recorded in `history.json`, broadcast on `history://changed` + and announced through `app://file-result`. +6. The UI reveals results only if the auto-reveal setting is enabled. + +Source files are opened read-only. Every output goes through `unique_output` or +`unique_output_in`, which append ` 2`, ` 3`, ... instead of replacing an +existing file. + +### Capture and recording + +1. `start_capture` checks screen-capture permission and selects the monitor + under the pointer. +2. The screen is captured to a temporary file, Shift's own windows are hidden, + and the `capture` overlay is shown with the frozen frame. +3. A crop is written through the same collision-safe naming path as any other + result. Full-screen capture skips the overlay. +4. A result card window is created; if it cannot be created, the editor opens + instead so the capture still has an action surface. +5. Recording is a separate child process. Stopping it finalizes the file, + restores hidden windows and hands the recording to the editor/card flow. + +### Editor + +Images are read by Rust and returned as a data URL so the canvas can export +without cross-origin taint. Annotation happens in the renderer; saving returns +the composed PNG to Rust, which decodes it, checks limits and writes a new file. +Text files are read by Rust and shown in a read-only `
`. Videos are loaded
+through the asset protocol and played by the webview.
+
+The editor does not write back to the source. `Copy` and `Save As` remain
+separate operations.
+
+### OCR
+
+Image OCR runs in the renderer through Tesseract.js/WASM. The worker, core and
+English/Simplified Chinese models are local files under `public/tesseract/`.
+PDF OCR is a Rust-to-renderer loop: Rust renders each PDF page into a cache
+folder, the renderer recognizes page images, then Rust writes the combined text
+result and the cache folder is cleaned up.
+
+No OCR path uploads a file or downloads a model at runtime.
+
+### LAN sharing
+
+One long-lived UDP discovery thread sends multicast, directed broadcast,
+limited broadcast and a bounded unicast sweep. Peers are kept in a table capped
+at 256 entries and expire after 15 seconds without a beacon. The table emits
+`share://peers` only when its visible signature changes.
+
+Transfers use a direct TCP connection to the port advertised in the beacon:
+
+```text
+"SHSF" | 4-byte big-endian header length | JSON header | 0/1 decision | body | ack
+```
+
+The receiver writes to a temporary `.shift-part` file and renames only after the
+exact declared byte count has arrived. The sender copies exactly the header's
+declared size, so a source file that grows cannot bleed bytes into the ack.
+Inbound offers prompt once; later files in the same accepted batch use a
+two-minute trust window.
+
+The protocol has no authentication or encryption. Consent prevents automatic
+writing, not sender impersonation. See [`SECURITY.md`](SECURITY.md).
+
+### Updates
+
+1. The manifest URL is derived at build time from the git remote, or overridden
+   with `SHIFT_UPDATE_URL`.
+2. The manifest is fetched, capped at 256 KiB, parsed as `schema: 1`, and each
+   named artifact must be a safe basename with a nonzero size and SHA256.
+3. If a public key is baked in, the detached `shift-update.sig` must verify over
+   the manifest's exact bytes.
+4. The artifact is downloaded to the temp update directory, then its exact size
+   and SHA256 are checked.
+5. Before installing, both checks run again; a failure deletes the artifact.
+6. macOS and Windows hand the installer to a detached helper only after Shift
+   exits. Paths are process arguments, never interpolated script text.
+
+## Events
+
+Events are grouped by owner and are not a replacement for durable state.
+
+| Event | Producer | Purpose |
+| --- | --- | --- |
+| `app://error` | Rust | User-visible native failure |
+| `app://file-action-progress` | `files.rs` | Job-specific progress |
+| `app://file-action-finished` | `files.rs` | Success or error for one job |
+| `app://file-result` | history/capture/share | New result is available |
+| `capture://ready` | capture | Overlay session data |
+| `editor://open` | editor | New editor session |
+| `pin://show` | editor | Pinned image payload |
+| `history://changed` | history | Shared recent list changed |
+| `radial://*` | drag bridge | Drag context, mode, drop and dismissal |
+| `recording://started` | recording | Recording session data |
+| `share://peers` | share | Visible peer list changed |
+| `share://transfer` | share | Sending/received/error transfer state |
+| `update://progress` | update | Download state |
+| `update://status` | update | Verified update or error state |
+
+## Platform adapters
+
+| Concern | macOS | Windows | Linux |
+| --- | --- | --- | --- |
+| Drag detection | AppKit drag bridge sidecar | Win32 drag-state poll plus native drop | No global drag bridge; main-window picker only |
+| Capture | `screencapture` | GDI `BitBlt` / `GetDIBits` | `grim`, fallback `gnome-screenshot` |
+| Recording | `screencapture -v` | FFmpeg/X11 | `wf-recorder` on Wayland, FFmpeg on X11 |
+| Document/PDF rendering | AppKit/PDFKit Swift sidecars | Poppler/Pandoc | Poppler/Pandoc |
+| LAN discovery interface list | `getifaddrs` | `GetAdaptersAddresses` | `getifaddrs` |
+
+All external processes go through `process::command`, which hides console
+windows on Windows. A source-check test rejects bare `Command::new` in shipped
+code.
+
+## Invariants
+
+- A conversion or tool never overwrites its source or an existing output.
+- A visible wedge exists only because the format catalogue lists it and the
+  backend has a handler.
+- Failures the interface maps have stable backend codes; raw third-party
+  diagnostics may pass through unchanged.
+- A transfer or update is not considered complete until all declared bytes are
+  present and any required hash matches.
+- A helper process receives untrusted paths as arguments, never as executable
+  script text.
+- Resource limits are enforced before unbounded allocation where a path can
+  receive large local input.
+
+## Related documents
+
+- [`SPECIFICATION.md`](SPECIFICATION.md): observable behaviour and acceptance.
+- [`SECURITY.md`](SECURITY.md): threat model and residual risk.
+- [`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md): regression constraints.
+- [`RELEASE.md`](RELEASE.md): update channel and handoff.
+
diff --git a/docs/ENGINEERING-NOTES.md b/docs/ENGINEERING-NOTES.md
index 2682181..8104723 100644
--- a/docs/ENGINEERING-NOTES.md
+++ b/docs/ENGINEERING-NOTES.md
@@ -132,7 +132,7 @@ cargo test share:: -- --ignored --nocapture
 | 权限拒绝再允许 | macOS 本地网络或 Windows 防火墙从拒绝改为允许后,重新打开面板可发现。 |
 
 0.1.7 的用户验收环境是 Mac 与 Windows 各一台,升级后 Drop 设备发现正常。该结论
-覆盖真实跨系统发现,但仓库所在平台没有 CI,也没有自动化的双机网络夹具,因此发布前
+覆盖真实跨系统发现;CI workflow 能验证协议单元测试,但没有双机网络夹具,因此发布前
 仍需重复上面的手工矩阵。
 
 ## DOCX、Markdown 与图片转换
@@ -610,6 +610,56 @@ CSS 画,不用图标字体,保证任何缩放下都锐利)。
 把 unknown 变成文案的唯一途径。不可用控件统一用 `--dimmed` 与 `cursor: default`,
 `:hover` 一律带 `:not(:disabled)`。
 
+## 更新、分享与读取边界
+
+2026-11 的全面评审补了一组不应被简化掉的约束。它们共同处理的是同一类问题:
+**一个被声明为“已校验”的对象,在真正使用前仍可能变化,或声明值本身可能不可信。**
+
+### 更新链路
+
+| 约束 | 原因 |
+| --- | --- |
+| 清单里的文件名必须直接位于发布目录 | 路径分隔符、`..`、空格和 shell 元字符不能进入下载路径或交接参数;发布脚本产出的文件名只含 ASCII 字母、数字、`.`、`-`、`_` |
+| 清单下载后限制 256 KiB | 清单是小型 JSON;损坏或被替换的 feed 不应无限占用内存 |
+| 下载后校验是普通文件、精确字节数和 SHA256 | 只比较哈希仍会接受声明尺寸与实际尺寸不一致的输入 |
+| 安装前再次执行同一组校验 | 下载文件位于可写的临时目录,下载完成到用户点击安装之间存在 TOCTOU 窗口;失败时必须删除文件 |
+| macOS/Windows 辅助脚本使用固定脚本常量,路径作为进程参数传入 | 文件夹名不能改变 helper 的脚本文本;Windows `cmd.exe` 的参数解析仍需真机覆盖极端路径字符 |
+| `Discard` 删除实际下载物 | 只清状态会留下可被误用的旧安装包 |
+
+回归测试:`artifact_names_stay_inside_the_release_directory`、
+`an_installer_changed_after_download_is_refused`,以及两个 handoff 脚本的参数化
+检查。真实 Windows 交接仍需在 Windows 机器上验收。
+
+### 分享链路
+
+| 约束 | 原因 |
+| --- | --- |
+| peer 表最多 256 项,满时先清理过期项 | 未认证信标可伪造无限 id;可见列表不能无限增长 |
+| 发送端按 header 声明大小精确复制 | 源文件在 metadata 之后变长时,多出的字节会被接收端误当成 ack |
+| 源文件比声明短时立即失败 | 不允许用半截文件换取成功状态;接收端删除 `.shift-part` |
+| 只有用户已接受后的接收失败才弹错误 | 任意 TCP 扫描或坏握手不应产生用户可见的 toast |
+| 接收错误事件带文件名与 peer 名 | 失败要可定位,而不是只有一句泛化提示 |
+
+回归测试:`the_peer_table_stops_accepting_new_ids_at_its_limit`、
+`bytes_after_the_declared_size_never_cross_the_wire`、
+`a_source_that_shrinks_is_refused_without_a_partial_file`。
+
+分享协议本身仍无认证、无加密;这里修的是拒绝自动落盘、路径安全、字节边界和可见
+失败,不是身份认证。安全边界见 `docs/SECURITY.md`。
+
+### 编辑器读取
+
+| 数据 | 上限 | 测试 |
+| --- | --- | --- |
+| 文本预览 | 8 MiB | `editor_reads_are_bounded_before_they_allocate` |
+| 图片文件 | 64 MiB | 同上 |
+| 图片像素 | 4000 万 | 与钉图上限一致 |
+| 编辑后 data URL | 128 MiB | 解码前检查 |
+
+文本与图片在 Rust 读盘前检查路径是否为普通文件并执行上限;UI 只负责把返回的
+`errNotAFile` / `errTextTooLarge` / `errImageTooLarge` / `errEditDataTooLarge`
+翻译成文案。不要在只读预览里静默吞掉读取错误。
+
 ## 修改这些路径时的统一回归命令
 
 ```bash
@@ -618,10 +668,12 @@ git diff --check
 cd src-tauri
 cargo fmt --check
 cargo test --lib
+cargo clippy --all-targets -- -D warnings
 
 cd ..
 pnpm check
 pnpm test
+pnpm build
 ```
 
 发布构建还需额外完成本文对应章节的手工矩阵。任何一次修改如果改变了发现协议、转换
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index ddf361b..2846671 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -32,7 +32,7 @@ already perform every day:
 | --- | --- | --- |
 | Shift-drag out of the Finder row, release over a wedge | **Share sheet**, including the drag-and-drop share from Files/Photos/Safari where the picker slides out from under the finger | **Share sheet**, same shape, from any app |
 | Radial ring of wedges | The share sheet's own app list, plus a Share Extension whose UI we own | Share sheet targets, plus an Action/Share Activity we own |
-| Ring reorder in Settings | Share sheet "Edit Actions" ordering, mirrored in our Settings | Same, mirrored |
+| Ring order (desktop reads `settings.json`; no editor UI in 0.1.11) | Share sheet "Edit Actions" ordering, mirrored in a mobile Settings surface | Same, mirrored |
 
 So the mobile pitch is not "Shift in your pocket", it is: **release a share over a Shift
 action**. Concretely: long-press an image in Files → Share → Shift → *HEIC → PNG, then
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..aeef98b
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,28 @@
+# Shift documentation
+
+Start with the user guide, then choose the engineering document that matches the
+work.
+
+| Document | Audience | Contents |
+| --- | --- | --- |
+| [`../README.md`](../README.md) / [`../README.zh-CN.md`](../README.zh-CN.md) | Users | Features, formats, shortcuts, privacy, known limitations |
+| [`ARCHITECTURE.md`](ARCHITECTURE.md) | Contributors | Process/window model, module ownership, events, data flows |
+| [`SPECIFICATION.md`](SPECIFICATION.md) | Product and QA | Observable behaviour, naming, limits, acceptance criteria |
+| [`SECURITY.md`](SECURITY.md) | Security reviewers and maintainers | Trust boundaries, update and LAN risk, residual gaps |
+| [`ENGINEERING-NOTES.md`](ENGINEERING-NOTES.md) | Contributors | Regression ledger and non-negotiable implementation constraints |
+| [`RELEASE.md`](RELEASE.md) | Release maintainers | Channel layout, signing, update handoff and verification |
+| [`BUILD_WINDOWS.md`](BUILD_WINDOWS.md) | Builders | Windows prerequisites, cross-build and installer notes |
+| [`ROADMAP.md`](ROADMAP.md) | Contributors | Completed milestones and next desktop work |
+| [`MOBILE.md`](MOBILE.md) | Product planning | Mobile feasibility and architecture plan |
+| [`../CONTRIBUTING.md`](../CONTRIBUTING.md) | Contributors | Setup, checks, change rules and manual matrix |
+
+## Source of truth
+
+- Current code and tests define implemented behavior.
+- The conversion/tool tables in `README` describe the user-visible catalogue;
+  the runtime catalogue lives in `src/lib/conversionFormats.ts` and
+  `src/lib/radialOrder.ts`.
+- Platform/runtime limitations must be stated as unverified when no real
+  hardware run exists.
+- Do not claim a CI run without linking its log.
+
diff --git a/docs/RELEASE.md b/docs/RELEASE.md
index f5e5a9d..ca17101 100644
--- a/docs/RELEASE.md
+++ b/docs/RELEASE.md
@@ -32,6 +32,11 @@ bytes and its SHA256:
 }
 ```
 
+Artifact names are restricted to ASCII letters, digits, `.`, `-` and `_`; path
+separators, `..`, spaces and shell metacharacters are rejected. The app also
+refuses a manifest over 256 KiB. These checks keep malformed manifest data out
+of download paths and out of the native handoff arguments.
+
 ## Supported release targets
 
 **Shift ships two installers: macOS (universal) and Windows x64.** That is a scope decision,
@@ -234,6 +239,12 @@ a new baked key; leaking it means an attacker can publish anything to the channe
 as leaking push access to `releases` already does today. Keep it outside the repository —
 `~/.config/shift-release/` is where the local publishing machine keeps it.
 
+`scripts/release-key.py` treats a file ending in `.pub` as an ed25519 public
+key and every other path as the 32-byte private key. `keygen` writes the private
+key (`release.ed25519`, mode 0600) and its public companion (`release.pub`). Keep
+the private key out of CI logs and do not rename the public file to a non-`.pub`
+name when using `pubkey`.
+
 ## Where a build looks for updates
 
 `src-tauri/build.rs` derives the feed from the `origin` remote at build time:
@@ -265,15 +276,17 @@ guessing at one.
    so restarts cannot spend the day's check twice.
 2. Versions are compared with semver rules, prereleases included: `0.2.0-alpha` sorts
    below `0.2.0`, so a test build does not offer to downgrade itself.
-3. Download writes into a temp folder, then two gates run before anything can be
-   installed: the byte length must equal the manifest's `size`, and the recomputed SHA256
-   must equal the manifest's `sha256`. A mismatch deletes the file and reports the error,
-   so a truncated or swapped installer never reaches the installer step.
+3. Download writes into a temp folder, then two gates run: the byte length must equal the
+   manifest's `size`, and the recomputed SHA256 must equal the manifest's `sha256`. Both
+   checks run again immediately before the handoff. A mismatch deletes the file and
+   reports the error, so a truncated or swapped installer never reaches the installer
+   step.
 4. **Install & relaunch** applies the verified artifact and restarts Shift on it, as
-   described in the next section; **Discard** removes the download. When an update is
-   available the tray menu gains a row that opens Settings on the Updates tab.
+   described in the next section; **Discard** removes the downloaded artifact as well as
+   the update status. When an update is available the tray menu gains a row that opens
+   Settings on the Updates tab.
 
-Manifest `schema` is checked, and a newer schema than this build understands is refused
+Manifest `schema` is checked; this build accepts exactly `1` and refuses anything else
 instead of being parsed optimistically. Unknown platform keys are ignored, so the
 manifest can name a platform an older app has never heard of. The Updates panel always
 states which of the two properties the current feed satisfies, so an unsigned channel
@@ -294,10 +307,12 @@ for that pid to disappear and only then touches the installed copy.
 
 Both scripts are written so a failure cannot end with Shift simply closed: every macOS
 failure path still `open`s the bundle it had, and the swap is `move aside, move in`, so a
-copy that fails halfway leaves the previous version where it was. Before the handoff
-starts, macOS writes a probe file next to the bundle — a root-owned copy in
-`/Applications` is reported as "open the downloaded installer yourself" rather than
-quietly quitting on an update that could not be applied.
+copy that fails halfway leaves the previous version where it was. The scripts themselves
+are fixed constants; the pid, installer, bundle and log paths are passed as process
+arguments, not interpolated into shell or batch source. Before the handoff starts, macOS
+writes a probe file next to the bundle — a root-owned copy in `/Applications` is reported
+as "open the downloaded installer yourself" rather than quietly quitting on an update
+that could not be applied.
 
 The Windows installer is the same one a user runs by hand, so the update path cannot drift
 from the manual one. Because the silent install comes from Shift itself, `${Silent}` skips
@@ -353,7 +368,10 @@ test, which is the proof that the check is real and not a pass-through.
 
 ## State of the published channel
 
-Checked against the live `releases` branch of this repository:
+This section is a historical audit of the published channel at the time it was
+performed. It is not a claim that the current `releases` branch still contains
+this version or that CI produced it. Re-run the verification below before using
+these numbers in release notes.
 
 Version **0.1.7**, checked by downloading each artifact back from the raw endpoint rather
 than trusting the local copy:
@@ -377,9 +395,9 @@ Both artifacts carry the key and the feed URL, which is what makes an in-app upg
 possible at all: a build whose binary predates those constants reports "this build has no
 feed" and can never see the channel, however new it is.
 
-The forge runs **no Actions**, so nothing on this list was built by CI: every artifact was
-cross-compiled on one macOS host and pushed with `scripts/publish-release.sh`. Treat "pass
-CI" in the contributing guide as a definition to run locally, not a gate that already ran.
+The workflow defines separate macOS, Windows and Linux jobs, but this audit did
+not record a linked CI run. Treat the local commands in `CONTRIBUTING.md` as the
+release gate unless a green run is attached to the release.
 
 A Linux release would slot in under the `linux` key with no code change — `artifact_keys_for`
 already answers `linux` for that host — so publishing one is a build task, not a feature.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 8fd5530..146ba7e 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -62,8 +62,8 @@ names what is still missing.
   unicast sweep; ordinary beacons receive one marked reply, and peer expiry is long enough
   for older copies to answer. The user-observed acceptance run covered one Mac and one
   Windows x64 machine after an upgrade. Unit tests cover the scan bounds, timeout and reply
-  semantics, but the live two-host check is manual because this forge runs no CI and the
-  repository has no second-machine fixture. Client-isolated Wi-Fi remains outside the app's
+  semantics, but the live two-host check is manual because the repository has no
+  second-machine fixture. Client-isolated Wi-Fi remains outside the app's
   control, and Windows still permits only one listener per machine. The exact invariants
   and manual matrix are in `docs/ENGINEERING-NOTES.md`.
 - Windows ARM64: the release pipeline ships only the x64 NSIS installer, checks its
@@ -162,9 +162,10 @@ Restricted to work this repository can do something about; hardware QA is last b
 commit closes it. Each item states the check that closes it. Linux packaging is deliberately
 absent — the platform is supported, not shipped.
 
-1. **A real CI run.** The forge (Gitea) returns 404 for `/actions/runs`, so `ci.yml` is
-   never executed. Either mirror to GitHub or install Forgejo Actions. Close: one green run
-   per platform whose log is linked from the release notes.
+1. **A verified CI run.** `ci.yml` defines macOS, Windows and Linux jobs, but no linked
+   run in this repository proves that the current hosting forge executes them. Either
+   configure a runner or run the workflow on a mirror. Close: one green run per platform
+   whose log is linked from the release notes.
 2. **Persistent job queue with cancel and retry.** `perform_file_action` already emits
    `app://file-action-progress` with real page counts, but a batch dies with the window and
    an error aborts the rest of the batch. Close: a queued batch survives an app restart,
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
new file mode 100644
index 0000000..b710e66
--- /dev/null
+++ b/docs/SECURITY.md
@@ -0,0 +1,193 @@
+# Security model
+
+Shift is a local desktop utility that opens files the user chooses, invokes
+native renderers and external tools, listens for local-network transfers, and
+installs signed or hash-verified updates. This document states what is
+protected, how, and what remains outside the current guarantee.
+
+It is a design document, not a promise that every path has received an
+independent audit.
+
+## Assets
+
+- The user's source files and output folders.
+- The integrity of the installed application and its update channel.
+- The user's consent before another machine writes a file.
+- Local data such as `settings.json` and `history.json`.
+- Release-signing and manifest-signing secrets.
+
+## Threat model
+
+Relevant adversaries include:
+
+- a malicious or malformed image, document, PDF or media file;
+- a machine on the same LAN that sends beacons, opens transfer sockets or
+  impersonates another Shift;
+- a compromised update feed, release branch or HTTP endpoint;
+- an attacker who can modify files in the user's temp or config directories;
+- a compromised renderer or injected content in the bundled webview.
+
+The model does not assume the local operating-system account is already
+compromised. An attacker with the user's account can generally read and modify
+the same files Shift can.
+
+## Local file access and webview
+
+Shift's own React bundle calls Tauri commands with paths selected by the user or
+returned by Shift. There is no user-authored HTML or remote page loaded into the
+main window. External files are treated as data, not executable content.
+
+The Tauri configuration currently sets `csp: null` and gives the asset protocol
+scope `**`. That is intentionally broad because the editor and previews need
+local files and the canvas needs same-origin image data. If renderer-content
+injection is ever found, those settings increase the impact: the injected script
+could call available commands or read local assets. Hardening this would require
+a tested CSP/asset-scope reduction and a full editor, OCR-worker and clipboard
+smoke test; until then, treat the webview bundle as part of the trusted computing
+base.
+
+The app does not ship a remote-content loader, analytics SDK or advertising
+component.
+
+## Untrusted files and resource exhaustion
+
+File extensions decide the conversion catalogue, but not trust. Document and
+media parsers receive attacker-controlled bytes.
+
+Implemented bounds:
+
+- editor text preview: 8 MiB before reading;
+- editor image input: 64 MiB before reading, plus a 40-megapixel decode limit
+  where the decoder can report dimensions before full decode;
+- editor data URL: 128 MiB, with a second decoded-size and pixel check;
+- pinned-image preview: 40 megapixels;
+- update manifest: 256 KiB after download;
+- update artifact: exact declared size and SHA256, rechecked before install;
+- LAN peer table: 256 entries;
+- LAN transfer: the receiver reads exactly the header-declared byte count and
+  removes a partial temp file on failure;
+- GIF conversion: time, frame-rate, width and byte ceiling;
+- PDF page extraction: per-page extracted-text limit and bounded render edge.
+
+Not yet uniformly bounded:
+
+- Office ZIP entries and XML can still expand under decoder defaults; there is
+  no one shared decompressed-size quota across DOCX/PPTX/XLSX paths.
+- PDF rendering and compression rely partly on external renderers (PDFKit,
+  Poppler, ImageMagick, FFmpeg) with their own limits.
+- CSV/TSV and some Office paths read whole files or sheets into memory.
+- LAN transfers have no maximum file size or free-space preflight. The receiver
+  sees the declared size before accepting, but a malicious peer can still
+  occupy disk after consent.
+- A manifest download is size-checked after it has been written, not while it is
+  streaming.
+
+Do not open adversarial documents in production until these paths have explicit
+quotas and tests. Report a reproducible resource-exhaustion case rather than
+assuming the editor limits cover every converter.
+
+## Update trust boundary
+
+The update channel is a git branch containing `shift-update.json`, optional
+`shift-update.sig`, and installer files. Builds derive the feed URL from the git
+remote or from `SHIFT_UPDATE_URL`.
+
+Controls:
+
+- manifest `schema` must be exactly the supported version (currently 1);
+- artifact filenames must be safe ASCII basenames;
+- artifact size must be nonzero and SHA256 must be valid hex;
+- the manifest is capped at 256 KiB;
+- a build compiled with `SHIFT_UPDATE_PUBKEY` requires a detached ed25519
+  signature over the manifest's exact bytes;
+- the installer is checked for exact byte length and SHA256 after download;
+- both checks run again immediately before installing;
+- the installer must be a regular file, not a symlink;
+- macOS and Windows handoff scripts receive paths as process arguments, not
+  interpolated shell/batch text;
+- `Discard` deletes the downloaded artifact, not just the UI state.
+
+Residual risk:
+
+- An **unsigned** build trusts the HTTPS origin plus anyone able to write the
+  release branch or its raw endpoint. SHA256 proves the file matches the
+  manifest, not that the manifest is authentic.
+- A signed build trusts the baked public key and the custody of its private key.
+  Leaking the key allows publishing a malicious manifest and installer.
+- The update artifacts are ad-hoc signed and not notarized on macOS. Gatekeeper
+  cannot independently vouch for the publisher; the in-app hash/signature path
+  is the relevant check.
+- Windows installer signing is not currently performed.
+- The download directory is under the system temp directory. Re-verification
+  detects replacement before install, but local temp-directory manipulation is
+  still a same-account threat.
+- Windows runs the handoff through `cmd.exe`; argument passing is covered by
+  source-level checks, but every legal character in a user-profile path still
+  needs real Windows validation.
+
+## LAN sharing
+
+Discovery uses UDP multicast/broadcast/unicast on `239.255.77.88:47888`.
+Transfers use a direct TCP connection advertised by the beacon.
+
+The SHSF protocol is **not authenticated, not encrypted and not confidential**.
+Anyone on the reachable network can:
+
+- observe beacon metadata such as machine name and platform;
+- send a forged offer with an arbitrary sender name and transfer id;
+- attempt connections to the receiver's TCP port.
+
+The consent card prevents an unsolicited transfer from being written
+automatically. It does **not** prove that the named sender is the real owner of
+that machine. Accept files only from people and networks you trust. The batch
+window means later files from the same unauthenticated batch id are accepted for
+120 seconds without another prompt.
+
+Implemented limits:
+
+- peer table capped at 256, with stale entries removed first;
+- transfer header capped at 64 KiB;
+- part files are removed after failure;
+- sender copies exactly the declared size, so extra source bytes cannot be
+  mistaken for the acknowledgement;
+- receiver reports a transfer error after an accepted transfer fails.
+
+No protocol-level authentication, encryption, rate limiting or maximum transfer
+size is implemented. Firewall or OS network policy is the outer boundary.
+
+## External processes and secrets
+
+External tools are invoked with argument arrays through `process::command`,
+which also hides console windows on Windows. Paths are not passed through a
+shell except where a documented system command requires one; those call sites
+must be reviewed individually.
+
+The release private key (`.ed25519`) must remain outside the repository and
+outside build artifacts. `SHIFT_RELEASE_KEY` is for the packaging host only;
+`SHIFT_UPDATE_PUBKEY` is the public value intended to be baked into builds.
+Never paste a private key into an issue, log or CI variable that is visible to
+untrusted jobs.
+
+## Platform permissions
+
+- macOS Screen Recording enables capture.
+- macOS Files & Folders enables selected output directories.
+- macOS Microphone enables recording with audio.
+- macOS Local Network enables multicast discovery.
+- Windows Firewall must allow private-network traffic for discovery/receive.
+
+Ad-hoc macOS signing can change the code identity on rebuild, causing
+permissions to reset. A Developer ID identity would stabilize them but is not
+currently part of the release pipeline.
+
+## Reporting
+
+Report a vulnerability privately through the repository host's available
+private security channel. Include the affected version, platform, minimal
+reproduction, expected/actual behavior and whether a file, LAN peer or update
+feed is required. Do not attach a stolen signing key or a working exploit to a
+public issue.
+
+If no private channel is configured, contact the maintainers first and share
+only enough detail to establish a private transfer method.
+
diff --git a/docs/SPECIFICATION.md b/docs/SPECIFICATION.md
new file mode 100644
index 0000000..5eda67a
--- /dev/null
+++ b/docs/SPECIFICATION.md
@@ -0,0 +1,281 @@
+# Shift 产品行为规范
+
+本文定义 Shift 0.1.11 可观察到的产品行为与验收口径。实现结构见
+[`ARCHITECTURE.md`](ARCHITECTURE.md),安全边界见 [`SECURITY.md`](SECURITY.md)。
+若本文与代码冲突,以代码和自动化测试为准,并应同步修正本文。
+
+## 1. 范围
+
+Shift 是一个本地桌面文件工作台,提供:
+
+- 类型感知的格式转换与文件工具;
+- 区域/全屏截图与区域录屏;
+- 图片标注、只读文本预览、视频播放;
+- 英文与简体中文 OCR;
+- 局域网设备发现与文件发送;
+- 基于 git 通道的应用内更新。
+
+不包含:账号、云端存储、遥测、文件上传、局域网中继、文本就地编辑、
+Linux 官方安装包、macOS 公证。
+
+## 2. 产品不变量
+
+1. **源文件只读。** 转换、压缩、旋转、裁剪、标注和 OCR 都写出新文件。
+2. **永不覆盖。** 所有输出使用唯一文件名;同名时追加 ` 2`、` 3`……
+3. **本地处理。** 转换与 OCR 不发起网络请求;只有更新检查和用户主动发起的
+   局域网传输会使用网络。
+4. **界面只展示可执行操作。** 格式目录决定扇区;后端没有处理器的动作不得出现。
+5. **失败必须可见。** 用户操作失败时,界面显示可读文案;不允许静默停在空状态。
+6. **已映射错误本地化。** 界面需要稳定识别后端失败时,Rust 返回 `err*` /
+   `share-*` 等代号,由 `src/i18n.ts` 映射为中英文;原始第三方诊断可以原样透传。
+7. **能力如实申报。** 录屏、OCR、转换和平台权限只显示当前后端真正支持的选项。
+
+## 3. 文件识别
+
+识别以扩展名、而非 MIME 或文件内容为准,扩展名不区分大小写。
+
+| 类型 `kind` | 扩展名 |
+| --- | --- |
+| `image` | `png` `jpg` `jpeg` `webp` `tiff` `tif` `bmp` `gif` `heic` `heif` `avif` |
+| `video` | `mp4` `mov` `m4v` `avi` `mkv` `webm` |
+| `audio` | `mp3` `wav` `m4a` `aiff` `aif` `caf` `flac` `ogg` |
+| `pdf` | `pdf` |
+| `document` | `docx` `doc` `rtf` `odt` `txt` `md` `html` `htm` `pages` |
+| `presentation` | `pptx` `ppt` `key` |
+| `spreadsheet` | `xlsx` `xls` `xlsb` `ods` `csv` `tsv` `numbers` |
+| `other` | 其他扩展名 |
+
+被识别但当前不解析:`.doc`、`.pages`、`.ppt`、`.key`、`.numbers`。这些文件
+只提供编辑/打开/显示,不提供格式扇区。
+
+## 4. 输出命名与位置
+
+### 4.1 普通结果
+
+默认写到源文件同目录:
+
+```text
+.
+ 2.
+ 3.
+```
+
+示例:`report (compressed).pdf`、`photo (rotated) 2.png`。
+
+设置选择「统一收集到一个文件夹」时,结果写入该目录,但唯一命名规则不变。
+
+### 4.2 页面文件夹
+
+PDF 转图片和 PDF 拆分写出:
+
+```text
+ pages/Page 001.png
+ pages/Page 002.png
+ pages 2/Page 001.png
+```
+
+页号至少三位;已存在的页面文件夹不会被复用。
+
+### 4.3 截图与录屏
+
+- 截图:`Shift-YYYYMMDD-HHMMSS.png`。同一秒内的第二张为
+  `Shift-YYYYMMDD-HHMMSS 2.png`。
+- 录屏:由当前后端决定扩展名,写入录屏输出目录;唯一命名规则相同。
+- 共享接收:写入文件输出目录;冲突时使用 ` 2.`。
+
+## 5. 转换与工具
+
+### 5.1 格式转换
+
+可见目标必须同时满足:
+
+- 文件类型支持该目标;
+- 目标不等于源格式;
+- 后端存在处理器。
+
+当前转换目标与引擎以 README 的「Conversions / 格式转换」表为准。缺少外部
+依赖时,动作返回可操作错误,说明缺少哪个工具;界面不得提前展示一个明知
+不会工作的扇区。
+
+### 5.2 工具
+
+工具包含压缩、移除元数据、旋转、翻转、黑白、50%、裁剪、抠图、合并、拆分、
+提取文字、720p、静音、截帧、提取音频、单声道、纯文本和 OCR。
+
+批量规则:
+
+- 2 张以上图片可选择合并为 PDF;
+- 2 个以上 PDF 可选择合并为一个 PDF;
+- 其他工具逐文件执行。
+
+### 5.3 取消与失败
+
+- 在圆环中心或环外松手不执行动作。
+- 一个批次中的失败必须报告;不得把失败结果计入成功数量。
+- 转换成功后的结果写入历史库。
+
+## 6. 截图与录屏
+
+### 6.1 截图
+
+1. 截图前检查屏幕录制权限;拒绝时返回可操作错误,不打开黑色遮罩。
+2. 区域截图为光标所在显示器的冻结画面。
+3. 全屏截图直接抓取光标所在显示器,不显示遮罩。
+4. 取消截图恢复先前隐藏的 Shift 窗口。
+5. 截图成功后显示结果卡片;卡片创建失败时打开编辑器。
+
+### 6.2 录屏
+
+- macOS:`screencapture -v`,可带麦克风。
+- Windows/Linux:FFmpeg 系后端,可选择 15/24/30 fps。
+- Wayland:区域录屏使用 `wf-recorder`;X11 使用 FFmpeg `x11grab`。
+- 界面只显示后端实现的选项;停止后必须完成文件收尾。
+
+## 7. 编辑器
+
+### 7.1 图片
+
+- 以原始像素尺寸加载到画布。
+- 标注工具:矩形、箭头、高亮、打码、马赛克、模糊、序号、图章、裁剪、文字。
+- 每种工具使用固定颜色和线宽;不提供逐条标注的样式面板。
+- 保存和复制都在画布副本上合成;源文件不变。
+- 图片编辑器提供 OCR、复制文字、钉图和保存副本。
+- 环形菜单的「编辑 / 标注 / 打码 / 加背景」只负责打开图片编辑器;当前不会
+  预选具体工具,用户需在编辑器工具栏中选择。
+
+### 7.2 文本
+
+- `txt` `md` `csv` `tsv` `html` `htm` 以只读 `
` 预览。
+- 不提供就地编辑;可复制、另存为、打开或显示源文件。
+- 文本读取失败时显示错误状态,不留空白预览。
+
+### 7.3 视频与其他文件
+
+- 视频使用 webview 播放器。
+- 其他可识别文件显示文件图标和打开入口。
+
+### 7.4 编辑器资源上限
+
+| 数据 | 上限 | 超限行为 |
+| --- | --- | --- |
+| 非普通文件路径 | — | `errNotAFile` |
+| 文本预览 | 8 MiB | `errTextTooLarge` |
+| 图片文件 | 64 MiB | `errImageTooLarge` |
+| 图片像素 | 40,000,000 | `errImageTooLarge` |
+| 编辑后 data URL | 128 MiB | `errEditDataTooLarge` |
+| OCR 结果写文本 | 8 MiB | `errTextTooLarge` |
+
+列表预览在图片超限时省略缩略图,但文件本身仍可被识别和操作。
+
+## 8. 历史库
+
+- 由 Rust 写入 `app_data_dir/history.json`。
+- 容量上限 300 条;置顶条目不因容量或清理被移除。
+- 不存在的未置顶文件在整理时被丢弃。
+- 截图、转换结果和收到的文件都进入同一历史库。
+- 新条目通过 `history://changed` 与 `app://file-result` 广播。
+- 清除历史不删除磁盘上的文件。
+
+## 9. OCR
+
+- 图片:单张识别,实时显示进度,结果可复制或写入编辑器。
+- PDF:逐页渲染后识别,合并文本写出 `(OCR).txt`;临时页面目录随后删除。
+- 语言:英文与简体中文,使用本地 Tesseract WASM 和模型。
+- OCR 过程中不得下载语言包。
+
+## 10. 局域网发送
+
+### 10.1 发现
+
+- UDP 组播:`239.255.77.88:47888`。
+- 另外使用定向广播、受限广播和受限 `/24` 单播扫描。
+- 信标包含实例 id、机器名、平台和 TCP 接收端口。
+- 15 秒未刷新即过期。
+- 可见 peer 上限 256;达到上限时先清理过期 peer,仍满则拒绝新 id。
+
+### 10.2 传输
+
+1. 发送端先写 `SHSF`、头部长度和 JSON 头。
+2. 接收端弹出确认卡片,默认 45 秒超时。
+3. 用户拒绝、关闭卡片或超时:不传文件字节。
+4. 用户接受:先回 1 字节同意,再传输正文。
+5. 接收端只写临时 `.shift-part`,按头部声明字节数收齐后原子重命名。
+6. 发送端只发送声明大小;源文件变短则失败,源文件变长不会多发送。
+7. 接收端完整落盘后才回确认;发送端看到确认才报告成功。
+
+多文件批次使用同一批 id,一次确认后在 120 秒窗口内自动接收同批文件。
+
+### 10.3 用户反馈
+
+- 接收成功显示发送者与文件名。
+- 接收过程中断显示 `shareReceiveFailed`,不再静默。
+- 旧版本缺失批次字段时按单文件处理。
+
+## 11. 更新
+
+### 11.1 清单
+
+- `schema` 必须为 1;缺失、0 或更高版本均拒绝。
+- 版本使用 semver,预发布版本低于同号正式版。
+- 文件不得包含路径分隔符,只允许 ASCII 字母、数字、`.`、`-`、`_`。
+- `size` 必须大于 0;SHA256 必须为 64 位十六进制。
+- 清单响应上限 256 KiB。
+
+### 11.2 下载与安装
+
+1. 下载到临时更新目录。
+2. 校验文件是普通文件、字节数精确一致、SHA256 匹配。
+3. 安装前再次运行相同校验;失败删除安装包。
+4. 只有状态为 `ready` 才允许安装。
+5. macOS 挂载 DMG 并替换 `.app`;Windows 运行同一 NSIS 安装器。
+6. 辅助脚本等待当前进程退出,路径通过进程参数传递。
+7. 失败时尽量重新打开旧版本,不留下“应用已退出且未安装”的状态。
+8. 丢弃下载会删除实际安装包并清空更新状态。
+
+## 12. 错误与国际化
+
+- 界面需要稳定识别的后端失败以代号返回;新增代号必须同时提供 `en` 与 `zh`。
+  无法稳定映射的第三方诊断原样显示。
+- `translate()` 查不到 key 时原样显示,保留第三方工具诊断信息。
+- 单次注册的监听器使用 `tLive()`,避免切换语言后仍显示旧语言。
+- 不可用控件使用 disabled 状态和视觉禁用态,不伪装成可点击。
+
+## 13. 平台能力
+
+| 能力 | macOS | Windows | Linux |
+| --- | --- | --- | --- |
+| 发布安装包 | 通用 DMG | x64 NSIS | 无 |
+| 全局拖拽唤起圆环 | AppKit 桥 | Win32 轮询 + 原生拖放 | 无;仅主窗口选择 |
+| 截图/录屏 | 原生 | GDI + FFmpeg | `grim` / `wf-recorder` / FFmpeg |
+| 文档渲染 | AppKit/PDFKit | Pandoc + Poppler | Pandoc + Poppler |
+| 局域网分享 | 支持 | 支持(单实例监听) | 支持 |
+| 更新 | 支持 | 支持 | 能检查,但通道无产物 |
+
+Linux 是构建目标,不是已发布产品。
+
+## 14. 验收标准
+
+功能改动至少满足:
+
+```bash
+pnpm check
+pnpm test
+pnpm build
+cd src-tauri
+cargo fmt --check
+cargo test --lib
+cargo clippy --all-targets -- -D warnings
+cd ..
+git diff --check
+```
+
+涉及以下行为时还需手工验收:
+
+- 跨机器发现与接收:两台真实设备,允许本地网络/防火墙;
+- 截图/录屏权限:macOS 屏幕录制、麦克风、本地网络;
+- Windows 拖拽与安装器:真实 Windows,不以交叉编译代替;
+- 更新:安装上一版本,执行一次应用内升级;
+- Linux 截图/录屏:Wayland 与 X11 各一次。
+
+若某项无法执行,应明确记录“未验证”,不得根据编译通过推断运行时通过。
+
diff --git a/scripts/publish-release.sh b/scripts/publish-release.sh
index 4146228..81b7051 100755
--- a/scripts/publish-release.sh
+++ b/scripts/publish-release.sh
@@ -31,15 +31,34 @@ NO_PUSH=0
 
 while [ $# -gt 0 ]; do
   case "$1" in
-    --notes) NOTES_FILE="$2"; shift 2 ;;
+    --notes|--key|--branch)
+      if [ "$#" -lt 2 ] || [ -z "${2:-}" ]; then
+        echo "$1 needs a value" >&2
+        exit 2
+      fi
+      case "$1" in
+        --notes) NOTES_FILE="$2" ;;
+        --key) KEY_FILE="$2" ;;
+        --branch) BRANCH="$2" ;;
+      esac
+      shift 2
+      ;;
     --dry-run) DRY_RUN=1; shift ;;
     --no-push) NO_PUSH=1; shift ;;
-    --branch) BRANCH="$2"; shift 2 ;;
-    --key) KEY_FILE="$2"; shift 2 ;;
     *) echo "unknown argument: $1" >&2; exit 2 ;;
   esac
 done
 
+[ -n "$BRANCH" ] || { echo "--branch cannot be empty" >&2; exit 2; }
+[ -z "$NOTES_FILE" ] || [ -f "$NOTES_FILE" ] || {
+  echo "notes file not found: $NOTES_FILE" >&2
+  exit 2
+}
+[ -z "$KEY_FILE" ] || [ -f "$KEY_FILE" ] || {
+  echo "release key not found: $KEY_FILE" >&2
+  exit 2
+}
+
 VERSION=$(python3 -c "import json;print(json.load(open('src-tauri/tauri.conf.json'))['version'])")
 PLAN=$(mktemp /tmp/shift-release-plan.XXXXXX)
 INDEX_FILE=$(mktemp /tmp/shift-release-index.XXXXXX)
diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs
index de73db6..7c74bda 100644
--- a/src-tauri/src/capture.rs
+++ b/src-tauri/src/capture.rs
@@ -131,8 +131,13 @@ fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result dimensions,
+        Err(error) => {
+            let _ = fs::remove_file(&output);
+            return Err(format!("Invalid capture: {error}"));
+        }
+    };
     Ok(CaptureSource {
         path: output.to_string_lossy().to_string(),
         width,
@@ -421,14 +426,18 @@ pub fn crop_session(
     }
     let cropped = image.crop_imm(x, y, crop_width.min(width - x), crop_height.min(height - y));
     let directory = screenshot_directory(app)?;
-    let name = format!("Shift-{}.png", Local::now().format("%Y%m%d-%H%M%S"));
-    let output = directory.join(name);
+    let stem = format!("Shift-{}", Local::now().format("%Y%m%d-%H%M%S"));
+    let output = unique_capture_path(&directory, &stem)?;
     cropped
         .save_with_format(&output, image::ImageFormat::Png)
         .map_err(|error| error.to_string())?;
     Ok(output)
 }
 
+fn unique_capture_path(directory: &Path, stem: &str) -> Result {
+    crate::files::unique_output_in(Path::new(stem), Some(directory), "", "png")
+}
+
 pub fn dismiss_capture(app: &AppHandle) {
     close_overlay(app, true)
 }
@@ -606,3 +615,23 @@ fn open_screen_recording_settings_sync() -> Result<(), String> {
         Err("Screen Recording settings are macOS-specific.".into())
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn two_captures_in_the_same_second_do_not_overwrite() {
+        let directory =
+            std::env::temp_dir().join(format!("shift-capture-name-{}", uuid::Uuid::new_v4()));
+        fs::create_dir_all(&directory).unwrap();
+        let stem = "Shift-20260101-120000";
+        let first = unique_capture_path(&directory, stem).unwrap();
+        fs::write(&first, b"first").unwrap();
+        let second = unique_capture_path(&directory, stem).unwrap();
+        assert_ne!(first, second);
+        assert_eq!(second.file_name().unwrap(), "Shift-20260101-120000 2.png");
+        assert_eq!(fs::read(&first).unwrap(), b"first");
+        fs::remove_dir_all(directory).ok();
+    }
+}
diff --git a/src-tauri/src/files.rs b/src-tauri/src/files.rs
index e6d78ad..60c6a74 100644
--- a/src-tauri/src/files.rs
+++ b/src-tauri/src/files.rs
@@ -1,7 +1,7 @@
 use std::{
     ffi::OsStr,
     fs::{self, File},
-    io::{BufReader, Cursor, Write},
+    io::{BufReader, Cursor, Read, Write},
     path::{Path, PathBuf},
     process::Command,
     sync::OnceLock,
@@ -31,6 +31,13 @@ const DOCUMENT_EXTENSIONS: &[&str] = &[
 ];
 const PRESENTATION_EXTENSIONS: &[&str] = &["pptx", "ppt", "key"];
 const SPREADSHEET_EXTENSIONS: &[&str] = &["xlsx", "xls", "xlsb", "ods", "csv", "tsv", "numbers"];
+/// Inline editor data crosses the Tauri IPC boundary twice (read and save), so a
+/// file that is unusually large for an image is refused before it is base64
+/// encoded or decoded a second time.
+const MAX_EDITOR_IMAGE_BYTES: u64 = 64 * 1024 * 1024;
+const MAX_EDITOR_IMAGE_PIXELS: u64 = 40_000_000;
+const MAX_EDITOR_DATA_URL_BYTES: usize = 128 * 1024 * 1024;
+const MAX_EDITOR_TEXT_BYTES: u64 = 8 * 1024 * 1024;
 
 fn extension_of(path: &Path) -> String {
     path.extension()
@@ -77,7 +84,16 @@ fn preview_for(path: &Path, ext: &str) -> Option<(String, Option, Option MAX_EDITOR_IMAGE_PIXELS {
+        return None;
+    }
+    let image = image::load_from_memory(&bytes).ok()?;
     let (width, height) = image.dimensions();
     let preview = image.thumbnail(520, 520);
     let mut png = Vec::new();
@@ -91,6 +107,34 @@ fn preview_for(path: &Path, ext: &str) -> Option<(String, Option, Option Result, String> {
+    let metadata = fs::metadata(path).map_err(|error| error.to_string())?;
+    if !metadata.is_file() {
+        return Err("errNotAFile".into());
+    }
+    if metadata.len() > limit {
+        return Err(too_large.into());
+    }
+
+    let file = File::open(path).map_err(|error| error.to_string())?;
+    let metadata = file.metadata().map_err(|error| error.to_string())?;
+    if !metadata.is_file() {
+        return Err("errNotAFile".into());
+    }
+    if metadata.len() > limit {
+        return Err(too_large.into());
+    }
+
+    let mut bytes = Vec::new();
+    file.take(limit + 1)
+        .read_to_end(&mut bytes)
+        .map_err(|error| error.to_string())?;
+    if bytes.len() as u64 > limit {
+        return Err(too_large.into());
+    }
+    Ok(bytes)
+}
+
 pub fn inspect_paths(paths: &[String]) -> Result, String> {
     let mut files = Vec::new();
     for raw_path in paths {
@@ -2014,11 +2058,14 @@ pub async fn open_file(path: String) -> Result<(), String> {
 
 #[tauri::command]
 pub async fn read_text_file(path: String) -> Result {
-    tauri::async_runtime::spawn_blocking(move || {
-        fs::read_to_string(path).map_err(|error| error.to_string())
-    })
-    .await
-    .map_err(|error| error.to_string())?
+    tauri::async_runtime::spawn_blocking(move || read_text_file_in(Path::new(&path)))
+        .await
+        .map_err(|error| error.to_string())?
+}
+
+fn read_text_file_in(path: &Path) -> Result {
+    let bytes = read_file_limited(path, MAX_EDITOR_TEXT_BYTES, "errTextTooLarge")?;
+    String::from_utf8(bytes).map_err(|error| error.to_string())
 }
 
 /// Return image bytes as a data URL. The editor draws this into a canvas and
@@ -2036,7 +2083,17 @@ fn image_data_url(path: &Path) -> Result {
     if !IMAGE_EXTENSIONS.contains(&ext.as_str()) {
         return Err("This file is not a supported image.".to_string());
     }
-    let bytes = fs::read(path).map_err(|error| error.to_string())?;
+    let bytes = read_file_limited(path, MAX_EDITOR_IMAGE_BYTES, "errImageTooLarge")?;
+    if image::ImageReader::new(Cursor::new(&bytes))
+        .with_guessed_format()
+        .ok()
+        .and_then(|reader| reader.into_dimensions().ok())
+        .is_some_and(|(width, height)| {
+            u64::from(width) * u64::from(height) > MAX_EDITOR_IMAGE_PIXELS
+        })
+    {
+        return Err("errImageTooLarge".into());
+    }
     Ok(format!(
         "data:{};base64,{}",
         image_mime(&ext),
@@ -2070,6 +2127,9 @@ fn save_image_data_in(
     suffix: Option<&str>,
     output_dir: Option<&Path>,
 ) -> Result {
+    if data_url.len() > MAX_EDITOR_DATA_URL_BYTES {
+        return Err("errEditDataTooLarge".into());
+    }
     let encoded = data_url
         .split_once(',')
         .map(|(_, value)| value)
@@ -2077,6 +2137,19 @@ fn save_image_data_in(
     let bytes = STANDARD
         .decode(encoded)
         .map_err(|error| format!("Invalid image data: {error}"))?;
+    if bytes.len() as u64 > MAX_EDITOR_IMAGE_BYTES {
+        return Err("errEditDataTooLarge".into());
+    }
+    if image::ImageReader::new(Cursor::new(&bytes))
+        .with_guessed_format()
+        .ok()
+        .and_then(|reader| reader.into_dimensions().ok())
+        .is_some_and(|(width, height)| {
+            u64::from(width) * u64::from(height) > MAX_EDITOR_IMAGE_PIXELS
+        })
+    {
+        return Err("errImageTooLarge".into());
+    }
     let image = image::load_from_memory(&bytes)
         .map_err(|error| format!("Could not decode edited image: {error}"))?;
     let input = Path::new(source);
@@ -2155,6 +2228,9 @@ fn save_text_near_in(
     suffix: Option<&str>,
     output_dir: Option<&Path>,
 ) -> Result {
+    if text.len() as u64 > MAX_EDITOR_TEXT_BYTES {
+        return Err("errTextTooLarge".into());
+    }
     let input = Path::new(source);
     let output = unique_output_in(input, output_dir, suffix.unwrap_or(" (OCR)"), "txt")?;
     fs::write(&output, text).map_err(|error| describe_write_error(&output, error))?;
@@ -2351,6 +2427,26 @@ mod tests {
         fs::remove_dir_all(dir).unwrap();
     }
 
+    #[test]
+    fn editor_reads_are_bounded_before_they_allocate() {
+        let dir = scratch_dir();
+        let text = dir.join("too-large.txt");
+        File::create(&text)
+            .unwrap()
+            .set_len(MAX_EDITOR_TEXT_BYTES + 1)
+            .unwrap();
+        assert_eq!(read_text_file_in(&text).unwrap_err(), "errTextTooLarge");
+        assert_eq!(read_text_file_in(&dir).unwrap_err(), "errNotAFile");
+
+        let image = dir.join("too-large.png");
+        File::create(&image)
+            .unwrap()
+            .set_len(MAX_EDITOR_IMAGE_BYTES + 1)
+            .unwrap();
+        assert_eq!(image_data_url(&image).unwrap_err(), "errImageTooLarge");
+        fs::remove_dir_all(dir).unwrap();
+    }
+
     #[test]
     fn saves_edited_image_data() {
         let dir = scratch_dir();
diff --git a/src-tauri/src/recording.rs b/src-tauri/src/recording.rs
index d85048e..13a07c5 100644
--- a/src-tauri/src/recording.rs
+++ b/src-tauri/src/recording.rs
@@ -120,11 +120,17 @@ fn recording_directory(app: &AppHandle) -> Result {
 }
 
 fn output_path(app: &AppHandle, extension: &str) -> Result {
-    Ok(recording_directory(app)?.join(format!(
-        "Shift Recording {}.{}",
-        Local::now().format("%Y-%m-%d %H.%M.%S"),
-        extension
-    )))
+    let directory = recording_directory(app)?;
+    let stem = format!(
+        "Shift Recording {}",
+        Local::now().format("%Y-%m-%d %H.%M.%S")
+    );
+    unique_recording_path(&directory, &stem, extension)
+}
+
+fn unique_recording_path(directory: &Path, stem: &str, extension: &str) -> Result {
+    let input = directory.join(format!("{stem}.{extension}"));
+    crate::files::unique_output_in(&input, Some(directory), "", extension)
 }
 
 fn start_process(
@@ -489,6 +495,24 @@ mod tests {
         assert_eq!(x11_geometry(®ion), "801x600+13+30");
     }
 
+    #[test]
+    fn recordings_from_the_same_second_do_not_overwrite() {
+        let directory =
+            std::env::temp_dir().join(format!("shift-recording-name-{}", uuid::Uuid::new_v4()));
+        fs::create_dir_all(&directory).unwrap();
+        let stem = "Shift Recording 2026-01-01 12.00.00";
+        let first = unique_recording_path(&directory, stem, "mov").unwrap();
+        fs::write(&first, b"first").unwrap();
+        let second = unique_recording_path(&directory, stem, "mov").unwrap();
+        assert_ne!(first, second);
+        assert_eq!(
+            second.file_name().unwrap(),
+            "Shift Recording 2026-01-01 12.00.00 2.mov"
+        );
+        assert_eq!(fs::read(&first).unwrap(), b"first");
+        fs::remove_dir_all(directory).ok();
+    }
+
     #[test]
     fn stops_recording_process_cleanly() {
         let child = Command::new("sleep")
diff --git a/src-tauri/src/share.rs b/src-tauri/src/share.rs
index 22b67cf..a1a185d 100644
--- a/src-tauri/src/share.rs
+++ b/src-tauri/src/share.rs
@@ -44,6 +44,9 @@ const BATCH_WINDOW: Duration = Duration::from_secs(120);
 const SOCKET_LIFETIME: Duration = Duration::from_secs(30);
 /// Starts every transfer so a stray connection cannot corrupt a file.
 const MAGIC: &[u8; 4] = b"SHSF";
+/// A local-network attacker can mint unlimited beacon ids. Keep the visible peer
+/// table bounded so discovery cannot grow without limit.
+const MAX_PEERS: usize = 256;
 
 #[derive(Debug, Clone, Serialize)]
 #[serde(rename_all = "camelCase")]
@@ -198,6 +201,12 @@ impl ShareState {
             return false;
         };
         let known = peers.contains_key(&beacon.id);
+        if !known && peers.len() >= MAX_PEERS {
+            peers.retain(|_, peer| peer.seen.elapsed() < PEER_TIMEOUT);
+            if peers.len() >= MAX_PEERS {
+                return false;
+            }
+        }
         peers.insert(
             beacon.id.clone(),
             KnownPeer {
@@ -1098,19 +1107,7 @@ where
         .set_read_timeout(Some(Duration::from_secs(120)))
         .map_err(|error| error.to_string())?;
     let mut file = fs::File::open(source).map_err(|error| error.to_string())?;
-    let mut buffer = vec![0u8; 64 * 1024];
-    let mut sent = 0u64;
-    while sent < header.size {
-        let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
-        if read == 0 {
-            break;
-        }
-        stream
-            .write_all(&buffer[..read])
-            .map_err(|error| error.to_string())?;
-        sent += read as u64;
-        on_progress(sent);
-    }
+    copy_file_body(&mut file, stream, header.size, &mut on_progress)?;
     stream.flush().map_err(|error| error.to_string())?;
 
     let mut ack = [0u8; 1];
@@ -1123,6 +1120,34 @@ where
     Ok(())
 }
 
+/// Copy exactly the number of bytes the header promised. Reading a fixed-size
+/// chunk would let a source file that grew after `metadata` push extra bytes into
+/// the stream, where the sender would mistake them for the receiver's ack.
+fn copy_file_body(
+    reader: &mut R,
+    writer: &mut W,
+    size: u64,
+    mut on_progress: P,
+) -> Result<(), String> {
+    let mut buffer = vec![0u8; 64 * 1024];
+    let mut sent = 0u64;
+    while sent < size {
+        let want = std::cmp::min(buffer.len() as u64, size - sent) as usize;
+        let read = reader
+            .read(&mut buffer[..want])
+            .map_err(|error| error.to_string())?;
+        if read == 0 {
+            return Err("The source file changed while it was being sent.".into());
+        }
+        writer
+            .write_all(&buffer[..read])
+            .map_err(|error| error.to_string())?;
+        sent += read as u64;
+        on_progress(sent);
+    }
+    Ok(())
+}
+
 /// Ask the user about an incoming file and block until they answer. The notice
 /// window owns the buttons; this thread only waits, so a decision still arrives
 /// correctly when Shift has been idle in the menu bar.
@@ -1226,10 +1251,19 @@ fn receive_file(app: &AppHandle, mut stream: TcpStream) -> Result<(), String> {
         .map_err(|error| error.to_string())?;
     let directory = crate::settings::received_dir(app)?;
     let mut last_emit = Instant::now();
-    let (header, target) = accept_transfer(
+    let approved = std::cell::Cell::new(false);
+    let current = std::cell::RefCell::new(None);
+    let result = accept_transfer(
         &mut stream,
         &directory,
-        |header| await_decision(app, header),
+        |header| {
+            *current.borrow_mut() = Some(header.clone());
+            let answer = await_decision(app, header);
+            if answer.is_ok() {
+                approved.set(true);
+            }
+            answer
+        },
         |header, received| {
             // Throttle progress so a fast LAN link does not flood the UI.
             if last_emit.elapsed() < Duration::from_millis(120) {
@@ -1249,7 +1283,30 @@ fn receive_file(app: &AppHandle, mut stream: TcpStream) -> Result<(), String> {
                 },
             );
         },
-    )?;
+    );
+    let (header, target) = match result {
+        Ok(value) => value,
+        Err(error) => {
+            if approved.get() {
+                if let Some(header) = current.borrow().clone() {
+                    emit_transfer(
+                        app,
+                        TransferEvent {
+                            transfer_id: header.transfer_id,
+                            file_name: safe_name(&header.file_name)
+                                .unwrap_or_else(|| "file".into()),
+                            peer_name: header.peer_name,
+                            sent: 0,
+                            total: header.size,
+                            state: "error".into(),
+                            path: None,
+                        },
+                    );
+                }
+            }
+            return Err(error);
+        }
+    };
     let name = safe_name(&header.file_name).unwrap_or_else(|| "file".into());
     let path = target.to_string_lossy().to_string();
     // Read the batch fields before the event below moves out of `header`.
@@ -1522,6 +1579,27 @@ mod tests {
         assert!(state.peers_visible().is_empty());
     }
 
+    #[test]
+    fn the_peer_table_stops_accepting_new_ids_at_its_limit() {
+        let state = ShareState::default();
+        let address = SocketAddr::from(([192, 168, 1, 20], 50_000));
+        for index in 0..MAX_PEERS {
+            let mut peer = beacon();
+            peer.id = format!("peer-{index}");
+            assert!(state.note(&peer, address));
+        }
+
+        let mut extra = beacon();
+        extra.id = "one-too-many".into();
+        assert!(!state.note(&extra, address));
+        assert_eq!(state.peers_visible().len(), MAX_PEERS);
+
+        let mut known = beacon();
+        known.id = "peer-0".into();
+        assert!(!state.note(&known, address), "refreshing is not a new peer");
+        assert_eq!(state.peer("peer-0").unwrap().1.port(), 51_000);
+    }
+
     #[test]
     fn peer_timeout_covers_a_legacy_peers_reply_cycle() {
         // Versions before the reply field answer once, forget this host after nine
@@ -1795,6 +1873,73 @@ mod tests {
         fs::remove_dir_all(&dir).ok();
     }
 
+    #[test]
+    fn bytes_after_the_declared_size_never_cross_the_wire() {
+        let dir = std::env::temp_dir().join(format!("shift-long-{}", uuid::Uuid::new_v4()));
+        let source = dir.join("grew.bin");
+        fs::create_dir_all(&dir).unwrap();
+        let body: Vec = (0..130_000u32).map(|index| (index % 251) as u8).collect();
+        fs::write(&source, &body).unwrap();
+
+        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+        let address = listener.local_addr().unwrap();
+        let inbound = dir.join("in");
+        let received_dir = inbound.clone();
+        let receiver = thread::spawn(move || {
+            let (mut stream, _) = listener.accept().unwrap();
+            accept_transfer(&mut stream, &received_dir, |_| Ok(()), |_, _| {})
+        });
+
+        let mut stream = TcpStream::connect(address).unwrap();
+        let header = TransferHeader {
+            file_name: "grew.bin".into(),
+            size: 1_000,
+            peer_name: "Mini".into(),
+            transfer_id: "t-long".into(),
+            ..Default::default()
+        };
+        push_file(&mut stream, &source, &header, |_| {}).unwrap();
+        drop(stream);
+
+        let (_, target) = receiver.join().unwrap().unwrap();
+        assert_eq!(fs::read(target).unwrap(), body[..1_000]);
+        assert_eq!(fs::read_dir(&inbound).unwrap().count(), 1);
+        fs::remove_dir_all(&dir).ok();
+    }
+
+    #[test]
+    fn a_source_that_shrinks_is_refused_without_a_partial_file() {
+        let dir = std::env::temp_dir().join(format!("shift-short-{}", uuid::Uuid::new_v4()));
+        let source = dir.join("shrank.bin");
+        fs::create_dir_all(&dir).unwrap();
+        fs::write(&source, b"only some of the promised bytes").unwrap();
+
+        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+        let address = listener.local_addr().unwrap();
+        let inbound = dir.join("in");
+        let received_dir = inbound.clone();
+        let receiver = thread::spawn(move || {
+            let (mut stream, _) = listener.accept().unwrap();
+            accept_transfer(&mut stream, &received_dir, |_| Ok(()), |_, _| {})
+        });
+
+        let mut stream = TcpStream::connect(address).unwrap();
+        let header = TransferHeader {
+            file_name: "shrank.bin".into(),
+            size: 1_000,
+            peer_name: "Mini".into(),
+            transfer_id: "t-short".into(),
+            ..Default::default()
+        };
+        let error = push_file(&mut stream, &source, &header, |_| {}).unwrap_err();
+        assert!(error.contains("source file changed"), "{error}");
+        drop(stream);
+
+        assert!(receiver.join().unwrap().is_err());
+        assert_eq!(fs::read_dir(&inbound).unwrap().count(), 0);
+        fs::remove_dir_all(&dir).ok();
+    }
+
     #[test]
     fn a_truncated_stream_is_rejected_without_a_partial_file() {
         let dir = std::env::temp_dir().join(format!("shift-cut-{}", uuid::Uuid::new_v4()));
diff --git a/src-tauri/src/update.rs b/src-tauri/src/update.rs
index b580c47..d8176fc 100644
--- a/src-tauri/src/update.rs
+++ b/src-tauri/src/update.rs
@@ -19,6 +19,7 @@
 
 use std::{
     collections::BTreeMap,
+    ffi::OsStr,
     fs,
     io::Read,
     path::{Path, PathBuf},
@@ -53,6 +54,9 @@ const BAKED_PUBLIC_KEY: &str = match option_env!("SHIFT_UPDATE_PUBKEY") {
 const FETCH_TIMEOUT: Duration = Duration::from_secs(20);
 /// Installers are tens of megabytes, so the download gets far longer than a probe.
 const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(600);
+/// The manifest is a small JSON document. Refuse an oversized response instead of
+/// letting a broken or hostile feed exhaust memory.
+const MAX_MANIFEST_BYTES: u64 = 256 * 1024;
 /// Startup probes are throttled to this interval so a menu bar app does not reach
 /// the network on every launch.
 pub const CHECK_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
@@ -307,13 +311,19 @@ fn parse_manifest(text: &str) -> Result {
     if manifest.version.trim().is_empty() {
         return Err("The manifest carries no version.".into());
     }
-    if manifest.schema > SUPPORTED_SCHEMA {
+    if manifest.schema != SUPPORTED_SCHEMA {
         return Err(format!(
-            "Manifest schema {} is newer than this build understands.",
+            "Manifest schema {} is not supported by this build (expected {SUPPORTED_SCHEMA}).",
             manifest.schema
         ));
     }
     for artifact in manifest.artifacts.values() {
+        if safe_artifact_name(&artifact.file).is_none() {
+            return Err("The manifest names an unsafe artifact file.".into());
+        }
+        if artifact.size == 0 {
+            return Err(format!("{} has no usable size.", artifact.file));
+        }
         if !is_sha256_hex(&artifact.sha256) {
             return Err(format!("{} has no usable SHA256.", artifact.file));
         }
@@ -325,14 +335,70 @@ fn is_sha256_hex(value: &str) -> bool {
     value.len() == 64 && value.chars().all(|character| character.is_ascii_hexdigit())
 }
 
+/// A manifest may only name a file that belongs directly in the release
+/// directory. Installer names produced by the release scripts are ASCII, so a
+/// strict basename allow-list also keeps path separators, shell metacharacters
+/// and Windows device names out of download and handoff paths.
+fn safe_artifact_name(value: &str) -> Option<&str> {
+    let name = value.trim();
+    if name.is_empty()
+        || value != name
+        || name == "."
+        || name == ".."
+        || name.ends_with('.')
+        || name.len() > 200
+        || !name
+            .bytes()
+            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
+    {
+        return None;
+    }
+    let stem = name
+        .split('.')
+        .next()
+        .unwrap_or_default()
+        .to_ascii_uppercase();
+    let reserved = matches!(
+        stem.as_str(),
+        "CON"
+            | "PRN"
+            | "AUX"
+            | "NUL"
+            | "COM1"
+            | "COM2"
+            | "COM3"
+            | "COM4"
+            | "COM5"
+            | "COM6"
+            | "COM7"
+            | "COM8"
+            | "COM9"
+            | "LPT1"
+            | "LPT2"
+            | "LPT3"
+            | "LPT4"
+            | "LPT5"
+            | "LPT6"
+            | "LPT7"
+            | "LPT8"
+            | "LPT9"
+    );
+    if reserved {
+        return None;
+    }
+    Some(name)
+}
+
 /// The forge path for one artifact sits next to the manifest.
 fn raw_asset_url(file: &str) -> Result {
     let base = manifest_url();
     if base.is_empty() {
         return Err("No update feed is configured.".into());
     }
+    let file = safe_artifact_name(file)
+        .ok_or_else(|| "The manifest names an unsafe artifact file.".to_string())?;
     let directory = base.rsplit_once('/').map(|(head, _)| head).unwrap_or(&base);
-    Ok(format!("{directory}/{}", file.trim_start_matches('/')))
+    Ok(format!("{directory}/{file}"))
 }
 
 /// One transport for both the manifest and the installers, using the platform's own
@@ -445,9 +511,19 @@ fn fetch_text(url: &str) -> Result {
         uuid::Uuid::new_v4()
     ));
     download(url, &target, FETCH_TIMEOUT, || {})?;
-    let text = fs::read_to_string(&target).map_err(|error| error.to_string())?;
+    let result = (|| {
+        let size = fs::metadata(&target)
+            .map_err(|error| error.to_string())?
+            .len();
+        if size > MAX_MANIFEST_BYTES {
+            return Err(format!(
+                "The update manifest is too large ({size} bytes; limit {MAX_MANIFEST_BYTES})."
+            ));
+        }
+        fs::read_to_string(&target).map_err(|error| error.to_string())
+    })();
     let _ = fs::remove_file(&target);
-    Ok(text)
+    result
 }
 
 fn download_directory() -> PathBuf {
@@ -468,6 +544,29 @@ pub fn sha256_of(path: &Path) -> Result {
     Ok(hex::encode(digest.finalize()))
 }
 
+/// Re-check the exact properties that made a download installable. This runs
+/// again at install time because the file lives in a writable temp directory
+/// between download and handoff.
+fn verify_downloaded_artifact(path: &Path, size: u64, sha256: &str) -> Result<(), String> {
+    let metadata = fs::symlink_metadata(path).map_err(|error| error.to_string())?;
+    if !metadata.file_type().is_file() {
+        return Err("The downloaded update is not a regular file.".into());
+    }
+    if metadata.len() != size {
+        return Err(format!(
+            "The downloaded update changed size: expected {size} bytes, found {}.",
+            metadata.len()
+        ));
+    }
+    let actual = sha256_of(path)?;
+    if !actual.eq_ignore_ascii_case(sha256) {
+        return Err(format!(
+            "The downloaded update changed after verification: expected {sha256}, found {actual}."
+        ));
+    }
+    Ok(())
+}
+
 fn emit_progress(app: &AppHandle, downloaded: u64, total: u64, state: &str) {
     let _ = app.emit(
         "update://progress",
@@ -636,7 +735,9 @@ pub async fn update_download(app: AppHandle) -> Result {
                 manifest.version
             )
         })?;
-    let target = download_directory().join(&artifact.file);
+    let file_name = safe_artifact_name(&artifact.file)
+        .ok_or_else(|| "The manifest names an unsafe artifact file.".to_string())?;
+    let target = download_directory().join(file_name);
     let reporter = app.clone();
     let expected = artifact.sha256.clone();
     let total = artifact.size;
@@ -656,21 +757,12 @@ pub async fn update_download(app: AppHandle) -> Result {
             },
         )?;
         let actual_size = fs::metadata(&target).map(|meta| meta.len()).unwrap_or(0);
-        if total > 0 && actual_size != total {
-            let _ = fs::remove_file(&target);
-            return Err(format!(
-                "Expected {} bytes but received {actual_size}. The download was discarded.",
-                total
-            ));
-        }
         emit_progress(&reporter, actual_size, total, "verifying");
-        let actual = sha256_of(&target)?;
-        if !actual.eq_ignore_ascii_case(&expected) {
+        if let Err(error) = verify_downloaded_artifact(&target, total, &expected) {
             let _ = fs::remove_file(&target);
-            return Err(format!(
-                "SHA256 mismatch: expected {expected}, got {actual}. The download was discarded."
-            ));
+            return Err(format!("{error} The download was discarded."));
         }
+        let actual = sha256_of(&target)?;
         let mut status = status_for(
             &manifest,
             Some(target.clone()),
@@ -699,7 +791,6 @@ fn bundle_path(exe: &Path) -> Option {
     Some(bundle.to_path_buf())
 }
 
-#[cfg(target_os = "macos")]
 #[cfg(target_os = "macos")]
 /// Whether this copy can be replaced where it sits. The handoff moves the bundle
 /// aside and moves a new one in, which needs write access to the folder holding it
@@ -721,24 +812,25 @@ fn can_replace(bundle: &Path) -> bool {
     }
 }
 
-#[cfg(target_os = "macos")]
 /// The macOS handoff: wait for this process to quit, then replace the bundle with
 /// the one inside the downloaded disk image and open the new copy. Written as a
 /// script because the copy can only happen once this process is gone.
 ///
 /// Every failure path ends with `open` on the bundle, so a handoff that cannot
 /// finish leaves the previous copy running rather than leaving Shift closed.
-fn macos_handoff(pid: u32, image: &Path, bundle: &Path, log: &Path) -> String {
-    format!(
-        r#"#!/bin/sh
-pid="{pid}"
-image="{image}"
-bundle="{bundle}"
-log="{log}"
+#[cfg(target_os = "macos")]
+const MACOS_HANDOFF_SCRIPT: &str = r#"#!/bin/sh
+if [ "$#" -ne 4 ]; then
+  exit 2
+fi
+pid="$1"
+image="$2"
+bundle="$3"
+log="$4"
 while kill -0 "$pid" 2>/dev/null; do sleep 0.2; done
-mount="$TMPDIR/Shift Updates/mount.$$"
-[ -n "$TMPDIR" ] || mount="/tmp/Shift Updates/mount.$$"
-mkdir -p "${{mount%/*}}"
+mount_base="${TMPDIR:-/tmp}"
+mount="$mount_base/Shift Updates/mount.$$"
+mkdir -p "${mount%/*}"
 if ! /usr/bin/hdiutil attach -nobrowse -readonly -mountpoint "$mount" "$image" >>"$log" 2>&1; then
   echo "mount failed" >>"$log"
   /usr/bin/open "$bundle"
@@ -764,25 +856,20 @@ fi
 [ "$status" -eq 0 ] || echo "handoff failed; reopening the previous copy" >>"$log"
 /usr/bin/open "$bundle"
 exit "$status"
-"#,
-        pid = pid,
-        image = image.display(),
-        bundle = bundle.display(),
-        log = log.display(),
-    )
-}
+"#;
 
 /// The Windows handoff: wait for this process to exit, run the installer silently,
 /// then start the copy the installer wrote. The installer refuses to overwrite a
 /// running EXE, so the wait is the whole point of the script.
 #[cfg(target_os = "windows")]
-fn windows_handoff(pid: u32, installer: &Path, log: &Path) -> String {
-    format!(
-        r#"@echo off
-setlocal EnableExtensions
-set "WAIT_FOR={pid}"
-set "INSTALLER={installer}"
-set "LOG={log}"
+const WINDOWS_HANDOFF_SCRIPT: &str = r#"@echo off
+setlocal EnableExtensions DisableDelayedExpansion
+set "WAIT_FOR=%~1"
+set "INSTALLER=%~2"
+set "LOG=%~3"
+if not defined WAIT_FOR exit /b 2
+if not defined INSTALLER exit /b 2
+if not defined LOG exit /b 2
 set /a TRIES=0
 :waitloop
 tasklist /FI "PID eq %WAIT_FOR%" /NH /FO CSV 2>nul | find /I "shift.exe" >nul || goto install
@@ -795,16 +882,12 @@ for /f "tokens=1,2,*" %%a in ('reg query "HKCU\Software\Shift" /v InstallDirecto
 start /wait "" "%INSTALLER%" /S
 if errorlevel 1 echo installer exited with %ERRORLEVEL% >> "%LOG%"
 if exist "%TARGET%" start "" "%TARGET%"
-"#,
-        pid = pid,
-        installer = installer.display(),
-        log = log.display(),
-    )
-}
+"#;
 
 /// Write a handoff script and start it detached, so it is still alive when this
-/// process has exited. `name` is the file in the update directory.
-fn spawn_handoff(name: &str, script: &str) -> Result<(), String> {
+/// process has exited. Paths travel as process arguments rather than interpolated
+/// script text, so folder names cannot change the helper's script source.
+fn spawn_handoff(name: &str, script: &str, arguments: &[&OsStr]) -> Result<(), String> {
     let path = download_directory().join(name);
     if let Some(parent) = path.parent() {
         fs::create_dir_all(parent).map_err(|error| error.to_string())?;
@@ -816,11 +899,11 @@ fn spawn_handoff(name: &str, script: &str) -> Result<(), String> {
     #[cfg(target_os = "windows")]
     let mut command = crate::process::command("cmd.exe");
     #[cfg(target_os = "windows")]
-    command.args(["/D", "/C", &path.to_string_lossy().to_string()]);
+    command.args(["/D", "/C"]).arg(&path).args(arguments);
     #[cfg(not(target_os = "windows"))]
     let mut command = crate::process::command("/bin/sh");
     #[cfg(not(target_os = "windows"))]
-    command.arg(&path);
+    command.arg(&path).args(arguments);
     command
         .spawn()
         .map_err(|error| format!("Could not start the updater: {error}"))?;
@@ -843,18 +926,34 @@ fn quit_for_update(app: &AppHandle) {
 /// system the way a double-click would.
 #[tauri::command]
 pub async fn update_install(app: AppHandle) -> Result {
-    let path = app
+    let status = app
         .state::()
         .status
         .lock()
         .ok()
-        .and_then(|guard| guard.as_ref().and_then(|status| status.path.clone()))
+        .and_then(|guard| guard.clone())
+        .filter(|status| status.state == "ready")
         .ok_or_else(|| "Download and verify an update first.".to_string())?;
+    let path = status
+        .path
+        .clone()
+        .ok_or_else(|| "Download and verify an update first.".to_string())?;
+    let expected_sha256 = status.sha256.clone();
+    let expected_size = status.size;
     tauri::async_runtime::spawn_blocking(move || {
         let artifact = PathBuf::from(&path);
         let log = download_directory().join("handoff.log");
         let pid = std::process::id();
 
+        if let Err(error) =
+            verify_downloaded_artifact(&artifact, expected_size, &expected_sha256)
+        {
+            let _ = fs::remove_file(&artifact);
+            return Err(format!(
+                "The downloaded update no longer matches the manifest. It was discarded: {error}"
+            ));
+        }
+
         // A bundled macOS build replaces itself; `open`ing the disk image instead
         // would leave the user dragging a window they were told to stop expecting.
         #[cfg(target_os = "macos")]
@@ -871,16 +970,33 @@ pub async fn update_install(app: AppHandle) -> Result {
                         "Shift cannot replace itself in {folder}. Open the downloaded installer to update by hand."
                     ));
                 }
-                let script = macos_handoff(pid, &artifact, &bundle, &log);
-                spawn_handoff("Shift-update.sh", &script)?;
+                let pid_argument = pid.to_string();
+                spawn_handoff(
+                    "Shift-update.sh",
+                    MACOS_HANDOFF_SCRIPT,
+                    &[
+                        OsStr::new(&pid_argument),
+                        artifact.as_os_str(),
+                        bundle.as_os_str(),
+                        log.as_os_str(),
+                    ],
+                )?;
                 quit_for_update(&app);
                 return Ok(path);
             }
         }
         #[cfg(target_os = "windows")]
         {
-            let script = windows_handoff(pid, &artifact, &log);
-            spawn_handoff("Shift-update.cmd", &script)?;
+            let pid_argument = pid.to_string();
+            spawn_handoff(
+                "Shift-update.cmd",
+                WINDOWS_HANDOFF_SCRIPT,
+                &[
+                    OsStr::new(&pid_argument),
+                    artifact.as_os_str(),
+                    log.as_os_str(),
+                ],
+            )?;
             quit_for_update(&app);
             return Ok(path);
         }
@@ -931,8 +1047,24 @@ pub async fn update_install(app: AppHandle) -> Result {
 /// Drop the downloaded installer so the next check starts clean.
 #[tauri::command]
 pub fn update_clear(app: AppHandle) {
-    if let Ok(mut guard) = app.state::().status.lock() {
-        *guard = None;
+    let downloaded = app
+        .state::()
+        .status
+        .lock()
+        .ok()
+        .and_then(|mut guard| guard.take())
+        .and_then(|status| status.path);
+    if let Some(path) = downloaded {
+        let artifact = PathBuf::from(path);
+        let is_download = artifact.parent() == Some(download_directory().as_path())
+            && artifact
+                .file_name()
+                .and_then(OsStr::to_str)
+                .and_then(safe_artifact_name)
+                .is_some();
+        if is_download {
+            let _ = fs::remove_file(artifact);
+        }
     }
     let _ = app.emit("update://status", serde_json::Value::Null);
 }
@@ -1180,9 +1312,47 @@ mod tests {
     }
 
     #[test]
-    fn a_newer_schema_is_not_guessed_at() {
-        let error = parse_manifest(&SAMPLE.replace("\"schema\": 1", "\"schema\": 9")).unwrap_err();
-        assert!(error.contains("schema"), "{error}");
+    fn artifact_names_stay_inside_the_release_directory() {
+        for safe in ["Shift.dmg", "Shift-Setup_0.2.0.exe", "a.b_c-1.AppImage"] {
+            assert_eq!(safe_artifact_name(safe), Some(safe));
+        }
+        for unsafe_name in [
+            "",
+            ".",
+            "..",
+            "../Shift.dmg",
+            "folder/Shift.dmg",
+            r"folder\Shift.dmg",
+            "/tmp/Shift.dmg",
+            "Shift dmg",
+            "Shift.dmg;rm",
+            "Shift'$(whoami)",
+            "Shift%TEMP%.dmg",
+            "Shift\n.dmg",
+            " Shift.dmg",
+            "Shift.dmg ",
+            "Shift.dmg.",
+            "CON",
+            "NUL.txt",
+            "COM1",
+            "LPT9.log",
+        ] {
+            assert_eq!(safe_artifact_name(unsafe_name), None, "{unsafe_name:?}");
+        }
+        let traversal = SAMPLE.replace("Shift-macOS-universal.dmg", "../Shift.dmg");
+        assert!(parse_manifest(&traversal).is_err());
+        let empty = SAMPLE.replace("\"size\": 55113440", "\"size\": 0");
+        assert!(parse_manifest(&empty).is_err());
+    }
+
+    #[test]
+    fn only_the_supported_schema_is_accepted() {
+        for schema in [0, 2, 9] {
+            let manifest = SAMPLE.replace("\"schema\": 1", &format!("\"schema\": {schema}"));
+            let error = parse_manifest(&manifest).unwrap_err();
+            assert!(error.contains("schema"), "{error}");
+        }
+        assert!(parse_manifest(SAMPLE).is_ok());
     }
 
     #[test]
@@ -1205,13 +1375,12 @@ mod tests {
     #[cfg(target_os = "macos")]
     #[test]
     fn the_macos_handoff_waits_for_this_process_before_it_touches_the_bundle() {
-        let script = macos_handoff(
-            4242,
-            Path::new("/tmp/Shift Updates/Shift.dmg"),
-            Path::new("/Applications/Shift.app"),
-            Path::new("/tmp/handoff.log"),
+        let script = MACOS_HANDOFF_SCRIPT;
+        assert!(
+            script.contains("pid=\"$1\""),
+            "the script lost its pid argument"
         );
-        assert!(script.contains("pid=\"4242\""), "the script lost our pid");
+        assert!(!script.contains("/Applications/Shift.app"));
         // The wait must come before any write to the bundle, or the copy races the
         // running executable.
         let wait = script.find("kill -0 \"$pid\"").expect("no wait loop");
@@ -1229,15 +1398,12 @@ mod tests {
     #[cfg(target_os = "windows")]
     #[test]
     fn the_windows_handoff_installs_only_after_this_process_is_gone() {
-        let script = windows_handoff(
-            4242,
-            Path::new("C:\\Users\\me\\Shift-Setup.exe"),
-            Path::new("C:\\tmp\\handoff.log"),
-        );
+        let script = WINDOWS_HANDOFF_SCRIPT;
         assert!(
-            script.contains("set \"WAIT_FOR=4242\""),
+            script.contains("set \"WAIT_FOR=%~1\""),
             "the script lost our pid"
         );
+        assert!(!script.contains("C:\\Users\\me\\Shift-Setup.exe"));
         let wait = script
             .find("tasklist /FI \"PID eq %WAIT_FOR%\"")
             .expect("no wait");
@@ -1320,6 +1486,26 @@ mod tests {
         let _ = fs::remove_file(&path);
     }
 
+    #[test]
+    fn an_installer_changed_after_download_is_refused() {
+        let path = std::env::temp_dir().join(format!("shift-verify-{}", uuid::Uuid::new_v4()));
+        fs::write(&path, b"installer bytes").unwrap();
+        let digest = sha256_of(&path).unwrap();
+        verify_downloaded_artifact(&path, 15, &digest).unwrap();
+
+        let changed = b"installer bytes plus a change";
+        fs::write(&path, changed).unwrap();
+        let error = verify_downloaded_artifact(&path, 15, &digest).unwrap_err();
+        assert!(
+            error.contains("size") || error.contains("changed"),
+            "{error}"
+        );
+
+        let error = verify_downloaded_artifact(&path, changed.len() as u64, &digest).unwrap_err();
+        assert!(error.contains("changed after verification"), "{error}");
+        let _ = fs::remove_file(path);
+    }
+
     /// The whole channel, offline: a manifest and its artifact served out of a
     /// temporary directory over `file://`, exercising fetch, parse, download, size
     /// check and hash comparison exactly as they run against the real forge.
diff --git a/src/components/Editor.tsx b/src/components/Editor.tsx
index c68b2a1..e03a659 100644
--- a/src/components/Editor.tsx
+++ b/src/components/Editor.tsx
@@ -38,6 +38,7 @@ export function Editor() {
   const [copied, setCopied] = useState(null);
   const [copiedIsError, setCopiedIsError] = useState(false);
   const [textContent, setTextContent] = useState("");
+  const [textError, setTextError] = useState(null);
   const copyTimer = useRef(null);
   const sessionRef = useRef(null);
 
@@ -50,6 +51,7 @@ export function Editor() {
     setOcrProgress(0);
     setOcrStatus("");
     setTextContent("");
+    setTextError(null);
     // Anything opened for editing belongs in the library. Rust assigns the kind
     // and timestamp, so the editor does not classify the file a second time.
     void history.record([next.path]).catch(() => undefined);
@@ -81,9 +83,14 @@ export function Editor() {
   useEffect(() => {
     if (session?.kind !== "text") return;
     let cancelled = false;
-    void api.readTextFile(session.path).then((text) => {
-      if (!cancelled) setTextContent(text);
-    });
+    void api
+      .readTextFile(session.path)
+      .then((text) => {
+        if (!cancelled) setTextContent(text);
+      })
+      .catch((error) => {
+        if (!cancelled) setTextError(messageFrom(error));
+      });
     return () => {
       cancelled = true;
     };
@@ -253,6 +260,11 @@ export function Editor() {
             />
           ) : session.kind === "video" ? (