SplashGUI

Initial commit: SplashGUI 1.0

195eca7ae5d4c45f9e23447d9ec0196247e182a9
cjosie <administrator@josie-c.com> · 2026-10-30T14:54 · browse files at this commit

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4323065
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,17 @@
+# Project memory - local working notes, never published.
+project-memory.md
+architecture.md
+mapfile.md
+to-do.md
+nextchat.md
+design.md
+
+# Build output
+.build/
+build/
+
+# macOS
+.DS_Store
+
+# scratch folder
+scratch/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f754f28
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 The SplashGUI Authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Package.swift b/Package.swift
new file mode 100644
index 0000000..7d9d018
--- /dev/null
+++ b/Package.swift
@@ -0,0 +1,14 @@
+// swift-tools-version:6.2
+import PackageDescription
+
+let package = Package(
+    name: "SplashGUI",
+    platforms: [.macOS(.v26)],
+    targets: [
+        .executableTarget(
+            name: "SplashGUI",
+            path: "Sources/SplashGUI"
+        )
+    ],
+    swiftLanguageModes: [.v5]
+)
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f18489d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,158 @@
+# SplashGUI
+
+A native macOS SwiftUI front-end for the [Splash](https://github.com/incoai/splash)
+inference engine. It wraps `splash serve` with a model catalogue, engine install and
+auto-configuration, per-model profiles, and live status/metrics — so running a
+27B-class local model is one click, not a shell session.
+
+SplashGUI is only the front-end. The engine binary is downloaded separately from the
+upstream project at first launch; see [the engine's README](https://github.com/incoai/splash)
+for how the engine itself works.
+
+## Features
+
+- **One-click server.** Start/stop the engine from the window toolbar; the app
+  launches `splash serve`, watches its logs, and shows live phase (starting, ready,
+  exited) in the footer.
+- **Engine manager.** First launch downloads the pinned Splash engine build (~71 MB),
+  verifies its SHA-256, and installs it atomically. Updates are checked on start and
+  can be overridden with a custom version/URL/digest.
+- **Model catalogue.** Splash's own suggested-model list (same order the engine's desktop
+  app offers), with revision + hash pinning on the entries verified on hardware, plus a
+  free-form `owner/repo[:variant]` slot for anything else.
+- **Auto-configuration.** Context size, memory cap, and KV format are derived from the
+  model's on-disk size and the machine's RAM/Metal headroom; per-model profiles let you
+  override and then "Reset to model card".
+- **SSD KV-cache tier.** The engine's persistent prefix cache gets a configurable disk
+  quota (default 10 GB) and survives server restarts when enabled — repeated prompts
+  re-prefill from disk instead of from scratch.
+- **Presets.** Multi-turn prompt sequences you can run against the live server with
+  streamed output and per-run metrics — a built-in smoke test and A/B harness.
+- **Status dashboard.** TTFT, prefill/decode throughput, draft acceptance, cache hit
+  rate, KV/GDN-state residency, and a RAM meter, with time-series charts.
+
+The engine runs the model's FFN projections on the Apple Neural Engine when it can
+(≈1.3× prefill on a 16-core M5 Pro with Qwen3.8-27B); the app simply leaves that
+engine-side behaviour enabled.
+
+## Requirements
+
+- macOS 26.4 or later
+- Apple silicon
+- Enough RAM for the model you pick — see the catalogue table below
+
+## Install
+
+Download the latest `SplashGUI-<version>.dmg` from
+[Releases](https://github.com/cjosie/SplashGUI/releases), open it, and drag
+SplashGUI to `/Applications`. The app is signed with a Developer ID certificate and
+notarized, so Gatekeeper opens it without any right-click workaround.
+
+On first launch the app downloads the Splash engine into its application-support
+directory. Model weights are downloaded from Hugging Face when you start a model.
+
+## The model catalogue
+
+The picker ships Splash's own suggested list — the same models and order the Splash
+desktop app offers, and the `splash` CLI completes — so the catalogue follows the engine
+rather than a third-party opinion. Download sizes are the engine's own figures and
+**include the auto-paired DFlash2 speed draft and vision projector**, the same basis the
+app's "too large for this Mac" warning uses.
+
+| Model | Download | Smallest Mac | Notes |
+| --- | --- | --- | --- |
+| Qwen3.6-35B-A3B Q4_K_M (GGUF) | 24 GB | 36 GB | Fast all-rounder |
+| Qwen3.6-35B-A3B MLX 4-bit | 21 GB | 36 GB | Fast all-rounder |
+| Qwen3.6-35B-A3B Q2_K_XL (GGUF) | 14 GB | 24 GB | Fast all-rounder |
+| Qwen3.8-27B Q4_K_M (GGUF) | 21 GB | 36 GB | Strongest at this size, slower |
+| Qwen3.8-27B MLX 4-bit | 20 GB | 36 GB | Strongest at this size, slower |
+| Qwen3.8-27B IQ3_XXS (GGUF) | 16 GB | 24 GB | Strongest at this size, slower |
+| Qwen3.8-Flash-Next Q2_0 (GGUF) | 69 GB | 64 GB | Most capable |
+| Flint Q4_K_XL (GGUF) | 26 GB | 48 GB | Text only |
+| Ornith-1.5-122B Q4_K_XL (GGUF) | 82 GB | 128 GB | Largest model |
+| Ornith-1.5-122B MLX 4-bit | 71 GB | 128 GB | Largest model |
+| Ternary-Bonsai 2 27B PQ2_0 | 12 GB | 24 GB | Smallest download |
+| Custom… | — | — | Any `owner/repo[:variant]` |
+
+Entries we have verified on hardware carry an exact Hugging Face revision and file
+digest (today: IQ3_XXS and Bonsai PQ2_0), so a re-upload under the same name can't
+silently change what your Mac loads; the rest follow the engine's default resolution.
+
+## Confirmed models for the Custom slot
+
+Beyond the catalogue, these have run well under SplashGUI — copy the ID into **Custom…**:
+
+| Model ID | Notes |
+| --- | --- |
+| `cjosie/Qwen3.8-27B-MLX-4bit-GPTQ` | The maintainer's daily driver; most real-world numbers were logged on this quant |
+| `unsloth/Qwen3.8-27B-GGUF:UD-IQ4_XS` | ~19 GB with draft + vision; comfortable on 32 GB Macs |
+| `unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_XL` | Dynamic 4-bit with 6-bit layers; the quality pick of the GGUF family |
+
+Custom entries are unpinned (no revision/hash pre-flight) — you get whatever the Hub
+serves today.
+
+## Using the server
+
+While the server is running it exposes an OpenAI-compatible API at
+`http://localhost:8095/v1` (port configurable on the Run tab). Any client that speaks
+that API — OpenAI's own SDKs, coding agents, chat front-ends — can point at it. For a
+quick start without any external tool, the engine also serves a built-in web chat page
+in the browser ("Built-in web chat page" toggle, on by default).
+
+## Building from source
+
+Requires the Swift 6.2 toolchain (Xcode 26 or the standalone toolchain).
+
+```sh
+swift build
+scripts/bundle-app.sh --open      # ad-hoc signed build/SplashGUI.app
+```
+
+`scripts/bundle-app.sh --release` produces a signed, notarized `SplashGUI-<version>.dmg`.
+Set `SIGN_IDENTITY` (a `Developer ID Application` identity) and `NOTARY_PROFILE` (a
+`notarytool` keychain profile) in the environment first.
+
+## Tests
+
+```sh
+scripts/profile-test/run.sh
+```
+
+Headless regression for the config store and per-model profiles (drives the real
+`AppModel`, no GUI). Quit SplashGUI before running it.
+
+## Headless modes
+
+The app binary doubles as a CLI for scripting and CI:
+
+```sh
+SplashGUI.app/Contents/MacOS/SplashGUI --install-engine   # install the pinned engine
+SplashGUI.app/Contents/MacOS/SplashGUI --auto-profile     # print the derived launch args
+SplashGUI.app/Contents/MacOS/SplashGUI --check-model      # verify installed weights' hash
+```
+
+## Release
+
+Maintainers only:
+
+```sh
+scripts/bundle-app.sh --release
+scripts/release.sh                # tags, pushes, and creates the GitHub release
+```
+
+## Contributing
+
+Issues and pull requests are welcome. A few notes:
+
+- Run `swift build` (zero warnings expected) and `scripts/profile-test/run.sh`
+  before opening a PR.
+- New `RunConfig` fields must be added to the explicit `init(from:)` decoder with a
+  `decodeIfPresent` default — the synthesized `Codable` would break existing
+  `config.json` files and silently reset every stored profile to factory defaults.
+- Keep GUI copy and code in English; match the existing SwiftUI patterns
+  (`Core/` is logic, `Views/` is presentation, `AppModel` is the single observable).
+
+## License
+
+MIT — see [LICENSE](LICENSE). SplashGUI ships no engine code; the Splash engine it
+manages is licensed separately under Apache-2.0 by its authors.
diff --git a/Resources/Info.plist b/Resources/Info.plist
new file mode 100644
index 0000000..49c5743
--- /dev/null
+++ b/Resources/Info.plist
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDisplayName</key>
+	<string>SplashGUI</string>
+	<key>CFBundleExecutable</key>
+	<string>SplashGUI</string>
+	<key>CFBundleIdentifier</key>
+	<string>com.splashgui.app</string>
+	<key>CFBundleName</key>
+	<string>SplashGUI</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>1.0</string>
+	<key>CFBundleVersion</key>
+	<string>4</string>
+	<key>LSApplicationCategoryType</key>
+	<string>public.app-category.developer-tools</string>
+	<key>LSMinimumSystemVersion</key>
+	<string>26.4</string>
+	<key>NSHighResolutionCapable</key>
+	<true/>
+	<key>NSPrincipalClass</key>
+	<string>NSApplication</string>
+	<key>NSSupportsAutomaticTermination</key>
+	<false/>
+	<key>NSSupportsSuddenTermination</key>
+	<false/>
+</dict>
+</plist>
diff --git a/Sources/SplashGUI/Core/AppConfig.swift b/Sources/SplashGUI/Core/AppConfig.swift
new file mode 100644
index 0000000..d8ece17
--- /dev/null
+++ b/Sources/SplashGUI/Core/AppConfig.swift
@@ -0,0 +1,491 @@
+import Foundation
+
+struct RunConfig: Codable, Equatable {
+    var modelID: String = "unsloth/Qwen3.8-27B-GGUF:UD-IQ3_XXS"
+    var port: Int = 8095
+    // Auto sizes context, memory and KV from the Metal ceiling and the model's weights, and
+    // leaves the SSD cache to the engine. Off restores the typed values below.
+    var auto: Bool = true
+    var maxContext: String = "auto"
+    var maxMemory: String = "auto"
+    var kvFormat: String = "auto"
+    var maxCacheDisk: String = "10G"
+    var languageOnly: Bool = false
+    var decodeShare: Double = 0.5
+    var showWebUI: Bool = true
+    var defaultReasoningEffort: String? = nil
+    // How long the engine keeps its memory wired without a request. Its own default is 10m:
+    // the first request after an idle minute pays a weight restore and a slower first prefill,
+    // which on a 48 GB Mac is a poor trade for the memory it gives back.
+    var idleRelease: String = "60m"
+    // Keep the SSD KV/state tier across restarts, so a project you come back to restores its
+    // prefix instead of prefilling it again.
+    var persistentCache: Bool = true
+    var schemaVersion: Int? = 6
+
+    // The memberwise initializer goes away with any custom initializer, and the defaults
+    // below are what a missing key falls back to.
+    init() {}
+
+    // Explicit decoder: a config.json written by an older build lacks the fields added since,
+    // and the synthesized one throws on a missing key, which would drop the whole config —
+    // per-model profiles with it — back to factory defaults.
+    enum CodingKeys: String, CodingKey {
+        case modelID, port, auto, maxContext, maxMemory, kvFormat, maxCacheDisk
+        case languageOnly, decodeShare, showWebUI, defaultReasoningEffort
+        case idleRelease, persistentCache, schemaVersion
+    }
+
+    init(from decoder: Decoder) throws {
+        let c = try decoder.container(keyedBy: CodingKeys.self)
+        let d = RunConfig()
+        modelID = try c.decodeIfPresent(String.self, forKey: .modelID) ?? d.modelID
+        port = try c.decodeIfPresent(Int.self, forKey: .port) ?? d.port
+        auto = try c.decodeIfPresent(Bool.self, forKey: .auto) ?? d.auto
+        maxContext = try c.decodeIfPresent(String.self, forKey: .maxContext) ?? d.maxContext
+        maxMemory = try c.decodeIfPresent(String.self, forKey: .maxMemory) ?? d.maxMemory
+        kvFormat = try c.decodeIfPresent(String.self, forKey: .kvFormat) ?? d.kvFormat
+        maxCacheDisk = try c.decodeIfPresent(String.self, forKey: .maxCacheDisk) ?? d.maxCacheDisk
+        languageOnly = try c.decodeIfPresent(Bool.self, forKey: .languageOnly) ?? d.languageOnly
+        decodeShare = try c.decodeIfPresent(Double.self, forKey: .decodeShare) ?? d.decodeShare
+        showWebUI = try c.decodeIfPresent(Bool.self, forKey: .showWebUI) ?? d.showWebUI
+        defaultReasoningEffort = try c.decodeIfPresent(String.self, forKey: .defaultReasoningEffort)
+            ?? d.defaultReasoningEffort
+        idleRelease = try c.decodeIfPresent(String.self, forKey: .idleRelease) ?? d.idleRelease
+        persistentCache = try c.decodeIfPresent(Bool.self, forKey: .persistentCache) ?? d.persistentCache
+        schemaVersion = try c.decodeIfPresent(Int.self, forKey: .schemaVersion) ?? d.schemaVersion
+    }
+
+    private static func isAuto(_ value: String) -> Bool {
+        let v = value.lowercased()
+        return v == "auto" || v.isEmpty
+    }
+
+    // Resolves what actually launches. With Auto on, the four covered fields come from the
+    // profile (or Splash's own sizing when there is none — a custom ID) and the SSD cache is
+    // left to the engine; the typed values stay saved untouched. With Auto off, a field that
+    // still says "auto" (the pre-switch spelling) falls back to the profile as before, so
+    // SplashServer stays policy-free and never sees "auto" for --kv-format.
+    func effective(using profile: AutoProfile?) -> RunConfig {
+        var out = self
+        if auto {
+            if let p = profile {
+                out.maxContext = String(p.contextTokens)
+                out.maxMemory = String(p.maxMemoryBytes)
+                out.kvFormat = p.kvFormat
+            } else {
+                out.maxContext = "auto"
+                out.maxMemory = "auto"
+                if Self.isAuto(out.kvFormat) { out.kvFormat = "bf16" }
+            }
+            out.maxCacheDisk = "auto"
+            return out
+        }
+        if let p = profile {
+            if Self.isAuto(maxContext) { out.maxContext = String(p.contextTokens) }
+            if Self.isAuto(maxMemory) { out.maxMemory = String(p.maxMemoryBytes) }
+            if Self.isAuto(kvFormat) { out.kvFormat = p.kvFormat }
+        } else if Self.isAuto(kvFormat) {
+            out.kvFormat = "bf16"
+        }
+        return out
+    }
+}
+
+// The app's shipped starting point: the thinking-mode sampling every model in the catalog's card
+// recommends (both cards publish 1.0 / 0.95 / 20 / min_p 0 / presence 0, and the GGUFs carry it
+// as general.sampling.*). These values reach Splash through the client configs the Provider
+// tab writes — the app itself sends no requests.
+struct SamplingDefaults: Codable, Equatable {
+    var temperature: Double = 1.0
+    var topP: Double = 0.95
+    var topK: Int = 20
+    // Engine 1.5.0 accepts and applies both (server/frontend.py SAMPLING_NUMBERS); only
+    // logit_bias is refused. The Qwen card asks presence 1.5 with thinking off; the Bonsai
+    // card asks min_p 0.05 in thinking mode.
+    var presencePenalty: Double = 0
+    var minP: Double = 0
+    var maxTokens: Int? = nil
+    var seed: UInt64? = nil
+    var reasoningEffort: String? = nil
+
+    init() {}
+
+    // Tolerant decoder (the Codable trap): configs saved before presencePenalty/minP existed
+    // must decode with them defaulted, not throw.
+    enum CodingKeys: String, CodingKey {
+        case temperature, topP, topK, presencePenalty, minP, maxTokens, seed, reasoningEffort
+    }
+
+    init(from decoder: Decoder) throws {
+        let c = try decoder.container(keyedBy: CodingKeys.self)
+        let d = SamplingDefaults()
+        temperature = try c.decodeIfPresent(Double.self, forKey: .temperature) ?? d.temperature
+        topP = try c.decodeIfPresent(Double.self, forKey: .topP) ?? d.topP
+        topK = try c.decodeIfPresent(Int.self, forKey: .topK) ?? d.topK
+        presencePenalty = try c.decodeIfPresent(Double.self, forKey: .presencePenalty) ?? d.presencePenalty
+        minP = try c.decodeIfPresent(Double.self, forKey: .minP) ?? d.minP
+        maxTokens = try c.decodeIfPresent(Int.self, forKey: .maxTokens)
+        seed = try c.decodeIfPresent(UInt64.self, forKey: .seed)
+        reasoningEffort = try c.decodeIfPresent(String.self, forKey: .reasoningEffort)
+    }
+}
+
+// What one model keeps its settings as, so switching models in the picker swaps each model's
+// own sampling and serve fields back in. `reasoningEffort` lives in `sampling`; applying a
+// profile also mirrors it into `run.defaultReasoningEffort`, which is the serve flag.
+struct ModelProfile: Codable, Equatable {
+    var sampling = SamplingDefaults()
+    var auto: Bool = true
+    var maxContext: String = "auto"
+    var maxMemory: String = "auto"
+    var kvFormat: String = "auto"
+    var languageOnly = false
+
+    // Tolerant decoder (the Codable trap): profiles saved before `auto` existed must decode
+    // with it at its default, not throw — a nested failure drops the whole config to factory.
+    init() {}
+
+    // The memberwise initializer the custom initializers take away.
+    init(sampling: SamplingDefaults, auto: Bool, maxContext: String,
+         maxMemory: String, kvFormat: String, languageOnly: Bool) {
+        self.sampling = sampling
+        self.auto = auto
+        self.maxContext = maxContext
+        self.maxMemory = maxMemory
+        self.kvFormat = kvFormat
+        self.languageOnly = languageOnly
+    }
+
+    enum CodingKeys: String, CodingKey {
+        case sampling, auto, maxContext, maxMemory, kvFormat, languageOnly
+    }
+
+    init(from decoder: Decoder) throws {
+        let c = try decoder.container(keyedBy: CodingKeys.self)
+        let d = ModelProfile()
+        sampling = try c.decodeIfPresent(SamplingDefaults.self, forKey: .sampling) ?? d.sampling
+        auto = try c.decodeIfPresent(Bool.self, forKey: .auto) ?? d.auto
+        maxContext = try c.decodeIfPresent(String.self, forKey: .maxContext) ?? d.maxContext
+        maxMemory = try c.decodeIfPresent(String.self, forKey: .maxMemory) ?? d.maxMemory
+        kvFormat = try c.decodeIfPresent(String.self, forKey: .kvFormat) ?? d.kvFormat
+        languageOnly = try c.decodeIfPresent(Bool.self, forKey: .languageOnly) ?? d.languageOnly
+    }
+
+    // Snapshot of the live settings, for archiving the model you are switching away from.
+    static func snapshot(of config: AppConfig) -> ModelProfile {
+        ModelProfile(sampling: config.sampling, auto: config.run.auto,
+                     maxContext: config.run.maxContext,
+                     maxMemory: config.run.maxMemory, kvFormat: config.run.kvFormat,
+                     languageOnly: config.run.languageOnly)
+    }
+}
+
+// What Splash actually granted a custom model (no app-side profile): the window and memory
+// budget from /status, shown as Auto's values on the next launch without waiting for a serve.
+struct GrantedSettings: Codable, Equatable {
+    var contextTokens: Int
+    var memoryBytes: Int
+}
+
+struct AppConfig: Codable, Equatable {
+    var run = RunConfig()
+    var sampling = SamplingDefaults()
+    // Archive of per-model settings, keyed by the full model ID including its `:variant`
+    // (that suffix is part of Splash's selection-link name, so never strip it). The live
+    // editing state stays in `sampling`/`run`; an entry is written when you switch away from
+    // that model, and a model with no entry gets its task card instead.
+    var modelProfiles: [String: ModelProfile] = [:]
+    // Last Splash-granted context/memory for custom IDs, keyed by model ID (see GrantedSettings).
+    var grantedAuto: [String: GrantedSettings] = [:]
+    var engineVersionOverride: String = ""
+    var engineURLOverride: String = ""
+    var engineSHA256Override: String = ""
+    var checkEngineUpdate: Bool = true
+    // Which build to run: the compiled-in pin, the newest release, or a hand-set pin. The
+    // override fields above are the custom pin; they decode in every mode so a switch back
+    // to .custom restores whatever was typed before.
+    var engineMode: EngineMode = .pinned
+    // Launch = start: serves the saved model on the saved port without a click. Skips when
+    // something already owns the port (the adopt path wins), and in the headless harness
+    // (SPLASHGUI_TEST=1) so tests never spawn a server.
+    var startOnLaunch: Bool = false
+
+    init() {}
+
+    // Explicit decoder so an older config.json (written before a field existed) still loads with
+    // that field at its default. The synthesized one throws on a missing key, which would drop
+    // the whole config back to factory defaults and lose the user's settings.
+    enum CodingKeys: String, CodingKey {
+        case run, sampling, modelProfiles, grantedAuto
+        case engineVersionOverride, engineURLOverride, engineSHA256Override, checkEngineUpdate
+        case engineMode
+        case startOnLaunch
+    }
+
+    init(from decoder: Decoder) throws {
+        let c = try decoder.container(keyedBy: CodingKeys.self)
+        run = try c.decodeIfPresent(RunConfig.self, forKey: .run) ?? RunConfig()
+        sampling = try c.decodeIfPresent(SamplingDefaults.self, forKey: .sampling) ?? SamplingDefaults()
+        modelProfiles = try c.decodeIfPresent([String: ModelProfile].self, forKey: .modelProfiles) ?? [:]
+        grantedAuto = try c.decodeIfPresent([String: GrantedSettings].self, forKey: .grantedAuto) ?? [:]
+        engineVersionOverride = try c.decodeIfPresent(String.self, forKey: .engineVersionOverride) ?? ""
+        engineURLOverride = try c.decodeIfPresent(String.self, forKey: .engineURLOverride) ?? ""
+        engineSHA256Override = try c.decodeIfPresent(String.self, forKey: .engineSHA256Override) ?? ""
+        checkEngineUpdate = try c.decodeIfPresent(Bool.self, forKey: .checkEngineUpdate) ?? true
+        // Decoded as a string and mapped, never as the enum directly: a value written by a
+        // future build must fall back to .pinned, not throw and drop the whole config to
+        // factory defaults (the Codable trap).
+        engineMode = EngineMode(rawValue: try c.decodeIfPresent(String.self, forKey: .engineMode) ?? "pinned") ?? .pinned
+        startOnLaunch = try c.decodeIfPresent(Bool.self, forKey: .startOnLaunch) ?? false
+    }
+
+    func enginePinOverride() -> EnginePin? {
+        guard !engineVersionOverride.isEmpty, !engineURLOverride.isEmpty,
+              !engineSHA256Override.isEmpty else { return nil }
+        return EnginePin(version: engineVersionOverride, sha256: engineSHA256Override,
+                         url: engineURLOverride)
+    }
+
+    // Writes a model's saved profile into the live fields. reasoningEffort is also the serve
+    // flag, so it lands in both places, exactly as the reasoning-effort control writes them.
+    mutating func apply(profile: ModelProfile) {
+        sampling = profile.sampling
+        run.auto = profile.auto
+        run.maxContext = profile.maxContext
+        run.maxMemory = profile.maxMemory
+        run.kvFormat = profile.kvFormat
+        run.languageOnly = profile.languageOnly
+        run.defaultReasoningEffort = profile.sampling.reasoningEffort
+    }
+}
+
+struct CatalogModel: Identifiable, Equatable {
+    static let windowTokens = 262_144  // Qwen3.8 native window (no YaRN); Splash's own ceiling
+
+    let id: String
+    let label: String
+    let note: String
+    // Whole assembly (target + draft + vision), used to size the auto-profile before a download.
+    var approxBytes: Int? = nil
+    // The tsv's MEMORY column: the smallest Mac RAM the vendor says the variant is meant for.
+    // The picker's too-large warning gates on this, so note and warning agree by construction.
+    var memoryGB: Int? = nil
+    // Immutable HF commit the pull is pinned to, so a catalog entry always names one exact set of
+    // bytes; nil = the repository's default branch (unpinned). Passed as serve --revision.
+    var revision: String? = nil
+    // The GGUF the engine links into assembly target/, and the sha256 Hugging Face publishes for
+    // it (the LFS oid). The engine records the same digest in its model.json, which is what the
+    // pre-flight check compares against — no re-hashing the file.
+    var targetFile: String? = nil
+    var sha256: String? = nil
+    // Sampling the model's own card recommends, so defaults come from the card instead of being
+    // guessed from the model name. Read from the HF cards 2026-10-29 (unsloth/Qwen3.8-27B-GGUF
+    // and prism-ml/Ternary-Bonsai-2-27B-gguf Best Practices): both publish the thinking-mode set
+    // below; the GGUFs carry temp/top_p/top_k as general.sampling.*. Engine 1.5.0 accepts every
+    // card value — presence penalty and min_p are applied; only logit_bias is refused.
+    var cardTemperature: Double = 1.0
+    var cardTopP: Double = 0.95
+    var cardTopK: Int = 20
+    var cardPresencePenalty: Double = 0
+    var cardMinP: Double = 0
+    // The same card's non-thinking set, relevant when reasoning effort is `none`. Offered as a
+    // link, never applied automatically — effort is a serve-wide flag while sampling is per-request.
+    var cardOffTemperature: Double = 0.7
+    var cardOffTopP: Double = 0.80
+    var cardOffTopK: Int = 20
+    var cardOffPresencePenalty: Double = 1.5
+    var cardOffMinP: Double = 0
+    // Reasoning levels this model accepts; nil = all of them. Bonsai's card: defaults to xhigh,
+    // medium for shorter answers, and `low` is NOT supported (it behaves like xhigh).
+    var supportedEfforts: [String]? = nil
+    // The card's own words about reasoning depth, shown in the effort tooltip.
+    var cardEffortNote: String = "The card recommends thinking mode; leave the effort at model default unless answers run long."
+    // Auto's KV-per-token and window constants are measured on this arch only; other rows get
+    // nil from autoProfile and the engine sizes itself.
+    var qwen27BArch: Bool = false
+
+    // Every level Splash's API accepts. A model's supportedEfforts filters this list.
+    static let allEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]
+
+    // The card as a starting profile: the model's card sampling, model-default reasoning effort,
+    // and auto serve fields.
+    func cardProfile() -> ModelProfile {
+        var p = ModelProfile()
+        p.sampling.temperature = cardTemperature
+        p.sampling.topP = cardTopP
+        p.sampling.topK = cardTopK
+        p.sampling.presencePenalty = cardPresencePenalty
+        p.sampling.minP = cardMinP
+        return p
+    }
+
+    var owner: String { id.split(separator: "/").first.map(String.init) ?? "" }
+    // Includes the :variant suffix, which is how Splash names its selection link.
+    var repo: String {
+        let parts = id.split(separator: "/")
+        return parts.count > 1 ? String(parts[1]) : id
+    }
+    // The bare repository, which is what Hugging Face names its cache directory by.
+    var hfRepo: String { String(repo.split(separator: ":").first ?? Substring(repo)) }
+
+    var downloadURL: String? {
+        guard let revision, let targetFile else { return nil }
+        return "https://huggingface.co/\(owner)/\(hfRepo)/resolve/\(revision)/\(targetFile)"
+    }
+
+    var onDisk: Bool { MachineInfo.weightsDir(for: id) != nil }
+
+    // The one disk-size-or-catalog-estimate rule: the live launch path, the headless probe, and
+    // the auto-profile all read this so they cannot drift apart.
+    var weightsBytes: Int? { MachineInfo.cachedModelSize(id) ?? approxBytes }
+
+    var fitsThisMac: Bool {
+        guard let memoryGB else { return true }
+        return MachineInfo.physicalRAM >= memoryGB * 1_073_741_824
+    }
+
+    // The catalog IS Splash's own suggested list (install/suggested-models.tsv as shipped by
+    // engine 1.5.0): same order (best first), same facts. The note line carries the tsv's
+    // MEMORY / SIZE / ABOUT columns verbatim in meaning — SIZE is the vendor's download figure
+    // including the vision projector and DFlash2 draft (the auto-profile's weight basis), and
+    // MEMORY feeds fitsThisMac directly, so note and the too-large warning agree by
+    // construction. Re-sync on every engine pin bump; the profile-test harness diffs IDs,
+    // order and MEMORY against the installed engine's tsv. Hand-verified revision pins and
+    // digests are kept only for entries actually measured on hardware (IQ3_XXS, Bonsai);
+    // everything else is unpinned, and the free-form Custom slot (see README "Confirmed
+    // models") covers the rest.
+    static let catalog: [CatalogModel] = [
+        CatalogModel(id: "unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q4_K_M", label: "Qwen3.6-35B-A3B Q4_K_M",
+                     note: "for 36 GB Macs · 24 GB download · Fast all-rounder",
+                     approxBytes: 24_000_000_000, memoryGB: 36),
+        CatalogModel(id: "mlx-community/Qwen3.6-35B-A3B-4bit", label: "Qwen3.6-35B-A3B MLX 4-bit",
+                     note: "for 36 GB Macs · 21 GB download · Fast all-rounder",
+                     approxBytes: 21_000_000_000, memoryGB: 36),
+        CatalogModel(id: "unsloth/Qwen3.6-35B-A3B-GGUF:UD-Q2_K_XL", label: "Qwen3.6-35B-A3B Q2_K_XL",
+                     note: "for 24 GB Macs · 14 GB download · Fast all-rounder",
+                     approxBytes: 14_000_000_000, memoryGB: 24),
+        CatalogModel(id: "unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M", label: "Qwen3.8-27B Q4_K_M",
+                     note: "for 36 GB Macs · 21 GB download · Strongest at this size, slower",
+                     approxBytes: 21_000_000_000, memoryGB: 36, qwen27BArch: true),
+        CatalogModel(id: "mlx-community/Qwen3.8-27B-4bit", label: "Qwen3.8-27B MLX 4-bit",
+                     note: "for 36 GB Macs · 20 GB download · Strongest at this size, slower",
+                     approxBytes: 20_000_000_000, memoryGB: 36, qwen27BArch: true),
+        CatalogModel(id: "unsloth/Qwen3.8-27B-GGUF:UD-IQ3_XXS", label: "Qwen3.8-27B IQ3_XXS",
+                     note: "for 24 GB Macs · 16 GB download · Strongest at this size, slower",
+                     approxBytes: 16_000_000_000, memoryGB: 24, revision: "4ca720788d1e01f1bff70c033e0d0028fd02e502",
+                     targetFile: "Qwen3.8-27B-UD-IQ3_XXS.gguf",
+                     sha256: "c0b7c3038681ed2e3040456c1dd45f9858b6c2290bed172c70388a94874f3eee",
+                     qwen27BArch: true),
+        CatalogModel(id: "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF:Q2_0", label: "Qwen3.8-Flash-Next Q2_0",
+                     note: "for 64 GB Macs · 69 GB download · Most capable",
+                     approxBytes: 69_000_000_000, memoryGB: 64),
+        CatalogModel(id: "unsloth/flint-GGUF:UD-Q4_K_XL", label: "Flint Q4_K_XL",
+                     note: "for 48 GB Macs · 26 GB download · Text only",
+                     approxBytes: 26_000_000_000, memoryGB: 48),
+        CatalogModel(id: "unsloth/Ornith-1.5-122B-GGUF:UD-Q4_K_XL", label: "Ornith-1.5-122B Q4_K_XL",
+                     note: "for 128 GB Macs · 82 GB download · Largest model",
+                     approxBytes: 82_000_000_000, memoryGB: 128),
+        CatalogModel(id: "ornith-ai/Ornith-1.5-122B-MLX-4bit", label: "Ornith-1.5-122B MLX 4-bit",
+                     note: "for 128 GB Macs · 71 GB download · Largest model",
+                     approxBytes: 71_000_000_000, memoryGB: 128),
+        CatalogModel(id: "prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0", label: "Bonsai 2 27B (PQ2_0)",
+                     note: "for 24 GB Macs · 12 GB download · Smallest download",
+                     approxBytes: 12_000_000_000, memoryGB: 24, revision: "b072e1d3b35a0a630cece372c2127528e0994386",
+                     targetFile: "Ternary-Bonsai-2-27B-PQ2_0.gguf",
+                     sha256: "3907dc1658db1f78a9826bf8d5bcb8dc65db0d466388937af57f2294fae62ec1",
+                     cardMinP: 0.05,
+                     supportedEfforts: ["none", "minimal", "medium", "high", "xhigh", "max"],
+                     cardEffortNote: "Card: thinking by default at xhigh effort; medium for shorter answers; `low` is NOT supported (it behaves like xhigh). The card also recommends min_p 0.05 in thinking mode, which the sampling fields carry."),
+        CatalogModel(id: "custom", label: "Custom…", note: "owner/repo[:variant]")
+    ]
+}
+
+enum AppPaths {
+    // ~/Library/Application Support/SplashGUI. Builds before 1.0 were named Splashpad; their
+    // folder (config, engine) is moved here on the first launch that finds no SplashGUI
+    // folder. The engine's `current` symlink is relative, so the move keeps it valid.
+    static let dataDir: URL = {
+        let fm = FileManager.default
+        let base = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
+            ?? fm.homeDirectoryForCurrentUser
+        let dir = base.appendingPathComponent("SplashGUI", isDirectory: true)
+        let old = base.appendingPathComponent("Splashpad", isDirectory: true)
+        if !fm.fileExists(atPath: dir.path), fm.fileExists(atPath: old.path) {
+            try? fm.moveItem(at: old, to: dir)
+        }
+        try? fm.createDirectory(at: dir, withIntermediateDirectories: true)
+        return dir
+    }()
+}
+
+final class ConfigStore {
+    static let shared = ConfigStore()
+
+    private let dir: URL
+    private let fileURL: URL
+
+    init() {
+        dir = AppPaths.dataDir
+        fileURL = dir.appendingPathComponent("config.json")
+    }
+
+    func load() -> AppConfig {
+        guard let data = try? Data(contentsOf: fileURL) else {
+            return AppConfig()
+        }
+        if let decoded = try? JSONDecoder().decode(AppConfig.self, from: data) {
+            var cfg = decoded
+            if (cfg.run.schemaVersion ?? 1) < 2 {
+                if cfg.run.kvFormat == "int8" { cfg.run.kvFormat = "bf16" }
+                cfg.run.schemaVersion = 2
+            }
+            if (cfg.run.schemaVersion ?? 1) < 3 {
+                if cfg.run.kvFormat == "bf16" { cfg.run.kvFormat = "auto" }
+                cfg.run.schemaVersion = 3
+            }
+            if (cfg.run.schemaVersion ?? 1) < 4 {
+                // Give the model already selected a profile entry, so its shipped-or-tuned
+                // settings survive the first switch away from it and are editable on disk.
+                let id = cfg.run.modelID
+                if !id.isEmpty && cfg.modelProfiles[id] == nil {
+                    cfg.modelProfiles[id] = ModelProfile.snapshot(of: cfg)
+                }
+                cfg.run.schemaVersion = 4
+            }
+            if (cfg.run.schemaVersion ?? 1) < 5 {
+                // 1.0 shipped with the SSD tier off. A 64K context costs 2.0 GiB of KV pages
+                // there (33,280 bytes a token) plus a 152 MiB state, so 10 GB holds about
+                // five of them, and the tier only pays for itself if it survives a restart.
+                if cfg.run.maxCacheDisk == "0" { cfg.run.maxCacheDisk = "10G" }
+                cfg.run.schemaVersion = 5
+            }
+            if (cfg.run.schemaVersion ?? 1) < 6 {
+                // The Auto switch: on only when every field it covers was still "auto".
+                // Otherwise off, with the existing values as the typed ones.
+                func isAuto(_ v: String) -> Bool { v.lowercased() == "auto" || v.isEmpty }
+                let allAuto = isAuto(cfg.run.maxContext) && isAuto(cfg.run.maxMemory)
+                    && isAuto(cfg.run.kvFormat) && isAuto(cfg.run.maxCacheDisk)
+                cfg.run.auto = allAuto
+                if !allAuto && isAuto(cfg.run.kvFormat) {
+                    // The KV picker no longer has an Auto segment — resolve what Auto would
+                    // have picked once, so the typed set is complete.
+                    let id = cfg.run.modelID
+                    let weights = CatalogModel.catalog.first { $0.id == id }?.weightsBytes
+                        ?? MachineInfo.cachedModelSize(id)
+                    let p = MachineInfo.autoProfile(modelID: id, languageOnly: cfg.run.languageOnly,
+                                                    weightsBytes: weights)
+                    cfg.run.kvFormat = p?.kvFormat ?? "bf16"
+                }
+                cfg.run.schemaVersion = 6
+            }
+            return cfg
+        }
+        return AppConfig()
+    }
+
+    func save(_ config: AppConfig) {
+        guard let data = try? JSONEncoder().encode(config) else { return }
+        try? data.write(to: fileURL, options: [.atomic])
+    }
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Core/AppModel.swift b/Sources/SplashGUI/Core/AppModel.swift
new file mode 100644
index 0000000..bd14527
--- /dev/null
+++ b/Sources/SplashGUI/Core/AppModel.swift
@@ -0,0 +1,717 @@
+import SwiftUI
+import Combine
+
+enum ServerPhase: Equatable {
+    case stopped
+    case starting
+    case ready
+    case stopping
+    case exited(String)
+}
+
+@MainActor
+final class AppModel: ObservableObject {
+    @Published var config: AppConfig {
+        didSet { ConfigStore.shared.save(config) }
+    }
+    @Published var phase: ServerPhase = .stopped
+    @Published var logTail: [String] = []
+    @Published var status: StatusSnapshot?
+    @Published var draftAcceptance: Double?
+    @Published var lastError: String?
+    @Published var effectiveModel: String?
+    @Published var history: [StatusSample] = []
+    @Published var adoptedPID: Int?
+    @Published var loadProgress: Double?
+    @Published var loadStage: String = ""
+    @Published var currentStage: SampleStage?
+    @Published var engineStep: EngineInstaller.Step = .idle
+    @Published var engineProgress: Double = 0
+    @Published var engineVersion: String?
+    @Published var engineResolvedVersion: String?
+    private var engineCancels: Set<AnyCancellable> = []
+    // Depth of the 27B arch every catalog model shares; used only to scale the load-progress bar.
+    private static let modelLayerCount = 66.0
+    private var weightsSizeModelID: String?
+    private var weightsRefreshedThisRun = false
+    private var loadStartedAt: Date?
+
+    private func updateLoadProgress() {
+        guard phase == .starting else {
+            if loadProgress != nil { loadProgress = nil }
+            loadStartedAt = nil
+            return
+        }
+        if loadStartedAt == nil { loadStartedAt = Date() }
+        let lines = server.logLines
+        var base = 0.06
+        var stage = "starting server…"
+
+        if let layer = preparingLayer(from: lines) {
+            // Every catalog model is Qwen3.8-27B-shaped (66 layers). The engine prints the layer
+            // index but not its total, so the fraction is scaled to that depth — a different arch
+            // would only misshape the progress bar, never the load.
+            let frac = min(1.0, Double(layer) / Self.modelLayerCount)
+            base = 0.78 + 0.17 * frac
+            stage = "preparing weights (one-time): \(Int(frac * 100))%"
+            loadProgress = base
+            loadStage = stage
+            return
+        }
+
+        if let fetch = downloadFraction(from: lines, since: loadStartedAt) {
+            stage = "downloading model: \(Int(fetch * 100))%"
+            base = 0.03 + 0.55 * fetch
+            loadProgress = min(0.95, base)
+            loadStage = stage
+            return
+        }
+
+        if lines.contains(where: { $0.contains("Loading ·") }) {
+            base = 0.22
+            stage = "loading weights…"
+        }
+        if lines.contains(where: { $0.contains("Chat template") }) {
+            base = 0.45
+            stage = "configuring chat template…"
+        }
+        if lines.contains(where: { $0.contains("Kernel policy") }) {
+            base = 0.68
+            stage = "preparing Metal kernels…"
+        }
+        if let started = loadStartedAt {
+            let elapsed = Date().timeIntervalSince(started)
+            let creep = min(0.26, elapsed * 0.012)
+            loadProgress = min(0.95, base + creep)
+        }
+        loadStage = stage
+    }
+
+    private func preparingLayer(from lines: [String]) -> Int? {
+        for line in lines.reversed() {
+            guard line.contains("Preparing weights") else { continue }
+            guard let range = line.range(of: "layer-") else { continue }
+            let digits = line[range.upperBound...].prefix(while: { $0.isNumber })
+            if let n = Int(digits) { return n }
+        }
+        return nil
+    }
+
+    // Done = in-flight .incomplete files plus blobs completed since this load started. HF renames
+    // a blob off its .incomplete name when it finishes, so counting only incomplete files drops
+    // each finished shard and the bar jumps backward on multi-blob models.
+    private func downloadFraction(from lines: [String], since: Date?) -> Double? {
+        var totalBytes: Double?
+        for line in lines {
+            guard let r = line.range(of: "file(s), ") else { continue }
+            let digits = line[r.upperBound...].prefix(while: { $0.isNumber || $0 == "." })
+            if let gb = Double(digits) { totalBytes = gb * 1e9 }
+        }
+        guard let totalBytes, totalBytes > 0 else { return nil }
+
+        guard let cache = MachineInfo.hfCacheDir(for: config.run.modelID) else { return nil }
+        let blobsDir = cache.appendingPathComponent("blobs")
+        var doneBytes: Int64 = 0
+        if let en = FileManager.default.enumerator(at: blobsDir, includingPropertiesForKeys: [.fileSizeKey, .isRegularFileKey, .contentModificationDateKey]) {
+            for case let f as URL in en {
+                guard let vals = try? f.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey, .contentModificationDateKey]),
+                      vals.isRegularFile == true else { continue }
+                if f.lastPathComponent.contains(".incomplete") {
+                    doneBytes += Int64(vals.fileSize ?? 0)
+                } else if let mtime = vals.contentModificationDate, let since, mtime >= since {
+                    doneBytes += Int64(vals.fileSize ?? 0)
+                }
+            }
+        }
+        guard doneBytes > 0 else { return nil }
+        let frac = Double(doneBytes) / totalBytes
+        let tqdm = tqdmPercent(from: lines).map { Double($0) / 100.0 }
+        return min(1.0, max(frac, tqdm ?? 0))
+    }
+
+    private func tqdmPercent(from lines: [String]) -> Int? {
+        for line in lines.reversed() {
+            guard let marker = line.range(of: "%|") else { continue }
+            let before = line[..<marker.lowerBound]
+            let digits = before.reversed().prefix(while: { $0.isNumber }).reversed()
+            if let value = Int(String(digits)), (0...100).contains(value) {
+                return value
+            }
+        }
+        return nil
+    }
+
+    var modelFootprint: Int? {
+        guard let pid = status?.instancePID else { return nil }
+        return MachineInfo.serverFootprint(parentPID: pid)
+    }
+
+    var prefillGaugeValue: Double? {
+        guard let last = history.last else { return nil }
+        if last.stage == nil { return 0 }
+        return last.prefillTps ?? 0
+    }
+
+    var decodeGaugeValue: Double? {
+        guard let last = history.last else { return nil }
+        if last.stage == nil { return 0 }
+        return last.decodeTps ?? 0
+    }
+
+    var lastRequestTTFT: Double? {
+        for sample in history.reversed() {
+            if let v = sample.ttftP50 { return v }
+        }
+        return nil
+    }
+
+    private func maxTps(_ keyPath: KeyPath<StatusSample, Double?>, within seconds: Double? = nil) -> Double? {
+        let source: [StatusSample]
+        if let seconds {
+            let cutoff = Date().addingTimeInterval(-seconds)
+            source = history.filter { $0.time >= cutoff }
+        } else {
+            source = history
+        }
+        return source.compactMap { $0[keyPath: keyPath] }.max()
+    }
+
+    var prefillMax5m: Double? { maxTps(\.prefillTps, within: 300) }
+    var decodeMax5m: Double? { maxTps(\.decodeTps, within: 300) }
+    var prefillMaxSession: Double? { maxTps(\.prefillTps) }
+    var decodeMaxSession: Double? { maxTps(\.decodeTps) }
+
+    var reasoningEffortBinding: Binding<String?> {
+        Binding(
+            get: { self.config.sampling.reasoningEffort ?? self.config.run.defaultReasoningEffort },
+            set: {
+                self.config.sampling.reasoningEffort = $0
+                self.config.run.defaultReasoningEffort = $0
+            }
+        )
+    }
+
+    let server = SplashServer()
+    let engine = EngineInstaller()
+    @Published var launchedRunConfig: RunConfig?
+    var hasPendingChanges: Bool {
+        guard let launched = launchedRunConfig else { return false }
+        return phase == .ready && launched != config.run
+    }
+    private var client: SplashClient { SplashClient(port: config.run.port) }
+    private var pollTask: Task<Void, Never>?
+    private var logTimer: Timer?
+
+    init() {
+        config = ConfigStore.shared.load()
+        logTimer = Timer(timeInterval: 0.3, repeats: true) { [weak self] _ in
+            Task { @MainActor in
+                guard let self else { return }
+                let new = self.server.logLines
+                if new != self.logTail { self.logTail = new }
+                self.updateLoadProgress()
+            }
+        }
+        RunLoop.main.add(logTimer!, forMode: .common)
+        NotificationCenter.default.addObserver(
+            forName: NSApplication.willTerminateNotification, object: nil, queue: nil
+        ) { _ in
+            AppModel.isQuitting = true
+            if let pid = AppModel.serverKillPID {
+                kill(Int32(pid), SIGTERM)
+                var waited = 0
+                while waited < 12 {
+                    if kill(Int32(pid), 0) != 0 { break }
+                    usleep(100_000)
+                    waited += 1
+                }
+                if kill(Int32(pid), 0) == 0 { kill(Int32(pid), SIGKILL) }
+            }
+        }
+        NotificationCenter.default.addObserver(
+            forName: NSWindow.willCloseNotification, object: nil, queue: nil
+        ) { _ in
+            guard !AppModel.isQuitting else { return }
+            DispatchQueue.main.async {
+                guard !AppModel.isQuitting else { return }
+                let visibleWindows = NSApp.windows.filter {
+                    $0.isVisible && !($0 is NSPanel) && $0.frame.width > 0
+                }
+                if visibleWindows.isEmpty {
+                    NSApp.terminate(nil)
+                }
+            }
+        }
+        Task { @MainActor in
+            // Launch = start (when enabled): wait for the adopt probe first so a server already
+            // on the port wins and auto-start never double-launches into a port conflict.
+            if !(await self.adoptExistingServer()) { self.autoStartIfNeeded() }
+        }
+        refreshModelSizeCache()
+
+        engineVersion = engine.installedVersion
+        engine.step = EngineInstaller.isInstalled ? .ready : .idle
+        // [weak self]: the cancellables are stored on self, so a strong capture here would be a
+        // self ↔ cancellable retain cycle.
+        engine.$step.receive(on: RunLoop.main).sink { [weak self] v in
+            Task { @MainActor in self?.engineStep = v }
+        }.store(in: &engineCancels)
+        engine.$progress.receive(on: RunLoop.main).sink { [weak self] v in
+            Task { @MainActor in self?.engineProgress = v }
+        }.store(in: &engineCancels)
+        engine.$installedVersion.receive(on: RunLoop.main).sink { [weak self] v in
+            Task { @MainActor in self?.engineVersion = v }
+        }.store(in: &engineCancels)
+        engine.$resolvedVersion.receive(on: RunLoop.main).sink { [weak self] v in
+            Task { @MainActor in self?.engineResolvedVersion = v }
+        }.store(in: &engineCancels)
+    }
+
+    // Drops the cached on-disk size when a model has just finished downloading, so the
+    // auto-profile and the download-progress bar re-read it instead of a stale nil. The
+    // non-force call on a model switch just re-arms the guard for the next download.
+    func refreshModelSizeCache(force: Bool = false) {
+        let id = config.run.modelID
+        guard force || weightsSizeModelID != id else { return }
+        if force { MachineInfo.invalidateModelSize(id) }
+        weightsSizeModelID = id
+    }
+
+    private func failureHint() -> String {
+        let lines = server.logLines
+        for line in lines.reversed() {
+            if line.contains("already serving") {
+                return "Another Splash server already owns this port (possibly from an earlier session). Stop it or pick a different port in Advanced."
+            }
+            if line.contains("Address already in use") || line.contains("failed to bind") {
+                return "Port \(config.run.port) is taken by another process. Pick a different port in Advanced."
+            }
+            if line.lowercased().contains("handshake") || line.contains("_ssl")
+                || line.lowercased().contains("cannot resolve") || line.lowercased().contains("timed out")
+                || line.lowercased().contains("connection refused") {
+                return "Couldn't reach Hugging Face to download or resolve this model (network/SSL timeout). Check the connection and try again."
+            }
+            if line.contains("model download or verification failed") {
+                return "The model download failed partway. Check the connection and try again. Partially downloaded files resume."
+            }
+            if line.lowercased().contains("out of memory") || line.lowercased().contains("not enough memory") {
+                return "Not enough free memory to load this model. Close other apps, or lower Max memory in Advanced."
+            }
+        }
+        return "splash exited before becoming ready; see the details below."
+    }
+
+    nonisolated(unsafe) static var serverKillPID: Int?
+
+    nonisolated(unsafe) static var isQuitting = false
+
+    @discardableResult
+    private func adoptExistingServer() async -> Bool {
+        guard canStart else { return false }
+        let probe = await client.probePort()
+        guard probe.open, let pid = probe.pid else { return false }
+        guard canStart else { return false }
+        adoptedPID = pid
+        AppModel.serverKillPID = pid
+        launchedRunConfig = config.run
+        server.note("- attached to existing splash on port \(config.run.port) (pid \(pid))")
+        server.spawnWatchdog(serverPID: pid, appPID: Int(ProcessInfo.processInfo.processIdentifier))
+        phase = await client.ready() ? .ready : .starting
+        startPolling()
+        return true
+    }
+
+    private func autoStartIfNeeded() {
+        guard config.startOnLaunch,
+              ProcessInfo.processInfo.environment["SPLASHGUI_TEST"] == nil else { return }
+        start()
+    }
+
+    var effectiveModelID: String { config.run.modelID }
+
+    // The catalog row for the selected model, nil for a Custom ID.
+    var catalogEntry: CatalogModel? {
+        CatalogModel.catalog.first { $0.id == config.run.modelID }
+    }
+
+    // Switching models swaps profiles: the model being left keeps its current settings, the model
+    // being entered restores its saved ones, or starts on its card if it has none. Also re-reads
+    // the on-disk weights size the auto-profile needs.
+    func selectModelID(_ id: String) {
+        guard config.run.modelID != id else { return }
+        let outgoing = config.run.modelID
+        if !outgoing.isEmpty { config.modelProfiles[outgoing] = ModelProfile.snapshot(of: config) }
+        config.run.modelID = id
+        if let saved = config.modelProfiles[id] {
+            config.apply(profile: saved)
+        } else {
+            applyCardProfile()
+        }
+        refreshModelSizeCache()
+    }
+
+    // A model with no saved profile starts on its own card — card sampling, model-default reasoning
+    // effort, auto serve fields — rather than keeping the model you came from.
+    private func applyCardProfile() {
+        config.apply(profile: catalogEntry?.cardProfile() ?? ModelProfile())
+    }
+
+    // Forget this model's saved profile and go back to its card. Global fields (port, storage
+    // cache, decode share, web chat) are untouched.
+    func resetModelProfile() {
+        config.modelProfiles[config.run.modelID] = nil
+        applyCardProfile()
+    }
+
+    // Reasoning levels this model accepts — its card's list, or every level for a hand-typed ID.
+    var supportedEfforts: [String] { catalogEntry?.supportedEfforts ?? CatalogModel.allEfforts }
+
+    // The card's non-thinking sampling set, applied only when the user asks for it. Deliberately
+    // not automatic: effort is a serve-wide flag while sampling is per-request, and an automatic
+    // rewrite would clobber numbers the user tuned for this model.
+    func applyCardOffSampling() {
+        guard let e = catalogEntry else { return }
+        config.sampling.temperature = e.cardOffTemperature
+        config.sampling.topP = e.cardOffTopP
+        config.sampling.topK = e.cardOffTopK
+        config.sampling.presencePenalty = e.cardOffPresencePenalty
+        config.sampling.minP = e.cardOffMinP
+    }
+
+    // The context limit to write into client configs: the window Splash actually granted while
+    // the server runs; otherwise the configured/Auto value — the tab flags that as an estimate.
+    var providerContextTokens: (tokens: Int, estimate: Bool) {
+        if phase == .ready, let granted = status?.maxContextTokens { return (granted, false) }
+        if config.run.auto {
+            if let p = currentAutoProfile { return (p.contextTokens, true) }
+            if let g = config.grantedAuto[config.run.modelID] { return (g.contextTokens, true) }
+            return (CatalogModel.windowTokens, true)
+        }
+        return (Self.parseContext(config.run.maxContext) ?? CatalogModel.windowTokens, true)
+    }
+
+    // "100K" → 102_400, "131072" → 131_072; nil for "auto"/garbage.
+    static func parseContext(_ text: String) -> Int? {
+        let t = text.trimmingCharacters(in: .whitespaces).lowercased()
+        if t.isEmpty || t == "auto" { return nil }
+        if t.hasSuffix("k"), let n = Int(t.dropLast()) { return n * 1024 }
+        return Int(t)
+    }
+
+    func clientConfigText(for client: ProviderClient) -> String {
+        let (tokens, _) = providerContextTokens
+        let modalities = phase == .ready
+            ? status?.inputModalities ?? (config.run.languageOnly ? ["text"] : ["text", "image", "pdf"])
+            : (config.run.languageOnly ? ["text"] : ["text", "image", "pdf"])
+        let ctx = ClientConfigContext(client: client, modelID: config.run.modelID,
+                                      label: catalogEntry?.label ?? config.run.modelID,
+                                      port: config.run.port, contextTokens: tokens,
+                                      inputModalities: modalities,
+                                      sampling: config.sampling,
+                                      efforts: catalogEntry?.supportedEfforts ?? CatalogModel.allEfforts)
+        return ClientConfigs.text(for: ctx)
+    }
+
+    // Any ID outside the catalog reads as Custom… so the popup never goes blank on a hand-typed ID.
+    var modelPickerSelection: Binding<String> {
+        Binding(
+            get: { self.catalogEntry?.id ?? "custom" },
+            set: { newValue in
+                if newValue != "custom" { self.selectModelID(newValue) }
+                else if self.catalogEntry != nil { self.selectModelID("") }
+            }
+        )
+    }
+
+    // Typing a Custom ID: no profile swap (that would clobber edits mid-keystroke), just a size
+    // refresh so the auto-profile caption tracks what's being typed.
+    var customIDBinding: Binding<String> {
+        Binding(
+            get: { self.config.run.modelID },
+            set: {
+                self.config.run.modelID = $0
+                self.refreshModelSizeCache()
+            }
+        )
+    }
+
+    // Resolved run profile for the current model, using the catalog weight estimate when the
+    // model hasn't downloaded yet. Cheap: weights size is cached, Metal ceiling read once.
+    var currentAutoProfile: AutoProfile? {
+        let id = config.run.modelID
+        let weights = catalogEntry?.weightsBytes ?? MachineInfo.cachedModelSize(id)
+        return MachineInfo.autoProfile(modelID: id, languageOnly: config.run.languageOnly, weightsBytes: weights)
+    }
+
+    // What the four Auto-covered fields show while Auto is on: the profile's values, or for a
+    // custom ID the last Splash-granted ones — blank until the first serve fills them.
+    var autoContextText: String {
+        if let p = currentAutoProfile { return "\(p.contextTokens / 1024)K" }
+        if let g = config.grantedAuto[config.run.modelID] { return "\(g.contextTokens / 1024)K" }
+        return ""
+    }
+
+    var autoMemoryText: String {
+        let bytes = currentAutoProfile?.maxMemoryBytes ?? config.grantedAuto[config.run.modelID]?.memoryBytes
+        guard let bytes else { return "" }
+        return "\(bytes / 1_073_741_824)G"
+    }
+
+    var autoKVFormat: String { currentAutoProfile?.kvFormat ?? "bf16" }
+
+    // The engine's own SSD-cache default: a quarter of the volume's free space, up to 32G.
+    var autoCacheText: String {
+        guard let free = MachineInfo.freeDisk else { return "engine default" }
+        return "\(min(free / 4, 34_359_738_368) / 1_073_741_824)G"
+    }
+
+    var canStart: Bool {
+        if case .exited = phase { return true }
+        return phase == .stopped
+    }
+
+    var portValid: Bool {
+        (1...65535).contains(config.run.port)
+    }
+
+    var isInstallingEngine: Bool {
+        switch engineStep {
+        case .checking, .downloading, .verifying, .extracting, .validating, .switching: return true
+        default: return false
+        }
+    }
+
+    // A start that never launched: the footer carries the message until the next Start, and the
+    // log tail gets a line in SplashServer's note style, so the failure survives in both places.
+    private func startBlocked(_ message: String) {
+        lastError = message
+        server.note("- start blocked: \(message)")
+    }
+
+    // Which engine build start() installs, as a pure decision the harness can pin: the custom
+    // pin applies only in .custom (complete fields install regardless of the update toggle;
+    // partial fields keep the pre-picker pinned behavior), .pinned never sees the override
+    // fields, and .latest keeps the installed engine on a failed check — the compiled-in pin
+    // would silently DOWNGRADE — while nothing-installed falls back to the compiled pin.
+    nonisolated static func enginePlan(mode: EngineMode, customOverride: EnginePin?, installed: Bool,
+                                       checkUpdate: Bool, latest: EnginePin?) -> (ensure: Bool, override: EnginePin?) {
+        var ensure = !installed || checkUpdate
+        var override: EnginePin?
+        switch mode {
+        case .pinned:
+            break
+        case .custom:
+            override = customOverride
+            if override != nil { ensure = true }
+        case .latest:
+            ensure = true
+            if let newest = latest {
+                override = newest
+            } else if installed {
+                ensure = false
+            }
+        }
+        return (ensure, override)
+    }
+
+    func start() {
+        lastError = nil
+        guard canStart else { return }
+        weightsRefreshedThisRun = false
+        if config.run.modelID.isEmpty {
+            startBlocked("No model ID set. Pick one from the Model popup, or Custom… and type owner/repo[:variant].")
+            return
+        }
+        if let mismatch = MachineInfo.modelHashMismatch(config.run.modelID) {
+            startBlocked(mismatch)
+            return
+        }
+        Task {
+            let probe = await client.probePort()
+            if probe.open {
+                let pidPart = probe.pid.map { " (pid \($0))" } ?? ""
+                self.startBlocked("Port \(self.config.run.port) is taken\(pidPart) by \(probe.detail ?? "unknown process"). Stop it or change the port.")
+                self.phase = .stopped
+                return
+            }
+            let installed = EngineInstaller.isInstalled
+            // The resolver is only consulted in latest mode; the mode table itself is pure
+            // (enginePlan) so the harness can pin it.
+            var resolved: EnginePin?
+            if case .latest = self.config.engineMode { resolved = await EngineResolver.latest() }
+            let (ensure, override) = Self.enginePlan(
+                mode: self.config.engineMode, customOverride: self.config.enginePinOverride(),
+                installed: installed, checkUpdate: self.config.checkEngineUpdate, latest: resolved)
+            if !ensure, case .latest = self.config.engineMode {
+                self.server.note("- engine update check: GitHub unreachable, keeping the installed engine")
+            }
+            if ensure {
+                do {
+                    try await self.engine.ensureInstalled(
+                        port: self.config.run.port,
+                        override: override)
+                } catch {
+                    self.startBlocked((error as? LocalizedError)?.errorDescription
+                        ?? "Engine install failed: \(error)")
+                    self.phase = .stopped
+                    return
+                }
+            }
+            self.phase = .starting
+            let profile = self.currentAutoProfile
+            do {
+                try self.server.launch(config: self.config.run.effective(using: profile),
+                                       revision: self.catalogEntry?.revision)
+                self.launchedRunConfig = self.config.run
+                if let pid = self.server.childPID {
+                    AppModel.serverKillPID = pid
+                    self.server.spawnWatchdog(serverPID: pid,
+                                              appPID: Int(ProcessInfo.processInfo.processIdentifier))
+                }
+                self.startPolling()
+            } catch {
+                self.startBlocked(error.localizedDescription)
+                self.phase = .stopped
+            }
+        }
+    }
+
+    func stop() {
+        pollTask?.cancel()
+        pollTask = nil
+        phase = .stopping
+        launchedRunConfig = nil
+        if let pid = adoptedPID {
+            kill(Int32(pid), SIGTERM)
+            Task { @MainActor in
+                for _ in 0..<24 {
+                    if kill(Int32(pid), 0) != 0 { break }
+                    try? await Task.sleep(nanoseconds: 250_000_000)
+                }
+                if kill(Int32(pid), 0) == 0 { kill(Int32(pid), SIGKILL) }
+                self.adoptedPID = nil
+                AppModel.serverKillPID = nil
+                self.phase = .stopped
+                self.status = nil
+                self.draftAcceptance = nil
+                self.effectiveModel = nil
+                self.currentStage = nil
+            }
+            return
+        }
+        server.stop()
+        Task { @MainActor in
+            for _ in 0..<40 {
+                if !self.server.isRunning { break }
+                try? await Task.sleep(nanoseconds: 250_000_000)
+            }
+            if self.server.isRunning { self.server.terminateHard() }
+            AppModel.serverKillPID = nil
+            self.phase = .stopped
+            self.status = nil
+            self.draftAcceptance = nil
+            self.effectiveModel = nil
+            self.currentStage = nil
+        }
+    }
+
+    func restart() {
+        guard phase == .ready || phase == .starting else { return }
+        stop()
+        Task { @MainActor in
+            // Wait for stop() to settle rather than a fixed delay: it flips to .stopped
+            // asynchronously once the engine process has actually exited (up to ~10s).
+            for _ in 0..<120 {
+                if self.phase == .stopped { break }
+                try? await Task.sleep(nanoseconds: 100_000_000)
+            }
+            if self.phase == .stopped { self.start() }
+        }
+    }
+
+    private func startPolling() {
+        pollTask?.cancel()
+        pollTask = Task { [weak self] in
+            while !Task.isCancelled {
+                guard let self else { return }
+                let isReady = await self.client.ready()
+                if isReady {
+                    self.phase = .ready
+                    // A model that just finished downloading now has a real on-disk size; re-read
+                    // it once per run so the weights line and card stop showing the estimate.
+                    if !self.weightsRefreshedThisRun {
+                        self.weightsRefreshedThisRun = true
+                        self.refreshModelSizeCache(force: true)
+                    }
+                    let snap = await self.client.fetchStatus()
+                    self.status = snap
+                    if let model = snap?.instanceModel { self.effectiveModel = model }
+                    // Custom IDs have no app-side profile — remember what Splash granted so the
+                    // Auto fields show it on the next launch at once. Only write on change:
+                    // every config write rewrites config.json.
+                    if self.catalogEntry == nil, self.config.run.auto,
+                       let ctx = snap?.maxContextTokens, let mem = snap?.hardBudgetBytes {
+                        let g = GrantedSettings(contextTokens: ctx, memoryBytes: mem)
+                        if self.config.grantedAuto[self.config.run.modelID] != g {
+                            self.config.grantedAuto[self.config.run.modelID] = g
+                        }
+                    }
+                    let draft = await self.client.fetchMetric("splash_draft_acceptance_ratio")
+                    self.draftAcceptance = draft
+
+                    let pre = snap?.prefilling ?? 0
+                    let dec = snap?.decoding ?? 0
+                    let stage: SampleStage? = pre > 0 ? .prefill : (dec > 0 ? .decode : nil)
+                    let decodeTps: Double?
+                    let prefillTps: Double?
+                    if stage != nil {
+                        decodeTps = await self.client.fetchMetric("splash_decode_tokens_per_second")
+                        prefillTps = await self.client.fetchMetric("splash_prefill_tokens_per_second")
+                    } else {
+                        decodeTps = nil
+                        prefillTps = nil
+                    }
+                    let sample = StatusSample(
+                        time: Date(),
+                        ttftP50: stage == nil ? nil : snap?.ttftP50,
+                        draftAcceptance: stage == nil ? nil : draft,
+                        cacheHitRate: stage == nil ? nil : snap?.cacheHitRate,
+                        decodeTps: decodeTps,
+                        prefillTps: prefillTps,
+                        stage: stage
+                    )
+                    self.history.append(sample)
+                    if self.history.count > 240 { self.history.removeFirst(self.history.count - 240) }
+                    self.currentStage = stage
+                } else if self.phase == .starting {
+                    let alive = self.adoptedPID.map { kill(Int32($0), 0) == 0 } ?? self.server.isRunning
+                    if !alive {
+                        self.phase = .stopped
+                        self.lastError = self.failureHint()
+                        return
+                    }
+                } else if self.phase == .ready {
+                    self.phase = .exited("lost /ready; engine may be recovering or stopped")
+                    let snap = await self.client.fetchStatus()
+                    self.status = snap
+                }
+                try? await Task.sleep(nanoseconds: 2_000_000_000)
+            }
+        }
+    }
+}
+
+enum SampleStage: Equatable {
+    case prefill
+    case decode
+}
+
+struct StatusSample {
+    let time: Date
+    let ttftP50: Double?
+    let draftAcceptance: Double?
+    let cacheHitRate: Double?
+    let decodeTps: Double?
+    let prefillTps: Double?
+    let stage: SampleStage?
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Core/ClientConfigs.swift b/Sources/SplashGUI/Core/ClientConfigs.swift
new file mode 100644
index 0000000..e6dcd33
--- /dev/null
+++ b/Sources/SplashGUI/Core/ClientConfigs.swift
@@ -0,0 +1,263 @@
+import Foundation
+
+// The coding clients the Provider tab writes configs for. The OpenCode shape mirrors the
+// engine's own connector (install/clients.py _opencode, engine 1.5.0, unchanged since 1.3.2) plus sampling; the
+// Claude Code env set and the Codex TOML mirror _claude and _codex. Zed's shape is from its
+// current docs (OpenAI-compatible endpoints + agent.model_parameters).
+enum ProviderClient: String, CaseIterable, Identifiable {
+    case opencode = "OpenCode"
+    case zed = "Zed"
+    case claudeCode = "Claude Code"
+    case codex = "Codex"
+
+    var id: String { rawValue }
+
+    var tooltip: String {
+        "The tool to write a config for. Each one gets the endpoint, the model, its context limit and the sampling below, in that tool's own format."
+    }
+
+    // Which sampling fields actually reach this client's requests. OpenCode merges the model's
+    // `body` into the request body verbatim (V2; verified live against 2.2.2 with an echo
+    // server); Zed carries temperature only (agent.model_parameters); Claude Code and Codex
+    // expose no sampling knobs — their requests set what they themselves want.
+    func carries(_ field: SamplingField) -> Bool {
+        switch self {
+        case .opencode: return field != .maxTokens
+        case .zed: return field == .temperature
+        case .claudeCode, .codex: return false
+        }
+    }
+
+    var configCaption: String {
+        switch self {
+        case .opencode: return "opencode.json: add this providers block; your model and agent defaults stay untouched"
+        case .zed: return "settings.json for Zed (AI section)"
+        case .claudeCode: return "settings.json: the env block for ~/.claude/settings.json"
+        case .codex: return "config.toml for ~/.codex/config.toml"
+        }
+    }
+
+    var saveName: String {
+        switch self {
+        case .opencode: return "opencode-splash.json"
+        case .zed: return "zed-splash-settings.json"
+        case .claudeCode: return "claude-code-splash-env.json"
+        case .codex: return "codex-splash-config.toml"
+        }
+    }
+
+    var filePattern: String {
+        switch self {
+        case .codex: return "toml"
+        default: return "json"
+        }
+    }
+}
+
+enum SamplingField {
+    case temperature, topP, topK, presencePenalty, minP, maxTokens, seed
+}
+
+// Everything the config text is built from, resolved by AppModel (granted window when the
+// server runs, configured/Auto values otherwise).
+struct ClientConfigContext {
+    let client: ProviderClient
+    let modelID: String
+    let label: String
+    let port: Int
+    let contextTokens: Int
+    let inputModalities: [String]
+    let sampling: SamplingDefaults
+    // Reasoning levels this model accepts; defaults to every level Splash's API takes.
+    var efforts: [String] = CatalogModel.allEfforts
+}
+
+enum ClientConfigs {
+    // The output allowance OpenCode, Zed and Codex reserve: CLIENT_RESPONSE_TOKENS in the
+    // engine connector, or a quarter of the window when that is less.
+    static func responseTokens(context: Int) -> Int {
+        min(32_768, max(1, context / 4))
+    }
+
+    static func text(for ctx: ClientConfigContext) -> String {
+        switch ctx.client {
+        case .opencode: return opencode(ctx)
+        case .zed: return zed(ctx)
+        case .claudeCode: return claudeCode(ctx)
+        case .codex: return codex(ctx)
+        }
+    }
+
+    // MARK: - OpenCode
+
+    private static func json(_ obj: Any) -> String {
+        let data = (try? JSONSerialization.data(withJSONObject: obj,
+                                                options: [.prettyPrinted, .sortedKeys])) ?? Data()
+        // JSONSerialization escapes every "/" as "\/" — valid but ugly in a preview meant to
+        // be read and pasted. "\/" is the only sequence it produces this way, safe to undo.
+        return String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\\/", with: "/")
+    }
+
+    private static func inputModalities(_ ctx: ClientConfigContext) -> [String] {
+        ctx.inputModalities
+    }
+
+    // JSONSerialization prints a Double's full binary expansion (0.95 -> 0.94999999999999996).
+    // A decimal built from Swift's shortest description round-trips to the value the user
+    // typed and reads cleanly in the pasted config.
+    private static func decimal(_ value: Double) -> NSDecimalNumber {
+        NSDecimalNumber(string: String(value))
+    }
+
+    // This snippet only adds the provider. It deliberately does NOT set the root `model` or
+    // `small_model` and does NOT define `agents`: those are the user's defaults, and overriding
+    // them was making every agent point at Splash. Splash appears as one more entry in
+    // /models; its reasoning efforts appear as variants in /variants.
+    private static func opencode(_ ctx: ClientConfigContext) -> String {
+        let out = responseTokens(context: ctx.contextTokens)
+        let modalities = inputModalities(ctx)
+        // Sampling rides in the model's `body`, which V2 merges into the request body verbatim.
+        // (V1's `options` was the old path; agent-level request fields are not sent in V2.)
+        var body: [String: Any] = [
+            "temperature": decimal(ctx.sampling.temperature),
+            "top_p": decimal(ctx.sampling.topP),
+            "top_k": ctx.sampling.topK,
+            "presence_penalty": decimal(ctx.sampling.presencePenalty),
+            "min_p": decimal(ctx.sampling.minP),
+        ]
+        if let seed = ctx.sampling.seed { body["seed"] = seed }
+
+        // One variant per effort Splash accepts for this model. Splash reads snake_case
+        // `reasoning_effort` from the request body, so the body overlay is the reliable path.
+        let variants: [[String: Any]] = ctx.efforts.map { effort in
+            ["id": effort, "body": ["reasoning_effort": effort]]
+        }
+        let reasoningEfforts = ctx.efforts.filter { $0 != "none" }
+        let reasoning: [String: Any] = [
+            "supported": true,
+            "toggle": ctx.efforts.contains("none"),
+            "effort": reasoningEfforts,
+        ]
+        let model: [String: Any] = [
+            "name": ctx.label,
+            "capabilities": [
+                "tools": true,
+                "input": modalities,
+                "output": ["text"],
+                "reasoning": reasoning,
+            ],
+            // Splash streams thinking in reasoning_content and reads the output cap as
+            // max_tokens, so tell the OpenAI-compatible package both.
+            "compatibility": [
+                "reasoningField": "reasoning_content",
+                "maxTokensField": "max_tokens",
+            ],
+            "limit": ["context": ctx.contextTokens,
+                      "input": ctx.contextTokens - out,
+                      "output": out],
+            "body": body,
+            "variants": variants,
+        ]
+        let root: [String: Any] = [
+            "$schema": "https://opencode.ai/config.json",
+            "providers": [
+                "splashgui": [
+                    "name": "SplashGUI",
+                    "package": "@opencode/ai/providers/openai-compatible",
+                    "settings": [
+                        "baseURL": "http://127.0.0.1:\(ctx.port)/v1",
+                        "apiKey": "local",
+                    ],
+                    "models": [ctx.modelID: model],
+                ]
+            ],
+        ]
+        return json(root)
+    }
+
+    // MARK: - Zed
+
+    private static func zed(_ ctx: ClientConfigContext) -> String {
+        let modalities = inputModalities(ctx)
+        var model: [String: Any] = [
+            "name": ctx.modelID,
+            "display_name": ctx.label,
+            "max_tokens": ctx.contextTokens,
+            "max_output_tokens": responseTokens(context: ctx.contextTokens),
+            // Splash streams thinking in a dedicated reasoning_content field and takes the
+            // output cap as max_tokens; tool calling works. Images follow the vision toggle.
+            "capabilities": [
+                "tools": true,
+                "images": modalities != ["text"],
+                "parallel_tool_calls": false,
+                "prompt_cache_key": false,
+                "chat_completions": true,
+                "interleaved_reasoning": true,
+                "max_tokens_parameter": true,
+            ],
+        ]
+        if ctx.sampling.reasoningEffort != "none" {
+            // Tells Zed which effort to send when thinking is on; unset = the server default.
+            model["reasoning_effort"] = ctx.sampling.reasoningEffort ?? "medium"
+        }
+        var root: [String: Any] = [
+            "language_models": [
+                "openai_compatible": [
+                    "splash": [
+                        "api_url": "http://127.0.0.1:\(ctx.port)/v1",
+                        "available_models": [model],
+                    ]
+                ]
+            ]
+        ]
+        // Zed carries temperature per model (agent.model_parameters); the provider is omitted
+        // so the entry matches Zed's provider key for the custom provider regardless of its
+        // exact spelling. Keys stay out of settings.json — Zed wants SPLASH_API_KEY in the
+        // environment (generated from the provider name), noted in the tab's caption.
+        if ctx.sampling.temperature > 0 {
+            root["agent"] = ["model_parameters": [["model": ctx.modelID,
+                                                   "temperature": ctx.sampling.temperature]]]
+        }
+        return json(root)
+    }
+
+    // MARK: - Claude Code
+
+    private static func claudeCode(_ ctx: ClientConfigContext) -> String {
+        // Mirrors the engine connector's _claude environment. ANTHROPIC_BASE_URL takes the
+        // bare server URL — Claude Code appends /v1/messages itself. No sampling fields:
+        // Claude Code sets its own per request.
+        let env: [String: Any] = [
+            "ANTHROPIC_BASE_URL": "http://127.0.0.1:\(ctx.port)",
+            "ANTHROPIC_AUTH_TOKEN": "local",
+            "ANTHROPIC_MODEL": ctx.modelID,
+            "ANTHROPIC_DEFAULT_OPUS_MODEL": ctx.modelID,
+            "ANTHROPIC_DEFAULT_SONNET_MODEL": ctx.modelID,
+            "ANTHROPIC_DEFAULT_HAIKU_MODEL": ctx.modelID,
+            "ANTHROPIC_SMALL_FAST_MODEL": ctx.modelID,
+            "CLAUDE_CODE_MAX_CONTEXT_TOKENS": String(ctx.contextTokens),
+            "CLAUDE_CODE_AUTO_COMPACT_WINDOW": String(ctx.contextTokens),
+        ]
+        return json(["env": env])
+    }
+
+    // MARK: - Codex
+
+    private static func codex(_ ctx: ClientConfigContext) -> String {
+        // Mirrors the engine connector's _codex -c overrides, as the config.toml shape.
+        // wire_api = responses: Codex speaks /v1/responses, which Splash serves.
+        """
+        model = "\(ctx.modelID)"
+        model_provider = "splash"
+        model_context_window = \(ctx.contextTokens)
+        model_auto_compact_token_limit = \(ctx.contextTokens * 9 / 10)
+        web_search = "disabled"
+
+        [model_providers.splash]
+        name = "Splash"
+        base_url = "http://127.0.0.1:\(ctx.port)/v1"
+        env_key = "SPLASH_API_KEY"
+        wire_api = "responses"
+        """
+    }
+}
diff --git a/Sources/SplashGUI/Core/EngineInstaller.swift b/Sources/SplashGUI/Core/EngineInstaller.swift
new file mode 100644
index 0000000..81642f8
--- /dev/null
+++ b/Sources/SplashGUI/Core/EngineInstaller.swift
@@ -0,0 +1,349 @@
+import Foundation
+import CryptoKit
+
+struct EnginePin: Equatable {
+    let version: String
+    let sha256: String
+    let url: String
+}
+
+final class EngineInstaller: ObservableObject {
+    enum Step: Equatable {
+        case idle
+        case checking
+        case downloading
+        case verifying
+        case extracting
+        case validating
+        case switching
+        case ready
+        case failed(String)
+    }
+
+    @Published var step: Step = .idle
+    @Published var progress: Double = 0
+    @Published var resolvedVersion: String?
+    @Published var installedVersion: String?
+
+    // Bumping the engine is an app release; AppConfig's engine*Override fields are the escape hatch.
+    static let defaultPin = EnginePin(
+        version: "1.5.0",
+        sha256: "1ddc28bf7bfda8833859a913d7072e2aac9072addb9eb5664f3bf1a83a8d6ee2",
+        url: "https://github.com/incoai/splash/releases/download/1.5.0/splash-1.5.0-arm64-macos26.tar.gz"
+    )
+
+    static let fm = FileManager.default
+
+    static var engineRoot: URL { AppPaths.dataDir.appendingPathComponent("engine", isDirectory: true) }
+    static var currentLink: URL { engineRoot.appendingPathComponent("current") }
+    static var stagedDir: URL { engineRoot.appendingPathComponent(".staged", isDirectory: true) }
+    static var installLock: URL { engineRoot.appendingPathComponent(".install.lock") }
+
+    static var pythonPath: URL { currentLink.appendingPathComponent("python/bin/python3") }
+    static var launcherPath: URL { currentLink.appendingPathComponent("install/launcher.py") }
+
+    static func currentReleaseVersion() -> String? {
+        let rel = currentLink.appendingPathComponent("release.json")
+        guard let data = try? Data(contentsOf: rel),
+              let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+              let v = obj["version"] as? String else { return nil }
+        return v
+    }
+
+    init() {
+        installedVersion = Self.currentReleaseVersion()
+    }
+
+    static var isInstalled: Bool {
+        FileManager.default.isExecutableFile(atPath: pythonPath.path)
+    }
+
+    func ensureInstalled(port: Int, override: EnginePin? = nil) async throws {
+        await MainActor.run { self.step = .checking; self.progress = 0 }
+        let pin = override ?? Self.defaultPin
+        await MainActor.run { self.resolvedVersion = pin.version }
+
+        // Reuse only when `current` points at exactly this pin's dir — an override of the same
+        // version from another URL installs into its own dir and must not be skipped.
+        if let have = Self.currentReleaseVersion(), have == pin.version, Self.isInstalled,
+           (try? Self.fm.destinationOfSymbolicLink(atPath: Self.currentLink.path)) == Self.dirName(for: pin) {
+            await MainActor.run { self.installedVersion = have; self.step = .ready }
+            return
+        }
+
+        try preflight(port: port)
+        // preflight takes the install lock; hold it only for the install itself. flock treats a
+        // second open of the same file in one process as a different holder, so without this a
+        // failed (or pin-changed) install would leave the GUI locked out — "another install is
+        // already in progress" — until relaunch.
+        defer { Self.releaseInstallLock() }
+
+        let name = Self.dirName(for: pin)
+        let stagedTar = Self.stagedDir.appendingPathComponent(name + ".tar.gz")
+        let stagedRoot = Self.stagedDir.appendingPathComponent(name, isDirectory: true)
+
+        try Self.fm.createDirectory(at: Self.stagedDir, withIntermediateDirectories: true)
+        try? Self.fm.removeItem(at: stagedTar)
+        try? Self.fm.removeItem(at: stagedRoot)
+
+        do {
+            try await download(pin: pin, to: stagedTar)
+            await MainActor.run { self.step = .verifying; self.progress = 1.0 }
+            let got = try Self.sha256(of: stagedTar)
+            guard got.caseInsensitiveCompare(pin.sha256) == .orderedSame else {
+                throw InstallError.preflight("Downloaded engine failed checksum (expected \(pin.sha256.prefix(12))…, got \(got.prefix(12))…).")
+            }
+
+            await MainActor.run { self.step = .extracting }
+            try Self.run("/usr/bin/tar", ["-xzf", stagedTar.path, "-C", Self.stagedDir.path])
+            let release = stagedRoot.appendingPathComponent("release.json")
+            guard Self.fm.fileExists(atPath: release.path) else {
+                throw InstallError.preflight("Extracted archive is missing release.json; unexpected payload.")
+            }
+            for rel in ["python/bin/python3", "engine/splash"] {
+                try? Self.fm.setAttributes([.posixPermissions: 0o755],
+                    ofItemAtPath: stagedRoot.appendingPathComponent(rel).path)
+            }
+
+            await MainActor.run { self.step = .validating }
+            try Self.run(stagedRoot.appendingPathComponent("python/bin/python3").path,
+                ["-u", stagedRoot.appendingPathComponent("install/launcher.py").path, "--help"])
+
+            await MainActor.run { self.step = .switching }
+            let finalDir = Self.engineRoot.appendingPathComponent(name, isDirectory: true)
+            try? Self.fm.removeItem(at: finalDir)
+            try Self.fm.createDirectory(at: Self.engineRoot, withIntermediateDirectories: true)
+            try Self.fm.moveItem(at: stagedRoot, to: finalDir)
+            try Self.flipCurrent(to: name)
+            Self.prune(keeping: name)
+            try? Self.fm.removeItem(at: stagedTar)
+
+            let v = Self.currentReleaseVersion()
+            await MainActor.run { self.installedVersion = v; self.step = .ready }
+        } catch {
+            try? Self.fm.removeItem(at: stagedRoot)
+            try? Self.fm.removeItem(at: stagedTar)
+            await MainActor.run {
+                if self.step != .ready {
+                    self.step = .failed((error as? LocalizedError)?.errorDescription ?? "\(error)")
+                }
+            }
+            throw error
+        }
+    }
+
+    // MARK: preflight
+
+    private func preflight(port: Int) throws {
+        var sys = utsname()
+        if uname(&sys) == 0 {
+            let machine = withUnsafeBytes(of: &sys.machine) { raw in
+                String(decoding: raw.prefix(while: { $0 != 0 }), as: UTF8.self)
+            }
+            if machine != "arm64" {
+                throw InstallError.preflight("This Mac is not running natively on arm64; the Splash engine needs native arm64.")
+            }
+        }
+        if #available(macOS 26.4, *) {} else {
+            throw InstallError.preflight("The Splash engine needs macOS 26.4 or later.")
+        }
+        guard let free = MachineInfo.freeDisk, free >= 1_200_000_000 else {
+            throw InstallError.preflight("Not enough free disk space to install the engine (need ~1.2 GB).")
+        }
+        if Self.splashServing(port: port) {
+            throw InstallError.preflight("A Splash server is already running. Stop it before updating the engine.")
+        }
+        if !Self.acquireInstallLock() {
+            throw InstallError.preflight("Another engine install is already in progress.")
+        }
+    }
+
+    private static func splashServing(port: Int) -> Bool {
+        let base = fm.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
+            .appendingPathComponent("Splash", isDirectory: true)
+            .appendingPathComponent("runtime", isDirectory: true)
+        guard let base, let names = try? fm.contentsOfDirectory(atPath: base.path) else { return false }
+        for n in names where n.hasPrefix("serve") && n.hasSuffix(".lock") {
+            guard let data = try? Data(contentsOf: base.appendingPathComponent(n)),
+                  let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+                  let pid = obj["pid"] as? Int else { continue }
+            if kill(Int32(pid), 0) == 0 { return true }
+        }
+        return false
+    }
+
+    private static var lockFD: Int32 = -1
+    private static func acquireInstallLock() -> Bool {
+        try? fm.createDirectory(at: engineRoot, withIntermediateDirectories: true)
+        let fd = open(installLock.path, O_RDWR | O_CREAT, 0o644)
+        if fd < 0 { return false }
+        if flock(fd, LOCK_EX | LOCK_NB) != 0 { close(fd); return false }
+        lockFD = fd
+        return true
+    }
+    static func releaseInstallLock() {
+        if lockFD >= 0 { flock(lockFD, LOCK_UN); close(lockFD); lockFD = -1 }
+    }
+
+    // MARK: download
+
+    private func download(pin: EnginePin, to dest: URL) async throws {
+        guard let url = URL(string: pin.url) else {
+            throw InstallError.preflight("Engine download URL is malformed.")
+        }
+        let delegate = DownloadDelegate { [weak self] frac in
+            Task { @MainActor in
+                self?.step = .downloading
+                self?.progress = frac
+            }
+        }
+        let cfg = URLSessionConfiguration.ephemeral
+        cfg.timeoutIntervalForRequest = 60
+        cfg.timeoutIntervalForResource = 1800
+        let session = URLSession(configuration: cfg, delegate: delegate, delegateQueue: nil)
+        defer { session.invalidateAndCancel() }
+        let task = session.downloadTask(with: url)
+        try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in
+            delegate.onFinish = { result in
+                switch result {
+                case .success(let tmp):
+                    try? FileManager.default.removeItem(at: dest)
+                    do { try FileManager.default.moveItem(at: tmp, to: dest); cont.resume() }
+                    catch { cont.resume(throwing: error) }
+                case .failure(let e):
+                    cont.resume(throwing: e)
+                }
+            }
+            task.resume()
+        }
+    }
+
+    // MARK: helpers
+
+    static func dirName(for pin: EnginePin) -> String {
+        let base = "splash-\(pin.version)-arm64-macos26"
+        // An override URL can serve a different payload under a version the pinned release
+        // already used; keying the dir by the URL keeps the two installs from sharing it.
+        guard pin.url != defaultPin.url else { return base }
+        let h = SHA256.hash(data: Data(pin.url.utf8)).prefix(4).map { String(format: "%02x", $0) }.joined()
+        return "splash-\(pin.version)-\(h)-arm64-macos26"
+    }
+
+    static func sha256(of url: URL) throws -> String {
+        let handle = try FileHandle(forReadingFrom: url)
+        defer { try? handle.close() }
+        var hasher = SHA256()
+        while autoreleasepool(invoking: {
+            let chunk = handle.readData(ofLength: 1 << 20)
+            if chunk.isEmpty { return false }
+            hasher.update(data: chunk)
+            return true
+        }) {}
+        return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+    }
+
+    static func run(_ exe: String, _ args: [String]) throws {
+        let p = Process()
+        p.executableURL = URL(fileURLWithPath: exe)
+        p.arguments = args
+        p.standardOutput = FileHandle.nullDevice
+        p.standardError = FileHandle.nullDevice
+        try p.run()
+        p.waitUntilExit()
+        if p.terminationStatus != 0 {
+            throw InstallError.preflight("`\(exe)` exited with status \(p.terminationStatus).")
+        }
+    }
+
+    static func flipCurrent(to name: String) throws {
+        let tmp = currentLink.appendingPathExtension("new")
+        try? fm.removeItem(at: tmp)
+        try fm.createSymbolicLink(atPath: tmp.path, withDestinationPath: name)
+        if rename(tmp.path, currentLink.path) != 0 {
+            try? fm.removeItem(at: tmp)
+            throw InstallError.preflight("Could not activate the new engine (symlink flip failed).")
+        }
+    }
+
+    static func prune(keeping name: String) {
+        guard let names = try? fm.contentsOfDirectory(atPath: engineRoot.path) else { return }
+        for n in names where n.hasPrefix("splash-") && n.hasSuffix("-arm64-macos26") && n != name {
+            try? fm.removeItem(at: engineRoot.appendingPathComponent(n, isDirectory: true))
+        }
+    }
+}
+
+enum InstallError: LocalizedError {
+    case preflight(String)
+    var errorDescription: String? {
+        switch self {
+        case .preflight(let m): return m
+        }
+    }
+}
+
+extension EngineInstaller {
+    // Headless install for `SplashGUI --install-engine` — drives the same flow, pumps the
+    // main runloop so MainActor hops run, prints phase changes, exits 0/1.
+    static func runCLI(port: Int) -> Int32 {
+        setbuf(stdout, nil)
+        let inst = EngineInstaller()
+        var code: Int32 = 1
+        let done = DispatchSemaphore(value: 0)
+        Task {
+            do {
+                try await inst.ensureInstalled(port: port)
+                code = 0
+            } catch {
+                let m = (error as? LocalizedError)?.errorDescription ?? "\(error)"
+                FileHandle.standardError.write(Data("install failed: \(m)\n".utf8))
+                code = 1
+            }
+            releaseInstallLock()
+            done.signal()
+        }
+        var last = ""
+        while done.wait(timeout: .now()) == .timedOut {
+            RunLoop.main.run(until: Date().addingTimeInterval(0.1))
+            let line = "\(inst.step) \(Int(inst.progress * 100))%"
+            if line != last { print(line); last = line }
+        }
+        print("engine \(inst.installedVersion ?? "?") → \(currentLink.path)")
+        return code
+    }
+}
+
+private final class DownloadDelegate: NSObject, URLSessionDownloadDelegate {
+    private let onProgress: (Double) -> Void
+    var onFinish: ((Result<URL, Error>) -> Void)?
+    init(onProgress: @escaping (Double) -> Void) { self.onProgress = onProgress }
+
+    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
+                    didFinishDownloadingTo location: URL) {
+        guard !finished else { return }
+        // A failed request (rate-limit page, missing asset) still "finishes downloading" its
+        // error body; without the status check that HTML lands as tar.gz and only surfaces as
+        // a confusing checksum failure.
+        if let http = downloadTask.response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
+            finished = true
+            onFinish?(.failure(InstallError.preflight(
+                "Engine download failed: HTTP \(http.statusCode) from \(http.url?.host ?? "server").")))
+            return
+        }
+        finished = true
+        onFinish?(.success(location))
+    }
+    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
+                    didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
+                    totalBytesExpectedToWrite: Int64) {
+        guard totalBytesExpectedToWrite > 0 else { return }
+        onProgress(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite))
+    }
+    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+        if let error, !finished {
+            finished = true
+            onFinish?(.failure(error))
+        }
+    }
+    private var finished = false
+}
diff --git a/Sources/SplashGUI/Core/EngineResolver.swift b/Sources/SplashGUI/Core/EngineResolver.swift
new file mode 100644
index 0000000..343344a
--- /dev/null
+++ b/Sources/SplashGUI/Core/EngineResolver.swift
@@ -0,0 +1,87 @@
+import Foundation
+
+// How the app decides which engine build to run.
+enum EngineMode: String, Codable, Equatable {
+    case pinned   // the build this SplashGUI shipped with (EngineInstaller.defaultPin)
+    case latest   // newest GitHub release, checked on every start; falls back below
+    case custom   // the three override fields (AppConfig.enginePinOverride)
+}
+
+// Resolves the newest Splash engine release from GitHub so "always latest" can install a
+// build this app never shipped with. The checksum comes from the release's own .sha256
+// asset and is verified by EngineInstaller exactly like the compiled-in pin; HTTPS plus
+// that digest is the same trust the published release gives the pin at review time.
+// Every failure — offline, rate-limited, unexpected payload — returns nil and the caller
+// falls back, so this can never block Start.
+struct EngineResolver {
+    static let repo = "incoai/splash"
+    static var latestAPI: String { "https://api.github.com/repos/\(repo)/releases/latest" }
+
+    // The release tag as an engine version: GitHub download paths use the tag, the payload
+    // names the version; today they are the same string ("1.5.0"), but a future "v" prefix
+    // must not leak into the version or the file name.
+    static func version(tagName: String) -> String {
+        tagName.hasPrefix("v") ? String(tagName.dropFirst()) : tagName
+    }
+
+    static func assetFile(version: String) -> String {
+        "splash-\(version)-arm64-macos26.tar.gz"
+    }
+
+    // The pure half, so the harness can feed it a fixture instead of the network: a
+    // release's tag, asset names, and .sha256 text become an EnginePin — or nil when the
+    // expected payload is not there. The URL is built exactly like EngineInstaller's
+    // defaultPin so a latest equal to the compiled-in pin reuses its install directory.
+    static func pin(tagName: String, assetNames: [String], sha256Text: String) -> EnginePin? {
+        let v = version(tagName: tagName)
+        let file = assetFile(version: v)
+        guard assetNames.contains(file), assetNames.contains(file + ".sha256") else { return nil }
+        let sha = sha256Text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
+        guard sha.count == 64, sha.allSatisfy(\.isHexDigit) else { return nil }
+        return EnginePin(version: v, sha256: sha,
+                         url: "https://github.com/\(repo)/releases/download/\(tagName)/\(file)")
+    }
+
+    // The live half: GET /releases/latest, then the .sha256 asset (a ~70-byte text file).
+    // Anonymous GitHub API is capped at 60 requests/hour/IP — one per Start is far under.
+    static func latest() async -> EnginePin? {
+        guard let release = try? await fetchJSON(latestAPI),
+              let tag = release["tag_name"] as? String,
+              let assets = release["assets"] as? [[String: Any]] else { return nil }
+        let names = assets.compactMap { $0["name"] as? String }
+        let file = assetFile(version: version(tagName: tag)) + ".sha256"
+        guard names.contains(file),
+              let text = try? await fetchText(
+                  "https://github.com/\(repo)/releases/download/\(tag)/\(file)") else { return nil }
+        return pin(tagName: tag, assetNames: names, sha256Text: text)
+    }
+
+    private static func request(_ url: String) -> URLRequest? {
+        guard let u = URL(string: url) else { return nil }
+        var r = URLRequest(url: u, timeoutInterval: 15)
+        // The API serves versioned JSON without this only by default; pin it so a media-type
+        // change cannot rename tag_name/assets under us.
+        r.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+        return r
+    }
+
+    private static func fetchJSON(_ url: String) async throws -> [String: Any] {
+        guard let r = request(url) else { throw URLError(.badURL) }
+        let (data, resp) = try await URLSession.shared.data(for: r)
+        guard let http = resp as? HTTPURLResponse, (200...299).contains(http.statusCode),
+              let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+            throw URLError(.badServerResponse)
+        }
+        return obj
+    }
+
+    private static func fetchText(_ url: String) async throws -> String {
+        guard let r = request(url) else { throw URLError(.badURL) }
+        let (data, resp) = try await URLSession.shared.data(for: r)
+        guard let http = resp as? HTTPURLResponse, (200...299).contains(http.statusCode),
+              let text = String(data: data, encoding: .utf8) else {
+            throw URLError(.badServerResponse)
+        }
+        return text
+    }
+}
diff --git a/Sources/SplashGUI/Core/MachineInfo.swift b/Sources/SplashGUI/Core/MachineInfo.swift
new file mode 100644
index 0000000..a52c68e
--- /dev/null
+++ b/Sources/SplashGUI/Core/MachineInfo.swift
@@ -0,0 +1,220 @@
+import Foundation
+import Metal
+import os
+
+enum MachineInfo {
+    private static let sizeLock = NSLock()
+    private static var sizeCache: [String: Int] = [:]
+
+    // Drop a cached size so the next lookup re-reads disk (e.g. after a model finishes downloading).
+    static func invalidateModelSize(_ modelID: String) {
+        sizeLock.lock()
+        sizeCache[modelID] = nil
+        sizeLock.unlock()
+    }
+
+    static func cachedModelSize(_ modelID: String) -> Int? {
+        sizeLock.lock()
+        if let v = sizeCache[modelID] {
+            sizeLock.unlock()
+            return v
+        }
+        sizeLock.unlock()
+        let v = weightsSize(for: modelID)
+        sizeLock.lock()
+        sizeCache[modelID] = v
+        sizeLock.unlock()
+        return v
+    }
+
+    static var physicalRAM: Int {
+        Int(ProcessInfo.processInfo.physicalMemory)
+    }
+
+    // The real GPU wired-memory ceiling for this exact chip/RAM combo, read once at runtime
+    // (37.44 GB on the 48 GB M5 Pro). Falls back to the ~66% stock ratio if Metal is unavailable.
+    static let metalMaxWorkingSet: Int = {
+        if let cap = MTLCreateSystemDefaultDevice()?.recommendedMaxWorkingSetSize, cap > 0 {
+            return Int(cap)
+        }
+        return physicalRAM * 66 / 100
+    }()
+
+    static var availableRAM: Int? {
+        var stats = vm_statistics64()
+        var count = mach_msg_type_number_t(
+            UInt32(MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size))
+        let kr = withUnsafeMutablePointer(to: &stats) { ptr in
+            ptr.withMemoryRebound(
+                to: integer_t.self,
+                capacity: MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size
+            ) { dataPtr in
+                host_statistics64(mach_host_self(), HOST_VM_INFO64, dataPtr, &count)
+            }
+        }
+        guard kr == KERN_SUCCESS else { return nil }
+        let avail = UInt64(stats.free_count + stats.inactive_count + stats.speculative_count)
+        return Int(avail * UInt64(vm_page_size))
+    }
+
+    static var freeDisk: Int? {
+        guard let attrs = try? FileManager.default.attributesOfFileSystem(forPath: "/") else { return nil }
+        return (attrs[.systemFreeSize] as? Int64).map(Int.init)
+    }
+
+    static func footprint(pid: Int) -> Int? {
+        var info = rusage_info_current()
+        let r = withUnsafeMutableBytes(of: &info) { rawBuf in
+            let typed = rawBuf.bindMemory(to: rusage_info_t?.self)
+            return proc_pid_rusage(Int32(pid), RUSAGE_INFO_CURRENT, typed.baseAddress)
+        }
+        guard r == 0 else { return nil }
+        return Int(info.ri_phys_footprint)
+    }
+
+    static func childPIDs(of parent: Int) -> [Int] {
+        var size = 0
+        guard sysctlbyname("kern.proc.all", nil, &size, nil, 0) == 0, size > 0 else { return [] }
+        let slots = size / MemoryLayout<kinfo_proc>.stride
+        var procs = [kinfo_proc](repeating: kinfo_proc(), count: slots)
+        guard sysctlbyname("kern.proc.all", &procs, &size, nil, 0) == 0 else { return [] }
+        let count = size / MemoryLayout<kinfo_proc>.stride
+        guard count > 0, count <= procs.count else { return [] }
+        return (0..<count)
+            .filter { Int(procs[$0].kp_eproc.e_ppid) == parent }
+            .map { Int(procs[$0].kp_proc.p_pid) }
+    }
+
+    static func serverFootprint(parentPID: Int) -> Int? {
+        var total = footprint(pid: parentPID) ?? 0
+        for child in childPIDs(of: parentPID) {
+            total += footprint(pid: child) ?? 0
+        }
+        return total > 0 ? total : nil
+    }
+
+    static func weightsSize(for modelID: String) -> Int? {
+        guard let dir = weightsDir(for: modelID) else { return nil }
+        return directorySize(dir)
+    }
+
+    // Splash's selection link for a model ID: <models root>/<owner>/<repo[:variant]>, a symlink
+    // to the content-addressed assembly under models/.resolved/ that holds model.json. The
+    // variant is part of the link name, so it stays in the path here.
+    static func selectionDir(for modelID: String) -> URL? {
+        guard let slash = modelID.firstIndex(of: "/") else { return nil }
+        let owner = String(modelID[..<slash])
+        let repo = String(modelID[modelID.index(after: slash)...])
+        guard !owner.isEmpty, !repo.isEmpty else { return nil }
+        let dir = FileManager.default.homeDirectoryForCurrentUser
+            .appendingPathComponent("Library/Application Support/Splash/models/\(owner)/\(repo)")
+        return FileManager.default.fileExists(atPath: dir.path) ? dir : nil
+    }
+
+    // The Hugging Face cache directory for a model ID: models--<owner>--<repo>, variant stripped.
+    // One implementation of the naming rule; existence is the caller's question.
+    static func hfCacheDir(for modelID: String) -> URL? {
+        guard let slash = modelID.firstIndex(of: "/") else { return nil }
+        let owner = String(modelID[..<slash])
+        let repo = String(modelID[modelID.index(after: slash)...]).split(separator: ":").first ?? ""
+        guard !owner.isEmpty, !repo.isEmpty else { return nil }
+        return FileManager.default.homeDirectoryForCurrentUser
+            .appendingPathComponent(".cache/huggingface/hub/models--\(owner)--\(repo)")
+    }
+
+    static func weightsDir(for modelID: String) -> URL? {
+        if let splash = selectionDir(for: modelID) { return splash }
+        guard let hf = hfCacheDir(for: modelID),
+              FileManager.default.fileExists(atPath: hf.path) else { return nil }
+        return hf
+    }
+
+    // The digest the engine recorded in model.json for one file of an installed assembly, keyed
+    // as the record keys it ("target/<file>.gguf"). nil = not installed, or no record. The
+    // engine's quick verify only re-checks these records' paths and byte counts, so comparing a
+    // catalog hash against them catches a swapped or edited blob that quick verify would pass.
+    static func installedDigest(for modelID: String, key: String) -> String? {
+        guard let record = selectionDir(for: modelID)?.appendingPathComponent("model.json"),
+              let data = try? Data(contentsOf: record), data.count < 4_194_304,
+              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+              let files = json["files"] as? [String: [String: Any]],
+              let entry = files[key] else { return nil }
+        return entry["digest"] as? String
+    }
+
+    // nil when the installed assembly matches the catalog hash (or there is nothing to compare),
+    // else a plain-language explanation. One implementation: Start blocks on it, --check-model prints it.
+    static func modelHashMismatch(_ modelID: String) -> String? {
+        guard let entry = CatalogModel.catalog.first(where: { $0.id == modelID }),
+              let expected = entry.sha256, let target = entry.targetFile
+        else { return nil }
+        guard let installed = installedDigest(for: modelID, key: "target/\(target)") else { return nil }
+        guard installed != expected else { return nil }
+        return "\(modelID): the installed \(target) does not match the catalog hash. On disk "
+            + "\(installed), expected \(expected). The cached download changed or is corrupt; delete "
+            + "~/.cache/huggingface/hub/models--\(entry.owner)--\(entry.hfRepo) and start again to re-pull it."
+    }
+
+    // Sums the real bytes under a directory, following symlinks. The Splash model path is a
+    // symlink into the HF snapshot and its files are symlinks into the content-addressed blob
+    // store, so the default enumerator (which treats symlinks as non-regular) sees nothing.
+    // Resolving each path and deduping by resolved URL counts each shared blob exactly once.
+    static func directorySize(_ url: URL) -> Int? {
+        let fm = FileManager.default
+        let keys: [URLResourceKey] = [.fileSizeKey, .isRegularFileKey]
+        let root = url.resolvingSymlinksInPath()
+        guard let enumerator = fm.enumerator(at: root, includingPropertiesForKeys: keys) else { return nil }
+        var seen = Set<URL>()
+        var total = 0
+        for case let file as URL in enumerator {
+            let real = file.resolvingSymlinksInPath()
+            guard let vals = try? real.resourceValues(forKeys: Set(keys)) else { continue }
+            guard vals.isRegularFile == true else { continue }
+            if !seen.insert(real).inserted { continue }
+            total += vals.fileSize ?? 0
+        }
+        return total > 0 ? total : nil
+    }
+
+    // Computes run settings for a model from this Mac's GPU wired-memory ceiling. Pure: no
+    // process, no UI. weightsBytes overrides the on-disk lookup (e.g. a catalog estimate
+    // before the model has downloaded). Returns nil when the model can't be sized confidently.
+    // Keys on the Metal ceiling, NOT free RAM: macOS keeps RAM resident and evicts on demand,
+    // so availableRAM sits ~50-60% "used" at idle and would spuriously collapse the pick.
+    static func autoProfile(modelID: String, languageOnly: Bool, weightsBytes: Int? = nil) -> AutoProfile? {
+        // Auto's KV-per-token and window constants were measured on the Qwen3.8-27B arch; other
+        // archs return nil here and the engine sizes itself.
+        guard CatalogModel.catalog.first(where: { $0.id == modelID })?.qwen27BArch == true else { return nil }
+        let weights = weightsBytes ?? weightsSize(for: modelID)
+        guard let weights else { return nil }
+        let maxMemory = metalMaxWorkingSet  // hard GPU wired ceiling; already reserves ~22% for the OS
+        let engineFixed = 1_610_612_736  // 1.5 GiB: engine buffers + native MTP draft
+        let vision = languageOnly ? 0 : 536_870_912  // 0.5 GiB: vision projector
+        let budget = maxMemory - weights - engineFixed - vision
+        guard budget > 0 else { return nil }
+        let window = CatalogModel.windowTokens
+        func context(_ bytesPerToken: Int) -> Int {
+            let capped = min(budget / bytesPerToken, window)
+            return (capped / 32_768) * 32_768
+        }
+        // One KV constant for the 27B arch (67 KiB/token BF16, half for INT8).
+        let bf16 = context(68_608)
+        if bf16 >= 32_768 {
+            return AutoProfile(maxMemoryBytes: maxMemory, contextTokens: bf16, kvFormat: "bf16")
+        }
+        let int8 = context(34_304)
+        guard int8 >= 32_768 else { return nil }
+        return AutoProfile(maxMemoryBytes: maxMemory, contextTokens: int8, kvFormat: "int8")
+    }
+
+    static func gb(_ bytes: Int?) -> String {
+        guard let bytes else { return "–" }
+        return String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
+    }
+}
+
+struct AutoProfile: Equatable {
+    let maxMemoryBytes: Int
+    let contextTokens: Int
+    let kvFormat: String
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Core/SplashClient.swift b/Sources/SplashGUI/Core/SplashClient.swift
new file mode 100644
index 0000000..0223822
--- /dev/null
+++ b/Sources/SplashGUI/Core/SplashClient.swift
@@ -0,0 +1,148 @@
+import Foundation
+
+struct StatusSnapshot {
+    let raw: [String: Any]
+
+    subscript(_ path: [String]) -> Any? {
+        var current: Any? = raw
+        for key in path {
+            guard let dict = current as? [String: Any] else { return nil }
+            current = dict[key]
+        }
+        return current
+    }
+
+    private func num(_ path: [String]) -> Double? {
+        guard let v = self[path] else { return nil }
+        if let d = v as? Double { return d }
+        if let i = v as? Int { return Double(i) }
+        if let s = v as? String { return Double(s) }
+        return nil
+    }
+
+    func number(_ path: String...) -> Double? {
+        num(path)
+    }
+
+    func string(_ path: String...) -> String? {
+        guard let v = self[path] else { return nil }
+        return v as? String
+    }
+
+    func int(_ path: String...) -> Int? {
+        num(path).map { Int($0) }
+    }
+
+    var instanceModel: String? { string("instance", "model") }
+    var instancePID: Int? { int("instance", "pid") }
+    var maxContextTokens: Int? {
+        int("maximum_context_tokens") ?? int("native", "maximum_context_tokens")
+    }
+    // The memory budget Splash actually charged itself (== the --max-memory it was given, or
+    // its own ceiling when the flag was omitted). Verified live on 1.3.2, spec §8.1; the 1.5.0
+    // backend status still emits it (frontend.status() passes backend.status() through).
+    var hardBudgetBytes: Int? { int("memory_plan", "budget", "hard_budget_bytes") }
+    var ttftP50: Double? { number("metrics", "ttft_ms", "p50") }
+    var ttftP95: Double? { number("metrics", "ttft_ms", "p95") }
+    var itlP50: Double? { number("metrics", "itl_ms", "p50") }
+    var itlP95: Double? { number("metrics", "itl_ms", "p95") }
+    var cacheHitRate: Double? { number("cache", "hit_rate") }
+    var cacheLookups: Int? { int("cache", "lookups") }
+    var reusedTokens: Int? { int("cache", "reused_tokens") }
+    var kvPagesActive: Int? { int("kv", "pages_active") }
+    var kvBlockTokens: Int? { int("kv", "block_tokens") }
+    // What the running server accepts: ["text"] or ["text","image","pdf"].
+    var inputModalities: [String]? { self[["input_modalities"]] as? [String] }
+
+    // Live fraction of the granted context window occupied by active requests' KV:
+    // resident tokens (active pages x tokens-per-page) over the ceiling. Server-wide, so it
+    // reflects every client (web chat included), not just app-run requests.
+    var contextUsedFraction: Double? {
+        guard let active = kvPagesActive, let block = kvBlockTokens, block > 0,
+              let max = maxContextTokens, max > 0 else { return nil }
+        return min(1.0, Double(active * block) / Double(max))
+    }
+    // Raw tokens held by active requests' KV (pages × tokens-per-page); the toolbar caption
+    // shows this over the granted window, the bar shows the fraction.
+    var contextUsedTokens: Int? {
+        guard let active = kvPagesActive, let block = kvBlockTokens else { return nil }
+        return active * block
+    }
+    var kvResidentBytes: Int? { int("kv", "resident_backing_bytes") }
+    var stateBytes: Int? { int("state", "bytes") }
+    var stateEntries: Int? { int("state", "entries") }
+    var queued: Int? { int("scheduler", "queued") }
+    var prefilling: Int? { int("scheduler", "prefilling") }
+    var decoding: Int? { int("scheduler", "decoding") }
+}
+
+final class SplashClient {
+    let port: Int
+
+    init(port: Int) { self.port = port }
+
+    private var baseURL: URL { URL(string: "http://127.0.0.1:\(port)")! }
+
+    func ready() async -> Bool {
+        guard let url = URL(string: "\(baseURL)/ready") else { return false }
+        let req = URLRequest(url: url, timeoutInterval: 3)
+        do {
+            let (_, resp) = try await URLSession.shared.data(for: req)
+            if let http = resp as? HTTPURLResponse { return http.statusCode == 200 }
+            return false
+        } catch {
+            return false
+        }
+    }
+
+    func fetchStatus() async -> StatusSnapshot? {
+        guard let url = URL(string: "\(baseURL)/status") else { return nil }
+        let req = URLRequest(url: url, timeoutInterval: 5)
+        do {
+            let (data, _) = try await URLSession.shared.data(for: req)
+            guard let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
+            return StatusSnapshot(raw: dict)
+        } catch {
+            return nil
+        }
+    }
+
+    func fetchMetric(_ name: String) async -> Double? {
+        guard let url = URL(string: "\(baseURL)/metrics") else { return nil }
+        let req = URLRequest(url: url, timeoutInterval: 5)
+        do {
+            let (data, _) = try await URLSession.shared.data(for: req)
+            guard let text = String(data: data, encoding: .utf8) else { return nil }
+            for line in text.split(separator: "\n") {
+                if line.hasPrefix(name + " ") || line.hasPrefix(name + "{") {
+                    let parts = line.split(separator: " ")
+                    if parts.count >= 2, let v = Double(parts.last!) { return v }
+                }
+            }
+            return nil
+        } catch {
+            return nil
+        }
+    }
+
+    func probePort() async -> (open: Bool, pid: Int?, detail: String?) {
+        let lockPath = FileManager.default.homeDirectoryForCurrentUser
+            .appendingPathComponent("Library/Application Support/Splash/runtime/serve-\(port).lock")
+        if let data = try? Data(contentsOf: lockPath),
+           let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+           let pid = dict["pid"] as? Int {
+            let model = dict["model"] as? String ?? "?"
+            let running = kill(Int32(pid), 0) == 0
+            if running { return (true, pid, "a Splash server for \(model)") }
+        }
+        guard let url = URL(string: "\(baseURL)/health") else { return (false, nil, nil) }
+        let req = URLRequest(url: url, timeoutInterval: 2)
+        do {
+            let (_, resp) = try await URLSession.shared.data(for: req)
+            if let http = resp as? HTTPURLResponse, http.statusCode == 200 {
+                return (true, nil, "something responding on port \(port)")
+            }
+        } catch {}
+        return (false, nil, nil)
+    }
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Core/SplashServer.swift b/Sources/SplashGUI/Core/SplashServer.swift
new file mode 100644
index 0000000..da4b08c
--- /dev/null
+++ b/Sources/SplashGUI/Core/SplashServer.swift
@@ -0,0 +1,239 @@
+import Foundation
+
+final class LogRing {
+    private let lock = NSLock()
+    private var lines: [String] = []
+    private let cap = 800
+
+    func append(_ line: String) {
+        lock.lock()
+        lines.append(line)
+        if lines.count > cap { lines.removeFirst(lines.count - cap) }
+        lock.unlock()
+    }
+
+    func snapshot() -> [String] {
+        lock.lock()
+        defer { lock.unlock() }
+        return lines
+    }
+}
+
+final class SplashServer {
+    private var process: Process?
+    private var watchdog: Process?
+    private let log = LogRing()
+    private var killTimer: Timer?
+    private var logFile: FileHandle?
+
+    static let logFileURL = AppPaths.dataDir.appendingPathComponent("server.log")
+
+    func spawnWatchdog(serverPID: Int, appPID: Int) {
+        stopWatchdog()
+        let script = """
+        exec 2>>/tmp/splashgui-watchdog.log
+        SERVER=\(serverPID)
+        APP=\(appPID)
+        echo "$(date +%T) armed: server=$SERVER app=$APP"
+        while kill -0 $SERVER 2>/dev/null; do
+          if ! kill -0 $APP 2>/dev/null; then
+            echo "$(date +%T) app gone; TERM $SERVER"
+            kill -TERM $SERVER 2>/dev/null
+            i=0
+            while [ $i -lt 12 ]; do
+              kill -0 $SERVER 2>/dev/null || { echo "$(date +%T) exited"; exit 0; }
+              sleep 0.1
+              i=$((i+1))
+            done
+            echo "$(date +%T) still alive; KILL $SERVER"
+            kill -KILL $SERVER 2>/dev/null
+            exit 0
+          fi
+          sleep 1
+        done
+        echo "$(date +%T) server gone on its own"
+        """
+        let p = Process()
+        p.executableURL = URL(fileURLWithPath: "/bin/sh")
+        p.arguments = ["-c", script]
+        p.standardOutput = FileHandle.nullDevice
+        p.standardError = FileHandle.nullDevice
+        do {
+            try p.run()
+            watchdog = p
+        } catch {
+            log.append("- watchdog failed to spawn: \(error.localizedDescription)")
+        }
+    }
+
+    func stopWatchdog() {
+        if let w = watchdog, w.isRunning {
+            kill(w.processIdentifier, SIGKILL)
+        }
+        watchdog = nil
+    }
+
+    var logLines: [String] { log.snapshot() }
+
+    var childPID: Int? {
+        guard let p = process, p.isRunning else { return nil }
+        return Int(p.processIdentifier)
+    }
+
+    func note(_ line: String) {
+        log.append(line)
+    }
+
+    var isRunning: Bool { process?.isRunning ?? false }
+
+    struct LaunchTarget {
+        let executable: String
+        let prefixArgs: [String]
+    }
+
+    static func resolveLaunch() -> LaunchTarget? {
+        let py = EngineInstaller.pythonPath
+        if EngineInstaller.isInstalled {
+            return LaunchTarget(executable: py.path, prefixArgs: ["-u", EngineInstaller.launcherPath.path])
+        }
+        #if DEBUG
+        let brew = "/opt/homebrew/bin/splash"
+        if FileManager.default.isExecutableFile(atPath: brew) {
+            return LaunchTarget(executable: brew, prefixArgs: [])
+        }
+        #endif
+        return nil
+    }
+
+    func launch(config: RunConfig, revision: String?) throws {
+        guard process == nil else { return }
+        guard let target = Self.resolveLaunch() else {
+            throw ServerError.missingExecutable
+        }
+
+        let p = Process()
+        p.executableURL = URL(fileURLWithPath: target.executable)
+        p.arguments = target.prefixArgs + Self.buildArguments(for: config, revision: revision)
+        var env = ProcessInfo.processInfo.environment
+        env["PYTHONUNBUFFERED"] = "1"
+        env["TERM"] = "dumb"
+        p.environment = env
+
+        let outPipe = Pipe()
+        let errPipe = Pipe()
+        p.standardOutput = outPipe
+        p.standardError = errPipe
+
+        try? FileManager.default.createDirectory(
+            at: Self.logFileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
+        FileManager.default.createFile(atPath: Self.logFileURL.path, contents: nil)
+        logFile = FileHandle(forWritingAtPath: Self.logFileURL.path)
+        logFile?.write(Data("- splash serve launch \(Date())\n".utf8))
+
+        outPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
+            let data = handle.availableData
+            guard !data.isEmpty else { return }
+            self?.ingest(data)
+        }
+        errPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
+            let data = handle.availableData
+            guard !data.isEmpty else { return }
+            self?.ingest(data)
+        }
+
+        p.terminationHandler = { [weak self] proc in
+            self?.process = nil
+            self?.killTimer?.invalidate()
+            self?.killTimer = nil
+            self?.log.append("- exited (\(proc.terminationReason), status \(proc.terminationStatus))")
+            try? self?.logFile?.close()
+            self?.logFile = nil
+        }
+
+        try p.run()
+        process = p
+        log.append("- splash serve launched (pid \(p.processIdentifier))")
+    }
+
+    func stop() {
+        guard let p = process else { return }
+        killTimer?.invalidate()
+        killTimer = nil
+        let pid = p.processIdentifier
+        kill(pid, SIGTERM)
+        log.append("- SIGTERM sent (pid \(pid))")
+        let t = Timer(timeInterval: 8.0, repeats: false) { [weak self] _ in
+            guard let self else { return }
+            self.killTimer = nil
+            if self.process?.isRunning == true {
+                kill(pid, SIGKILL)
+                self.log.append("- SIGKILL fallback (pid \(pid))")
+            }
+        }
+        RunLoop.main.add(t, forMode: .common)
+        killTimer = t
+    }
+
+    func terminateHard() {
+        guard let p = process else { return }
+        kill(p.processIdentifier, SIGKILL)
+    }
+
+    private func ingest(_ data: Data) {
+        guard let text = String(data: data, encoding: .utf8) else { return }
+        for line in text.split(omittingEmptySubsequences: true, whereSeparator: { $0 == "\n" || $0 == "\r" }) {
+            log.append(String(line))
+            logFile?.write(Data((String(line) + "\n").utf8))
+        }
+    }
+
+    static func buildArguments(for config: RunConfig, revision: String? = nil) -> [String] {
+        var args = ["serve", "--model", config.modelID, "--port", String(config.port)]
+        // A catalog entry pins an exact HF commit, so the pull is reproducible and a later
+        // re-upload under the same name cannot change what this Mac loads.
+        if let revision, !revision.isEmpty { args += ["--revision", revision] }
+        if config.maxContext.lowercased() != "auto", !config.maxContext.isEmpty {
+            args += ["--max-context", config.maxContext]
+        }
+        if config.maxMemory.lowercased() != "auto", !config.maxMemory.isEmpty {
+            args += ["--max-memory", config.maxMemory]
+        }
+        args += ["--kv-format", config.kvFormat]
+        // The SSD tier's quota. "0" turns the tier off and has to be passed; "auto" leaves it
+        // to the engine (a quarter of the volume's free space, up to 32G) by leaving the flag
+        // out; a size like 10G sets it.
+        if !config.maxCacheDisk.isEmpty, config.maxCacheDisk.lowercased() != "auto" {
+            args += ["--max-cache-disk", config.maxCacheDisk]
+        }
+        // The tier's files only outlive the process with this. The engine refuses it without a
+        // quota, so it follows the storage cache setting.
+        if config.persistentCache, !config.maxCacheDisk.isEmpty, config.maxCacheDisk != "0" {
+            args += ["--persistent-cache"]
+        }
+        // How long the engine keeps its memory wired without a request. "auto" leaves the
+        // engine's own 10m, which costs a weight restore and a slower first prefill.
+        if !config.idleRelease.isEmpty, config.idleRelease.lowercased() != "auto" {
+            args += ["--idle-release", config.idleRelease]
+        }
+        if config.languageOnly { args += ["--language-only"] }
+        if !config.showWebUI { args += ["--no-webui"] }
+        if abs(config.decodeShare - 0.5) > 0.001 {
+            args += ["--decode-share", String(format: "%.2f", config.decodeShare)]
+        }
+        if let effort = config.defaultReasoningEffort, !effort.isEmpty {
+            args += ["--default-reasoning-effort", effort]
+        }
+        return args
+    }
+}
+
+enum ServerError: LocalizedError {
+    case missingExecutable
+
+    var errorDescription: String? {
+        switch self {
+        case .missingExecutable:
+            return "Splash engine is not installed yet. Use the Run tab to download it."
+        }
+    }
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Views/ProviderTab.swift b/Sources/SplashGUI/Views/ProviderTab.swift
new file mode 100644
index 0000000..2284d62
--- /dev/null
+++ b/Sources/SplashGUI/Views/ProviderTab.swift
@@ -0,0 +1,246 @@
+import SwiftUI
+import AppKit
+
+// Client configs are the app's only path to Splash for sampling: the app itself sends no
+// requests (Presets retired), and the engine has no serve-level sampling defaults (spec §7).
+struct ProviderTab: View {
+    @EnvironmentObject var model: AppModel
+    @State private var client: ProviderClient = .opencode
+
+    var body: some View {
+        SettingsPage {
+            SettingsSection("Client") {
+                HStack(spacing: 6) {
+                    Picker("Client", selection: $client) {
+                        ForEach(ProviderClient.allCases) { c in
+                            Text(c.rawValue).tag(c)
+                        }
+                    }
+                    .pickerStyle(.segmented)
+                    .labelsHidden()
+                    .fixedSize()
+                    .help(client.tooltip)
+                    Spacer()
+                }
+            }
+
+            // Sampling and the config preview sit side by side: sampling is a narrow fixed
+            // column, the config takes the rest. Stacked, the page ran past 720pt and forced a
+            // scroll on every reasonable window.
+            SettingsSection("Sampling & Config") {
+                HStack(alignment: .top, spacing: 20) {
+                    samplingColumn
+                        .frame(width: 300, alignment: .leading)
+                    configColumn
+                        .frame(maxWidth: .infinity, alignment: .leading)
+                }
+            }
+        }
+    }
+
+    private var samplingColumn: some View {
+        VStack(alignment: .leading, spacing: 10) {
+            HStack(spacing: 6) {
+                Button("Reset to model card") { model.resetModelProfile() }
+                    .buttonStyle(.link)
+                    .help(resetHelp)
+                Spacer()
+            }
+            SamplingFieldRow(label: "Temperature",
+                             value: clamped($model.config.sampling.temperature, 0...2),
+                             enabled: client.carries(.temperature),
+                             help: "Sampling temperature, 0 = greedy (deterministic). Every model card in the catalog recommends 1.0 for thinking mode, and the app starts there. Written into the client config; each model keeps its own value.")
+            SamplingFieldRow(label: "Top-p",
+                             value: clamped($model.config.sampling.topP, 0...1),
+                             enabled: client.carries(.topP),
+                             help: "Nucleus sampling cutoff: keep the smallest set of tokens whose probabilities sum to top-p. The model cards recommend 0.95.")
+            SamplingFieldRow(label: "Top-k",
+                             value: clamped(Binding(
+                                get: { Double(model.config.sampling.topK) },
+                                set: { model.config.sampling.topK = Int($0.rounded()) }), 1...100),
+                             digits: 0,
+                             enabled: client.carries(.topK),
+                             help: "Keep only the k most likely tokens before sampling. The model cards recommend 20; Splash honours larger values (verified to 200).")
+            SamplingFieldRow(label: "Presence penalty",
+                             value: clamped($model.config.sampling.presencePenalty, -2...2),
+                             enabled: client.carries(.presencePenalty),
+                             help: "Penalizes tokens that have already appeared, which curbs repetition. Splash accepts −2 to 2. The Qwen3.8 card asks for 1.5 with thinking off.")
+            SamplingFieldRow(label: "Min-p",
+                             value: clamped($model.config.sampling.minP, 0...1),
+                             enabled: client.carries(.minP),
+                             help: "Drops tokens whose probability is below this fraction of the most likely token's. Splash accepts 0 to 1. The Bonsai card asks for 0.05 in thinking mode.")
+            HStack(spacing: 10) {
+                Text("Max Output Tokens")
+                    .lineLimit(1)
+                    .frame(width: 112, alignment: .leading)
+                OptionalIntField(value: $model.config.sampling.maxTokens, placeholder: "unlimited")
+                    .disabled(!client.carries(.maxTokens))
+                    .opacity(client.carries(.maxTokens) ? 1 : 0.4)
+                Spacer()
+            }
+            .help("Cap on total generated tokens: reasoning AND visible output both count. The app sends no requests itself, and none of the supported client configs carries a per-request output cap: OpenCode reserves output space from the context limit in the config beside this column.")
+            HStack(spacing: 10) {
+                Text("Seed")
+                    .lineLimit(1)
+                    .frame(width: 112, alignment: .leading)
+                OptionalUInt64Field(value: $model.config.sampling.seed, placeholder: "random")
+                    .disabled(!client.carries(.seed))
+                    .opacity(client.carries(.seed) ? 1 : 0.4)
+                Spacer()
+            }
+            .help("Fixed seed reproduces outputs, reliably only when the request runs alone with identical cached prefixes; concurrency changes batching and can change results. Written into the OpenCode config's model options.")
+            if let off = cardOffLinkLabel {
+                HStack(spacing: 6) {
+                    Button(off) { model.applyCardOffSampling() }
+                        .buttonStyle(.link)
+                        .help(cardOffLinkHelp)
+                    Spacer()
+                }
+            }
+            HStack(alignment: .top, spacing: 6) {
+                Image(systemName: "lock.fill")
+                    .foregroundStyle(.secondary)
+                    .font(.caption)
+                Text("logit_bias isn't supported: Splash refuses any request that sets it")
+                    .font(.caption)
+                    .foregroundStyle(.secondary)
+                    .fixedSize(horizontal: false, vertical: true)
+                Spacer()
+            }
+            Text("The app sends no requests itself; these values reach Splash through the config beside them.")
+                .font(.caption)
+                .foregroundStyle(.secondary)
+                .fixedSize(horizontal: false, vertical: true)
+        }
+    }
+
+    private var configColumn: some View {
+        VStack(alignment: .leading, spacing: 10) {
+            Text(configCaption)
+                .font(.caption)
+                .foregroundStyle(.secondary)
+                .fixedSize(horizontal: false, vertical: true)
+            ScrollView {
+                Text(model.clientConfigText(for: client))
+                    .font(.system(size: 11, design: .monospaced))
+                    .textSelection(.enabled)
+                    .frame(maxWidth: .infinity, alignment: .leading)
+                    .padding(10)
+            }
+            .frame(height: 300)
+            .background(Color(nsColor: .controlBackgroundColor))
+            .clipShape(RoundedRectangle(cornerRadius: 8))
+            .overlay(
+                RoundedRectangle(cornerRadius: 8)
+                    .stroke(Color(nsColor: .separatorColor), lineWidth: 1)
+            )
+            HStack(spacing: 10) {
+                Button("Copy") {
+                    NSPasteboard.general.clearContents()
+                    NSPasteboard.general.setString(model.clientConfigText(for: client),
+                                                   forType: .string)
+                }
+                Button("Save…") { saveConfig() }
+                Spacer()
+            }
+            if client == .opencode {
+                Text("Paste the providers block into ~/.config/opencode/opencode.jsonc. It adds SplashGUI to /models and its efforts to /variants; it does not set your default model, small model, or agents.")
+                    .font(.caption)
+                    .foregroundStyle(.secondary)
+                    .fixedSize(horizontal: false, vertical: true)
+            }
+            if client == .zed {
+                Text("Zed keeps API keys out of settings.json: export SPLASH_API_KEY=local before launching Zed.")
+                    .font(.caption)
+                    .foregroundStyle(.secondary)
+                    .fixedSize(horizontal: false, vertical: true)
+            }
+            if client == .claudeCode {
+                Text("Merge the env block into ~/.claude/settings.json, and unset ANTHROPIC_API_KEY in the shell so Claude Code uses the local token.")
+                    .font(.caption)
+                    .foregroundStyle(.secondary)
+                    .fixedSize(horizontal: false, vertical: true)
+            }
+            if client == .codex {
+                Text("Add this to ~/.codex/config.toml, and export SPLASH_API_KEY=local before launching Codex.")
+                    .font(.caption)
+                    .foregroundStyle(.secondary)
+                    .fixedSize(horizontal: false, vertical: true)
+            }
+        }
+    }
+
+    private var configCaption: String {
+        var text = client.configCaption
+        if model.providerContextTokens.estimate {
+            text += " · the context limit is an estimate until the server runs"
+        }
+        return text
+    }
+
+    // Shown only when thinking is actually off AND the model is in the catalog, i.e. only where
+    // there is a card to quote.
+    private var cardOffLinkLabel: String? {
+        guard model.config.sampling.reasoningEffort == "none", let e = model.catalogEntry else { return nil }
+        return String(format: "card set for thinking off: %.2f / %.2f / %d · presence %.1f",
+                      e.cardOffTemperature, e.cardOffTopP, e.cardOffTopK, e.cardOffPresencePenalty)
+    }
+
+    private var cardOffLinkHelp: String {
+        guard let e = model.catalogEntry else { return "" }
+        return String(format: "Your model card recommends this set when thinking is off: temperature %.2f, top-p %.2f, top-k %d and presence penalty %.1f. Nothing changes until you click it.",
+                      e.cardOffTemperature, e.cardOffTopP, e.cardOffTopK, e.cardOffPresencePenalty)
+    }
+
+    private var resetHelp: String {
+        let serve = " Reasoning effort goes back to model default, Auto goes back on, and language-only resets with it. Other models keep their own settings."
+        if let e = model.catalogEntry {
+            return "Forget this model's saved settings and go back to its card: temperature \(e.cardTemperature), top-p \(e.cardTopP), top-k \(e.cardTopK), presence \(e.cardPresencePenalty), min-p \(e.cardMinP)." + serve
+        }
+        return "Forget this model's saved settings and go back to the shipped defaults: the sampling every card in the catalog publishes." + serve
+    }
+
+    private func clamped(_ value: Binding<Double>, _ range: ClosedRange<Double>, digits: Int = 2) -> Binding<Double> {
+        Binding(
+            get: { value.wrappedValue },
+            set: { value.wrappedValue = min(max($0, range.lowerBound), range.upperBound) }
+        )
+    }
+
+    private func saveConfig() {
+        let panel = NSSavePanel()
+        panel.nameFieldStringValue = client.saveName
+        panel.allowedContentTypes = client == .codex ? [.plainText] : [.json]
+        panel.begin { response in
+            guard response == .OK, let url = panel.url else { return }
+            try? model.clientConfigText(for: client).write(to: url, atomically: true, encoding: .utf8)
+        }
+    }
+}
+
+// One sampling row: label (112 pt, shared so the fields align) + numeric text field, greyed
+// when the selected client cannot carry the value.
+private struct SamplingFieldRow: View {
+    let label: String
+    @Binding var value: Double
+    var digits: Int = 2
+    let enabled: Bool
+    let help: String
+
+    var body: some View {
+        HStack(spacing: 10) {
+            Text(label)
+                .lineLimit(1)
+                .frame(width: 112, alignment: .leading)
+            TextField("", value: $value, format: .number.precision(.fractionLength(0...digits)))
+                .labelsHidden()
+                .textFieldStyle(.roundedBorder)
+                .frame(width: 90)
+                .monospacedDigit()
+                .disabled(!enabled)
+                .opacity(enabled ? 1 : 0.4)
+            Spacer()
+        }
+        .help(help)
+    }
+}
diff --git a/Sources/SplashGUI/Views/RootView.swift b/Sources/SplashGUI/Views/RootView.swift
new file mode 100644
index 0000000..ae5044b
--- /dev/null
+++ b/Sources/SplashGUI/Views/RootView.swift
@@ -0,0 +1,198 @@
+import SwiftUI
+
+@main
+struct SplashGUIApp: App {
+    @StateObject private var model = AppModel()
+
+    init() {
+        if CommandLine.arguments.contains("--install-engine") {
+            let args = CommandLine.arguments
+            var port = 8095
+            if let i = args.firstIndex(of: "--port"), i + 1 < args.count, let p = Int(args[i + 1]) {
+                port = p
+            }
+            exit(EngineInstaller.runCLI(port: port))
+        }
+        if CommandLine.arguments.contains("--auto-profile") {
+            exit(runAutoProfileProbe())
+        }
+        if CommandLine.arguments.contains("--check-model") {
+            setbuf(stdout, nil)
+            let cfg = ConfigStore.shared.load()
+            if let mismatch = MachineInfo.modelHashMismatch(cfg.run.modelID) {
+                print(mismatch)
+                exit(1)
+            }
+            print("\(cfg.run.modelID): hash check passed")
+            exit(0)
+        }
+    }
+
+    var body: some Scene {
+        WindowGroup("SplashGUI") {
+            RootView()
+                .environmentObject(model)
+        }
+        .defaultSize(width: 1240, height: 720)
+        .windowStyle(.hiddenTitleBar)
+        .windowToolbarStyle(.unifiedCompact)
+    }
+}
+
+struct RootView: View {
+    enum Section: String, CaseIterable, Identifiable {
+        case run = "Run"
+        case provider = "Provider"
+        case status = "Status"
+
+        var id: String { rawValue }
+
+        var icon: String {
+            switch self {
+            case .run: return "server.rack"
+            case .provider: return "powerplug"
+            case .status: return "gauge"
+            }
+        }
+    }
+
+    @EnvironmentObject var model: AppModel
+    @State private var section: Section = .run
+    @State private var columnVisibility: NavigationSplitViewVisibility = .all
+
+    var body: some View {
+        VStack(spacing: 0) {
+            titleBar
+            NavigationSplitView(columnVisibility: $columnVisibility) {
+                List(selection: $section) {
+                    ForEach(Section.allCases) { s in
+                        Label(s.rawValue, systemImage: s.icon).tag(s)
+                    }
+                }
+                .listStyle(.sidebar)
+                .navigationSplitViewColumnWidth(180)
+            } detail: {
+                Group {
+                    switch section {
+                    case .run: RunTab()
+                    case .provider: ProviderTab()
+                    case .status: StatusTab()
+                    }
+                }
+                .safeAreaInset(edge: .bottom) { phaseFooter }
+            }
+        }
+        .ignoresSafeArea(.container, edges: .top)
+        .frame(minWidth: 1040, minHeight: 620)
+    }
+
+    // The spec §2 fallback. A `.toolbar` sizes its items to content, so the context slot's
+    // `maxWidth: .infinity` never stretched: the row collapsed, the chips clipped and the
+    // endpoint wrapped over the field. This bar owns the hidden title-bar strip instead, with
+    // the traffic-light gutter reserved on the left and the rest of the width given to the
+    // controls. `WindowDragArea` keeps the strip draggable like a real title bar.
+    private var titleBar: some View {
+        HStack(spacing: 0) {
+            // Traffic lights + the sidebar toggle live in the strip over the 180pt sidebar;
+            // the server controls belong to the detail column, as they did under .toolbar.
+            Color.clear
+                .frame(width: 192)
+            ServerToolbarControls()
+                .frame(maxWidth: .infinity)
+        }
+        .padding(.trailing, 16)
+        .frame(height: 54)
+        .background(.bar)
+        .background(WindowDragArea())
+    }
+
+    private var phaseFooter: some View {
+        HStack(spacing: 8) {
+            Circle()
+                .fill(phaseColor)
+                .frame(width: 9, height: 9)
+            Text(phaseLabel)
+                .font(.footnote)
+                .foregroundStyle(.secondary)
+            Spacer()
+        }
+        .padding(.horizontal, 14)
+        .padding(.vertical, 8)
+        .background(.bar)
+    }
+
+    private var phaseColor: Color {
+        switch model.phase {
+        case .ready: return .green
+        case .starting: return .orange
+        case .stopping: return .orange
+        case .exited: return .red
+        case .stopped: return .secondary
+        }
+    }
+
+    private var phaseLabel: String {
+        switch model.phase {
+        case .stopped:
+            // A start failure stays on the footer until the next Start (spec §3).
+            if let err = model.lastError { return "Stopped: \(err)" }
+            return "Stopped"
+        case .starting: return "Starting…"
+        case .ready:
+            let m = model.effectiveModel ?? model.effectiveModelID
+            // The port the server is actually on, not the (possibly edited) toolbar field.
+            if let launched = model.launchedRunConfig {
+                return "Ready · \(m) on 127.0.0.1:" + String(launched.port)
+            }
+            return "Ready · \(m)"
+        case .stopping: return "Stopping…"
+        case .exited(let why): return "Exited: \(why)"
+        }
+    }
+}
+
+// Draggable backing for the custom title bar. Buttons and fields sit above it and keep their
+// own clicks; empty parts of the strip move the window, like the system title bar did.
+private struct WindowDragArea: NSViewRepresentable {
+    func makeNSView(context: Context) -> NSView { DragView() }
+    func updateNSView(_ nsView: NSView, context: Context) {}
+
+    private final class DragView: NSView {
+        override var mouseDownCanMoveWindow: Bool { true }
+    }
+}
+
+// Headless readout of what the Run tab would do for the configured model: the catalog pin, the
+// auto-config, and the exact launch arguments. Mirrors AppModel.currentAutoProfile +
+// RunConfig.effective + SplashServer.buildArguments so all of it is verifiable without the GUI.
+func runAutoProfileProbe() -> Int32 {
+    setbuf(stdout, nil)
+    let cfg = ConfigStore.shared.load()
+    let id = cfg.run.modelID
+    let entry = CatalogModel.catalog.first { $0.id == id }
+    let weights = entry?.weightsBytes ?? MachineInfo.cachedModelSize(id)
+    let profile = MachineInfo.autoProfile(modelID: id, languageOnly: cfg.run.languageOnly, weightsBytes: weights)
+    let eff = cfg.run.effective(using: profile)
+    print("model: \(id)  languageOnly: \(cfg.run.languageOnly)")
+    if let e = entry {
+        print("catalog: revision \(e.revision ?? "unpinned")  sha256 \(e.sha256.map { String($0.prefix(16)) + "…" } ?? "none")")
+        if let url = e.downloadURL { print("pull URL: \(url)") }
+        if let target = e.targetFile,
+           let installed = MachineInfo.installedDigest(for: id, key: "target/\(target)") {
+            print("installed target digest: \(installed.prefix(16))…  matches catalog: \(installed == e.sha256)")
+        } else if e.sha256 != nil {
+            print("installed target digest: none (not installed; the pull will be checked after)")
+        }
+    } else {
+        print("catalog: no entry (custom ID: unpinned, no hash check)")
+    }
+    print("physicalRAM: \(MachineInfo.gb(MachineInfo.physicalRAM))  availableRAM: \(MachineInfo.gb(MachineInfo.availableRAM))  metalCap: \(MachineInfo.gb(MachineInfo.metalMaxWorkingSet))")
+    print("weightsBytes: \(MachineInfo.gb(weights)) (\(weights ?? -1))")
+    if let p = profile {
+        print("autoProfile: \(p.contextTokens) tokens (\(p.contextTokens / 1024)K)  maxMemory: \(MachineInfo.gb(p.maxMemoryBytes))  kv: \(p.kvFormat)")
+    } else {
+        print("autoProfile: nil (insufficient headroom; Splash auto-sizes)")
+    }
+    print("args: splash " + SplashServer.buildArguments(for: eff, revision: entry?.revision).joined(separator: " "))
+    return 0
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Views/RunTab.swift b/Sources/SplashGUI/Views/RunTab.swift
new file mode 100644
index 0000000..54f0e5e
--- /dev/null
+++ b/Sources/SplashGUI/Views/RunTab.swift
@@ -0,0 +1,290 @@
+import SwiftUI
+
+struct RunTab: View {
+    @EnvironmentObject var model: AppModel
+
+    var body: some View {
+        // The server controls (Start/Stop, port, chips, context slot) live in the custom
+        // title bar — see ServerToolbarControls in StatusWidgets.swift + RootView.titleBar.
+        SettingsPage {
+            SettingsSection("Model & Server") {
+                HStack(alignment: .top, spacing: 28) {
+                    modelColumn
+                        .frame(maxWidth: .infinity, alignment: .leading)
+                    serverColumn
+                        .frame(maxWidth: .infinity, alignment: .leading)
+                }
+            }
+
+            SettingsSection("Engine") {
+                Toggle("Start server on app launch", isOn: $model.config.startOnLaunch)
+                    .help("Launch SplashGUI and it serves the saved model on the saved port, no click needed. A server already on the port is adopted instead of double-launched; engine updates (per the source setting below) install first. Quitting stops the server.")
+                HStack(spacing: 6) {
+                    Text("Engine source")
+                        .fixedSize(horizontal: true, vertical: false)
+                    Picker("Engine source", selection: $model.config.engineMode) {
+                        Text("This build's pin (\(EngineInstaller.defaultPin.version))").tag(EngineMode.pinned)
+                        Text("Always latest release").tag(EngineMode.latest)
+                        Text("Custom pin").tag(EngineMode.custom)
+                    }
+                    .labelsHidden()
+                    .fixedSize()
+                    Spacer()
+                }
+                .help("Pinned: always run the engine version this SplashGUI was released and tested with; bumping it takes a new app build. Latest: before every start, check GitHub's newest Splash release and install it (checksum verified against the release's own .sha256); if GitHub can't be reached the installed engine stays. Custom: install the exact build named by the three fields below.")
+                switch model.config.engineMode {
+                case .pinned:
+                    Toggle("Check for engine update on start", isOn: $model.config.checkEngineUpdate)
+                        .help("On: each start installs the engine this SplashGUI build pins if a different one is installed. Off: only download if no engine is installed yet.")
+                case .latest:
+                    Text("Checks GitHub on every start; a newer release downloads before the server launches. Unreachable GitHub keeps the installed engine.")
+                        .font(.caption2)
+                        .foregroundStyle(.secondary)
+                case .custom:
+                    // No disclosure wrapper: the picker already hides these unless Custom is
+                    // picked, so a second fold on top is just one more click.
+                    VStack(alignment: .leading, spacing: 10) {
+                        LabeledField("Engine version", $model.config.engineVersionOverride, width: 150)
+                        LabeledField("Engine URL", $model.config.engineURLOverride, width: 360)
+                        LabeledField("SHA-256", $model.config.engineSHA256Override, width: 360)
+                        Text("All three are required; they override the published pin entirely.")
+                            .font(.caption2)
+                            .foregroundStyle(.secondary)
+                    }
+                }
+                HStack {
+                    Text("Installed engine")
+                    Spacer()
+                    Text(model.engineVersion ?? "not installed")
+                        .font(.system(.caption, design: .monospaced))
+                        .foregroundStyle(.secondary)
+                }
+            }
+        }
+        .safeAreaInset(edge: .bottom) {
+            logPane
+        }
+    }
+
+    // The two columns are separate computed properties: inline they push the GridRow's
+    // result-builder tree past the type-checker's complexity limit.
+
+    private var modelColumn: some View {
+        VStack(alignment: .leading, spacing: 10) {
+            HStack(spacing: 6) {
+                Text("Model")
+                    .fixedSize(horizontal: true, vertical: false)
+                Picker("Model", selection: model.modelPickerSelection) {
+                    ForEach(CatalogModel.catalog) { m in
+                        HStack {
+                            Text(m.label)
+                            Spacer()
+                            Text(m.id == "custom" ? "" : m.id)
+                                .font(.caption)
+                                .foregroundStyle(.secondary)
+                        }.tag(m.id)
+                    }
+                }
+                .labelsHidden()
+            }
+            .help("Hub ID, owner/repo[:variant], shown so you know exactly whose upload you're pulling. The DFlash2 draft model pairs automatically. First start downloads weights and prepares them; later starts map from disk. Each model keeps its own sampling and context settings, saved under its full ID including the :variant; switching models swaps them in, and a model you have not tuned starts on its card's sampling.")
+            if model.catalogEntry == nil {
+                HStack(spacing: 6) {
+                    Text(model.config.run.modelID.isEmpty
+                        ? "no model ID set; pick Custom… and type owner/repo[:variant]"
+                        : model.config.run.modelID)
+                        .font(.system(.caption, design: .monospaced))
+                        .foregroundStyle(.secondary)
+                    Spacer()
+                }
+                TextField("owner/repo[:variant]", text: model.customIDBinding)
+                    .textFieldStyle(.roundedBorder)
+                    .font(.system(.body, design: .monospaced))
+            }
+            if let entry = model.catalogEntry {
+                HStack(spacing: 6) {
+                    Image(systemName: entry.onDisk ? "checkmark.circle.fill" : "arrow.down.circle")
+                        .foregroundStyle(entry.onDisk ? Color.green : Color.orange)
+                    Text(entry.onDisk
+                         ? "installed, maps from disk"
+                         : "not installed, first start pulls it from Hugging Face")
+                        .font(.caption)
+                        .foregroundStyle(.secondary)
+                    Text("· \(entry.note)").font(.caption).foregroundStyle(.secondary)
+                    Spacer()
+                }
+                .help((entry.downloadURL.map { "pulls, pinned to commit \($0). " } ?? "")
+                      + "serve --revision pins the download to this exact commit, so a later re-upload under the same file name cannot change what loads. The catalog also carries its sha256; the app checks it against the digest Splash records before starting.")
+                if !entry.fitsThisMac {
+                    Label("too large for this Mac's memory, expected to fail",
+                          systemImage: "exclamationmark.triangle")
+                        .font(.caption)
+                        .foregroundStyle(.red)
+                }
+            }
+            Toggle(isOn: $model.config.run.auto) {
+                HStack(spacing: 6) {
+                    Text("Auto")
+                    if model.catalogEntry == nil && model.config.run.auto {
+                        Text("custom models fill auto settings once Splash launches")
+                            .font(.caption)
+                            .foregroundStyle(.secondary)
+                    }
+                }
+            }
+            .help("Size context, memory and KV precision from this Mac's GPU memory ceiling and the selected model's weights, and let the engine size the SSD cache. The greyed fields show what Auto picked; turn it off to use your own values.")
+            LabeledField("Max context", autoAwareText($model.config.run.maxContext, model.autoContextText), width: 120)
+                .disabled(model.config.run.auto)
+                .help("Context limit: a number with optional K, e.g. 100K or 131072. Lower frees KV memory. With Auto on, the app sizes it from this Mac's GPU memory and the model's weights, up to 262144 tokens.")
+            LabeledField("Max memory", autoAwareText($model.config.run.maxMemory, model.autoMemoryText), width: 120)
+                .disabled(model.config.run.auto)
+                .help("Cap on Metal allocations, e.g. 28G. Lower it to leave room for other GPU work. With Auto on, the app uses this Mac's GPU memory ceiling: \(MachineInfo.gb(MachineInfo.metalMaxWorkingSet)) here, of \(MachineInfo.gb(MachineInfo.physicalRAM)) physical RAM (recommendedMaxWorkingSetSize).")
+            LabeledField("SSD cache", autoAwareText($model.config.run.maxCacheDisk, model.autoCacheText), width: 120)
+                .disabled(model.config.run.auto)
+                .help("SSD cache for KV pages and GDN states, e.g. 16G; 0 turns it off. With Auto on, the engine sizes it: a quarter of the volume's free space, up to 32G. A 64K context costs 2.0 GiB of pages here plus a 152 MiB state. The cache does not raise the context limit. Free disk on this volume: \(MachineInfo.gb(MachineInfo.freeDisk)).")
+            Toggle("Keep SSD cache across restarts", isOn: $model.config.run.persistentCache)
+                .help("Write the SSD tier to ~/Library/Caches/Splash/prefix-cache instead of a temporary directory, so a project you come back to restores its prefix rather than prefilling it again. Needs an SSD cache above 0.")
+            HStack(spacing: 6) {
+                Text("KV cache")
+                    .lineLimit(1)
+                    .fixedSize(horizontal: true, vertical: false)
+                Picker("KV cache", selection: kvSelection) {
+                    Text("BF16").tag("bf16")
+                    Text("INT8").tag("int8")
+                }
+                .pickerStyle(.segmented)
+                .labelsHidden()
+                .fixedSize()
+                .disabled(model.config.run.auto)
+                .help("KV cache precision. BF16 is fastest at long contexts and exact; INT8 halves KV memory for RAM-constrained machines, but slows decode at depth and can cost accuracy (4-bit KV exists in Splash but is not offered here). With Auto on, the app picks BF16 and only drops to INT8 when BF16 would leave under a 32K window. Restart to apply.")
+            }
+        }
+    }
+
+    private var serverColumn: some View {
+        VStack(alignment: .leading, spacing: 10) {
+            LabeledField("Idle release", $model.config.run.idleRelease, width: 120)
+                .help("How long the engine keeps its memory wired without a request: a duration such as 30m or 2h, or off. The engine's own default is 10m, after which the next request pays a weight restore and a slower first prefill. off keeps the weights resident until POST /v1/memory/release.")
+            SliderNumberField(
+                label: "Decode share",
+                value: $model.config.run.decodeShare,
+                range: 0...1, step: 0.05, digits: 2
+            )
+            .help("When a long prompt prefills while other requests decode, each prefill slice owes this fraction of its own duration to the decoding lanes. 0.5 default; higher keeps in-flight outputs fast at the cost of the new prompt's TTFT; 0 alternates one command each. Only matters under concurrency.")
+            HStack(spacing: 6) {
+                Text("Default reasoning effort")
+                    .lineLimit(1)
+                    .fixedSize(horizontal: true, vertical: false)
+                Picker("Default reasoning effort", selection: model.reasoningEffortBinding) {
+                    Text("model default").tag(String?.none)
+                    ForEach(model.supportedEfforts, id: \.self) { e in
+                        Text(e).tag(String?.some(e))
+                    }
+                }
+                .labelsHidden()
+                .fixedSize()
+                .help("The effort Splash uses for requests that don't set one, such as the web chat on Default or OpenCode with no variant picked. Clients that ask for an effort get what they ask for, and Anthropic-style clients like Claude Code always say. Restart to apply.")
+                Spacer()
+            }
+            Toggle("Language only (skip vision)", isOn: $model.config.run.languageOnly)
+                .help("Serve text only: skips loading the vision projector, saving memory. Restart to apply.")
+            HStack(spacing: 6) {
+                Toggle("Built-in web chat page", isOn: $model.config.run.showWebUI)
+                    .help("Serve Splash's built-in chat page at the server URL.")
+                // Shipped bug fixed: the button used to show whenever the server was ready,
+                // even with the page off (--no-webui) — where it opened a URL that isn't served.
+                if model.config.run.showWebUI, model.phase == .ready {
+                    Button("Open built-in chat") { openWebChat() }
+                }
+                Spacer()
+            }
+        }
+    }
+
+    private func openWebChat() {
+        if let url = URL(string: "http://127.0.0.1:" + String(model.config.run.port)) {
+            NSWorkspace.shared.open(url)
+        }
+    }
+
+    // While Auto is on the field shows Auto's value and swallows edits (it is disabled — this
+    // binding just keeps the typed value untouched underneath).
+    private func autoAwareText(_ typed: Binding<String>, _ autoValue: String) -> Binding<String> {
+        Binding(
+            get: { model.config.run.auto ? autoValue : typed.wrappedValue },
+            set: { if !model.config.run.auto { typed.wrappedValue = $0 } }
+        )
+    }
+
+    // The KV picker follows the same rule: Auto's pick while Auto is on, the typed value below.
+    private var kvSelection: Binding<String> {
+        Binding(
+            get: { model.config.run.auto ? model.autoKVFormat : model.config.run.kvFormat },
+            set: { if !model.config.run.auto { model.config.run.kvFormat = $0 } }
+        )
+    }
+
+    @ViewBuilder
+    private var logPane: some View {
+        VStack(spacing: 0) {
+            Divider()
+            ZStack(alignment: .topTrailing) {
+                ScrollViewReader { proxy in
+                    ScrollView {
+                        Text(model.logTail.isEmpty
+                             ? "no log output yet"
+                             : model.logTail.joined(separator: "\n"))
+                            .font(.system(size: 11, design: .monospaced))
+                            .foregroundStyle(model.logTail.isEmpty ? .tertiary : .secondary)
+                            .textSelection(.enabled)
+                            .frame(maxWidth: .infinity, alignment: .leading)
+                            .padding(10)
+                            .id("logEnd")
+                    }
+                    .frame(height: 170)
+                    .onChange(of: model.logTail.count) {
+                        proxy.scrollTo("logEnd", anchor: .bottom)
+                    }
+                }
+                if !model.logTail.isEmpty {
+                    Button {
+                        let text = model.logTail.joined(separator: "\n")
+                        NSPasteboard.general.clearContents()
+                        NSPasteboard.general.setString(text, forType: .string)
+                    } label: {
+                        Image(systemName: "doc.on.doc")
+                    }
+                    .buttonStyle(.borderless)
+                    .help("Copy the log to the clipboard")
+                    .padding(6)
+                }
+            }
+        }
+        .background(.bar)
+    }
+}
+
+struct LabeledField: View {
+    let title: String
+    @Binding var text: String
+    var width: CGFloat
+
+    init(_ title: String, _ text: Binding<String>, width: CGFloat) {
+        self.title = title
+        self._text = text
+        self.width = width
+    }
+
+    var body: some View {
+        HStack(spacing: 6) {
+            Text(title)
+                .lineLimit(1)
+                .fixedSize(horizontal: true, vertical: false)
+            TextField(title, text: $text)
+                .labelsHidden()
+                .textFieldStyle(.roundedBorder)
+                .frame(width: width)
+                .font(.system(.body, design: .monospaced))
+        }
+    }
+}
diff --git a/Sources/SplashGUI/Views/SettingsLayout.swift b/Sources/SplashGUI/Views/SettingsLayout.swift
new file mode 100644
index 0000000..91fd6e0
--- /dev/null
+++ b/Sources/SplashGUI/Views/SettingsLayout.swift
@@ -0,0 +1,53 @@
+import SwiftUI
+
+// macOS's grouped FormStyle centers its rows in a fixed ~704pt column, leaving large dead
+// margins on a wide window. These keep the grouped-form look (header + rounded card) while
+// letting the cards fill the detail column.
+struct SettingsPage<Content: View>: View {
+    private let content: Content
+
+    init(@ViewBuilder content: () -> Content) {
+        self.content = content()
+    }
+
+    var body: some View {
+        ScrollView {
+            VStack(alignment: .leading, spacing: 20) {
+                content
+            }
+            .frame(maxWidth: .infinity, alignment: .leading)
+            .padding(16)
+        }
+    }
+}
+
+struct SettingsSection<Content: View>: View {
+    private let title: String
+    private let content: Content
+
+    init(_ title: String, @ViewBuilder content: () -> Content) {
+        self.title = title
+        self.content = content()
+    }
+
+    var body: some View {
+        VStack(alignment: .leading, spacing: 8) {
+            Text(title)
+                .font(.subheadline)
+                .fontWeight(.medium)
+                .foregroundStyle(.secondary)
+                .padding(.leading, 4)
+            VStack(alignment: .leading, spacing: 12) {
+                content
+            }
+            .frame(maxWidth: .infinity, alignment: .leading)
+            .padding(16)
+            .background(Color(nsColor: .controlBackgroundColor))
+            .clipShape(RoundedRectangle(cornerRadius: 10))
+            .overlay(
+                RoundedRectangle(cornerRadius: 10)
+                    .stroke(Color(nsColor: .separatorColor), lineWidth: 1)
+            )
+        }
+    }
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Views/StatusTab.swift b/Sources/SplashGUI/Views/StatusTab.swift
new file mode 100644
index 0000000..5102dbd
--- /dev/null
+++ b/Sources/SplashGUI/Views/StatusTab.swift
@@ -0,0 +1,219 @@
+import SwiftUI
+
+struct StatusTab: View {
+    @EnvironmentObject var model: AppModel
+
+    var body: some View {
+        if model.phase == .ready, let snap = model.status {
+            ScrollView {
+                VStack(alignment: .leading, spacing: 16) {
+                    memorySection
+                    HStack(alignment: .top, spacing: 10) {
+                        Card("TTFT", msText(model.lastRequestTTFT), note: "server p50",
+                             help: "Time to first token: how long a request waits before its first token arrives. The median across recent requests, as the server reports it. Long prompts raise it; cached prefixes lower it.")
+                        Card("Prefill tok/s", tpsText(model.prefillGaugeValue),
+                             note: maximaText(model.prefillMax5m, model.prefillMaxSession),
+                             help: "Prompt tokens read per second right now, with the highest rate in the last 5 minutes and in this session.")
+                        Card("Decode tok/s", tpsText(model.decodeGaugeValue),
+                             note: maximaText(model.decodeMax5m, model.decodeMaxSession),
+                             help: "Tokens generated per second right now, with the highest rate in the last 5 minutes and in this session.")
+                        Card("Draft acceptance", pctText(snapOfDraft()),
+                             help: "Share of the draft model's guessed tokens that the main model accepted. Higher means faster generation; it drops on unpredictable text.")
+                        Card("Cache hit rate", pctText(snap.cacheHitRate), note: "lookups \(snap.cacheLookups ?? 0)",
+                             help: "Share of prompt lookups that found a cached prefix, so the server skipped reading that part of the prompt again.")
+                    }
+                    chartBlock
+
+                    LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: 4),
+                              spacing: 10) {
+                        Card("TTFT p95", msText(snap.ttftP95),
+                             help: "Time to first token for the slowest 5% of recent requests.")
+                        Card("ITL p50", msText(snap.itlP50),
+                             help: "Inter-token latency: the typical gap between generated tokens. Lower is faster.")
+                        Card("ITL p95", msText(snap.itlP95),
+                             help: "Inter-token latency for the slowest 5% of gaps between generated tokens.")
+                        Card("Reused tokens", compactTokens(snap.reusedTokens),
+                             help: "Prompt tokens served from the prefix cache instead of being read again, since the server started. Exact count: \(snap.reusedTokens.map { $0.formatted(.number) } ?? "–").")
+                        Card("GDN state", bytesText(snap.stateBytes), note: "\(snap.stateEntries ?? 0) entries",
+                             help: "Memory held by cached GDN states, the running state of the model's linear-attention layers, and how many are kept.")
+                        Card("Scheduler", schedulerTotal(snap), note: schedulerText(snap),
+                             help: "Total requests in the scheduler: the breakdown below counts those waiting, reading their prompt and generating right now.")
+                        Card("Free disk", MachineInfo.gb(MachineInfo.freeDisk),
+                             note: "volume hosting the SSD cache tier",
+                             help: "Free space on the volume that holds the SSD cache.")
+                        Card("Engine", model.engineVersion, note: "app-managed",
+                             help: "The Splash engine version the app installed and manages, at \(EngineInstaller.currentLink.path).")
+                    }
+
+                    Text("Prefix cache is in RAM, and the SSD tier keeps its KV pages and GDN states on disk, including across restarts when “Keep SSD cache across restarts” is on. Restarting the server clears the RAM part; the disk part survives it.")
+                        .font(.caption)
+                        .foregroundStyle(.secondary)
+                }
+                .padding(16)
+            }
+        } else {
+            VStack(spacing: 10) {
+                Image(systemName: "gauge")
+                    .font(.system(size: 34))
+                    .foregroundStyle(.secondary)
+                Text(statusText)
+                    .foregroundStyle(.secondary)
+                if let v = model.engineVersion {
+                    Text("engine \(v) installed at \(EngineInstaller.currentLink.path)")
+                        .font(.caption)
+                        .foregroundStyle(.secondary)
+                }
+            }
+        }
+    }
+
+    @ViewBuilder
+    private var memorySection: some View {
+        if let physical = physicalRAM {
+            MemoryBar(
+                modelBytes: model.modelFootprint,
+                otherBytes: otherUsed,
+                freeBytes: availableRAM,
+                totalBytes: physical
+            )
+        }
+    }
+
+    @ViewBuilder
+    private var chartBlock: some View {
+        TimeSeriesChart(samples: model.history, defs: [
+            .init(name: "Draft accept", color: .green,
+                  extract: { $0.draftAcceptance }, format: { String(format: "%.0f%%", $0 * 100) }),
+            .init(name: "Cache hit", color: .mint,
+                  extract: { $0.cacheHitRate }, format: { String(format: "%.0f%%", $0 * 100) }),
+            .init(name: "Prefill tok/s", color: .orange,
+                  extract: { $0.prefillTps }, format: { String(format: "%.0f", $0) }),
+            .init(name: "Decode tok/s", color: .blue,
+                  extract: { $0.decodeTps }, format: { String(format: "%.0f", $0) })
+        ])
+    }
+
+    private func maximaText(_ fiveMin: Double?, _ session: Double?) -> String {
+        let f = fiveMin.map { String(format: "%.0f", $0) } ?? "–"
+        let s = session.map { String(format: "%.0f", $0) } ?? "–"
+        return "peak \(f) (5m) · \(s) (session)"
+    }
+
+    // "3.77M" style — the grid card has no room for grouped seven-digit counts.
+    private func compactTokens(_ n: Int?) -> String? {
+        guard let n else { return nil }
+        if n >= 1_000_000 { return String(format: "%.2fM", Double(n) / 1_000_000) }
+        if n >= 1_000 { return String(format: "%.1fK", Double(n) / 1_000) }
+        return String(n)
+    }
+
+    private var physicalRAM: Int? {
+        let v = MachineInfo.physicalRAM
+        return v > 0 ? v : nil
+    }
+
+    private var availableRAM: Int? {
+        MachineInfo.availableRAM
+    }
+
+    private var otherUsed: Int? {
+        guard let physical = physicalRAM, let avail = availableRAM else { return nil }
+        let used = max(0, physical - avail)
+        let model = model.modelFootprint ?? 0
+        return max(0, used - model)
+    }
+
+    private func snapOfDraft() -> Double? {
+        model.draftAcceptance ?? model.history.last?.draftAcceptance
+    }
+
+    private var statusText: String {
+        switch model.phase {
+        case .starting:
+            return "Starting: status appears once the model has loaded"
+        case .stopping:
+            return "Stopping…"
+        case .ready:
+            return "waiting for /status…"
+        default:
+            return "Server not running; press Start in the toolbar"
+        }
+    }
+
+    private func msText(_ v: Double?) -> String? {
+        v.map { String(format: "%.0f ms", $0) }
+    }
+
+    private func tpsText(_ v: Double?) -> String? {
+        v.map { String(format: "%.1f", $0) }
+    }
+
+    private func pctText(_ v: Double?) -> String? {
+        v.map { String(format: "%.1f%%", $0 * 100) }
+    }
+
+    private func bytesText(_ v: Int?) -> String {
+        guard let v else { return "–" }
+        let gb = Double(v) / 1_073_741_824
+        if gb >= 1 { return String(format: "%.2f GB", gb) }
+        return String(format: "%.0f MB", Double(v) / 1_048_576)
+    }
+
+    // The card's big slot is the total; the breakdown lives in the note line like every other
+    // card. The three-word form used to sit in the value slot and wrapped to two lines, which
+    // made this the tallest card in the grid.
+    private func schedulerTotal(_ snap: StatusSnapshot) -> String {
+        "\((snap.queued ?? 0) + (snap.prefilling ?? 0) + (snap.decoding ?? 0))"
+    }
+
+    private func schedulerText(_ snap: StatusSnapshot) -> String {
+        "\(snap.queued ?? 0) queued · \(snap.prefilling ?? 0) prefilling · \(snap.decoding ?? 0) generating"
+    }
+}
+
+struct Card: View {
+    let title: String
+    let value: String?
+    var note: String = ""
+    var help: String = ""
+
+    init(_ title: String, _ value: String?, note: String = "", help: String = "") {
+        self.title = title
+        self.value = value
+        self.note = note
+        self.help = help
+    }
+
+    var body: some View {
+        VStack(alignment: .leading, spacing: 4) {
+            Text(title).font(.caption).foregroundStyle(.secondary)
+            Text(value ?? "–")
+                .font(.system(.title3, design: .monospaced))
+                .fontWeight(.medium)
+            // Reserve two note lines on every card so a card without a note (Draft acceptance)
+            // is the same height as its neighbours, and a wrapping note cannot stretch one card.
+            Text(note.isEmpty ? " " : note)
+                .font(.caption2)
+                .foregroundStyle(.secondary)
+                .lineLimit(2, reservesSpace: true)
+        }
+        .frame(maxWidth: .infinity, alignment: .leading)
+        .padding(12)
+        .background(Color(nsColor: .controlBackgroundColor))
+        .cornerRadius(8)
+        .overlay(
+            RoundedRectangle(cornerRadius: 8)
+                .stroke(Color(nsColor: .separatorColor), lineWidth: 1)
+        )
+        .modifier(HelpIfNotEmpty(help))
+    }
+}
+
+// .help has no optional overload; an empty tooltip must attach nothing.
+private struct HelpIfNotEmpty: ViewModifier {
+    let text: String
+    init(_ text: String) { self.text = text }
+    @ViewBuilder func body(content: Content) -> some View {
+        if text.isEmpty { content } else { content.help(text) }
+    }
+}
\ No newline at end of file
diff --git a/Sources/SplashGUI/Views/StatusWidgets.swift b/Sources/SplashGUI/Views/StatusWidgets.swift
new file mode 100644
index 0000000..25d3bcc
--- /dev/null
+++ b/Sources/SplashGUI/Views/StatusWidgets.swift
@@ -0,0 +1,438 @@
+import SwiftUI
+
+struct StageChipsRow: View {
+    @EnvironmentObject var model: AppModel
+    var flexibleWidth = true  // trailing Spacer fills the container; off inside toolbars
+
+    var body: some View {
+        HStack(spacing: 8) {
+            chip("prefill", active: model.currentStage == .prefill)
+            chip("generation", active: model.currentStage == .decode)
+            if flexibleWidth { Spacer() }
+        }
+        .help("Live request stage from the 2s status poll. Green = active right now: prefill while a prompt is read, generation while tokens come out.")
+    }
+
+    private func chip(_ label: String, active: Bool) -> some View {
+        HStack(spacing: 6) {
+            Circle()
+                .fill(active ? Color.green : Color.secondary.opacity(0.4))
+                .frame(width: 7, height: 7)
+            Text(label)
+                .font(.callout)
+                .fontWeight(active ? .semibold : .regular)
+        }
+        .padding(.horizontal, 12)
+        .padding(.vertical, 6)
+        // Green lives on the dot and the chip outline only. An un-clipped tinted fill let the
+        // green wash past the rounded border into the title-bar material.
+        .background(Color(nsColor: .controlBackgroundColor))
+        .clipShape(RoundedRectangle(cornerRadius: 7))
+        .overlay(
+            RoundedRectangle(cornerRadius: 7)
+                .stroke(active ? Color.green : Color(nsColor: .separatorColor), lineWidth: 1)
+        )
+    }
+}
+
+// The server control row lives in the window toolbar (title-bar strip), so it works from every
+// tab. Was the Run-tab mode bar until 2026-10-15; the blank hidden-titlebar strip above it made
+// the old placement read as double-height chrome.
+struct ServerToolbarControls: View {
+    @EnvironmentObject var model: AppModel
+
+    var body: some View {
+        HStack(spacing: 12) {
+            contextSlot
+                .frame(minWidth: 140, maxWidth: .infinity, alignment: .leading)
+            StageChipsRow(flexibleWidth: false)
+                .fixedSize(horizontal: true, vertical: false)
+            HStack(spacing: 6) {
+                Text("http://127.0.0.1:")
+                    .font(.system(.caption, design: .monospaced))
+                    .help("The endpoint other services connect to. OpenAI-compatible API under /v1, Anthropic under /v1/messages.")
+                // String ports: Text interpolation of an Int applies locale number formatting,
+                // which grouped the port as "8,095".
+                TextField("", value: $model.config.run.port, format: .number.grouping(.never))
+                    .labelsHidden()
+                    .textFieldStyle(.roundedBorder)
+                    .font(.system(.body, design: .monospaced))
+                    .frame(width: 52)
+                    .foregroundStyle(model.portValid ? Color.primary : Color.red)
+                    .help("HTTP port of the server. Splash's own default is 8000; the app uses 8095. Change if something else owns the port. Editable while running; an edit is a pending change for Apply & Restart.")
+                Button {
+                    NSPasteboard.general.clearContents()
+                    NSPasteboard.general.setString(endpoint, forType: .string)
+                } label: {
+                    Image(systemName: "doc.on.doc")
+                }
+                .buttonStyle(.borderless)
+                .help("Copy the endpoint URL")
+            }
+            .fixedSize(horizontal: true, vertical: false)
+            Button("Apply & Restart") { model.restart() }
+                .keyboardShortcut("r", modifiers: [.command, .shift])
+                .disabled(!(model.phase == .ready && model.hasPendingChanges))
+                .help("Stop the server and start it again with the edited settings. Model, context, memory, KV and port changes always need this.")
+                .fixedSize(horizontal: true, vertical: false)
+            if model.phase == .ready || model.phase == .starting {
+                Button("Stop", role: .destructive) { model.stop() }
+                    .fixedSize(horizontal: true, vertical: false)
+            } else {
+                Button(model.engineVersion == nil ? "Download & start" : "Start") { model.start() }
+                    .disabled(!model.canStart || !model.portValid || model.isInstallingEngine)
+                    .fixedSize(horizontal: true, vertical: false)
+            }
+        }
+    }
+
+    private var endpoint: String { "http://127.0.0.1:" + String(model.config.run.port) }
+
+    // One slot, switched in place: the engine install / model load progress while getting to
+    // ready, the KV context gauge once ready, and the plain server state with an empty gauge
+    // while not running — a bar captioned "Context" would imply a context to spend.
+    @ViewBuilder
+    private var contextSlot: some View {
+        if model.isInstallingEngine {
+            VStack(alignment: .leading, spacing: 3) {
+                Text(engineStepLabel)
+                    .font(.caption)
+                    .lineLimit(1)
+                    .foregroundStyle(.secondary)
+                ProgressView(value: min(1, max(0.02, model.engineProgress)))
+            }
+            .help("First launch downloads the Splash engine (~71 MB). Later launches reuse it.")
+        } else if model.phase == .starting {
+            VStack(alignment: .leading, spacing: 3) {
+                Text(model.loadStage.isEmpty ? "starting…" : model.loadStage)
+                    .font(.caption)
+                    .lineLimit(1)
+                    .foregroundStyle(.secondary)
+                ProgressView(value: model.loadProgress ?? 0.05)
+            }
+            .help("Covers the model download (if needed) and engine loading")
+        } else if model.phase == .ready, let snap = model.status, let max = snap.maxContextTokens, max > 0 {
+            let used = snap.contextUsedFraction ?? 0
+            VStack(alignment: .leading, spacing: 3) {
+                HStack(spacing: 6) {
+                    Text("Context")
+                        .font(.caption)
+                        .foregroundStyle(.secondary)
+                    Spacer()
+                    Text("\(snap.contextUsedTokens ?? 0)/\(max / 1024)K")
+                        .font(.caption)
+                        .monospacedDigit()
+                        .foregroundStyle(.secondary)
+                }
+                ProgressView(value: used)
+                    .progressViewStyle(.linear)
+                    .tint(used > 0.9 ? .orange : .accentColor)
+            }
+            .help("Tokens held by active requests' KV out of the granted window (server pool gauge, updated on the 2s status poll). While the server starts, this shows the download and load progress instead.")
+        } else {
+            VStack(alignment: .leading, spacing: 3) {
+                Text(slotStatusLabel)
+                    .font(.caption)
+                    .lineLimit(1)
+                    .foregroundStyle(.secondary)
+                ProgressView(value: 0)
+                    .progressViewStyle(.linear)
+            }
+            .help("The context gauge appears once the server is up; until then this is the server state.")
+        }
+    }
+
+    // The context slot's caption while there is no context to gauge. .starting and the engine
+    // install have their own progress branches above.
+    private var slotStatusLabel: String {
+        switch model.phase {
+        case .ready: return "Waiting for status…"   // up, first poll not in yet
+        case .stopping: return "Stopping…"
+        case .exited: return "Exited"
+        default: return "Stopped"
+        }
+    }
+
+    private var engineStepLabel: String {
+        let v = model.engineResolvedVersion.map { " \($0)" } ?? ""
+        switch model.engineStep {
+        case .checking: return "Checking for the engine…"
+        case .downloading: return "Downloading Splash\(v): \(Int(model.engineProgress * 100))%"
+        case .verifying: return "Verifying the download…"
+        case .extracting: return "Installing the engine…"
+        case .validating: return "Checking the engine…"
+        case .switching: return "Activating the engine…"
+        default: return "Installing the engine…"
+        }
+    }
+}
+
+struct SliderNumberField: View {
+    let label: String
+    @Binding var value: Double
+    let range: ClosedRange<Double>
+    var step: Double = 0.05
+    var digits: Int = 2
+    var trailing: String? = nil
+    var labelWidth: CGFloat? = nil
+
+    var body: some View {
+        HStack(spacing: 10) {
+            Text(label)
+                .lineLimit(1)
+                .frame(width: labelWidth, alignment: .leading)
+            Slider(value: clampedBinding, in: range)
+            TextField("", value: clampedBinding, format: .number.precision(.fractionLength(digits)))
+                .labelsHidden()
+                .textFieldStyle(.roundedBorder)
+                .frame(width: 70)
+                .monospacedDigit()
+            if let trailing {
+                Text(trailing)
+                    .font(.caption)
+                    .foregroundStyle(.orange)
+                    .fixedSize(horizontal: true, vertical: false)
+            }
+        }
+        .help(helpText)
+    }
+
+    var helpText: String {
+        "Drag or type a value; it snaps to \(step) and clamps to \(range.lowerBound)–\(range.upperBound)."
+    }
+
+    private var clampedBinding: Binding<Double> {
+        Binding(
+            get: { value },
+            set: { value = Self.snap($0, range: range, step: step) }
+        )
+    }
+
+    static func snap(_ v: Double, range: ClosedRange<Double>, step: Double) -> Double {
+        let clamped = min(max(v, range.lowerBound), range.upperBound)
+        guard step > 0 else { return clamped }
+        let snapped = (clamped / step).rounded() * step
+        return min(max(snapped, range.lowerBound), range.upperBound)
+    }
+}
+
+struct OptionalIntField: View {
+    @Binding var value: Int?
+    let placeholder: String
+
+    var body: some View {
+        HStack(spacing: 8) {
+            TextField(placeholder, value: $value, format: .number.grouping(.never))
+                .textFieldStyle(.roundedBorder)
+                .frame(width: 130)
+                .disabled(value == nil)
+                .opacity(value == nil ? 0.4 : 1)
+            Toggle("Set", isOn: Binding(
+                get: { value != nil },
+                set: { value = $0 ? (value ?? 4096) : nil }
+            ))
+            .labelsHidden()
+            .toggleStyle(.checkbox)
+        }
+    }
+}
+
+struct OptionalUInt64Field: View {
+    @Binding var value: UInt64?
+    let placeholder: String
+
+    var body: some View {
+        HStack(spacing: 8) {
+            TextField(placeholder, value: $value, format: .number.grouping(.never))
+                .textFieldStyle(.roundedBorder)
+                .frame(width: 130)
+                .disabled(value == nil)
+                .opacity(value == nil ? 0.4 : 1)
+            Toggle("Set", isOn: Binding(
+                get: { value != nil },
+                set: { value = $0 ? (value ?? 42) : nil }
+            ))
+            .labelsHidden()
+            .toggleStyle(.checkbox)
+        }
+    }
+}
+
+struct MemoryBar: View {
+    let modelBytes: Int?
+    let otherBytes: Int?
+    let freeBytes: Int?
+    let totalBytes: Int
+
+    var body: some View {
+        VStack(alignment: .leading, spacing: 6) {
+            GeometryReader { geo in
+                HStack(spacing: 2) {
+                    Rectangle()
+                        .fill(Color.blue)
+                        .frame(width: max(0, geo.size.width * frac(modelBytes)))
+                    Rectangle()
+                        .fill(Color.orange)
+                        .frame(width: max(0, geo.size.width * frac(otherBytes)))
+                    Rectangle()
+                        .fill(Color.secondary.opacity(0.25))
+                        .frame(maxWidth: .infinity)
+                }
+            }
+            .frame(height: 16)
+            .clipShape(Capsule())
+            HStack(spacing: 14) {
+                legend("model (charged)", modelBytes, .blue)
+                legend("other apps + macOS", otherBytes, .orange)
+                legend("free", freeBytes, Color.secondary.opacity(0.25))
+                Spacer()
+                Text("\(MachineInfo.gb(totalBytes)) total")
+                    .foregroundStyle(.secondary)
+            }
+            .font(.caption)
+        }
+        .help("Unified-memory breakdown. Model = physical pages charged to the server process tree right now. Weights are memory-mapped and fault in on use; idle weights sit as instantly-reclaimable file cache, so this grows during decode and shrinks when idle. Other = everything else in use. Free = available now.")
+    }
+
+    private func frac(_ bytes: Int?) -> CGFloat {
+        guard let bytes, totalBytes > 0 else { return 0 }
+        return max(0, min(1, CGFloat(bytes) / CGFloat(totalBytes)))
+    }
+
+    private func legend(_ name: String, _ bytes: Int?, _ color: Color) -> some View {
+        HStack(spacing: 4) {
+            Circle().fill(color).frame(width: 7, height: 7)
+            Text("\(name) \(MachineInfo.gb(bytes))")
+                .foregroundStyle(.secondary)
+        }
+    }
+}
+
+struct TimeSeriesChart: View {
+    struct SeriesDef {
+        let name: String
+        let color: Color
+        let extract: (StatusSample) -> Double?
+        let format: (Double) -> String
+    }
+
+    let samples: [StatusSample]
+    let defs: [SeriesDef]
+
+    private let bracketHeight: CGFloat = 20
+
+    var body: some View {
+        VStack(alignment: .leading, spacing: 6) {
+            Canvas { ctx, size in
+                let plotH = max(0, size.height - bracketHeight)
+                for i in 1..<4 {
+                    let y = plotH * CGFloat(i) / 4
+                    var grid = Path()
+                    grid.move(to: CGPoint(x: 0, y: y))
+                    grid.addLine(to: CGPoint(x: size.width, y: y))
+                    ctx.stroke(grid, with: .color(.secondary.opacity(0.12)), lineWidth: 1)
+                }
+                guard samples.count > 1 else { return }
+                let span = CGFloat(Double(max(1, samples.count - 1)))
+                let xAt = { (i: Int) in CGFloat(Double(i)) / span * size.width }
+
+                for def in defs {
+                    let vals = samples.map(def.extract)
+                    let present = vals.compactMap { $0 }
+                    guard !present.isEmpty else { continue }
+                    let scale = p90(present)
+                    guard scale > 0 else { continue }
+                    var path = Path()
+                    var started = false
+                    for (i, v) in vals.enumerated() {
+                        guard let v else {
+                            started = false
+                            continue
+                        }
+                        let clamped = min(v / scale, 1.0)
+                        let x = xAt(i)
+                        let y = plotH * 0.96 - CGFloat(clamped) * plotH * 0.92
+                        if started {
+                            path.addLine(to: CGPoint(x: x, y: y))
+                        } else {
+                            path.move(to: CGPoint(x: x, y: y))
+                            started = true
+                        }
+                    }
+                    ctx.stroke(path, with: .color(def.color), style: StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))
+                }
+
+                drawBracket(ctx: ctx, width: size.width, plotH: plotH)
+            }
+            .frame(height: 170)
+            .background(Color(nsColor: .controlBackgroundColor))
+            .clipShape(RoundedRectangle(cornerRadius: 8))
+            .overlay(
+                RoundedRectangle(cornerRadius: 8)
+                    .stroke(Color(nsColor: .separatorColor), lineWidth: 1)
+            )
+            HStack(spacing: 14) {
+                ForEach(defs, id: \.name) { def in
+                    HStack(spacing: 4) {
+                        Circle().fill(def.color).frame(width: 7, height: 7)
+                        Text("\(def.name) \(currentText(def))")
+                            .foregroundStyle(.secondary)
+                    }
+                }
+                Spacer()
+                stageLegend
+            }
+            .font(.caption)
+        }
+        .help("Rolling window (8 min at 2s cadence) of /status samples taken only while the server is actively prefilling or decoding; idle periods leave gaps. Each line scales to the 90th percentile of its own values so bursts don't flatten the rest. The strip below shows request stages: orange prefill, green generation.")
+    }
+
+    private var stageLegend: some View {
+        HStack(spacing: 10) {
+            legendDot(.orange, "prefill")
+            legendDot(.green, "generation")
+        }
+    }
+
+    private func legendDot(_ color: Color, _ name: String) -> some View {
+        HStack(spacing: 3) {
+            Circle().fill(color).frame(width: 7, height: 7)
+            Text(name).foregroundStyle(.secondary)
+        }
+    }
+
+    private func drawBracket(ctx: GraphicsContext, width: CGFloat, plotH: CGFloat) {
+        let stripY = plotH + 3
+        let stripH = bracketHeight - 6
+        guard samples.count > 1 else { return }
+        let span = CGFloat(Double(max(1, samples.count - 1)))
+        let xAt = { (i: Int) in CGFloat(Double(i)) / span * width }
+        let segWidth = width / span
+
+        for (i, s) in samples.enumerated() {
+            guard let stage = s.stage else { continue }
+            let color: Color
+            switch stage {
+            case .prefill: color = .orange
+            case .decode: color = .green
+            }
+            let x = xAt(i)
+            let w = max(1.5, segWidth)
+            let rect = CGRect(x: x, y: stripY, width: w, height: stripH)
+            ctx.fill(Path(roundedRect: rect, cornerRadius: 2), with: .color(color.opacity(0.8)))
+        }
+    }
+
+    private func p90(_ vals: [Double]) -> Double {
+        let sorted = vals.sorted()
+        let idx = min(sorted.count - 1, Int(Double(sorted.count - 1) * 0.9))
+        return max(0.0001, sorted[idx])
+    }
+
+    private func currentText(_ def: SeriesDef) -> String {
+        for sample in samples.reversed() {
+            if let v = def.extract(sample) { return def.format(v) }
+        }
+        return "–"
+    }
+}
\ No newline at end of file
diff --git a/scripts/bundle-app.sh b/scripts/bundle-app.sh
new file mode 100755
index 0000000..3fa6810
--- /dev/null
+++ b/scripts/bundle-app.sh
@@ -0,0 +1,48 @@
+#!/bin/zsh
+# Usage: bundle-app.sh [--release] [--open]
+# Default: ad-hoc signed build/SplashGUI.app for local dev.
+# --release: Developer ID + hardened runtime + timestamp, then a notarized, stapled
+# build/SplashGUI-<version>.dmg. Requires SIGN_IDENTITY (a "Developer ID Application"
+# identity) and NOTARY_PROFILE (a notarytool keychain profile) in the environment.
+# The engine is downloaded by the app at runtime, so only the app's own binary is signed.
+set -e
+cd "$(dirname "$0")/.."
+
+swift build -c release
+
+APP="build/SplashGUI.app"
+rm -rf "$APP"
+mkdir -p "$APP/Contents/MacOS"
+cp .build/release/SplashGUI "$APP/Contents/MacOS/SplashGUI"
+cp Resources/Info.plist "$APP/Contents/Info.plist"
+
+if [[ " $* " == *" --release "* ]]; then
+  : "${SIGN_IDENTITY:?set SIGN_IDENTITY to your Developer ID Application identity}"
+  : "${NOTARY_PROFILE:?set NOTARY_PROFILE to your notarytool keychain profile}"
+  VERSION=$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' Resources/Info.plist)
+  DMG="build/SplashGUI-$VERSION.dmg"
+  codesign --force --options runtime --timestamp --sign "$SIGN_IDENTITY" "$APP"
+  codesign --verify --strict --verbose=2 "$APP"
+
+  staging=$(mktemp -d -t splashgui-dmg)
+  ditto "$APP" "$staging/SplashGUI.app"
+  ln -s /Applications "$staging/Applications"
+  rm -f "$DMG"
+  diskutil image create from --format UDZO --volumeName "SplashGUI $VERSION" "$staging" "$DMG"
+  codesign --force --timestamp --sign "$SIGN_IDENTITY" "$DMG"
+
+  xcrun notarytool submit "$DMG" --keychain-profile "$NOTARY_PROFILE" --wait
+  xcrun stapler staple "$DMG"
+  xcrun stapler staple "$APP"
+  spctl --assess --type open --context context:primary-signature -vv "$DMG"
+  spctl --assess -vv "$APP"
+  echo "built $DMG"
+else
+  codesign --force --sign - "$APP" 2>/dev/null
+fi
+
+if [[ " $* " == *" --open "* ]]; then
+  open "$APP"
+fi
+
+echo "built $APP"
diff --git a/scripts/profile-test/main.swift b/scripts/profile-test/main.swift
new file mode 100644
index 0000000..b014f87
--- /dev/null
+++ b/scripts/profile-test/main.swift
@@ -0,0 +1,436 @@
+// Headless assertions for SplashGUI's config store and per-model profiles — no GUI, no Xcode.
+// Run via ./run.sh (it handles the config.json backup/fixture dance). Exits non-zero on any failure.
+import Foundation
+import SwiftUI
+
+let A = "unsloth/Qwen3.8-27B-GGUF:UD-IQ3_XXS"
+let B = "prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0"
+let C = "unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M"
+
+var failures = 0
+func check(_ label: String, _ cond: Bool, _ detail: String = "") {
+    print((cond ? "PASS  " : "FAIL  ") + label + (detail.isEmpty ? "" : "  — " + detail))
+    if !cond { failures += 1 }
+}
+
+@MainActor
+func runTests() {
+    // A: a pre-profiles config still decodes (no fallback to factory) and migrates.
+    let cfg = ConfigStore.shared.load()
+    check("old config decodes — typed values survived",
+          cfg.run.maxContext == "100K" && cfg.sampling.temperature == 0.23,
+          "\(cfg.run.maxContext) / \(cfg.sampling.temperature)")
+    check("schemaVersion migrated to 6", cfg.run.schemaVersion == 6, "\(cfg.run.schemaVersion ?? -1)")
+    // v2 flipped int8→bf16, v3 flipped bf16→auto; v6 then resolved the still-auto KV because
+    // the typed maxContext keeps Auto off. The endpoint that matters: a concrete KV pick.
+    check("typed serve fields migrate to Auto off", cfg.run.auto == false)
+    check("auto KV resolved on the Auto-off migration",
+          cfg.run.kvFormat == "bf16" || cfg.run.kvFormat == "int8", cfg.run.kvFormat)
+    check("v4->v5 turned the SSD tier on", cfg.run.maxCacheDisk == "10G", cfg.run.maxCacheDisk)
+    check("idle release defaults to 60m", cfg.run.idleRelease == "60m", cfg.run.idleRelease)
+    check("persistent cache defaults on", cfg.run.persistentCache == true)
+    check("current model got a seeded profile", cfg.modelProfiles[A] != nil)
+    check("seed keeps tuned temp 0.23", cfg.modelProfiles[A]?.sampling.temperature == 0.23)
+    check("key keeps the :variant suffix", cfg.modelProfiles.keys.contains { $0.contains(":UD-IQ3_XXS") })
+
+    // B: switching to an untuned model starts it on its CARD — the thinking-mode set both cards
+    // publish (1.0 / 0.95 / 20, reasoning left at model default), not the old invented numbers.
+    let m = AppModel()
+    m.config.sampling.temperature = 0.42
+    m.config.sampling.reasoningEffort = "low"
+    m.config.run.defaultReasoningEffort = "low"
+    m.config.run.maxContext = "100K"
+    m.config.run.languageOnly = true
+    m.selectModelID(B)
+    check("modelID switched", m.config.run.modelID == B)
+    check("outgoing temp archived", m.config.modelProfiles[A]?.sampling.temperature == 0.42)
+    check("outgoing maxContext archived", m.config.modelProfiles[A]?.maxContext == "100K")
+    check("Bonsai card temp 1.0", m.config.sampling.temperature == 1.0, "\(m.config.sampling.temperature)")
+    check("Bonsai card topP 0.95", m.config.sampling.topP == 0.95, "\(m.config.sampling.topP)")
+    check("Bonsai card topK 20", m.config.sampling.topK == 20, "\(m.config.sampling.topK)")
+    check("card leaves reasoning effort at model default",
+          m.config.sampling.reasoningEffort == nil && m.config.run.defaultReasoningEffort == nil)
+    check("untuned model: maxContext back to auto", m.config.run.maxContext == "auto", m.config.run.maxContext)
+    check("untuned model: languageOnly off", m.config.run.languageOnly == false)
+
+    // C: switching back restores the saved profile.
+    m.selectModelID(A)
+    check("restored temp 0.42", m.config.sampling.temperature == 0.42, "\(m.config.sampling.temperature)")
+    check("restored maxContext 100K", m.config.run.maxContext == "100K")
+    check("restored reasoning effort (both places)",
+          m.config.sampling.reasoningEffort == "low" && m.config.run.defaultReasoningEffort == "low")
+
+    // D: a second Qwen row is also card-driven, and card data is per row.
+    m.selectModelID(C)
+    check("Qwen Q4_K_M card temp 1.0", m.config.sampling.temperature == 1.0, "\(m.config.sampling.temperature)")
+    check("Qwen Q4_K_M card topP 0.95", m.config.sampling.topP == 0.95)
+    let bonsai = CatalogModel.catalog.first { $0.id == B }!
+    check("Bonsai hides the unsupported 'low' effort",
+          bonsai.supportedEfforts?.contains("low") == false
+            && bonsai.supportedEfforts?.contains("xhigh") == true,
+          "\(bonsai.supportedEfforts ?? [])")
+    m.config.run.modelID = B
+    check("model exposes the filtered effort list", m.supportedEfforts == bonsai.supportedEfforts)
+    m.config.run.modelID = "someone/Custom-Model:x"
+    check("hand-typed ID offers every effort", m.supportedEfforts == CatalogModel.allEfforts)
+
+    // E: reset forgets this model's profile and returns to its card.
+    m.config.run.modelID = A
+    m.resetModelProfile()
+    check("reset cleared the stored profile", m.config.modelProfiles[A] == nil)
+    check("reset re-applies the card (1.0 / 0.95 / 20)",
+          m.config.sampling.temperature == 1.0 && m.config.sampling.topP == 0.95 && m.config.sampling.topK == 20,
+          "\(m.config.sampling.temperature)/\(m.config.sampling.topP)/\(m.config.sampling.topK)")
+    check("reset returns serve fields to auto",
+          m.config.run.maxContext == "auto" && m.config.run.kvFormat == "auto" && m.config.run.languageOnly == false)
+
+    // G: thinking off offers the card's non-thinking set, and only on click.
+    m.config.sampling.reasoningEffort = "none"
+    m.config.run.defaultReasoningEffort = "none"
+    m.applyCardOffSampling()
+    check("card's non-thinking set applied on request (0.7 / 0.80 / 20)",
+          m.config.sampling.temperature == 0.7 && m.config.sampling.topP == 0.8 && m.config.sampling.topK == 20,
+          "\(m.config.sampling.temperature)/\(m.config.sampling.topP)/\(m.config.sampling.topK)")
+    m.config.sampling.temperature = 0.55          // hand-tuned value must survive
+    m.config.run.modelID = "someone/Custom-Model:x"
+    m.applyCardOffSampling()
+    check("hand-typed ID has no card, so nothing is rewritten",
+          m.config.sampling.temperature == 0.55, "\(m.config.sampling.temperature)")
+
+    // H: what landed on disk reloads the same.
+    let reread = ConfigStore.shared.load()
+    check("B's card profile persisted", reread.modelProfiles[B]?.sampling.temperature == 1.0,
+          "\(reread.modelProfiles[B]?.sampling.temperature ?? -1)")
+    check("typed temp 0.55 survives a save", reread.sampling.temperature == 0.55,
+          "\(reread.sampling.temperature)")
+    check("schemaVersion stays 6", reread.run.schemaVersion == 6)
+    // startOnLaunch is absent from this v2 fixture — the tolerant decoder must default it
+    // false, not throw the whole config back to factory (the Codable missing-key trap).
+    check("startOnLaunch defaults false when the key is absent", reread.startOnLaunch == false)
+
+    // F: the SSD tier and the idle release reach the engine's command line, and the tier's
+    // persistence follows the quota (the engine refuses it without one).
+    var run = RunConfig()
+    run.maxCacheDisk = "10G"
+    run.persistentCache = true
+    run.idleRelease = "60m"
+    let args = SplashServer.buildArguments(for: run)
+    check("serve carries the SSD quota", args.contains("--max-cache-disk") && args.contains("10G"))
+    check("serve carries the persistent cache", args.contains("--persistent-cache"))
+    check("serve carries the idle release", args.contains("--idle-release") && args.contains("60m"))
+    var off = RunConfig()
+    off.maxCacheDisk = "0"
+    off.persistentCache = true
+    check("no persistent cache without a quota",
+          !SplashServer.buildArguments(for: off).contains("--persistent-cache"))
+    off.persistentCache = false
+    off.idleRelease = "auto"
+    let offArgs = SplashServer.buildArguments(for: off)
+    check("persistent cache can be turned off", !offArgs.contains("--persistent-cache"))
+    check("auto leaves the engine's own idle release", !offArgs.contains("--idle-release"))
+    off.maxCacheDisk = "auto"
+    check("auto leaves the SSD quota to the engine", !SplashServer.buildArguments(for: off).contains("--max-cache-disk"))
+
+    // I: the Auto switch resolves the four covered fields at launch.
+    let prof = AutoProfile(maxMemoryBytes: 40_000_000_000, contextTokens: 131_072, kvFormat: "int8")
+    var arun = RunConfig()   // shipped default: Auto on
+    let effAuto = arun.effective(using: prof)
+    check("Auto on: profile sizes context and memory",
+          effAuto.maxContext == "131072" && effAuto.maxMemory == "40000000000",
+          "\(effAuto.maxContext) / \(effAuto.maxMemory)")
+    check("Auto on: KV follows the profile", effAuto.kvFormat == "int8")
+    check("Auto on: the SSD cache goes to the engine",
+          effAuto.maxCacheDisk == "auto"
+            && !SplashServer.buildArguments(for: effAuto).contains("--max-cache-disk"))
+    let effCustom = arun.effective(using: nil)
+    check("Auto on with no profile: Splash sizes context and memory, KV falls back to bf16",
+          !SplashServer.buildArguments(for: effCustom).contains("--max-context")
+            && !SplashServer.buildArguments(for: effCustom).contains("--max-memory")
+            && effCustom.kvFormat == "bf16")
+    arun.auto = false
+    arun.maxContext = "64K"; arun.maxMemory = "24G"; arun.kvFormat = "bf16"; arun.maxCacheDisk = "10G"
+    let effTyped = arun.effective(using: prof)
+    check("Auto off: the typed values launch untouched",
+          effTyped.maxContext == "64K" && effTyped.maxMemory == "24G"
+            && effTyped.kvFormat == "bf16" && effTyped.maxCacheDisk == "10G")
+
+    // J: the Codable trap on the new fields — a profile saved before `auto` existed must
+    // decode with it defaulted, and grantedAuto must round-trip.
+    let legacy = #"{"sampling":{"temperature":0.5,"topP":0.9,"topK":10},"maxContext":"50K","maxMemory":"auto","kvFormat":"bf16","languageOnly":false}"#
+    if let pdata = legacy.data(using: .utf8),
+       let prof2 = try? JSONDecoder().decode(ModelProfile.self, from: pdata) {
+        check("legacy profile without auto decodes defaulted",
+              prof2.auto == true && prof2.maxContext == "50K")
+    } else {
+        check("legacy profile without auto decodes defaulted", false, "decoder threw")
+    }
+    var gcfg = AppConfig()
+    gcfg.grantedAuto["someone/Custom-Model:x"] = GrantedSettings(contextTokens: 65536, memoryBytes: 25_769_803_776)
+    if let gd = try? JSONEncoder().encode(gcfg),
+       let back = try? JSONDecoder().decode(AppConfig.self, from: gd) {
+        check("grantedAuto round-trips",
+              back.grantedAuto["someone/Custom-Model:x"]?.contextTokens == 65536
+                && back.grantedAuto["someone/Custom-Model:x"]?.memoryBytes == 25_769_803_776)
+    } else {
+        check("grantedAuto round-trips", false, "encode/decode threw")
+    }
+
+    // K: a schema-5 config whose four covered fields are all "auto" migrates to Auto ON,
+    // leaving the KV field alone for the launch-time resolution.
+    let cfgURL = AppPaths.dataDir.appendingPathComponent("config.json")
+    if let raw = try? Data(contentsOf: cfgURL),
+       var dict = try? JSONSerialization.jsonObject(with: raw) as? [String: Any],
+       var runDict = dict["run"] as? [String: Any] {
+        runDict["schemaVersion"] = 5
+        runDict["maxContext"] = "auto"
+        runDict["maxMemory"] = "auto"
+        runDict["kvFormat"] = "auto"
+        runDict["maxCacheDisk"] = "auto"
+        dict["run"] = runDict
+        if let out = try? JSONSerialization.data(withJSONObject: dict) {
+            try? out.write(to: cfgURL)
+            let migrated = ConfigStore.shared.load()
+            check("all-auto schema 5 migrates to Auto on", migrated.run.auto == true)
+            check("all-auto migration leaves KV at auto",
+                  migrated.run.kvFormat == "auto", migrated.run.kvFormat)
+            check("all-auto migration lands on schema 6", migrated.run.schemaVersion == 6)
+        } else {
+            check("all-auto schema 5 migrates to Auto on", false, "fixture write failed")
+        }
+    } else {
+        check("all-auto schema 5 migrates to Auto on", false, "fixture unreadable")
+    }
+
+    // L: the Provider tab's new sampling fields and client configs.
+    let legacySampling = #"{"temperature":0.5,"topP":0.9,"topK":10,"maxTokens":null,"seed":null,"reasoningEffort":"none"}"#
+    if let sdata = legacySampling.data(using: .utf8),
+       let sam = try? JSONDecoder().decode(SamplingDefaults.self, from: sdata) {
+        check("legacy sampling without presencePenalty/minP decodes defaulted",
+              sam.presencePenalty == 0 && sam.minP == 0 && sam.reasoningEffort == "none")
+    } else {
+        check("legacy sampling without presencePenalty/minP decodes defaulted", false, "threw")
+    }
+    let bonsaiRow = CatalogModel.catalog.first { $0.id == B }!
+    check("Bonsai card: min_p 0.05, presence 0 in thinking mode",
+          bonsaiRow.cardProfile().sampling.minP == 0.05
+            && bonsaiRow.cardProfile().sampling.presencePenalty == 0)
+    m.config.run.modelID = A
+    m.applyCardOffSampling()
+    check("card-off applies presence 1.5 and min_p 0",
+          m.config.sampling.presencePenalty == 1.5 && m.config.sampling.minP == 0
+            && m.config.sampling.temperature == 0.7)
+    check("parseContext reads the field spellings",
+          AppModel.parseContext("100K") == 102_400 && AppModel.parseContext("131072") == 131_072
+            && AppModel.parseContext("auto") == nil)
+
+    var sam = SamplingDefaults()
+    sam.seed = 12_345_678_901
+    let base = ClientConfigContext(client: .opencode, modelID: "someone/Model:x", label: "Model X",
+                                   port: 8095, contextTokens: 65_536,
+                                   inputModalities: ["text", "image", "pdf"], sampling: sam)
+    if let data = ClientConfigs.text(for: base).data(using: .utf8),
+       let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+       let provider = (root["providers"] as? [String: Any])?["splashgui"] as? [String: Any],
+       let models = provider["models"] as? [String: Any],
+       let model = models["someone/Model:x"] as? [String: Any] {
+        let body = model["body"] as? [String: Any]
+        check("OpenCode: sampling in the model body",
+              (body?["temperature"] as? Double) == 1.0 && (body?["top_k"] as? Int) == 20
+                && (body?["presence_penalty"] as? Double) == 0 && (body?["min_p"] as? Double) == 0)
+        check("OpenCode: seed passes through body", body?["seed"] != nil)
+        let limit = model["limit"] as? [String: Any]
+        check("OpenCode: limit math at 64K — out 16384, in 49152",
+              (limit?["context"] as? Int) == 65_536 && (limit?["output"] as? Int) == 16_384
+                && (limit?["input"] as? Int) == 49_152)
+        check("OpenCode: no root model/small_model or agent overrides",
+              root["model"] == nil && root["small_model"] == nil
+                && root["agent"] == nil && root["agents"] == nil)
+        let variants = model["variants"] as? [[String: Any]]
+        let variantIDs = variants?.compactMap { $0["id"] as? String }
+        let highBody = variants?.first { ($0["id"] as? String) == "high" }?["body"] as? [String: Any]
+        check("OpenCode: one variant per effort, reasoning_effort in the body",
+              variantIDs == CatalogModel.allEfforts
+                && (highBody?["reasoning_effort"] as? String) == "high")
+        let reasoning = (model["capabilities"] as? [String: Any])?["reasoning"] as? [String: Any]
+        check("OpenCode: reasoning capability advertises the efforts",
+              (reasoning?["supported"] as? Bool) == true && (reasoning?["toggle"] as? Bool) == true
+                && (reasoning?["effort"] as? [String])?.contains("high") == true)
+        let settings = provider["settings"] as? [String: Any]
+        let compatibility = model["compatibility"] as? [String: Any]
+        check("OpenCode: V2 package + baseURL, reasoning_content and max_tokens compatibility",
+              (provider["package"] as? String) == "@opencode/ai/providers/openai-compatible"
+                && (settings?["baseURL"] as? String) == "http://127.0.0.1:8095/v1"
+                && (compatibility?["reasoningField"] as? String) == "reasoning_content"
+                && (compatibility?["maxTokensField"] as? String) == "max_tokens")
+    } else {
+        check("OpenCode: sampling in the model body", false, "config did not parse")
+    }
+    let zctx = ClientConfigContext(client: .zed, modelID: base.modelID, label: base.label,
+                                   port: base.port, contextTokens: base.contextTokens,
+                                   inputModalities: base.inputModalities, sampling: base.sampling)
+    let ztext = ClientConfigs.text(for: zctx)
+    check("Zed: openai_compatible + api_url + temperature only",
+          ztext.contains("openai_compatible") && ztext.contains("api_url")
+            && ztext.contains("model_parameters") && !ztext.contains("top_k")
+            && ztext.contains("interleaved_reasoning"))
+    let cctx = ClientConfigContext(client: .claudeCode, modelID: base.modelID, label: base.label,
+                                   port: base.port, contextTokens: base.contextTokens,
+                                   inputModalities: base.inputModalities, sampling: base.sampling)
+    let ctext = ClientConfigs.text(for: cctx)
+    check("Claude Code: env block, bare base URL (no /v1), no sampling",
+          ctext.contains("ANTHROPIC_BASE_URL") && ctext.contains("http://127.0.0.1:8095\"")
+            && !ctext.contains("/v1") && !ctext.contains("temperature"))
+    let xctx = ClientConfigContext(client: .codex, modelID: base.modelID, label: base.label,
+                                   port: base.port, contextTokens: base.contextTokens,
+                                   inputModalities: base.inputModalities, sampling: base.sampling)
+    let xtext = ClientConfigs.text(for: xctx)
+    check("Codex: TOML provider, responses wire, 90% compact limit",
+          xtext.contains("wire_api = \"responses\"") && xtext.contains("env_key = \"SPLASH_API_KEY\"")
+            && xtext.contains("model_auto_compact_token_limit = 58982")
+            && xtext.contains("model_provider = \"splash\""))
+
+    // M: engine source — the mode field's tolerant decode and the latest-release resolver.
+    // Synthetic JSON, not the live fixture: the app now WRITES engineMode, so the on-disk
+    // config always has the key and cannot prove the absent-key default.
+    let noMode = #"{"engineURLOverride":"keep-me","sampling":{"temperature":0.3}}"#
+    if let nm = noMode.data(using: .utf8),
+       let ncfg = try? JSONDecoder().decode(AppConfig.self, from: nm) {
+        check("engineMode absent decodes pinned without losing the config",
+              ncfg.engineMode == .pinned && ncfg.sampling.temperature == 0.3
+                && ncfg.engineURLOverride == "keep-me")
+    } else {
+        check("engineMode absent decodes pinned without losing the config", false, "decoder threw")
+    }
+    let oddMode = #"{"engineMode":"sideways","sampling":{"temperature":0.3}}"#
+    if let od = oddMode.data(using: .utf8),
+       let om = try? JSONDecoder().decode(AppConfig.self, from: od) {
+        check("unknown engineMode falls back to pinned without losing the config",
+              om.engineMode == .pinned && om.sampling.temperature == 0.3)
+    } else {
+        check("unknown engineMode falls back to pinned without losing the config", false, "decoder threw")
+    }
+    var mcfg = AppConfig()
+    mcfg.engineMode = .latest
+    if let md = try? JSONEncoder().encode(mcfg),
+       let mback = try? JSONDecoder().decode(AppConfig.self, from: md) {
+        check("engineMode round-trips", mback.engineMode == .latest)
+    } else {
+        check("engineMode round-trips", false, "encode/decode threw")
+    }
+    // The resolver's pure half, fed the real 1.5.0 release fixture. A latest that equals the
+    // compiled-in pin must produce the identical URL so EngineInstaller reuses its directory
+    // instead of keying a hash-named twin off the URL.
+    let v150 = "1ddc28bf7bfda8833859a913d7072e2aac9072addb9eb5664f3bf1a83a8d6ee2"
+    let assets150 = ["splash-1.5.0-arm64-macos26.tar.gz", "splash-1.5.0-arm64-macos26.tar.gz.sha256",
+                     "Splash-1.5.0.dmg", "SHA256SUMS", "appcast.xml"]
+    if let lp = EngineResolver.pin(tagName: "1.5.0", assetNames: assets150, sha256Text: v150 + "\n") {
+        check("latest 1.5.0 resolves to the compiled-in pin exactly",
+              lp == EngineInstaller.defaultPin, "\(lp.version) \(lp.url)")
+        check("latest-equals-pinned reuses the pinned install dir",
+              EngineInstaller.dirName(for: lp) == EngineInstaller.dirName(for: EngineInstaller.defaultPin))
+    } else {
+        check("latest 1.5.0 resolves to the compiled-in pin exactly", false, "pin() returned nil")
+        check("latest-equals-pinned reuses the pinned install dir", false)
+    }
+    if let vp = EngineResolver.pin(tagName: "v1.6.1", assetNames: ["splash-1.6.1-arm64-macos26.tar.gz",
+                                                                   "splash-1.6.1-arm64-macos26.tar.gz.sha256"],
+                                   sha256Text: String(repeating: "A", count: 64)) {
+        check("v-prefixed tag: version stripped, download URL keeps the tag",
+              vp.version == "1.6.1" && vp.url == "https://github.com/incoai/splash/releases/download/v1.6.1/splash-1.6.1-arm64-macos26.tar.gz"
+                && vp.sha256 == String(repeating: "a", count: 64), "\(vp.version) \(vp.url)")
+    } else {
+        check("v-prefixed tag: version stripped, download URL keeps the tag", false, "pin() returned nil")
+    }
+    check("release without the .sha256 asset resolves to nil",
+          EngineResolver.pin(tagName: "1.6.0", assetNames: ["splash-1.6.0-arm64-macos26.tar.gz"],
+                             sha256Text: v150) == nil)
+    check("release with a malformed checksum resolves to nil",
+          EngineResolver.pin(tagName: "1.6.0", assetNames: assets150.map { $0.replacingOccurrences(of: "1.5.0", with: "1.6.0") },
+                             sha256Text: "not-hex") == nil)
+    check("release with a renamed payload resolves to nil",
+          EngineResolver.pin(tagName: "1.6.0", assetNames: ["splash-1.6.0-x64-macos15.tar.gz",
+                                                            "splash-1.6.0-x64-macos15.tar.gz.sha256"],
+                             sha256Text: v150) == nil)
+    var ccfg = AppConfig()
+    ccfg.engineMode = .custom
+    ccfg.engineVersionOverride = "1.4.1"
+    ccfg.engineURLOverride = "https://github.com/incoai/splash/releases/download/1.4.1/splash-1.4.1-arm64-macos26.tar.gz"
+    ccfg.engineSHA256Override = String(repeating: "b", count: 64)
+    check("custom mode with all three fields yields the override pin",
+          ccfg.enginePinOverride()?.version == "1.4.1")
+    ccfg.engineSHA256Override = ""
+    check("custom mode with a blank SHA falls back to no override", ccfg.enginePinOverride() == nil)
+
+    // The mode table start() installs by: the custom pin applies only in custom mode, pinned
+    // mode ignores the override fields, and latest falls back to the installed engine, never
+    // downward to the compiled pin.
+    let stale = EnginePin(version: "1.4.1", sha256: String(repeating: "b", count: 64),
+                          url: "https://github.com/incoai/splash/releases/download/1.4.1/splash-1.4.1-arm64-macos26.tar.gz")
+    let pinnedPlan = AppModel.enginePlan(mode: .pinned, customOverride: stale, installed: true,
+                                         checkUpdate: true, latest: nil)
+    check("pinned mode ignores complete custom fields",
+          pinnedPlan.override == nil && pinnedPlan.ensure == true, "\(pinnedPlan)")
+    let customPlan = AppModel.enginePlan(mode: .custom, customOverride: stale, installed: true,
+                                         checkUpdate: false, latest: nil)
+    check("custom mode installs the custom pin regardless of the update toggle",
+          customPlan.ensure == true && customPlan.override == stale)
+    let partialPlan = AppModel.enginePlan(mode: .custom, customOverride: nil, installed: true,
+                                          checkUpdate: false, latest: nil)
+    check("custom mode with partial fields keeps pinned behavior",
+          partialPlan.ensure == false && partialPlan.override == nil)
+    let latestHit = AppModel.enginePlan(mode: .latest, customOverride: nil, installed: true,
+                                        checkUpdate: false, latest: stale)
+    check("latest mode installs the resolver answer",
+          latestHit.ensure == true && latestHit.override == stale)
+    let latestKeep = AppModel.enginePlan(mode: .latest, customOverride: nil, installed: true,
+                                         checkUpdate: false, latest: nil)
+    check("latest mode offline keeps the installed engine",
+          latestKeep.ensure == false && latestKeep.override == nil)
+    let latestBootstrap = AppModel.enginePlan(mode: .latest, customOverride: nil, installed: false,
+                                              checkUpdate: false, latest: nil)
+    check("latest mode offline with nothing installed installs the compiled pin",
+          latestBootstrap.ensure == true && latestBootstrap.override == nil)
+
+    // N: the catalog must track the installed engine's suggested list (the sync guard for the
+    // Splash-defaults swap). Skips with a PASS when no engine is installed on the test machine.
+    let tsv = EngineInstaller.currentLink.appendingPathComponent("install/suggested-models.tsv")
+    if let tsvText = try? String(contentsOf: tsv, encoding: .utf8) {
+        let ids = tsvText.split(separator: "\n").compactMap { line -> String? in
+            let s = line.trimmingCharacters(in: .whitespaces)
+            guard !s.isEmpty, !s.hasPrefix("#") else { return nil }
+            return s.split(separator: "\t").first.map(String.init)
+        }
+        let cat = CatalogModel.catalog.map(\.id).filter { $0 != "custom" }
+        check("catalog matches the installed engine's suggested list",
+              cat == ids, "catalog \(cat.count) vs tsv \(ids.count)"
+                + (cat == ids ? "" : " diff: \(Set(cat).symmetricDifference(ids).sorted())"))
+        let mem = tsvText.split(separator: "\n").compactMap { line -> (String, Int)? in
+            let s = line.trimmingCharacters(in: .whitespaces)
+            guard !s.isEmpty, !s.hasPrefix("#") else { return nil }
+            let cols = s.split(separator: "\t").map(String.init)
+            guard cols.count >= 3, let gb = Int(cols[2]) else { return nil }
+            return (cols[0], gb)
+        }
+        let tsvMemory = Dictionary(mem.map { ($0.0, $0.1) }, uniquingKeysWith: { a, _ in a })
+        let memoryDrift = CatalogModel.catalog.filter { $0.id != "custom" }.compactMap { entry -> String? in
+            guard let gb = entry.memoryGB else { return "\(entry.id): catalog row lacks MEMORY" }
+            return tsvMemory[entry.id] == gb ? nil : "\(entry.id): tsv \(tsvMemory[entry.id] ?? -1) vs catalog \(gb)"
+        }
+        check("catalog MEMORY figures match the engine's suggested list",
+              memoryDrift.isEmpty, memoryDrift.joined(separator: "; "))
+    } else {
+        check("catalog matches the installed engine's suggested list", true, "no engine installed, skipped")
+    }
+
+    // Auto sizing constants are 27B-arch-only: other archs return nil so the engine sizes itself.
+    // The synthetic weight is small so nil can only come from the arch gate, not the budget.
+    check("Auto sizing skips non-27B arch rows",
+          MachineInfo.autoProfile(modelID: "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF:Q2_0",
+                                  languageOnly: false, weightsBytes: 1_000_000_000) == nil)
+    check("Auto sizing still covers the 27B arch",
+          MachineInfo.autoProfile(modelID: A, languageOnly: false, weightsBytes: 10_000_000_000) != nil)
+
+    exit(failures == 0 ? 0 : 1)
+}
+
+MainActor.assumeIsolated { runTests() }
diff --git a/scripts/profile-test/run.sh b/scripts/profile-test/run.sh
new file mode 100755
index 0000000..1105b5b
--- /dev/null
+++ b/scripts/profile-test/run.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env zsh
+# Headless regression for the config store: profile swap, schema migration, model cards.
+# Drives the real AppModel (no GUI) against a temp fixture at the real config.json path,
+# because HOME does not redirect applicationSupportDirectory. Refuses to run while the app
+# is up, and restores the original config.json whatever happens.
+set -e
+cd "$(dirname "$0")"
+CORE="../../Sources/SplashGUI/Core"
+CFG="$HOME/Library/Application Support/SplashGUI/config.json"
+# AppModel auto-starts the server on init when config.startOnLaunch is on; never let the
+# harness spawn a real serve.
+export SPLASHGUI_TEST=1
+
+if pgrep -f "SplashGUI.app/Contents/MacOS/SplashGUI" >/dev/null; then
+  print "SplashGUI is running — quit it first (it saves config.json on change and at exit)." && exit 2
+fi
+[[ -f "$CFG" ]] || { print "no config.json at $CFG"; exit 2; }
+
+backup=$(mktemp)
+cp "$CFG" "$backup"
+trap 'cp "$backup" "$CFG"; rm -f "$backup"; print "config.json restored"' EXIT
+
+# A pre-profiles (schemaVersion 2) config: no modelProfiles key, and typed values the assertions
+# below read back — proof the file decoded and migrated rather than falling back to factory.
+python3 - <<'EOF'
+import json, os
+p = os.path.expanduser("~/Library/Application Support/SplashGUI/config.json")
+c = json.load(open(p))
+c['run']['schemaVersion'] = 2
+c['run']['kvFormat'] = 'bf16'
+c['run']['maxContext'] = '100K'
+# Pin the starting model: the assertions below assume the current model is A (IQ3_XXS),
+# so the fixture must not inherit whatever model the live config happens to select.
+c['run']['modelID'] = 'unsloth/Qwen3.8-27B-GGUF:UD-IQ3_XXS'
+c['startOnLaunch'] = False   # live config may have it on; the fixture must stay inert
+c['sampling']['temperature'] = 0.23
+c.pop('modelProfiles', None)
+json.dump(c, open(p, 'w'), indent=1)
+EOF
+
+swiftc -swift-version 5 -o /tmp/splashgui-profiletest \
+  "$CORE"/AppConfig.swift "$CORE"/AppModel.swift "$CORE"/ClientConfigs.swift \
+  "$CORE"/EngineInstaller.swift "$CORE"/EngineResolver.swift \
+  "$CORE"/MachineInfo.swift "$CORE"/SplashClient.swift "$CORE"/SplashServer.swift main.swift
+
+/tmp/splashgui-profiletest
diff --git a/scripts/release.sh b/scripts/release.sh
new file mode 100755
index 0000000..0ee1195
--- /dev/null
+++ b/scripts/release.sh
@@ -0,0 +1,38 @@
+#!/bin/zsh
+# release.sh: tag the current commit splashgui/v<version>, push main + the tag to origin,
+# and create the GitHub release with the notarized DMG as its asset.
+# Precondition: scripts/bundle-app.sh --release (builds, notarizes and staples the DMG).
+# Auth: the `gh` CLI (run `gh auth login` once).
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+VERSION=$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' Resources/Info.plist)
+TAG="splashgui/v${VERSION}"
+DMG="build/SplashGUI-${VERSION}.dmg"
+
+[[ -f "$DMG" ]] || { echo "error: $DMG not found; run scripts/bundle-app.sh --release first" >&2; exit 1; }
+xcrun stapler validate -q "$DMG" || { echo "error: $DMG has no stapled notarization ticket" >&2; exit 1; }
+git diff-index --quiet HEAD -- . || { echo "error: uncommitted changes; commit before releasing" >&2; exit 1; }
+command -v gh >/dev/null || { echo "error: gh CLI not found; install it and run gh auth login" >&2; exit 1; }
+
+if ! git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
+  git tag -a "$TAG" -m "SplashGUI v${VERSION}"
+  echo "==> tagged ${TAG}"
+fi
+echo "==> pushing main + ${TAG} to origin"
+git push origin main
+git push origin "$TAG"
+
+# Notes: app commits since the previous SplashGUI tag, plus the DMG checksum.
+PREV=$(git describe --tags --abbrev=0 --match 'splashgui/v*' "${TAG}^" 2>/dev/null || true)
+if [[ -n "$PREV" ]]; then
+  NOTES=$(git log --no-merges --pretty='- %s' "${PREV}..${TAG}" -- .)
+else
+  NOTES="First Developer ID-signed, notarized release."
+fi
+SHA=$(shasum -a 256 "$DMG" | awk '{print $1}')
+NOTES="${NOTES}"$'\n\n'"SHA-256 (SplashGUI-${VERSION}.dmg): \`${SHA}\`"
+
+echo "==> creating GitHub release ${TAG}"
+gh release create "$TAG" "$DMG" --title "SplashGUI v${VERSION}" --notes "$NOTES"
+echo "==> done"