Files
museion/MuseionTests/HermesSettingsWriterTests.swift
T
AlexKucera 5ad605eb3c 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
2026-10-27 18:32:30 +01:00

235 lines
9.2 KiB
Swift

//
// 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",
)
}
}