Skip to content

Visual Studio Code, rebuilt in Rust

Rust

docs: add area documents, a router and a glossary for agents (#106)

Artur Rok96bd20a7fecf
diff --git a/.claude b/.claude
new file mode 120000
index 00000000000..c0ca4685663
--- /dev/null
+++ b/.claude
@@ -0,0 +1 @@
+.agents
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
index d2495b58a55..4c79c859a5b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,6 +2,14 @@
Vscrs is a Rust/GPUI port of VS Code 1.148.0 (README.md). Upstream VS Code is a checkout in `upstream/` (`VSCODE_SRC`), never edited: the upstream changes the port needs are `port/patches/*.patch` and `port/product.json`.
+The owner's message wins over this file. This file wins over a skill, a document and a comment in the code: where two of them disagree, follow the higher one and name the disagreement in the report.
+
+Three ways to lose work or leak it:
+
+- Never edit `upstream/`. A change the port needs there is a file in `port/patches`.
+- Never touch another session's worktree (`git worktree list`), and never push to `main` unless the owner asked for it.
+- The repository is public: no credentials, personal data, host names or internal links in code, commits, pull requests or docs. Name a secret by its variable, never by its value.
+
The port's state, about 1 MB: search it with `rg`, never read it whole.
- The ledger, the one source of truth. `port/ledger.md`, the open work: decisions, milestones with their "done when" checks and status; `port/ledger/done.md` the closed work. `port/ledger/units/<area>.md`, the Units table: one row per upstream unit with its milestone, status, open gaps and the narrowest check that proves it (`rg -n '^\| workbench/contrib/scm ' port/ledger/units`). A gap leaves its cell and an item turns `done` and moves to `done.md` in the commit that closes it; `bun port/tools/ledger-check.ts` checks the tables agree. A row that tracks a GitHub issue names it as `vscrs#N`; `bun port/tools/ledger-issues.ts` lists where the rows and the issues disagree.
@@ -10,7 +18,9 @@ The port's state, about 1 MB: search it with `rg`, never read it whole.
How the code is built, read before the first edit in an area:
- `ARCHITECTURE.md`: the crates, the processes, the path of a key and of a frame, the invariants. Read it before a change that crosses a module or adds one.
-- `docs/README.md`: the index of the area documents (workbench, editor, extension host, testing) and the list of areas that have none.
+- `docs/README.md`: the table from the code a change touches to the area document to read, the table of shared helpers to reuse before adding one, and the libraries that differ from the stock ones.
+- `docs/recipes.md`: the steps to start a task, close a gap, add a command, answer a host call, cover every surface and ship.
+- `GLOSSARY.md`: the port's own words (unit, gap, verified, lane, gate). Use them as defined, in reports, commits and test names.
- `docs/memory-safety.md`: read before a change to `unsafe` code, FFI, a raw pointer or a `Send`/`Sync` impl.
- `docs/performance.md`: read before a change to a `render`, `key_context`, a list row, tokenization or startup.
@@ -21,7 +31,6 @@ Rules:
- Run tests with `port/tools/cargo-test [-p <crate>] <filter>`, and every other cargo command as `cargo gc <cmd>` (bounds `native/target`): only failures and summaries, and a filter that matches nothing fails.
- Markdown: one paragraph per source line, no hard wrapping.
- UI labels use title-style capitalization, as upstream's.
-- The repository is public: no credentials, personal data or internal links in code, commits or docs.
- Remove temporary files and scripts made while working.
- `unsafe` only in `app` and `exthost`, each block under a `// SAFETY:` comment that names the fact it relies on, its file a row of the inventory in `docs/memory-safety.md`. The check: `cargo gc clippy -p app -p exthost --all-targets -- -A clippy::all`.
- Speed and memory are the product: the goal is the fastest editor there is, ahead of Zed on every benchmark and lowest in RAM, with every VS Code feature (`docs/performance.md`). Every change picks the design that costs the least time and memory; one that makes a measured number worse names it and why in the report.
@@ -45,4 +54,4 @@ Open every pull request through `.agents/skills/pr/SKILL.md`, the repo's own `pr
### Domain docs
-Single-context: `GLOSSARY.md` at the root, created by `/domain-modeling` when the first term is resolved; decisions in `port/notes.md`. See `docs/agents/domain.md`.
+Single-context: `GLOSSARY.md` at the root, extended by `/domain-modeling` when a term is resolved; decisions in `port/notes.md`. See `docs/agents/domain.md`.
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 723b53b21a9..7adbe41ba65 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -35,11 +35,11 @@ Extensions start more processes (git, language servers). Those are children of t
### Crates
-`native/` is one Cargo workspace (`native/Cargo.toml`) with nine crates in `native/crates`. The dependencies point one way: `app` uses all, `exthost` uses `config`, `files`, `search` and `storage`, `search` uses `files`, `files` uses `config`.
+`native/` is one Cargo workspace (`native/Cargo.toml`) with the crates of `native/crates`. The dependencies point one way: `app` uses all, `exthost` uses `config`, `files`, `search` and `storage`, `search` uses `files`, `files` uses `config`.
| Crate | Owns | Upstream |
|---|---|---|
-| `app` | The binary: the workbench, the editor, the terminal, the webviews, the platform glue. 832 of the 934 Rust files. | `src/vs/workbench`, `src/vs/editor`, `src/vs/code`, parts of `src/vs/platform` |
+| `app` | The binary: the workbench, the editor, the terminal, the webviews, the platform glue. | `src/vs/workbench`, `src/vs/editor`, `src/vs/code`, parts of `src/vs/platform` |
| `exthost` | The parent side of the extension host: process start, framing, RPC, the session, the MainThread calls that need no window, extension scan, install and gallery, HTTP requests. | `src/vs/workbench/services/extensions`, `src/vs/workbench/api/browser`, `src/vs/platform/extensionManagement` |
| `config` | Settings: the registry, the layers and their merge, JSON with comments, JSON edits, variables, workspaces. | `src/vs/platform/configuration`, `src/vs/base/common/json.ts` |
| `files` | The file service over providers, the disk, text encodings, globs, the file watcher, file operations with undo. | `src/vs/platform/files`, `src/vs/base/common/glob.ts` |
@@ -47,11 +47,12 @@ Extensions start more processes (git, language servers). Those are children of t
| `storage` | SQLite key-value storage, `storage.json` state, user data profiles. | `src/vs/base/parts/storage`, `src/vs/platform/state`, `src/vs/platform/userDataProfile` |
| `textmate` | TextMate grammars and tokenization on Oniguruma, token colors. | the `vscode-textmate` package |
| `diff` | The line and character diff. | `src/vs/editor/common/diff` |
+| `ghostty_vt` | The terminal screen: libghostty-vt behind the types the terminal draws from. | none, it takes the place of xterm.js |
| `pixeldiff` | Screenshot comparison for the port's tools. | none |
**Invariant:** only `app` depends on GPUI. The other crates are plain data and I/O, so their tests need no window and run in milliseconds.
-**Invariant:** `config`, `diff`, `files`, `pixeldiff`, `search`, `storage` and `textmate` contain no `unsafe` code. `#![forbid(unsafe_code)]` at each crate root enforces it. See [docs/memory-safety.md](docs/memory-safety.md).
+**Invariant:** `config`, `diff`, `files`, `ghostty_vt`, `pixeldiff`, `search`, `storage` and `textmate` contain no `unsafe` code. `#![forbid(unsafe_code)]` at each crate root enforces it. See [docs/memory-safety.md](docs/memory-safety.md).
GPUI comes from gpui-fast, a Zed GPUI fork with Retained Mode (a frame redraws only the views that called `cx.notify()`), pinned by commit in `native/Cargo.toml`. The GPUI crates the port changes are copies in `native/vendor/gpui-fast` (`native/vendor/README.md`). Retained Mode keeps a view's last frame until it notifies, so a change to what a view draws must notify it; a value measured in paint and read by the next render draws again through `part_view::redraw_after_frame` (`port/notes.md`, "GPUI on gpui-fast"). Do not edit `native/vendor` for a feature: a change there is a change to the framework, and `git log -p native/vendor` must show only such changes.
@@ -84,7 +85,7 @@ To find the code of an upstream folder, search the Units table of the ledger: `r
### Platform glue per OS
-Code that calls an OS API sits in a file named after the OS, beside the portable module that uses it: `app/src/power/macos.rs` and `app/src/power/windows.rs` under `app/src/power.rs`, and the same for `app/src/dialog`, `app/src/file_dialog`, `app/src/keyboard_layout`, `app/src/policy`, `app/src/system_wide_keybindings`, `app/src/webview` and `exthost/src/request`. `app/src/win32.rs` and `app/src/x11.rs` hold shared helpers. The portable module selects the file with `cfg(target_os)` and gives every OS the same functions.
+Code that calls an OS API sits in a file named after the OS, beside the portable module that uses it: `app/src/power/macos.rs` and `app/src/power/windows.rs` under `app/src/power.rs`, and the same for `app/src/file_dialog`, `app/src/keyboard_layout`, `app/src/policy`, `app/src/system_wide_keybindings`, `app/src/webview` and `exthost/src/request`. A module whose code for one OS is short keeps it inline: `app/src/dialog.rs` has files for Linux and Windows only, `exthost/src/main_thread_secret_state.rs` for Windows only. The pty is `app/src/terminal/pty.rs` on Unix and `app/src/terminal/pty/conpty.rs` on Windows. `app/src/win32.rs` and `app/src/x11.rs` hold shared helpers. [docs/platform.md](docs/platform.md) has the table of what lives where. The portable module selects the file with `cfg(target_os)` and gives every OS the same functions.
**Invariant:** `unsafe` code is allowed only in this glue: FFI to the OS, the pty and the web views. The full list is the inventory in [docs/memory-safety.md](docs/memory-safety.md). If a file outside the list contains `unsafe`, `port/tools/docs-check.ts` fails.
@@ -134,11 +135,11 @@ The host is upstream's extension host code, bundled by `port/tools/build-exthost
All user data is under `~/.vscrs` (`--user-data-dir` changes it), in upstream's layout, so a VS Code user data folder has the same shape.
- Settings. `config/src/registry.rs::Registry` holds every registered setting. `config/src/service.rs::Settings` holds the layers of one window (defaults, policy, user, workspace, folder) and merges them as upstream does (`config/src/configuration.rs::Configuration`). One `Arc<Mutex<Settings>>` per window is shared with the session thread. The workbench watches the settings files and reloads (`app/src/workbench/configuration.rs::watch_settings_files`).
-- Storage. `storage/src/lib.rs::Storage` is upstream's SQLite `state.vscdb` with a cache in front. A window has three: application (shared by all windows), profile and workspace. UI state uses upstream's storage keys, so the keys in a state database match VS Code's.
+- Storage. `storage/src/lib.rs::Storage` is upstream's SQLite `state.vscdb` with a cache in front. A window has three: application (one file for all windows, read by each window into its own cache), profile and workspace. UI state uses upstream's storage keys, so the keys in a state database match VS Code's.
- State file. `storage/src/state.rs::FileStorage` is `storage.json`: the windows of the last session and other state the app needs before a window exists.
- Profiles. `storage/src/profiles.rs::Profiles` and `app/src/user_data_profile.rs`.
- Dirty files. `app/src/backups.rs` writes working copy backups (hot exit). `app/src/workbench/backup_tracker.rs` restores them.
-- Keybindings. The defaults are generated tables per OS in `app/src/keybindings` (`port/tools/default-keybindings`). The user file is `keybindings.json` of the profile.
+- Keybindings. The defaults are generated tables in `app/src/keybindings` (`port/tools/default-keybindings`), one for macOS and one for Windows; Linux reads the macOS table until it has its own (`app/src/keybindings.rs::default_table`). The user file is `keybindings.json` of the profile.
- Secrets. `exthost/src/main_thread_secret_state.rs` stores them in the Keychain, the Secret Service or the Credential Manager.
**Invariant:** a lock on settings or storage is short and never held across an await or a call to the host. The session thread takes the same locks.
@@ -184,7 +185,7 @@ The tools in `port/tools` each start with a header that states their use. The ma
- Build inputs. The build needs the upstream checkout: `native/vscode_src.rs` resolves it for the build scripts. `app/build.rs` makes the NLS index from upstream's `localize` calls and renders the Dock icons. A few modules embed upstream files, and tests read upstream fixtures. A binary outside a package also reads the checkout at run time as its app root: `product.json`, icons and the built-in extensions.
- Build order. Compile upstream once, run `bun port/tools/build-exthost`, then `cargo gc build --release -p app`. `README.md` has the commands. The debug profile builds dependencies with optimization and the port's crates without (`native/Cargo.toml`).
- Packaging. `port/tools/package-app` makes the signed macOS app and its update files. `port/tools/package-linux` makes the Linux archive. `port/tools/app-files.ts` lists the files a package ships.
-- CI. `.github/workflows/ci.yml` runs the repository checks and every crate's tests on macOS and Linux for each push to `main` and each pull request (Windows, paused, by hand in `windows.yml`). `.github/workflows/linux.yml` and `.github/workflows/windows.yml` build a package by hand. A release is a manual step.
+- CI. `.github/workflows/ci.yml` runs the repository checks and every crate's tests on macOS and Linux for each push to `main` and each pull request (Windows, paused, by hand in `windows.yml`). By hand, `.github/workflows/linux.yml` builds a package, and `.github/workflows/windows.yml` builds the app and runs its tests without a package. A release is a manual step.
## Cross-cutting rules
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 120000
index 00000000000..47dc3e3d863
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/GLOSSARY.md b/GLOSSARY.md
new file mode 100644
index 00000000000..ad074e31561
--- /dev/null
+++ b/GLOSSARY.md
@@ -0,0 +1,125 @@
+# Vscrs
+
+The words the port gave its own parts and its own way of working. A VS Code word (part, view, contribution, extension host, context key) means what it means upstream and is not repeated here.
+
+## Language
+
+### The port and its measure
+
+**Upstream**:
+The VS Code source at the tag the port follows. It is the specification, and the port reads it and never edits it.
+_Avoid_: original, VS Code repo, vscode source
+
+**Reference**:
+A running VS Code of the **Upstream** version that the port is compared with: its pixels, its sizes, its API behavior.
+_Avoid_: original app, baseline, real VS Code
+
+**1:1**:
+The rule that a ported feature matches **Upstream** in behavior, look and tests. A difference is either a **Gap** or a **Decision**.
+_Avoid_: parity, compatible, close enough
+
+**Uplift**:
+The move of the port from one **Upstream** version to a newer one.
+_Avoid_: upgrade, bump, rebase
+
+### Tracking the work
+
+**Ledger**:
+The one source of truth for the state of the port: the Work table (open rows in `port/ledger.md`, closed ones in `port/ledger/done.md`) and the Units table (`port/ledger/units`).
+_Avoid_: tracker, roadmap, backlog
+
+**Notes**:
+The decisions, traps and measurements behind the **Ledger**, one section per **Milestone**. They take the place of ADRs.
+_Avoid_: changelog, wiki
+
+**Unit**:
+One folder or seam of **Upstream**, tracked as one row of the **Ledger**'s Units table.
+_Avoid_: module, feature, component
+
+**Milestone**:
+A numbered group of **Units** that ships one feature end to end. It is done only when each of its units is **Verified**, removed or not applicable.
+_Avoid_: phase, sprint, epic
+
+**Gap**:
+A known difference from **Upstream** in a **Unit**, written in the unit's row with a class and a size.
+_Avoid_: TODO, bug, missing feature
+
+**Class**:
+What kind of **Gap** it is, which says what closes it: 1 is stale, 2 is a platform limit, 3 is a behavior difference, and `scheduling` and `linux` name their own kind. A class 3 gap keeps its **Unit** from being **Verified**.
+_Avoid_: priority, severity
+
+**Ported**:
+The status of a **Unit** whose behavior is written and that still lists a **Gap**.
+_Avoid_: done, finished
+
+**Verified**:
+The status of a **Unit** whose **Narrowest check** passes and that has no open class 3 **Gap**.
+_Avoid_: done, complete, tested
+
+**Narrowest check**:
+The smallest test filter, tool run or fixture that can fail on one **Unit**. It is the evidence of the unit's row.
+_Avoid_: full suite, test plan, smoke test
+
+**Decision**:
+A choice of the owner, recorded in the **Ledger** or the **Notes**. A deliberate difference from **Upstream** is always one.
+_Avoid_: ADR, assumption, default
+
+**Accepted platform difference**:
+A class 2 **Gap** that the owner accepted with one line in the **Notes**, because the OS or the framework cannot give what **Upstream** has.
+_Avoid_: known issue, won't fix
+
+### The shape of the code
+
+**Model**:
+The plain data and functions of one feature, with no knowledge of the window that shows it.
+_Avoid_: service, store, controller
+
+**Workbench**:
+The single owner of all state of one window. Upstream's services are its fields and methods.
+_Avoid_: app state, window controller, root component
+
+**Part view**:
+The cached drawing of one workbench part, drawn again only when that part is notified.
+_Avoid_: component, widget, panel
+
+**Session**:
+The thread that owns the connection of one window to its extension host and answers the calls that need no window.
+_Avoid_: host thread, RPC thread, connection
+
+**Host sync**:
+The one ordered queue through which the **Workbench** tells the extension host about state and asks it for answers.
+_Avoid_: channel, bridge, bus
+
+**Platform glue**:
+The code that calls an OS API, in a file named after the OS beside the portable module that uses it. It is the only place for `unsafe` code.
+_Avoid_: native code, bindings, shim
+
+**Hot path**:
+Code that runs for each frame, each key or each scroll event.
+_Avoid_: critical path, performance-sensitive code
+
+### Checking a change
+
+**Studio**:
+The build machine. Every build, test and GUI run happens there, not on a laptop.
+_Avoid_: CI, server, remote
+
+**Lane**:
+A desktop on the **Studio** that one GUI tool holds while it runs, because an app that opens a window takes the focus.
+_Avoid_: slot, queue, runner
+
+**Pixel check**:
+A comparison of one still window of the port with the same window of the **Reference**.
+_Avoid_: screenshot test, visual regression test
+
+**Paired run**:
+One step file driven through the port and the **Reference**, for a state that only input reaches.
+_Avoid_: e2e test, UI test
+
+**Gate**:
+A check with a fixed limit that fails on a performance regression.
+_Avoid_: benchmark (a measurement without a limit), perf test
+
+**Budget**:
+The measured value of a whole-app metric that a **Gate** holds the port to.
+_Avoid_: target, goal, threshold
diff --git a/docs/README.md b/docs/README.md
index cf5fca7770a..141939430c6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -2,31 +2,106 @@
[ARCHITECTURE.md](../ARCHITECTURE.md) is the map of the whole project. Read it first. Each file here goes one level deeper into one area, in the same style: what is where, why, the invariants, and what not to do. A file cites code as a path plus a symbol. If a cited path or symbol is gone, `bun port/tools/docs-check.ts` fails.
-The state of the work, per upstream folder, is not here. It is in `port/ledger.md` and `port/ledger/`, with the decisions and measurements in `port/notes.md`.
+The state of the work, per upstream folder, is not here. It is in `port/ledger.md` and `port/ledger/`, with the decisions and measurements in `port/notes.md`. The words the port uses for its own parts are in [GLOSSARY.md](../GLOSSARY.md).
-## What exists
+## Change touches, read
-| File | Area |
+Find the row of the code you are about to change and read its file before the first edit. A change that crosses two rows reads both.
+
+| The change touches | Read |
+|---|---|
+| A step that is the same in every area: start a task, close a gap, add a command, answer a host call, ship | [recipes.md](recipes.md) |
+| `app/src/workbench.rs`, `app/src/workbench`: layout, parts, views, editor groups, keys, commands, context keys, menus, lists | [workbench.md](workbench.md) |
+| `app/src/editor.rs`, `app/src/editor`, `app/src/syntax.rs`, `textmate`, `diff`: the model, cursors, edits, tokens, the editor view | [editor.md](editor.md) |
+| `exthost/src`, `app/src/host_sync.rs`, `app/src/main_thread_commands.rs`, `port/patches`: the host process, the protocol, a `MainThread*` method | [extension-host.md](extension-host.md) |
+| `exthost/src/extension_management.rs`, `exthost/src/gallery.rs`, `exthost/src/scan.rs`: scan, install, gallery, signatures, built-ins | [extensions.md](extensions.md) |
+| `app/src/terminal.rs`, `app/src/terminal`, `ghostty_vt`: the pty, the screen, shell integration | [terminal.md](terminal.md) |
+| `app/src/webview.rs`, `app/src/webview`: the native web view, its messages and resources | [webviews.md](webviews.md) |
+| `files`, `search`, `app/src/explorer.rs`: disk access, watchers, globs, ripgrep | [files-and-search.md](files-and-search.md) |
+| `config`, `storage`, `app/src/keybindings`, `app/src/user_data_profile.rs`: settings, storage, profiles, keybinding tables | [settings-and-storage.md](settings-and-storage.md) |
+| `app/src/debug.rs`, `app/src/debug`: debug sessions, adapters, breakpoints | [debug.md](debug.md) |
+| `app/src/testing.rs`, `app/src/testing_coverage.rs`: test controllers, runs, results, coverage | [test-explorer.md](test-explorer.md) |
+| `app/src/scm.rs`, `app/src/scm_history.rs`: source control providers, the SCM view, quick diff | [scm.md](scm.md) |
+| `app/src/notebook.rs`, `app/src/notebook`: notebook models, kernels, cell editors, outputs | [notebooks.md](notebooks.md) |
+| A file named after an OS, a `cfg(target_os)`, `app/src/win32.rs`, `app/src/x11.rs` | [platform.md](platform.md) |
+| `unsafe` code, FFI, a raw pointer, a `Send` or `Sync` impl | [memory-safety.md](memory-safety.md) |
+| A `render`, `key_context`, a list row, tokenization, startup | [performance.md](performance.md) |
+| A new view, a role or label, focus, an announcement, a High Contrast color | [accessibility.md](accessibility.md) |
+| `port/tools/package-app`, `app/src/update.rs`, `port/product.json`, `.github/workflows`: packages, signing, the update feed | [packaging.md](packaging.md) |
+| Any test, a comparison with the reference, CI | [testing.md](testing.md) |
+
+## Reuse before adding
+
+Before you write a helper, look for its home here. Each row is the one place the port already does the thing. A second copy drifts from the first.
+
+| Need | Home |
|---|---|
-| [workbench.md](workbench.md) | The `Workbench` entity, the grid of parts, part views, the path of a key and of a command, context keys. |
-| [editor.md](editor.md) | The text model, cursors and edits, tokenization, how the editor view draws, what runs per frame. |
-| [extension-host.md](extension-host.md) | The Node process, the protocol, the main-thread side in `exthost`, how state reaches the workbench. |
-| [testing.md](testing.md) | Where tests live, the GPUI harness, upstream's tests, the comparison tools against the reference app, CI. |
-| [memory-safety.md](memory-safety.md) | Where `unsafe` code is allowed, the inventory of every file that has it, how to add a block, and the checks that fail. |
-| [performance.md](performance.md) | The budgets, the rules for hot paths, how to measure, and the gates that fail on a regression. |
+| Theme color by upstream's key | `app/src/workbench.rs::color`, with a fallback `app/src/workbench.rs::foreground_or` |
+| Mix, fade or parse a color | `app/src/theme.rs::color_mix`, `app/src/theme.rs::parse_hex` |
+| Codicon or product icon | `app/src/workbench.rs::icon`, with its own style `app/src/workbench.rs::styled_icon` |
+| File or folder icon | `app/src/file_icons.rs::file_icon` |
+| Scroll state and scrollbar of a list | `app/src/workbench/list_scroll.rs::ListId`, `app/src/workbench/list_scroll.rs::list_scroll_layer` |
+| Scrollbar on a container that is not a list | `app/src/workbench/list_scroll.rs::scrollable` |
+| List math: reveal, sticky rows, indent guides | `app/src/list_tree.rs::reveal_scroll_top`, `app/src/list_tree.rs::sticky_rows`, `app/src/list_tree.rs::indent_guides` |
+| Tree indent and its guides | `app/src/workbench/explorer_actions.rs::tree_indent`, `app/src/workbench/tree_guides.rs::tree_guides_in_group` |
+| Text input | `app/src/workbench/input_box_view.rs::InputId`, drawn by `app/src/workbench/input_box_view.rs::input_text`; the model is `app/src/input_box.rs::InputBox` |
+| Toolbar or action bar item with focus and keys | `app/src/workbench/action_bar.rs::action_bar_item` |
+| Context menu | `app/src/workbench/context_menu.rs::show_context_menu`, from a list of actions `app/src/workbench/context_menu.rs::show_context_menu_actions` |
+| Hover or tooltip | `app/src/workbench/hover.rs::hover_target` with `app/src/workbench/hover.rs::HoverOptions` |
+| Label with match highlights | `app/src/workbench/quick_input_view.rs::highlighted_label` |
+| Markdown | `app/src/markdown.rs::parse`, then `app/src/workbench/markdown_view.rs::markdown_blocks` |
+| Sash and split sizes | `app/src/workbench/part_grid.rs::sash_highlight`, `app/src/split_view.rs::SplitView` |
+| Draw one part again, or draw again after paint | `app/src/workbench/part_view.rs::notify_editor_view`, `app/src/workbench/part_view.rs::redraw_after_frame` |
+| Register or run a command | `app/src/commands.rs::register`, `app/src/commands.rs::execute_command` |
+| Keybinding: parse, label, resolve | `app/src/keybindings.rs::parse_keybinding`, `app/src/keybindings.rs::label`, `app/src/keybindings.rs::Resolver` |
+| Context keys and a `when` clause | `app/src/workbench/keyboard.rs::key_context`, `app/src/contextkey.rs::Expr` |
+| Menu items of a menu id | `app/src/menus.rs::menu_actions` |
+| Quick pick or input box | `app/src/quick_input.rs::QuickInput`, shown by `app/src/workbench/quick_input_view.rs::show_quick_input` |
+| Notification | `app/src/workbench/notifications_view.rs::notify`, `app/src/workbench/notifications_view.rs::notify_error` |
+| Message dialog | `app/src/dialog.rs::show_message_box` |
+| File open or save dialog | `app/src/workbench/file_dialogs.rs::show_open_dialog`, `app/src/workbench/file_dialogs.rs::show_save_dialog` |
+| Open an editor | `app/src/workbench.rs::open_file` |
+| Open a link or a URI | `app/src/workbench/opener.rs::open_link` |
+| Status bar entry | `app/src/workbench/status_entries.rs::status_bar_entry` |
+| Read or write a setting | `app/src/workbench/explorer_actions.rs::setting`, `app/src/workbench/explorer_actions.rs::update_setting` ([settings-and-storage.md](settings-and-storage.md)) |
+| Stored UI state | `storage/src/lib.rs::Storage`, under upstream's key and scope |
+| Localized string | `app/src/nls.rs::localize_in` |
+| Call the extension host | `app/src/host_sync.rs::HostSync` ([extension-host.md](extension-host.md)) |
+| Edit text and tell the host | `app/src/editor/edit.rs::execute_edits`, then `app/src/workbench/model_events.rs::model_content_changed` |
+| Screen reader announcement, sound signal | `app/src/workbench/accessibility.rs::aria_alert`, `app/src/workbench/accessibility.rs::aria_status`, `app/src/workbench/accessibility.rs::play_signal` |
+| File operation with upstream's checks and errors | `files/src/lib.rs::FileSystem` ([files-and-search.md](files-and-search.md)) |
+| Watch a path | `files/src/watcher.rs::Watcher` |
+| Glob | `files/src/glob.rs::parse` |
+| Parse JSONC, or edit it and keep the comments | `config/src/json.rs::parse`, `config/src/json_edit.rs::set_property` |
+| URI | `app/src/uri.rs::Uri` |
+| Path label relative to the workspace | `app/src/quick_input.rs::path_label` |
+| Fuzzy match with highlight ranges | `app/src/filters.rs::matches_fuzzy`, `app/src/filters.rs::fuzzy_score` |
+| Diff of two texts | `diff/src/lib.rs::compute_diff` |
+
+No shared home yet: a generic button, a select box, a count badge, text measurement (`text_width`), the font constants, the UTF-16 helpers and `basename` each have a copy per feature. Use the copy nearest to your code and do not add one more. Joining the copies is a change of its own, not a side effect of a feature.
-## What is missing
+## Libraries that are not what you know
-These areas have only their section in ARCHITECTURE.md and the `//!` headers of their modules.
+A model knows the stock library. The port uses a fork, a pin or only a part of it.
-| Area | Start reading at | Note |
+| Library | What differs | Read |
|---|---|---|
-| Terminal | `app/src/terminal.rs` | The backend moves to libghostty-vt on another branch. Write this file after that lands. |
-| Webviews | `app/src/webview.rs` | |
-| Files, search and watchers | `files/src/lib.rs`, `search/src/text_search.rs` | |
-| Settings, storage, profiles, keybinding tables | `config/src/service.rs`, `storage/src/lib.rs` | |
-| Platform glue per OS | `app/src/power.rs` as a small example | Windows (M24) and Linux (M23) are in progress. |
-| Extensions: scan, install, gallery, signatures | `exthost/src/extension_management.rs`, `exthost/src/gallery.rs` | |
-| Debug, testing, SCM, notebooks | `app/src/debug.rs`, `app/src/testing.rs`, `app/src/scm.rs`, `app/src/notebook.rs` | |
-| Packaging, signing, the update feed | `port/tools/package-app`, `app/src/update.rs` | `port/notes.md` has the feed format. |
-| Accessibility | `app/src/workbench/accessibility.rs` | |
+| GPUI | gpui-fast, a fork with Retained Mode: a view keeps its last frame until it calls `cx.notify()`. The crates the port changes are copies in `native/vendor/gpui-fast`. The port does not use GPUI's actions and keymap. | ARCHITECTURE.md, "GPUI as the port uses it"; `native/vendor/README.md` |
+| Bun | The extension host runs on Bun 1.4.5, not Node. Each difference is a patch in `port/patches`, gated on `process.versions.bun`. `--node` is the control. | [extension-host.md](extension-host.md); `port/notes.md`, "Bun (1.4.5) as the extension host runtime" |
+| libghostty-vt | The terminal screen, from a fork of libghostty-rs pinned by commit in `native/crates/ghostty_vt/Cargo.toml`. It needs Zig 0.17 to build. Its key encoder is not used. | [terminal.md](terminal.md) |
+| Web views | No wry. Each OS has its own: WKWebView, WebKitGTK, WebView2. | [webviews.md](webviews.md) |
+| Oniguruma | TextMate grammars run on `onig`, not on the `regex` crate: the grammars need its syntax. | [editor.md](editor.md) |
+| SQLite | `rusqlite`, reading and writing upstream's `state.vscdb` format. | [settings-and-storage.md](settings-and-storage.md) |
+
+## Write a document
+
+- A document holds what the code cannot show: why, the invariant, the trap, the order of steps. A list of files that `ls` gives, or a sentence that repeats a function's name, does not belong.
+- Most changes need no change here. Before adding a paragraph, name what the next reader would get wrong without it; if reading the code answers that, leave it out.
+- When a documented decision or constraint changes, rewrite or remove its text. Never append a second account next to the old one.
+- Cite code as a path plus a symbol, as `app/src/commands.rs::register`. Never a line number: it is wrong after the next edit.
+- No state of the work: status, gaps and "not done yet" go to the ledger (`port/ledger.md`, `port/ledger/`), the story of a decision to `port/notes.md`.
+- No counts of files, lines or tests. They are stale in a week and nothing checks them.
+- One paragraph per source line. Short sentences. 50 to 110 lines for an area.
+- An area document ends with `## Check a change`: the narrowest commands that fail on a mistake in the area.
+- A new document gets a row in "Change touches, read". A new shared helper gets a row in "Reuse before adding".
+- Then run `bun port/tools/docs-check.ts`.
diff --git a/docs/accessibility.md b/docs/accessibility.md
new file mode 100644
index 00000000000..b5c14dde5b8
--- /dev/null
+++ b/docs/accessibility.md
@@ -0,0 +1,104 @@
+# Accessibility
+
+How the port talks to assistive technology and to a keyboard-only user: the roles, labels and state a view gives the OS accessibility tree, screen reader mode, the live region, the accessible view and accessibility help, the signals, focus and Tab rules, and High Contrast themes. The code is `app/src/workbench/accessibility.rs`, `app/src/workbench/accessible_view.rs`, `app/src/accessibility_signals.rs` and the `role` calls in the views. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md). Upstream is `src/vs/platform/accessibility`, `src/vs/workbench/contrib/accessibility`, `src/vs/platform/accessibilitySignal` and `src/vs/base/browser/ui/aria`.
+
+Accessibility is never cut for size or speed. The section "What a new view provides" is the rule for every new row, button and view.
+
+## What lives where
+
+- `app/src/workbench/accessibility.rs`: upstream's `IAccessibilityService` for the window. Screen reader detection, `is_screen_reader_optimized`, `is_motion_reduced`, the status entry and prompt, the live region, the editor's text node, and when a signal plays.
+- `app/src/workbench/accessible_view.rs`: the accessible view and accessibility help (accessibleView.ts, accessibleViewActions.ts): one read-only text widget, its providers, its toolbar and its own keys.
+- `app/src/accessibility_signals.rs`: 38 of the 39 signals of accessibilitySignalService.ts as data (`SIGNALS`; `dictationDisconnected` is missing), `is_enabled` (upstream's `checkEnabledState`) and `SoundPlayer`. No workbench state.
+- `app/src/workbench/inlay_hints_accessibility.rs`: Read Line with Inlay Hints. `app/src/terminal/accessible_buffer.rs`: the terminal buffer as lines for the accessible view.
+- `app/src/workbench/action_bar.rs`: keyboard navigation of every action bar (actionbar.ts). `app/src/workbench/part_navigation.rs`: F6 and Shift+F6 between parts (navigationActions.ts).
+- `app/src/workbench/themes.rs::host_color_scheme` and `app/src/theme.rs::ThemeKind`: High Contrast.
+
+## The accessibility tree
+
+GPUI builds an AccessKit tree from the elements of each frame and hands it to the platform adapter. The guide is the module header of `native/vendor/gpui-fast/crates/gpui/src/_accessibility.rs`.
+
+**Invariant:** an element is a node of the tree only when it has an id and a role: `div().id(..).role(Role::Button)`. An element with one of the two missing does not exist for VoiceOver, however it looks.
+
+**Invariant:** the id of a node stays the same across frames while it stands for the same thing. A screen reader takes a new id for a removed node plus an added one and announces it. Key a row by what it shows when the list reorders, and keep ids unique within a frame.
+
+Label and state go on the same element with the `aria_*` builders: `aria_label`, `aria_description`, `aria_level`, `aria_selected`, `aria_expanded`, `aria_toggled`, the numeric value builders. The Explorer row in `app/src/workbench.rs` (search `Role::TreeItem`) is the model for a tree row, the welcome page (`app/src/workbench/welcome_page.rs`) for buttons, check boxes, links and a progress bar.
+
+Lists and trees follow listWidget.ts: the container keeps the keyboard focus and the focused row carries `aria_active_descendant`. A row does not take the GPUI focus.
+
+An `on_click` handler also answers the AccessKit Click action. A handler on `on_mouse_down` does not: such an element adds `on_a11y_action(Action::Click, ..)` beside it, as the Manage button in `app/src/workbench.rs` does, and handles `ClickEvent::is_keyboard` for Enter and Space.
+
+**Trap:** `Role::GenericContainer` is filtered out of the tree. Use `Role::Group` for a container that must be a node, as `aria_live_region` does.
+
+Text has no element per line. `app/src/workbench/accessibility.rs::editor_accessibility` makes the editor one `MultilineTextInput` with the label of textAreaEditContext.ts and gives it synthetic children: `screen_reader_page` picks the page of lines around the selection (screenReaderUtils.ts `SimplePagedScreenReaderStrategy`, `editor.accessibilityPageSize`) and `ScreenReaderPage` writes one `TextRun` per line plus the selection. The accessible view reuses both.
+
+**Invariant:** a text run states its character lengths in UTF-8 bytes, and the parent carries the whole page as its value. accesskit derives the value from the runs only for single-line inputs, so a text area without it reads as empty.
+
+**Invariant:** work that only the tree can observe is gated on `Window::is_a11y_active`, as `editor_accessibility` gates the page. The page copies up to two pages of lines per frame; without the gate every frame of every user pays for it ([performance.md](performance.md)). GPUI redraws when a client activates the tree.
+
+## Screen reader mode
+
+`screen_reader_running` is Electron's `app.isAccessibilitySupportEnabled`, not `is_a11y_active`: on macOS VoiceOver is on, or an assistive app set `AXManualAccessibility` or `AXEnhancedUserInterface` on the application; on Linux AT-SPI's `ScreenReaderEnabled`. `watch_assistive_apps` runs once from `app/src/main.rs`, and on macOS adds two methods to GPUI's application class ([memory-safety.md](memory-safety.md) has the row). A client that only reads the tree does not switch the mode.
+
+`is_screen_reader_optimized` is the one answer to "is a screen reader in use": `editor.accessibilitySupport` `on`, or `auto` with `screen_reader_running`. It feeds the `accessibilityModeEnabled` context key, `auto` values of the signals, the Explorer's compact folders (`app/src/explorer.rs::FileTree` field `screen_reader_optimized`), the debug and file dialog settings that have an `auto`. Read it; do not call `screen_reader_running` from a view. Its only callers are `accessibility_frame` and the diagnostics that report the raw state (`app/src/launch.rs`, `app/src/workbench/perf_view.rs`).
+
+`accessibility_frame` runs on every render of the workbench. It notices the mode change (status entry "Screen Reader Optimized", the prompt once per window, accessibilityStatus.ts) and runs `line_signals`. It is a hot path: `line_signals` compares the cursor and the model version, and while a line or position signal is enabled it also reads the watched properties (markers, folds, breakpoints) at the cursor on every frame. Add no other work to it.
+
+**Trap:** the GUI tools drive the app with cua-driver, which sets `AXManualAccessibility` or `AXEnhancedUserInterface` (`port/notes.md`), so the port and the reference both detect a screen reader under them. `port/tools/ui-pair` writes `editor.accessibilitySupport: off` unless `SETTINGS` sets it. A frame that differs only under a tool is this.
+
+## Announcements and signals
+
+`aria_alert` (assertive) and `aria_status` (polite) are aria.ts `alert` and `status`. They store the message with a counter; `aria_live_region`, one element in the root that `Workbench` renders (an editor window drawn by `app/src/workbench/auxiliary_windows.rs` has none), turns each into a synthetic `Status` node whose id comes from the counter, so the same message twice is read twice. Any code with a `Workbench` announces through these two functions. A second live region would compete with the first.
+
+`play_signal` is `playSignal`: the announcement through `aria_alert`, the sound through `SoundPlayer`, each when `is_enabled` says so for its modality. The editor's line and position signals (editorTextPropertySignalsContribution.ts) are the table `TEXT_PROPERTIES`; a new text property is a row there, not a new caller.
+
+GPUI has no focusable synthetic node, so a feature that upstream implements by focusing a hidden aria element announces through the live region instead (`app/src/workbench/inlay_hints_accessibility.rs`, listed with the accepted differences in `port/notes.md`).
+
+## Accessible view and accessibility help
+
+One widget serves both: Alt+F1 shows help, Alt+F2 shows content. `Provider` in `app/src/workbench/accessible_view.rs` lists the providers and `Provider::id` gives upstream's `AccessibleViewProviderId`; `accessible_view_content` holds the one match that produces each provider's text, and the command handlers in `register_accessible_view_actions` check the providers' conditions in a fixed order and take the first that holds. Upstream orders its MultiCommand implementations by priority; the port's order differs from it (hover help before terminal help, notification and terminal before the hover view). A new provider is a variant, an arm in that match, an arm in `Provider::id` and `verbosity_key`, and a place in that order.
+
+Help text names keys as `<keybinding:command.id>`. `resolve_keybindings` replaces each with the aria label of the current binding (`app/src/keybindings.rs::aria_label`) or lists the command as unassigned. Write the command id, never a key name, so a user's rebinding is read correctly.
+
+**Invariant:** `accessible_view_key` runs before the keybindings (`app/src/workbench/keyboard.rs::dispatch_key`), as the view's editor gets `onKeyDown` before the window listener upstream. A key it returns false for reaches the keybindings; the context keys of `accessible_view_context` gate those.
+
+The view keeps its own cursor and selection and is drawn by `accessible_view_widget`. With `accessibility.hideAccessibleView` it is moved off screen, not removed, so the screen reader still reads it.
+
+## Keyboard and focus
+
+Everything a mouse can do, a key can do. The general rules are in [ARCHITECTURE.md](../ARCHITECTURE.md) ("Focus") and [workbench.md](workbench.md) ("Keys, commands, context keys, menus"). The accessibility part:
+
+- Each part is reachable with F6 (`app/src/workbench/part_navigation.rs::FocusPart`) and with Tab in upstream's DOM order.
+- An action bar is one tab stop (roving tabindex). Its container goes through `app/src/workbench/action_bar.rs::action_bar`, which handles the arrow, Home and End keys, and its items through `action_bar_item`, which gives the item its focus handle and the 1px `focusBorder` outline. Enter and Space reach the focused item's own `on_click`. A hand-made row of icon buttons has none of these.
+- A focused element shows it: the `focusBorder` color, as upstream's CSS for that widget.
+- Tab types a tab in the editor and the terminal until Toggle Tab Key Moves Focus (`editor.tabFocusMode`, the `editorTabMovesFocus` context key). A new text surface that captures Tab honors `app/src/workbench/editor_status.rs::tab_focus_mode`.
+- A popup (menu, dialog, hover, accessible view) returns the focus to where it came from when it closes, as `hide_accessible_view` does per provider.
+- An animation checks `is_motion_reduced` (`workbench.reduceMotion`, the OS setting on `auto`).
+
+## High Contrast
+
+`app/src/theme.rs::ThemeKind` has `HighContrastDark` and `HighContrastLight`; `is_high_contrast` stands for upstream's `.hc-black` and `.hc-light` CSS rules. The color registry in `app/src/theme.rs` holds a default per kind, and in High Contrast most borders come from `contrastBorder` and `contrastActiveBorder`, which the other kinds leave unset.
+
+**Invariant:** a view draws a border, outline or background by registry key and draws nothing when the key is unset. A hard-coded color, or a fallback for an unset key, breaks High Contrast in one of two ways: the outline is missing, or a fill hides the text. Rules that upstream writes only for `.hc-black` are an `is_high_contrast` branch, as `high_contrast_list_outline` in `app/src/workbench.rs`.
+
+`host_color_scheme` reads the system's dark appearance and Increase Contrast; `color_theme_setting_id` picks the preferred High Contrast theme setting when `window.autoDetectHighContrast` is on (themeConfiguration.ts). Only the macOS variant reads the contrast setting. Dotted borders draw dashed (accepted GPUI limit, `port/notes.md`).
+
+## What a new view provides
+
+1. Every interactive element has an id, a role and an `aria_label` that matches upstream's `aria-label` or the visible text. An icon-only button has no visible text: its label is its title.
+2. State is on the node: selected, expanded, checked, level, value, where upstream sets the `aria-*` attribute.
+3. A list or tree: the container has `Role::List` or `Role::Tree` and a label, rows `ListItem` or `TreeItem`, the focused row `aria_active_descendant`.
+4. Each action works from the keyboard, the element is a tab stop or part of a roving one, and its focus is visible.
+5. A change the user cannot see from where the focus is (a result count, a completed step, an error) goes to `aria_alert` or `aria_status` where upstream calls `alert` or `status`.
+6. Colors come from registry keys and the view is checked in a High Contrast theme.
+7. A view with upstream accessibility help or an accessible view gets a `Provider`.
+
+## Check a change
+
+- `port/tools/cargo-test -p app accessible_view`: Alt+F1 and Alt+F2 providers, keys, keybinding resolution.
+- `port/tools/cargo-test -p app accessibility`: the screen reader page, line and position signals, `is_enabled`, the sound files, inlay hint reading.
+- `port/tools/cargo-test -p app accessible_buffer`: the terminal's lines.
+- `port/tools/cargo-test -p app part_navigation` and `port/tools/cargo-test -p app in_tab_focus_mode`: F6, Tab order, Tab leaving the editor and the terminal.
+- `port/tools/cargo-test -p app the_host_color_scheme_picks_the_preferred_theme_setting`: High Contrast detection.
+- `port/tools/studio --lane 'port/tools/a11y-check'`: what VoiceOver reads. It dumps the window's AX tree after each step and fails when the Explorer tree, its rows, the editor text area or the help text are missing. Run it with `REF_APP=1` to see the reference's tree: that run skips the help step and asserts nothing. A new view with roles gets its assertion here.
+- `port/tools/ui-pair` with `port/fixtures/ui-steps/screen-reader-detection.json` and `SETTINGS='{"editor.accessibilitySupport":"auto"}'`: the detection prompt and status entry beside the reference.
+- `THEMES="hc hclight" port/tools/pixel-check` for a change to a border or focus outline.
diff --git a/docs/debug.md b/docs/debug.md
new file mode 100644
index 00000000000..981e523c1e6
--- /dev/null
+++ b/docs/debug.md
@@ -0,0 +1,65 @@
+# Debug
+
+Debugging is the breakpoint and watch model, the sessions that speak the debug adapter protocol (DAP), and the Run and Debug views. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), section "Extension host bridge", and under [extension-host.md](extension-host.md). Upstream is `src/vs/workbench/contrib/debug` and `src/vs/workbench/api/browser/mainThreadDebugService.ts`. The decisions per feature (hover, inline values, memory, extension host debugging) are in `port/notes.md`, "Milestone 16: debug and testing".
+
+## What is where
+
+Data without a window, in `app/src/debug.rs` and its submodules:
+
+- `app/src/debug.rs::DebugModel`: breakpoints of every kind and the watch expressions, debugModel.ts `DebugModel` without the sessions. It also holds the storage round trip of debugStorage.ts (`storage_entries`, `from_storage`) and the breakpoint DTOs for the extension host (`dtos`).
+- `app/src/debug/session.rs::Session`: one session's threads, frames, capabilities and its DAP request bookkeeping (debugSession.ts and the request state of rawDebugSession.ts). The same file converts paths as debugUtils.ts does.
+- `app/src/debug/configuration.rs`: the debuggers extensions contribute, launch.json as `Launch`, and the `${command:...}` and `${input:...}` references of a configuration.
+- `app/src/debug/disassembly.rs::Disassembly`: the instruction list of the Disassembly view, merged by address.
+- `app/src/debug/ansi.rs::parse`: output text split into styled runs (debugANSIHandling.ts).
+
+The service and the views, in `app/src/workbench`:
+
+- `app/src/workbench/debug_service.rs::DebugService`: the state of debugService.ts, debugViewModel.ts and debugAdapterManager.ts in one struct: the model, the sessions, the focus, the variables cache, the REPL. It is the field `debug` of `app/src/workbench.rs::Workbench`. The file's `impl Workbench` block is the protocol: start, stop, restart, events, breakpoints sent to sessions.
+- `app/src/workbench/debug_view.rs`: the Run and Debug views. `debug_console.rs`, `debug_toolbar.rs`, `breakpoint_widget.rs`, `inline_breakpoints.rs`, `debug_hover.rs`, `debug_inline_values.rs`, `disassembly_view.rs`, `debug_memory.rs` and `debug_visualizers.rs` beside it each name the upstream files they port in their `//!` header.
+- `app/src/workbench/debug_commands.rs`: the commands, and `debug_context`, the context keys of debug.ts.
+- `app/src/workbench/debug_task_runner.rs` and `app/src/workbench/debug_dynamic.rs`: `preLaunchTask` and `postDebugTask`, and dynamic configurations.
+
+## Who owns the adapter
+
+The extension host owns every debug adapter. Inline, executable and server adapters all run behind `ExtHostDebugService`, as on VS Code desktop, and the app starts no adapter process. The app owns the session: it decides which DAP request goes out and when, and it holds all state.
+
+The path of a message:
+
+- App to adapter: `app/src/workbench/debug_service.rs::dap_request` gives the request its sequence number (`app/src/debug/session.rs::request`), converts paths, and sends `$sendDAMessage` with the session's `handle` through `app/src/host_sync.rs::HostSync`. It returns a receiver for the response.
+- Adapter to app: the host calls `MainThreadDebugService.$acceptDAMessage`. `app/src/main_thread_commands.rs::route` forwards the whole proxy (path 3 of extension-host.md), and `app/src/workbench/debug_service.rs::handle_debug_request` hands the message to `accept_adapter_message`. A response resolves its pending request, an event goes to `accept_adapter_event`, a reverse request (`runInTerminal`, `startDebugging`, `launchVSCode`) to `accept_reverse_request`.
+- The adapter ends: `$acceptDAExit` or `$acceptDAError` reach `adapter_exited`, and `app/src/debug/session.rs::cancel_pending` fails every request still waiting.
+
+The host addresses a session by `handle`, the workbench by `id`. `app/src/workbench/debug_service.rs::session_by_handle` is the one lookup from a handle to its session, and it finds only running sessions.
+
+## How state reaches the views
+
+There is no event emitter. The views are `impl Workbench` methods that read `self.debug` in `render`, and whoever changes debug state calls `cx.notify()`. Three functions bundle the follow-up work, use them instead of a bare field write:
+
+- `app/src/workbench/debug_service.rs::breakpoints_changed`: stores the model, sends `$acceptBreakpointsDelta` to the host, sends the breakpoints to every session again when `send_to_sessions` is set, and refreshes the Breakpoints hint. A change marked `session_only` goes to neither. The `DebugModel` methods that add, remove, update or enable breakpoints return a `app/src/debug.rs::BreakpointsChange` for it; the three that set exception breakpoints per session do not.
+- `app/src/workbench/debug_service.rs::set_debug_focus`: the way to move the focus to a session, thread or frame. It tells the host and reveals the frame. Three functions write `focus` without it, to drop the frame of a resumed thread or to leave an ended session: `threads_continued`, `session_ended` and `app/src/workbench/debug_commands.rs::resume_thread`.
+- `app/src/workbench/debug_service.rs::update_debug_views`: fetches the shown variable rows and watch values again, each keeping its rows until the reply.
+
+A flow that waits on the adapter (a start, a restart, a lazy variable) is an async function that takes a `WeakEntity<Workbench>` and re-enters through `app/src/workbench/debug_service.rs::on_workbench` for each step. It holds no borrow of the workbench across an `await`.
+
+## Invariants
+
+- Message order at session start. `launch_or_attach` calls `$startDASession` so the host creates the adapter, then sends `initialize`, then `launch` or `attach`. An `initialized` event that arrives with the initialize response sets `initialized_event_pending` and is handled only after the launch request went out, because js-debug rejects `setBreakpoints` before `launch`. `session_initialized` then sends all breakpoints, waits for their answers, sends `configurationDone` if the adapter supports it, and fetches the threads.
+- One sequence counter per session. Requests and the responses to reverse requests both take the next number (`app/src/debug/session.rs::number`).
+- Paths convert at one boundary. Toward the adapter `to_adapter_paths` turns source paths into `UriComponents`; from it `from_adapter_paths` turns them back. Inside the app a source is a path.
+- Lines. A breakpoint's line is 1-based in the model and in DAP, and 0-based in the DTO the host gets (`debug::tests::dtos_carry_zero_based_lines`).
+- Cancellation tokens. A host method whose last parameter is a `CancellationToken` gets its token when the call goes out through `app/src/host_sync.rs::call_cancellable`, or through `call` with an entry in `app/src/main_thread.rs::TOKEN_METHODS`. Without either the extension gets `undefined` as its token.
+
+## Traps
+
+- A handler in `handle_debug_request` that needs the adapter's answer returns `Outcome::Pending` with the receiver. Do not wait in the handler: it runs on the main thread.
+- `app/src/workbench/debug_memory.rs` serves the `vscode-debug-memory` file system from the workbench while the session thread waits, and its answer needs a `readMemory` round trip to the host. This works only because `exthost/src/session.rs::ask_workbench` keeps sending the workbench's queued calls while it waits. `port/notes.md` ("View Binary Data") has the case.
+- `sessions` holds running sessions, `inactive_sessions` the ended ones upstream keeps as `State.Inactive`. `app/src/workbench/debug_service.rs::session` finds only running ones; use `sessions_including_inactive` for a view that lists both.
+- `app/src/workbench/extension_host_restart.rs::stop_extension_host` clears the host's commands, language features, SCM model, webview views and markers. It does not clear `providers` or `adapter_types`, and no other code in `native/crates` clears them on a restart: the new host's `$registerDebugTypes` replaces `adapter_types`, and its `$registerDebugConfigurationProvider` calls add to the `providers` of the old host. A running session vetoes a restart (`stop_extension_hosts`), and the user can answer Restart Anyway.
+- An `extensionHost` session needs a V8 inspector, so the host it debugs runs on Node, not Bun (`port/notes.md`, "Extension host debugging").
+
+## Check a change
+
+- `port/tools/cargo-test -p app debug::` runs the model, storage, session and path tests (upstream's breakpoints.test.ts and debugUtils.test.ts cases).
+- `port/tools/cargo-test -p app debug_service` and `port/tools/cargo-test -p app debug_view` run the service and view tests, most of them in a test window.
+- `MOCHA_GREP="vscode API - debug" port/tools/api-tests` runs upstream's API tests for `MainThreadDebugService`.
+- `port/tools/studio --lane 'FOLDER=port/fixtures/debug-node FILE=app.js port/tools/ui-pair /tmp/out port/fixtures/ui-pair/m16/breakpoint.json'` compares a real session against the reference app: the script sets a breakpoint on line 5 of the open file and runs Launch app.js. `port/fixtures/ui-pair/debug` holds the scripts of more cases, one per file.
diff --git a/docs/extension-host.md b/docs/extension-host.md
index 2408f68dfc8..b9a9709906d 100644
--- a/docs/extension-host.md
+++ b/docs/extension-host.md
@@ -66,7 +66,7 @@ The workbench does not need a running host to know what extensions contribute. `
- Install, uninstall and update: `exthost/src/extension_management.rs`, against Open VSX (`exthost/src/gallery.rs`) with signature checks (`exthost/src/sign.rs`).
- Which extensions run: enablement (`app/src/extension_enablement.rs`), workspace trust (`app/src/workspace_trust.rs`), proposed API (`exthost/src/proposed_api.rs`).
-- Restart: `app/src/workbench/extension_host_restart.rs` ends the host, disposes what it registered in the workbench, and starts a new session.
+- Restart: `app/src/workbench/extension_host_restart.rs` ends the host, disposes what it registered, and starts a new session. `app/src/workbench/extension_host_restart.rs::stop_extension_host` names each thing it clears (commands, language features, SCM, webview views, URL handlers, diagnostics). State of the host that it does not name survives the restart, so a feature that keeps host registrations adds its line there.
## Check a change
diff --git a/docs/extensions.md b/docs/extensions.md
new file mode 100644
index 00000000000..7762bbf5f5f
--- /dev/null
+++ b/docs/extensions.md
@@ -0,0 +1,105 @@
+# Extensions: scan, install, gallery, signatures
+
+How an extension gets on disk and into a window: the folders, the scan, the install path from a gallery query to a running extension, what is verified, and the built-in set. The code is `exthost/src/extension_management.rs`, `exthost/src/gallery.rs`, `exthost/src/sign.rs`, `exthost/src/zip.rs`, `exthost/src/scan.rs` and their callers in `app/src`. The host process, the wire format and how the workbench reads contributions are in [extension-host.md](extension-host.md). Upstream is `src/vs/platform/extensionManagement`; the decisions are in `port/notes.md`, "Milestone 18: extensions, install, update, gallery".
+
+## What is where
+
+| File | Job |
+|---|---|
+| `exthost/src/scan.rs` | One folder to one `ScannedExtension`: `package.json` with its `%key%` strings replaced. The built-in scan. |
+| `exthost/src/extension_management.rs` | The user folder (`UserExtensions`), the disk jobs (`Job`), and the step that applies a job to the running host (`WindowExtensions`). |
+| `exthost/src/extension_validator.rs` | `extensionValidator.ts`: `engines.vscode` and the manifest checks. |
+| `exthost/src/zip.rs` | The VSIX reader, a port of `base/node/zip.ts`. |
+| `exthost/src/gallery.rs` | `extensionGalleryService.ts` against Open VSX, and the download of `extensionDownloader.ts`. |
+| `exthost/src/sign.rs` | The signature check of a downloaded VSIX. |
+| `app/src/workbench/extension_management.rs` | The workbench commands: gallery lookup and download off the main thread, then jobs to the host thread; the watcher of `extensions.json`. |
+| `app/src/workbench/trusted_publishers.rs` | The publisher trust prompt before a gallery install. |
+| `app/src/cli_process.rs` | `--install-extension` and its siblings in the CLI process, without a window or a host. |
+| `app/src/workbench/extensions_view.rs`, `app/src/extensions_model.rs` | The Extensions view and its model of one extension. |
+
+## On disk
+
+- Built-in extensions: `<app root>/extensions`, or the folder in `VSCODE_GPUI_EXTENSIONS`, plus the product.json `builtInExtensions` under `<app root>/.build/builtInExtensions` (`app/src/main.rs::scan_system_extensions`). Nothing writes there at run time.
+- User extensions: `<user data>/extensions`, or `--extensions-dir`. One folder per extension, named `<publisher>.<name>-<version>` for a VSIX and `exthost/src/gallery.rs::extension_key` for a gallery install (it adds `-<targetPlatform>`).
+- `extensions.json` is the list of what a profile has installed. The default profile's file is in the extensions folder; another profile has its own file and shares the folders. The default profile's file also holds the application scoped extensions of every profile (`port/notes.md`, "Application scope").
+- `.obsolete` lists `<id>-<version>` keys of folders to delete at the next start. A folder that starts with `.` is an install in progress, one that ends in `.vsctmp` a delete in progress. `exthost/src/extension_management.rs::clean_up` removes the `.vsctmp` folders and the folder each `.obsolete` key names, once per process start, before any window. Nothing removes a `.` folder that a killed install left.
+- Gallery downloads: `<user data>/CachedExtensionVSIXs/<key>`.
+
+The layout is upstream's (`extensionsProfileScannerService.ts`, `extensionManagementService.ts` `ExtensionsScanner`), down to the old `location` each entry keeps beside `relativeLocation`.
+
+**Invariant:** a folder in the extensions folder is installed only when a profile's `extensions.json` names it. A scan never lists the folder itself. The one exception is a default profile with no `extensions.json`: `initialize_profile` writes the file from the folders it finds.
+
+**Invariant:** a folder appears and disappears by rename. An install fills a `.<suffix>` folder and renames it into place (`extract`); a delete renames to `.vsctmp` first (`delete_folder`). A scan that runs at the same time never reads a half-written extension. A new write path keeps this.
+
+## The scan
+
+`exthost/src/scan.rs::scan_extension` reads one `package.json`, applies the display language's messages, and adds the fields of an `IExtensionDescription` (`identifier`, `extensionLocation`, `isBuiltin`). Its result is plain data: the workbench and the host get the same `ScannedExtension`.
+
+The set of a window is built in `app/src/main.rs::open_window`: the built-ins scanned once per process, then `exthost/src/extension_management.rs::add_user_extensions` with the profile's `UserExtensions::scan`. A user extension replaces the built-in with its id unless the built-in is newer, as `dedupExtensions` does.
+
+- A user extension goes through `validate_extension_manifest`, and one that fails is left out with a line on stderr. Built-ins are not validated.
+- The display language must be resolved before the first scan (`exthost/src/language_packs.rs::set_nls`), because the scan bakes the translated strings into the description.
+- There is no scan cache. Upstream caches the scanned manifests (`extensionsScannerService.ts` `CachedExtensionsScanner`); the port reads every `package.json` at each start, on the main thread, before the first frame. A change that makes the scan do more per extension is a startup change: measure it ([performance.md](performance.md)).
+
+**Trap:** `--builtin-extensions-dir` and `--extensions-download-dir` are parsed (`app/src/argv.rs`) and their values are read by nothing. The built-in folder is set with `VSCODE_GPUI_EXTENSIONS`, as the tools in `port/tools` do.
+
+## From a query to a running extension
+
+1. The Extensions view or a command asks `exthost/src/gallery.rs::Gallery`. Every call blocks on HTTP, so every caller in a window runs it on the background executor; the CLI process calls it directly. `installable_extension` picks the version: the engine, the target platform, release or pre-release.
+2. `app/src/workbench/extension_management.rs::install_from_gallery` asks about an untrusted publisher (`check_trusted_publishers`), before any download.
+3. Still off the main thread, `Gallery::dependencies_and_packs` lists what must come along, and `Gallery::download` fetches and verifies each VSIX. The result is a list of `Job::InstallGallery`, dependencies first.
+4. `app/src/workbench/extension_management.rs::run_extension_jobs` sends each job with `app/src/host_sync.rs::run_extensions`. It travels in the same queue as every other message to the host ([extension-host.md](extension-host.md), "Calls the port makes").
+5. On the `exthost-session` thread, `exthost/src/extension_management.rs::WindowExtensions::run` does the disk work, then upstream's `_deltaExtensions`: configuration defaults change first, then `exthost/src/session.rs::delta_extensions` tells the host, which activates the extension if one of its events already fired.
+6. The reply is the list of running extensions. `set_running_extensions` reads languages, menus, keybindings and themes from it again.
+
+An install from a VSIX file enters at step 3 with `Job::InstallVsix`; uninstall, and the settings import's `Job::InstallFolder`, at step 4. An enablement change is `Job::Delta`: nothing on disk.
+
+**Invariant:** the disk job and the host delta run on the session thread, one job at a time, because that thread knows which extensions started to activate. The network part runs on the background executor. Besides `clean_up` at startup and `initialize_profile` in a scan, the main thread's one write to the extensions folder is Apply Extension to all Profiles (upstream's capitalization) (`toggle_application_scope`, called from `app/src/workbench/extensions_view.rs`), which changes `extensions.json` and starts nothing.
+
+**Invariant:** an extension whose activation started is neither removed nor replaced until the host restarts (`exthost/src/session.rs::applicable_delta`). The files change on disk; `running` keeps the old one. The Extensions view shows Restart Extensions for this case.
+
+The CLI is a second writer. `app/src/cli_process.rs` calls `UserExtensions` directly, in another process. A window sees it through the watcher (`start_extensions_watcher`): 100 ms after the last change of the profile's `extensions.json` it scans again and sends at most one `Job::Delta` (`apply_profile_extensions`). A read of a half-written file makes no delta; the next change brings the rest.
+
+## What is verified, and when
+
+A VSIX and a gallery response are untrusted input. A VSIX is a zip an attacker can shape; a gallery response decides file names, URLs and the public key. The checks, in the order an install meets them:
+
+| When | Check | Where |
+|---|---|---|
+| Download | The bytes are a zip with `extension/package.json`, two attempts. | `exthost/src/gallery.rs::download_vsix` |
+| Download | The signature, unless `extensions.verifySignature` is false. Anything but `Success` deletes the file and refuses the install; `NotSigned` passes only for a private extension. | `exthost/src/gallery.rs::check_verification` |
+| Install | The manifest's id and version are the ones the gallery named. | `exthost/src/extension_management.rs::install` |
+| Install | `engines.vscode` accepts this version. | the same function |
+| Install | The folder name built from the manifest has no `/`, `\`, `..` or leading `.`. | the same function |
+| Extract | Each entry stays inside the target; its size and CRC match. Encrypted entries and unknown compression methods are refused. | `exthost/src/zip.rs::open`, `exthost/src/zip.rs::extract`, `exthost/src/zip.rs::read` |
+| Scan | `validate_extension_manifest`, at every start. | `exthost/src/extension_management.rs::scan_valid` |
+
+The signature is not upstream's scheme. Upstream checks a PKCS#7 signature chained to Microsoft's certificates with `@vscode/vsce-sign`. Open VSX signs with Ed25519, so `exthost/src/sign.rs::verify` checks that `.signature.sig` signs the VSIX bytes with the version's public key, then that `.signature.manifest` names the size and SHA-256 of the package and of every entry, and answers upstream's `ExtensionSignatureVerificationCode` names.
+
+- The public key's URL comes from the same gallery response as the VSIX's. The signature proves the file is the one Open VSX signed, and no more: the root of trust is the TLS connection to the gallery. There is no pinned key and no certificate chain.
+- A VSIX from disk has no signature. It gets the install and extract checks only, as upstream.
+- Install Anyway, the prompt of Install on a gallery extension that has no signature (`install_unsigned`), runs the same path with verification off (`install_from_gallery_verifying`).
+- A file already in `CachedExtensionVSIXs` under the right key is used instead of a download. With verification on it is verified again; the zip check of `download_vsix` does not run for it. The port never empties that folder.
+
+**Invariant:** a string from a VSIX or from the gallery is checked before it names a folder or file that an install writes (`install`, `vsix_file_name`, `extract`). The download cache is the exception: `exthost/src/gallery.rs::download_and_verify` joins `extension_key` to the folder with no check. New code that joins such a string to a folder makes the same check.
+
+**Invariant:** `zip.rs` takes every length and offset from the archive. Each offset and stored length is checked against the archive's size before it is used, and a forged entry count reserves no more than the archive could hold (`Archive::open`). The uncompressed size is compared after `read` inflates the entry, and nothing caps the inflated bytes. The reader has no `unsafe` code and answers an error, never a panic, for any input.
+
+## Built-in extensions
+
+The built-ins are upstream's `extensions/` folder, run as they are. `exthost/src/scan.rs::scan_builtin_extensions` takes every child folder with a `package.json`, in name order, except two lists: `REMOVED_BUILTINS` (sign-in, AI and tunnels, which the port does not ship) and `TEST_BUILTINS` (upstream's product leaves them out too). `scan_dev_system_extensions` adds the extensions product.json downloads (js-debug and its companions), which `port/tools/fetch-builtin-extensions` puts in place.
+
+- A built-in cannot be uninstalled, and the workbench refuses a gallery install of its id (`install_from_gallery_verifying`). A VSIX or a CLI install of the same id becomes a user extension that shadows it, and uninstalling that copy puts the built-in back (`WindowExtensions::run`, `Job::Uninstall`).
+- To drop a built-in from the product, add its folder name to `REMOVED_BUILTINS`. `port/tools/shipped-files.ts` reads the two lists from `scan.rs`, so the package follows.
+- Which extensions of the scanned set run is a separate question: enablement, workspace trust and proposed API ([extension-host.md](extension-host.md), "Extensions as data").
+
+## Check a change
+
+- `port/tools/cargo-test -p exthost extension_management`: the folder layout, profiles, application scope, `.obsolete`.
+- `port/tools/cargo-test -p exthost gallery`: version choice, target platforms, the query, `verification_failures_refuse_the_install`.
+- `port/tools/cargo-test -p exthost sign` and `port/tools/cargo-test -p exthost zip`: signatures; `refuses_entries_outside_the_target`, `detects_corruption`.
+- `port/tools/cargo-test -p exthost extension_validator`: upstream's table of `extensionValidator.test.ts`.
+- `port/tools/cargo-test -p app extension_management`: the workbench path against a local gallery server, the watcher (`extensions_installed_by_another_source_start_and_stop`).
+- `port/tools/cargo-test -p app cli_process`: the CLI commands.
+- `port/tools/extensions-check` (on the Studio, after `port/tools/build-exthost`): packs the fixture VSIXs and installs and uninstalls them in a running app; `PORT_GALLERY=1` adds an install from Open VSX.
+- `exthost/src/bin/exthost-probe.rs` with `--install-vsix <file> --uninstall <id>`: the same against a host, without a window.
diff --git a/docs/files-and-search.md b/docs/files-and-search.md
new file mode 100644
index 00000000000..9c3aa39f47d
--- /dev/null
+++ b/docs/files-and-search.md
@@ -0,0 +1,105 @@
+# Files, search and watchers
+
+How the port reaches the disk, watches it and searches it: the `files` and `search` crates, and their callers in `app` and `exthost`. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), section "Files, search and watchers". Upstream is `src/vs/platform/files`, `src/vs/base/common/glob.ts` and `src/vs/workbench/services/search`.
+
+## What is where
+
+| File | Its one job | Upstream |
+|---|---|---|
+| `files/src/lib.rs` | The file service as free functions over a `files/src/lib.rs::FileSystem`: the checks, the error names and messages of each layer. | `src/vs/platform/files/common/fileService.ts` |
+| `files/src/disk.rs` | `files/src/disk.rs::Disk`, the `file` scheme, with Node's errno messages and the Trash. | `src/vs/platform/files/node/diskFileSystemProvider.ts` |
+| `files/src/operations.rs` | File operations that ask the participants first, report after, and return their undo. | `workingCopyFileService.ts`, `bulkFileEdits.ts` |
+| `files/src/watcher.rs` | The disk watcher: batch, cover, coalesce. | `src/vs/platform/files/common/watcher.ts` |
+| `files/src/glob.rs` | VS Code's glob dialect, expressions with sibling clauses, exclude expressions with `!` exceptions. | `src/vs/base/common/glob.ts` |
+| `files/src/encoding.rs`, `files/src/unc.rs`, `files/src/user_data.rs` | Text encodings, the UNC host allowlist, the `vscode-userdata` scheme over the disk. | `encoding.ts`, `unc.ts`, `fileUserDataProvider.ts` |
+| `search/src/query.rs`, `search/src/search_paths.rs` | Build a `search/src/query.rs::Query` from options and the folders' settings, and from the search view's include and exclude inputs. | `src/vs/workbench/services/search/common/queryBuilder.ts` |
+| `search/src/ripgrep.rs` | Start ripgrep, read its lines, kill it. | `ripgrep.ts`, `ripgrepSearchUtils.ts` |
+| `search/src/file_search.rs`, `search/src/text_search.rs` | The two searches: the ripgrep arguments, the parse of its output, the filters ripgrep cannot express. | `fileSearch.ts`, `ripgrepFileSearch.ts`, `ripgrepTextSearchEngine.ts`, `textSearchManager.ts` |
+
+Both crates are synchronous and know nothing of GPUI or the extension host. The caller picks the thread. This is what lets the same code serve the workbench and the session thread.
+
+## Which thread touches the disk
+
+There is no file service object. A caller passes a `FileSystem` to a function of `files/src/lib.rs`, and the call blocks until the disk or the provider answers. Three callers exist:
+
+- The session thread. `exthost/src/main_thread_files.rs::Providers` is the `FileSystem` that knows every scheme: the disk, `vscode-userdata`, the settings scheme, debug memory, and extension providers, which it asks over the protocol. It answers the host's `workspace.fs` calls on the `exthost-session` thread ([extension-host.md](extension-host.md), "Threads").
+- The workbench, through the session. A file operation that must run participants or reach an extension provider is a `app/src/host_sync.rs::FileJob`. `app/src/host_sync.rs::HostSync::run_files` queues it, the session thread runs it in `app/src/main_thread.rs` with `Providers`, and the main thread awaits the oneshot reply. The Explorer's create, move and delete, the file edits of a rename, and their undo take this path. With no host, `run_files` runs the job at once on `Disk`, on the calling thread and without participants.
+- The workbench, directly. Opening and saving a text document (`app/src/workbench/text_files.rs::read_document`, `app/src/workbench/text_files.rs::write_text_file`) and listing an Explorer folder (`app/src/explorer.rs::read_children`) call `std::fs` on the main thread. `app/src/explorer.rs::root_error` calls `files::resolve` on `Disk` there too.
+
+The rule of [performance.md](performance.md) ("No I/O on the main thread in a hot path") applies like this:
+
+- A search never runs on the main thread. Every caller in `app` starts it with `cx.background_spawn`; the session starts a `std::thread` per `findFiles` or `findTextInFiles` request. The exception is `exthost/src/main_thread_workspace.rs::MainThreadWorkspace::glob_file_exists` (a `workspaceContains:` glob): it runs on the session thread and holds it until a file matches, at most 7 s. See "Search" below.
+- A watcher event never does I/O on the main thread before it is needed: the batch arrives as data, and `app/src/workbench/text_files.rs::files_changed` touches the disk only for a path that has an open model. A clean model reads its file again, a placeholder for a missing file opens it, and a delete is checked with one `exists` 100 ms later.
+- The direct `std::fs` calls above run once per user action (open, save), not per frame or per key. The Explorer is the one that sits near a hot path: `app/src/explorer.rs::entries` runs when the rows are built, so it costs one `stat` of each shown folder, and reads a folder again when its mtime changed. It also reads it on every call while the mtime is younger than 2 s (100 ms when the mtime has a sub-second part), while the sort order is `modified`, and while a new item is being named in it. Keep that cache in front of any new per-row disk question.
+- New code that reads a file whose size the user controls, walks a tree, or starts a process goes to the background executor or to the session through `FileJob`. Add no new `std::fs` call to a `render`, a list row or a key handler.
+
+**Invariant:** errors keep the JavaScript error name and message of the upstream layer that raised them (`files/src/lib.rs::FileError`), because extensions and upstream's API tests match on them. `files/src/lib.rs::handle_error` renames them once, at the boundary to the host. A new failure path builds its error with `files/src/lib.rs::provider_error` or, inside `files`, with `files/src/disk.rs::io_error`, not with a free-form string.
+
+**Invariant:** on Windows the file service, the text file models and webview resources call `files/src/unc.rs::check_unc_access` before they touch a path. `Disk` calls it for every path. Code that calls `std::fs` directly must call it first, as `read_document` does. The Explorer listing (`read_children`) and the searches do not call it.
+
+## The watcher
+
+`files/src/watcher.rs::Watcher` stands in for upstream's parcel watcher. One `Watcher` owns one `notify` watcher and one thread named `file-watcher`. Watches are added by id (`files/src/watcher.rs::Watcher::watch`), and one callback gets every batch.
+
+An event goes through four steps, all off the main thread:
+
+1. `files/src/watcher.rs::forward`, on the thread of `notify`: maps the event to `Added`, `Updated` or `Deleted`. A create, remove or rename is `Added` when the path exists afterwards, else `Deleted`, as parcel reports FSEvents. This is one `lstat` per path of such an event; a plain modify needs none.
+2. `files/src/watcher.rs::deliver_batches`, on `file-watcher`: after the first event it collects for 75 ms (upstream's `FILE_CHANGES_HANDLER_DELAY`). The window is fixed from the first event; later events do not extend it.
+3. Cover: each event is kept if a watch covers it (below its root, within its depth, not matched by its excludes) and gets the path below the root the watch was asked for, not the realpath. A file under `/var` is reported as `/var/...` even though the event names `/private/var/...`.
+4. `files/src/watcher.rs::coalesce`, a port of `EventCoalescer`: one event per path, create then delete dropped, delete then create turned into `Updated`, no delete below a deleted folder.
+
+The callback then runs on `file-watcher`. It must only send: every caller pushes the batch into a channel. In `app` the channel is drained by a `cx.spawn` task on the main thread; in `exthost` a `exthost/src/lib.rs::WakingSender` wakes the session, which turns the batch into `$onFileEvent` (`exthost/src/main_thread_files.rs::MainThreadFiles::take_events`).
+
+Who watches what:
+
+- The workbench: `app/src/workbench/text_files.rs::start_file_watcher` watches each workspace folder recursively minus `files.watcherExclude`, plus the visible file outside the folders, one watch at a time (`watch_visible_file`). `files_changed` is the single entry for these events in the workbench; a new consumer of disk changes is called from there.
+- The session: `exthost/src/main_thread_files.rs::MainThreadFiles` watches the same folders again for the host, and serves the host's `$watch` calls. A correlated flat watch or a `vscode-userdata` watch gets a `Watcher` of its own, because a batch carries no watch id: the callback is the only place that knows the session and the scheme.
+- Single folders: settings (`app/src/workbench/configuration.rs`), `keybindings.json` (`app/src/workbench/keyboard.rs`), the profile's extensions (`app/src/workbench/extension_management.rs`), and the policy file on Linux (`app/src/policy/linux.rs`). Each makes its own `Watcher` and watches flat.
+
+Traps:
+
+- A batch says "something changed here", not "this is the state". A consumer reads the disk again or compares a stat; `files_changed` waits 100 ms before it believes a delete (upstream issue 13665).
+- An event covered by two watches of one `Watcher` is reported once, under the root of whichever watch matches first. Watches that need their own paths or their own events need their own `Watcher`.
+- Paths are keyed ignoring case in `coalesce` and exclude patterns match ignoring case, as upstream does on macOS. This holds on every OS here.
+- The callback is dropped by `Drop` of `Watcher` on the dropping thread, not on `file-watcher`: a channel sender dropped there would wake a GPUI foreground task off the main thread. Drop a `Watcher` on the thread its callback's captures belong to: the main thread in `app`, the session thread in `exthost`.
+- A workspace folder is under two recursive watches (workbench and session). A change to watcher cost counts twice.
+
+## Search
+
+A search is one call that blocks: `search/src/file_search.rs::search` or `search/src/text_search.rs::search`, given a `Query`, the path of ripgrep (`search/src/ripgrep.rs::rg_path`), a `search/src/ripgrep.rs::Cancellation` and a callback for results. It runs the query's folders one after the other, one ripgrep process at a time (`search/src/ripgrep.rs::run`). Results reach the callback while ripgrep still runs.
+
+- File search lists with `rg --files` and filters here: the fuzzy file pattern, include globs, and the excludes ripgrep cannot express. A query with sibling clauses (`"**/*.js": { "when": "$(basename).ts" }`) keeps the whole listing and walks it as a tree once ripgrep is done, so its memory grows with the folder.
+- Text search runs `rg --json`, parses matches and context lines, and groups them by file before the callback sees them. The limit is counted in match ranges, 20000 unless the query sets one.
+- Excludes with `!` exceptions run ripgrep twice per folder: ripgrep does not descend into an excluded folder, so the second run uses `--no-ignore`, searches what the exceptions re-include, and skips what the first run reported. This follows upstream; the two runs are the design, not a leftover.
+- With `search.followSymlinks`, more than `search/src/ripgrep.rs::MAX_SYMLINK_LOOPS` loop reports on stderr kill the run, and the folder is searched again without following links.
+
+Ignore files are ripgrep's job. The port reads no `.gitignore`; it only passes flags. `search/src/query.rs::FolderQuery` carries `disregard_ignore_files`, `disregard_parent_ignore_files` and `disregard_global_ignore_files`, filled from the caller's options or else from `search.useIgnoreFiles`, `search.useParentIgnoreFiles` and `search.useGlobalIgnoreFiles` of the folder. They become `--no-ignore`, `--no-ignore-parent` and `--no-ignore-global`. Every run also passes `--hidden`, `--no-require-git` and `--no-config`. `files.exclude` and `search.exclude` are a different mechanism: `search/src/query.rs::excludes` merges them into the exclude expression of each `FolderQuery`, which becomes `-g` arguments plus the filters applied here. A caller that must see ignored files sets the `disregard` options in the query; it does not post-filter.
+
+Cancellation: `Cancellation::cancel` sets a flag and kills the ripgrep child it holds. `run` stops at the next line, and the search function returns. A cancelled search can return `Ok` with partial results or `Err`; the caller asks `is_cancelled` to tell it from a real result or a real error, as `app/src/workbench/search_actions.rs::search_complete` does.
+
+How callers run and cancel:
+
+| Caller | Runs on | Cancelled by |
+|---|---|---|
+| Search view and search editor (`app/src/workbench/search_actions.rs::spawn_text_search`) | `cx.background_spawn`; file matches stream over an unbounded channel | the next search; in the view also `cancel_search` and `clear_search_results`. Closing a search editor does not cancel its search |
+| Quick Open file list (`app/src/workbench/quick_open.rs::load_file_query_cache`) | `cx.background_spawn`; one listing per picker, filtered in memory per key | `Drop` of `app/src/workbench/quick_open.rs::FilePickState` |
+| Explorer find (`app/src/workbench/explorer_find.rs::search_folders`) | `cx.background_spawn` | the next pattern |
+| `workspace.findFiles`, `findTextInFiles` (`exthost/src/main_thread_workspace.rs::MainThreadWorkspace::start`) | one `std::thread` per request; results go back through a `WakingSender` in order | the host's `Cancel` for the request; the reply is then `null` |
+
+Traps:
+
+- One `Cancellation` per search. It holds one child, so sharing it between two searches that run at the same time leaves the first child without a way to be killed.
+- Dropping the GPUI task does not stop ripgrep. The blocking call sits on a background thread until ripgrep ends. The owner keeps the `Arc` of its `Cancellation` and must call `cancel` when the result is no longer wanted.
+- The result callback runs on the search thread. It sends or collects; it does not touch the workbench.
+- ripgrep is the binary under `node_modules/@vscode/ripgrep-universal` of the app root. A test that searches needs the app root of a checkout with its node modules.
+- The searches report paths relative to the folder and match globs against them with `/` separators. An exclude key that starts with `/` is matched against the absolute path. `files/src/glob.rs` has no relative patterns (`IRelativePattern`): convert before calling.
+
+## Check a change
+
+- The file service, operations: `port/tools/cargo-test -p files moves_and_copies`, `port/tools/cargo-test -p files operations`. `files/src/disk.rs` has no unit test.
+- Globs (upstream's `glob.test.ts` cases): `port/tools/cargo-test -p files glob`.
+- The watcher: `port/tools/cargo-test -p files coalesces_like_the_event_coalescer reports_changes_below_the_requested_path`. The second one writes real files and waits for FSEvents.
+- Watcher events in the workbench: `port/tools/cargo-test clean_models_follow_their_file_and_deleted_files_orphan_them`.
+- Search: `port/tools/cargo-test -p search file_search`, `port/tools/cargo-test -p search text_search`, `port/tools/cargo-test -p search too_many_symlink_loops`.
+- The host side (`workspace.fs`, watch sessions, `findFiles`): `port/tools/cargo-test -p exthost user_data_watch_events_keep_their_scheme`, then upstream's API tests with `port/tools/api-tests` ([testing.md](testing.md)).
+- After a rename or a move: `bun port/tools/docs-check.ts`.
diff --git a/docs/notebooks.md b/docs/notebooks.md
new file mode 100644
index 00000000000..0789a5b8e83
--- /dev/null
+++ b/docs/notebooks.md
@@ -0,0 +1,72 @@
+# Notebooks
+
+A notebook is a list of cells with outputs, opened by an extension's serializer, run by an extension's kernel, and drawn as a list of code editors over one webview. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md). Upstream is `src/vs/workbench/contrib/notebook`, `contrib/interactive` and `contrib/replNotebook`, with the `mainThreadNotebook*.ts` files of `src/vs/workbench/api/browser`. What each session ported and what differs from the reference is in `port/notes.md`, "Milestone 17: webviews and notebooks".
+
+## What is where
+
+- `app/src/notebook.rs`: the model. `app/src/notebook.rs::Notebooks` holds the open `NotebookModel`s, the serializers, the kernels, one `NotebookEditor` per notebook tab, and what the host was last told. `apply_edits` is notebookTextModel.ts `applyEdits`. No GPUI.
+- `app/src/notebook/kernels.rs`: kernels, which kernel a notebook is bound to, cell executions. `app/src/notebook/renderers.rs`: contributed renderers and which mime type of an output shows. `app/src/notebook/layout.rs`: the height and top of every cell. `app/src/notebook/outline.rs`: outline entries and fold ranges. All four have no GPUI and carry their tests.
+- `app/src/workbench/notebooks.rs`: the main thread. `handle_notebook_request` answers the five `MainThreadNotebook*` proxies; open, save, backup, revert, the delta to the host, kernel execution.
+- `app/src/workbench/notebook_editor.rs`: the editor of a notebook tab: toolbar, cell list, the back layer webview, view state, undo. Its parts are in `app/src/workbench/notebook_editor`: cell toolbars and commands, outputs, find, folding, drag and drop, the overview ruler.
+- `app/src/notebook/back_layer.html` and `app/src/notebook/webview_preloads.js`: the page of the back layer webview. The preloads are upstream's webviewPreloads.ts.
+- `app/src/workbench/interactive.rs` and `app/src/workbench/repl_notebook.rs`: the interactive window and the REPL editor, both a notebook editor plus an input cell.
+
+## Who owns what
+
+The extension host owns the file format and the execution. A serializer turns bytes into cells (`$dataToNotebook`) and cells into bytes (`$notebookToData`); the app never parses an `.ipynb`. A kernel runs cells and sends their outputs. A renderer's script runs in the webview, not in the host.
+
+The app owns the notebook document: `app/src/notebook.rs::NotebookModel` is the truth for cells, metadata, outputs, the version and the dirty state, and the host holds a copy it learns of through events. The model lives in `app/src/host_sync.rs::HostSync` (`notebooks`), not in the workbench, because a cell's text change is a change of its notebook and the host must hear both from one place.
+
+**A cell's text is not in the model.** Each cell has a workbench text model at its `vscode-notebook-cell` URI (`app/src/notebook.rs::cell_uri`: the notebook's URI with the cell's handle in the fragment). `Cell` has no source field. Code that needs a cell's text reads the text model (`app/src/workbench/notebooks.rs::cell_text`), and `snapshot` and `added_data` take a closure for it.
+
+## From a kernel to the view
+
+1. The kernel's extension calls `MainThreadNotebookKernels.$updateExecution` with outputs. `app/src/workbench/notebooks.rs::update_execution` turns the updates into cell edits.
+2. `app/src/workbench/notebooks.rs::apply_notebook_edits` applies them: `apply_edits` changes the model and returns an `Applied` with one event, the cells it added and removed, and the inverse edits. The function then creates and drops the cells' text models, sends `$acceptModelChanged` and the dirty state to `ExtHostNotebookDocuments`, and calls `editors_changed`.
+3. On the next render, `app/src/workbench/notebook_editor.rs::sync_back_layer` compares the model with what the webview was sent (`BackLayer`) and posts the difference: new outputs with their bytes, cleared outputs, markup previews, and the top of each.
+4. The webview renders, measures, and posts `dimension`. `handle_notebook_message` stores the heights, `app/src/notebook/layout.rs::layout` gives every cell its top, and the next `view-scroll` moves the outputs there.
+
+An edit by the user (insert, delete, move, change language) and a workspace edit from an extension take the same step 2. A typed character in a cell is a text edit ([editor.md](editor.md)); `app/src/host_sync.rs::send_cell_content_change` then bumps the notebook's version and tells the host.
+
+**Invariant:** every change of cells goes through `apply_notebook_edits`. It is the one place that keeps the model, the cells' text models, the host and the running executions together. A cell pushed into `cells` directly has no text model and the host never hears of it.
+
+**Invariant:** the host hears of a notebook before the documents of its cells. `app/src/workbench/notebooks.rs::send_notebook_changes` runs before `send_host_changes` in `editors_changed`, and sends a delta from the `sent_*` fields of `Notebooks`.
+
+**Invariant:** `apply_edits` applies a batch from the last index to the first and sends one event with the next version id, as upstream's `_doApplyEdits`. Undo is the reverse: the inverse edits were computed one after another, so `run_cells_element` applies them one by one, and a redo is the original batch.
+
+## The editor and the code editors
+
+A notebook tab is an editor with scheme `vscode-notebook-editor` whose path is the notebook's URI string. Its own text model is an empty placeholder (`app/src/workbench/notebooks.rs::show_notebook`).
+
+Upstream gives every cell its own code editor widget. The port has one focused code editor per group ([workbench.md](workbench.md), "Editor groups"), so the focused cell's text model is the one the group's code editor edits: `sync_notebook_editors` writes it into `stacked_editors` of `app/src/editor.rs::EditorGroup`. The other cells draw through `app/src/workbench/editor_view.rs::embedded_code_editor`. Typing, selections, find and language features in the focused cell are the editor's own code, with no notebook branch.
+
+`app/src/notebook.rs::CellList` models the row templates of notebookCellList.ts: which cells in the render range hold a code editor. The host sees those cells, and an interactive window's input, as visible text editors (`app/src/workbench/notebooks.rs::notebook_cells`), which is what upstream's extensions and API tests observe.
+
+Undo is the window's one service ([editor.md](editor.md)). Cell edits are `UndoElement::Cells` in `app/src/editor/edit_stack.rs`, on the notebook's resource; a released notebook drops its elements.
+
+A notebook has no diff editor: upstream's `contrib/notebook/browser/diff` is not ported.
+
+## The back layer webview
+
+Outputs and markdown previews are HTML, so they draw in one webview per notebook editor that spans the list's content, as upstream's backLayerWebView.ts. GPUI draws the cell editors, toolbars and focus bars.
+
+- Only the active notebook editor has a webview. `update_notebook_views` drops the others' each render and makes it again on return, so everything the webview shows must be rebuildable from the model.
+- The webview is a native view over GPUI. It hides while a quick input, a context menu or the keybindings editor is open, and the find widget gets a hole in its clip. A GPUI element that must show over outputs needs one of the two.
+- List content coordinates are the webview's document coordinates. A cell's height depends on heights the webview measures and posts back, so a layout is final only after the webview answered.
+- Keystrokes the webview forwards are dispatched deferred (`handle_notebook_webview_event`): dispatching inside the handler updates the workbench while it is being updated.
+
+## Traps
+
+- A notebook that neither the host holds nor an editor shows is released, with its cells' text models and undo elements (`release_notebooks`). A dirty one stays. Code that keeps a notebook URI across frames must expect the model gone.
+- A scratchpad (an interactive window, or a REPL editor on an untitled notebook, without `interactiveWindow.promptToSaveOnClose`) is never `dirty` but is `modified`. Backups take a dirty notebook or a modified scratchpad; the close prompt reads `dirty`.
+- A REPL editor's last cell is its input box, and the list leaves it out: the list has one row fewer than `cells`. Go through `app/src/workbench/notebook_editor.rs::notebook_rows`.
+- The inverse of a replace needs the removed cells' text, which is not in the model. `apply_edits` names the cells in `restore` and `apply_notebook_edits` fills in their text before their text models go.
+- `update_notebook_views`, `send_notebook_visible_ranges` and `render_notebook_cell_lists` run in the workbench's `render`. Each must stay a comparison that does nothing when nothing changed ([performance.md](performance.md)).
+
+## Check a change
+
+- `port/tools/cargo-test notebook::`: the model, layout, kernels, renderers, outline.
+- `port/tools/cargo-test notebook_editor`: undo, focus, find, drag and drop, view state.
+- `port/tools/cargo-test the_interactive_window` and `port/tools/cargo-test a_dirty_notebook_backs_up`: the interactive window and backups.
+- `MOCHA_GREP="Notebook|ipynb|Interactive Window" port/tools/api-tests`: the extension API against the port ([testing.md](testing.md)).
+- `port/tools/ui-pair` with a step file of `port/fixtures/ui-pair/m17`, for example `notebook-open.json` or `notebook-output-toolbar.json`.
diff --git a/docs/packaging.md b/docs/packaging.md
new file mode 100644
index 00000000000..639a4569e90
--- /dev/null
+++ b/docs/packaging.md
@@ -0,0 +1,109 @@
+# Packaging, signing and the update feed
+
+How a build becomes the app a user downloads, and how an installed app replaces itself with a newer one. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), section "Build, packaging, release". The code is `port/tools/package-app`, `port/tools/package-linux`, `port/tools/app-files.ts` and `app/src/update.rs` with `app/src/update/install.rs`. Upstream is `build/gulpfile.vscode.ts` for the package and `src/vs/platform/update` for the service; the part Electron leaves to Squirrel.Mac is ported too. The feed format, the version rules and the publish steps are in `port/notes.md`, section "Milestone 19: product shell, privacy, accessibility, release", entries "Update feed", "Update service", "Packaging" and "Signing": this file does not repeat them.
+
+## What lives where
+
+| File | Job |
+|---|---|
+| `port/tools/app-files.ts` | The app folder, the same on every OS: `buildProduct`, `copyAppFiles`, `rebuildNativeModule`, `displayVersion`, `writeFeedEntries`. |
+| `port/tools/shipped-files.ts` | Which built-in extensions and packages ship. `port/tools/telemetry-source-check` reads the same list, so the check covers what ships. |
+| `port/tools/package-app` | macOS: the bundle around the app folder, Info.plist, the icon, signing, notarization, the update zip, the feed entries. |
+| `port/tools/package-linux` | Linux: the archive folder, the `.tar.gz`, the AppImage (`port/tools/linux/appimage`), the feed entries. |
+| `app/src/update.rs` | The update service: states, schedule, the feed check, the download. |
+| `app/src/update/install.rs` | What Squirrel.Mac does upstream: the writable check, verification, the helper that swaps the bundle. |
+| `app/src/update/unattended_restart.rs` | The scheduler that restarts to apply an update while the screen is locked (`unattendedRestartScheduler.ts`). |
+| `app/src/workbench/update.rs`, `app/src/workbench/update_title_bar.rs`, `app/src/workbench/release_notes.rs` | The commands, menu items, title bar entry and release notes over the service. |
+
+## What a package contains
+
+A package is two layers. The inner one is the app folder, which `port/tools/app-files.ts::copyAppFiles` fills the same way for every OS. The outer one is per OS.
+
+| Part | Comes from |
+|---|---|
+| The `vscrs` binary | `cargo gc build --release -p app`, from `native/target/release` or the target triple's folder for another arch. |
+| `bun` beside the binary | The host's own bun, or for another arch the pinned release that `port/tools/package-app` downloads and checks against a SHA-256 in the script. |
+| `product.json` | `port/tools/app-files.ts::buildProduct`: upstream's `product.json`, then `port/product.json`, then `version`, `quality`, `commit` and `date`. |
+| `out-exthost/bootstrap-exthost.js` | `port/tools/build-exthost`. |
+| `extensions/` | The built extensions folder that `VSCODE_GPUI_EXTENSIONS` names, filtered by `port/tools/shipped-files.ts::shippedBuiltins`, with `port/patches/extensions-*.patch` applied to the copy. |
+| `node_modules/` | The pnpm entries the host bundle and the shipped extension code load, copied whole with their relative links. |
+| Media under `src/vs/` | The upstream files the workbench reads at run time, listed in `copyAppFiles`. |
+| `ThirdPartyNotices.txt`, `LICENSE.txt` | Upstream's notices plus the licenses of what the port adds. |
+| `bin/code` (macOS), `bin/<applicationName>` (Linux) | Upstream's `code.sh` with the port's names. |
+| Info.plist, icons | The reference build's Info.plist for the document types, upstream's `resources/darwin` for their icons, `port/AppIcon.icon` compiled by `actool` for the app's. |
+
+The binary finds the app folder by its position: `app/src/product.rs::BUNDLED_APP` is the path from the bundle, and `app/src/product.rs::is_bundled` tells a package from a checkout run. `exthost/src/lib.rs::Runtime` takes the `bun` beside the executable before one on `PATH`.
+
+**Invariant:** a new file the app reads at run time is added to `copyAppFiles`. A checkout run reads it from `upstream/`, so every test passes and only the packaged app fails. `port/tools/app-smoke` starts the package from outside the checkout to catch this.
+
+**Invariant:** every native binary in a package has the package's arch. `port/tools/package-app` rebuilds a `.node` of another arch with `node-gyp` and then fails on any Mach-O that `lipo -archs` reports as another arch; `port/tools/package-linux` does the same for ELF files. There are no universal builds.
+
+**Trap:** `port/tools/package-app` fails when `out-exthost` is older than `port/tools/build-exthost`, `port/product.json` or a `port/patches/src-*.patch`. It compares with the port's inputs only, so after a change in `upstream/` run `port/tools/build-exthost` yourself.
+
+## Signing and notarization
+
+All of it is in `port/tools/package-app`, in this order. The order is the contract: each step seals what the earlier ones wrote.
+
+1. Sign every Mach-O in the app folder (native modules, ripgrep), with the hardened runtime and no entitlements.
+2. Sign `bun` with the entitlements `allow-jit`, `allow-unsigned-executable-memory` and `disable-library-validation`: JavaScriptCore needs the first two, and bun loads native modules signed by others.
+3. Sign the bundle, with the same entitlements.
+4. With `NOTARIZE=1`: zip, `notarytool submit --wait`, `stapler staple`.
+5. `codesign --verify --deep --strict`. Only when it passes: make the update zip and write the feed entries. The zip is made with `ditto --norsrc --noextattr`: without them it holds `._` files, other unzippers write them into the bundle, and the seal breaks ("Vscrs is damaged"). The script fails when the zip holds one.
+6. `spctl -a`, as the exit code. Where Gatekeeper assessments are disabled it accepts any bundle, so the script reports "not assessed" and exits 3 instead of a pass.
+
+What it needs, by name. No private key and no password is in the repository; `port/notes.md`, "Signing", names the identity and its Team ID:
+
+| Name | What it is |
+|---|---|
+| `IDENTITY` | Environment variable: the name of a Developer ID Application identity. Its private key is in the login keychain of the build machine. Unset means ad-hoc signing. |
+| `vscrs-notary` | A `notarytool` keychain profile on the build machine, stored once with `xcrun notarytool store-credentials`. It holds the Apple ID, the team and an app-specific password. |
+| `FOREIGN_IDENTITY` | Environment variable of `port/tools/update-check` only: a second signing identity, for the update that must be refused. |
+
+No workflow in `.github/workflows` signs, notarizes or publishes, and none reads a repository secret: they use only the run's own `github.token`.
+
+**Trap:** the login keychain stays locked in an ssh session, so codesign with a Developer ID fails there with `errSecInternalComponent`. `inGuiSession` in `port/tools/package-app` writes the commands to a `.command` file that Terminal opens in the GUI session and waits for its exit code. A build machine with no user logged in at the screen cannot sign with a Developer ID.
+
+**Trap:** an ad-hoc signed app can be packaged and started, but it can never update: `app/src/update/install.rs::verify_signature` refuses when the installed bundle has no Team ID. A test of the update path needs a Developer ID.
+
+## Update check and apply
+
+There is one `app/src/update.rs::UpdateService` per app, created with the first window by `app/src/update.rs::service`; upstream's lives in the main process. Windows subscribe to its `State` events. The decisions are upstream's (`abstractUpdateService.ts`, `updateService.darwin.ts`); the release channel is a port addition.
+
+The service is `Disabled` unless the app runs from a package and its `product.json` has `updateUrl`, `commit` and `date`. Only the packaging scripts write `commit` and `date`, so a checkout run never checks.
+
+What must pass before the installed app is replaced, in order:
+
+1. The bundle and its parent folder are writable and the app is not translocated (`app/src/update/install.rs::check_writable`), before the feed is read.
+2. The feed entry is newer than the running build and has a SHA-256 hash, and its URL is https, or http on a loopback host (`app/src/update.rs::parse_feed`).
+3. The downloaded zip has that hash, and holds exactly one `.app` (`app/src/update/install.rs::verify_download`).
+4. The bundle's signature is valid and satisfies the installed bundle's designated requirement, with the same identifier and Team ID (`verify_signature`).
+5. After the app quit, the helper checks 4 again on the staged bundle, then swaps (`app/src/update/install.rs::apply_update`).
+
+**Invariant:** trust comes from the installed app's own signature, not from the feed. The feed and the hash in it are served from the same place as the zip, so the hash proves only that the download is whole. Step 4 is what stops a foreign build, and it must stay a check against the installed bundle.
+
+**Invariant:** the helper verifies again because the staged bundle waits in a cache folder the user can write, for as long as the app keeps running. Do not pass the result of step 4 to the helper instead.
+
+**Invariant:** a failed update leaves the installed app as it was. `app/src/update/install.rs::replace` moves the installed bundle aside first, and on any failure after that moves it back. A helper started with `--relaunch` starts the app again whether the swap passed or not.
+
+The helper is the app's own executable: `app/src/main.rs` hands `app/src/update/install.rs::APPLY_UPDATE` to `apply_update` before it starts anything else. `spawn_helper` puts it in its own process group so it outlives the app. It starts on app quit, from `Ready` (a plain Quit, no relaunch) and from `Restarting` (Restart to Update). Its log is `ShipIt_stderr.log` in `app/src/update/install.rs::shipit_dir`.
+
+**Trap:** the staging folder is removed at startup and when a check or a download fails. A `Ready` update that was not installed on quit is downloaded again.
+
+**Trap:** the feed's platform is `exthost/src/gallery.rs::CURRENT_TARGET_PLATFORM`, fixed at compile time: an x64 build under Rosetta stays on the x64 feed. Linux and Windows have no apply path. A found update waits in `AvailableForDownload`, and Download opens `downloadUrl` or the archive's link in the browser (`updateService.linux.ts`). `spawn_helper` on Windows only fails. No feed names the AppImage.
+
+## What a release needs
+
+A release is made by hand; `port/notes.md` has the steps ("Update feed", "Publishing a release"). What must be true:
+
+- `release` in `port/product.json` is bumped, and `port/tools/build-exthost` ran after that.
+- One run of `port/tools/package-app` per arch, with `IDENTITY` and `NOTARIZE=1`, on a machine with a GUI session. `PRERELEASE=1` makes an Insiders build; `TAG` must be the tag the files are uploaded to, because the feed entry's URL names it.
+- A stable release writes both feed entries, a pre-release only the pre-release one (`port/tools/app-files.ts::writeFeedEntries`). Both channels read fixed URLs, so an entry uploaded to the wrong release is an update nobody sees.
+- `.github/workflows/linux.yml` builds the Linux package as an artifact; it does not upload to a release. Publishing a release starts `.github/workflows/update-flake.yml` and `.github/workflows/update-issue-release-options.yml`, which commit to the default branch.
+
+## Check a change
+
+- `port/tools/cargo-test -p app update::` runs the feed, state and install tests; `a_failed_move_in_puts_the_installed_app_back` is the one for the swap.
+- `port/tools/studio 'port/tools/package-app'` makes an ad-hoc signed package. Its exit code is `codesign --verify`'s, else `spctl -a`'s: 3 with a good signature on the Studio, where Gatekeeper assessments are disabled, so read the `codesign --verify ok` line.
+- `port/tools/studio --lane 'port/tools/app-smoke'` starts that package from outside the checkout.
+- `port/tools/update-check` is the end to end check: it packages an old build, a new one, a pre-release and a foreign-signed one, serves them with `port/tools/update-feed`, and runs each update and each refusal. Its header has the two commands; it needs `IDENTITY` and `FOREIGN_IDENTITY`.
+- `port/tools/check-licenses` after a new crate, `port/tools/telemetry-source-check` after a change to what ships.
diff --git a/docs/performance.md b/docs/performance.md
index a2e18d34ce4..2fb7c7701b0 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -39,7 +39,7 @@ The margins come from the spread of the samples in `port/results/benchmark.md`.
### No budget yet
-Terminal throughput, terminal typing latency, time to open a large file, search time and memory with many editors open have no number and no gate. A budget for one of them starts with a measurement in `port/notes.md`.
+Terminal throughput, time to open a large file, search time and memory with many editors open have no number and no gate. A budget for one of them starts with a measurement in `port/notes.md`.
### Zed
@@ -79,7 +79,7 @@ The machine is shared, and its load changes a time by about 30%. Check the load
|---|---|---|
| Whole-app budgets | `port/tools/bench > run.tsv`, then `bun port/tools/bench-check.ts run.tsv` | A median is over its budget by more than its margin |
| Typing | `cargo gc test --release -p app -- --ignored typing_latency_on_a_large_file --nocapture` | p95 per edit is 16 ms or more |
-| Scroll frames | `cargo gc test --release -p app -- --ignored scroll_frame_time --nocapture --test-threads=1` | A median or p95 is 8 ms or more |
+| Scroll frames | `cargo gc test --release -p app -- --ignored scroll_frame_time --nocapture --test-threads=1` | A median or p95 is 8 ms or more. The same filter runs `app/src/workbench/scroll_frame_time.rs::terminal_typing_frame_time`: p95 per frame is 16 ms or more |
| Render counts | `port/tools/cargo-test part_view` | A part draws that did not change |
`port/tools/bench-check.ts` reads the output of `port/tools/bench` and `port/budgets.json`. It prints each metric with its limit and exits 1 on a failure. `port/tools/bench-check.test.ts` shows it red on a planted regression.
diff --git a/docs/platform.md b/docs/platform.md
new file mode 100644
index 00000000000..4355494b126
--- /dev/null
+++ b/docs/platform.md
@@ -0,0 +1,79 @@
+# Platform glue per OS
+
+This file covers the code that calls an OS API or behaves differently per OS: where it lives in `app/src` and `exthost/src`, the shape a per-OS module has, how its tests run on a machine of another OS, and how a change is checked on an OS the author is not on. It goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), section "Platform glue per OS". Upstream has no single folder for this: the port follows Electron's and Chromium's per-OS code behind `src/vs/platform/native/electron-main/nativeHostMainService.ts`, and `src/vs/base/common/platform.ts` for the OS constants. Which OS has which feature is the ledger's (the "M23 Linux" and "M24 Windows" rows of `port/ledger.md`), not this file's.
+
+## The shape of a per-OS module
+
+`app/src/power.rs` is the small example. The rows of the map below that have a file for each OS have the same shape; the other rows keep the code of one or two OSes in the portable file.
+
+- The portable module holds what upstream holds in TypeScript: the request names, the ids, the state (`app/src/power.rs::PowerSaveBlockers`, `app/src/power.rs::request`). It has no OS call.
+- Each OS has one file beside it, named after the OS: `app/src/power/macos.rs`, `app/src/power/linux.rs`, `app/src/power/windows.rs`. The portable module declares each with `#[cfg(target_os = "...")] mod` and re-exports the same names from the one that is built.
+- The contract between them is a set of plain functions with one signature on every OS (`system_idle_time`, `on_battery_power`, `watch`), plus a type alias when the OS handle differs: `Assertion` is a `u32` on macOS, an inhibitor on Linux, a request handle on Windows, and `PowerSaveBlockers` stores it without knowing which. There is no trait and no `dyn`: one OS is built, so a direct call is enough.
+- An OS that has no such feature still has the function, with the answer Electron gives there (`app/src/power/windows.rs::thermal_state` returns `unknown`, as Electron has a thermal state on macOS only). The caller has no `cfg`.
+- Events leave the OS file through a channel the caller passes in (`watch(events: UnboundedSender<PowerEvent>)`). The OS callback, which may run on any thread, only sends; the workbench reads the channel on the main thread.
+
+When the split is small, the OS code stays in the portable file as `cfg` functions of one name: `app/src/metered_connection.rs::watch` has three bodies, `app/src/clipboard.rs` three `mod pasteboard` blocks.
+
+`cfg(unix)` and `cfg(windows)` are for what macOS and Linux share against Windows: the pty (`app/src/terminal/pty.rs` against `app/src/terminal/pty/conpty.rs`), sockets against named pipes, signals, file modes. `cfg(target_os)` is for an OS API.
+
+## What lives where
+
+| Behavior | Portable module | macOS | Linux | Windows |
+|---|---|---|---|---|
+| Power monitor and sleep blockers | `app/src/power.rs` | CoreGraphics, IOKit | D-Bus: logind, UPower, ScreenSaver | Power requests |
+| Message box with a checkbox | `app/src/dialog.rs` | NSAlert sheet, in the module itself | GTK dialog, `app/src/dialog/linux.rs` | Task dialog, `app/src/dialog/windows.rs` |
+| Open and save dialogs | `app/src/file_dialog.rs` | NSOpenPanel, NSSavePanel | xdg-desktop-portal FileChooser | Common item dialogs |
+| Keyboard layout | `app/src/keyboard_layout.rs` | UCKeyTranslate | The X server's XKB keymap | `app/src/keyboard_layout/windows.rs` |
+| Policies | `app/src/policy.rs` | CFPreferences | A policy file | `app/src/policy/windows.rs` |
+| System-wide keybindings | `app/src/system_wide_keybindings.rs` | Carbon hot keys | X11 key grabs or the GlobalShortcuts portal | `app/src/system_wide_keybindings/windows.rs` |
+| Webview | `app/src/webview.rs` | WKWebView | WebKitGTK | WebView2 |
+| HTTP requests and proxy | `exthost/src/request.rs` | NSURLSession | curl, `exthost/src/request/linux.rs` | The same curl code, with the proxy from WinHTTP |
+| Secrets | `exthost/src/main_thread_secret_state.rs` | Keychain | Secret Service | Credential Manager |
+| Terminal process | `app/src/terminal/pty.rs` | `openpty` and a child in a new session | The same code | `app/src/terminal/pty/conpty.rs` |
+| IPC transport | `exthost/src/lib.rs` | Unix socket | Unix socket | `exthost/src/pipe.rs` |
+
+Shared helpers on GPUI's native window: `app/src/dialog.rs::ns_window` (macOS), `app/src/x11.rs` (Linux: the X window id, window manager states), `app/src/win32.rs` (Windows: the HWND). Smaller per-OS branches sit inline in `app/src/main.rs` (the app root, the console), `app/src/workbench/host.rs` (always on top), `app/src/workbench/accessibility.rs` (screen reader and reduced motion), `app/src/accessibility_signals.rs` (the sound player), `app/src/diagnostics.rs` (machine info) and `app/src/app_icon.rs` (the Dock icon, macOS only). `rg -c 'target_os' native/crates/app/src native/crates/exthost/src` lists every file.
+
+Why each OS uses the API it uses is in `port/notes.md`, "Milestone 23: Linux build" and "Milestone 24: Windows build": the rule is Electron's choice for that OS, then Chromium's, each entry naming the file it follows.
+
+## The OS as a value
+
+A behavior that depends on the OS but calls nothing of it is not `cfg` code. It takes the OS as a parameter, so one test run on one machine checks every branch.
+
+- `app/src/keybindings.rs::Os` is upstream's `OperatingSystem`, and `app/src/keybindings.rs::OS` the build's value. Labels, accelerators, the default table (`app/src/keybindings.rs::default_table`) and the `isMac`, `isWindows`, `isLinux` context keys (`app/src/contextkey.rs::constant_in`) take an `Os`.
+- `app/src/uri.rs::fs_path_on` takes `windows: bool`; `app/src/uri.rs::fs_path` passes the build's.
+- The pure half of an OS file moves up into the portable module under `#[cfg(any(target_os = "windows", test))]`: `app/src/dialog.rs::windows_mnemonic`, `app/src/dialog.rs::task_dialog_answer`, and the whole of `exthost/src/request/proxy_rules.rs`. It is built on Windows and in every test build, so the macOS test run covers it and no release build of another OS carries it.
+
+**Invariant:** `cfg(target_os)` and `cfg!(...)` are for code that cannot compile or cannot run on the other OS. A rule about labels, paths, button order or key names reads `Os`. A rule behind `cfg` is tested only on its own OS, and Windows tests do not run on a push.
+
+## FFI and unsafe
+
+[memory-safety.md](memory-safety.md) owns the rules, the inventory and the review list. Three things follow from the layout here:
+
+- An `unsafe` block goes in the OS file, and the functions the portable module imports are safe to call. Of the portable modules in the map, two have `unsafe`, each as one OS's side: `app/src/dialog.rs`, whose macOS code is inline, and `app/src/terminal/pty.rs`, the Unix side. Outside the map, a module with inline `cfg` functions holds its own: `app/src/clipboard.rs`, `app/src/metered_connection.rs`.
+- The binding crates of each OS are in the `[target.'cfg(target_os = ...)'.dependencies]` tables of `native/crates/app/Cargo.toml` and `native/crates/exthost/Cargo.toml`: `objc2` and its framework crates on macOS, `windows-sys` for Win32 and `windows` for COM on Windows, `zbus`, `ashpd`, `gtk` and `x11rb` on Linux. Where GPUI already builds a crate (`windows`, `zbus`, `x11rb`, `xkbcommon`, `oo7`), the version is GPUI's, as the comments in those tables say, so the binary links one copy. A new crate for an API one of these covers needs a reason in `port/notes.md`.
+- An API with no binding is declared in an `extern "C"` block in the file that uses it, as `app/src/metered_connection.rs` does for `nw_path_monitor_create`.
+
+## Traps
+
+- A new function in the contract needs a body in all three OS files in the same change. The author's build passes without them; the other two fail to compile, and only the cross builds below show it.
+- A name that one OS exports alone needs `cfg` at each call site: `app/src/power/linux.rs::animations_disabled` has no macOS or Windows twin, and its caller in `app/src/workbench/accessibility.rs` is under `cfg(target_os = "linux")`. Prefer a function on every OS.
+- Linux is two session types. GTK code (the webview, the message box) runs only when `app/src/webview/linux.rs::supported` is true: GPUI's X11 session, on the main thread. On Wayland and in unit tests the caller takes the fallback, so each GTK feature needs one. `app/src/x11.rs::window_xid` returns none for a Wayland window.
+- GTK has no loop of its own here: `app/src/webview/linux.rs::pump_gtk` runs its events from GPUI's loop. GTK lives on the thread that initialized it, GPUI's main thread, so every GTK call is made there.
+- Tests run in parallel on a developer's machine, so a test build must not touch machine state. `app/src/clipboard.rs` replaces its `pasteboard` module with a per-thread one under `cfg(test)`, and `app/src/file_dialog.rs` uses GPUI's path prompts in tests. A new glue module that writes shared state (the pasteboard, global hot keys, the Dock) needs the same switch.
+- `app/src/keybindings.rs::OS` has no Linux value: a Linux build reads `Macintosh`. Code that must tell Linux from macOS today uses `cfg`, and the M23 rows of the ledger name what moves when the value exists.
+- A Windows child process that is a console program opens a console window unless it is started through `exthost/src/lib.rs::hide_console`.
+- An OS file may be a `shortcut:` stub that compiles and answers a constant (`app/src/power/windows.rs` for idle time and battery). Read the `//!` header of the OS file before relying on it.
+
+## Check a change
+
+Run each from the checkout root. The macOS commands build on the Studio through `port/tools/studio`.
+
+- The portable half and the host tests of the Windows and Linux pure parts, on macOS: `port/tools/cargo-test power::tests`, `port/tools/cargo-test dialog::tests`, `port/tools/cargo-test file_dialog::tests`, `port/tools/cargo-test system_wide_keybindings`, `port/tools/cargo-test -p exthost proxy_rules`.
+- Linux compiles and its tests pass: `port/tools/linux-build 'cd native && cargo gc check -p app -p exthost --all-targets'`, then the module's tests in the same container, under Xvfb when they open a window (`dialog::linux`, the keyboard layout, the X11 key grabs).
+- Linux starts: `port/tools/linux-build port/tools/linux/smoke`.
+- Windows compiles: `port/tools/windows-build 'cargo gc xwin check -p app -p exthost --all-targets --target x86_64-pc-windows-msvc'`. This is a compile check only; nothing runs.
+- The SAFETY gate per OS: the three commands of [memory-safety.md](memory-safety.md), "The checks".
+- CI, after the push. `.github/workflows/ci.yml` runs on each push to `main` and each pull request: clippy's SAFETY check on macOS arm64 and Linux x64 and arm64, a smoke start on macOS arm64 and Linux x64, and `cargo test --workspace` on macOS arm64 and, under `xvfb-run`, on Linux x64 and arm64. The Linux test jobs are `continue-on-error`, so a red one does not fail the run: open the job and read it.
+- Windows tests run only in `.github/workflows/windows.yml`, started by hand (`gh workflow run windows.yml --ref <branch>`): a release build and `cargo test -p app -p exthost` on x64 and arm64. Run it for every change to a `windows.rs` file or to code under `cfg(windows)`.
+- `.github/workflows/linux.yml` builds and uploads the Linux x64 package by hand. It runs no tests.
diff --git a/docs/recipes.md b/docs/recipes.md
new file mode 100644
index 00000000000..7a1580142ce
--- /dev/null
+++ b/docs/recipes.md
@@ -0,0 +1,76 @@
+# Recipes
+
+The steps that are the same in every area, in the order they run. A recipe that belongs to one area is in that area's document, and the table at the end points to it.
+
+## Start a task
+
+1. Find the unit: `rg -n '^\| workbench/contrib/<name> ' port/ledger/units`. Its row has the milestone, the status, the open gaps and the narrowest check.
+2. Read the section of `port/notes.md` that the row or its milestone names (`rg -n '^## ' port/notes.md` lists the sections). A decision or a trap there wins over what looks right in the code.
+3. Read the upstream files of the unit in `upstream/src/vs`. They are the specification, tests included.
+4. Read the document of each area the change touches: [README.md](README.md), "Change touches, read".
+5. Look for what you need in "Reuse before adding" in the same file before you write a helper.
+6. Name the check that will fail without your change, before the first edit.
+
+## Close a gap
+
+A gap is one entry of a unit's gaps cell: `[class size] where: what`. `port/ledger.md` explains the classes under its "Units" heading.
+
+1. Class 3, a behavior gap: port upstream's behavior and its test. The test fails without the fix. Run it once without the fix to see it fail.
+2. Class 1, stale: prove with a named test that the behavior is already right. Then delete the `shortcut:` comment the gap points to.
+3. Class 2, a platform limit: do not work around it. It is closed only by a line of the owner in `port/notes.md`, "Accepted platform differences".
+4. In the commit that closes the gap, remove the entry from the cell. When the last class 3 gap of a row goes, the row turns `verified` and its evidence cell names the check.
+5. Run `bun port/tools/ledger-check.ts`. After a status change, run `bun port/tools/readme-coverage.ts` too: it rewrites the coverage block of `README.md`.
+
+A new difference you find and do not fix is a new gap entry in the same commit, with a `shortcut:` comment at the code. A difference with no entry is a bug in the ledger.
+
+## Add a command
+
+1. Use upstream's command id. Find where upstream registers it (`rg "'<id>'" upstream/src/vs`) and read its precondition, its keybinding and its menus.
+2. Register the handler in `Workbench::new` with `app/src/commands.rs::register`.
+3. The default keybinding is already there if upstream has one: the tables in `app/src/keybindings` are generated from the reference by `port/tools/default-keybindings`. Do not edit them by hand and do not handle the key in an element.
+4. A menu entry is data in `app/src/menus.rs`, under upstream's menu id, group and order.
+5. A `when` clause reads context keys. A new key is set in `app/src/workbench/keyboard.rs::key_context`, under upstream's name, from state that is already computed.
+6. Test it through `app/src/commands.rs::execute_command` in a `#[gpui::test]`, and through the key when the keybinding has a `when` clause.
+
+## Answer a host call
+
+A `MainThreadX.$method` that an extension reaches through the `vscode` API.
+
+1. Read upstream's `src/vs/workbench/api/browser/mainThreadX.ts` for the method and `extHost.protocol.ts` for its types.
+2. Choose the path, as [extension-host.md](extension-host.md) explains, "Host calls the port answers": the session thread for state that needs no window, `Blocking` for an answer that depends on the document state at that moment, `Forwarded` for the rest.
+3. Add the arm in `app/src/main_thread_commands.rs::route`, or in the session for path 1. Replace the method's `not_ported` arm if it has one, and remove the method from the gaps of its main thread class in the ledger.
+4. Convert positions at the boundary only: chars in the port, UTF-16 units in the host.
+5. Check with `port/tools/api-tests`: the suite of `upstream/extensions/vscode-api-tests` that calls the method.
+
+## Hit every surface
+
+A behavior has more than one way in. Before the report, go through the list and say for each line "done", "not applicable" or the gap entry you wrote.
+
+- Keyboard, mouse and touchpad scroll.
+- The menu bar, the context menu, the Command Palette, and `vscode.commands.executeCommand` from an extension.
+- macOS, Linux and Windows: a per-OS file has a sibling for each OS ([platform.md](platform.md)).
+- The four theme kinds: dark, light, High Contrast and High Contrast Light.
+- A screen reader: role, label and announcement ([accessibility.md](accessibility.md)).
+- State after a restart: storage under upstream's key, and what the extension host gets after it restarts.
+- An editor in an auxiliary window and in a second editor group.
+
+## Ship it
+
+1. The checks of [testing.md](testing.md), "Before a report or a commit".
+2. The ledger row, the gap entries and the documents change in the same commit as the code. After a rename or a move: `bun port/tools/docs-check.ts`.
+3. Commit messages follow Conventional Commits, `type(scope): subject`, with the scopes of `git log --oneline -10`.
+4. A pull request goes through `.agents/skills/pr/SKILL.md`. The remote is `vscrs`. A worker's branch lands through `.agents/skills/port-crew/SKILL.md`.
+5. The report pairs each requirement with the command that proves it and its real result. A number in the report is measured after the last edit.
+
+## Recipes in the area documents
+
+| To | Read |
+|---|---|
+| Add a workbench feature | [workbench.md](workbench.md), "Add a workbench feature" |
+| Add a setting or a stored key | [settings-and-storage.md](settings-and-storage.md), "Add a setting or a stored key" |
+| Add an `unsafe` block | [memory-safety.md](memory-safety.md), "Add an unsafe block" |
+| Give a new view its accessibility | [accessibility.md](accessibility.md), "What a new view provides" |
+| Measure a hot path | [performance.md](performance.md), "How to measure" |
+| Write a workbench test | [testing.md](testing.md), "Workbench tests" |
+| Compare with the reference | [testing.md](testing.md), "Comparing with VS Code" |
+| Write or change a document | [README.md](README.md), "Write a document" |
diff --git a/docs/scm.md b/docs/scm.md
new file mode 100644
index 00000000000..2cbf637c4d1
--- /dev/null
+++ b/docs/scm.md
@@ -0,0 +1,72 @@
+# Source control
+
+Source control is the model of the repositories that extensions register, the three views that draw it (Changes, Graph, Repositories), and the quick diff in the editor gutter. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md). Upstream is `src/vs/workbench/contrib/scm` with `src/vs/workbench/api/browser/mainThreadSCM.ts` and `mainThreadQuickDiff.ts`. The diff editor, the multi diff editor and the merge editor have their notes in `port/notes.md`, "Milestone 14: source control and diff".
+
+## What is where
+
+- `app/src/scm.rs`: the model. `app/src/scm.rs::Scm` is the list of `Provider`s in registration order, each with its `Input`, its `Group`s and their `Resource`s. No GPUI.
+- `app/src/scm_history.rs`: the graph of scmHistory.ts. `to_history_item_view_models` is upstream's `toISCMHistoryItemViewModelArray`: history items in, swimlanes and colors out. No GPUI, upstream's tests beside it in `app/src/scm_history/tests.rs`.
+- `app/src/workbench/scm_view.rs`: `ScmView` (the model plus the view's state, the `scm` field of the workbench), `handle_scm_request`, the Changes view, the status bar entries and the activity badge.
+- `app/src/workbench/scm_tree.rs`: list and tree mode of the Changes view. `app/src/workbench/scm_actions.rs`: the input history and the title menus. `app/src/workbench/scm_repositories_view.rs`: the Repositories view and the artifacts. `app/src/workbench/scm_graph_view.rs`: the Graph view and its requests.
+- `app/src/workbench/editor_view/quick_diff.rs`: the quick diff model per file and its gutter, ruler and minimap marks. `app/src/workbench/editor_view/quick_diff_widget.rs`: the peek under a change.
+
+## Who owns what
+
+The extension (git) runs in the extension host and owns the truth: which repositories exist, which files changed, the history. The app holds a mirror and never computes a repository's state itself. There is no git code in the app: upstream's `MainThreadGitExtension`, `platform/git` and `contrib/git` are removed, because they serve chat and agent sessions.
+
+The mirror keeps the host's DTOs as `serde_json::Value` wherever the app only hands them back: a resource's `uri` and `command`, a provider's `root_uri`, `action_button` and `status_bar_commands`, a history item ref. Only what a view reads is a typed field.
+
+The app owns the view state, which the host learns of in three calls: the selected repository (`$setSelectedSourceControl`), the input box text (`$onInputBoxValueChange`) and a clicked resource (`$executeResourceCommand`).
+
+## From a provider to the view
+
+1. The extension calls a `MainThreadSCM` method. The session forwards it to the main thread ([extension-host.md](extension-host.md)), and `app/src/main_thread_commands.rs::handle_host_request` hands it to `app/src/workbench/scm_view.rs::handle_scm_request`.
+2. `app/src/scm.rs::apply` changes the model and returns a `ScmChange`: `None` (unknown provider or method), `Registered` or `Changed`.
+3. `handle_scm_request` does what upstream's listeners do for that method: it bumps the quick diff generation, opens or drops the input box model, moves the shown and focused repository, refreshes the status bar entries, and calls `cx.notify()`.
+
+Two methods never reach `apply`, because they carry no state, only "ask again": `$onDidChangeHistoryProviderHistoryItemRefs` refreshes the Graph (a silent change of a scrolled Graph only marks it outdated) and `$onDidChangeArtifacts` reloads the artifacts.
+
+The Graph, the artifacts and the quick diff originals are pulled, not pushed: the app asks `ExtHostSCM` (`$provideHistoryItems`, `$provideHistoryItemChanges`, `$provideArtifacts`, `$provideOriginalResource`) and draws the answer. The Graph reloads when `app/src/workbench/scm_graph_view.rs::update_scm_graph` sees another active repository or other current refs, and only while its pane is expanded.
+
+**Invariant:** `$spliceResourceStates` carries several splices per group, whose indices all refer to the list before the call. `app/src/scm.rs::splice_resource_states` applies them last first. Applied in order, the second splice lands on the wrong rows.
+
+**Invariant:** a late answer checks `generation` of `app/src/workbench/scm_graph_view.rs::ScmGraph` before it writes. `reset` bumps it, so a page asked for the repository of before is dropped.
+
+## Three repositories
+
+scmViewService.ts has three notions, and the port keeps them apart in `app/src/workbench/scm_view.rs::ScmView`:
+
+- `visible`: the repositories the Changes view shows, picked in the Repositories view.
+- `focused`: the repository whose input the input box edits. The host hears of it as the selected source control.
+- `active`: the repository of the active editor or the focused one, whichever changed last (`active_scm_provider`). The Graph and the status bar entries follow it.
+
+Which repositories show after a restart is `scm:view:visibleRepositories` in workspace storage. `store_scm_view_state` writes it only after `finished_loading` turned true, 5 s after the last repository came or went, as upstream's `eventuallyFinishLoading`. Stored earlier, a window that closes while git still registers repositories forgets the ones not yet there.
+
+## The editor and the diff
+
+**The input box is a text model.** `$registerSourceControl` carries `inputBoxDocumentUri`, and `scm_registered` opens a text model there with language `scminput`, so the host sees the commit message as a document. The model has no tab and no host reference: `app/src/workbench/host_requests.rs::release_host_models` keeps the ones `scm_input_models` lists. Without that it dropped them on its first run and the next commit panicked. A change of the input goes through `edit_scm_input`, which updates the provider, the host and the model together.
+
+**A clicked resource.** A resource whose command is `_workbench.open` or `_workbench.diff` runs it in the app. Any other command goes back to the host with `$executeResourceCommand`. A history item's change opens `_workbench.diff` with both sides. The multi diff editor of a resource group (`_workbench.openScmMultiDiffEditor`) takes the group's new files on every `$spliceResourceStates` through `app/src/workbench/editor_view/multi_diff_editor_view.rs::scm_group_resources_changed`.
+
+**The quick diff.** For each visible file, `app/src/workbench/editor_view/quick_diff.rs::update_quick_diff` asks every provider whose root holds the file for an original URI, loads the original through the host's `resolveTextContent` as a text model, and diffs the two models with the `diff` crate (`diff/src/computer.rs`). The source controls' primary and secondary quick diffs and the providers of `MainThreadQuickDiff` go through the same path.
+
+- `update_quick_diff` runs in the workbench's `render`. It asks the host only when `QuickDiffs::generation` moved or an original's model is gone, and diffs only when a model version moved. A new early exit must keep both checks cheap ([performance.md](performance.md)).
+- Every `MainThreadSCM` request bumps the generation, except `$setInput*`, `$showValidation*` and the two that never reach `apply`: typing a commit message must not ask for every original again.
+- The diff runs on the main thread, capped at 1000 ms (`MAX_COMPUTATION_TIME_MS`), without moves and without subword extension.
+
+## Traps
+
+- git names the ref in the query of a `git:` URI. A text model keys on scheme and path, so a non-file URI's query is kept after a `?` inside the model's path, which keeps two refs of one file apart. Code that needs the file's path or name calls `app/src/editor.rs::split_query` first. `files/src/lib.rs::Resource` carries the query too, because git's file system provider fails without it.
+- `ScmChange::None` returns before the view refresh. A new method added to `apply` must return `Changed`, or the view keeps the old state until something else notifies.
+- A provider with `hidden` set is in `Scm::providers` and in the quick diff, and left out of the views' lists. Views read `scm_repositories`, not the model's list.
+- `Provider::count` is the provider's own count when it sent one, else the sum of the resources. A view that counts the resources itself disagrees with git, which leaves untracked files out of its count by setting.
+- The input box value has three writers: the user (`edit_scm_input`), the host (`$setInputBoxValue`) and the stored input history at registration (`app/src/workbench/scm_actions.rs::restore_scm_input`). All end in `sync_scm_input_model`. Code that writes `provider.input.value` directly leaves the text model and the host stale.
+
+## Check a change
+
+- `port/tools/cargo-test groups_and_splices`: the model.
+- `port/tools/cargo-test scm_history`: upstream's graph tests.
+- `port/tools/cargo-test scm`: the views, the input, the Graph requests (matches `scm_view`, `scm_actions`, `scm_graph_view`).
+- `port/tools/cargo-test quick_diff`: providers, changes, the peek. `port/tools/cargo-test -p diff fixture` when the diff itself changed.
+- `port/tools/ui-pair` with `port/fixtures/ui-pair/m14/quick-diff-peek.json` for the look of the peek ([testing.md](testing.md)).
+- `port/tools/extension-tests git` runs git's own tests against the port; the counts to match are in `port/results/scm.md`.
diff --git a/docs/settings-and-storage.md b/docs/settings-and-storage.md
new file mode 100644
index 00000000000..fdcd15bdec4
--- /dev/null
+++ b/docs/settings-and-storage.md
@@ -0,0 +1,105 @@
+# Settings, storage, profiles and keybinding tables
+
+Settings are the `config` crate, storage and profiles are the `storage` crate, and the keybinding tables are `app/src/keybindings.rs`. This file covers how they are layered, where each lives on disk, how a change reaches the window, and how to add a setting or a stored key. It goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md) ("State and persistence"). Upstream is `src/vs/platform/configuration`, `src/vs/workbench/services/configuration`, `src/vs/base/parts/storage`, `src/vs/platform/userDataProfile` and `src/vs/workbench/services/keybinding`. Key dispatch is in [workbench.md](workbench.md), the host's view of settings and storage in [extension-host.md](extension-host.md).
+
+## What is where
+
+- `config/src/registry.rs::Registry`: every registered setting with its schema, scope and default. Upstream's own settings are data: `config/core-settings.json`, dumped from the reference's registry by `port/tools/dump-settings`, with `config/core-settings-stable.json` for what a stable build registers differently. The port's own settings are `config/port-settings.json`. Two sets are registered in code: the port's `update.releaseChannel` (`config/src/registry.rs::core_of_quality`) and upstream's Windows-only UNC settings (`config/src/registry.rs::windows_settings`). Extension settings come from each `contributes.configuration` and `contributes.configurationDefaults`.
+- `config/src/model.rs::ConfigurationModel`: one layer, its parser with the scope filter (`config/src/model.rs::ParseFilter`), and `config/src/model.rs::compare`, which names the keys a reload touched.
+- `config/src/configuration.rs::Configuration`: the layers of one window and the merged view.
+- `config/src/service.rs::Settings`: loads the files into layers, reloads them, writes values as `configurationEditing.ts` does.
+- `config/src/json.rs` and `config/src/json_edit.rs`: JSON with comments, and the minimal text edits that set one value. A write of one value into a settings or keybindings file goes through `config/src/json_edit.rs::set_property`, so comments and layout survive. A write of the whole `tasks`, `launch` or `mcp` key into its own file replaces the file's text (`config/src/service.rs::write`).
+- `config/src/policy.rs`: the policy layer. `app/src/policy.rs` reads the values from the OS.
+- `storage/src/lib.rs::Storage`: one `state.vscdb`. `storage/src/state.rs::FileStorage`: `storage.json`. `storage/src/profiles.rs::Profiles`: the profiles and their workspace associations.
+- `app/src/workbench/configuration.rs`: the watchers and the workbench's change listeners. `app/src/user_data_profile.rs` and `app/src/workbench/user_data_profile.rs`: the profile of a window and the switch.
+- `app/src/keybindings.rs`: the parser, `app/src/keybindings.rs::Resolver`, and the default, extension and user rules. `app/src/keybinding_editing.rs` computes the edited text of `keybindings.json`, and `app/src/workbench/keybindings_editor_view.rs::write_keybindings_file` writes it.
+
+## Layers and precedence
+
+`config/src/configuration.rs::consolidated` merges, later wins: defaults, application, user, workspace, the folder that holds the resource, then the `[language]` block of that merge, then policy over everything. The port has no remote and no in-memory layer; `config/src/configuration.rs::to_data` still sends the remote one empty (`userRemote`), in upstream's shape.
+
+| Layer | File | Scopes it accepts |
+|---|---|---|
+| Defaults | the registry | all |
+| Application | the default profile's `settings.json`, only in a profile with its own settings | `APPLICATION_SCOPES`, plus the keys in `workbench.settings.applyToAllProfiles` |
+| User | the profile's `settings.json`, `tasks.json`, `mcp.json` | all in the default profile, `PROFILE_SCOPES` in another |
+| Workspace | `settings`, `launch`, `tasks` of the `.code-workspace` file; in a folder window, the folder's layer | `WORKSPACE_SCOPES` |
+| Folder | `settings.json`, `tasks.json`, `launch.json`, `mcp.json` of the folder's configuration folders | `FOLDER_SCOPES` in a workspace, `WORKSPACE_SCOPES` in a folder window |
+| Policy | CFPreferences on macOS, a policy file on Linux | settings that declare a `policy` |
+
+A key outside the accepted scopes is dropped at parse time, not at read time. An untrusted window also drops restricted and unregistered keys from the workspace and folder layers (`config/src/service.rs::update_workspace_trust`).
+
+Port decision, not upstream: a folder's configuration is read from `.vscode`, `.vsrustium` and `.vscrs`, the later winning per key (`config/src/service.rs::FOLDER_CONFIG_DIRS`), and written to the last one that exists (`config/src/service.rs::folder_config_dir`). Code that builds a `.vscode/...` path by hand misses the other two.
+
+**Invariant:** the merged models are cached per folder and language, and the `config.*` context keys as one map (`config/src/configuration.rs::context_keys`, read on every key through `app/src/workbench/keyboard.rs::key_context`). Code that assigns a layer field of `Configuration` calls `config/src/configuration.rs::layers_changed` after it. Without the call, reads return the old value.
+
+## Reading, writing and change
+
+A read is `config/src/service.rs::get_value` with `config/src/configuration.rs::Overrides` (a resource and a language). In the workbench use `app/src/workbench/explorer_actions.rs::setting` for a plain key and `app/src/workbench/format.rs::language_setting` for a value of the editor's language. A read takes the settings lock and reads the cached merge, so a `render` can ask for the value it needs each frame and needs no listener.
+
+A write returns a `config/src/model.rs::Change`, the keys and language overrides that changed. Nothing is emitted: the caller carries the `Change` to whoever must hear it. There are four sources:
+
+1. A file edited on disk. `app/src/workbench/configuration.rs::watch_settings_files` watches the folders of `config/src/service.rs::watched_files`, and `config/src/service.rs::reload_changed_files` reloads the layers whose size or modification time moved.
+2. The workbench. `config/src/service.rs::update_value_derived` writes where the key is already set, else into user settings, where the default value removes the key. `config/src/service.rs::update_value` writes to a named target.
+3. The extension host. `exthost/src/main_thread_configuration.rs::MainThreadConfiguration` runs on the session thread on the same `Arc<Mutex<Settings>>` and sends `$acceptConfigurationChanged` before its reply, as upstream's event fires before the update resolves.
+4. A new registry (extensions added or removed), a policy change, a trust change, a profile switch, another workspace or other folders: `set_registry`, `set_policy_values`, `update_workspace_trust`, `set_profile`, `set_workspace`, `write_workspace_folders` of `config/src/service.rs::Settings`.
+
+`app/src/workbench/configuration.rs::configuration_changed` is the one place that plays upstream's `onDidChangeConfiguration` listeners: it tells the host, then refreshes what the workbench derived from a setting and keeps (the theme, icon themes, model indentation, folding, the proxy), then notifies.
+
+**Trap:** `app/src/workbench/explorer_actions.rs::update_setting` tells the host and stops there. It is right for a setting the views read live. A setting with a branch in `configuration_changed` must be written through a path that calls it, as `app/src/workbench/settings_editor_view.rs::write_setting_value` does.
+
+**Trap:** a write from the host (source 3) refreshes the file stamps (`config/src/service.rs::reload_after_write`), so the reload the watcher starts (`config/src/service.rs::reload_changed_files`) finds no file changed and `configuration_changed` does not run for it. The request is served on the session thread and is not forwarded to the workbench. The views see the new value on their next frame; derived state does not follow.
+
+**Invariant:** a `settings.json` or `tasks.json` under the user home is written through `config/src/service.rs::write_user_data_file` (a temporary file renamed over the target, as `FileUserDataProvider`; a symbolic link is written in place). `mcp.json` and the folder and workspace files are written in place (`config/src/service.rs::write_settings_file`). A policy value blocks the write with upstream's error (`config/src/service.rs::validate`).
+
+Settings that upstream renamed are moved by `app/src/workbench/configuration_migration.rs`, a port of each registered migration of the kept features.
+
+## Storage
+
+`Storage` is upstream's `ItemTable` behind an in-memory map. A read never touches SQLite. A write updates the map and runs one SQLite statement at once, where upstream batches for 100 ms. On drop a healthy file is copied to `.backup`; a file that failed at runtime is rebuilt from the map.
+
+| Scope | Field of `app/src/workbench.rs::Workbench` | File under the user data folder |
+|---|---|---|
+| Application | `application_storage` | `User/globalStorage/state.vscdb` |
+| Profile | `profile_storage` | the same file in the default profile, else `User/profiles/<id>/globalStorage/state.vscdb` |
+| Workspace | `workspace_storage` | `User/workspaceStorage/<id>/state.vscdb`, in memory for an empty window |
+
+The workspace id is upstream's (`exthost/src/session.rs::workspace_id`). The profile and workspace storages are shared with the session thread through `exthost/src/main_thread_storage.rs::MainThreadStorage`: an extension's `globalState` is one JSON string under its id in profile storage, its `workspaceState` the same in workspace storage. Extension test runs use `storage/src/lib.rs::in_memory`.
+
+`storage.json` (`User/globalStorage/storage.json`) is for state needed before a window exists: the profiles, the windows of the last session (`app/src/windows_state.rs`), the telemetry ids. Each writer opens it again for its change (`app/src/user_data_profile.rs::edit`), so the keys another writer set are kept. Keep a `FileStorage` only for the length of one change.
+
+**Invariant:** keys and value formats are upstream's, so a VS Code user data folder loads as it is and the settings import can copy rows (`app/src/settings_import.rs`). A key the port invents is a decision in `port/notes.md`.
+
+**Invariant:** a storage lock is held for one get or set. In the default profile `application_storage` and `profile_storage` are the same mutex: locking both in one expression deadlocks (see the read of the bisect state in `app/src/main.rs::open_window`).
+
+**Trap:** each window opens its own `Storage` over the file. A value another window writes is not in this window's map until `storage/src/lib.rs::refresh` rereads the file. Two reads call it: `app/src/workbench/opener.rs::trusted_domains` on application storage and `app/src/recently_opened.rs::load` on the `shared_storage` field (`app/src/main.rs::open_shared_storage`, one per process). Every other read returns the map as that `Storage` loaded it or last wrote it.
+
+## Profiles
+
+`Profiles` keeps upstream's `userDataProfiles` and `profileAssociations` keys of `storage.json`. It emits nothing: the create, update, remove and association methods return a `storage/src/profiles.rs::Change`; `clean_up` and `clean_up_transient_profiles` return none. `storage/src/profiles.rs::to_profile` gives every resource path of a profile; a resource whose `use_default_flags` entry is true points at the default profile's file. The default profile is `User`, another is `User/profiles/<id>`. Take a path from the `storage/src/profiles.rs::Profile` field, never from a joined string.
+
+`app/src/user_data_profile.rs::UserDataProfilesService` is one GPUI global for the process. `app/src/user_data_profile.rs::resolve` picks a window's profile: `--profile`, `--profile-temp`, the workspace's association, `window.newWindowProfile`, the default. `app/src/user_data_profile.rs::user_files` turns it into the `config/src/service.rs::UserFiles` the settings read.
+
+A switch (`app/src/workbench/user_data_profile.rs::change_current_profile`) stops the extension host, moves the settings layers, `keybindings.json`, profile storage and the user extensions file to the new profile, runs `configuration_changed`, and starts the host again. State the workbench read from profile storage at startup is read again in `app/src/workbench.rs::restore_profile_state`; state that is loaded only once keeps the old profile's value.
+
+## Keybinding tables
+
+The default rules are data, not code: `app/src/keybindings/default-macos.json` and `app/src/keybindings/default-win.json` are the reference's `--export-default-keybindings` output without the built-in extensions' rows, written by `port/tools/default-keybindings`. Linux reads the macOS table for now (`app/src/keybindings.rs::default_table`). A new command gets its default key from a new export, not from a hand-written row.
+
+`app/src/keybindings.rs::default_keybindings_in` orders the rules as upstream's sorter: table rows without a `weight` first, then rows by weight, command and registration order, with each extension's `contributes.keybindings` at 300 (built-in) or 400 plus its index. `app/src/keybindings.rs::user_keybindings` reads the profile's `keybindings.json`, and the resolver puts those rules over both. `app/src/workbench/keyboard.rs::load_keybindings` builds the resolver; `app/src/workbench/keyboard.rs::start_keybindings_watcher` reloads the user file 50 ms after its last change.
+
+## Add a setting or a stored key
+
+A setting of upstream is already registered: read it with `setting` or `language_setting` under upstream's key. If the workbench keeps state derived from it, add a branch to `configuration_changed`. A setting only the port has is an entry of `config/port-settings.json` in the shape of the dump (numeric `scope` as `config/src/registry.rs::Scope`, `section` for the Settings editor) and a decision in `port/notes.md`. Do not edit `config/core-settings.json` by hand: rerun `port/tools/dump-settings`.
+
+A stored key takes upstream's key string and upstream's `StorageScope`, written as a string to the matching field of `Workbench`. If the value must follow a profile switch, load it from `restore_profile_state`.
+
+## Check a change
+
+- Layers, scopes, writes and their errors: `port/tools/cargo-test -p config service`, and `port/tools/cargo-test -p config profile_tests` for the application layer of a profile.
+- The registry and the models: `port/tools/cargo-test -p config registry`, `port/tools/cargo-test -p config model`.
+- JSON with comments and edits: `port/tools/cargo-test -p config json`.
+- The database, `storage.json` and profiles: `port/tools/cargo-test -p storage`.
+- Keybinding rules and the resolver: `port/tools/cargo-test keybindings::tests`. User rules over defaults in a window: `port/tools/cargo-test user_keybindings_remove_defaults_and_bind_chords`.
+- Against the reference app, after a release build: `port/tools/studio 'port/tools/settings-check configuration state'`, and `port/tools/studio 'port/tools/settings-check preferences'` for the default settings and keybindings documents.
+- After a rename: `bun port/tools/docs-check.ts`.
diff --git a/docs/terminal.md b/docs/terminal.md
new file mode 100644
index 00000000000..91e136b1551
--- /dev/null
+++ b/docs/terminal.md
@@ -0,0 +1,92 @@
+# Terminal
+
+The integrated terminal is a shell behind a pty, a VT screen that parses its output, the shell integration read from that output, and the view that draws the screen. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), "Terminal, webviews, updates". The code is `app/src/terminal.rs`, the folder `app/src/terminal`, the crate `ghostty_vt`, and the `terminal_*.rs` files of `app/src/workbench`. Upstream is `src/vs/workbench/contrib/terminal`, `src/vs/workbench/contrib/terminalContrib` and `src/vs/platform/terminal`.
+
+## What is where
+
+- `app/src/terminal.rs::TerminalInstance`: one terminal, upstream's `terminalInstance.ts`. It owns the pty, the screen (`term`), the shell integration state, the finished commands and the titles. It does not import the workbench: a test builds one and feeds it bytes.
+- `app/src/terminal/pty.rs::Pty`: the shell process, node-pty's `spawn` in Rust. The Windows side is `app/src/terminal/pty/conpty.rs`.
+- `ghostty_vt/src/lib.rs::Term`: the screen, in the place of xterm.js. `ghostty_vt/src/selection.rs` is the selection on it.
+- `app/src/terminal/shell_integration.rs::ShellIntegration`: the OSC scanner and the command state machine, upstream's `shellIntegrationAddon.ts` and `commandDetectionCapability.ts`. `app/src/terminal/prompt_input.rs` is `promptInputModel.ts`, and `app/src/terminal/injection.rs` decides how a shell loads the scripts.
+- The other files of `app/src/terminal` port upstream files or an xterm.js addon, named in their `//!` header (`fixed_dims.rs` has none): keys, mouse reports, links, search, serialize, history, profiles, quick fixes, completions, OSC 99.
+- `app/src/workbench/terminal_view.rs::TerminalView`: the terminals of a window, their groups, the tabs. It is a field of the `Workbench`, not a GPUI entity. `app/src/workbench/terminal_view/grid.rs::paint` draws one terminal.
+- `app/src/workbench/terminal_host.rs`: the extension API, upstream's `mainThreadTerminalService.ts` and `mainThreadTerminalShellIntegration.ts`.
+- `app/src/workbench/terminal_editor.rs`: terminals in the editor area, and the save and revive of terminals across a restart.
+
+## The backend today
+
+The VT parser and screen model is libghostty-vt 1.0.2, through the safe bindings of libghostty-rs. The move from `alacritty_terminal` has landed: no crate of the workspace depends on `alacritty_terminal`. The reasons, the fork, its three `build.rs` changes and the measured throughput are in `port/notes.md`, "Milestone 15: integrated terminal".
+
+`ghostty_vt` forbids `unsafe` and is the only crate that depends on `libghostty-vt`. The rest of the port sees `Term` and its plain types.
+
+- `Term` keeps the shapes the port used with alacritty: `ghostty_vt/src/lib.rs::Line` 0 is the first line of the active area, and a negative line is in the scrollback. `app/src/terminal/shell_integration.rs::BufferPoint` counts from the first scrollback line instead, so a command's lines stay valid while output scrolls. Convert with `history_size`, as `app/src/terminal.rs::buffer_cursor` does.
+- Ghostty prunes scrollback by whole pages, so it holds more rows than `terminal.integrated.scrollback` allows. `ghostty_vt/src/lib.rs::history_size` and `hidden_rows` hide the extra rows. Code that reads the scrollback size from the raw terminal sees lines xterm.js would have dropped.
+- The parser answers queries through effect callbacks (`ghostty_vt/src/lib.rs::Handler`), and the answers wait in `ghostty_vt/src/lib.rs::Effects` until `take_effects`. The replies to `CSI c`, `CSI > c` and `CSI > q` are set to xterm.js's, the ones VS Code's terminal gives.
+- A callback runs inside Zig. A panic there unwinds into foreign code, so a callback that can fail keeps the old value (`on_title_changed`).
+- Selection follows alacritty 0.25's rules, which the port's selection tests were written against. Its anchors are tracked grid references, so a selection moves with scrolled output as xterm.js's does.
+
+**Invariant:** keys and mouse reports are encoded by `app/src/terminal/keys.rs` and `app/src/terminal/mouse.rs` with xterm.js's encodings. libghostty-vt's key encoder is not used.
+
+## The pty and its threads
+
+Upstream runs every pty in a separate pty host process (`ptyService.ts`). The port spawns the shell from the app process, so a terminal does not survive the window (see "Restart" below).
+
+`app/src/terminal/pty.rs::spawn` starts two threads per terminal. `pty-read` reads the master in 64 KiB chunks and sends `PtyEvent::Data`. `pty-wait` waits for the child, then for the reader to finish or 200 ms, then sends `PtyEvent::Exit`. Both send into one unbounded channel, so the exit follows the last output unless the reader is still reading after the 200 ms, as node-pty's `unixTerminal.ts` orders them.
+
+`app/src/workbench/terminal_view.rs::pump_terminal_events` is the one reader of that channel: a task on the main thread that takes every event that is ready and hands the batch to `terminal_events`. Everything after the channel runs on the main thread: UTF-8 decoding, the parser, shell integration, the calls to the extension host.
+
+- Writes to the pty (`app/src/terminal/pty.rs::write`) and the resize are direct calls from the main thread. A write after the shell exited fails and is dropped, as node-pty drops it.
+- The channel is unbounded and nothing pauses the reader, where upstream has flow control (`FlowControlConstants`). A process that prints faster than the main thread parses grows the queue.
+- A chunk can end inside a UTF-8 character. `app/src/terminal.rs::decode` keeps the cut bytes for the next chunk. Feed the pty's bytes through `process`, never straight to `Term::advance`.
+- `Pty` kills the shell with SIGHUP when it is dropped, so dropping the instance is the kill. [memory-safety.md](memory-safety.md) lists `kill` as a known weak point: after the shell exits, the stored pid can belong to another process.
+- The foreground process name and the cwd are polled every 200 ms for all terminals (`app/src/workbench/terminal_view.rs::start_title_poll`, `app/src/terminal.rs::refresh_process`). On macOS they are three syscalls per terminal on the main thread (`tcgetpgrp` and two `proc_pidinfo`), on Linux `tcgetpgrp` and two reads of `/proc`. Keep anything slower out of that poll.
+
+**Trap:** `pump_terminal_events` returns at once under `cfg!(test)`, because the `pty-read` thread would wake the task off the test scheduler's thread and abort the run. In a workbench test no shell output arrives by itself: the test calls `app/src/workbench/terminal_view.rs::terminal_data` with the bytes. The tests of `app/src/terminal/tests.rs` read the receiver themselves.
+
+## From bytes to a frame
+
+`app/src/workbench/terminal_view.rs::terminal_data` is the one entry for process output, a pty's or an extension pseudoterminal's. It calls `app/src/terminal.rs::process`, then acts on what the chunk raised: the clipboard (OSC 52), auto replies, task output, history, the events for the extension host, quick fixes, OSC 99 notifications. Then it notifies, and the next frame draws.
+
+`process` returns `app/src/terminal.rs::Processed`: the chunk's text and its shell integration events in stream order. Output fed to `process` without `terminal_data` still updates the instance's commands, but is invisible to tasks, to `onDidWriteTerminalData`, to the command history and to the extension host's shell integration events.
+
+`app/src/terminal.rs::feed` sets the theme's colors and the cell size on the `Term` before each parse. The parser answers OSC 4, 10, 11 and 12 and `CSI 14 t` while it parses, so the values must be there first.
+
+There is no cell buffer between the screen and the frame. `app/src/workbench/terminal_view/grid.rs::paint` reads the visible rows with `ghostty_vt/src/lib.rs::viewport_rows` each frame and paints each cell's background, find match, selection, underline and strikethrough, then each row's text, the link underlines and the cursor. A focused block cursor is its cell's background.
+
+**Invariant:** `app/src/workbench/terminal_view/grid.rs::paint` reads the screen through one `viewport_rows` call, which reads each row's raw cells in one call. `ghostty_vt/src/lib.rs::row` and `cell` resolve a grid reference per cell and are for the code outside `paint`: links, search, serialize, the command line, the sticky scroll overlay. The numbers are in `port/notes.md`.
+
+The budget: one echoed key and the draw, over a full scrollback, under 16 ms at p95 (`app/src/workbench/scroll_frame_time.rs::terminal_typing_frame_time`).
+
+## Shell integration
+
+`app/src/workbench/terminal_host.rs::prepare_terminal_launch` gives each launch a nonce and changes its arguments and environment so that bash, zsh, fish or pwsh loads upstream's own scripts from `src/vs/workbench/contrib/terminal/common/scripts` under the workbench's `app_root` (`app/src/terminal/injection.rs::injection`, upstream's `terminalEnvironment.ts`). For zsh the four zsh scripts are copied as dotfiles into a `ZDOTDIR` under the temp folder. A task terminal (`is_feature_terminal`) and a disabled `terminal.integrated.shellIntegration.enabled` get no injection.
+
+The sequences are read before the parser, not by it. `app/src/terminal/shell_integration.rs::scan` finds every OSC sequence in a chunk, and `process` feeds the screen up to the end of each one before it handles it. So the cursor is where the shell printed the mark, and the text between C and D is the command's output.
+
+- The whole chunk still goes to the screen, sequences included. OSC 633, 133, 1337, 7, 99 and 52 are acted on from the scanner's result, never from a libghostty-vt callback.
+- A sequence can be cut by the end of a chunk. The scanner keeps its state between chunks, so one `ShellIntegration` belongs to one instance for its whole life.
+- A command line is trusted only when its E sequence carries the launch's nonce (`is_trusted`). Any program can print OSC 633. Rerun Command asks before it runs an untrusted line. Keep that check when a new feature runs a recorded command.
+- Without an E sequence the command line is read from the screen between B and the cursor, with low or medium confidence, as `extractCommandLine` does.
+
+## The extension host side
+
+The `exthost` crate holds no terminal logic, only the proxy ids of the terminal actors and the activation events of the `terminal` and `terminalQuickFixes` contributions (`exthost/src/activation_events.rs`). The calls of `MainThreadTerminalService` and `MainThreadTerminalShellIntegration` are forwarded to the main thread ([extension-host.md](extension-host.md), "Host calls the port answers") and answered by `app/src/workbench/terminal_host.rs::handle_terminal_request`.
+
+- State goes to the host as a diff. `app/src/workbench/terminal_host.rs::Reported` holds what the host last heard of each terminal, and `sync_terminals_to_host` sends only what changed. Call it after a change to a title, a size, a selection or the active terminal instead of sending the event yourself.
+- An extension `Pseudoterminal` is an instance with `extension_pty` and no `Pty`. Its output arrives as `$sendProcessData` and enters `terminal_data` like a shell's. Its input leaves through the `process_input` callback that `connect_terminal_to_host` sets. Code that writes to `pty` directly skips these terminals: write through `app/src/terminal.rs::input` or `send_text`.
+- The instance id is the id the host knows. A detached terminal (`app/src/workbench/terminal_view.rs::create_detached`, used by the test results output) counts down from `u32::MAX`, is in no group and is never reported to the host.
+- `$acceptTerminalClosed` sends a missing exit code as `undefined`, not `null`: the API tests compare with `undefined` (`exthost/src/rpc.rs::undefined`).
+
+## Restart
+
+On quit the buffers of the persistent terminals are written as escape sequences that redraw them (`app/src/terminal/serialize.rs`, the serialize addon's format) and the layout of the groups beside them. On start `app/src/workbench/terminal_editor.rs::revive_terminals` starts new shells and replays the stored text onto each terminal's screen. The processes are new: only the screen content comes back, where upstream's pty host can reconnect to a live process after a window reload.
+
+## Check a change
+
+- The screen: `port/tools/cargo-test -p ghostty_vt the_viewport_rows_match_the_rows_read_one_cell_at_a_time`, or the whole crate with `port/tools/cargo-test -p ghostty_vt`.
+- The instance, the pty and the models: `port/tools/cargo-test terminal::`. One test of the pty: `port/tools/cargo-test a_shell_runs_in_a_pty_and_its_output_reaches_the_screen`.
+- Shell integration: `port/tools/cargo-test shell_integration::`, `port/tools/cargo-test prompt_input::`, `port/tools/cargo-test injection::`.
+- The view and the editor terminals: `port/tools/cargo-test terminal_view::`, `port/tools/cargo-test terminal_editor::`.
+- The extension API has no Rust test of its events. Run upstream's suites: `MOCHA_GREP='vscode API - terminal' port/tools/api-tests` and `MOCHA_GREP='vscode API - Terminal.shellIntegration' port/tools/api-tests`.
+- The typing budget: `cargo gc test --release -p app -- --ignored terminal_typing_frame_time --nocapture`, on a quiet machine ([performance.md](performance.md)).
+- After a change to `app/src/terminal/pty.rs` or `app/src/terminal/pty/conpty.rs`: `cargo gc clippy -p app -p exthost --all-targets -- -A clippy::all` and the inventory row in [memory-safety.md](memory-safety.md).
diff --git a/docs/test-explorer.md b/docs/test-explorer.md
new file mode 100644
index 00000000000..c81e438d3ec
--- /dev/null
+++ b/docs/test-explorer.md
@@ -0,0 +1,64 @@
+# Test explorer
+
+The Testing view, test runs and test coverage: the tests extensions publish, the runs of them, and how the results and coverage reach the views and the editor. This file goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), section "Extension host bridge", and under [extension-host.md](extension-host.md). Upstream is `src/vs/workbench/contrib/testing` and `src/vs/workbench/api/browser/mainThreadTesting.ts`. The port's own tests are a different subject: [testing.md](testing.md). The decisions per feature are in `port/notes.md`, "Milestone 16: debug and testing".
+
+## What is where
+
+Data without a window:
+
+- `app/src/testing.rs::TestCollection`: every test item the controllers published, by id, with each item's children (mainThreadTestCollection.ts). `apply` takes a `TestsDiffOp` list.
+- `app/src/testing.rs::Profile`: a run profile, with `default_profile` as testProfileService.ts picks one for a test.
+- `app/src/testing.rs::TestResult`: one run, live or complete (testResult.ts `LiveTestResult`): its tasks, the tests in it with a state per task, messages and output. `computed_state` is getComputedState.ts.
+- `app/src/testing_coverage.rs::TestCoverage`: one task's coverage as a prefix tree by URI path, whose folder nodes sum their files (testCoverage.ts). The same file has the details model of codeCoverageDecorations.ts (`detail_ranges`, `inline_coverage`, `describe`) and the display rules of codeCoverageDisplayUtils.ts.
+
+The service and the views, in `app/src/workbench`:
+
+- `app/src/workbench/testing_service.rs::TestingService`: the state of testServiceImpl.ts, testProfileService.ts and testResultService.ts in one struct. It is the field `testing` of `app/src/workbench.rs::Workbench`. The file's `impl Workbench` block is `MainThreadTesting` and the run logic.
+- `app/src/workbench/testing_view.rs`: the Testing view, its commands, the run glyphs of the editor gutter. `testing_filter.rs`, `testing_profiles.rs`, `testing_continuous.rs`, `testing_item_menu.rs` and `testing_gutter.rs` hold the filter box, the profile dropdowns, continuous run, the row menu and the gutter menu.
+- `app/src/workbench/testing_results.rs`: the Test Results panel view, with `testing_peek.rs` (the peek at a failed test) and `testing_message_colorizer.rs`.
+- `app/src/workbench/testing_coverage_view.rs::CoverageService`: which coverage is open, the filter to one test, and the Test Coverage view's tree state. `app/src/workbench/coverage_decorations.rs` draws the inline coverage and the coverage toolbar in the editor.
+
+## Who owns the tests
+
+The extension host owns the test controllers, the test items' code (`resolveHandler`, `runHandler`) and the coverage details. The app owns a copy of the item tree, the profiles, and every result. Nothing in the app can run a test: a run is a request to the host.
+
+All of `MainThreadTesting` is forwarded to the main thread (`app/src/main_thread_commands.rs::route`, path 3 of extension-host.md) and served by `app/src/workbench/testing_service.rs::handle_testing_request`. The paths:
+
+- Discovery: the host sends `$publishDiff`. The handler applies it to the collection and answers `$expandTest` for each expandable controller root in the diff, which makes the extension resolve that root's children. If an extension subscribed (`$subscribeToDiffs`), the same diff goes back as `$acceptDiff`.
+- A run the user starts: `run_tests` groups the tests by the profile that runs each, `run_resolved_tests` creates the live result and asks for workspace trust, and `run_trusted_tests` sends one `$runControllerTests` per controller. The result completes when every controller answered, or at once when trust is refused.
+- A run an extension starts (`createTestRun` without a request from the app): the host sends `$startedExtensionTestRun` with its own run id, and the app creates the result under that id.
+- Progress, for both kinds: `$startedTestRunTask` adds the task to the `TestResult`. `$applyTestRunUpdates` and its single-update siblings land in `apply_test_run_update`, which writes into the `TestResult`.
+- The end: `finish_test_run` marks the result complete and sends the whole serialized result back with `$publishTestResults`, as mainThreadTesting.ts does for `vscode.tests.testResults`.
+- Coverage: `$appendCoverage` carries per-file counts only. The ranges of one file are asked from the host on demand with `$getCoverageDetails` and the file's id, and cached in `app/src/testing_coverage.rs::TestCoverage` under `(uri, test)` with `None` while the request is out.
+
+## How state reaches the views
+
+There is no event emitter. `handle_testing_request` ends with `cx.notify()` (`$runTests` and `$getCoverageDetails` return before it), and the views are `impl Workbench` methods that read `self.testing` in `render`. A row's icon is `app/src/workbench/testing_service.rs::state_of` at draw time, and Sort by Status orders the rows by it in `explorer_children` on the same render, so a state update needs no separate tree update. The context keys of testingContextKeys.ts are computed from the same state in `testing_service_context` and `testing_coverage_context`.
+
+Coverage in the editor goes the other way round: `app/src/workbench/coverage_decorations.rs::sync_inline_coverage` runs on every workbench render, computes each open editor's ranges from the cached details, and writes the count badges and missed-branch indicators into the editor as `InjectionOwner::Coverage` injected text only when they differ from what is there.
+
+## Invariants
+
+- A test id is the path of ids from the controller down, joined by `\0` (testId.ts). `app/src/testing.rs::parent_id` and `root_id` read it; the first segment is the controller id. Build no id by hand.
+- Only controller roots expand at publish. `TestCollection::apply` returns the roots and nothing deeper, as treeProjection.ts `storeItem` does. Expanding file items too makes every `resolveHandler` run at startup and changes what Run All runs (`port/notes.md`, "Test resolution timing").
+- A terminal state never goes back. `app/src/testing.rs::TestResult::update_state` keeps the higher terminal state, as testResult.ts does; a late "running" after "failed" is dropped.
+- `results` is newest first and holds at most 128. `state_of` and `is_retired` read the newest result that has the test, so the order is the meaning.
+- The open coverage is a result id plus a task id (`CoverageService.selected`), looked up on each use. It is gone when its result leaves `results`; hold no reference to a `TestCoverage` across frames.
+- Positions and paths. Coverage positions are 1-based on the wire; `app/src/testing_coverage.rs::model_position` clamps one to the model as a 0-based line and column. Coverage tree keys are lower-cased for `file` paths on macOS (`tree_path`), so look a file up through `TestCoverage::file`, not by string compare.
+- Cancellation tokens. `$runControllerTests`, `$startContinuousRun`, `$getCoverageDetails` and the other token-taking methods of `ExtHostTesting` are listed in `app/src/main_thread.rs::TOKEN_METHODS`. A new one needs its entry or a send through `app/src/host_sync.rs::call_cancellable`, or the extension gets `undefined` as its token.
+
+## Traps
+
+- `sync_inline_coverage` is in the render path. Work added there runs every frame for every open editor: keep it to a lookup in the cached details, and start requests only through the `None` placeholder so one file asks once.
+- Output of a run can arrive as a string or as a `VSBuffer`, which the session turns into an array of bytes. `apply_test_run_update` handles both; a new handler that reads output must too.
+- `app/src/workbench/testing_view.rs::test_output_changed` is an empty function that `apply_test_run_update` calls on every output update. It is the place for work that must follow new output; today nothing does.
+- The Test Results view's editors live in `app/src/editor.rs::TEST_RESULTS_GROUP`, a group outside the editor grid. Code that walks "all groups in the grid" does not see them.
+- `app/src/workbench/extension_host_restart.rs::stop_extension_host` does not clear `controllers`, `collection` or `profiles`, and no other code in `native/crates` clears them on a restart. Their entries are added and removed only in `handle_testing_request`, on the host's own calls (`$unregisterTestController`, `$publishDiff`, `$removeTestProfile`).
+- Profile defaults and hidden tests are in workspace storage (`testingPreferredProfiles2`, `excludedTestItems`). `handle_testing_request` and `finish_test_run` write no result to storage.
+
+## Check a change
+
+- `port/tools/cargo-test -p app testing::` runs the collection, state and profile tests.
+- `port/tools/cargo-test -p app testing_coverage` runs upstream's testCoverage.test.ts and codeCoverageDecorations.test.ts cases and the coverage view tests.
+- `port/tools/cargo-test -p app testing_service`, `testing_view`, `testing_results` or `testing_profiles` runs one view's tests in a test window.
+- `port/tools/studio --lane 'FOLDER=port/fixtures/debug-node FILE=math.test.js ARGS=--extensionDevelopmentPath=port/fixtures/extensions/tests-provider port/tools/ui-pair /tmp/out port/fixtures/ui-pair/m16/inline-coverage.json'` compares coverage in the editor against the reference app. The controller in these runs is the fixture extension `port/fixtures/extensions/tests-provider`, which `ARGS` loads in both apps.
diff --git a/docs/webviews.md b/docs/webviews.md
new file mode 100644
index 00000000000..84addc2f115
--- /dev/null
+++ b/docs/webviews.md
@@ -0,0 +1,99 @@
+# Webviews
+
+A webview is a native web view of the OS that shows an extension's HTML inside the app window. This file covers the native view per OS, how it sits over GPUI's content, the message path between the page, the workbench and the extension host, resource loading with its security boundary, and lifetime. It goes one level under [ARCHITECTURE.md](../ARCHITECTURE.md), "Terminal, webviews, updates". The code is `app/src/webview.rs`, the three platform files of `app/src/webview/`, and the workbench files that own webviews. Upstream is `src/vs/workbench/contrib/webview` and `src/vs/workbench/api/browser/mainThreadWebviews.ts`.
+
+## What is where
+
+- `app/src/webview.rs`: everything the platforms share. `app/src/webview.rs::Webview` is one webview, `app/src/webview.rs::Resources` answers its requests and receives its messages, `app/src/webview.rs::theme_data` builds the `styles` message, `app/src/webview.rs::BRIDGE_SCRIPT` and `app/src/webview.rs::FIND_SCRIPT` are the two scripts the port injects into the host page.
+- `app/src/webview/macos.rs`, `app/src/webview/linux.rs`, `app/src/webview/windows.rs`: one `Native` each, with the same methods (`new`, `view`, `hide`, `evaluate`, `take_keyboard`, `release_keyboard`, `has_keyboard`, `open_inspector`), plus `place`, `supported` and `ClipView`. There is no trait: `app/src/webview.rs` imports the one `Native` of the target OS.
+- `app/src/webview/color_ids.txt`: the ids of upstream's color registry, one per line, that `theme_data` sends as `--vscode-*` variables.
+- `app/src/workbench/webview_panels.rs`: `MainThreadWebviews` and `MainThreadWebviewPanels`. It owns `app/src/workbench/webview_panels.rs::WebviewPanel`, the per-frame bookkeeping (`update_webview_panels`) and the event handler (`handle_webview_event`) of every webview but the welcome page's.
+- `app/src/workbench/webview_views.rs`, `app/src/workbench/custom_editors.rs`, `app/src/workbench/media_preview.rs`, `app/src/workbench/release_notes.rs`: webview views, custom editors and the built-in pages. Each is a `WebviewPanel` with another scheme or an extra field, so they share the panel code.
+- Four more owners make a `Webview` of their own: `app/src/workbench/notebook_editor.rs` (the back layer), `app/src/workbench/editor_insets.rs`, `app/src/workbench/extension_editor.rs` and `app/src/workbench/welcome_page.rs`. `Webview::new` has five call sites in all.
+
+## The native view per OS
+
+| OS | View | Stands in for the service worker | Message handler |
+|---|---|---|---|
+| macOS | WKWebView, a subview of GPUI's NSView | a `WKURLSchemeHandler` on `https` (`app/src/webview/macos.rs::SchemeHandler`) | `WKScriptMessageHandler` |
+| Linux | WebKitGTK view in a GTK window reparented into GPUI's X11 window | a TLS proxy on loopback, set as the view's https proxy (`app/src/webview/linux.rs::serve`) | script message handler |
+| Windows | WebView2 in a child window of GPUI's HWND | a `WebResourceRequested` handler (`app/src/webview/windows.rs::answer`) | `chrome.webview.postMessage` |
+
+Every platform loads upstream's host page, `src/vs/workbench/contrib/webview/browser/pre/index.html`, unchanged, with the query `webviewElement.ts` gives its iframe (`app/src/webview.rs::host_page_url`). The page runs with `disableServiceWorker=true`: the native request handler answers what `service-worker.js` answers upstream. The reason for each seam is in the `//!` header of its file and in `port/notes.md`, "Milestone 17: webviews and notebooks".
+
+- macOS: WebKit refuses a scheme handler for `https`, so `app/src/webview/macos.rs::allow_https_scheme_handler` swizzles `+[WKWebView handlesURLScheme:]` to answer NO for `https`. It is process-wide and runs once.
+- Linux: WebKitGTK has no way around that refusal, hence the proxy. Its certificate is trusted by the view's own context and only for the two served sites; every other host is tunnelled untouched. GTK has no main loop of its own here: `app/src/webview/linux.rs::pump_gtk`, started in `app/src/main.rs`, iterates it from GPUI's loop.
+- Windows: WebView2 makes its controller asynchronously. Until it arrives, `app/src/webview/windows.rs::Host` holds the frame and visibility the controller takes on.
+
+**Invariant:** check `app/src/webview.rs::supported` before `Webview::new`. It is false off the main thread (every unit test), on Wayland, and on Windows without the WebView2 runtime. All five call sites guard on it; on macOS a `Native::new` off the main thread panics.
+
+## Placing a webview over GPUI
+
+GPUI does not draw a webview and has no child-view API. The owner renders an empty box with a `canvas` whose prepaint calls `place` with the box's bounds in window coordinates (`app/src/workbench/webview_panels.rs::webview_body`). `place` sets the native frame only when it changed, and shows the view. A webview is created hidden: it shows only when a frame places it.
+
+**Invariant:** the native view is above GPUI's layer, so GPUI cannot draw over it. While a quick input, the keybindings editor, a context menu or the modal editor part would overlap, the panel is `covered`: the body stops placing it and `update_webview_panels` hides it. Electron draws those over its iframe; this difference is a recorded shortcut. A new GPUI overlay that can lie over a webview joins the `covered` condition.
+
+A webview that must sit inside scrolling GPUI content uses a `ClipView` (`app/src/webview/macos.rs::ClipView` and its two siblings): the notebook back layer and editor insets. The clip view shows the webview inside its own bounds only, passes presses to the webview only inside the given hit rectangles, and can cut a hole where a GPUI widget must stay visible and pressable (the notebook find widget). `ClipView::new` has two call sites.
+
+Keyboard focus is explicit. The host page's `did-focus` makes the view take the keyboard and blurs GPUI (`window.blur`); when GPUI focuses one of its own elements again, `update_webview_panels` calls `release_keyboard`. The host page forwards each keydown of its frame as `did-keydown`; all but a lone modifier go through GPUI's keybindings (`app/src/workbench/webview_panels.rs::keystroke`), deferred, because the keystroke interceptors update the workbench the handler is already updating.
+
+## The message path
+
+1. Page to app. `BRIDGE_SCRIPT` runs at document start in the top frame, before the host page's own script. It replaces `window.postMessage`, keeps the `MessagePort` the host page hands over with `webview-ready`, and relays each port message to the native handler as `{ channel, data }` JSON.
+2. `Resources::receive` turns that text into a `app/src/webview.rs::WebviewEvent` and sends it on an unbounded channel. One task per window reads the channel (`app/src/workbench/webview_panels.rs::webview_events`) and calls `handle_webview_event` on the main thread. The welcome page's media webview has a channel and a handler of its own (`app/src/workbench/welcome_page.rs::welcome_webview_events`, `handle_welcome_webview_event`).
+3. `handle_webview_event` routes by the webview's id prefix (`extension-editor-`, `editor-inset-`, `notebook-`), else by panel handle, then by channel. The channels are upstream's `FromWebviewMessage` of `webviewMessages.d.ts`, plus the port's `webview-ready`, `find-focus` and `find-hidden`.
+4. App to extension host. `onmessage` goes out as `ExtHostWebviews.$onMessage` through `app/src/host_sync.rs::send`.
+5. Extension host to app. `MainThreadWebviews` and `MainThreadWebviewPanels` calls are `Path::Forwarded` in `app/src/main_thread_commands.rs::route` and land in `handle_webview_request` ([extension-host.md](extension-host.md), "Host calls the port answers").
+6. App to page. `Webview::send` evaluates `globalThis.__vscodeWebviewHost.post(channel, args)`, which posts on the kept port.
+
+**Contract:** an extension message crosses as `extHostWebviewMessaging.ts` serializes it: JSON text with `$$vscode_array_buffer_reference$$` objects, the ArrayBuffers beside it as base64. The bridge serializes and deserializes in the page. For a panel Rust passes both parts through and does not parse the message; the built-in pages and editor insets parse its text.
+
+**Invariant:** `Webview::send` queues until `webview-ready` (`Webview::did_become_ready`), as `webviewElement.ts` does in its Initializing state. A script evaluated directly before that reaches a page with no port. Messages posted before the first webview of a panel exists wait in the panel (`first_load_messages`).
+
+The built-in pages (media preview, release notes, image carousel) take `onmessage` in the workbench and never reach the extension host. A new built-in page adds its arm before the general `onmessage` arm.
+
+## Resources and the security boundary
+
+`app/src/webview.rs::Resources::serve` is the one function all three request handlers call, and the whole boundary:
+
+- Host site, `https://<hash>.vscode-webview.vscode-cdn.net`: files inside `pre/` only, 404 for a path with a `..` or a drive component. The hash is `app/src/webview.rs::parent_origin_hash` of a fixed parent origin and the webview's origin, the check `index.html` makes itself. One origin per extension and view type (`webview_origin`) keeps the page's storage across loads.
+- Resource site, `https://<scheme>+<authority>.vscode-resource.vscode-cdn.net/<path>` (`webview.ts` `asWebviewUri`): `app/src/webview.rs::resource_uri` restores the resource, `app/src/webview.rs::is_contained` checks it against the local resource roots. 401 outside the roots, 404 when the read fails, byte ranges for media.
+- Any other host: `serve` returns `false` and the request goes to the network.
+
+**Invariant:** containment follows upstream's `resourceLoading.ts`. A `file` resource is checked lexically (no `..` segment, under a root of the same scheme and authority, case-insensitive on Windows), then by its resolved path, so a symlink out of a root answers 401. A resource of an extension file system provider has the lexical check only, and its read goes to the workbench as `app/src/webview.rs::ResourceRead`, answered through `app/src/host_sync.rs::read_file`. `vscode-remote` always answers 401. A new way to read a file for a webview goes through `serve`.
+
+**Invariant:** the request handler compares the host itself with `app/src/webview.rs::is_subdomain`. A URL filter is not a host check: WebView2's `*` matches `/`, so `https://example.com/.vscode-resource.vscode-cdn.net/a` passes the filter (`app/src/webview.rs::https_url_parts` and its test).
+
+The roots come from the extension host, which already added the defaults (`app/src/workbench/webview_panels.rs::local_resource_roots`); `$setOptions` replaces them on the live webview. Scripts and forms are the `allowScripts` and `allowForms` options of the `content` message (`update_content`), which the unchanged host page turns into its iframe sandbox. The same message carries `cspSource`; the page reports HTML without a policy as `no-csp-found`, forwarded as `$onMissingCsp`.
+
+Three more rules sit outside `serve`:
+
+- Plain `http` loads only from loopback on WebKit (`app/src/webview.rs::HTTP_LOOPBACK_ONLY_RULES`), which is what Chromium allows in an https page.
+- The Linux proxy answers only connections of its own user (`app/src/webview/linux.rs::is_own_connection`): any local user can reach a loopback port.
+- Cut, Copy and Paste on WebKit run the view's own editing actions (`Webview::clipboard_command`). The host page's `execCommand` would need a clipboard setting that every page in the webview would get.
+
+## Lifetime
+
+A panel outlives its webview. `WebviewPanel` holds the HTML, options and state; `WebviewPanel.webview` is an `Option`.
+
+- Created when the panel first shows, in `update_webview_panels`, which runs each render.
+- Hidden panel: released (`webview = None`) unless `retainContextWhenHidden`, when it is only hidden. The release happens as the editor hides (`release_hidden_webview_panels`), not at the next frame, so a reveal right after loads the page again. An editor inset keeps its webview while hidden.
+- State: `do-update-state` stores what `vscode.setState` gave in the panel, and the next `content` message hands it back to the reloaded page.
+- Dropping the `Native` removes the native view, gives the keyboard back and, on Linux and Windows, closes the proxy or the controller. Drop a `Webview` on the main thread.
+- A theme change sends `styles` again to the live webviews of panels and editor insets only (`restyle_webviews`). The welcome page makes its webview again; the notebook back layer and the extension editor get `styles` only when made.
+
+## Traps
+
+- A unit test never has a native view: `supported` is false, so tests cover the panel state, the protocol functions and `serve`, not the page. What the page does is checked by `port/tools/webview-check` against the reference app.
+- `BRIDGE_SCRIPT` talks to `window.webkit.messageHandlers`. Windows wraps it with a shim of that shape for the top frame only (`app/src/webview/windows.rs::bridge_script`); keep the script free of engine-specific calls.
+- A late `did-focus` arrives up to 250 ms after the fact, because the host page polls its focus. `handle_webview_event` sets `focused` but does not take the keyboard or blur GPUI while the same webview's context menu is open; another focus-stealing overlay needs the same care.
+- The find widget is HTML inside the host page (`FIND_SCRIPT`), not a GPUI widget, because GPUI cannot draw over the view.
+- A change to `unsafe` code in the three platform files follows [memory-safety.md](memory-safety.md), which has a row for each.
+
+## Check a change
+
+- `port/tools/cargo-test -p app webview::tests`: the protocol and the boundary (`serves_only_files_inside_pre_dir_and_the_roots`, `maps_resource_urls_to_resources_inside_the_roots`, `splits_https_urls_as_nsurl_does`).
+- `port/tools/cargo-test -p app webview_panels`: panels, restore, the context menu, resource reads through the file service.
+- `port/tools/cargo-test -p app webview_views` and `port/tools/cargo-test -p app custom_documents`: the other panel kinds.
+- `port/tools/studio --lane 'port/tools/webview-check'`: the fixture extension `port/fixtures/extensions/webview-tests` in the port and in the reference, one line per check. It covers messages with ArrayBuffers both ways and resource loads in a real view.
+- `cargo gc clippy -p app -p exthost --all-targets -- -A clippy::all` after a change to `unsafe` code.
diff --git a/docs/workbench.md b/docs/workbench.md
index 95d31983ea3..02445620989 100644
--- a/docs/workbench.md
+++ b/docs/workbench.md
@@ -6,7 +6,7 @@ The workbench is everything in a window around the editors: the layout, the part
`app/src/workbench.rs::Workbench` is the one GPUI entity of a window. It has a field for every model of the window: the file tree, the editor groups, the terminals, the settings, the storage, the extension host queue.
-The 280 files in `app/src/workbench` do not define types of their own that own state. Each one is an `impl Workbench` block for one upstream feature, named after it: `app/src/workbench/panel.rs` for `panelPart.ts`, `app/src/workbench/view_locations.rs` for `viewDescriptorService.ts`. A file holds the drawing of the feature, its input handling, its commands and its storage keys. Small state structs of a feature are fields of `Workbench`, defined in the feature's file.
+The files in `app/src/workbench` do not define types of their own that own state. Each one is an `impl Workbench` block for one upstream feature, named after it: `app/src/workbench/panel.rs` for `panelPart.ts`, `app/src/workbench/view_locations.rs` for `viewDescriptorService.ts`. A file holds the drawing of the feature, its input handling, its commands and its storage keys. Small state structs of a feature are fields of `Workbench`, defined in the feature's file.
This shape replaces upstream's services and dependency injection. A feature that needs another feature calls its method on `self`. Jump-to-definition finds every call.
diff --git a/port/tools/docs-check.test.ts b/port/tools/docs-check.test.ts
index bc67381dd4c..3ff10fcacc0 100644
--- a/port/tools/docs-check.test.ts
+++ b/port/tools/docs-check.test.ts
@@ -3,13 +3,15 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-// A repo with one crate file (`open_window`, and an unsafe block), the architecture text and the unsafe inventory given.
-function check(architecture: string, inventory = '| `app/src/main.rs` | libc | a fact |') {
+// A repo with one crate file (`open_window`, and an unsafe block), the architecture text, the unsafe inventory and the
+// crate table given.
+function check(architecture: string, inventory = '| `app/src/main.rs` | libc | a fact |', crateTable = '| `app` | The binary. |', glossary = '') {
const root = mkdtempSync(join(tmpdir(), 'docs-check-test-'));
mkdirSync(join(root, 'native/crates/app/src'), { recursive: true });
mkdirSync(join(root, 'docs'));
writeFileSync(join(root, 'native/crates/app/src/main.rs'), 'fn open_window() {\n // SAFETY: a fact.\n unsafe { libc::getpid() };\n}\n');
- writeFileSync(join(root, 'ARCHITECTURE.md'), architecture);
+ writeFileSync(join(root, 'ARCHITECTURE.md'), `${architecture}\n${crateTable}\n`);
+ writeFileSync(join(root, 'GLOSSARY.md'), glossary);
writeFileSync(join(root, 'docs/memory-safety.md'), `| File | Calls | Relies on |\n|---|---|---|\n${inventory}\n`);
const run = Bun.spawnSync(['bun', join(import.meta.dir, 'docs-check.ts'), root]);
rmSync(root, { recursive: true });
@@ -37,3 +39,11 @@ test('the unsafe inventory and the files that hold unsafe code must agree', () =
expect(check('', '').out).toContain('app/src/main.rs holds unsafe code and is not in the inventory');
expect(check('', '| `app/src/main.rs` | libc | a fact |\n| `app/src/safe.rs` | none | none |').out).toContain('app/src/safe.rs is in the inventory and holds no unsafe code');
});
+
+test('a crate without a row in the crate table fails', () => {
+ expect(check('', undefined, '').out).toContain('ARCHITECTURE.md: the crate app has no row in the crate table');
+});
+
+test('GLOSSARY.md is checked as the other documents', () => {
+ expect(check('', undefined, undefined, '`app/src/gone.rs`').out).toContain('GLOSSARY.md:1: `app/src/gone.rs` does not exist');
+});
diff --git a/port/tools/docs-check.ts b/port/tools/docs-check.ts
index 191cee8c6cf..7518e2de26d 100644
--- a/port/tools/docs-check.ts
+++ b/port/tools/docs-check.ts
@@ -1,6 +1,7 @@
#!/usr/bin/env bun
-// Fails when a path, a `path::Symbol` or a link cited in ARCHITECTURE.md, AGENTS.md, CONTRIBUTING.md or docs/ no longer
-// exists, and when the unsafe inventory of docs/memory-safety.md and the files that hold `unsafe` disagree.
+// Fails when a path, a `path::Symbol` or a link cited in ARCHITECTURE.md, AGENTS.md, CONTRIBUTING.md, GLOSSARY.md or
+// docs/ no longer exists, when the unsafe inventory of docs/memory-safety.md and the files that hold `unsafe` disagree,
+// and when a crate of native/crates has no row in the crate table of ARCHITECTURE.md.
// Prints each dead reference as file:line and exits 1 if any. Run after moving code or editing the docs:
// bun port/tools/docs-check.ts [repo root]
// A cited path starts at the repo root (`port/tools/bench`) or at a crate of native/crates (`app/src/main.rs`).
@@ -81,14 +82,28 @@ function checkUnsafeInventory() {
}
}
+function checkCrateTable() {
+ const doc = 'ARCHITECTURE.md';
+ if (!existsSync(crates) || !existsSync(join(root, doc))) {
+ return;
+ }
+ const text = readFileSync(join(root, doc), 'utf8');
+ for (const entry of readdirSync(crates, { withFileTypes: true })) {
+ if (entry.isDirectory() && !text.includes(`| \`${entry.name}\` |`)) {
+ errors.add(`${doc}: the crate ${entry.name} has no row in the crate table`);
+ }
+ }
+}
+
const docsDir = join(root, 'docs');
const docs = existsSync(docsDir) ? (readdirSync(docsDir, { recursive: true }) as string[]).filter(name => name.endsWith('.md')).map(name => `docs/${name}`) : [];
-for (const doc of ['ARCHITECTURE.md', 'AGENTS.md', 'CONTRIBUTING.md', ...docs]) {
+for (const doc of ['ARCHITECTURE.md', 'AGENTS.md', 'CONTRIBUTING.md', 'GLOSSARY.md', ...docs]) {
if (existsSync(join(root, doc))) {
checkDoc(doc);
}
}
checkUnsafeInventory();
+checkCrateTable();
for (const error of errors) {
console.log(error);
}