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