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:
AlexKucera committed 2026-10-27 18:32:30 +01:00
1 parent 42a27cc8a3
commit 5ad605eb3c
20 files changed
+1983 -161

No files matched your search

@@ -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*
+1
View File
@@ -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 |