# CodeShellManager A WPF .NET 10 multi-terminal host for Claude Code (and other CLI tools). Runs multiple pseudo-terminal sessions in a tabbed/grid layout with full-text search, alert detection, git status, and session persistence. ## Build & Run ```bash # From repo root dotnet build src/CodeShellManager/CodeShellManager.csproj dotnet run --project src/CodeShellManager/CodeShellManager.csproj # Or open CodeShellManager.slnx in Visual Studio / Rider ``` **Requirements:** .NET 10 SDK, Windows 10/11 (uses ConPTY + WebView2) ### Visual Studio: Hot Reload disabled `Properties/launchSettings.json` ships with `"hotReloadEnabled": false`, and the csproj sets `false` in Debug. Both are workarounds for a `System.ExecutionEngineException` that crashes the app on F5 under .NET 10.0.8 + VS 18 — `Microsoft.Extensions.DotNetDeltaApplier.dll` faults during its own startup before any managed code runs. Ctrl+F5 (Start Without Debugging) is unaffected either way. **Remove both when the runtime bug is fixed upstream.** ### Command-line flags | Flag | Effect | |---|---| | `--clean` | Debug isolation mode — see below. | **`--clean`** (parsed in `App.OnStartup`, exposed as `App.CleanStart`): - `MainWindow.OnLoaded` skips the restore loop and clears the in-memory `SessionManager` — both sessions AND groups — so any new work in the run starts from a blank slate. - `MainViewModel.SaveStateAsync` short-circuits — **nothing is written to `state.json`** for the entire run. Window bounds, layout changes, settings tweaks, and any sessions created during the clean run are all discarded on exit. - The user's prior `state.json` survives the run untouched, so this is the safe way to test from a blank slate. - The terminals use their own WebView2 data folder (`WebView2-clean`), so a clean run — usually a dev build next to the installed app — never shares the installed copy's browser process. See "DPI awareness and the WebView2 data folder". - **Not isolated:** `output.db` (search index, notes, session history) and `crash.log` are shared with any other copy that is running, so test-session output shows up in the real copy's search. ## Architecture ### Key layers ``` PTY (ConPTY) → PseudoTerminal → TerminalBridge → WebView2 (xterm.js) ↓ OutputIndexer → SQLite FTS5 AlertDetector → SessionViewModel.RaiseAlert() ``` - **PseudoTerminal** (`Terminal/PseudoTerminal.cs`): Windows ConPTY wrapper, P/Invoke only. Implements `IPseudoTerminal` (`Terminal/IPseudoTerminal.cs`) — the minimum surface needed by `RunInstance` (`DataReceived`, `Exited`, `ExitCode`, `Start`). Tests inject a fake via the `internal RunInstance(item, Func)` constructor. `BuildCmdLine` passes shells through verbatim (`cmd`/`powershell`/`pwsh`/`wsl`/`bash`/`zsh`/`sh`/`ssh`/`nu`/`fish`); anything else is wrapped in `pwsh.exe -NoExit -Command …` (falls back to `powershell.exe` when pwsh isn't on PATH). The pwsh preference is deliberate — it loads the user's PowerShell 7 profile so functions defined there (e.g. `claudelocal`, `claudework`) resolve as bare session commands. - **TerminalBridge** (`Terminal/TerminalBridge.cs`): Routes bytes between PTY and xterm.js via WebView2 messages. Surfaces accelerator keys (Ctrl-combos, F-keys, Esc) via `_webView.PreviewKeyDown` — the newer WPF WebView2 wrapper forwards accelerators through standard key events rather than a separate `CoreWebView2Controller.AcceleratorKeyPressed`. Bridge re-raises them as `AcceleratorKeyPressed` so `MainWindow.OnBridgeAcceleratorKey` can run global shortcuts even when the terminal has focus. - **OutputIndexer** (`Terminal/OutputIndexer.cs`): Async channels → SQLite, strips ANSI - **AlertDetector** (`Services/AlertDetector.cs`): Regex on raw PTY output, fires after 1.5s idle ### MVVM - `MainViewModel` — sessions collection, layout mode, search state, alert count - `SessionViewModel` — per-session state: alert, git info, waiting state, bridge/pty refs - `MainWindow.xaml.cs` — heavy orchestration code-behind (sidebar building, layout, search handlers) ### Services | Service | Purpose | |---|---| | `SessionManager` | CRUD for ShellSession models | | `StateService` | JSON persistence → `%AppData%/CodeShellManager/state.json`. Writes are **atomic**: serialize to `.tmp`, then `File.Replace` into place, rotating the previous file to `.bak`. `LoadAsync` falls back to `.bak` when the primary won't parse, and logs every step to `crash.log` rather than silently starting empty. A static `SemaphoreSlim` serializes saves — 29 of the ~32 `SaveStateAsync` call sites are fire-and-forget, and overlapping saves would otherwise race on the shared temp file. See issue #88. | | `SearchService` | SQLite FTS5 search of all terminal output; also owns the `project_notes` table | | `ColorService` | FNV-1a hash of folder path → 12-color palette | | `GitService` | Async `git branch --show-current` + `git status --porcelain`. **Every await is `ConfigureAwait(false)`, `RunGitFullAsync` is `Task.Run`-wrapped, and command lines are built as argv via `JoinArgv` — do not "simplify" any of the three away.** WSL repos are dispatched through `wsl.exe -d -e git …`; `-e` is a security boundary, see "Never interpolate a value into a command line" | | `GitRepoWatcher` | Shared, reference-counted `FileSystemWatcher` on a repo's `.git/HEAD` + `index`, debounced 400ms. Lets git state refresh on checkout/commit/stage instead of by polling. Resolves the `gitdir:` indirection so a linked worktree watches its own HEAD, not the main repo's. Acquire/Release per session — one watcher per `.git` dir, however many sessions share it. Returns null outside a repo — callers treat that as "poll only", not an error | | `GitStatusText` | WPF-free wording for the toolbar git chip and menu: ↑/↓ counts, the menu header line, the post-fetch toast, and a short hint recognised from git's own failure text. See "Git tools on the terminal toolbar" | | `WslDiscoveryService` | `wsl.exe` probes for distro list, `$HOME` and login shell, each cached per (distro, user) and capped at 3s. All three go through `RunWslCaptureAsync`, which is `Task.Run`-wrapped — **never call `Process.Start` inline here**, `wsl.exe` can boot a stopped distro VM | | `ShellIntegrationPayload` | WPF-free validation for OSC 9001. Every field is untrusted: colour is strict hex, dirty is an allowlist, title and branch strip control characters and are length-capped (`MaxTitleLength` 80, `MaxBranchLength` 200) | | `AlertDetector` | Pattern matching for Claude prompts/approvals | | `CommandPresetsService` | Launch presets + in-session shortcuts | | `ClaudeSessionService` | Detects `claude` invocations; finds last `--resume` session id under `~/.claude/projects/` | | `UpdateService` | GitHub Releases version check; caches result for 24h at `%AppData%/CodeShellManager/update-cache.json` | | `ImportExportService` | Read/write a full `AppState` to a JSON file (settings + sessions backup) | | `SessionConfigEditor` | Diffs/applies a `SessionConfigDraft` onto a `ShellSession`; decides whether the change needs a PTY restart | | `SidebarDropResolver` | WPF-free: maps a drop Y over the rendered sidebar rows to "before / after session X" (+ the group, in inline-headers mode) and the Y of the insertion line. See "Sidebar order and drag-and-drop" | | `SessionOrder` | WPF-free order helpers: id-relative moves, re-aligning the grid to the sidebar order, and where a new worktree sibling should be placed. See "Sidebar order and drag-and-drop" | | `DbGate` | Serializes every use of the shared `output.db` `SqliteConnection`. That one connection is handed to `SearchService` *and* to every `OutputIndexer`, and it is not thread-safe — concurrent create/dispose corrupts its internal command list. Acquire as `using var _ = await DbGate.AcquireAsync();` at the top of anything touching it. See issue #102 | | `PwshLocator` | Single answer to "pwsh or powershell?", shared by `RunInstance` (run commands) and `PseudoTerminal.BuildCmdLine` (session wrapper) so they can't disagree. Resolves via `where.exe`. An ordinary executable is accepted from metadata alone (no spawn). A **zero-byte reparse point is ambiguous, not bad**: that shape is a Store App Execution Alias, and a *working* Store install of PowerShell 7 looks identical to a stub left by an uninstalled app — so only that case is settled by actually probing execution. Rejecting the shape outright silently downgraded Store-PS7 users to 5.1 on every session launch | | `ToastHelper` | Tray balloon notifications | | `SessionRunner` | Per-session owner of `RunInstance` dictionary (run commands runtime) | | `RunInstance` | One headless PTY-backed run with ANSI-stripped output buffer | | `RunCommandTemplatesService` | Detects project type (dotnet/cargo/node/python/make) → seed run-command list | | `WindowsTerminalProfileService` | Reads Windows Terminal `settings.json` from all install variants | | `BuiltInTerminalSchemes` | Lookup table of WT default color schemes not present in user `settings.json` | | `SchemeMapper` | WT scheme JSON → xterm.js theme JSON (renames `purple` → `magenta`, rewrites background as `rgba()` when opacity < 1) | | `CursorShapeMapper` | WT `cursorShape` → xterm.js `cursorStyle` (+ optional forced blink) | | `PaddingParser` | WT `padding` shorthand (1/2/4 comma ints) → CSS `Npx` shorthand | | `CommandLineSplitter` | Helper — quote-aware split of a Windows commandline into `(exe, args)` | | `ShellIntegrationPayload` | WPF-free validation for the OSC 9001 channel: hex-colour check + `#rrggbbaa`→`#aarrggbb`, dirty-flag parse, title/branch sanitising (control chars stripped, 80-char cap). See "Shell Integration (OSC 9001)" | | `WslDiscoveryService` | `wsl -l -v` parsing (UTF-16, header skipped, `*` default marker, names with spaces, Docker-internal distros filtered), `GetDistroHomeAsync` (cached `cd ~ && pwd` per distro+user), `GetLoginShellAsync` (cached `bash`-or-`sh` probe per distro+user, defaults to `bash` on any failure), `ToUncPath` / `TryParseUncPath` — the **only** UNC↔Linux path converters; GitService and NewSessionDialog delegate here | ## Project Structure ``` src/CodeShellManager/ ├── App.xaml / App.xaml.cs # App startup, tray icon, crash log ├── MainWindow.xaml / .cs # Main UI (toolbar, sidebar, terminal grid) ├── Models/ │ ├── AppState.cs # AppSettings + AppState (JSON root) │ ├── ShellSession.cs # Session data model (SSH fields, BuildSshArgs, IsDormant) │ ├── SessionGroup.cs # Group model │ └── AlertEvent.cs # Alert types: InputRequired, ToolApproval ├── Services/ │ ├── SessionManager.cs # Session CRUD + events │ ├── StateService.cs # JSON persistence │ ├── SearchService.cs # SQLite FTS5 search │ ├── ColorService.cs # Folder-path → accent color │ ├── GitService.cs # Git branch + dirty detection │ ├── AlertDetector.cs # PTY output pattern matching │ ├── CommandPresetsService.cs # Launch presets + in-session shortcuts │ ├── GitRepoWatcher.cs # .git HEAD/index watcher; replaces most git polling │ ├── WslDiscoveryService.cs # wsl.exe probes: distros, $HOME, login shell │ ├── ShellIntegrationPayload.cs # OSC 9001 validation (WPF-free, all values untrusted) │ └── ToastHelper.cs # Tray balloon notifications ├── Diagnostics/ │ ├── DiagnosticTrace.cs # Buffered [DEBUG-tt] writer (never blocks the caller) │ └── UiThreadHeartbeat.cs # UI-thread lateness, attributed to no session ├── Terminal/ │ ├── PseudoTerminal.cs # ConPTY P/Invoke wrapper │ ├── TerminalBridge.cs # WebView2 ↔ PTY bridge │ ├── OutputCoalescer.cs # Collapses PTY chunks into one dispatcher post │ └── OutputIndexer.cs # Async ANSI-stripped SQLite writer ├── ViewModels/ │ ├── MainViewModel.cs # App-level state │ └── SessionViewModel.cs # Per-session state + git/alert/waiting props ├── Views/ │ ├── NewSessionDialog.xaml/.cs # New session modal │ └── SettingsWindow.xaml/.cs # Settings modal └── Assets/ ├── terminal.html # xterm.js host page ├── xterm.js / xterm.css └── xterm-addon-fit.js tests/ ├── CodeShellManager.Tests/ # xunit unit tests (model logic, headless) └── CodeShellManager.UITests/ # FlaUI UI tests (requires live desktop) ``` ## Color / Theme **Dark theme** (Catppuccin-inspired, hardcoded throughout): - Background: `#1e1e2e`, Toolbar: `#181825`, Panel: `#11111b` - Foreground: `#cdd6f4`, Muted: `#6c7086`, Border: `#313244` - Accent blue: `#89b4fa`, Green: `#a6e3a1`, Alert pink: `#f38ba8` - Hover: `#45475a`, Selected: `#585b70` **Session accent colors** — `ColorService.GetHexColor(key)` uses FNV-1a hash to deterministically assign one of 12 colors. For local sessions the key is `WorkingFolder`; for SSH sessions `user@host`; for WSL `wsl://`. Used as sidebar stripe + terminal toolbar top border. **Active-terminal highlight** — every terminal pane is wrapped in an outer "active ring" Border (constant 2px thickness, transparent by default) so toggling it doesn't shift content. `UpdateActiveTerminalHighlight` (called from `UpdateSidebarActiveState`, which fires on every `MainViewModel.ActiveSession` change) paints the ring of the active session's pane in its accent color and clears all others. The accent comes from the **live VM**, not the `Border.Tag` stashed at build time: `RepoRoot` is populated asynchronously by `GitService` and `AccentColor` changes when it lands, so a cached Tag goes stale and stops matching the sidebar ring. The Tag survives only as a fallback. `SetBorderColor` also assigns only when the colour actually differs — it previously allocated a fresh brush and reassigned every pane on every call, which was invisible at one call per switch and a visible flicker storm when something called it rapidly. ## Never spawn a process on the UI thread An `async` method runs everything **before its first `await` synchronously on the calling thread**. `GitService.RunGitFullAsync` had `Process.Start` there, and the git poll chain starts in `SessionViewModel`'s constructor — which `MainWindow.LaunchSessionAsync` runs on the UI thread. The WPF `SynchronizationContext` was therefore captured, every continuation returned to the UI thread, and git process creation happened *on* it. At 47 sessions polling every 10s that was ~94 synchronous `Process.Start` calls per cycle on the UI thread. Traced live (issue #70): **42 UI stalls, worst 28.5s**, with foreground panes accumulating output and flushing it in one blob — `dispatcher-latency=12781ms len=3350`. That is the "I type and nothing appears, then it all appears at once" report. Measured on this hardware, and the numbers are the argument: | | | |---|---| | `cmd /c exit` | 21 ms — Windows baseline process creation | | `git --version` | 42 ms — git startup, **zero** repo access | | `git branch --show-current` | 41 ms — indistinguishable from doing nothing | | `git status --porcelain` | 48–65 ms — only 6–23 ms of it is the tree walk | | `Process.Start` alone | ~15 ms — the part that lands on the calling thread | **~85-90% of any git call is process startup, not git.** There is no faster query to switch to, so the only fixes are to not be on the UI thread and to not spawn at all. **This has now been got wrong twice.** The v0.8.0 pre-release review found `WslDiscoveryService` doing exactly the same thing in a new service — three `Process.Start` calls ahead of the first `await`, every caller on the UI thread including `LaunchSessionAsync` inside the restore loop — and `wsl.exe` is the worse offender, because it can boot a stopped distro VM. All three now go through `RunWslCaptureAsync`, which is `Task.Run`-wrapped. When adding a service that shells out, this is the pattern to copy. Four rules, all load-bearing: 1. **`GitService` must never depend on the caller's thread.** `RunGitFullAsync` is `Task.Run`-wrapped so `Process.Start` cannot run inline, and every await is `ConfigureAwait(false)` so no continuation can climb back. Both halves are needed: `ConfigureAwait` alone would not have moved `Process.Start`. 2. **Long-lived loops started from the UI thread must be `Task.Run`-wrapped.** `SessionViewModel`'s constructor does this for the git poll. A bare `_ = SomeAsync()` in a constructor that runs on the UI thread silently pins the whole chain to it. 3. **Don't poll what you can watch.** `GitRepoWatcher` catches checkout/commit/stage immediately; the poll only survives for working-tree edits, which dirty `status` without touching `.git`. Foreground sessions poll at 10s, background at 120s, and switching to a pane forces an immediate refresh via `SessionViewModel.IsForegroundSession`. Acquire it with `GitRepoWatcher.Acquire`/`Release`, never `new` — watchers are shared and reference-counted per `.git` directory, because several sessions in one repo is the normal case. 4. **Build command lines as argv, never by interpolation.** `GitService` composes every invocation through `JoinArgv`, which quotes each element with the MSVCRT rules. This is a security boundary, not a style rule — see below. ## Never interpolate a value into a command line `wsl.exe … -- ` runs the tail **through the distro's default login shell**; `-e` execs the program directly. That distinction is documented for *correctness* under `ShellSession.BuildWslArgs` (double expansion mangles payloads), but in `GitService` it was a **command-injection vector**, found in the v0.8.0 pre-release review: ```csharp // before — every value below reached a shell $"-d {QuoteForCmd(distro)} -- git -C {QuoteForCmd(cwd)} {arguments}" ``` `QuoteForCmd` is MSVCRT **argv** quoting. It does not, and cannot, neutralise `$(…)`, backticks, `;`, `|` or `&`. Two live paths: a branch name from a cloned repo flowing into `worktree add -b` (git ref names legally contain all of those), and the session's working folder, reached **unattended** by the git poll. Opening a hostile repository was enough. The rule: values go in as argv elements, and the process is exec'd directly. No shell, so argv quoting is both correct and sufficient. `GitService.BuildWslGitCommandLine` and `BuildLocalGitCommandLine` are the only places that build these, and `GitServiceInjectionTests` round-trips hostile payloads through the real `CommandLineToArgvW` to prove each survives as exactly one argument — 18 of its 27 cases fail against the pre-fix code. The same fix removed a plain bug: `--format=%(refname:short)` is a bash syntax error once a login shell sees it, so `ListBranchesAsync` could never have worked under WSL. **Two escaping layers, and a value can cross both.** `SshRemoteFolder` was POSIX-escaped in one round and *still* exploitable in the next, because the remote command was additionally hand-wrapped in `" … "` for Windows argv — and `PosixSingleQuote` escapes `'`, not `"`. A `"` in the folder therefore broke out at the **Windows** layer, and text after it became separate ssh arguments; ssh honours options after the host, and `ProxyCommand` runs *locally*. Both ssh builders now assemble the remote command and pass it through `QuoteForCmd(force: true)` as a single argv element. When a value crosses layers, ask which layer each escaper defends. **`SendToTerminal` types; `PasteToTerminal` pastes.** A raw PTY write submits at every newline — that is what made a dropped filename containing `%0A` a command-execution bug. `SendToTerminal` is only for text the app authored (a keystroke, a fixed preset command). Anything the app did not write — run-command output, clipboard, dropped paths — goes through `PasteToTerminal`, which routes via the page so xterm applies bracketed-paste markers. **Verified empirically against a real distro**, because two rounds of reasoning about this had already been wrong: ``` $ wsl -d Ubuntu -- echo '$(id)' # the v0.7.0 form uid=1000(thraen) gid=1000(thraen) groups=1000(thraen),4(adm),… ← executed $ wsl -d Ubuntu -e sh -lc 'exec "$0" "$@"' echo '$(id)' # the current form $(id) ← data ``` Backticks behave the same way. The form is `-e sh -lc 'exec "$0" "$@"' git …` rather than a bare `-e git` for one reason: `-e git` skips the login shell, and the login shell is where `~/.local/bin` and friends enter PATH — ``` -e sh -c (no login): /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:… -e sh -lc (login): /home/thraen/.local/bin:/usr/local/sbin:/usr/local/bin:… ``` so anyone whose git comes from nix, asdf, pipx or linuxbrew would have silently lost WSL git, reported as "not a git repo". Also confirmed on the real distro: `exec` preserves git's exit code (0 and 128 both propagate), arguments beginning with `-` pass through as data, and a clean profile adds nothing to stdout. If a *chatty* `~/.profile` ever does contaminate stdout, that is the one known weakness of this form — the symptom would be a garbage branch name in the sidebar, and the fix would be to strip non-git lines, not to go back to `--`. Guarded by `tests/CodeShellManager.Tests/GitServiceThreadingTests.cs`, which calls `GitService` from a thread whose `SynchronizationContext` never runs work: if any await captures it the call never completes and the test times out. All three tests fail against the pre-fix code — verify that still holds before trusting a change here. **`GitBranch` / `GitIsDirty` / `GitInfoLoaded` are hand-written properties, not `[ObservableProperty]`.** They share one notification, `GitInfoVersion`, because three generated setters meant three PropertyChanged events per poll per session — 141 sidebar rebuilds per cycle at 47 sessions. `ApplyGitInfo` also returns early when the result is unchanged, which is almost always: a branch changes maybe once an hour. Bind to `GitInfoVersion`; the individual properties raise nothing of their own. ## What makes a session "active" `MainViewModel.ActiveSession` drives the highlight, the dispatcher priority of terminal output (`TerminalBridge.IsForeground`, issue #70), and every `ActiveSession`-scoped command (`Ctrl+W`, `F5`, the run buttons). Three things set it: 1. **A sidebar row click** → `FocusSession`, which also calls `FocusTerminal()` when `AutoFocusTerminalOnSelect` is on. 2. **Typing in a pane** → the page posts `userkey` from xterm's `onKey`, throttled to one per 500ms. 3. **Clicking in a pane** → the page posts `activate` from a capture-phase `mousedown`, throttled to 300ms. Both (2) and (3) **must come from the page**, and this is the part that is easy to get wrong twice: - **WebView2 is an `HwndHost`.** Mouse input landing on hosted native content raises **no** WPF routed events, tunnelling `Preview*` ones included. A `PreviewMouseLeftButtonDown` on the host Border only ever fires for the thin ring around the terminal (#108). The same fact bites on the way out too — WPF content cannot be *drawn* over a pane either, whatever `Panel.ZIndex` says. See "Session Spinners". - **xterm's `onData` is not "the user typed".** It also carries replies the terminal generates itself — device attributes (`ESC[?1;2c`), cursor-position reports, OSC colour replies, focus in/out (`ESC[I`/`ESC[O`) — plus mouse reports when the app enables tracking. Filtering those by inspecting the bytes cannot work; a device-attribute reply is not distinguishable from typing by shape. xterm knows internally (`triggerDataEvent`'s `wasUserInput`) but does not expose it on `onData`. `onKey` is the only honest source (#106). The page-side `mousedown` handler also calls `doFit()`, and the initial fit is re-run on `document.fonts.ready`. xterm derives its column count from the *measured advance width* of the font, so a fit that runs before the font loads computes the wrong `cols` and tells the PTY a width that doesn't match what is drawn — text then overlaps mid-line. The `ResizeObserver` cannot catch that, because the element size never changed, only the glyph metrics (#113). ## A fit that changes nothing must still report the size Every fit in `terminal-init.js` goes through `doFit()`, which calls `fitAddon.fit()` and then `postSize()`. **Do not call `fitAddon.fit()` directly** — that is the shape that loses the size report, and it cost a new session three quarters of its pane. Two library facts combine into the trap, and neither is visible at the call site: | | | |---|---| | `FitAddon.fit()` | skips `term.resize()` entirely when the proposed dimensions already match | | `Terminal.resize(c, r)` | early-returns when `c === this.cols && r === this.rows` | So `onResize` fires **only on a change**. `new Terminal()` starts at xterm's default 80x24, which means the *initial* fit is the one call that genuinely changes the size — and `term.onResize` used to be registered some seventy lines below it. The host therefore never learned the size at all, and every later fit was a silent no-op: the 50ms/250ms timeouts, `document.fonts.ready`, the `ResizeObserver`, and `TerminalBridge.FitTerminal`'s own `fit` message included. `_lastSize` stayed at its `(80, 24)` placeholder, `pty.Start` created the ConPTY 80 columns wide, and `AttachPty`'s `_pty.Resize(_lastSize)` re-applied the same wrong value. xterm drew ~220x55 while the program believed it had 80x24, so Claude Code painted its frame into roughly a sixth of the pane. The only thing that ever fixed it was a real change in **element** size — resizing the window or switching layout — which is why the bug presented as "a new session needs a resize before it uses the full screen". Moving the registration above the first fit is necessary but **not sufficient**: it fixes only the first fit, and leaves every subsequent one unable to correct a size the host got wrong. `postSize()` reports `term.cols`/`term.rows` directly and dedupes against the last pair, so a no-op fit re-syncs the host exactly once and a genuine one is not reported twice. **Only report a size that was actually measured.** `FitAddon.proposeDimensions()` returns `undefined` when the cell metrics are still 0, and otherwise clamps to `Math.max(2, …)` / `Math.max(1, …)`. So a pane whose container is 0×0 — the case the 50ms/250ms fallbacks exist for — yields either xterm's untouched 80×24 default or a **2×1** clamp. `doFit()` therefore declines to report at all in that state. This matters much more now that the host *creates* the ConPTY from the first size it is told: pre-fix those bogus reports were simply dropped. **`bridge.TerminalSize` is a placeholder until the page reports**, and its initializer deliberately matches `PseudoTerminal.Start`'s own `cols = 220, rows = 50` defaults. It was `(80, 24)`, which meant the one path the wait cannot rescue — navigation failure, wedged renderer — created the ConPTY at the narrowest plausible width, straight back into the symptom. **The wait is gated on an options token, not on arrival order.** `LaunchSessionAsync` awaits `TerminalBridge.WaitForInitialSizeAsync()` after `ApplyFontSettings` / `ApplyProfileOverrides` and before `pty.Start`. Waiting for merely the *first* size report is not enough, and this is the subtle part: both of those post their `setOptions` through `Dispatcher.BeginInvoke`, and cols derives from the measured advance width, so a first-report wait resolves on the size measured with the **default** font — and usually resolves *synchronously*, never yielding the UI thread, so the queued `BeginInvoke` cannot even have run. A session with a profile font override would get its ConPTY created at the wrong column count: the very failure this exists to prevent. So each `setOptions` carries an incrementing token (stamped **synchronously**, before the `BeginInvoke` — inside the closure would reintroduce the race), the page echoes it on every size report, and the wait resolves only once an echo is at least as new as the last token stamped. That is a happens-after relationship rather than a timing guess. **The page promotes that token late, in `settle()`, not when the message arrives.** Stamping it on arrival is the same bug wearing the fix's clothes: the `doFit()` that runs immediately after the option assignments still measures the *old* metrics, and any `fit`/`focus` message landing before the next frame does too — so those reports carry the new token, `NoteOptionsToken` sees an echo new enough, and the wait releases on a pre-font measurement. Only a report made after the new metrics are in effect may carry the new token. **And `settle()` must not depend on a frame.** It runs from `requestAnimationFrame` *or* a 250ms timer, whichever comes first, because WebView2 suspends rAF whenever the control isn't rendering — window minimized, or the wrapper detached by `RefreshTerminalLayout`'s `TerminalGrid.Children.Clear()` while a launch sits in its `await`. In that state every other release path is already gated off (`doFit` declines an unmeasurable pane, the `ResizeObserver` needs a size *change*, and the 50ms/250ms one-shots fired long ago at page load), so nothing acked the token and each affected launch burned the full 1.5s — roughly +37s across a 25-session restore. rAF still wins whenever frames are running, so the measured-metrics path is unchanged in the normal case. The page also posts a separate `optionsApplied` ack, and that split is load-bearing in both directions: `doFit()` may legitimately decline to report an unmeasurable pane, and without an ack of its own a launch waiting on that token would burn the full 1.5s timeout per session. The host adopts a size only from `resize`, and releases the wait from either. `NavigationCompleted` is not a substitute for any of this — the page posts its size during load, but that message reaches the host as a separate dispatcher item, so `InitializeAsync` can return first. The wait is bounded (1.5s) so a wedged renderer cannot block a launch; the `resize` handler still corrects the size whenever it arrives. It traces `RESIZE cols= rows= token= released=` under `DebugTerminalTrace` — the *absence* of that line is the signature of this bug. ## DPI awareness and the WebView2 data folder **The app is per-monitor DPI aware (v2)**, declared in `app.manifest`. Before that it had no manifest and WPF defaulted to *system* DPI awareness: a process fixed its scale to the primary monitor's DPI **at the moment it started** and kept it for life. Whenever that stopped matching — another monitor, docking or undocking, a scale change in Settings, RDP from a different screen — Windows bitmap-stretched the whole window (soft, wrongly sized). The terminals made it worse, because they are not drawn by the app's process. WebView2 runs **one browser process per user-data folder**, shared by every app process pointing at that folder, and that process renders at its own scale. Observed: the installed app had started at 150% and stayed there after the monitors went to 100%; a dev build started afterwards came up at the correct 100%, but its panes were rendered by the installed copy's browser process at 150% — so the WPF chrome was right and the terminal text 1.5× too big, inside one window. **All terminals share one data folder** — `%AppData%\CodeShellManager\WebView2`, resolved by `Terminal/WebView2DataFolder`. `MainWindow` used to set a per-session `UserDataFolder` through `CreationProperties`, with a comment saying each instance needs its own; it was dead code — `TerminalBridge.InitializeAsync` passes an explicit environment, which wins, and no per-session folder was ever created on disk. Don't rename `WebView2`: that orphans every user's existing profile. **Two copies that create WebView2 differently cannot share that folder.** A per-monitor build starting next to a still-running system-DPI copy fails with `COMException 0x8007139F` ("The group or resource is not in the correct state…") the moment it calls `EnsureCoreWebView2Async`. `--clean` therefore uses its own `WebView2-clean` folder. A *normal* run of a different build next to the installed one (a portable ZIP, F5 without `--clean`) can still hit it — and so can the first launch of *this* release if a pre-manifest copy is somehow still running, since it is the first version on the other side of the DPI change. Closing the other copy ends its browser process and clears it. That case now fails cleanly instead of silently: - `LaunchSessionAsync` catches any `InitializeAsync` failure and tears down exactly like the PTY-failure path. Before, the exception escaped a launch nobody awaited, so it only reached `crash.log` later from the finalizer as an unobserved `TASK:` line; the pane kept its spinner forever; and a new session stayed in `SessionManager` with no row — persisted to `state.json`, invisible. That looked exactly like a hang, and was first diagnosed as one. - A new session shows `WebView2StartupError.Describe`'s message ("close the other copy"); restore, wake and restart rethrow, and each ends with the session **asleep** in the sidebar. The restore loop batches 0x8007139F with the existing folder access-denied case into one dialog. Covered by `DpiAndWebView2FolderTests`, including that the *built* `CodeShellManager.exe` contains `PerMonitorV2`: removing `` from the csproj would leave `app.manifest` on disk and silently bring the old behaviour back. The `WFO0003` analyzer warning is suppressed in the csproj deliberately — it recommends WinForms' `Application.SetHighDpiMode`, which a WPF app never calls. ## Session Lifecycle 1. User clicks **+ New Session** → `NewSessionDialog` modal (Local, Remote SSH, or WSL) 2. `SessionManager.CreateSession()` creates `ShellSession` model; caller sets `Kind` and copies SSH or WSL fields; for WSL it also sets `WorkingFolder` to the `\\wsl$\\` UNC mirror (see "WSL Sessions") 3. `LaunchSessionAsync()` creates: `SessionViewModel` → `WebView2` → `TerminalBridge` → `PseudoTerminal` 4. `OutputIndexer` indexes all output to SQLite; `AlertDetector` watches for prompts 5. Termination paths: - **Close** (`vm.CloseCommand`) → `MainViewModel.OnSessionCloseRequested` → `vm.Dispose()` + remove from `Sessions` + `SessionManager.RemoveSession()`. Session is gone from `state.json`. - **Sleep** (`SleepSession(vm)`) → `vm.Dispose()` + remove from `Sessions` but **keep** the `ShellSession` in `SessionManager` with `IsDormant = true`. A muted dormant sidebar entry replaces the active one. - **Wake** (`WakeSessionAsync(session)`) → re-runs `LaunchSessionAsync(session, restoring: true, removeOnFailure: false)` — same path as restore-on-startup. **Both pass `removeOnFailure: false` and then `FallBackToDormantIfNotLive`.** With the default, a session whose launch was refused or whose PTY failed to start (a WSL distro uninstalled, `claude` briefly off PATH) was *deleted* from `SessionManager` and the next save made it permanent — the PTY-failure path returns rather than throws, so Wake's catch never ran. Verified before/after against a real `state.json` (via `CSM_STATE_PATH`): the old build lost the session from the sidebar and the file; the fixed one keeps it asleep. Every relaunch path — restore, wake, restart — now ends a failure with the session asleep and editable. - **Restart** (`RestartSessionAsync(vm)`) → sleep-style teardown *without* the dormant bookkeeping, then `LaunchSessionAsync(session, restoring: true, removeOnFailure: false)`. The `ShellSession` stays in `SessionManager` (so Id, group, run commands and sidebar slot survive) and never enters the recently-closed ring. Reachable from the **↻ toolbar button and the "Restart" menu entries** (see "Restarting sessions" below) and from "Edit session…". Both non-default arguments matter: `restoring: true` makes a Claude session resume rather than start a fresh conversation (matching Wake — a restart tears down the same way, so it must recover the same way), and `removeOnFailure: false` stops a bad edit from *deleting* the session, since `LaunchSessionAsync`'s PTY-failure path calls `SessionManager.RemoveSession` — correct for a session that never started, destructive for a relaunch. If the relaunch fails either way, the session falls back to dormant so the row stays visible and fixable instead of leaving a launching placeholder that never resolves. A Claude restart also **waits for the old process to actually exit** (`DisposeAndWaitForExitAsync` + a config quiesce) before relaunching. Without that it recreates the concurrent-config-writer race the launch stagger and the shutdown loop both exist to prevent, and `--resume` can read a session index the outgoing process hasn't finalised. Non-Claude sessions skip the wait — they don't touch that file. 6. On app close: `_vm.SaveStateAsync()` flushes `_sessionManager.Sessions` (live + dormant) to `state.json` (unless `--clean`). **Waiting for a PTY to exit.** Check `PseudoTerminal.HasExited`, never `IsRunning`. `IsRunning` is `_hProcess != IntPtr.Zero` and the handle is only released in `Dispose`, so it stays true for a child that exited on its own — subscribing to `Exited` for one of those waits out the full timeout for an event that already fired. `HasExited` is latched immediately before `Exited` is raised. This is not academic: combined with `ClaudeShutdownBudgetMs`, two stale panes consumed the entire shutdown budget and every remaining *live* Claude session was then force-disposed with no exit wait — the exact opposite of what the budget was for. **`ClaudeShutdownBudgetMs` is sized from measurement (30s).** The original 15s came from the only data available at the time — idle sessions exiting in 460–770ms. Real shutdowns of *busy* sessions measure **2.3–4.7s each**, so nine of them need roughly 30s, and 15s meant force-disposing more than half the fleet on an ordinary close. Waiting is the right trade: a clean exit lets Claude finish writing its config, and `ShutdownOverlay` is already on screen telling the user why. The budget exists to bound a genuinely wedged session, not to hurry a healthy one. If you shrink it, re-measure `exit=` in `crash.log` first — the summary line alone can't distinguish "slow exits" from "waits that aren't returning". ### Restarting sessions Restart closes and reopens a session in place. The use case is picking up a new build of the CLI — `claude` updated on disk — without losing the session, its group, its run commands or its conversation. Five entry points, all routed through `RestartSessionsAsync`: | Entry point | Scope | Confirms? | |---|---|---| | **↻** on the terminal toolbar (between ⚙ and 💤) | the one session | no | | **"Restart"** in the per-session right-click menu (above Sleep / Close) | the one session | no | | **"Restart (N)…"** — same menu, with 2+ sidebar rows selected | the selection | yes | | **"Restart all…"** in the group right-click menu, next to Sleep all / Close all | live sessions in that group | yes | | **"Restart all…"** under Bulk actions in the sidebar quick-menu | every live session | yes | Multi-select resolves through `MainViewModel.ResolveActionTargets`, exactly like Sleep / Close. The per-session menu is rebuilt on `ContextMenuOpening`, so the count always reflects the live selection. Confirmation is driven by the `confirmHeadline` parameter rather than a count test: **null** (the toolbar button and the per-session menu) prompts only for 2+ targets with a generic headline, so a single "Restart" just goes; the bulk entry points pass a scope-naming headline and therefore always prompt, matching their "Close all…" siblings. The prompt defaults to **No**, like "Close all…" — a restart terminates every running process *and* stops in-flight run commands (`vm.Runner.StopAll()`), and a stray Enter shouldn't start a minute-scale operation with no stop button. Dormant sessions are filtered out everywhere — they want Wake, and they pick up a new binary when woken anyway. **The guard lives on the entry points, not the restart itself.** `RestartSessionCoreAsync` does the work and holds no guard; `RestartSessionAsync` (single session — used by "Edit session…") and `RestartSessionsAsync` (everything else) each take `_restartInProgress` and call the core. The split exists because the bulk loop holds the flag across all its iterations, so a guard inside the core would reject the loop's own work. Don't call the core from anywhere that doesn't already hold the flag: the edit dialog used to call the restart directly, which meant answering "Restart now?" during a bulk restart put two `claude.exe` instances on `~/.claude.json` at once. A rejected invocation raises a toast rather than failing silently, since a bulk restart runs long enough that a dead-feeling button reads as a bug. **Two shutdown checks, and both are needed.** `RestartSessionsAsync` breaks out of its queue when `_isShuttingDown`, and `RestartSessionCoreAsync` checks again *after* its teardown waits and before `LaunchSessionAsync`. The second one is the load-bearing one: the core removes the VM from `_vm.Sessions` **before** the 10s exit wait, so a session that is mid-restart is invisible to `OnClosing`'s `var all = _vm.Sessions.ToList()` snapshot. Relaunching past that point starts a ConPTY child nothing will ever dispose — and session PTYs are started with `useJobObject: false` (only `RunInstance` passes `true`), so no job object cleans up the tree either. The result is an orphaned `claude.exe` outliving the app. Returning early leaves the `ShellSession` in the `SessionManager`, so it is still in `state.json` and simply starts again next launch. **Restart restores focus.** The teardown hands `ActiveSession` to `_vm.Sessions.LastOrDefault()` and `LaunchSessionAsync` never claims it back, so the core captures `wasActive` up front and re-resolves the session by id afterwards (the relaunch builds a *new* `SessionViewModel`). Without it, restarting the session you're looking at swaps the visible pane in `LayoutMode.Single` and silently retargets `Ctrl+W` / `F5` at an unrelated session. `RestartSessionsAsync` runs its targets **strictly sequentially** — `RestartSessionAsync` waits for each Claude process to exit before starting its replacement, and awaiting those in parallel would put several `claude.exe` instances back on the shared config file at once, which is the race the wait exists to prevent. A `_restartInProgress` flag drops (rather than queues) an overlapping invocation for the same reason — see the guard note above. That sequencing is also why the bulk entry points confirm: restarting a fleet of Claude sessions is a minute-scale operation, not an instant one. Each target is re-resolved per iteration, since every restart replaces the `SessionViewModel` for that id and an earlier one in the loop may have failed into dormant. **The rail, and why it is not the shutdown board.** A bulk restart drives `RestartRail` (2px, docked under `RestoreRail`) plus a `RestartPill` counter in the toolbar's right stack, via `SetRestartProgress`. That is the *restore* pattern, deliberately, and the choice is forced: `ShutdownOverlay` only works because `OnClosing` collapses `TerminalGrid` before showing it — WebView2 is an `HwndHost` and composites over any WPF overlay — and collapsing the grid here would black out every live pane for the whole run. A bulk restart does not block the user, so it gets the quiet rail; shutdown does, so it gets the board. Both are hidden for a single target: the toolbar ↻ restarts in seconds and a rail that appears and vanishes is noise. The restart pair is **separate from the restore pair rather than a shared rail** — two unrelated loops with unrelated lifetimes, and one shared rail would need a precedence rule to no benefit. Peach (`#fab387`, the shutdown board's "closing…" colour) rather than the restore blue. **A restart refuses to start while the restore loop is running** (`_restoreInProgress`, dropped with a toast like `_restartInProgress`). Both loops spawn `claude.exe` and neither one's stagger can see the other's launches, so overlapping them is exactly the unlocked read-modify-write on `~/.claude.json` that `ClaudeLaunchStaggerMs` exists to prevent. The `OnLoaded` restore loop awaits per session and leaves the quick menu clickable throughout, so this is an ordinary click on a 55-session start, not a corner case. An earlier version of this section cited that overlap as the *reason* for separate rails — writing a config race down as a layout question. Both single-session `RestartSessionAsync` and bulk `RestartSessionsAsync` carry the guard; one session is enough to lose the race. **Stop means "after the current one".** The `⏹` on the pill sets `_restartCancelRequested`, read at the **top** of each loop iteration. It cannot abandon the session already mid-restart: by that point the VM is out of `_vm.Sessions` and the PTY is down, so returning early would strand it as dormant — the failure path, not a stop. Targets not yet reached keep their live terminals untouched, and a toast reports how many were skipped. The flag clears in the same `finally` as `_restartInProgress`. **The confirmation quotes a duration**, built by the WPF-free `Services/BulkRestartEstimate` (tested in `BulkRestartEstimateTests`) so the wording is unit-testable at all. It costs a Claude target at 4–8s (exit wait 2.3–4.7s + stagger + ~1.4s relaunch) and a plain shell at 1–2s, reports a range rather than false precision, and switches to minutes only once the *optimistic* bound passes 60s. At or above `ScaleWarningThreshold` (10 targets) it also says the restarts are sequential and names how many are Claude — that count is what makes the estimate look earned rather than arbitrary. `MessageBox` cannot emphasise anything, so scale is carried by the words; making the warning *look* like one would mean a themed window instead. ## Editing a Session's Configuration Any existing session can be reconfigured through the **same form used to create one** — `NewSessionDialog` has an edit mode rather than a second, drifting dialog. **Entry points:** the ⚙ button on the terminal toolbar, **"Edit session…"** in the sidebar right-click menu (single-target only), and **"Edit session…"** in the right-click menu on a dormant row (edit a sleeping session without waking it). **Dialog** — `NewSessionDialog.ForEdit(session, launchCommands, profiles)`: - Title becomes "Edit Session", the primary button becomes "Save". - "Recently closed" and the sibling-worktree checkbox list are hidden (both are create-only concepts); the worktree probe is skipped entirely (`IsEditMode` guard). - Local/Remote/WSL radio, folder, SSH host/port/remote folder, WSL distro (pre-selected once the async list loads; a since-uninstalled distro is kept as a `(not installed)` entry so Save cannot wipe it), WSL user and Linux folder are all pre-filled, as is command (matched against the launch-command list, falling back to `[custom]`), and name. - **Appearance combobox in edit mode:** when the session already carries profile overrides, the list gains a `— keep current appearance —` entry (tag `KeepCurrentAppearanceTag`, selected by default so saving never silently resets the look) and the old `— none —` entry is relabelled `— clear appearance overrides —`. The panel is shown when there are profiles to pick **or** overrides to clear, so overrides remain removable with Windows Terminal import switched off. The appearance panel is shown for Local and WSL, hidden only for SSH. **Result plumbing** — the dialog's `ToDraft()` returns a `Models.SessionConfigDraft` (a flat, UI-free snapshot of every field the form owns). `Services.SessionConfigEditor` then does the work, and being WPF-free is what makes the rules unit-testable (`tests/CodeShellManager.Tests/SessionConfigEditorTests.cs`): - `Diff(session, draft)` → `SessionConfigChange(AnyChange, RequiresRelaunch, WorkingFolderChanged, AppearanceChanged)`. `WorkingFolderChanged` also fires for a WSL distro/Linux-folder change, not just a local folder edit. - `Apply(session, draft)` writes every form-owned field verbatim (blanks included, so clearing in the dialog really clears), including `Kind` directly; for WSL it also **re-derives the UNC `WorkingFolder`** from the saved distro + Linux folder rather than trusting whatever the dialog had cached. Runtime state — `Id`, `GroupId`, `Status`, `RunCommands`, `IsDormant` — is untouched. **What needs a restart.** `RequiresRelaunch` is true for: any `Kind` change, command or args change, working-folder change (path-normalized compare), any SSH target field change, any WSL field change (distro, user, Linux folder), crossing the transparency boundary (opacity `< 1.0` picks a different xterm host page at navigation time), and *clearing* an override (`TerminalBridge.ApplyProfileOverrides` only ever **sets** options, so it can't push a value back to the global default). SSH and WSL fields and the working folder are only compared while the session stays in the same kind, so leftovers from a previous mode don't read as a change. Everything else is applied live: `SessionViewModel.NotifyConfigChanged()` re-raises the model-mirroring properties so the sidebar row and terminal toolbar repaint in place (no rebuild → no orphaned `PropertyChanged` subscriptions), and added/changed overrides go out via `ApplyFontSettings` + `ApplyProfileOverrides`. A folder change also calls `SessionViewModel.ReloadGitInfoAsync()`, which clears the once-only `RepoRoot` cache before re-probing. When a restart *is* needed, the user is asked. **No** keeps the live terminal and defers the change to the next launch (it's already persisted); **Yes** runs `RestartSessionAsync`. Editing a **dormant** session skips all of that — `EditDormantSession` rewrites the model and rebuilds the muted sidebar row, which renders name/folder/accent statically. Run commands are *not* part of this form; they have their own editor (`SessionRunCommandsDialog`, see below). ## SSH Remote Sessions Remote sessions use the system `ssh` client as the PTY command — no extra library. - `ShellSession.Kind == SessionKind.Ssh` distinguishes remote sessions from Local/WSL ones. `IsRemote` still exists as a `[JsonIgnore]`d two-way convenience view over `Kind` for the SSH case (not the persisted discriminator — see "WSL Sessions"). - SSH config fields on `ShellSession`: `SshUser`, `SshHost`, `SshPort` (default 22), `SshRemoteFolder` - `ShellSession.BuildSshArgs()` (internal) produces: `-t [–p PORT] user@host "cd 'folder' && shell"` - `LaunchSessionAsync()` branches on `Kind`: SSH sessions use `ssh` + `BuildSshArgs()`, skipping Claude auto-resume - `PseudoTerminal.BuildCmdLine` passes `ssh` through directly (same as `cmd`/`pwsh`) — not wrapped in PowerShell - `SessionViewModel.RefreshGitInfoAsync()` early-returns for remote sessions (no local working folder) - SSH fields serialize to `state.json` automatically — sessions restore and relaunch on next startup ## WSL Sessions `SessionKind.Wsl` launches `wsl.exe -d [-u ] --cd -e -lc ""` (PR #65, hardened on `feat/wsl-sessions-v2`; `-e` replaced a bare `--` separator during the same hardening — see below). - **`Kind` is the only persisted discriminator.** `IsRemote` is a `[JsonIgnore]`d two-way convenience over `Kind` (`false` on an SSH session makes it Local; a WSL session is untouched). The legacy `"IsRemote"` JSON key lands in `LegacyIsRemote` and `StateService.Normalize` folds it into `Kind` — migration lives in the loader, never in a setter. A promote-only setter was tried first and silently broke "Edit session" (SSH→Local could not demote) and then every save (`FullCommandLine` was serialised and threw); see `ShellSessionMigrationTests`. - **UNC mirror invariant.** A WSL session stores `WorkingFolder = WslDiscoveryService.ToUncPath(WslDistro, WslWorkingFolder)` (`\\wsl$\Ubuntu\home\alice\proj`). Explorer, the dormant row, run-command template seeding and `GitService` all work off that path unchanged. The Linux-side path lives on `WslWorkingFolder` and is what `--cd` receives. Every path that creates or edits a WSL session must keep both in step: `MainWindow` session creation, `InheritSessionKindFrom` (duplicate / worktree), `SessionConfigEditor.Apply`, `ReopenClosedSessionAsync`. - **`-e`, not `--`.** `wsl.exe -- …` runs the trailing command through the distro's *default* login shell before our own ` -lc "…"` ever sees it — a second, unwanted expansion pass in the wrong environment. Verified empirically: `wsl -d Ubuntu -- bash -lc 'for t in a b; do echo "L=$t"; done'` printed `L=` / `L=` (the loop variable never survived the first pass); the same command with `-e bash` printed `L=a` / `L=b`. `-e`/`--exec` runs the given program directly, skipping that pass, and composes fine with both `--cd` and `-u`. `--` looks more natural here — resist the urge to change it back. Any user command or run command containing `$var`, `` `…` ``, globs or `~` was silently mangled before this fix. - **A blank Linux folder means `$HOME`, and `--cd` is always emitted.** The dialog labels the Linux Working Folder "(optional)", so blank has to mean something sensible. It now emits `--cd ~` (unquoted — quoting would make it a literal directory name), which is wsl.exe's own spelling for the home directory and honours `-u` (`-u root --cd ~` lands in `/root`). **Testing this from PowerShell will mislead you:** PowerShell expands a bare `~` to the *Windows* profile path before wsl.exe sees it, so you get `/mnt/c/Users/` and conclude the flag is broken — a review of this very change did exactly that. Quote it, or test from `cmd`. Our own call passes the argument string straight to `CreateProcess` with no shell in between, so it behaves like the `cmd` case. A folder typed as `~/proj` is expanded by `LaunchSessionAsync` before it reaches wsl.exe, which special-cases only the bare `~` token and would otherwise treat `~/proj` as an absolute Windows path and fail the launch. Omitting `--cd` entirely, as this did before, does **not** do that: wsl inherits the launching *Windows* process's cwd, so the session landed in `/mnt/c/Users/` on the slow 9p mount instead of `$HOME`. Separately, `NewSessionDialog` resolves `$HOME` eagerly to keep the UNC mirror in step, but that probe is capped at 3s and a cold distro (first launch after `wsl --install`) blows through it — leaving `WorkingFolder` at the distro root so git status and "Open in Explorer" aimed at `/` while the shell sat in `$HOME`. `LaunchSessionAsync` therefore retries the probe at launch, where the distro is starting anyway, and re-derives the UNC mirror via `ResyncWslWorkingFolder` when it lands (`GetDistroHomeAsync` caches only successes, so the retry really re-probes). - **Login-shell fallback (bash → sh).** `BuildWslArgs` no longer hardcodes `bash` as the login shell — minimal distros (Alpine, BusyBox images, Docker Desktop's own `docker-desktop` distro) have no bash, so hardcoding it failed *every* session and run command there, no matter what the user typed. `WslDiscoveryService.GetLoginShellAsync(distro, user)` probes `-e sh -c "command -v bash >/dev/null 2>&1 && echo bash || echo sh"` (mirrors `GetDistroHomeAsync`: cached per `(distro, user)`, 3s timeout, drains both stdout and stderr, never throws) and returns `"bash"` on any failure — that preserves prior behaviour rather than silently downgrading a distro that actually works. `MainWindow.LaunchSessionAsync` resolves it into the runtime-only `ShellSession.ResolvedWslShell` (`[JsonIgnore] internal`, never persisted — a distro's shells can change between runs) before calling `BuildWslArgs`, which uses `ResolvedWslShell ?? "bash"` for both the `-e ` login shell and the empty-`Command` fallback payload. Run commands share the resolved value for free since `RunInstance` reads the same `ShellSession` instance — no second probe. - **Docker-internal distros are filtered from the picker.** `WslDiscoveryService.Parse` drops `docker-desktop` and `docker-desktop-data` (exact, case-insensitive match — a name that merely *contains* the phrase, e.g. `my-docker-desktop-clone`, is kept) before the listing reaches `NewSessionDialog`. Those are Docker's own BusyBox-based plumbing — root-only, rebuilt on Docker updates, not a user environment — and offering them (often as the *only* entry on a dev machine) is how a maintainer here hit the bash-not-found bug during manual testing. A listing containing only Docker distros now returns empty, so the dialog falls through to its existing "No WSL distros found" hint. - **GitService routing.** `RunGitFullAsync` detects the UNC and runs `wsl.exe -d -- git -C …`, translating `\\wsl$` args to Linux (`TranslateUncArgsToLinux`, with a distro-name boundary so `Ubuntu` never matches `Ubuntu-22.04`) and Linux paths in stdout back to UNC. This path still uses `--` deliberately, not `-e`: `git` is invoked with a literal argv, not a shell-interpreted string payload, so there is no second expansion pass to avoid. `SessionViewModel.RefreshGitInfoAsync` runs the probe on the thread pool (a `Directory.Exists` on `\\wsl$` boots a stopped distro and used to freeze the UI), polls WSL sessions every **30 s** (10 s local) and caches a "not a repo" answer for WSL so it does not spawn `wsl.exe` for it forever. - **Quoting.** Everything that reaches `wsl.exe` goes through `ShellSession.QuoteForCmd` — MSVCRT rules (backslashes before a quote doubled, trailing backslashes doubled), verified by round-tripping through `CommandLineToArgvW` in `Win32CommandLineTests`. There is one `BuildWslArgs` (`ShellSession.BuildWslArgs(string? inner)`); `RunInstance` delegates to it and turns a build failure into a failed run chip rather than a throw. - **Validation before UI.** `ShellSession.LaunchValidationError` (blank distro / blank SSH host) is checked at the top of `LaunchSessionAsync` before any WebView2 exists. `state.json` and imports are untrusted; a bad entry used to leak a pane. - **Relaunch paths.** `RecentlyClosedEntry` and the `session_history.snapshot_json` column carry `Kind` + WSL fields, so Ctrl+Shift+T, the "Recently closed" list and relaunch-from-search all restore the right kind. - **Known gaps:** WSL Claude sessions do not auto-resume on restore (`--resume` id lookup reads the Windows `~/.claude`); a distro name beginning with `-` is not defended against in `wsl.exe` option parsing. ## Windows Terminal Profile Import (opt-in) When `AppSettings.ImportWindowsTerminalProfiles` is on, the New Session dialog reads the user's Windows Terminal `settings.json` and offers each profile in a "Profile (optional)" combobox. **Service:** `WindowsTerminalProfileService.GetProfiles()` probes Stable / Preview / Unpackaged install paths, parses each `settings.json`, flattens `profiles.defaults`, filters hidden profiles, and emits `WindowsTerminalProfile` POCOs with appearance fields already mapped to xterm equivalents. **Per-session overrides** (all on `ShellSession`, all nullable, all persisted to `state.json`): - `ProfileFontFamily`, `ProfileFontSize`, `ProfileFontWeight`, `ProfileFontLigatures` - `ProfileCursorShape` (`"block" | "underline" | "bar"`), `ProfileCursorBlink` - `ProfilePadding` (CSS shorthand) - `ProfileBackgroundOpacity` (0.0–1.0; 1.0 = opaque) - `ProfileRetroEffect` (CSS scanlines overlay only — not a real CRT shader) - `ProfileColorSchemeJson` (pre-baked xterm theme) When any override is set, `LaunchSessionAsync` calls `bridge.ApplyProfileOverrides(session)` after `ApplyFontSettings`, posting a `setOptions` message that wins over the global font. **Transparency:** xterm.js requires `allowTransparency` in the constructor, so transparent sessions navigate to `Assets/terminal-transparent.html` instead of `terminal.html`. Both files share `Assets/terminal-init.js`. (Acrylic blur is not reachable from WebView2 — we get flat alpha over the WPF chrome instead.) **Once stamped, profile overrides are independent.** A session keeps its appearance even if the user later edits or deletes the source profile in Windows Terminal. ## Recently Closed Sessions Closing a session (`Ctrl+W`, sidebar `✕`, or terminal-toolbar close) pushes a snapshot onto a ring buffer (`AppState.RecentlyClosed`, cap `MainViewModel.MaxRecentlyClosed = 10`, newest first). Two ways to reopen: - **`Ctrl+Shift+T`** — pops the newest entry and re-launches it via `MainWindow.ReopenClosedSessionAsync`. The reopened session gets a **fresh Id** so it's independent of anything that may still reference the old one. - **"Recently closed" list at the top of the New Session dialog** — click an entry to reopen it; that entry is removed from the ring. Sleep/wake doesn't touch the ring (`SleepSession` bypasses `OnSessionCloseRequested`). `--clean` mode clears the ring at startup (full debug isolation) and never persists changes — `SaveStateAsync` is a no-op in clean mode. The snapshot model is `Models/RecentlyClosedEntry.cs` — a separate POCO from `ShellSession` so PTY/runtime fields (`IsDormant`, `Status`, `LastActivityAt`) don't leak into the ring buffer. `RunCommands` are deep-copied with fresh Ids on both snapshot creation and session recreation, so edits to either side never alias the other. Entries carry `Kind` and the SSH/WSL fields; legacy entries are migrated by `StateService.Normalize` like sessions. FTS5 scrollback retention is **out of scope** for v1 — restored sessions start with an empty xterm buffer. ## Shell Integration (OSC 9001) Programs running inside a terminal can push session state up to CSM by emitting a custom OSC sequence — useful for SSH overlays (e.g. `nexus`) where CSM cannot inspect the remote repo locally. > **Integrator-facing reference:** [`docs/shell-integration.md`](docs/shell-integration.md) (wire format + bash/PowerShell/Python/Node/Rust/Go snippets). The notes below are CSM-internal. **Wire format:** `ESC ] 9001 ; key=value ; key=value … ST` ST may be `BEL` (`\x07`) or `ESC \\` — xterm.js accepts both. **Recognised keys:** | Key | Effect | |---|---| | `color` | Override the session accent (`#rrggbb` / `#rgb` / `#rrggbbaa`). Repaints sidebar stripe + active ring. 8-digit values use alpha-last (`#rrggbbaa`); CSM converts to WPF's `#aarrggbb` internally. | | `git-branch` | Set `SessionViewModel.GitBranch` directly, bypassing `GitService`. | | `git-dirty` | `1`/`true` → dirty-marker shown; `0`/anything else → clean. | | `title` | Renames the session (calls `vm.Rename`). Capped at `ShellIntegrationPayload.MaxTitleLength` (80), control chars stripped; empty-after-cleanup is ignored. | Unknown keys are ignored. Multiple keys can be sent in a single sequence. Values cannot contain `;` (the field separator, no escaping) — documented as a limitation rather than solved. **Every value is untrusted.** It comes from whatever is printing to the terminal — a remote host, a `cat` of some file, a hook — and `color`/`title` end up in `state.json`. All validation lives in the WPF-free `Services/ShellIntegrationPayload` (`TryNormalizeColor`, `ParseDirty`, `SanitizeTitle`, `SanitizeBranch`) so it is unit-tested (`ShellIntegrationPayloadTests`); `SessionViewModel.ApplyShellIntegration` only applies what that class accepts. **Git poller stand-down.** Once a session has received `git-branch` or `git-dirty`, `RefreshGitInfoAsync` stops touching `GitBranch`/`GitIsDirty` (`_gitOverriddenByOsc`) — otherwise the local CWD's state would clobber the pushed value every 10s. The flag is per-session-lifetime, not persisted, and `ReloadGitInfoAsync` (folder edit) resets it, since the pushed info described the old folder. **Colour is sticky, so it is resettable.** OSC 9001 is the only writer of `ShellSession.ColorOverride` and the override survives sleep/wake and restart. The sidebar right-click menu shows **Reset accent color** (→ `vm.ClearColorOverride()`) whenever an override exists. **AlertDetector must strip both OSC terminators.** Its ANSI regex originally matched only BEL-terminated OSC; every example in `docs/shell-integration.md` uses `ESC \`, which either leaked the payload into prompt matching or lazily swallowed real output up to the next BEL. It now mirrors `OutputIndexer.AnsiPattern` — keep the two in step (`AlertDetectorStripAnsiTests`). **Pipeline:** `terminal-init.js` registers an OSC handler via `term.parser.registerOscHandler(9001, …)` (requires `allowProposedApi: true`, already set). It posts `{type: "shellIntegration", fields: {…}}` to WPF. `TerminalBridge` parses it and raises `ShellIntegrationReceived`. `MainWindow.LaunchSessionAsync` subscribes and calls `vm.ApplyShellIntegration(fields)` on the dispatcher, then `MainViewModel.SaveStateDebounced()` (500ms idle coalescing — a prompt hook fires on every prompt, and a `state.json` write per emission would be silly). Repainting the stripe and ring is **not** done here: the existing `AccentColor` `PropertyChanged` subscriptions in `BuildSidebarItem` / `BuildTerminalWrapper` already handle it, exactly as they do when `RepoRoot` lands. The OSC handler returns `true` so xterm consumes the sequence and it doesn't render. ## Sleep / Wake (Dormant Sessions) Sessions can be put to sleep instead of closed — the PTY is torn down but the `ShellSession` is kept in `state.json` (`IsDormant = true`) so it can be relaunched from the sidebar later. Useful when you have many long-running projects but only need a few live at once. **UI:** - 💤 button appears in both the sidebar action panel (next to ✕) and the terminal toolbar. - Dormant entries render with a muted (55% opacity) appearance, trailing the live rows. Clicking anywhere on a dormant entry wakes it; the small ✕ on a dormant entry permanently deletes (with confirmation). - **Dormant rows obey the group filter too.** In `FilterStrip` mode a group tab lists only its own sleeping sessions ("All" and `GroupDisplayMode.None` list every one); in `InlineHeaders` mode each sleeping row sits at the end of its own group section and counts toward that header's badge, so it collapses with the group. They used to be appended unconditionally at the very bottom — the comment there called it "kept reachable", but on a filtered tab it read as a leak, and a sleeping session already stays reachable one click away on "All". **Implementation (`MainWindow.xaml.cs`):** - `SleepSession(vm)` — sets `session.IsDormant = true`, removes from `_vm.Sessions` directly (bypassing `CloseCommand` so the `ShellSession` is **not** removed from `SessionManager`), disposes the VM, and calls `AddDormantSidebarItem(session)`. - `WakeSessionAsync(session)` — clears `IsDormant`, removes the dormant sidebar entry, then `await LaunchSessionAsync(session, restoring: true)`. On launch failure it restores the dormant entry. - `BuildDormantSidebarItem(ShellSession)` — builds a static (no-VM) sidebar Border with muted accent stripe + 💤 icon. Click handler resolves to `WakeSessionAsync`. - Dormant entries are tracked in `_dormantSidebarItems: Dictionary`. `AddDormantSidebarItem` only *registers* the row — it deliberately does **not** add it to the visual tree, because its placement depends on the display mode and the active filter. `RebuildSidebarOrder` is the single placer, and it walks `_sessionManager.Sessions` (not the dictionary) so sleeping rows follow drag-reorder like live ones. Every caller that stages a dormant row must run `RebuildSidebarOrder` afterwards — `SleepSession` and the wake-failure path do so in place of their old bare `RefreshTerminalLayout`. - `OnLoaded` partitions saved sessions: dormant ones go through `AddDormantSidebarItem`; live ones through `LaunchSessionAsync`. - The empty-state placeholder hides whenever `_vm.Sessions.Count > 0` **or** `_dormantSidebarItems.Count > 0`. ## Sidebar order and drag-and-drop **`SessionManager.Sessions` order is the one source of truth.** It is what the sidebar renders and what `state.json` persists. `_vm.Sessions` (the pane grid) is *derived* from it, via `MainViewModel.SyncSessionOrderFromManager` → `SessionOrder.AlignTo`. **Never carry an index from one list to another.** The two lists hold different sessions — the manager's includes dormant ones and every group, the view model's only live ones — and the visible sidebar rows are a third list again (cluster headers, group headers, dormant rows, and in FilterStrip mode only one group). Doing exactly that was the "a dragged session doesn't land where I want it" bug, and it had five separate causes, each reproduced by a simulation of the old code before it was fixed: 1. The drop index counted the visible rows, so a `⎇` worktree cluster header shifted it. 2. In FilterStrip mode, an index into the *filtered* rows was applied to the unfiltered list. 3. A `_vm.Sessions` index was applied to `SessionManager`, which also holds dormant sessions. 4. One index moved both lists, so the grid and the sidebar diverged. 5. Remove-then-insert at the pre-removal index made every downward move overshoot by one. So a drop now resolves to an **anchor id** (`SidebarDropResolver`: before X / after Y), which means the same slot in every list, and `SessionManager.MoveSessionRelative` finds the anchor *after* removing the moved session. There is deliberately no index-based move left. The insertion line drawn while dragging (`Views/InsertionLineAdorner`) is computed from that same resolved target, so it cannot disagree with where the drop lands. `RegisterSession` (new, woken or restarted sessions joining the grid) inserts by relative position for the same reason. Dropping onto an inline **group header** assigns that group and lands the session at the top of it, directly under the header. Dormant rows are never drop anchors; they always render after their section's live rows. **Auto-clustering places new sessions once and never re-sorts.** "Open PowerShell here" makes a ` (PS)` session in the same repo as its Claude session; `PlaceNewSessionsInClusters` moves it next to its sibling when its repo root resolves. Only sessions launched with `restoring: false` are eligible (`_clusterOnRepoResolve`), and a drag removes a session from that set. The previous `ApplyClusteredOrder` re-sorted *every* sibling on any Add/Remove and on every restore, so a PS session dragged away from its Claude session snapped back the next time anything opened or closed, and the saved order was rewritten on each launch. Covered by `SidebarDropResolverTests`, `SessionOrderTests` and `SidebarReorderScenarioTests` (the end-to-end scenarios, each of which misplaced the session before the fix). ## Per-Session Run Commands Each session can have a list of "run commands" — labelled command lines invoked by the toolbar ▶ button, the F5 keybinding, or the sidebar right-click submenu. Runs spawn a **separate headless `PseudoTerminal`** in the session's working folder (or a fresh `ssh` connection for SSH parents); they do **not** type into the parent PTY, so a Claude session is untouched. **Data:** `ShellSession.RunCommands: List { Id, Label, CommandLine, IsDefault, Mode, PostRunUrl }`. Exactly one item has `IsDefault=true`; see `RunCommandItem.EnsureSingleDefault`. Persisted to `state.json`. - **`Mode`** (`RunMode.Process` default / `RunMode.PowerShell`) — `Process` runs through `cmd /c` as before; `PowerShell` wraps the command line in `pwsh.exe -NonInteractive -NoLogo -ExecutionPolicy Bypass -EncodedCommand ` (falls back to `powershell.exe` if `pwsh` isn't on PATH). SSH and WSL parents ignore `Mode` — those runs always go through a POSIX shell (`ssh … bash -c` / `wsl.exe … -e -lc`, where the WSL shell is probed per-distro and falls back to `sh` where bash is absent). Use PowerShell when the command relies on pipes (`|`), redirection (`>`), `$env:` variables, or cmdlets. - **`PostRunUrl`** (`string?`, default `null`) — when set and the run exits with code 0, `Process.Start` opens the URL via `UseShellExecute=true` (default browser). No health-check polling. The value is gated by `RunInstance.IsLaunchableUrl` first: **only absolute `http`/`https` URLs are launched.** ShellExecute would otherwise run a local exe, a `.ps1`, a UNC path or any registered protocol handler, and this fires automatically with no confirmation — and `ImportExportService` deserializes a whole `AppState` (run commands included) from any JSON file the user points at, so the stored value is not trusted. Rejections and launch failures both append to `crash.log`; neither pops UI, since this runs on the PTY-exit callback thread. Scheme-less input (`localhost:5173`) is rejected rather than guessed at. **Templates:** `RunCommandTemplatesService.SeedFor(folder)` detects project type (top-level scan, first-match: dotnet → cargo → node → python → make) and returns a seed list with fresh Ids. Templates are *copied* onto new sessions at creation time; subsequent edits don't propagate back. SSH sessions skip detection (empty list). **Runtime:** `SessionRunner` (one per `SessionViewModel`) owns a dictionary of `RunInstance` keyed by item Id. Each `RunInstance` wraps a `PseudoTerminal` started with `useJobObject: true` so the whole child tree dies when the PTY is disposed (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`). Output is captured to an ANSI-stripped string buffer (capped at 1MB). Not persisted. **UI:** - Toolbar `[▶][▼]` next to ⚙ / 💤. Hidden when `RunCommands` is empty. - Chips strip between toolbar and terminal — one chip per active/finished run, color-coded (blue=running, green=ok, pink=failed). Click a chip to open the drawer; ✕ on a chip to dismiss it. - Drawer (slide-down panel, like Notes) shows the selected run's output with `[⏹ Stop] [📋 Copy] [↗ Send to terminal]`. - **Send to terminal:** for Claude parents (`ClaudeSessionService.IsClaudeCommand`), wraps in fenced preamble and writes to PTY (no trailing `\r`). For non-Claude shells, falls back to clipboard with a toast — auto-paste would risk executing pasted lines. **Editor:** `SessionRunCommandsDialog` modal — reachable from right-click on ▶, the ▼ dropdown's "Edit commands…" entry, and the sidebar right-click "Session commands" submenu. Inline-edit rows with up/down reorder, default-radio column, +Add / 🗑 Delete, Cancel/Save. **Keybindings:** `F5` runs the active session's default. `Shift+F5` stops it. Mirrors Visual Studio; deliberately not `Ctrl+R` (collides with shell history search). **Lifecycle:** All runs are killed on session close, session sleep, and app exit. `SessionViewModel.Dispose()` calls `Runner.Dispose()` which iterates and disposes every instance. `SleepSession` also calls `vm.Runner.StopAll()` defensively before UI teardown. ## Git tools on the terminal toolbar When a session's folder is a git repo, its terminal toolbar shows a chip — `⎇ main ● ↑2 ↓5` (branch, peach dirty dot, blue ahead/behind) — just left of ▶. Clicking it opens a menu: a header line (`main → origin/main · ↑2 ↓5 · 3 changed`), **Fetch**, **Pull (fast-forward only)**, **Status…**, **Switch branch ▸** (local branches, loaded when the submenu opens), and **Copy branch name**. The UI is in `MainWindow.Git.cs`; git calls are in `GitService`. Hidden for SSH sessions — an OSC 9001 branch is display-only, there is no local folder to run git in. **"Open in VS Code" is not in this menu** — it is not a git action and must work for a folder that isn't a repo. It lives in `MainWindow.OpenIn.cs`: a `{ }` button beside 📁 / >_ on the terminal toolbar, and an item after "Open PowerShell here" in the sidebar right-click menu. Both appear only when VS Code was found (`code.cmd` on PATH → its `Code.exe`, launched directly with the folder as one argv element, never through `code.cmd`/`cmd.exe`) and the session has a local folder. A configurable "Open with…" for other editors and installs is tracked in #178. **Deliberately read-mostly: no commit, push or merge.** A Claude session is usually editing that same working tree, and a one-click history write from outside its conversation is both a race and a misclick nobody can take back. Pull is `--ff-only --no-rebase`: it moves the branch only when that loses nothing, and on a diverged branch or a conflicting local edit git refuses and the panel shows why — it never stashes or merges on the user's behalf. Push, if ever added, should confirm and show exactly what is going out. **Nothing is typed into the terminal.** Every operation is its own background git process via `GitService` — in a Claude session, typed text would land in Claude's prompt. **One status call now feeds everything.** The poll used `branch --show-current` + `status --porcelain` (two spawns). It is now one `status --porcelain=v2 --branch` (`GitService.GetStatusAsync` / `ParseStatusV2`), which also yields upstream, ahead/behind and the changed-file list — cheaper *and* richer, since a spawn is ~all of the cost (see "Never spawn a process on the UI thread"). `GetGitInfoAsync` keeps its old contract on top of it, detached HEAD → `(null, false)` included. The extra fields (`GitUpstream`, `GitAhead`, `GitBehind`, `GitChangeCount`) follow the same rule as `GitBranch`: plain properties, announced only through `GitInfoVersion`. An upstream that is configured but whose remote branch is gone produces no `# branch.ab` line, so it reads "upstream gone", not "up to date". **Environment for every git spawn** (`GitService.GitEnvironment`): - `GIT_TERMINAL_PROMPT=0` — git has no console, so an HTTPS credential prompt would wait for input that can never come until the timeout. With it, git fails at once ("terminal prompts disabled") and `GitStatusText.FailureHint` says to sign in from a terminal once. GUI credential helpers (Git Credential Manager) are unaffected. - `GIT_OPTIONAL_LOCKS=0` on read-only calls — a plain `git status` opportunistically takes `index.lock`, which is how a background poll makes a git command the user (or Claude) runs at the same moment fail. - WSL: Windows env vars reach a distro only when `WSLENV` names them, so both are merged into it (`MergeWslEnv`) — without that, the git inside WSL never saw them. A timed-out run now kills the **whole process tree** — a fetch's real work happens in children (`git-remote-https`, `ssh`) that killing `git.exe` alone left running. **Switch branch** runs `switch --no-guess -- `. The name comes from the repo and a ref can legally be called `-x`; `--` keeps it a branch name (verified against git 2.54 with a branch literally named `-x`). `--no-guess` stops git silently creating a tracking branch for a name that exists only on a remote. **One operation per repo at a time** (`_gitBusyRepos`, keyed by `RepoRoot` so worktrees of one repo share the slot); the chip shows `⟳` meanwhile. Afterwards *every* live pane on that repo re-reads git state explicitly: a fetch moves only remote refs, which `GitRepoWatcher` (HEAD + index) never sees. Success → a toast; failure → the git panel (docked under the toolbar, like notes) opens with git's own output plus the recognised hint. Covered by `GitToolsTests.cs`: the parser against captured `porcelain=v2` output, the wording, the argv (hostile and option-shaped branch names round-tripped through `CommandLineToArgvW`), and the operations end to end against a throwaway bare "remote" — fast-forward, refusing a diverged branch even with `pull.rebase=true`, refusing to overwrite a local edit, the `-x` branch, and the remote-only branch `--no-guess` must not invent. Removing `--` or `--no-guess` fails 6 tests each; removing `--no-rebase` fails none, because git 2.54 already lets `--ff-only` win — it is kept as a guard for other git versions. ### Worktrees in the git menu Worktrees are the normal way this tool is used — a Claude session per task, each in its own worktree — so the git menu knows about them. Logic is in the WPF-free `Services/GitWorktrees`; the UI in `MainWindow.Git.cs`. - **Which worktree am I in.** In a linked worktree the chip tooltip and menu header end with `· worktree of
`. Worked out from the `.git` FILE (`gitdir: …/worktrees/`), with no git spawn, off the UI thread. A submodule's `.git` is a file too, so the `/worktrees/` segment is what tells them apart. - **Switch branch knows where branches are checked out.** git allows a branch in one worktree at a time; switching to one held elsewhere fails with `already used by worktree at …`. Such a branch is listed as `feature — in wt-feature` and opens that worktree instead. - **Worktrees ▸** lists every worktree (branch, dirty dot, ↑/↓ — one status per worktree, only when the submenu opens). Clicking one focuses its live session, else wakes a sleeping one, else opens a new session there. Then: New worktree from this branch…, **Prune N missing worktrees** (only git's bookkeeping for folders already deleted), **Remove this worktree…**. **Compare paths by their real form, never as strings.** git lists a worktree's long path; a session can hold an 8.3 spelling of the same folder, or reach it through a junction. This machine's `%TEMP%` is `C:\Users\MORTEN~1\…` (GitHub's runners use `RUNNER~1`), and the first end-to-end run of "Remove this worktree" failed on exactly that: the session was judged to be in no worktree, so the item never appeared. `GitWorktrees.Canonical` resolves both sides through `GetFinalPathNameByHandle` (expands 8.3, follows junctions and symlinks) before any comparison. It touches the disk, so it always runs off the UI thread. **Remove is the one write here beyond pull/switch, so it is guarded three ways:** refused up front when the worktree has changes; confirmed with the exact folder and the sessions it will close (and sleeping ones it will delete); and run as `git worktree remove` **without** `--force`, so git itself refuses modified, untracked or locked worktrees and never removes the main checkout. Deleting the branch is a separate, explicit question afterwards, using `branch -d` (not `-D`), so an unmerged branch is kept. **Refused when another repository lives inside it.** git's clean check does not look inside an ignored folder, and a nested worktree usually sits in one (`.worktrees/` in `.gitignore`). Reproduced with git 2.54: worktree B inside A's ignored `.worktrees/`, with uncommitted work — A reports clean, `git worktree remove A` exits 0 and deletes B, work included. Two checks, both at click time: `GitWorktrees.NestedInside` against a freshly re-read worktree list, and `GitWorktrees.NestedRepositories`, an on-disk scan for any folder below it with a `.git` of its own — an independent clone or another repo's worktree is deleted just the same, and only the scan sees those (it also catches submodules, which git refuses to remove anyway). Junctions are not followed. **Both fail closed:** the listing returns empty on any git error, so a list that does not contain the target refuses; a scan that hits its folder cap returns null and refuses. **Sleeping sessions are deleted only after git has removed the folder.** They never go through Recently closed, so deleting them before git ran meant a refusal lost them for good. **WSL paths follow Linux case rules.** `\\wsl.localhost\` is folded into `\\wsl$\` (GitService always reports the latter), and below the distro name paths compare case-sensitively — `/home/u/WT` is not `/home/u/wt`, and matching it would close the wrong worktree's sessions. **Close the sessions and wait for their processes to exit first.** On Windows a process whose cwd is inside the folder locks it, and git then fails half-way through the delete with `failed to delete … Permission denied` — verified by running the remove from inside the worktree. The remove therefore runs from the main worktree, after every session in the folder has been closed and its PTY's exit awaited (bounded, `HasExited` — see "Waiting for a PTY to exit"). Something else holding the folder (an editor, a dev server) still produces that error; `FailureHint` explains it and gives the `--force` command to finish with — safe, because git had already checked the tree was clean. `GitService.RunOpAsync` is now `Task.Run`-wrapped: its `Directory.Exists` used to run on the caller's thread, which for a WSL session is `\\wsl$` I/O on the UI thread. Covered by `GitWorktreeTests`, against real git: listing and branch mapping; the switch refusal; linked vs main vs submodule; removing a clean worktree (branch kept); refusing modified, untracked and locked ones and the main checkout; `branch -d` keeping an unmerged branch; deleting a branch named `-x`; prune touching only the missing one; and the 8.3 and junction spellings. Adding `--force` to the remove fails 3 tests; dropping `--` from the branch delete fails 2. The full flow was also run end to end in the app with a terminal open inside the worktree: session closed, folder deleted, merged branch deleted. `GitServiceThreadingTests` now also find the repo root from a worktree checkout, where `.git` is a file. ## Opening a folder in Explorer "Open in Explorer" (toolbar 📁, sidebar menu, note search results) goes through `Services/FolderOpener`, never `explorer.exe `. Passing the folder as Explorer's command line silently opened **Documents** instead for two kinds of path, measured by asking the Shell which folder each new Explorer window showed: - **forward slashes** (`C:/repos/wt-feat`) — the form git prints, which "New session in sibling worktree" (and the Worktrees menu) stored as a session's `WorkingFolder`; - **a comma** anywhere in the name — Explorer splits its arguments on commas, and quoting does not stop it. `FolderOpener` opens the folder itself through the shell (ShellExecute `open` on the full Windows path), which was right for every case tried — spaces, comma, `&`, `%`, forward slashes, trailing separator, 8.3 — and honours a replacement file manager. **It refuses anything that is not an existing directory first**: ShellExecute on a *file* runs it, and a folder path comes from `state.json` and imports. `LaunchSessionInSiblingWorktreeAsync` now stores the Windows form of the git path, so new worktree sessions don't carry forward slashes at all. ## Per-Session Notes Each session gets a collapsible 📝 notepad panel between the terminal toolbar and the terminal. Toggled by the 📝 button on the terminal toolbar; the panel is a docked 160px-high `TextBox` (`Visibility.Collapsed` by default). **Storage:** notes are **not** on `ShellSession` and not in `state.json`. They live in the FTS5 SQLite DB owned by `SearchService` in a separate `project_notes` table keyed by `folder_path` (the session's `WorkingFolder`). Two sessions in the same folder share one note; SSH sessions and sessions with no working folder don't get a note (`vm.WorkingFolder` is empty → save is skipped). - `SearchService.GetNoteAsync(folderPath)` — `SELECT content FROM project_notes WHERE folder_path = ?` - `SearchService.SaveNoteAsync(folderPath, content)` — UPSERT on `folder_path`, stamps `updated_at` (ms since epoch) **UI lifecycle:** content is lazy-loaded on the first time the panel is opened (`notesLoaded` flag in the toolbar build). Each keystroke restarts a 1-second `System.Threading.Timer` debounce; when it fires, `SaveNoteAsync` is called on the dispatcher thread. No explicit save action — closing the panel or the session just leaves the last debounce to flush. There's no save-on-exit hook, so a note edited in the final ~1s before app close can be lost. **Search integration:** `SearchService.SearchAsync` queries notes alongside terminal output — notes use `LIKE %query%` (short free-text, FTS5 overkill) and are tagged `SearchResultType.Note` so the search panel can label them. The note's row in the search panel is keyed by folder, not session. **Dormant sessions:** because notes are folder-keyed and live outside `state.json`, a dormant or reopened session in the same folder transparently picks up the existing note on next wake/restore. `AlertDetector` fires `AlertRaised(AlertEvent)` after 1.5s idle when it detects: - **ToolApproval**: Claude asking to run a tool (regex on approval phrases) - **InputRequired**: Claude's `❯` prompt or generic `y/N` prompts `SessionViewModel.RaiseAlert(message, alertType)` sets: - `NeedsAttention` → shows pink badge + global alert count - `IsWaitingForInput` → green dot in sidebar + terminal toolbar - `IsWaitingForApproval` → orange dot in sidebar + terminal toolbar `AlertDetector.NotifyUserInteracted()` clears alert state on user input. ## Session Spinners Two overlays cover launch and shutdown so the user sees progress instead of a blank pane. **Launch overlay (per session)** lives in `Assets/terminal.html` and `Assets/terminal-transparent.html` as a CSS-animated rotating SVG arc with a phase label. Visible by default; `TerminalBridge` posts `setBootState` after `NavigationCompleted` (label = `Starting {cmd}…` for local, `Connecting to {host}…` for SSH; accent = session color) and `bootDone` on the first PTY byte (via `OnPtyData → PostBootDoneIfNeeded`, race-safe via `Interlocked.CompareExchange`). An 8-second fallback timer scheduled in `NavCompleted` also calls `PostBootDoneIfNeeded` so silent sessions and slow SSH handshakes don't lock the user out of the pane. **You cannot draw WPF content over a terminal pane.** WebView2 is an `HwndHost`, and a native child window is composited by the OS *on top of* everything WPF renders — `Panel.ZIndex` does not enter into it. This is the same `HwndHost` fact recorded under "What makes a session active", but for **output** rather than input, and it is the more expensive half to rediscover: the code looks correct, the overlay is genuinely in the tree with `Panel.ZIndex="100"`, and it simply does not appear. The original centred shutdown spinner was invisible for exactly this reason. All the user ever saw was scrim leaking through the few-pixel gaps *between* panes — reported, fairly, as "more like 1 line, hard to see, no spinner". Anything full-window must therefore either collapse `TerminalGrid` first (what `OnClosing` does) or live in the toolbar/sidebar chrome, which no `HwndHost` covers. **Restore rail (startup, app-level)** — `RestoreRail` (a 2px `ProgressBar`, `FlatBar` style) docked under the toolbar plus a `RestorePill` counter in the toolbar's right stack, both driven by `SetRestoreProgress(done, total)` from the `OnLoaded` restore loop and hidden outside it. Determinate on purpose: a 25-session restore runs ~131s with per-session cost swinging 12×, so there is no rate to extrapolate and a spinner reads identically at session 2 and session 22. Placed in the toolbar because that is above the airspace problem. The counter advances *after* the `try`/`catch` around `LaunchSessionAsync`, so a session that fails to restore still moves the rail — otherwise one bad session strands it short of full, which reads as a hang. **Shutdown board (app-level)** — `ShutdownOverlay` is now a card listing every session with a per-row glyph (`·` pending → `◐` closing → `✓` clean / `⨯` force-disposed), elapsed time, an overall `k / N` bar, and a budget bar running against `ClaudeShutdownBudgetMs`. Built by `BuildShutdownBoard`, updated in place by `MarkShutdownRow` / `SetShutdownProgress` / `SetShutdownBudget`. Force-disposed sessions are **marked, not hidden** — that is the case a user most wants to see, and it used to happen silently. `ShutdownHint` escalates with elapsed time to explain *why* the wait is long; keep it explanatory rather than jokey, since it has to still read well on the four-hundredth shutdown. The board is skipped entirely when there are no sessions, so `--clean` runs don't get a full-window flash of "0 / 0". Full design: `docs/superpowers/specs/2026-05-16-session-spinners-design.md`. Option comparison behind the current design: the "Waiting States" artifact (Quiet Rail for startup, Restore Board for shutdown — the two paths deliberately differ, because restore does not block the user and shutdown does). ## Search - All PTY output is stripped of ANSI and indexed to SQLite FTS5 by `OutputIndexer` - `SearchService.SearchAsync(query, limit)` uses FTS5 `snippet()` for result excerpts - Clicking a result navigates to the matching session; panel auto-closes (configurable) ## Settings (AppSettings) Persisted in `state.json`. Key settings: - `AutoRestoreSessions` — restore open sessions on next launch - `AutoResumeClaude` — when restoring, append `--resume ` to claude commands so the prior conversation is picked up. Toggle off if you want fresh sessions on restart. - `ClaudeLaunchStaggerMs` (default 2000) — flat delay between consecutive Claude launches, and the cap on the post-exit settle at shutdown. The Claude CLI rewrites its config unlocked on startup and exit, so two `claude.exe` doing it at once can lose each other's updates. Evidence this is real: a machine here had two orphaned `.claude.json.tmp..` files with the same timestamp and different pids. **Do not replace this with an adaptive wait again.** That was tried (#96), watched the config file settle instead of sleeping a fixed 2s, and was reverted in #111 after three attempts to make it hold its cap. Measured on a real restore it produced gates of 12574ms, 22953ms and 31378ms against a 2000ms cap. Two follow-ups helped without bounding it: #107 moved it off the UI thread, #110 removed a thread-pool thread that `PseudoTerminal` was parking per PTY. The reason it could never work is worth recording: the restore loop periodically stalls for seconds at a time under load, and *any* timer's continuation absorbs that stall. After the revert, a plain `Task.Delay(2000)` still logged `gate=36339ms`. The gate was never slow — it was a stopwatch measuring someone else's freeze. The gate is now gone from BOTH paths. It was kept at shutdown on the reasoning that "the machine is quiet there, so polling is reliable" — measurement falsified that: a real run logged `cfgSettle=8731ms` against a 1000ms cap, 56% of the entire shutdown budget in one session, which is what forced the rest of the fleet to be killed without a wait. Same disease, same fix: flat delay. - `ShowGitBranch` — show `⎇ branch` in sidebar - `ShowTerminalStatusDot` — show status dot in terminal toolbar - `SidebarActionIconsMode` — `OnHover` (default) / `Always` / `Hidden`. Controls the per-row `➕ 💤 ✕` button stack in the sidebar. `Hidden` collapses the panel and reclaims the horizontal space; `OnHover` keeps the panel laid out (no text shift on hover) but transparent + non-interactive until the row is hovered. Rename / Open in Explorer / Open PowerShell here remain reachable via the right-click context menu in all modes, and the terminal toolbar's `✕` is unconditional. - `SearchCollapseAfterNavigate` — auto-close search after clicking result - `MaxSearchResults` — FTS5 result limit (default 100) - `DefaultWorkingFolder` / `DefaultCommand` — pre-fill new session dialog **Layout persistence**: `AppState.LastLayout` (string, e.g. `"TwoByTwo"`) persists the active grid layout. On startup, `MainViewModel.LoadStateAsync` parses it into `Layout`, which fires `MainViewModel.PropertyChanged`; the `MainWindow` constructor subscribes and syncs `_currentLayout` + calls `RefreshTerminalLayout`, so the saved layout is what the user sees on relaunch. ## Keyboard Shortcuts | Key | Action | |---|---| | `Ctrl+T` | New session | | `Ctrl+Shift+T` | Reopen the most-recently-closed session (browser convention) | | `Ctrl+Alt+T` | Duplicate active session (was `Ctrl+Shift+T` pre-bundle) | | `Ctrl+W` | Close active session | | `Ctrl+F` | Toggle search | | `Ctrl+Tab` | Cycle sessions | | `F5` | Run the active session's default run command | | `Shift+F5` | Stop the active session's default run command | | `Escape` (in search) | Close search panel | | `Enter` (in search) | Execute search | ## Testing | Project | Type | Command | |---|---|---| | `tests/CodeShellManager.Tests/` | Unit tests (xunit) | `dotnet test tests/CodeShellManager.Tests/` | | `tests/CodeShellManager.UITests/` | FlaUI UI tests | `dotnet test tests/CodeShellManager.UITests/` | Unit tests cover model logic (`ShellSession`, etc.) and run headless. UI tests require the app running on a live Windows desktop. `ShellSession.BuildSshArgs()` is `internal` — accessible from tests via `[assembly: InternalsVisibleTo("CodeShellManager.Tests")]` in `AssemblyInfo.cs`. **`IPseudoTerminal` testability seam.** `PseudoTerminal` implements `IPseudoTerminal` (in `Terminal/IPseudoTerminal.cs`), and `RunInstance` / `SessionRunner` both expose an `internal` constructor that accepts a `Func` factory. Production code uses the parameterless public ctors which default to `() => new PseudoTerminal()`; tests pass a hand-rolled `FakePseudoTerminal` to exercise the run-command lifecycle (Run, Stop, Dismiss, kill-and-restart, 1MB output-buffer cap) without spawning a real ConPTY child. Keep the interface surface minimal — only what `RunInstance` actually calls (`DataReceived`, `Exited`, `ExitCode`, `Start`). **SearchService tests** open a fresh file-backed SQLite at `Path.GetTempPath()` per test for isolation. The test class is `IDisposable` and clears the connection pool (`SqliteConnection.ClearAllPools()`) before deleting the file on Windows. Seed `session_history` rows with explicit timestamps rather than `Task.Delay` — Windows' 15.6ms timer granularity makes wall-clock-based ordering flaky on CI. ## Releases CI/CD is in `.github/workflows/build.yml`. Releases are triggered by pushing a `v*.*.*` tag: ```bash git tag v1.2.3 -m "v1.2.3 - description" git push origin v1.2.3 ``` The tag value overrides the csproj `` at publish time (`-p:Version=` flag). `AssemblyVersion` / `FileVersion` are deliberately **not** set in the csproj so they derive from `Version` — pinning them is what made every release through v0.5.0 ship binaries reporting `FileVersion 0.3.4.0`. CI produces a signed exe, MSI installer, and portable ZIP, then creates a GitHub Release automatically. ### Pushing the tag is only half the release **The `release: released` triggers on `winget.yml` and `chocolatey.yml` have never fired.** Every run in the repo's history is a `workflow_dispatch`. This is GitHub behaving as designed: events raised by a workflow authenticated with the default `GITHUB_TOKEN` do not trigger other workflows, and `softprops/action-gh-release` creates the Release with exactly that token. Both workflows still *declare* the trigger, which makes it look automatic. It is not. **Post-tag checklist — required, not optional:** ```bash # 1. wait for CI / Release to finish and the GitHub Release to exist # 2. then dispatch the mirrors by hand gh workflow run winget.yml -f tag=vX.Y.Z gh workflow run chocolatey.yml -f tag=vX.Y.Z # 3. watch them — they fail independently of CI and nothing else will tell you ``` **Budget for winget needing a second dispatch.** It has required manual intervention on three consecutive releases (v0.6.0, v0.7.0, v0.9.0) — a different cause each time, which is why it keeps getting rediagnosed from scratch. Chocolatey has been reliable. See "winget: the `CreateRef` error names the wrong culprit" for how to tell this release's cause from the last one's; the short version is **read the error text and check whether the sync step passed before touching anything**. To make it genuinely automatic, CI / Release would have to create the Release with a PAT rather than `GITHUB_TOKEN`. That is also what would close the sync→submit race, since the mirrors would no longer be dispatched as a separate step minutes later — worth doing before v1.0. **Chocolatey moderation: cleared 08 Sep 2026.** The v0.5.0 submission — the package's first — sat in the human review queue from May, which is why the listing stayed on 0.5.0 through two releases and why its download counter (44) reflects the moderation pipeline more than users: a package under moderation isn't listed in search and can't be installed without an explicit `--version`. That is now resolved and dispatching works normally. Two things learned from that first submission, both worth keeping: - **A first submission to a new package id goes to human review, and can take months.** Only the *first* one; subsequent versions from a maintainer with an approved package auto-verify. Plan the first release of any new id accordingly. - **Don't back-fill skipped versions.** Only the newest matters to `choco install`; submitting 0.6.0 and 0.7.0 now would be pure churn. Go straight to the current tag. The moderator explicitly endorsed the WebView2 approach from #112 — probing all three EdgeUpdate registry keys and *warning* with a symptom and remedy rather than hard-failing or force-installing. They floated `` as an alternative and then argued against it themselves, since it forces an install on machines that already have the runtime (all of Windows 11). Keep the warning; do not add the dependency unless blank-terminal reports actually show up. ### Download counts: GitHub's number already contains the other two There is no per-channel breakdown, and it is easy to add the three up and get a wrong total. Both mirrors resolve to **the GitHub Release MSI asset**: the winget manifest's `InstallerUrl` points straight at it, and `.chocolatey/tools/chocolateyinstall.ps1` has its `__URL64__` placeholder substituted with the same URL at pack time. So the MSI `download_count` on the GitHub Release is the **union** of GitHub-direct, winget and Chocolatey installs — not the GitHub-only slice — and Chocolatey's own counter is a subset of it, not an addition. It also includes the winget-pkgs validation pipeline's download of each submitted MSI. Winget publishes no install statistics at all (Microsoft doesn't expose them, and the unofficial `api.winget.run` index doesn't carry this package). Separating the channels would mean publishing a byte-identical second MSI per release and pointing `winget.yml`'s `installers-regex` at it — same SHA256, so winget-pkgs validation is unaffected — and that only works going forward. ### winget: the `CreateRef` error names the wrong culprit `winget.yml` submits the signed MSI to microsoft/winget-pkgs as `UmageAI.CodeShellManager` via [winget-releaser](https://github.com/vedantmgoyal9/winget-releaser). Needs `WINGET_TOKEN` — a **classic** PAT (fine-grained tokens are unsupported) with **both** `public_repo` and `workflow`. When it fails you will see: ``` 0: AThraen does not have the correct permissions to execute `CreateRef` 1: failed to create branch UmageAI.CodeShellManager-- ``` **The message points at the wrong thing.** Two distinct causes produce it, and the token itself is the *second* one, not the first: 1. **The fork is stale.** komac creates its branch in `umage-ai/winget-pkgs`; upstream lands dozens of commits a day, so a fork untouched since the last release is always too far behind for GitHub to accept a new branch. 2. **`WINGET_TOKEN` is missing the `workflow` scope**, so the automatic sync that would have fixed (1) *cannot* run — `merge-upstream` returns HTTP 422 because upstream winget-pkgs contains `.github/workflows/*.yml` and syncing means writing them. The fork stays stale and you land back at (1). **As of v0.9.0 both of those are fixed, and a third cause has taken over — read the error text before assuming either.** The failure now looks like this instead, with **no** mention of permissions or of a user: ``` 0: Ref cannot be created. 1: failed to create branch UmageAI.CodeShellManager-- ``` That shape is a **race, not staleness**. Measured on the v0.9.0 release (2026-09-30): the workflow's sync step *succeeded* at 18:51:46, the submit failed at 18:52:23, and at the moment of failure the fork was behind upstream by exactly **5 commits** — everything winget-pkgs had landed in those 34 seconds. komac resolves the upstream HEAD at submit time and branches from it, so a commit that arrived inside the gap is one the fork does not have yet and the ref cannot be created. Re-running `merge-upstream` by hand (clean fast-forward to 0/0) and dispatching immediately succeeded with no other change. So **diagnose by the error text and the sync step's own conclusion, in that order**: | What you see | Cause | Fix | |---|---|---| | `…does not have the correct permissions to execute CreateRef`, **sync step failed** | token missing `workflow` | fix the scope | | same message, **sync step succeeded**, fork far behind | stale fork the sync could not close | `merge-upstream`, re-dispatch | | `Ref cannot be created.`, **sync step succeeded**, fork behind by a handful | the sync→submit race | `merge-upstream`, re-dispatch **immediately** | **Check the direction when you compare forks.** `gh api repos/umage-ai/winget-pkgs/compare/master...microsoft:winget-pkgs:master` takes the fork as *base* and upstream as *head*, so `ahead_by` is how far **upstream is ahead of the fork** and `behind_by` is the fork's own extra commits. Reading it the natural way round turns "5 behind upstream" into "5 ahead of it" and sends you looking for a divergence that isn't there. Expect this to recur: the window is as wide as the gap between the sync step and the submit step, against a repository that commits dozens of times a day. Closing it properly means syncing inside the submit step rather than ahead of it — or removing the manual dispatch entirely (see the `GITHUB_TOKEN` note above), which removes the gap with it. Two traps that cost real time across v0.6.0 and v0.7.0: - **Sync the fork under the org, `umage-ai/winget-pkgs`** — komac uses the fork owned by the same account as this repo. A maintainer's *personal* fork (`AThraen/winget-pkgs`) may also exist and is a red herring; syncing it changes nothing. Re-tested at v0.9.0, because the original error names `AThraen` and the personal fork is an obvious suspect: it sat **19,108 commits behind** upstream, untouched since 2026-08-19 — and v0.7.0 and v0.8.0 both published successfully in September while it was already that stale. komac is not using it. Don't re-open this one. - **`public_repo` alone is not enough — the token also needs `workflow`.** This was recorded backwards here through v0.6.0 ("`public_repo` is sufficient"), which is why the same failure was rediagnosed three releases running. It is still true that widening to *full* `repo` is wrong and does not help: that grants CI write access to every private repo the owner can reach. `public_repo` + `workflow`, nothing more. `winget.yml` syncs the org fork automatically before submitting, and that step is deliberately **not** `continue-on-error` — it used to be, which is exactly how a failing sync stayed invisible and only the misleading `CreateRef` error was ever seen. That change earned its keep at v0.9.0: the sync step passing is what ruled out both historical causes in one glance. If the sync fails, fix the token scope; to unblock a release in the meantime, sync by hand and re-dispatch: ```bash gh api -X POST repos/umage-ai/winget-pkgs/merge-upstream -f branch=master ``` A third workflow, `.github/workflows/chocolatey.yml`, also fires on `release: released` and publishes the signed MSI to community.chocolatey.org as `codeshellmanager`. It downloads the MSI from the GitHub Release, computes its SHA256, substitutes `__URL64__` / `__CHECKSUM64__` placeholders in `.chocolatey/tools/chocolateyinstall.ps1`, then runs `choco pack` and `choco push`. Needs the repo secret `CHOCO_API_KEY` (API key from a chocolatey.org account with push rights on the `codeshellmanager` id). Also `workflow_dispatch`-able with a `tag` input. The `.chocolatey/` folder holds the package skeleton (`codeshellmanager.nuspec`, `tools/chocolateyinstall.ps1`, `tools/chocolateyuninstall.ps1`); never commit a resolved URL or checksum into the install script — those placeholders are only substituted by the workflow at pack time. The nuspec's `licenseUrl` points at the GitHub `LICENSE` file, so no bundled `LICENSE.txt`/`VERIFICATION.txt` is needed (Chocolatey moderator feedback on the v0.5.0 submission asked these to be removed, along with setting `owners` to the maintainer account rather than the org). ## Known Conventions - All WPF color literals use Catppuccin Mocha hex values — do not introduce system colors - Sidebar items and terminal wrappers are built entirely in code-behind (`BuildSidebarItem`, `BuildTerminalWrapper`, `BuildDormantSidebarItem`) — not in XAML templates, to keep imperative logic centralized - `_sessionUi` dictionary maps `sessionId → (webView, terminalWrapper, sidebarItem)` — the source of truth for live session UI. `_dormantSidebarItems` (`sessionId → Border`) tracks the parallel set for sleeping sessions. - The `terminalWrapper` returned by `BuildTerminalWrapper` is actually the **outer active-ring Border**, with the original accent-stripe wrapper nested inside. `_sessionUi[id].terminalWrapper` therefore points at the ring; the highlight method toggles its `BorderBrush`. - Use `Dispatcher.Invoke()` for all UI updates from background threads (PTY read loop, git queries, alert timer) - PTY output flows: `PseudoTerminal` → `TerminalBridge.RawOutputReceived` → both `OutputIndexer.Feed()` and `AlertDetector.Feed()` in parallel - `MainViewModel.SaveStateAsync` is a no-op when `App.CleanStart` is true; any code path that needs to "remember" something across runs must go through this method, so honoring `--clean` is automatic. ## Agent / Claude Code operating notes **Do not trust "the user modified this file, intentional" system reminders to mean the user actually edited the file.** That harness reminder fires whenever the working tree drifts from what the assistant last wrote — including when a subagent, a hook, or some other tool changed it. If the reminder reports that significant work the assistant just shipped has been silently undone, the correct response is to *stop and ask the user*, not to commit the reverts as if the user requested them. Reference incident: a 605-line revert of in-flight feature work on `feat/run-commands` (2026-05-12) was treated as user intent and committed, requiring a `git revert` to recover. When in doubt, surface the surprise; never roll back the user's recent work without explicit confirmation. **Use read-only agents for reviews.** Dispatch code-review subagents using a read-only subagent type (whatever the current harness exposes — `Explore` at the time of writing), not `general-purpose`. Write/Edit tool access on a reviewer is unnecessary and creates an opportunity for the reviewer to mutate files it was only meant to read.