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
+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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user