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