feat(settings): profiles write path + Test Connection (#136)
Profiles S3 over the S2 shell: every Settings change now persists. Model/effort writes ride the engine's own CLI — `hermes -p <profile> config set/unset` for model.provider / model.default / model.reasoning_effort / model.base_url (zai endpoint family written LAST: setting model.provider clears a stale base_url, live-probed; unset-when-absent is idempotent success). Provider keys upsert VAR=value into ALL THREE profiles' .env — a key entered before any surface is on its provider still persists and pre-lands for any later switch (maintainer ruling 2026-10-28; no switch re-fire). 0600, foreign lines preserved byte-for-byte, line-broken values refused at the shared sink (env-file injection guard), NSLock serializes the read-upsert-write across concurrent provider writes. Hydration reads model blocks and keys back at pane open — a restart neither blanks the key fields nor refuses Test Connection; an edit made mid-read owns the truth (no stomp), and a custom z.ai base_url seeds the endpoint field instead of being clobbered to a family default. Per-target writes coalesce AND chain past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write queues — the last edit is always the last write to land (finish-audit race fix, pinned). Test Connection = two-step probe (GET /models, then a minimal streaming chat) with honest decode per the factsheet: zai 1113 → wrong key type, 401s → auth failed (Anthropic request_id), finish=length → starved, empty 200 → request failed, errors riding a 2xx decoded as the provider error. Live-probed wire corrections (dogfood, 2026-10-28): Content-Type application/json on every request — URLSession defaults to form-urlencoded and providers diverge (zai 200+envelope, OpenAI 400, Anthropic tolerates); OpenAI speaks the Responses API (/responses, input + max_output_tokens, flagship gpt-6.1-sol); probe token cap 512 (64 starved reasoning models into "no content"); OpenAI's "error": null event snapshots don't decode as failures. Finish-audit (ponytail + security + general reviewers): write-ordering race + .env lost update + hydrate stomp + custom-endpoint clobber fixed and pinned (one-shot hold / latched read knobs in the test double); ~30 lines of dead flexibility cut (keyType protocol param, works(reply:) payload, unused timeout knob, double JSON round trips). Suite 468/468 xcresult-verified; swiftlint clean; factsheet §6 correction logged. Closes #136
This commit is contained in:
1 parent
42a27cc8a3
commit
5ad605eb3c
20 files changed
+1983
-161
No files matched your search
@@ -130,7 +130,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
|
||||
<!-- gitnexus:start -->
|
||||
# GitNexus — Code Intelligence
|
||||
|
||||
This project is indexed by GitNexus as **museion** (4911 symbols, 17496 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
This project is indexed by GitNexus as **museion** (5099 symbols, 19010 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
|
||||
|
||||
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
|
||||
|
||||
@@ -185,8 +185,10 @@ This project is indexed by GitNexus as **museion** (4911 symbols, 17496 relation
|
||||
Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent:
|
||||
|
||||
<!-- write-log: window-start -->
|
||||
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-27 | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](docs/devlog/20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) |
|
||||
| 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](docs/devlog/20261027-issue135-profiles-s2-settings-page-ui_log.md) |
|
||||
| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) |
|
||||
| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md) |
|
||||
@@ -196,5 +198,5 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
| 2026-10-21 | [20261021-issue27-dismiss-decay-learnings_log.md](docs/devlog/20261021-issue27-dismiss-decay-learnings_log.md) |
|
||||
| 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) |
|
||||
| 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) |
|
||||
| 2026-10-20 | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](docs/devlog/20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) |
|
||||
|
||||
<!-- write-log: window-end -->
|
||||
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **settings:** Profiles S3 — the real write path + Test Connection (#136) — every Settings change now persists: model/effort writes ride the engine's own CLI (`hermes -p <profile> config set/unset` model.provider/default/reasoning_effort/base_url, wire-verified) and provider keys upsert `VAR=value` into ALL THREE profiles' `.env` (0600, foreign lines preserved, line-broken values refused at the sink — an env-file injection guard); hydration reads model blocks and keys back at pane open, so a restart neither blanks the UI nor refuses Test Connection, and a custom z.ai base_url survives instead of being clobbered to a family default. Per-target writes coalesce AND chain past the debounce guard — the last edit is always the last write to land. Test Connection is a two-step probe (`GET /models` then a minimal streaming chat) with honest decode per the factsheet: z.ai 1113 → wrong key type, 401s → auth failed with request id, finish=length → starved, empty 200 → request failed. Live-probed wire corrections: `Content-Type: application/json` on every request (URLSession defaults to form-urlencoded — z.ai answers 200 with an error envelope), OpenAI speaks the Responses API (`/responses`, `input` + `max_output_tokens`, flagship `gpt-6.1-sol`), probe token cap 512 (64 starved reasoning models into "no content"). Suite 468; three-reviewer finish-audit fixed a write-ordering race, an `.env` lost-update race, a mid-hydrate stomp, and cut ~30 lines of dead flexibility (issue #136)
|
||||
|
||||
- **settings:** Profiles S2 — Settings page as sidebar + detail (#130 prototype variant C verdict) — destinations Content (the unchanged Home control) · Pass 1 · Pass 2 · Chat (annotated "· Sessions") · Provider Keys. Each surface page edits its model block over an in-memory model: provider menu, model combobox sourcing Hermes' own registry cache with first-class free text (the seed `claude-sonnet-5-5` reads as *custom (not in registry)* — the default state), per-provider reasoning-effort menu led by "unset · provider default", variant B's current-model headline, and Restore Defaults back to the #132 seed; the Provider Keys page carries endpoint, the z.ai key-type toggle swapping the endpoint family (`/api/paas/v4` ↔ `/api/coding/paas/v4`, custom endpoints survive), and masked keys with reveal. Persistence is S3's — every change routes through an injectable `SettingsWriting` seam whose contract (debounce, secrets never via argv, redacted error text) is frozen now; write failures surface in an orange strip. Dropdown picks commit through `comboBoxSelectionDidChange` reading the selection index — the notification fires before `stringValue` updates (log-observed dogfood fix). Suite 432 (issue #135)
|
||||
|
||||
- **profiles:** Profiles S1 — surface registry + provisioning ×3 (PRD #134, ADR-0014) — one gate pass now provisions ALL THREE Hermes profiles: `museion` is adopted in place (never re-created or reconfigured — its model stays the user's), `museion-pass1`/`museion-pass2` are created fresh with the #132 defaults (`claude-sonnet-5-5` on anthropic, reasoning effort unset, 24k output budget as a guardrail) written via the engine's own `hermes -p <profile> config set` rail — wire-verified, marker-gated so a re-pass is a no-op and Settings changes survive, and a failed provision names the profile on the #48 card. Writing skills move to ONE master copy at `~/Library/Application Support/Museion/skills/` symlinked into each profile per the #133 allocation (Pass 1: 9 · Pass 2: 8 · Chat: 10 — the persona pair never co-occurs); today's copy-era dirs migrate to symlinks only on byte-match, diverged dirs stay copies, user skills untouched. Daily backup widens to one stamp carrying all three profiles — any live engine skips the whole stamp; restore docs name the three folders (issue #134)
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
|
||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
||||
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting.
|
||||
- Settings (#135, Profiles S2 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models, `ZaiKeyType` endpoint families, `ModelRegistry` (lenient load of `~/.hermes/provider_models_cache.json`, memoized via `loadedDefault` — the pane's @State init re-runs the default args per SwiftUI construction), `SettingsModel` (@MainActor @Observable, pane-local until S3): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (S3 reads hand-edited config.yaml — a blank menu selection never renders), fire-and-forget writes tracked in `pendingWrites` (capped; `awaitPendingWrites()` is the tests' sync point), and the `SettingsWriting` write-path seam — S3 implements it (`config set` + `.env` fan-out); the docstring carries the implementer contract (MUST debounce — the key field fires per keystroke; secrets via stdin/env never argv; error text redacted before `lastWriteError` renders it); S2 ships `NoopSettingsWriter`; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write — interleaving ceiling ponytail-noted). DesignTokens gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480.
|
||||
- Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). **#136:** `ModelRegistry` (the lenient `~/.hermes/provider_models_cache.json` load, memoized via `loadedDefault`) lives here — the combobox's own data source. `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models, `ZaiKeyType` endpoint families, `SettingsModel` (@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders), `hydrate()` reads each profile's model block IN PARALLEL through the writer's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending write task — 2026-10-28 audit fix, no mid-hydrate stomp); reads only — hydrate never writes), `testConnection(for:)` runs the probe per provider (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectable `writeDebounce`, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach `.env`; tests pass 0); `awaitPendingWrites()` is the tests' sync point; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are igLine truncated
|
||||
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
|
||||
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
|
||||
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//
|
||||
// HermesSettingsWriter.swift
|
||||
// Museion
|
||||
//
|
||||
// #136 (Profiles S3): the real SettingsWriting — surface model blocks via
|
||||
// the engine's own CLI (`hermes -p <profile> config set/unset`, format
|
||||
// owned by Hermes, wire-verified `✓` lines — the provisioner's posture),
|
||||
// provider keys via direct `.env` edit per matching profile (one key fans
|
||||
// out to every profile on that provider, no Keychain — ADR-0014), and the
|
||||
// z.ai key type's endpoint family written through as `model.base_url`.
|
||||
//
|
||||
// Live-probed wire facts (2026-10-27): `config set` prints
|
||||
// `✓ Set <key> = <value> in <path>` exit 0; `config unset` prints
|
||||
// `✓ Unset <key> from <path>` exit 0 and exits 1 with
|
||||
// `Config key not set: <key>` when already absent (idempotent success);
|
||||
// `config get` prints the value exit 0, or the not-set line on stderr
|
||||
// exit 1. Setting `model.provider` CLEARS a stale `model.base_url` — so
|
||||
// the z.ai endpoint is (re)written after the provider, and key writes
|
||||
// write it again (both paths converge on the same value).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// The write-path seam (#135/#136). `HermesSettingsWriter` is the
|
||||
/// production implementation — `hermes -p <profile> config set` for the
|
||||
/// model block (validated keys, format owned by Hermes), `.env` fan-out for
|
||||
/// provider keys (ADR-0014). Contract for implementers (finish-audit
|
||||
/// #135, amended #136): the MODEL coalesces rapid edits per target before
|
||||
/// calling (a superseded write never reaches the writer), but calls still
|
||||
/// arrive tentative — implementations MUST hop off-main internally (the
|
||||
/// CLI rail blocks) and keep surfaced error text free of key-bearing
|
||||
/// content (`lastWriteError` renders verbatim). Secrets never ride argv
|
||||
/// (`ps` reads live command lines).
|
||||
@MainActor
|
||||
protocol SettingsWriting: Sendable {
|
||||
/// `zaiEndpoint`: the z.ai endpoint family when (and only when) the
|
||||
/// config's provider is z.ai — written LAST because setting
|
||||
/// `model.provider` clears a stale `model.base_url` (live-probed).
|
||||
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig, zaiEndpoint: String?) async throws
|
||||
|
||||
/// The key lands in ALL THREE profiles' `.env` (a key entered before
|
||||
/// any surface is on its provider still persists and pre-lands for any
|
||||
/// later switch; inert vars are ignored by hermes for other providers).
|
||||
/// `profiles` gates only the z.ai `base_url` write-through. An empty
|
||||
/// `config.apiKey` leaves `.env` alone — the field sets, never removes.
|
||||
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, profiles: [ProfileSurface]) async throws
|
||||
|
||||
/// The profile's live model block for hydration; nil = unreadable or a
|
||||
/// provider Settings doesn't offer (the surface keeps its seed — never
|
||||
/// stomped by defaults).
|
||||
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)?
|
||||
|
||||
/// The provider's persisted key from the profiles' `.env` (first
|
||||
/// non-empty wins); nil = nothing stored. Hydration fills the key
|
||||
/// fields so a restart doesn't read as "no key" — the probe and the
|
||||
/// masked field ride the STORED truth.
|
||||
func readProviderKey(provider: ModelProvider) async throws -> String?
|
||||
}
|
||||
|
||||
/// The inert writer: previews and pre-gate states; the UI runs over the
|
||||
/// in-memory model.
|
||||
struct NoopSettingsWriter: SettingsWriting {
|
||||
func writeSurface(_: ProfileSurface, config _: SurfaceModelConfig, zaiEndpoint _: String?) async throws {}
|
||||
|
||||
func writeProviderKey(
|
||||
provider _: ModelProvider,
|
||||
config _: ProviderKeyConfig,
|
||||
profiles _: [ProfileSurface],
|
||||
) async throws {}
|
||||
|
||||
func readSurface(_: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
|
||||
nil
|
||||
}
|
||||
|
||||
func readProviderKey(provider _: ModelProvider) async throws -> String? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
struct HermesSettingsWriter: SettingsWriting {
|
||||
let hermesBinary: String?
|
||||
var profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath
|
||||
|
||||
struct WriteError: LocalizedError, Equatable {
|
||||
let message: String
|
||||
var errorDescription: String? {
|
||||
message
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Surface writes (the profile's `model:` block)
|
||||
|
||||
func writeSurface(
|
||||
_ surface: ProfileSurface,
|
||||
config: SurfaceModelConfig,
|
||||
zaiEndpoint: String?,
|
||||
) async throws {
|
||||
guard let hermesBinary else {
|
||||
throw WriteError(message: "hermes binary not found — pass the engine gate first")
|
||||
}
|
||||
let binary = hermesBinary, profile = surface.profileName
|
||||
try await Task.detached(priority: .utility) {
|
||||
// Provider first (switching clears a stale base_url — probed),
|
||||
// then the model, then effort, then the z.ai endpoint family.
|
||||
try Self.setKey("model.provider", config.provider.rawValue, profile: profile, binary: binary, timeout: 30)
|
||||
try Self.setKey("model.default", config.model, profile: profile, binary: binary, timeout: 30)
|
||||
if let effort = config.effort {
|
||||
try Self.setKey("model.reasoning_effort", effort.rawValue, profile: profile, binary: binary, timeout: 30)
|
||||
} else {
|
||||
try Self.unsetKey("model.reasoning_effort", profile: profile, binary: binary, timeout: 30)
|
||||
}
|
||||
if let zaiEndpoint, !zaiEndpoint.isEmpty {
|
||||
try Self.setKey("model.base_url", zaiEndpoint, profile: profile, binary: binary, timeout: 30)
|
||||
}
|
||||
}.value
|
||||
}
|
||||
|
||||
// MARK: Provider keys (.env fan-out + the z.ai endpoint family)
|
||||
|
||||
/// The key upserts into ALL THREE profiles' `.env` (it pre-lands for
|
||||
/// any later provider switch; an EMPTY key leaves `.env` alone — the
|
||||
/// field sets a key, it never removes one). The z.ai endpoint family
|
||||
/// write-through (`model.base_url`, factsheet §1.1) rides only the
|
||||
/// profiles currently on z.ai — a zai endpoint in an anthropic profile
|
||||
/// would be wrong.
|
||||
func writeProviderKey(
|
||||
provider: ModelProvider,
|
||||
config: ProviderKeyConfig,
|
||||
profiles: [ProfileSurface],
|
||||
) async throws {
|
||||
let writesBaseURL = provider == .zai && !config.endpoint.isEmpty
|
||||
if writesBaseURL, hermesBinary == nil {
|
||||
throw WriteError(message: "hermes binary not found — pass the engine gate first")
|
||||
}
|
||||
let root = profileRoot, key = config.apiKey, varName = provider.envVarName
|
||||
let endpoint = writesBaseURL ? config.endpoint : nil
|
||||
let binary = hermesBinary
|
||||
try await Task.detached(priority: .utility) {
|
||||
for surface in ProfileSurface.allCases {
|
||||
let dir = (root as NSString).appendingPathComponent(surface.profileName)
|
||||
if !key.isEmpty {
|
||||
try Self.upsertEnvFile(varName: varName, value: key, profileDir: dir, profile: surface.profileName)
|
||||
}
|
||||
}
|
||||
if let endpoint, let binary {
|
||||
for surface in profiles {
|
||||
try Self.setKey("model.base_url", endpoint, profile: surface.profileName, binary: binary, timeout: 30)
|
||||
}
|
||||
}
|
||||
}.value
|
||||
}
|
||||
|
||||
// MARK: Reads (hydration)
|
||||
|
||||
/// The profile's live `model:` block. nil = unreadable profile or a
|
||||
/// provider Settings doesn't offer (a hand-configured kimi-coding
|
||||
/// surface stays untouched rather than stomped by defaults).
|
||||
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
|
||||
guard let hermesBinary else { return nil }
|
||||
let binary = hermesBinary, profile = surface.profileName
|
||||
return await Task.detached(priority: .utility) { () -> (SurfaceModelConfig, String?)? in
|
||||
func get(_ key: String) -> String? {
|
||||
let run = EngineProbe.execute([binary, "-p", profile, "config", "get", key], timeout: 30)
|
||||
guard run.exitCode == 0 else { return nil } // not set / unknown profile
|
||||
let value = run.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return value.isEmpty ? nil : value
|
||||
}
|
||||
guard let slug = get("model.provider"), let provider = ModelProvider(rawValue: slug) else { return nil }
|
||||
return (
|
||||
SurfaceModelConfig(
|
||||
provider: provider,
|
||||
model: get("model.default") ?? ProfileSurface.defaultModelID,
|
||||
effort: get("model.reasoning_effort").flatMap(ReasoningEffort.init(rawValue:)),
|
||||
),
|
||||
get("model.base_url"),
|
||||
)
|
||||
}.value
|
||||
}
|
||||
|
||||
/// The provider's persisted key: the first non-empty `VAR=` line
|
||||
/// across the profiles' `.env` files (the write landed the same key in
|
||||
/// all of them; one authoritative copy is enough to refill the field).
|
||||
/// File reads only — no CLI spawn.
|
||||
func readProviderKey(provider: ModelProvider) async throws -> String? {
|
||||
let root = profileRoot, varName = provider.envVarName
|
||||
return await Task.detached(priority: .utility) { () -> String? in
|
||||
for surface in ProfileSurface.allCases {
|
||||
let envPath = ((root as NSString).appendingPathComponent(surface.profileName) as NSString)
|
||||
.appendingPathComponent(".env")
|
||||
guard let text = try? String(contentsOfFile: envPath, encoding: .utf8) else { continue }
|
||||
for line in text.split(separator: "\n") where line.hasPrefix("\(varName)=") {
|
||||
let value = line.dropFirst("\(varName)=".count).trimmingCharacters(in: .whitespaces)
|
||||
if !value.isEmpty {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}.value
|
||||
}
|
||||
|
||||
// MARK: CLI rail (wire-verified, the provisioner's posture) — nonisolated:
|
||||
|
||||
// they run inside Task.detached, off the actor.
|
||||
|
||||
private nonisolated static func setKey(
|
||||
_ key: String,
|
||||
_ value: String,
|
||||
profile: String,
|
||||
binary: String,
|
||||
timeout: TimeInterval,
|
||||
) throws {
|
||||
let run = EngineProbe.execute([binary, "-p", profile, "config", "set", key, value], timeout: timeout)
|
||||
guard run.exitCode == 0, run.stdout.contains("✓ Set \(key)") else {
|
||||
throw WriteError(message: "couldn't set \(key) on \(profile): \(excerpt(run))")
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated static func unsetKey(
|
||||
_ key: String,
|
||||
profile: String,
|
||||
binary: String,
|
||||
timeout: TimeInterval,
|
||||
) throws {
|
||||
let run = EngineProbe.execute([binary, "-p", profile, "config", "unset", key], timeout: timeout)
|
||||
// Absent already = the desired state (idempotent; exit 1 + not-set line).
|
||||
let output = run.stdout + run.stderr
|
||||
guard run.stdout.contains("✓ Unset \(key)") || output.contains("Config key not set: \(key)") else {
|
||||
throw WriteError(message: "couldn't unset \(key) on \(profile): \(excerpt(run))")
|
||||
}
|
||||
}
|
||||
|
||||
/// Secrets never ride argv (`ps` reads live command lines) — this rail
|
||||
/// only ever carries provider/model/effort/base_url. Errors keep the
|
||||
/// same guarantee: excerpt content is CLI output, key text never
|
||||
/// reaches `lastWriteError`.
|
||||
private nonisolated static func excerpt(_ run: EngineProbe.ProcessOutput) -> String {
|
||||
let text = run.stdout.isEmpty ? run.stderr : run.stdout
|
||||
return String(text.trimmingCharacters(in: .whitespacesAndNewlines).prefix(300))
|
||||
}
|
||||
|
||||
// MARK: .env edit
|
||||
|
||||
/// Upsert `VAR=value` preserving every other line (hermes' own .env
|
||||
/// header comments and foreign keys survive byte-for-byte). Pure — the
|
||||
/// fan-out tests pin the edges.
|
||||
nonisolated static func upsertEnv(varName: String, value: String, in text: String) -> String {
|
||||
let prefix = "\(varName)="
|
||||
var lines = text.isEmpty
|
||||
? []
|
||||
: text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
||||
if lines.last == "" {
|
||||
lines.removeLast()
|
||||
} // trailing-newline artifact; re-added below
|
||||
lines = lines.filter { !$0.hasPrefix(prefix) }
|
||||
lines.append(prefix + value)
|
||||
return lines.joined(separator: "\n") + "\n"
|
||||
}
|
||||
|
||||
/// 2026-10-28 audit fix: a pasted value containing a line break (or
|
||||
/// NUL) is an env-file injection — "key\nOTHER_VAR=x" would land as a
|
||||
/// real second line in every profile's `.env`. One guard at the shared
|
||||
/// sink; the thrown error rides `lastWriteError`, nothing is written.
|
||||
/// The lock serializes the read→upsert→write across concurrent
|
||||
/// cross-provider key writes (same three files — last writer would
|
||||
/// otherwise drop the other's var).
|
||||
private nonisolated static let envWriteLock = NSLock()
|
||||
|
||||
private nonisolated static func upsertEnvFile(varName: String, value: String, profileDir: String, profile: String) throws {
|
||||
guard !value.contains(where: { $0 == "\n" || $0 == "\r" || $0 == "\0" }) else {
|
||||
throw WriteError(message: "\(varName) value contains a line break — not written")
|
||||
}
|
||||
envWriteLock.lock()
|
||||
defer { envWriteLock.unlock() }
|
||||
let envPath = (profileDir as NSString).appendingPathComponent(".env")
|
||||
let existing = (try? String(contentsOfFile: envPath, encoding: .utf8)) ?? ""
|
||||
let updated = upsertEnv(varName: varName, value: value, in: existing)
|
||||
do {
|
||||
try FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
|
||||
try updated.write(toFile: envPath, atomically: true, encoding: .utf8)
|
||||
// Hermes' own .env files are 0600; a secret we just wrote must
|
||||
// not be group/world-readable (String.write creates 0644).
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: envPath)
|
||||
} catch {
|
||||
throw WriteError(message: "couldn't write \(profile)/.env: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,51 @@
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// Hermes' own picker cache (`~/.hermes/provider_models_cache.json`) — zero
|
||||
/// HTTP, exactly what Hermes accepts (ADR-0014). Lenient by design: a
|
||||
/// missing, unreadable, or foreign-shaped file leaves every model free-text
|
||||
/// (all custom), which is the picker's first-class mode anyway.
|
||||
nonisolated struct ModelRegistry: Sendable {
|
||||
var models: [ModelProvider: [String]] = [:]
|
||||
|
||||
func list(for provider: ModelProvider) -> [String] {
|
||||
models[provider] ?? []
|
||||
}
|
||||
|
||||
/// Cache shape: `{provider: {fp, at, models: [ids]}}`. Lenient per the
|
||||
/// DECODE, not per entry: unknown provider slugs are skipped, but any
|
||||
/// foreign shape inside a known provider's entry (a non-string models
|
||||
/// element) fails the whole decode and the registry degrades to
|
||||
/// free-text-only — the picker's first-class mode anyway.
|
||||
static func load(path: String = ("~/.hermes/provider_models_cache.json" as NSString).expandingTildeInPath) -> ModelRegistry {
|
||||
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
|
||||
return ModelRegistry()
|
||||
}
|
||||
struct Entry: Decodable {
|
||||
let models: [String]?
|
||||
}
|
||||
guard let parsed = try? JSONDecoder().decode([String: Entry].self, from: data) else {
|
||||
return ModelRegistry()
|
||||
}
|
||||
var registry = ModelRegistry()
|
||||
for (slug, entry) in parsed {
|
||||
if let provider = ModelProvider(rawValue: slug) {
|
||||
registry.models[provider] = entry.models ?? []
|
||||
}
|
||||
}
|
||||
return registry
|
||||
}
|
||||
|
||||
/// The default load, memoized — `SettingsModel()` runs its default
|
||||
/// arguments on every SwiftUI construction of the pane, so the disk read
|
||||
/// + decode must happen once. ponytail: refreshed on next launch, not
|
||||
/// live.
|
||||
static let loadedDefault = ModelRegistry.load()
|
||||
}
|
||||
|
||||
struct ModelComboBox: NSViewRepresentable {
|
||||
/// The committed model id (the model's truth; the box echoes it).
|
||||
var value: String
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
//
|
||||
// ProviderProbe.swift
|
||||
// Museion
|
||||
//
|
||||
// #136 (Profiles S3): Test Connection — the factsheet §4 two-step probe
|
||||
// per provider: (1) GET /models = key validity + reachability (on z.ai it
|
||||
// proves nothing about key-type/endpoint pairing, §1.2), (2) a minimal
|
||||
// streaming chat call (max_tokens ≈ 64, "hi") proving key × endpoint ×
|
||||
// model actually generates. Decoding is honest per the factsheet: HTTP
|
||||
// status + provider error envelope, z.ai 1113 → wrong key type for this
|
||||
// endpoint family, `finish=length` + empty content → raise the cap — never
|
||||
// gated on status 200 alone (§1.5 starvation is a 200).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
nonisolated enum ProviderProbe {
|
||||
/// What one probe needs: the provider dialect, endpoint base URL, key,
|
||||
/// and the model the chat step proves generation on (a surface's model —
|
||||
/// what the writer actually configures).
|
||||
struct Config: Sendable, Equatable {
|
||||
var provider: ModelProvider
|
||||
var endpoint: String
|
||||
var apiKey: String
|
||||
var model: String
|
||||
}
|
||||
|
||||
/// The honest verdicts (factsheet §1.6/§2.5/§3.5). `works` carries the
|
||||
/// chat latency (ms) and the /models count.
|
||||
enum Outcome: Equatable, Sendable {
|
||||
case works(latencyMS: Int, modelCount: Int)
|
||||
case authFailed(String)
|
||||
case wrongKeyType(String)
|
||||
case unreachable(String)
|
||||
/// 200 + finish=length/stop_reason=max_tokens with no content — the
|
||||
/// cap starved reasoning (§1.5); not "the model broke".
|
||||
case starved(String)
|
||||
case requestFailed(status: Int, detail: String)
|
||||
}
|
||||
|
||||
/// One HTTP round trip: (body, response). Injected in tests with canned
|
||||
/// bodies; production buffers the streamed response (the request still
|
||||
/// carries `stream: true` — the wire shape the app's engines use).
|
||||
typealias Transport = @Sendable (_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
|
||||
|
||||
static let urlSessionTransport: Transport = { request in
|
||||
let (data, response) = try await URLSession.shared.data(for: request)
|
||||
guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
|
||||
return (data, http)
|
||||
}
|
||||
|
||||
/// The two-step probe. Step 1 failure short-circuits (an unreachable or
|
||||
/// rejected key on /models needs no chat call); step 2 is the real
|
||||
/// key × endpoint × model proof.
|
||||
static func probe(_ config: Config, transport: Transport = urlSessionTransport) async -> Outcome {
|
||||
guard !config.apiKey.isEmpty else {
|
||||
return .authFailed("no API key set — paste the key first")
|
||||
}
|
||||
let step = await stepModels(config, transport: transport)
|
||||
if let failure = step.failure {
|
||||
return failure
|
||||
}
|
||||
let modelCount = step.count ?? 0
|
||||
guard let chatRequest = makeChatRequest(config) else {
|
||||
return .unreachable("endpoint is not a valid URL")
|
||||
}
|
||||
let started = Date()
|
||||
do {
|
||||
let (data, response) = try await transport(chatRequest)
|
||||
let elapsed = Int(Date().timeIntervalSince(started) * 1000)
|
||||
guard (200 ..< 300).contains(response.statusCode) else {
|
||||
return decodeError(status: response.statusCode, body: data, provider: config.provider)
|
||||
}
|
||||
return decodeChat(provider: config.provider, body: data, modelCount: modelCount, latencyMS: elapsed)
|
||||
} catch {
|
||||
return .unreachable(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Requests (factsheet §1–§3 wire shapes)
|
||||
|
||||
/// The z.ai chat call pins the stable GLM-5.x wire format (§1.5):
|
||||
/// thinking enabled + explicit effort (`low` keeps thinking minimal).
|
||||
/// OpenAI speaks the RESPONSES API (2026-10-28 maintainer correction:
|
||||
/// `POST /v1/responses`, `input`, `max_output_tokens` — the
|
||||
/// chat-completions dialect is the retired path); Anthropic requires
|
||||
/// `max_tokens` and auths via header, never Bearer. The cap is 512
|
||||
/// everywhere — the live 2026-10-28 tail proved 64 starves reasoning
|
||||
/// models (glm-5.3: reasoning_tokens 64/64, finish=length, zero
|
||||
/// content), so the factsheet's "≈64" would always read starved.
|
||||
static func makeChatRequest(_ config: Config) -> URLRequest? {
|
||||
guard let url = chatURL(for: config.provider, endpoint: config.endpoint) else { return nil }
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = "POST"
|
||||
request.timeoutInterval = 30
|
||||
// 2026-10-28 live incident: without this header URLSession defaults
|
||||
// the request to x-www-form-urlencoded — z.ai answers HTTP 200 with
|
||||
// an error envelope (content type not supported), OpenAI can't
|
||||
// parse the body ("you must provide a model parameter"). curl set
|
||||
// it; the app didn't. Anthropic tolerated the omission.
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
let user: [String: Any] = ["role": "user", "content": "hi"]
|
||||
var body: [String: Any] = ["model": config.model, "stream": true]
|
||||
switch config.provider {
|
||||
case .zai:
|
||||
body["messages"] = [user]
|
||||
body["max_tokens"] = Self.probeTokenCap
|
||||
body["thinking"] = ["type": "enabled"]
|
||||
body["reasoning_effort"] = "low"
|
||||
case .openaiAPI:
|
||||
body["input"] = "hi"
|
||||
body["max_output_tokens"] = Self.probeTokenCap
|
||||
case .anthropic:
|
||||
body["messages"] = [user]
|
||||
body["max_tokens"] = Self.probeTokenCap // required
|
||||
}
|
||||
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
|
||||
applyAuth(&request, provider: config.provider, key: config.apiKey)
|
||||
return request
|
||||
}
|
||||
|
||||
/// The probe's token cap — generous enough that a reasoning model's
|
||||
/// thinking can't starve it (the failure mode is real: 64 burned
|
||||
/// entirely on glm-5.3 reasoning), small enough to stay cents.
|
||||
static let probeTokenCap = 512
|
||||
|
||||
static func makeModelsRequest(_ config: Config) -> URLRequest? {
|
||||
guard let url = modelsURL(for: config.provider, endpoint: config.endpoint) else { return nil }
|
||||
var request = URLRequest(url: url)
|
||||
request.timeoutInterval = 20
|
||||
applyAuth(&request, provider: config.provider, key: config.apiKey)
|
||||
return request
|
||||
}
|
||||
|
||||
/// z.ai's endpoint carries its version segment already (`…/paas/v4`);
|
||||
/// Anthropic's base is bare and appends `/v1`; OpenAI speaks the
|
||||
/// Responses API (`/v1/responses`, 2026-10-28 maintainer correction —
|
||||
/// chat-completions is the retired path). A trailing slash on a
|
||||
/// hand-edited endpoint never doubles up. A non-URL endpoint is nil
|
||||
/// (URL(string:) happily percent-encodes "not a url" — the scheme check
|
||||
/// is what actually rejects garbage; probe reports unreachable, never
|
||||
/// traps).
|
||||
static func chatURL(for provider: ModelProvider, endpoint: String) -> URL? {
|
||||
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
|
||||
let path = switch provider {
|
||||
case .anthropic: "/v1/messages"
|
||||
case .openaiAPI: "/responses"
|
||||
case .zai: "/chat/completions"
|
||||
}
|
||||
return httpURL(base + path)
|
||||
}
|
||||
|
||||
static func modelsURL(for provider: ModelProvider, endpoint: String) -> URL? {
|
||||
let base = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
|
||||
let path = provider == .anthropic ? "/v1/models" : "/models"
|
||||
return httpURL(base + path)
|
||||
}
|
||||
|
||||
private static func httpURL(_ string: String) -> URL? {
|
||||
guard let url = URL(string: string), let scheme = url.scheme?.lowercased(),
|
||||
scheme == "http" || scheme == "https", url.host != nil
|
||||
else { return nil }
|
||||
return url
|
||||
}
|
||||
|
||||
/// Bearer everywhere except Anthropic: `x-api-key` + a pinned
|
||||
/// `anthropic-version` (factsheet §2.1 — never send none).
|
||||
static func applyAuth(_ request: inout URLRequest, provider: ModelProvider, key: String) {
|
||||
switch provider {
|
||||
case .zai, .openaiAPI:
|
||||
request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
|
||||
case .anthropic:
|
||||
request.setValue(key, forHTTPHeaderField: "x-api-key")
|
||||
request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Step 1 — models (key validity + reachability)
|
||||
|
||||
private static func stepModels(_ config: Config, transport: Transport) async -> (count: Int?, failure: Outcome?) {
|
||||
guard let request = makeModelsRequest(config) else {
|
||||
return (nil, .unreachable("endpoint is not a valid URL"))
|
||||
}
|
||||
do {
|
||||
let (data, response) = try await transport(request)
|
||||
guard (200 ..< 300).contains(response.statusCode) else {
|
||||
return (nil, decodeError(status: response.statusCode, body: data, provider: config.provider))
|
||||
}
|
||||
// A foreign-shaped 200 still lets the chat step run — /models is
|
||||
// the prelude, the chat call is the proof (§1.2).
|
||||
return (decodeModelsCount(data) ?? 0, nil)
|
||||
} catch {
|
||||
return (nil, .unreachable(error.localizedDescription))
|
||||
}
|
||||
}
|
||||
|
||||
/// All three listings put the entries in `data: []`.
|
||||
static func decodeModelsCount(_ data: Data) -> Int? {
|
||||
guard let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let entries = parsed["data"] as? [Any]
|
||||
else { return nil }
|
||||
return entries.count
|
||||
}
|
||||
|
||||
// MARK: Decode — the factsheet cases (pure; unit-pinned)
|
||||
|
||||
/// Maps an HTTP error envelope to the honest verdict: z.ai
|
||||
/// `error.code` (1113 = wrong key type for this endpoint family, 401 =
|
||||
/// auth), Anthropic `error.type` + `request_id`, OpenAI `error.code`.
|
||||
static func decodeError(status: Int, body: Data, provider: ModelProvider) -> Outcome {
|
||||
let root = (try? JSONSerialization.jsonObject(with: body)).flatMap { $0 as? [String: Any] }
|
||||
return decodeErrorRoot(status: status, root: root ?? [:], provider: provider)
|
||||
}
|
||||
|
||||
/// The same decode over an already-parsed envelope — the SSE path
|
||||
/// holds the parsed object, no serialize-then-reparse round trip.
|
||||
private static func decodeErrorRoot(status: Int, root: [String: Any], provider: ModelProvider) -> Outcome {
|
||||
let envelope = (root["error"] as? [String: Any]) ?? [:]
|
||||
let code = envelope["code"] as? String ?? ""
|
||||
let type = envelope["type"] as? String ?? ""
|
||||
let message = (envelope["message"] as? String) ?? "HTTP \(status)"
|
||||
let requestID = (root["request_id"] as? String).map { " (request \($0))" } ?? ""
|
||||
|
||||
if provider == .zai, code == "1113" {
|
||||
return .wrongKeyType("z.ai 1113 — wrong key type for this endpoint family; switch the key type")
|
||||
}
|
||||
if status == 401 || code == "401" || code == "invalid_api_key" || type == "authentication_error" {
|
||||
return .authFailed(message + requestID)
|
||||
}
|
||||
return .requestFailed(status: status, detail: message + requestID)
|
||||
}
|
||||
|
||||
/// A 2xx chat response: SSE events (the request streamed). Content
|
||||
/// arrived → works; the finish marker says length/max_tokens/
|
||||
/// incomplete with no content → starved; no content at all →
|
||||
/// requestFailed (never a silent "works" on an empty 200, §4.4).
|
||||
/// HTTP 200 can also CARRY the provider's error — live 2026-10-28: z.ai
|
||||
/// answers a wrong content-type as 200 + a plain-JSON error envelope —
|
||||
/// so the envelope decodes before any no-content fallback.
|
||||
static func decodeChat(provider: ModelProvider, body: Data, modelCount: Int, latencyMS: Int) -> Outcome {
|
||||
let raw = String(bytes: body, encoding: .utf8) ?? ""
|
||||
let events = ssePayloads(raw)
|
||||
if let failure = errorEnvelope(in: events, rawBody: body, provider: provider) {
|
||||
return failure
|
||||
}
|
||||
let (text, finish): (String, String?)
|
||||
switch provider {
|
||||
case .anthropic: (text, finish) = anthropicStream(events)
|
||||
case .openaiAPI: (text, finish) = responsesStream(events)
|
||||
case .zai: (text, finish) = chatCompletionsStream(events)
|
||||
}
|
||||
if !text.isEmpty {
|
||||
return .works(latencyMS: latencyMS, modelCount: modelCount)
|
||||
}
|
||||
if finish == "length" || finish == "max_tokens" || finish == "incomplete" {
|
||||
return .starved("finish=\(finish!) with empty content — raise the token cap")
|
||||
}
|
||||
return .requestFailed(status: 200, detail: "no content (finish=\(finish ?? "none"))")
|
||||
}
|
||||
|
||||
/// Errors riding a 2xx: an `error` OBJECT in any SSE event (OpenAI
|
||||
/// Responses nests it under `response.error` — and every response
|
||||
/// snapshot carries `"error": null`, which is NOT an error), or the
|
||||
/// whole body as a plain-JSON envelope (z.ai's 200 content-type
|
||||
/// rejection) — routed through the same decoder as HTTP errors.
|
||||
private static func errorEnvelope(in events: [JSONValue], rawBody: Data, provider: ModelProvider) -> Outcome? {
|
||||
for event in events {
|
||||
guard case let .object(obj) = event else { continue }
|
||||
var envelope = obj
|
||||
if !isError(obj["error"]), case let .object(response)? = obj["response"] {
|
||||
envelope = response // response.failed carries response.error
|
||||
}
|
||||
guard isError(envelope["error"]),
|
||||
let root = JSONValue.object(envelope).any as? [String: Any]
|
||||
else { continue }
|
||||
return decodeErrorRoot(status: 200, root: root, provider: provider)
|
||||
}
|
||||
if let parsed = try? JSONSerialization.jsonObject(with: rawBody) as? [String: Any], parsed["error"] is [String: Any] {
|
||||
return decodeErrorRoot(status: 200, root: parsed, provider: provider)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// JSON null isn't nil — OpenAI's response snapshots carry `"error":
|
||||
/// null` on every event; only a real error object counts (2026-10-28
|
||||
/// dogfood: the null tripped the check and a healthy stream decoded as
|
||||
/// "HTTP 200").
|
||||
private static func isError(_ value: JSONValue?) -> Bool {
|
||||
if case .object = value {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Anthropic SSE: `content_block_delta.delta.text_delta` carries text,
|
||||
/// `message_delta.delta.stop_reason` the finish marker.
|
||||
private static func anthropicStream(_ events: [JSONValue]) -> (text: String, finish: String?) {
|
||||
var text = ""
|
||||
var finish: String?
|
||||
for event in events {
|
||||
guard case let .object(obj) = event, case let .object(delta)? = obj["delta"] else { continue }
|
||||
if delta["type"] == .string("text_delta"), case let .string(chunk)? = delta["text"] {
|
||||
text += chunk
|
||||
}
|
||||
if case let .string(reason)? = delta["stop_reason"] {
|
||||
finish = reason
|
||||
}
|
||||
}
|
||||
return (text, finish)
|
||||
}
|
||||
|
||||
/// z.ai SSE (chat-completions dialect): `choices[0].delta.content`
|
||||
/// carries text (the reasoning side-channel is ignored), the last
|
||||
/// non-null `choices[0].finish_reason` the finish marker; usage chunks
|
||||
/// carry an empty `choices` array and skip through.
|
||||
private static func chatCompletionsStream(_ events: [JSONValue]) -> (text: String, finish: String?) {
|
||||
var text = ""
|
||||
var finish: String?
|
||||
for event in events {
|
||||
guard case let .object(obj) = event,
|
||||
case let .array(choices)? = obj["choices"],
|
||||
case let .object(choice)? = choices.first
|
||||
else { continue }
|
||||
if case let .object(delta) = choice["delta"], case let .string(chunk)? = delta["content"] {
|
||||
text += chunk
|
||||
}
|
||||
if case let .string(reason)? = choice["finish_reason"] {
|
||||
finish = reason
|
||||
}
|
||||
}
|
||||
return (text, finish)
|
||||
}
|
||||
|
||||
/// OpenAI Responses SSE: `response.output_text.delta` events carry text
|
||||
/// (`.delta` string); the closing `response.completed`/`incomplete`/
|
||||
/// `failed` events carry `response.status`.
|
||||
private static func responsesStream(_ events: [JSONValue]) -> (text: String, finish: String?) {
|
||||
var text = ""
|
||||
var finish: String?
|
||||
for event in events {
|
||||
guard case let .object(obj) = event else { continue }
|
||||
if obj["type"] == .string("response.output_text.delta"), case let .string(chunk)? = obj["delta"] {
|
||||
text += chunk
|
||||
}
|
||||
if case let .object(response)? = obj["response"], case let .string(status)? = response["status"] {
|
||||
finish = status
|
||||
}
|
||||
}
|
||||
return (text, finish)
|
||||
}
|
||||
|
||||
/// SSE event payloads: `data: {…}` lines as JSON values. `data:
|
||||
/// [DONE]`, `event:` lines, and blanks are not payloads.
|
||||
static func ssePayloads(_ text: String) -> [JSONValue] {
|
||||
var payloads: [JSONValue] = []
|
||||
for line in text.split(separator: "\n") {
|
||||
guard line.hasPrefix("data:") else { continue }
|
||||
let payload = line.dropFirst("data:".count).trimmingCharacters(in: .whitespaces)
|
||||
guard payload != "[DONE]", !payload.isEmpty,
|
||||
let data = payload.data(using: .utf8),
|
||||
let parsed = try? JSONSerialization.jsonObject(with: data)
|
||||
else { continue }
|
||||
payloads.append(JSONValue(parsed))
|
||||
}
|
||||
return payloads
|
||||
}
|
||||
}
|
||||
+150
-97
@@ -5,8 +5,14 @@
|
||||
// #135 (Profiles S2): the Settings page's in-memory model + the injectable
|
||||
// write-path protocol. Per ADR-0014 the per-surface model block IS each
|
||||
// Hermes profile's `model:` block and provider keys fan out to every
|
||||
// profile on that provider — persistence lands with S3 over this seam;
|
||||
// S2 ships a no-op writer.
|
||||
// profile on that provider.
|
||||
//
|
||||
// #136 (Profiles S3): the real write path — HermesSettingsWriter (CLI
|
||||
// rail + .env fan-out) is the production writer; the model hydrates from
|
||||
// the profiles at pane open, COALESCES rapid edits per target (the key
|
||||
// field fires per keystroke — a superseded write is canceled before it
|
||||
// ever spawns, so partial key prefixes never reach `.env`), and runs the
|
||||
// Test Connection probe per provider.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@@ -38,12 +44,14 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
|
||||
}
|
||||
|
||||
/// The model a provider switch lands on (prototype #130's pinned
|
||||
/// flagships — registry order is capability-sorted, not default-sorted).
|
||||
/// flagships — registry order is capability-sorted, not default-sorted;
|
||||
/// #136 dogfood: OpenAI's flagship is gpt-6.1-sol, the current
|
||||
/// Responses-era default).
|
||||
var switchDefaultModel: String {
|
||||
switch self {
|
||||
case .zai: "glm-5.3"
|
||||
case .anthropic: "claude-sonnet-5"
|
||||
case .openaiAPI: "gpt-5.6-sol"
|
||||
case .openaiAPI: "gpt-6.1-sol"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +63,17 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
|
||||
case .openaiAPI: "https://api.openai.com/v1"
|
||||
}
|
||||
}
|
||||
|
||||
/// #136: the `.env` var Hermes' own provider registry maps each slug to
|
||||
/// (`hermes_cli/auth.py` live-read): zai→GLM_API_KEY (ZAI_/Z_AI_ are
|
||||
/// aliases), anthropic→ANTHROPIC_API_KEY, openai-api→OPENAI_API_KEY.
|
||||
var envVarName: String {
|
||||
switch self {
|
||||
case .zai: "GLM_API_KEY"
|
||||
case .anthropic: "ANTHROPIC_API_KEY"
|
||||
case .openaiAPI: "OPENAI_API_KEY"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable {
|
||||
@@ -110,76 +129,11 @@ nonisolated struct ProviderKeyConfig: Equatable, Sendable {
|
||||
var apiKey: String = ""
|
||||
}
|
||||
|
||||
/// Hermes' own picker cache (`~/.hermes/provider_models_cache.json`) — zero
|
||||
/// HTTP, exactly what Hermes accepts (ADR-0014). Lenient by design: a
|
||||
/// missing, unreadable, or foreign-shaped file leaves every model free-text
|
||||
/// (all custom), which is the picker's first-class mode anyway.
|
||||
nonisolated struct ModelRegistry: Sendable {
|
||||
var models: [ModelProvider: [String]] = [:]
|
||||
|
||||
func list(for provider: ModelProvider) -> [String] {
|
||||
models[provider] ?? []
|
||||
}
|
||||
|
||||
/// Cache shape: `{provider: {fp, at, models: [ids]}}`. Lenient per the
|
||||
/// DECODE, not per entry: unknown provider slugs are skipped, but any
|
||||
/// foreign shape inside a known provider's entry (a non-string models
|
||||
/// element) fails the whole decode and the registry degrades to
|
||||
/// free-text-only — the picker's first-class mode anyway.
|
||||
static func load(path: String = ("~/.hermes/provider_models_cache.json" as NSString).expandingTildeInPath) -> ModelRegistry {
|
||||
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
|
||||
return ModelRegistry()
|
||||
}
|
||||
struct Entry: Decodable {
|
||||
let models: [String]?
|
||||
}
|
||||
guard let parsed = try? JSONDecoder().decode([String: Entry].self, from: data) else {
|
||||
return ModelRegistry()
|
||||
}
|
||||
var registry = ModelRegistry()
|
||||
for (slug, entry) in parsed {
|
||||
if let provider = ModelProvider(rawValue: slug) {
|
||||
registry.models[provider] = entry.models ?? []
|
||||
}
|
||||
}
|
||||
return registry
|
||||
}
|
||||
|
||||
/// The default load, memoized — `SettingsModel()` runs its default
|
||||
/// arguments on every SwiftUI construction of the pane, so the disk read
|
||||
/// + decode must happen once. ponytail: refreshed on next launch, not
|
||||
/// live; S3 lifts persistence anyway.
|
||||
static let loadedDefault = ModelRegistry.load()
|
||||
}
|
||||
|
||||
/// The write-path seam (#135). S3 implements this against the Hermes CLI
|
||||
/// (`hermes -p <profile> config set` for the model block, `.env` fan-out
|
||||
/// for provider keys — ADR-0014); implementations own batching/debounce and
|
||||
/// hop off-main internally when the rail needs it. Contract for implementers
|
||||
/// (finish-audit #135): in-flight edits are TENTATIVE — implementations MUST
|
||||
/// debounce writes (the key field fires per keystroke; persisting every
|
||||
/// partial prefix of a secret to `.env` leaks key material through later
|
||||
/// overwrites). Secrets travel via stdin or the child's environment, never
|
||||
/// argv (`ps` reads live command lines), and surfaced error text must be
|
||||
/// redacted of key-bearing content (lastWriteError renders verbatim).
|
||||
@MainActor
|
||||
protocol SettingsWriting {
|
||||
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig) async throws
|
||||
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, keyType: ZaiKeyType?) async throws
|
||||
}
|
||||
|
||||
/// S2's inert writer: persistence is S3's job; the UI runs over the
|
||||
/// in-memory model meanwhile.
|
||||
struct NoopSettingsWriter: SettingsWriting {
|
||||
func writeSurface(_: ProfileSurface, config _: SurfaceModelConfig) async throws {}
|
||||
|
||||
func writeProviderKey(provider _: ModelProvider, config _: ProviderKeyConfig, keyType _: ZaiKeyType?) async throws {}
|
||||
}
|
||||
|
||||
/// The Settings page's state (#135): per-surface model configs, per-provider
|
||||
/// keys, the registry the model combobox reads, and the write path every
|
||||
/// committed change flows through. Pane-local for S2 — S3 lifts it to
|
||||
/// AppGateState when persistence lands.
|
||||
/// committed change flows through. #136: hydrated from the profiles at pane
|
||||
/// open; pane-local still — the AppGateState lift waits on the
|
||||
/// restart-on-change slice.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class SettingsModel {
|
||||
@@ -187,18 +141,28 @@ final class SettingsModel {
|
||||
private(set) var keys: [ModelProvider: ProviderKeyConfig]
|
||||
private(set) var zaiKeyType: ZaiKeyType = .standard
|
||||
private(set) var registry: ModelRegistry
|
||||
/// Write failures land here — the honest strip (S3's rail can fail).
|
||||
/// Write failures land here — the honest strip (the CLI rail can fail).
|
||||
private(set) var lastWriteError: String?
|
||||
/// #136: Test Connection state per provider (the Provider Keys page).
|
||||
private(set) var testStates: [ModelProvider: TestState] = [:]
|
||||
|
||||
private let writer: any SettingsWriting
|
||||
/// Rapid edits per target coalesce: a newer write cancels the older
|
||||
/// task during its debounce window (the key field fires per keystroke —
|
||||
/// a partial prefix of a secret must never reach `.env`). Tests pass 0.
|
||||
private let writeDebounce: TimeInterval
|
||||
private var surfaceTasks: [ProfileSurface: Task<Void, Never>] = [:]
|
||||
private var keyTasks: [ModelProvider: Task<Void, Never>] = [:]
|
||||
|
||||
init(
|
||||
registry: ModelRegistry = .loadedDefault,
|
||||
writer: any SettingsWriting = NoopSettingsWriter(),
|
||||
surfaces: [ProfileSurface: SurfaceModelConfig]? = nil,
|
||||
writeDebounce: TimeInterval = 0.35,
|
||||
) {
|
||||
self.registry = registry
|
||||
self.writer = writer
|
||||
self.writeDebounce = writeDebounce
|
||||
self.surfaces = surfaces
|
||||
?? Dictionary(uniqueKeysWithValues: ProfileSurface.allCases.map { ($0, .surfaceDefault) })
|
||||
keys = Dictionary(
|
||||
@@ -232,6 +196,48 @@ final class SettingsModel {
|
||||
return !registry.list(for: config.provider).contains(config.model)
|
||||
}
|
||||
|
||||
/// #136: hydration — each profile's live `model:` block, read in
|
||||
/// parallel through the writer's CLI rail (format owned by Hermes).
|
||||
/// Surfaces on providers Settings doesn't offer stay seeded (their
|
||||
/// config is the user's, not ours to rewrite); a z.ai profile pinned to
|
||||
/// the coding endpoint infers the key type. Keys persist in the
|
||||
/// fanned-out `.env` files — they're read back too, so a restart
|
||||
/// neither blanks the fields nor refuses Test Connection. Reads only —
|
||||
/// hydrate never writes.
|
||||
func hydrate() async {
|
||||
let writer = writer
|
||||
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
|
||||
for surface in ProfileSurface.allCases {
|
||||
group.addTask { await (surface, try? writer.readSurface(surface)) }
|
||||
}
|
||||
for await (surface, read) in group {
|
||||
guard let read else { continue }
|
||||
// An edit that fired while this read was in flight owns the
|
||||
// truth — applying the stale read would revert the UI and
|
||||
// the next edit would persist from the stale base.
|
||||
guard surfaceTasks[surface] == nil else { continue }
|
||||
surfaces[surface] = read.config
|
||||
if read.config.provider == .zai {
|
||||
if read.baseURL == ZaiKeyType.coding.endpoint {
|
||||
zaiKeyType = .coding
|
||||
keys[.zai]?.endpoint = ZaiKeyType.coding.endpoint
|
||||
} else if let baseURL = read.baseURL, !baseURL.isEmpty, baseURL != ZaiKeyType.standard.endpoint {
|
||||
// A custom zai base_url (hand-edited, or a family
|
||||
// Settings doesn't model) survives hydration — the
|
||||
// next zai write-through threads it, never a default.
|
||||
keys[.zai]?.endpoint = baseURL
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for provider in ModelProvider.allCases {
|
||||
guard keyTasks[provider] == nil else { continue }
|
||||
if let key = try? await writer.readProviderKey(provider: provider), !key.isEmpty {
|
||||
keys[provider]?.apiKey = key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A provider switch lands on that provider's pinned default model with
|
||||
/// effort reset (each provider's ladder differs; the writer should see
|
||||
/// intent, not residue).
|
||||
@@ -243,6 +249,9 @@ final class SettingsModel {
|
||||
config.effort = nil
|
||||
surfaces[surface] = config
|
||||
persist(surface, config)
|
||||
// No key re-fire: key writes land in ALL THREE .env files, so the
|
||||
// key pre-landed before any switch (the zai endpoint family rides
|
||||
// the surface write's zaiEndpoint).
|
||||
}
|
||||
|
||||
func setModel(_ model: String, for surface: ProfileSurface) {
|
||||
@@ -295,51 +304,95 @@ final class SettingsModel {
|
||||
persistKey(provider)
|
||||
}
|
||||
|
||||
/// Fire-and-forget: the UI never blocks on writes; failures surface in
|
||||
/// `lastWriteError` (LearningsPane's strip posture), cleared by the next
|
||||
/// SUCCESSFUL write — not optimistically at commit.
|
||||
/// ponytail: interleaved writes are unordered — an older write failing
|
||||
/// after a newer one succeeded leaves its error up; a write-generation
|
||||
/// token fixes it if S3's real writers ever interleave.
|
||||
private var pendingWrites: [Task<Void, Never>] = []
|
||||
// MARK: Test Connection (#136 — factsheet §4)
|
||||
|
||||
enum TestState: Equatable {
|
||||
case running
|
||||
case done(ProviderProbe.Outcome)
|
||||
}
|
||||
|
||||
/// One probe per provider over the CURRENT key/endpoint state. Guarded
|
||||
/// against stacking; the empty-key precondition makes an unkeyed probe
|
||||
/// fail fast without touching the network.
|
||||
func testConnection(for provider: ModelProvider) async {
|
||||
guard testStates[provider] != .running else { return }
|
||||
testStates[provider] = .running
|
||||
let keyConfig = keyConfig(for: provider)
|
||||
let config = ProviderProbe.Config(
|
||||
provider: provider,
|
||||
endpoint: keyConfig.endpoint,
|
||||
apiKey: keyConfig.apiKey,
|
||||
model: probeModel(for: provider),
|
||||
)
|
||||
testStates[provider] = await .done(ProviderProbe.probe(config))
|
||||
}
|
||||
|
||||
/// The model the probe proves generation on: the first surface on this
|
||||
/// provider (what the writer actually configures), else the provider's
|
||||
/// pinned flagship.
|
||||
func probeModel(for provider: ModelProvider) -> String {
|
||||
for surface in ProfileSurface.allCases where config(for: surface).provider == provider {
|
||||
return config(for: surface).model
|
||||
}
|
||||
return provider.switchDefaultModel
|
||||
}
|
||||
|
||||
// MARK: Write plumbing
|
||||
|
||||
/// Awaits in-flight writes — the tests' deterministic sync point.
|
||||
func awaitPendingWrites() async {
|
||||
for task in pendingWrites {
|
||||
let tasks = Array(surfaceTasks.values) + Array(keyTasks.values)
|
||||
for task in tasks {
|
||||
await task.value
|
||||
}
|
||||
pendingWrites.removeAll()
|
||||
}
|
||||
|
||||
// ponytail: finished tasks are only reference-hygiene; cap, don't track.
|
||||
private func track(_ task: Task<Void, Never>) {
|
||||
pendingWrites.append(task)
|
||||
if pendingWrites.count > 64 {
|
||||
pendingWrites.removeFirst(pendingWrites.count - 64)
|
||||
}
|
||||
surfaceTasks.removeAll()
|
||||
keyTasks.removeAll()
|
||||
}
|
||||
|
||||
private func persist(_ surface: ProfileSurface, _ config: SurfaceModelConfig) {
|
||||
track(Task {
|
||||
let zaiEndpoint = config.provider == .zai ? keyConfig(for: .zai).endpoint : nil
|
||||
let previous = surfaceTasks[surface]
|
||||
previous?.cancel()
|
||||
surfaceTasks[surface] = Task { [writeDebounce] in
|
||||
if writeDebounce > 0 {
|
||||
try? await Task.sleep(for: .seconds(writeDebounce))
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
// Cancellation can't stop a past-the-guard CLI write, so the
|
||||
// newer write WAITS — the last edit is always the last write to
|
||||
// land (2026-10-28 audit fix).
|
||||
await previous?.value
|
||||
guard !Task.isCancelled else { return }
|
||||
do {
|
||||
try await writer.writeSurface(surface, config: config)
|
||||
try await writer.writeSurface(surface, config: config, zaiEndpoint: zaiEndpoint)
|
||||
lastWriteError = nil
|
||||
} catch {
|
||||
lastWriteError = error.localizedDescription
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private func persistKey(_ provider: ModelProvider) {
|
||||
let config = keyConfig(for: provider)
|
||||
let keyType = provider == .zai ? zaiKeyType : nil
|
||||
track(Task {
|
||||
// The zai base_url write-through targets: surfaces currently on
|
||||
// this provider (the KEY lands in all three .env files regardless).
|
||||
let profiles = ProfileSurface.allCases.filter { surfaces[$0]?.provider == provider }
|
||||
let previous = keyTasks[provider]
|
||||
previous?.cancel()
|
||||
keyTasks[provider] = Task { [writeDebounce] in
|
||||
if writeDebounce > 0 {
|
||||
try? await Task.sleep(for: .seconds(writeDebounce))
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
// Same contract as persist: wait out the in-flight predecessor.
|
||||
await previous?.value
|
||||
guard !Task.isCancelled else { return }
|
||||
do {
|
||||
try await writer.writeProviderKey(provider: provider, config: config, keyType: keyType)
|
||||
try await writer.writeProviderKey(provider: provider, config: config, profiles: profiles)
|
||||
lastWriteError = nil
|
||||
} catch {
|
||||
lastWriteError = error.localizedDescription
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,32 @@ private struct ProviderKeyBlock: View {
|
||||
.font(.system(size: 11.5))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
// #136: Test Connection (factsheet §4) — /models count + a
|
||||
// minimal streaming chat; latency + model count on success,
|
||||
// the honest decoded verdict otherwise.
|
||||
HStack(spacing: 8) {
|
||||
Button("Test Connection") {
|
||||
Task { await model.testConnection(for: provider) }
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.controlSize(.small)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.disabled(model.testStates[provider] == .running)
|
||||
switch model.testStates[provider] {
|
||||
case .running:
|
||||
HStack(spacing: 4) {
|
||||
ProgressView()
|
||||
.controlSize(.small)
|
||||
Text("testing…")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
case let .done(outcome):
|
||||
TestConnectionResult(outcome: outcome)
|
||||
case nil:
|
||||
EmptyView()
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16))
|
||||
.background(
|
||||
@@ -233,6 +259,41 @@ private struct ProviderKeyBlock: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe's one-line verdict (#136): works carries latency + model
|
||||
/// count; every failure states its decoded reason (the AC's
|
||||
/// wrong-key-type vs unreachable vs works distinction).
|
||||
private struct TestConnectionResult: View {
|
||||
let outcome: ProviderProbe.Outcome
|
||||
|
||||
var body: some View {
|
||||
switch outcome {
|
||||
case let .works(latencyMS, modelCount):
|
||||
Text("✓ works · \(latencyMS) ms · \(modelCount) models")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.accent)
|
||||
case let .authFailed(detail):
|
||||
text("key rejected — \(detail)")
|
||||
case let .wrongKeyType(detail):
|
||||
text("wrong key type — \(detail)")
|
||||
case let .unreachable(detail):
|
||||
text("unreachable — \(detail)")
|
||||
case let .starved(detail):
|
||||
text("token cap starved — \(detail)")
|
||||
case let .requestFailed(status, detail):
|
||||
text("HTTP \(status) — \(detail)")
|
||||
}
|
||||
}
|
||||
|
||||
private func text(_ content: String) -> some View {
|
||||
Text(content)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(.orange)
|
||||
.lineLimit(2)
|
||||
.truncationMode(.middle)
|
||||
.help(content)
|
||||
}
|
||||
}
|
||||
|
||||
/// The z.ai key-type toggle (prototype `.seg`): a two-segment capsule, the
|
||||
/// selected segment filled with the foreground ink. Toggling swaps the
|
||||
/// endpoint family (the model guards a custom endpoint).
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
// a Settings sidebar + detail column (System Settings shape): destinations
|
||||
// Content · Pass 1 · Pass 2 · Chat · Provider Keys. Content keeps the #17
|
||||
// Home control unchanged; the surface and keys pages live in
|
||||
// SettingsPagesView.swift over the in-memory SettingsModel (persistence is
|
||||
// S3's job — the write-path protocol is the seam).
|
||||
// SettingsPagesView.swift.
|
||||
// #136 (Profiles S3): the model runs over HermesSettingsWriter (the real
|
||||
// CLI/.env rail) and hydrates from the profiles at pane open.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
@@ -17,9 +18,20 @@ import SwiftUI
|
||||
/// Settings pane — sidebar + detail per prototype variant C.
|
||||
struct SettingsPaneView: View {
|
||||
@Binding var home: URL
|
||||
/// #136: the gate's binary winner — HermesSettingsWriter's CLI rail and
|
||||
/// the hydration reads both need it (nil before a gate pass: writes
|
||||
/// surface their failure, reads leave the seed).
|
||||
let binaryPath: String?
|
||||
@State private var page: SettingsPage = .content
|
||||
/// #135: in-memory model, pane-local until S3 lifts persistence in.
|
||||
@State private var model = SettingsModel()
|
||||
/// #135/#136: the model over the REAL write path; hydrated from the
|
||||
/// profiles at pane open.
|
||||
@State private var model: SettingsModel
|
||||
|
||||
init(home: Binding<URL>, binaryPath: String?) {
|
||||
_home = home
|
||||
self.binaryPath = binaryPath
|
||||
_model = State(initialValue: SettingsModel(writer: HermesSettingsWriter(hermesBinary: binaryPath)))
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
@@ -41,6 +53,7 @@ struct SettingsPaneView: View {
|
||||
}
|
||||
}
|
||||
.background(DesignTokens.background)
|
||||
.task { await model.hydrate() }
|
||||
}
|
||||
|
||||
// MARK: Sidebar (prototype `.vC .side`)
|
||||
|
||||
@@ -215,7 +215,7 @@ struct WorkspaceView: View {
|
||||
selection = .posts
|
||||
}
|
||||
case .settings:
|
||||
SettingsPaneView(home: $gate.museionHome)
|
||||
SettingsPaneView(home: $gate.museionHome, binaryPath: gate.gateModel.currentBinaryPath)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ Owned by the root AGENTS.md contract.
|
||||
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
|
||||
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
|
||||
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt` — streams then holds the turn reading, `cancelOnPrompt` — one chunk then stopReason cancelled, `noStopReason` — prompt result without stopReason, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. **#124:** `hangOnPrompt` is the cancel-acknowledging hold — while the turn is held the fake keeps reading; `session/cancel` answers the held prompt `stopReason "cancelled"` (the real engine's contract), stdin EOF without a cancel (teardown) answers end_turn so the child exits; during the hold ONLY `session/cancel` is answered — any other request waits until teardown. Every fake-spawning test tears down via `defer` at rig creation (`client.close()`/`model.shutdown()`, both idempotent) — a cancelled or interrupted test cannot leak the child; explicit mid-test teardown remains only where it IS the mechanism or a regression bound. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub. **#28:** the fake gains the session-lifecycle surface — unique session ids per `session/new`, a prompt-sid echo, **`loadReplay` mode** (answers `session/load` for a planted id by FIRST streaming user+agent+thought chunk updates then the load response — the adapter's replay-before-response contract; **#30: the load response carries the REAL 0.21.5 shape — `_meta.hermes.sessionProvenance.acpSessionId`, NO top-level `sessionId`, so every resume pin guards the live wire; an empty result stays the unknown-refusal**; a `loadReplayLegacy` knob answers the OLDER top-level-`sessionId` shape — pinning resumeSession's dual-shape acceptance), `session/fork` → fresh `F-<n>` id (unknown id → empty-string sessionId, the adapter's refusal shape), and `mcpServers` strictness on new/load/fork alike.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates profiles at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. The fake speaks `-p <any-profile> mcp list`/`mcp add` (per-profile marker `mcp-registered-<profile>` = already registered, invocation log `mcp-add-invocation-<profile>` for the exact add command line, one stdin line read, `mcp-add-fails` reject knob) AND `-p <profile> config set` (argv log `config-set-<profile>`, `config-set-fails` knob), logging every `profile create` to `profile-create-log` (#134). **#136:** `config set` also maintains a KEY=VALUE `config-store-<profile>` map (dedup per key), and the fake speaks `config get <key>` (store value, or the not-set line on stderr exit 1) and `config unset <key>` (argv log `config-unset-<profile>`, store line removed, `✓ Unset …`; unset-when-absent = exit 1) — the live-probed wire shapes. **#134 (Profiles S1):** `ProfileSurfaceTests.swift` (own file — registry mapping, ×3 provisioning + exact config-set lines, allocation symlinks, re-pass no-op, adoption, marker heal/no-stomp, profile-named failures, per-profile registration) and `ProfileSkillMigrationTests.swift` (own file — copy-era→symlink byte-match migration incl. the `.DS_Store`-browsed case, diverged-stays-copy, untracked-untouched) share the harness; `makeShippedPayload`/`shippedSkillNames`/`fakeHermesLog` are internal there; every `perform` call injects `masterRoot` (the default writes the REAL Application Support). #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23, and per #134 only for adopted/engine-owned configs: fresh pass profiles ARE configured via `config set`), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`, `skillPath(profile:_:_:)`, `readSkillBody`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture(at:name:)`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`.
|
||||
- `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts.
|
||||
@@ -39,7 +39,7 @@ Owned by the root AGENTS.md contract.
|
||||
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
|
||||
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
|
||||
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
|
||||
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing).
|
||||
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the ResponseLine truncated
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//
|
||||
// HermesSettingsWriterTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #136 (Profiles S3) — scenario headers:
|
||||
//
|
||||
// ## Scenario: Settings writes reach the profile
|
||||
// From user story #136
|
||||
// Given the gate passed and a surface profile exists
|
||||
// When the user changes that surface's model in Settings
|
||||
// Then `hermes -p <profile> config get model.default` returns it and the
|
||||
// write order keeps the z.ai endpoint family intact (provider first —
|
||||
// switching clears base_url, live-probed).
|
||||
//
|
||||
// ## Scenario: one provider key fans out
|
||||
// From user story #136
|
||||
// Given profiles on provider z.ai
|
||||
// When the user saves a z.ai key
|
||||
// Then every fanned-out profile's .env carries GLM_API_KEY (foreign lines
|
||||
// preserved, 0600) and model.base_url matches the key-type family.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("HermesSettingsWriterTests")
|
||||
struct HermesSettingsWriterTests {
|
||||
/// Fresh temp dir + fake hermes per test (Real-Process pattern).
|
||||
private func makeRig() -> (binDir: String, writer: HermesSettingsWriter) {
|
||||
let binDir = provTempDir("s3writer")
|
||||
let writer = HermesSettingsWriter(hermesBinary: makeFakeHermes(at: binDir, mode: "ok"), profileRoot: binDir + "/profiles")
|
||||
return (binDir, writer)
|
||||
}
|
||||
|
||||
@Test func `surface write round-trips through config get`() async throws {
|
||||
let (binDir, writer) = makeRig()
|
||||
let config = SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .high)
|
||||
try await writer.writeSurface(.pass1, config: config, zaiEndpoint: ZaiKeyType.coding.endpoint)
|
||||
let read = try await writer.readSurface(.pass1)
|
||||
#expect(read?.config == config)
|
||||
#expect(read?.baseURL == ZaiKeyType.coding.endpoint)
|
||||
}
|
||||
|
||||
@Test func `surface write order is provider model effort then base_url`() async throws {
|
||||
let (binDir, writer) = makeRig()
|
||||
try await writer.writeSurface(
|
||||
.pass1,
|
||||
config: SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .high),
|
||||
zaiEndpoint: ZaiKeyType.coding.endpoint,
|
||||
)
|
||||
// base_url LAST: setting model.provider clears a stale base_url, so
|
||||
// the endpoint family must be (re)written after the provider.
|
||||
#expect(fakeHermesLog(binDir, "config-set-museion-pass1") == [
|
||||
"-p museion-pass1 config set model.provider zai",
|
||||
"-p museion-pass1 config set model.default glm-5.3",
|
||||
"-p museion-pass1 config set model.reasoning_effort high",
|
||||
"-p museion-pass1 config set model.base_url \(ZaiKeyType.coding.endpoint)",
|
||||
])
|
||||
}
|
||||
|
||||
@Test func `nil effort unsets and unset-when-absent stays success`() async throws {
|
||||
let (binDir, writer) = makeRig()
|
||||
// Never set: the unset is idempotent success, no throw.
|
||||
try await writer.writeSurface(
|
||||
.pass1,
|
||||
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: nil),
|
||||
zaiEndpoint: nil,
|
||||
)
|
||||
#expect(fakeHermesLog(binDir, "config-unset-museion-pass1") == [
|
||||
"-p museion-pass1 config unset model.reasoning_effort",
|
||||
])
|
||||
// Set then unset: readSurface sees effort nil.
|
||||
try await writer.writeSurface(
|
||||
.pass1,
|
||||
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: .low),
|
||||
zaiEndpoint: nil,
|
||||
)
|
||||
try await writer.writeSurface(
|
||||
.pass1,
|
||||
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: nil),
|
||||
zaiEndpoint: nil,
|
||||
)
|
||||
let read = try await writer.readSurface(.pass1)
|
||||
#expect(read?.config.effort == nil)
|
||||
}
|
||||
|
||||
@Test func `keys land in every env and the base url write-through rides the listed profiles`() async throws {
|
||||
let (binDir, writer) = makeRig()
|
||||
let root = binDir + "/profiles"
|
||||
let chatEnv = root + "/museion/.env"
|
||||
try? FileManager.default.createDirectory(atPath: root + "/museion", withIntermediateDirectories: true)
|
||||
let original = """
|
||||
# Per-profile secrets for this Hermes profile.
|
||||
EXA_API_KEY=keep-me
|
||||
|
||||
"""
|
||||
try original.write(toFile: chatEnv, atomically: true, encoding: .utf8)
|
||||
|
||||
try await writer.writeProviderKey(
|
||||
provider: .zai,
|
||||
config: ProviderKeyConfig(endpoint: ZaiKeyType.coding.endpoint, apiKey: "sk-zai-test"),
|
||||
profiles: [.chat],
|
||||
)
|
||||
|
||||
let updated = try String(contentsOfFile: chatEnv, encoding: .utf8)
|
||||
#expect(updated.contains("GLM_API_KEY=sk-zai-test"))
|
||||
#expect(updated.contains("# Per-profile secrets for this Hermes profile."))
|
||||
#expect(updated.contains("EXA_API_KEY=keep-me"))
|
||||
#expect(updated == HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "sk-zai-test", in: original))
|
||||
let perms = try FileManager.default.attributesOfItem(atPath: chatEnv)[.posixPermissions] as? Int
|
||||
#expect(perms == 0o600) // hermes' own .env posture; a secret must not be world-readable
|
||||
|
||||
// #136 dogfood amendment: the key lands in ALL THREE .env files —
|
||||
// a key entered before any surface is on its provider still
|
||||
// persists (inert vars are ignored for other providers).
|
||||
for name in ["museion", "museion-pass1", "museion-pass2"] {
|
||||
let env = try String(contentsOfFile: root + "/\(name)/.env", encoding: .utf8)
|
||||
#expect(env.contains("GLM_API_KEY=sk-zai-test"))
|
||||
}
|
||||
// The zai endpoint family write-through rides ONLY the listed
|
||||
// profiles — a zai endpoint in an anthropic profile would be wrong.
|
||||
#expect(fakeHermesLog(binDir, "config-set-museion") == [
|
||||
"-p museion config set model.base_url \(ZaiKeyType.coding.endpoint)",
|
||||
])
|
||||
#expect(fakeHermesLog(binDir, "config-set-museion-pass1").isEmpty)
|
||||
#expect(fakeHermesLog(binDir, "config-set-museion-pass2").isEmpty)
|
||||
|
||||
// And it reads back — the restart round trip.
|
||||
let readBack = try await writer.readProviderKey(provider: .zai)
|
||||
#expect(readBack == "sk-zai-test")
|
||||
}
|
||||
|
||||
@Test func `empty key leaves env bytes untouched but writes the endpoint family`() async throws {
|
||||
let (binDir, writer) = makeRig()
|
||||
let root = binDir + "/profiles"
|
||||
try? FileManager.default.createDirectory(atPath: root + "/museion", withIntermediateDirectories: true)
|
||||
let chatEnv = root + "/museion/.env"
|
||||
try "GLM_API_KEY=existing\n".write(toFile: chatEnv, atomically: true, encoding: .utf8)
|
||||
let before = try String(contentsOfFile: chatEnv, encoding: .utf8)
|
||||
|
||||
try await writer.writeProviderKey(
|
||||
provider: .zai,
|
||||
config: ProviderKeyConfig(endpoint: ZaiKeyType.coding.endpoint, apiKey: ""),
|
||||
profiles: [.chat],
|
||||
)
|
||||
|
||||
#expect(try String(contentsOfFile: chatEnv, encoding: .utf8) == before)
|
||||
#expect(fakeHermesLog(binDir, "config-set-museion") == [
|
||||
"-p museion config set model.base_url \(ZaiKeyType.coding.endpoint)",
|
||||
])
|
||||
}
|
||||
|
||||
@Test func `a line-broken key value is refused with nothing written`() async throws {
|
||||
// 2026-10-28 audit pin: a pasted "key\nOTHER_VAR=x" is an env-file
|
||||
// injection — the shared sink refuses it before any file is
|
||||
// touched (the error rides lastWriteError in the app).
|
||||
let (binDir, writer) = makeRig()
|
||||
do {
|
||||
try await writer.writeProviderKey(
|
||||
provider: .zai,
|
||||
config: ProviderKeyConfig(endpoint: "", apiKey: "a\nOPENAI_API_KEY=x"),
|
||||
profiles: [],
|
||||
)
|
||||
Issue.record("expected a throw")
|
||||
} catch {
|
||||
let message = (error as? HermesSettingsWriter.WriteError)?.message ?? String(describing: error)
|
||||
#expect(message.contains("line break"))
|
||||
}
|
||||
let root = binDir + "/profiles"
|
||||
for name in ["museion", "museion-pass1", "museion-pass2"] {
|
||||
#expect(!FileManager.default.fileExists(atPath: root + "/\(name)/.env"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `non-zai key write only touches env`() async throws {
|
||||
let (binDir, writer) = makeRig()
|
||||
let root = binDir + "/profiles"
|
||||
try? FileManager.default.createDirectory(atPath: root + "/museion-pass1", withIntermediateDirectories: true)
|
||||
try await writer.writeProviderKey(
|
||||
provider: .anthropic,
|
||||
config: ProviderKeyConfig(endpoint: "https://api.anthropic.com", apiKey: "sk-ant-test"),
|
||||
profiles: [.pass1],
|
||||
)
|
||||
let env = try String(contentsOfFile: root + "/museion-pass1/.env", encoding: .utf8)
|
||||
#expect(env == "ANTHROPIC_API_KEY=sk-ant-test\n")
|
||||
#expect(fakeHermesLog(binDir, "config-set-museion-pass1").isEmpty)
|
||||
}
|
||||
|
||||
@Test func `failing config set names the profile`() async {
|
||||
let (binDir, writer) = makeRig()
|
||||
try? "".write(toFile: binDir + "/config-set-fails", atomically: true, encoding: .utf8)
|
||||
do {
|
||||
try await writer.writeSurface(
|
||||
.pass1,
|
||||
config: SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: nil),
|
||||
zaiEndpoint: nil,
|
||||
)
|
||||
Issue.record("expected a throw")
|
||||
} catch {
|
||||
#expect("\(error)".contains("museion-pass1"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `missing binary refuses writes and reads nil`() async throws {
|
||||
let writer = HermesSettingsWriter(hermesBinary: nil)
|
||||
await #expect(throws: (any Error).self) {
|
||||
try await writer.writeSurface(.pass1, config: .surfaceDefault, zaiEndpoint: nil)
|
||||
}
|
||||
let read = try await writer.readSurface(.pass1)
|
||||
#expect(read == nil)
|
||||
}
|
||||
|
||||
// MARK: upsertEnv (pure)
|
||||
|
||||
@Test func `upsertEnv replaces in place appends fresh and keeps trailing newline`() {
|
||||
#expect(
|
||||
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "GLM_API_KEY=a\nOTHER=x\n")
|
||||
== "OTHER=x\nGLM_API_KEY=b\n",
|
||||
)
|
||||
#expect(
|
||||
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "# comment\n")
|
||||
== "# comment\nGLM_API_KEY=b\n",
|
||||
)
|
||||
#expect(
|
||||
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "")
|
||||
== "GLM_API_KEY=b\n",
|
||||
)
|
||||
#expect(
|
||||
HermesSettingsWriter.upsertEnv(varName: "GLM_API_KEY", value: "b", in: "GLM_API_KEY=a")
|
||||
== "GLM_API_KEY=b\n",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -34,10 +34,62 @@ struct SeedSkill {
|
||||
/// invocation in `<binaryDir>/mcp-add-invocation-<profile>`, drops the
|
||||
/// per-profile marker, prints "Saved 'museion-tools' to …" (verified wire
|
||||
/// strings). `config set <key> <value> [--force]` appends the exact argv to
|
||||
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …" line.
|
||||
/// `<binaryDir>/mcp-add-fails` / `config-set-fails` force the matching
|
||||
/// `<binaryDir>/config-set-<profile>` and prints the verified "✓ Set …"
|
||||
/// line. `<binaryDir>/mcp-add-fails` / `config-set-fails` force the matching
|
||||
/// failure. Every `profile create` name appends to
|
||||
/// `<binaryDir>/profile-create-log`.
|
||||
/// #136: `config set` also records KEY=VALUE into
|
||||
/// `<binaryDir>/config-store-<profile>` (dedup per key), and the fake speaks
|
||||
/// `config get <key>` (store value, or the not-set line on stderr exit 1)
|
||||
/// and `config unset <key>` (argv log `<binaryDir>/config-unset-<profile>`,
|
||||
/// store line removed, "✓ Unset …"; unset-when-absent = the not-set line,
|
||||
/// exit 1) — the live-probed wire shapes HermesSettingsWriter pins.
|
||||
// #136: the config rail (set/get/unset over the config-store map) — its
|
||||
// own literal so makeFakeHermes stays under its function-body ceiling.
|
||||
private func fakeHermesConfigCLI() -> String {
|
||||
"""
|
||||
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then
|
||||
PROFILE="$2"
|
||||
if [[ -f "${0:h}/config-set-fails" ]]; then
|
||||
print "Error: config set exploded"
|
||||
exit 1
|
||||
fi
|
||||
STORE="${0:h}/config-store-$PROFILE"
|
||||
touch "$STORE"
|
||||
grep -v "^$5=" "$STORE" > "$STORE.tmp" && mv "$STORE.tmp" "$STORE"
|
||||
print -r -- "$5=$6" >> "$STORE"
|
||||
print -r -- "$*" >> "${0:h}/config-set-$PROFILE"
|
||||
print "✓ Set $5 = $6 in ${0:h}/profiles/$PROFILE/config.yaml"
|
||||
exit 0
|
||||
fi
|
||||
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "get" ]]; then
|
||||
PROFILE="$2"; KEY="$5"
|
||||
STORE="${0:h}/config-store-$PROFILE"
|
||||
if [[ -f "$STORE" ]]; then
|
||||
VAL="$(grep -m1 "^${KEY}=" "$STORE" | cut -d= -f2-)"
|
||||
if [[ -n "$VAL" ]]; then
|
||||
print -r -- "$VAL"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
print "Config key not set: $KEY" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "unset" ]]; then
|
||||
PROFILE="$2"; KEY="$5"
|
||||
print -r -- "$*" >> "${0:h}/config-unset-$PROFILE"
|
||||
STORE="${0:h}/config-store-$PROFILE"
|
||||
if [[ -f "$STORE" && -n "$(grep -m1 "^${KEY}=" "$STORE")" ]]; then
|
||||
grep -v "^${KEY}=" "$STORE" > "$STORE.tmp" && mv "$STORE.tmp" "$STORE"
|
||||
print "✓ Unset $KEY from ${0:h}/profiles/$PROFILE/config.yaml"
|
||||
exit 0
|
||||
fi
|
||||
print "Config key not set: $KEY" >&2
|
||||
exit 1
|
||||
fi
|
||||
"""
|
||||
}
|
||||
|
||||
func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
|
||||
let path = (dir as NSString).appendingPathComponent(name)
|
||||
let createBlock = switch mode {
|
||||
@@ -64,6 +116,7 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
|
||||
exit 1
|
||||
"""
|
||||
}
|
||||
// #136: the config rail lives in fakeHermesConfigCLI().
|
||||
let script = """
|
||||
#!/bin/zsh
|
||||
if [[ "$1" == "profile" && "$2" == "create" ]]; then
|
||||
@@ -101,16 +154,7 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
if [[ "$1" == "-p" && "$3" == "config" && "$4" == "set" ]]; then
|
||||
PROFILE="$2"
|
||||
if [[ -f "${0:h}/config-set-fails" ]]; then
|
||||
print "Error: config set exploded"
|
||||
exit 1
|
||||
fi
|
||||
print -r -- "$*" >> "${0:h}/config-set-$PROFILE"
|
||||
print "✓ Set $5 = $6 in ${0:h}/profiles/$PROFILE/config.yaml"
|
||||
exit 0
|
||||
fi
|
||||
\(fakeHermesConfigCLI())
|
||||
exit 97
|
||||
"""
|
||||
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
//
|
||||
// ProviderProbeTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #136 (Profiles S3) — scenario:
|
||||
//
|
||||
// ## Scenario: Test Connection tells the truth
|
||||
// From user story #136
|
||||
// Given a provider key and endpoint in Settings
|
||||
// When the user clicks Test Connection
|
||||
// Then the verdict distinguishes works (latency + model count) from
|
||||
// wrong-key-type from unreachable from auth-failed — decoded per the
|
||||
// factsheet envelopes, never gated on status 200 alone (§1.5 starvation
|
||||
// is a 200).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
/// Canned probe responses — free functions shared with
|
||||
/// ProviderProbeTransportTests (shared-helper convention); nonisolated for
|
||||
/// @Sendable transport closures.
|
||||
nonisolated func probeHTTPResponse(_ status: Int) -> HTTPURLResponse {
|
||||
HTTPURLResponse(url: URL(string: "https://api.test/v1")!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: nil)!
|
||||
}
|
||||
|
||||
nonisolated func probeData(_ json: String) -> Data {
|
||||
Data(json.utf8)
|
||||
}
|
||||
|
||||
@Suite("ProviderProbeTests")
|
||||
struct ProviderProbeTests {
|
||||
// MARK: Error decode — the factsheet envelopes (§1.6/§2.5/§3.5)
|
||||
|
||||
@Test func `zai 1113 decodes as wrong key type for this endpoint family`() {
|
||||
let outcome = ProviderProbe.decodeError(
|
||||
status: 403,
|
||||
body: probeData(#"{"error":{"code":"1113","message":"Insufficient balance"}}"#),
|
||||
provider: .zai,
|
||||
)
|
||||
guard case .wrongKeyType = outcome else {
|
||||
Issue.record("expected wrongKeyType, got \(outcome)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `zai 401 decodes as auth failed with the provider message`() {
|
||||
let outcome = ProviderProbe.decodeError(
|
||||
status: 401,
|
||||
body: probeData(#"{"error":{"code":"401","message":"token expired or incorrect"}}"#),
|
||||
provider: .zai,
|
||||
)
|
||||
guard case let .authFailed(detail) = outcome else {
|
||||
Issue.record("expected authFailed, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(detail.contains("token expired"))
|
||||
}
|
||||
|
||||
@Test func `anthropic auth error carries the request id`() {
|
||||
let outcome = ProviderProbe.decodeError(
|
||||
status: 401,
|
||||
body: probeData(#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"},"request_id":"req_123"}"#),
|
||||
provider: .anthropic,
|
||||
)
|
||||
guard case let .authFailed(detail) = outcome else {
|
||||
Issue.record("expected authFailed, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(detail.contains("invalid x-api-key"))
|
||||
#expect(detail.contains("req_123"))
|
||||
}
|
||||
|
||||
@Test func `openai invalid_api_key decodes as auth failed`() {
|
||||
let outcome = ProviderProbe.decodeError(
|
||||
status: 401,
|
||||
body: probeData(#"{"error":{"message":"Incorrect API key","type":"invalid_request_error","param":null,"code":"invalid_api_key"}}"#),
|
||||
provider: .openaiAPI,
|
||||
)
|
||||
guard case .authFailed = outcome else {
|
||||
Issue.record("expected authFailed, got \(outcome)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `rate limit and unparseable bodies decode as request failures`() {
|
||||
guard case let .requestFailed(status, detail) = ProviderProbe.decodeError(
|
||||
status: 429,
|
||||
body: probeData(#"{"error":{"message":"rate limited"}}"#),
|
||||
provider: .zai,
|
||||
) else {
|
||||
Issue.record("expected requestFailed")
|
||||
return
|
||||
}
|
||||
#expect(status == 429)
|
||||
#expect(detail.contains("rate limited"))
|
||||
// Foreign body (HTML error page): the status still names it.
|
||||
guard case let .requestFailed(foreignStatus, _) = ProviderProbe.decodeError(
|
||||
status: 502,
|
||||
body: Data("<html>bad gateway</html>".utf8),
|
||||
provider: .anthropic,
|
||||
) else {
|
||||
Issue.record("expected requestFailed for foreign body")
|
||||
return
|
||||
}
|
||||
#expect(foreignStatus == 502)
|
||||
}
|
||||
|
||||
// MARK: Chat decode — the three SSE dialects
|
||||
|
||||
@Test func `zai sse content decodes works and empty length decodes starved`() {
|
||||
let sse = """
|
||||
data: {"choices":[{"delta":{"reasoning_content":"thinking…"},"finish_reason":null}]}
|
||||
|
||||
data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":null}]}
|
||||
|
||||
data: {"choices":[{"delta":{"content":"!"},"finish_reason":"stop"}]}
|
||||
|
||||
data: {"choices":[{"delta":{},"finish_reason":null}]}
|
||||
|
||||
data: [DONE]
|
||||
"""
|
||||
guard case let .works(_, modelCount) = ProviderProbe.decodeChat(
|
||||
provider: .zai, body: Data(sse.utf8), modelCount: 11, latencyMS: 412,
|
||||
) else {
|
||||
Issue.record("expected works")
|
||||
return
|
||||
}
|
||||
#expect(modelCount == 11)
|
||||
|
||||
let starved = """
|
||||
data: {"choices":[{"delta":{"reasoning_content":"…"},"finish_reason":"length"}]}
|
||||
|
||||
data: [DONE]
|
||||
"""
|
||||
guard case .starved = ProviderProbe.decodeChat(
|
||||
provider: .zai, body: Data(starved.utf8), modelCount: 11, latencyMS: 10,
|
||||
) else {
|
||||
Issue.record("expected starved (§1.5: 200 + finish=length + empty content)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `anthropic sse decodes works and starved via stop reasons`() {
|
||||
let sse = """
|
||||
event: message_start
|
||||
data: {"type":"message_start","message":{}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"lo"}}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
"""
|
||||
guard case let .works(_, modelCount) = ProviderProbe.decodeChat(
|
||||
provider: .anthropic, body: Data(sse.utf8), modelCount: 14, latencyMS: 300,
|
||||
) else {
|
||||
Issue.record("expected works")
|
||||
return
|
||||
}
|
||||
#expect(modelCount == 14)
|
||||
|
||||
let starved = """
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"}}
|
||||
"""
|
||||
guard case .starved = ProviderProbe.decodeChat(
|
||||
provider: .anthropic, body: Data(starved.utf8), modelCount: 14, latencyMS: 10,
|
||||
) else {
|
||||
Issue.record("expected starved")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `openai responses sse decodes works starved and failed`() {
|
||||
// The Responses dialect (2026-10-28 maintainer correction):
|
||||
// response.output_text.delta carries text, response.completed
|
||||
// closes the turn. The leading response.created carries
|
||||
// "error": null on every snapshot — JSON null is not nil, and the
|
||||
// 2026-10-28 dogfood showed a null tripping the envelope check
|
||||
// (healthy stream decoded as "HTTP 200").
|
||||
let sse = """
|
||||
event: response.created
|
||||
data: {"type":"response.created","response":{"status":"in_progress","error":null}}
|
||||
|
||||
event: response.output_text.delta
|
||||
data: {"type":"response.output_text.delta","delta":"Hey"}
|
||||
|
||||
event: response.completed
|
||||
data: {"type":"response.completed","response":{"status":"completed","error":null}}
|
||||
|
||||
"""
|
||||
guard case let .works(_, modelCount) = ProviderProbe.decodeChat(
|
||||
provider: .openaiAPI, body: Data(sse.utf8), modelCount: 135, latencyMS: 250,
|
||||
) else {
|
||||
Issue.record("expected works")
|
||||
return
|
||||
}
|
||||
#expect(modelCount == 135)
|
||||
|
||||
// Cap starved: incomplete status, no text.
|
||||
let starved = """
|
||||
data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}}
|
||||
"""
|
||||
guard case .starved = ProviderProbe.decodeChat(
|
||||
provider: .openaiAPI, body: Data(starved.utf8), modelCount: 135, latencyMS: 10,
|
||||
) else {
|
||||
Issue.record("expected starved for incomplete with no text")
|
||||
return
|
||||
}
|
||||
|
||||
// response.failed carries response.error — decoded as a request
|
||||
// failure, never a silent "works" on an empty 200.
|
||||
let failed = """
|
||||
data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"boom"}}}
|
||||
"""
|
||||
guard case let .requestFailed(status, detail) = ProviderProbe.decodeChat(
|
||||
provider: .openaiAPI, body: Data(failed.utf8), modelCount: 135, latencyMS: 10,
|
||||
) else {
|
||||
Issue.record("expected requestFailed for response.failed")
|
||||
return
|
||||
}
|
||||
#expect(status == 200)
|
||||
#expect(detail.contains("boom"))
|
||||
}
|
||||
|
||||
@Test func `a 200-carried error envelope decodes as the provider error`() {
|
||||
// Live 2026-10-28: z.ai answers a wrong content-type as HTTP 200
|
||||
// with a plain-JSON error envelope — the decoder must surface the
|
||||
// provider message, not "no content".
|
||||
let envelope = #"{"error":{"message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported","code":"500"}}"#
|
||||
let body = Data(envelope.utf8)
|
||||
guard case let .requestFailed(status, detail) = ProviderProbe.decodeChat(
|
||||
provider: .zai, body: body, modelCount: 11, latencyMS: 10,
|
||||
) else {
|
||||
Issue.record("expected requestFailed for the 200 envelope")
|
||||
return
|
||||
}
|
||||
#expect(status == 200)
|
||||
#expect(detail.contains("not supported"))
|
||||
}
|
||||
|
||||
// MARK: SSE + models parsing (pure)
|
||||
|
||||
@Test func `sse payloads skip event lines DONE and blanks`() {
|
||||
let payloads = ProviderProbe.ssePayloads("""
|
||||
event: message_start
|
||||
data: {"a":1}
|
||||
|
||||
data: [DONE]
|
||||
data: not json
|
||||
|
||||
""")
|
||||
#expect(payloads.count == 1)
|
||||
}
|
||||
|
||||
@Test func `models count decodes all three listing shapes`() {
|
||||
#expect(ProviderProbe.decodeModelsCount(probeData(#"{"object":"list","data":[{},{},{}]}"#)) == 3)
|
||||
#expect(ProviderProbe.decodeModelsCount(probeData(#"{"data":[{"id":"claude-haiku-5-5"}]}"#)) == 1)
|
||||
#expect(ProviderProbe.decodeModelsCount(probeData(#"{"data":[]}"#)) == 0)
|
||||
#expect(ProviderProbe.decodeModelsCount(probeData("not json")) == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//
|
||||
// ProviderProbeTransportTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #136 (Profiles S3) — the Test Connection probe's REQUEST shapes and the
|
||||
// transport-driven flow, split from ProviderProbeTests (type-body ceiling,
|
||||
// MCPToolsPromoteTests precedent): the per-provider auth/wire pins and
|
||||
// probe() over canned transports (no-key fail-fast, end-to-end works,
|
||||
// /models auth short-circuit, transport errors → unreachable).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("ProviderProbeTransportTests")
|
||||
struct ProviderProbeTransportTests {
|
||||
// MARK: Requests (auth + wire shapes per factsheet)
|
||||
|
||||
/// 2026-10-28 live incident, pinned for all three providers: without
|
||||
/// Content-Type the request reads as form-urlencoded — z.ai answers 200
|
||||
/// + an error envelope, OpenAI can't parse the body.
|
||||
@Test func `every chat request carries the json content type`() throws {
|
||||
for provider in ModelProvider.allCases {
|
||||
let config = ProviderProbe.Config(provider: provider, endpoint: provider.defaultEndpoint, apiKey: "k", model: "m")
|
||||
let request = try #require(ProviderProbe.makeChatRequest(config))
|
||||
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `anthropic requests auth via header with a pinned version and required max_tokens`() throws {
|
||||
let config = ProviderProbe.Config(
|
||||
provider: .anthropic, endpoint: "https://api.anthropic.com", apiKey: "sk-ant", model: "claude-sonnet-5-5",
|
||||
)
|
||||
let request = try #require(ProviderProbe.makeChatRequest(config))
|
||||
#expect(request.value(forHTTPHeaderField: "x-api-key") == "sk-ant")
|
||||
#expect(request.value(forHTTPHeaderField: "anthropic-version") == "2023-06-01")
|
||||
#expect(request.value(forHTTPHeaderField: "Authorization") == nil)
|
||||
let body = try #require(request.httpBody)
|
||||
#expect(try #require(String(bytes: body, encoding: .utf8)).contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#))
|
||||
}
|
||||
|
||||
@Test func `zai chat carries the stable glm wire format and bearer auth`() throws {
|
||||
let config = ProviderProbe.Config(
|
||||
provider: .zai, endpoint: ZaiKeyType.coding.endpoint, apiKey: "sk-zai", model: "glm-5.3",
|
||||
)
|
||||
let request = try #require(ProviderProbe.makeChatRequest(config))
|
||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer sk-zai")
|
||||
let bodyData = try #require(request.httpBody)
|
||||
let body = try #require(String(bytes: bodyData, encoding: .utf8))
|
||||
#expect(body.contains(#""thinking":{"type":"enabled"}"#))
|
||||
#expect(body.contains(#""reasoning_effort":"low""#)) // keeps thinking minimal
|
||||
// The cap is 512 — the live 2026-10-28 tail proved 64 starves
|
||||
// glm-5.3 (reasoning_tokens 64/64, finish=length, no content).
|
||||
#expect(body.contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#))
|
||||
#expect(request.url?.absoluteString == "\(ZaiKeyType.coding.endpoint)/chat/completions")
|
||||
}
|
||||
|
||||
@Test func `openai chat speaks the responses api and urls append cleanly`() throws {
|
||||
let config = ProviderProbe.Config(
|
||||
provider: .openaiAPI, endpoint: "https://api.openai.com/v1/", apiKey: "sk-oai", model: "gpt-6.1-sol",
|
||||
)
|
||||
let request = try #require(ProviderProbe.makeChatRequest(config))
|
||||
let bodyData = try #require(request.httpBody)
|
||||
let body = try #require(String(bytes: bodyData, encoding: .utf8))
|
||||
// Responses dialect (2026-10-28 maintainer correction): input +
|
||||
// max_output_tokens; the chat-completions params never ride.
|
||||
#expect(body.contains(#""input":"hi""#))
|
||||
#expect(body.contains(#""max_output_tokens":\#(ProviderProbe.probeTokenCap)"#))
|
||||
#expect(body.contains(#""model":"gpt-6.1-sol""#))
|
||||
#expect(!body.contains("messages")) // chat-completions is the retired path
|
||||
#expect(!body.contains("max_completion_tokens"))
|
||||
#expect(!body.contains(#""max_tokens":"#)) // any max_tokens form
|
||||
#expect(request.url?.absoluteString == "https://api.openai.com/v1/responses")
|
||||
#expect(ProviderProbe.chatURL(for: .anthropic, endpoint: "https://api.anthropic.com")?
|
||||
.absoluteString == "https://api.anthropic.com/v1/messages")
|
||||
#expect(ProviderProbe.chatURL(for: .zai, endpoint: "not a url") == nil) // garbage endpoint, no trap
|
||||
}
|
||||
|
||||
// MARK: probe() over a canned transport
|
||||
|
||||
@Test func `probe without a key fails fast without touching the network`() async {
|
||||
let outcome = await ProviderProbe.probe(
|
||||
ProviderProbe.Config(provider: .anthropic, endpoint: "https://api.anthropic.com", apiKey: "", model: "m"),
|
||||
transport: { _ in
|
||||
Issue.record("transport must not be called without a key")
|
||||
throw URLError(.badURL)
|
||||
},
|
||||
)
|
||||
guard case .authFailed = outcome else {
|
||||
Issue.record("expected authFailed precondition, got \(outcome)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `probe works end to end with models count`() async {
|
||||
let zaiWorks = """
|
||||
data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":null}]}
|
||||
|
||||
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
|
||||
|
||||
data: [DONE]
|
||||
"""
|
||||
let outcome = await ProviderProbe.probe(
|
||||
ProviderProbe.Config(provider: .zai, endpoint: ZaiKeyType.standard.endpoint, apiKey: "sk-zai", model: "glm-5.3"),
|
||||
transport: { request in
|
||||
if request.url!.path.hasSuffix("/models") {
|
||||
return (probeData(#"{"object":"list","data":[{},{},{}]}"#), probeHTTPResponse(200))
|
||||
}
|
||||
return (Data(zaiWorks.utf8), probeHTTPResponse(200))
|
||||
},
|
||||
)
|
||||
guard case let .works(latencyMS, modelCount) = outcome else {
|
||||
Issue.record("expected works, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(modelCount == 3)
|
||||
#expect(latencyMS >= 0)
|
||||
}
|
||||
|
||||
@Test func `probe short-circuits on a models auth failure and reports transport errors unreachable`() async {
|
||||
let authRejected = await ProviderProbe.probe(
|
||||
ProviderProbe.Config(provider: .openaiAPI, endpoint: "https://api.openai.com/v1", apiKey: "bad", model: "gpt-5.6-sol"),
|
||||
transport: { request in
|
||||
if request.url!.path.hasSuffix("/models") {
|
||||
return (
|
||||
probeData(#"{"error":{"message":"Incorrect API key","code":"invalid_api_key"}}"#),
|
||||
probeHTTPResponse(401),
|
||||
)
|
||||
}
|
||||
Issue.record("chat must not run after /models rejected the key")
|
||||
return (Data(), probeHTTPResponse(200))
|
||||
},
|
||||
)
|
||||
guard case .authFailed = authRejected else {
|
||||
Issue.record("expected authFailed, got \(authRejected)")
|
||||
return
|
||||
}
|
||||
|
||||
let offline = await ProviderProbe.probe(
|
||||
ProviderProbe.Config(provider: .anthropic, endpoint: "https://api.anthropic.com", apiKey: "sk-ant", model: "m"),
|
||||
transport: { _ in throw URLError(.cannotConnectToHost) },
|
||||
)
|
||||
guard case .unreachable = offline else {
|
||||
Issue.record("expected unreachable, got \(offline)")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,12 @@
|
||||
// effort options, custom-model state, key-type → endpoint family, and the
|
||||
// write-path seam S3 implements.
|
||||
//
|
||||
// #136 (Profiles S3) — the real write path's model side: hydration reads
|
||||
// each profile's model block (unknown providers stay seeded), key writes
|
||||
// land in all three .env files (no switch re-fire — they pre-land),
|
||||
// rapid edits coalesce per target (partial key prefixes never spawn),
|
||||
// and Test Connection fails fast without a key.
|
||||
//
|
||||
// Scenario: Provider pins its effort ladder — Given a surface page whose
|
||||
// provider is known, when the reasoning-effort menu builds (or the provider
|
||||
// switches), then the menu offers exactly that provider's ladder — z.ai
|
||||
@@ -42,45 +48,87 @@ import Testing
|
||||
|
||||
/// Records write-path calls; the injected seam's test double.
|
||||
@MainActor
|
||||
private final class RecordingWriter: SettingsWriting {
|
||||
final class RecordingWriter: SettingsWriting {
|
||||
/// A labeled record, not a tuple — SwiftLint's `large_tuple` (the #134
|
||||
/// ConfigWrite precedent).
|
||||
struct KeyWriteRecord: Equatable {
|
||||
let provider: ModelProvider
|
||||
let config: ProviderKeyConfig
|
||||
let keyType: ZaiKeyType?
|
||||
let profiles: [ProfileSurface]
|
||||
}
|
||||
|
||||
var surfaces: [(ProfileSurface, SurfaceModelConfig)] = []
|
||||
struct SurfaceWriteRecord: Equatable {
|
||||
let surface: ProfileSurface
|
||||
let config: SurfaceModelConfig
|
||||
let zaiEndpoint: String?
|
||||
}
|
||||
|
||||
var surfaces: [SurfaceWriteRecord] = []
|
||||
var keys: [KeyWriteRecord] = []
|
||||
/// Knob: surface writes throw while set (the failure-path tests).
|
||||
var failSurfaceWrites = false
|
||||
/// #136: canned readSurface results — the hydration tests' truth.
|
||||
var cannedReads: [ProfileSurface: (SurfaceModelConfig, String?)] = [:]
|
||||
/// #136: canned persisted keys for readProviderKey.
|
||||
var cannedKeys: [ModelProvider: String] = [:]
|
||||
/// 2026-10-28 audit pins: one-shot — the NEXT writeSurface suspends
|
||||
/// until releaseHolds() (the write-ordering pin: the successor must
|
||||
/// queue behind the in-flight write); latched — EVERY readSurface
|
||||
/// suspends until releaseHolds() (the hydrate-race pin).
|
||||
var holdFirstWrite = false
|
||||
var holdReads = false
|
||||
private var released = false
|
||||
private var writeHold: CheckedContinuation<Void, Never>?
|
||||
private var readHolds: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig) async throws {
|
||||
func releaseHolds() {
|
||||
released = true
|
||||
writeHold?.resume()
|
||||
writeHold = nil
|
||||
readHolds.forEach { $0.resume() }
|
||||
readHolds.removeAll()
|
||||
}
|
||||
|
||||
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig, zaiEndpoint: String?) async throws {
|
||||
if failSurfaceWrites {
|
||||
throw NSError(domain: "test", code: 1, userInfo: [NSLocalizedDescriptionKey: "config set failed"])
|
||||
}
|
||||
surfaces.append((surface, config))
|
||||
if holdFirstWrite, !released {
|
||||
holdFirstWrite = false
|
||||
await withCheckedContinuation { writeHold = $0 }
|
||||
}
|
||||
surfaces.append(SurfaceWriteRecord(surface: surface, config: config, zaiEndpoint: zaiEndpoint))
|
||||
}
|
||||
|
||||
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, keyType: ZaiKeyType?) async throws {
|
||||
keys.append(KeyWriteRecord(provider: provider, config: config, keyType: keyType))
|
||||
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, profiles: [ProfileSurface]) async throws {
|
||||
keys.append(KeyWriteRecord(provider: provider, config: config, profiles: profiles))
|
||||
}
|
||||
|
||||
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
|
||||
if holdReads, !released {
|
||||
await withCheckedContinuation { readHolds.append($0) }
|
||||
}
|
||||
return cannedReads[surface]
|
||||
}
|
||||
|
||||
func readProviderKey(provider: ModelProvider) async throws -> String? {
|
||||
cannedKeys[provider]
|
||||
}
|
||||
}
|
||||
|
||||
/// The real cache's shape, subset — shared with SettingsModelWritePathTests
|
||||
/// (shared-helper convention; claude-sonnet-5-5 deliberately absent —
|
||||
/// custom is the default state).
|
||||
func liveShapedRegistry() -> ModelRegistry {
|
||||
ModelRegistry(models: [
|
||||
.zai: ["glm-4.5", "glm-5", "glm-5.3", "glm-5.3-flashx"],
|
||||
.anthropic: ["claude-fable-5.1", "claude-opus-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
|
||||
.openaiAPI: ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4-mini"],
|
||||
])
|
||||
}
|
||||
|
||||
@Suite("SettingsModelTests")
|
||||
struct SettingsModelTests {
|
||||
/// The real cache's shape, subset — zai + anthropic + openai-api lists,
|
||||
/// with claude-sonnet-5-5 deliberately absent (live truth: the seed is
|
||||
/// NOT in the registry, so custom is the default state).
|
||||
private func liveShapedRegistry() -> ModelRegistry {
|
||||
ModelRegistry(models: [
|
||||
.zai: ["glm-4.5", "glm-5", "glm-5.3", "glm-5.3-flashx"],
|
||||
.anthropic: ["claude-fable-5.1", "claude-opus-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
|
||||
.openaiAPI: ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4-mini"],
|
||||
])
|
||||
}
|
||||
|
||||
// MARK: Provider → effort options
|
||||
|
||||
@Test func `provider pins its effort ladder`() {
|
||||
@@ -90,14 +138,14 @@ struct SettingsModelTests {
|
||||
}
|
||||
|
||||
@Test @MainActor func `effort unset is the leading default state`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
for surface in ProfileSurface.allCases {
|
||||
#expect(model.config(for: surface).effort == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test @MainActor func `provider switch rebuilds the effort menu and resets effort`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
model.setEffort(.max, for: .pass1)
|
||||
model.setProvider(.zai, for: .pass1)
|
||||
// zai's ladder drops xhigh/medium — the menu rebuilds from the new
|
||||
@@ -109,7 +157,7 @@ struct SettingsModelTests {
|
||||
// MARK: Custom-model state
|
||||
|
||||
@Test @MainActor func `the seeded sonnet model reads as custom not in registry`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
#expect(model.config(for: .pass1).model == ProfileSurface.defaultModelID)
|
||||
#expect(model.isCustom(.pass1))
|
||||
#expect(model.isCustom(.pass2))
|
||||
@@ -121,25 +169,25 @@ struct SettingsModelTests {
|
||||
}
|
||||
|
||||
@Test @MainActor func `a registry model reads as known`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
// Chat's provider is anthropic by default — an in-registry id reads known.
|
||||
model.setModel("claude-sonnet-5", for: .chat)
|
||||
#expect(!model.isCustom(.chat))
|
||||
}
|
||||
|
||||
@Test @MainActor func `provider switch lands on the provider's pinned default model`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
model.setProvider(.zai, for: .chat)
|
||||
#expect(model.config(for: .chat).model == "glm-5.3")
|
||||
#expect(!model.isCustom(.chat))
|
||||
model.setProvider(.openaiAPI, for: .chat)
|
||||
#expect(model.config(for: .chat).model == "gpt-5.6-sol")
|
||||
#expect(model.config(for: .chat).model == "gpt-6.1-sol")
|
||||
model.setProvider(.anthropic, for: .chat)
|
||||
#expect(model.config(for: .chat).model == "claude-sonnet-5")
|
||||
}
|
||||
|
||||
@Test @MainActor func `an empty registry leaves every model custom free text stays first class`() {
|
||||
let model = SettingsModel(registry: ModelRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: ModelRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
#expect(model.isCustom(.pass1))
|
||||
model.setModel("any-model-id-anyone-types", for: .pass1)
|
||||
#expect(model.config(for: .pass1).model == "any-model-id-anyone-types")
|
||||
@@ -147,7 +195,7 @@ struct SettingsModelTests {
|
||||
}
|
||||
|
||||
@Test @MainActor func `blank model edits never commit`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
model.setModel(" ", for: .pass2)
|
||||
#expect(model.config(for: .pass2).model == ProfileSurface.defaultModelID)
|
||||
}
|
||||
@@ -156,19 +204,22 @@ struct SettingsModelTests {
|
||||
|
||||
@Test @MainActor func `reset returns a changed surface to the seed and persists it`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
model.setProvider(.zai, for: .pass2)
|
||||
model.setEffort(.max, for: .pass2)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.surfaces.count == 2)
|
||||
// #136: rapid successive edits coalesce per target — ONE write with
|
||||
// the final value (a superseded write never spawns).
|
||||
#expect(writer.surfaces.count == 1)
|
||||
#expect(writer.surfaces[0].config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .max))
|
||||
model.resetToDefault(for: .pass2)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(model.config(for: .pass2) == SurfaceModelConfig(provider: .anthropic, model: ProfileSurface.defaultModelID, effort: nil))
|
||||
#expect(writer.surfaces.count == 3)
|
||||
#expect(writer.surfaces.count == 2)
|
||||
// Already at the seed — a second reset is a no-op, no write.
|
||||
model.resetToDefault(for: .pass2)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.surfaces.count == 3)
|
||||
#expect(writer.surfaces.count == 2)
|
||||
}
|
||||
|
||||
// MARK: Key-type → endpoint family
|
||||
@@ -179,7 +230,7 @@ struct SettingsModelTests {
|
||||
}
|
||||
|
||||
@Test @MainActor func `zai toggle swaps the endpoint family`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.standard.endpoint)
|
||||
model.setZaiKeyType(.coding)
|
||||
#expect(model.zaiKeyType == .coding)
|
||||
@@ -189,14 +240,14 @@ struct SettingsModelTests {
|
||||
}
|
||||
|
||||
@Test @MainActor func `a custom zai endpoint survives the toggle`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
model.setEndpoint("https://proxy.internal:8443/v4", for: .zai)
|
||||
model.setZaiKeyType(.coding)
|
||||
#expect(model.keyConfig(for: .zai).endpoint == "https://proxy.internal:8443/v4")
|
||||
}
|
||||
|
||||
@Test @MainActor func `a cleared zai endpoint still adopts the new family`() {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
model.setEndpoint("", for: .zai)
|
||||
model.setZaiKeyType(.coding)
|
||||
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
|
||||
@@ -206,34 +257,38 @@ struct SettingsModelTests {
|
||||
|
||||
@Test @MainActor func `surface changes route through the writer`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
model.setProvider(.zai, for: .pass1)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.surfaces.count == 1)
|
||||
let (surface, config) = writer.surfaces[0]
|
||||
#expect(surface == .pass1)
|
||||
#expect(config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
|
||||
let record = writer.surfaces[0]
|
||||
#expect(record.surface == .pass1)
|
||||
#expect(record.config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
|
||||
// A zai surface ALWAYS carries the endpoint family (written last —
|
||||
// setting model.provider clears a stale base_url); the standard
|
||||
// key type's family at the seed.
|
||||
#expect(record.zaiEndpoint == ZaiKeyType.standard.endpoint)
|
||||
}
|
||||
|
||||
@Test @MainActor func `key changes route through the writer with key type only for zai`() async {
|
||||
@Test @MainActor func `key changes route through the writer per provider`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
model.setZaiKeyType(.coding)
|
||||
model.setAPIKey("sk-test", for: .anthropic)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.keys.count == 2)
|
||||
let first = writer.keys[0]
|
||||
#expect(first.provider == .zai)
|
||||
#expect(first.keyType == .coding)
|
||||
// The endpoint field carries the family (keyType's job, 2026-10-28
|
||||
// audit: the dead param is gone).
|
||||
#expect(first.config.endpoint == ZaiKeyType.coding.endpoint)
|
||||
let second = writer.keys[1]
|
||||
#expect(second.provider == .anthropic)
|
||||
#expect(second.keyType == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `a failed write surfaces lastWriteError and a later success clears it`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
writer.failSurfaceWrites = true
|
||||
model.setModel("glm-5.3", for: .chat)
|
||||
await model.awaitPendingWrites()
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//
|
||||
// SettingsModelWritePathTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #136 (Profiles S3) — the write path's MODEL-side pins, split from
|
||||
// SettingsModelTests (file-length ceiling, own-file precedent): fan-out
|
||||
// lists, endpoint threading on a provider switch, per-target write
|
||||
// coalescing, hydration mapping, and the no-key Test Connection guard.
|
||||
// Shares RecordingWriter + liveShapedRegistry (internal, shared-helper
|
||||
// convention).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("SettingsModelWritePathTests")
|
||||
struct SettingsModelWritePathTests {
|
||||
// MARK: #136 — the real write path's model side
|
||||
|
||||
@Test @MainActor func `provider switch to a keyed zai threads the endpoint without re-firing keys`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
// Key entered while nothing was on z.ai yet — it already landed in
|
||||
// ALL THREE .env files (the writer's own test pins that), so the
|
||||
// switch needs no key re-fire.
|
||||
model.setAPIKey("sk-z", for: .zai)
|
||||
model.setZaiKeyType(.coding)
|
||||
await model.awaitPendingWrites()
|
||||
// The two rapid edits COALESCE into one key write carrying the
|
||||
// final state (key + coding endpoint family).
|
||||
#expect(writer.keys.count == 1)
|
||||
#expect(writer.keys[0].config.apiKey == "sk-z")
|
||||
#expect(writer.keys[0].config.endpoint == ZaiKeyType.coding.endpoint)
|
||||
|
||||
model.setProvider(.zai, for: .pass1)
|
||||
await model.awaitPendingWrites()
|
||||
// The surface write carries the endpoint family LAST (setting
|
||||
// model.provider clears a stale base_url — live-probed)…
|
||||
let surface = writer.surfaces.last
|
||||
#expect(surface?.config.provider == .zai)
|
||||
#expect(surface?.zaiEndpoint == ZaiKeyType.coding.endpoint)
|
||||
// …and no additional key write fired.
|
||||
#expect(writer.keys.count == 1)
|
||||
}
|
||||
|
||||
@Test @MainActor func `key writes fan out to the surfaces on that provider`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
model.setProvider(.zai, for: .chat)
|
||||
model.setProvider(.zai, for: .pass1)
|
||||
await model.awaitPendingWrites()
|
||||
model.setAPIKey("sk-z", for: .zai)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.keys.count == 1)
|
||||
// chat first (ProfileSurface.allCases order); pass2 stays anthropic
|
||||
// and is NOT in the fan-out.
|
||||
#expect(writer.keys[0].profiles == [.chat, .pass1])
|
||||
}
|
||||
|
||||
@Test @MainActor func `rapid key edits coalesce into one write with the final value`() async {
|
||||
let writer = RecordingWriter()
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0.05)
|
||||
model.setAPIKey("s", for: .anthropic)
|
||||
model.setAPIKey("sk", for: .anthropic)
|
||||
model.setAPIKey("sk-", for: .anthropic)
|
||||
await model.awaitPendingWrites()
|
||||
// A superseded write never spawns — partial key prefixes must not
|
||||
// reach .env (the #135 finish-audit contract, now model-owned).
|
||||
#expect(writer.keys.count == 1)
|
||||
#expect(writer.keys[0].config.apiKey == "sk-")
|
||||
}
|
||||
|
||||
@Test @MainActor func `hydrate maps profile reads and infers the zai key type`() async {
|
||||
let writer = RecordingWriter()
|
||||
writer.cannedReads[.chat] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), ZaiKeyType.coding.endpoint)
|
||||
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: .low), nil)
|
||||
writer.cannedKeys[.zai] = "sk-stored"
|
||||
// pass2 absent = unreadable/unknown provider — stays seeded.
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
await model.hydrate()
|
||||
#expect(model.config(for: .chat) == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
|
||||
#expect(model.config(for: .pass1).effort == .low)
|
||||
#expect(model.config(for: .pass2) == .surfaceDefault)
|
||||
// The coding base_url infers the key type + endpoint family.
|
||||
#expect(model.zaiKeyType == .coding)
|
||||
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
|
||||
// Keys persist in the .env files — hydrate refills the field (a
|
||||
// restart neither blanks the UI nor refuses Test Connection).
|
||||
#expect(model.keyConfig(for: .zai).apiKey == "sk-stored")
|
||||
}
|
||||
|
||||
@Test @MainActor func `a second edit waits for the in-flight write before replacing it`() async {
|
||||
// 2026-10-28 audit pin: cancellation can't stop a past-the-guard
|
||||
// write, so the newer write must QUEUE — the last edit is always
|
||||
// the last write to land. Without the chain the successor records
|
||||
// FIRST (["new", "old"]) and disk ends at the stale value.
|
||||
let writer = RecordingWriter()
|
||||
writer.holdFirstWrite = true
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
model.setModel("old", for: .chat) // task A
|
||||
await Task.yield() // let A pass its debounce guard and consume the hold
|
||||
model.setModel("new", for: .chat) // task B: cancels A (past its guard — a no-op), must wait
|
||||
writer.releaseHolds()
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.surfaces.map(\.config.model) == ["old", "new"])
|
||||
}
|
||||
|
||||
@Test @MainActor func `hydrate never stomps an edit made while it was reading`() async {
|
||||
// 2026-10-28 audit pin: hydration spans seconds of CLI reads; an
|
||||
// edit that fires mid-read owns the truth — applying the stale
|
||||
// read would revert the UI and the next edit would persist from
|
||||
// the stale base.
|
||||
let writer = RecordingWriter()
|
||||
writer.cannedReads[.chat] = (SurfaceModelConfig(provider: .zai, model: "glm-old", effort: nil), nil)
|
||||
writer.holdReads = true
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
let hydrating = Task { await model.hydrate() }
|
||||
model.setModel("glm-new", for: .chat) // the user edits mid-read
|
||||
writer.releaseHolds()
|
||||
await hydrating.value
|
||||
#expect(model.config(for: .chat).model == "glm-new")
|
||||
}
|
||||
|
||||
@Test @MainActor func `hydrate seeds a custom zai base url instead of clobbering it`() async {
|
||||
// 2026-10-28 audit pin: only the coding family maps back to the
|
||||
// key type; any OTHER non-empty base_url seeds the endpoint field,
|
||||
// so the next zai write-through threads the custom endpoint —
|
||||
// never a family default over the user's URL.
|
||||
let writer = RecordingWriter()
|
||||
writer.cannedReads[.chat] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), "https://proxy.example/api/paas/v4")
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
||||
await model.hydrate()
|
||||
#expect(model.keyConfig(for: .zai).endpoint == "https://proxy.example/api/paas/v4")
|
||||
model.setAPIKey("sk-z", for: .zai)
|
||||
await model.awaitPendingWrites()
|
||||
#expect(writer.keys.last?.config.endpoint == "https://proxy.example/api/paas/v4")
|
||||
}
|
||||
|
||||
@Test @MainActor func `connection without a key fails fast off the network`() async {
|
||||
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
||||
await model.testConnection(for: .anthropic)
|
||||
guard case let .done(outcome) = model.testStates[.anthropic], case .authFailed = outcome else {
|
||||
Issue.record("expected the empty-key precondition to authFail, got \(String(describing: model.testStates[.anthropic]))")
|
||||
return
|
||||
}
|
||||
// The probe model: a surface on the provider rides, else flagship.
|
||||
#expect(model.probeModel(for: .anthropic) == ProfileSurface.defaultModelID)
|
||||
#expect(model.probeModel(for: .zai) == ModelProvider.zai.switchDefaultModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
# Issue #136 — Profiles S3: Settings → profile write path + Test Connection
|
||||
|
||||
> **Date:** 2026-10-27
|
||||
> **Type:** issue
|
||||
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/136
|
||||
|
||||
## Goal
|
||||
|
||||
Land the real write path behind the #135 Settings UI: model/effort changes persist into each Hermes profile's `model:` block, provider keys persist on disk, and a Test Connection button proves a key × endpoint × model triple against the live provider. Then make it survive dogfood.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- `HermesSettingsWriter` — the production `SettingsWriting`: surface writes ride the engine's own CLI (`hermes -p <profile> config set/unset model.provider|model.default|model.reasoning_effort|model.base_url`, wire-verified ✓ lines), provider keys upsert `VAR=value` into the profile `.env` files, `readSurface` hydrates via `config get` ×4, `readProviderKey` reads keys back so a restart refills the fields. Secrets never ride argv; `.env` written at 0600.
|
||||
- `ProviderProbe` — Test Connection per the factsheet §4: step 1 `GET /models` (key validity + reachability), step 2 a minimal streaming chat. Injected `Transport` closure, nil-safe URL builders, honest error decode (zai `error.code` 1113 → wrongKeyType, 401s → authFailed with Anthropic `request_id`, finish markers → starved, empty 200 → requestFailed).
|
||||
- `SettingsModel` grew `hydrate()` (parallel per-surface reads + key read-back), `testConnection(for:)`, per-target coalescing writes, `probeModel(for:)`; `SettingsPaneView` takes the gate's `binaryPath` and hydrates at pane open.
|
||||
- Six test files: decode matrix, transport/wire-shape pins (Content-Type per provider, OpenAI Responses dialect), writer round-trips against the fake-hermes CLI rail, model-side write-path pins.
|
||||
- Live dogfood (3 rounds) + finish-audit (3 parallel reviewers) — see Gotchas.
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Keys land in ALL THREE profiles' `.env`, not just matching surfaces | Maintainer ruling mid-session: a key entered before any surface is on its provider must persist (it died on restart otherwise); inert vars are ignored by hermes for other providers; the key pre-lands for any later provider switch, so the switch needs no key re-fire — that block was deleted. Per-provider gating survives only for the z.ai `base_url` write-through (a zai endpoint in an anthropic profile would be wrong). |
|
||||
| OpenAI speaks the Responses API (`/responses`, `input` + `max_output_tokens`, flagship `gpt-6.1-sol`) | Maintainer correction over the factsheet draft; chat-completions is the retired path. Wire pinned with the old forms asserted absent. |
|
||||
| `Content-Type: application/json` on every probe request | 2026-10-28 live incident: URLSession defaults to form-urlencoded without it; z.ai answers HTTP 200 with an error envelope, OpenAI 400s. curl set the header; the app didn't. Anthropic tolerated the omission — which is why it worked first. |
|
||||
| Probe token cap 512 (was 64) | 64 always starved glm-5.3 reasoning (reasoning_tokens 64/64, finish=length, zero content) — decoded as "HTTP 200 - no content". |
|
||||
| Writes chain past the debounce guard (`await previous?.value`) | Cancellation can't stop a past-the-guard CLI write (detached rail ignores it); without the chain a stale write could land after its replacement. Audit fix, converged by two reviewers. |
|
||||
| `.env` newline/NUL guard at the shared sink | A pasted `key\nOTHER_VAR=x` is an env-file injection into every profile (clipboard-hijack primitive). One guard in `upsertEnvFile`; refusal rides `lastWriteError`. |
|
||||
| `NSLock` around the `.env` read→upsert→write | Cross-provider key writes race on the same three files; atomic-write prevents torn files but not lost updates. |
|
||||
| Hydrate skips targets with a pending write task; custom zai base_urls seed the endpoint field | Edits made during hydrate's seconds of CLI reads owned the truth; only the coding family maps back to the key type — any other non-empty zai base_url must survive, or the next write-through clobbers it to a family default. |
|
||||
| `works` carries latency + model count only; `keyType` protocol param deleted | Finish-audit ponytail: no consumer of the reply payload or the keyType (the endpoint field already carries the family). ~30 lines of dead flexibility cut. |
|
||||
| No Keychain | Issue text: keys live in hermes' own `.env` mechanism (ADR-0014 posture). |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| z.ai "HTTP 200 - no content", openai HTTP 400, anthropic ✓ | `makeChatRequest` never set `Content-Type: application/json` — URLSession defaults to form-urlencoded; providers diverge in tolerance | Header pinned on every request + per-provider wire tests |
|
||||
| OpenAI "HTTP 200 - HTTP 200" on healthy streams | OpenAI Responses snapshots carry `"error": null` on every event; JSON null ≠ nil tripped `envelope["error"] != nil` | `isError` checks `.object` case only; regression pin with null-error events |
|
||||
| Keys vanished on restart | `hydrate()` never read keys back; keys also only fanned out to matching surfaces (none → nowhere) | `readProviderKey` + all-three-`.env` landing + hydrate refill |
|
||||
| Suite "pass" with 0 tests | `-only-testing` filters match nothing for free-function Swift Testing tests (again — #31/#134) | Always read `totalTestCount` from xcresult |
|
||||
| Two full-run failures | PassRunTests #30 flake class under load | Idle rerun 464/464, then 468/468 with the audit pins |
|
||||
| Flip-cycle restore silently no-oped | python replace anchored on text whose comment lines had moved; no match ≠ applied | Assert `count == 1` before every scripted replace; caught because a pin kept failing "restored" |
|
||||
| xcresult sampled mid-run | Background suite still executing when I read the latest xcresult | Wait for the DONE marker before sampling |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/HermesSettingsWriter.swift` | NEW — production SettingsWriting (CLI rail, .env fan-out, reads, injection guard, lock) |
|
||||
| `Museion/ProviderProbe.swift` | NEW — two-step Test Connection probe + honest decode |
|
||||
| `Museion/SettingsModel.swift` | hydrate/testConnection/coalescing+chaining writes, ZaiKeyType, ModelProvider |
|
||||
| `Museion/SettingsPagesView.swift` | Test Connection button + verdict row |
|
||||
| `Museion/SettingsPaneView.swift` | binaryPath wiring + hydrate on open |
|
||||
| `Museion/ModelComboBox.swift` | ModelRegistry moved in (file-length split) |
|
||||
| `Museion/WorkspaceView.swift` | passes the gate's binary path |
|
||||
| `MuseionTests/` (6 files) | writer/probe/model suites + RecordingWriter knobs |
|
||||
| `MuseionTests/ProfileProvisionerTests.swift` | fake hermes: config get/set/unset rail |
|
||||
| `docs/research/native-llm-providers.md` | §6 correction 2026-10-28 |
|
||||
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX through the audit fixes |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Non-zai endpoint persistence — anthropic/openai endpoints are session-only; needs a product call (ticket-worthy)
|
||||
- [ ] Plaintext `http://` non-localhost endpoints send the key in cleartext — warn at probe time or field render
|
||||
- [ ] Hydrate costs 12 CLI spawns per pane visit — a multi-key `config get` would cut it if it ever bothers
|
||||
- [ ] Restart-on-change slice (SettingsModel → AppGateState lift) — the pane-local model is deliberately scoped
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-10-27 | issue | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | Profiles S3: settings write path (config set + .env), Test Connection probe, three dogfood rounds, three-reviewer audit |
|
||||
| 2026-10-27 | issue | [20261027-issue135-profiles-s2-settings-page-ui_log.md](20261027-issue135-profiles-s2-settings-page-ui_log.md) | #135 Profiles S2: variant C Settings sidebar+detail over the SettingsWriting seam; NSComboBox stale-stringValue dogfood fix; 432 tests |
|
||||
| 2026-10-27 | issue | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | #134 Profiles S1: ×3 surface registry + provisioner, master-symlink skills with byte-match migration, three-profile backup; 412 tests |
|
||||
| 2026-10-22 | issue | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | #31 S5.1: Swift-native first-draft stats stamped in place at pass invocation; two frontmatter-erasure bugs fixed; finish-audit fanout — 396 tests |
|
||||
|
||||
@@ -304,3 +304,23 @@ silent latency hole; TTFT fires on first content.
|
||||
- Live probes 2026-10-23: /models ×4, cross-family chat calls, thinking-disable, effort enum,
|
||||
budget starvation, stream cadence ×2 families, typed-tool streaming ×3 providers, bad-key
|
||||
errors ×4 endpoints, Anthropic adaptive/effort/forced-tool probes, OpenAI tools×effort clash.
|
||||
|
||||
## 6. Correction 2026-10-28 (Museion #136 dogfood, live-probed)
|
||||
|
||||
- **Content-Type is load-bearing.** Without `Content-Type: application/json`,
|
||||
URLSession defaults the request to `x-www-form-urlencoded` — z.ai answers
|
||||
**HTTP 200** with `{"error":{"code":"500","message":"Content type
|
||||
'application/x-www-form-urlencoded;charset=UTF-8' not supported"}}` (an error
|
||||
envelope riding a 200), OpenAI can't parse the body ("you must provide a
|
||||
model parameter"). The original curl probes worked because they passed the
|
||||
header explicitly; the app (URLSession) did not. Anthropic tolerated the
|
||||
omission.
|
||||
- **OpenAI chat probes must speak the RESPONSES API** (`POST /v1/responses`,
|
||||
`{"model","input"}`, `max_output_tokens`; flagship `gpt-6.1-sol`) —
|
||||
chat-completions is the retired path for current models (maintainer
|
||||
correction; §3.1/§3.3 above describe the older wire).
|
||||
- **§4's "max_tokens ≈ 64" starves reasoning models.** Live tail on
|
||||
glm-5.3 + `reasoning_effort:"low"` + `max_tokens:64`: all 64 tokens burned
|
||||
as reasoning (`reasoning_tokens:64/64`), `finish_reason:"length"`, empty
|
||||
content — the probe can never produce text at that cap. Museion's probe
|
||||
uses 512.
|
||||
Reference in new issue
Block a user