SPB Git

Repository Public

NextGenTests.swift 27.4 KB 283 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Tests/CoreTests/NextGenTests.swift3// Description: Backend 1.0 additions: catalogue fields, chat-turn options and events (web search, citations, follow-ups, exact cost), sync feed reducer and client, prompt variables, composer triggers, search filters.4import Foundation5import Testing6@testable import SPChatCore78@Suite struct CatalogueFieldTests {9    static let payload = #"""10    {"models":[11     {"id":"claude-haiku-5-5","provider":"anthropic","displayName":"Claude Haiku 5.5","kind":"chat","api":null,"status":"verified","available":true,"tested":true,"capabilities":{"text":true,"tools":true,"vision":true},"contextWindow":1000000,"pricing":{"input":0.1,"output":0.5,"cachedInput":0.01},"hidden":false,"favorite":true,"route":"direct","creator":"anthropic","creatorName":"Anthropic","logo":"anthropic","description":null,"catalog":null,"categories":["reasoning","vision"],"lastUsedAt":"2026-11-19T14:20:30.257Z"},12     {"id":"or:google/gemini-4-neon","provider":"openrouter","displayName":"Gemini 4 Neon","kind":"chat","api":"chat","status":"catalog","available":true,"tested":false,"capabilities":{"text":true,"effortLevels":["xhigh","high"]},"contextWindow":1048576,"maxOutputTokens":943718,"pricing":{"input":3,"notes":"Prix publié par le catalogue OpenRouter (USD par million de jetons).","output":15,"cachedInput":0.15,"tiers":[{"input":6,"output":30,"minPromptTokens":200000}]},"benchmark":null,"hidden":false,"favorite":false,"route":"openrouter","creator":"google","creatorName":"Google","logo":"google","description":"Fast model.","catalog":{"slug":"google/gemini-4-neon","source":"openrouter","aliasOf":null,"created":1795006977,"rankedIn":[],"moderated":false,"reasoning":{"efforts":["xhigh","high"],"mandatory":true,"defaultEffort":"medium"},"tokenizer":"Gemini","benchmarks":{"available":["artificial_analysis"]},"huggingFaceId":null,"expirationDate":null,"inputModalities":["audio","image","text"],"outputModalities":["text"],"supportedParameters":["tools","top_p"],"prices":{"web_search":0.014,"image":"0.000003"}},"categories":["reasoning","multimodal"],"lastUsedAt":null},13     {"id":"or:newvendor/x-1","provider":"some-new-api","displayName":"X 1","kind":"hologram","status":"quarantined","available":true,"tested":false,"capabilities":{"tools":"unknown"},"route":"teleport","creator":"newvendor","creatorName":"New Vendor","logo":null,"categories":["telepathy"],"catalog":{"slug":"newvendor/x-1","futureField":{"a":1}}},14     {"displayName":"row without id"},15     "not even an object"16    ],"defaultModel":"claude-haiku-5-5","dock":["or:google/gemini-4-neon","claude-haiku-5-5"],"registry":{"refreshedAt":"2026-11-19T14:19:08.190Z"},"openrouter":{"configured":true,"catalog":{"chat":444,"added":444,"total":"444","removed":0,"syncedAt":"2026-11-19T14:19:12.804Z"}}}17    """#1819    @Test func decodesNewFieldsAndSkipsMalformedRows() throws {20        let c = try JSONDecoder.api().decode(ModelCatalog.self, from: Data(Self.payload.utf8))21        #expect(c.models.count == 3, "two malformed rows are skipped, never fatal")22        #expect(c.dock == ["or:google/gemini-4-neon", "claude-haiku-5-5"])23        #expect(c.openrouter?.configured == true); #expect(c.openrouter?.catalog?.total == 444); #expect(c.openrouter?.catalog?.syncedAt != nil)24        let haiku = try #require(c.model("claude-haiku-5-5"))25        #expect(haiku.route == "direct"); #expect(haiku.logo == "anthropic"); #expect(haiku.isVerified); #expect(!haiku.isCatalogOnly); #expect(haiku.lastUsedAt != nil); #expect(haiku.cachedInputPrice == 0.01)26        let neon = try #require(c.model("or:google/gemini-4-neon"))27        #expect(neon.isOpenRouter); #expect(neon.isCatalogOnly); #expect(neon.creatorName == "Google"); #expect(neon.isSelectableForChat)28        #expect(neon.catalog?.slug == "google/gemini-4-neon"); #expect(neon.catalog?.reasoning?.mandatory == true); #expect(neon.catalog?.benchmarkSources == ["artificial_analysis"])29        #expect(neon.catalog?.prices?["web_search"] == 0.014); #expect(neon.catalog?.prices?["image"] == 0.000003, "unit prices sent as strings are numbers")30        #expect(neon.publishedAt == Date(timeIntervalSince1970: 1_795_006_977)); #expect(neon.effortLevels == ["xhigh", "high"]); #expect(neon.blendedPrice == 18)31    }3233    @Test func unknownProviderStatusRouteAndKindAreKeptAsIs() throws {34        let c = try JSONDecoder.api().decode(ModelCatalog.self, from: Data(Self.payload.utf8))35        let x = try #require(c.model("or:newvendor/x-1"))36        #expect(x.provider == "some-new-api"); #expect(x.status == "quarantined"); #expect(x.route == "teleport"); #expect(x.kind == "hologram")37        #expect(x.logo == nil); #expect(x.categories == ["telepathy"]); #expect(!x.has("tools"), "« unknown » is not true"); #expect(!x.isSelectableForChat)38    }3940    @Test func olderPayloadIsCompletedFromTheIdOnly() throws {41        let old = #"{"models":[{"id":"gpt-5.5","provider":"openai","displayName":"GPT 5.5","kind":"chat","status":"verified","available":true,"tested":true,"capabilities":{},"hidden":false,"favorite":false},{"id":"or:meta-llama/llama-4","displayName":"Llama 4"}],"defaultModel":"gpt-5.5"}"#42        let c = try JSONDecoder.api().decode(ModelCatalog.self, from: Data(old.utf8))43        #expect(c.dock.isEmpty); #expect(c.openrouter == nil)44        #expect(c.model("gpt-5.5")?.route == "direct"); #expect(c.model("gpt-5.5")?.creator == "openai"); #expect(c.model("gpt-5.5")?.creatorName == "OpenAI")45        #expect(c.model("or:meta-llama/llama-4")?.route == "openrouter"); #expect(c.model("or:meta-llama/llama-4")?.creator == "meta", "vendor prefix mapped through the registry aliases")46        #expect(Maker.slug(forModelId: "claude-opus-5-5") == "anthropic"); #expect(Maker.slug(forModelId: "grok-4.7") == "xai"); #expect(Maker.slug(forModelId: "or:~x-ai/grok-latest") == "xai")47    }4849    @Test func catalogueSurvivesACacheRoundTrip() throws {50        let c = try JSONDecoder.api().decode(ModelCatalog.self, from: Data(Self.payload.utf8))51        let again = try JSONDecoder.api().decode(ModelCatalog.self, from: JSONEncoder.api().encode(c))52        #expect(again.dock == c.dock); #expect(again.defaultModel == c.defaultModel); #expect(again.openrouter?.catalog?.total == c.openrouter?.catalog?.total); #expect(again.registry == c.registry)53        for (a, b) in zip(again.models, c.models) {54            // dates are written with millisecond precision: compared within a millisecond, everything else exactly55            var x = a, y = b56            #expect(abs((x.lastUsedAt ?? .distantPast).timeIntervalSince(y.lastUsedAt ?? .distantPast)) < 0.001, "\(a.id)")57            x.lastUsedAt = nil; y.lastUsedAt = nil; x.lastVerifiedAt = nil; y.lastVerifiedAt = nil58            #expect(x == y, "\(a.id)")59        }60    }61}6263@Suite struct ChatTurnAdditionTests {64    @Test func webSearchAndToolNamesAreSentAndOrIdsFlowThrough() {65        let o = TurnOptions(modelId: "or:anthropic/claude-opus-5.5", routingMode: .manual, toolsEnabled: true, toolNames: ["web_search", "python"], webSearch: true).payload66        #expect(o["modelId"] == "or:anthropic/claude-opus-5.5"); #expect(o["settings"]?["webSearch"] == true); #expect(o["toolNames"] == ["web_search", "python"])67        #expect(TurnOptions(modelId: "m").payload["settings"] == nil, "webSearch is only sent when on")68        #expect(TurnOptions(webSearch: false).payload["settings"] == nil)69    }7071    @Test func followupsCitationsServedByAndExactCostAccumulate() {72        var acc = MessageAccumulator(conversationId: "c1")73        func ev(_ e: String, _ j: String) -> ChatEvent { ChatEvent(SSEEvent(event: e, data: j)) }74        acc.apply(ev("start", #"{"messageId":"m1","model":"or:google/gemini-4-neon","provider":"openrouter","routing":{"mode":"manual","selected":"or:google/gemini-4-neon"},"applied":{"applied":{},"ignored":[{"param":"images","requested":2,"reason":"modèle sans vision"}]}}"#))75        acc.apply(ev("part", #"{"type":"citation","url":"https://www.postgresql.org/docs/release","title":"Release Notes","snippet":"…"}"#))76        acc.apply(ev("part", #"{"type":"citation","url":"https://www.postgresql.org/docs/release","title":"Release Notes","snippet":"…"}"#))77        acc.apply(ev("part", #"{"type":"citation","url":"https://example.org/a"}"#))78        acc.apply(ev("meta", #"{"servedBy":"OpenRouter · Google"}"#))79        acc.apply(ev("text", #"{"delta":"18.7"}"#))80        acc.apply(ev("usage", #"{"usage":{"input":4607,"output":385,"costUsd":0.019596},"costUsd":0.019596,"latencyMs":10968,"ttftMs":10207,"exactCost":true}"#))81        acc.apply(ev("status", #"{"messageId":"m1","status":"complete"}"#))82        let applied = acc.apply(ev("followups", #"{"messageId":"m1","suggestions":["A ?","B ?","C ?"]}"#))83        let foreign = acc.apply(ev("followups", #"{"messageId":"other","suggestions":["X"]}"#))84        #expect(applied); #expect(!foreign, "follow-ups of another message are ignored")85        let m = acc.message!86        #expect(m.followups == ["A ?", "B ?", "C ?"]); #expect(m.routing?.servedBy == "OpenRouter · Google"); #expect(m.isCostExact); #expect(m.exactCost == true)87        #expect(m.citations.map(\.domain) == ["postgresql.org", "example.org"], "duplicates removed, www stripped")88        #expect(m.appliedParameters?.ignored.first?.param == "images")89        #expect(ev("usage", #"{"usage":{"input":1,"output":1},"costUsd":0.1}"#) == .usage(TokenUsage(input: 1, output: 1), costUsd: 0.1, latencyMs: nil, ttftMs: nil, exactCost: false))90    }9192    @Test func storedMessageCarriesFollowupsAndBilledCost() throws {93        let j = #"{"id":"m","conversation_id":"c","role":"assistant","parts":[{"type":"text","text":"ok"}],"usage":{"input":10,"output":2,"costUsd":0.0003},"cost_usd":0.0003,"status":"complete","active":true,"created_at":"2026-11-19T14:20:30.257Z","followups":["Et ensuite ?"],"tsv":"ignored","client_request_id":"x"}"#94        let m = try JSONDecoder.api().decode(Message.self, from: Data(j.utf8))95        #expect(m.followups == ["Et ensuite ?"]); #expect(m.isCostExact)96        let estimated = try JSONDecoder.api().decode(Message.self, from: Data(#"{"id":"m","role":"assistant","parts":[],"usage":{"input":10,"output":2},"cost_usd":0.0003,"followups":null}"#.utf8))97        #expect(!estimated.isCostExact); #expect(estimated.followups == nil)98    }99100    @Test func conversationBranchFieldsAndPatch() throws {101        let c = try JSONDecoder.api().decode(Conversation.self, from: Data(#"{"id":"conv_b","title":"T","parent_id":"conv_a","branch_label":"Variante courte","branch_message_id":"msg_1"}"#.utf8))102        #expect(c.branchLabel == "Variante courte"); #expect(c.branchMessageId == "msg_1")103        #expect(ConversationPatch(branchLabel: .some("Plan B")).json["branchLabel"] == "Plan B")104        #expect(ConversationPatch(branchLabel: .some(nil)).json["branchLabel"] == .null)105        #expect(ConversationPatch(title: "x").json["branchLabel"] == nil)106    }107108    @Test func searchFiltersBuildTheServerQuery() {109        var f = SearchFilters(); #expect(f.isDefault); #expect(f.query("a")["semantic"] == .some(nil))110        f.semantic = false; f.provider = "openrouter"; f.favoritesOnly = true; f.fileType = .pdf; f.role = "assistant"; f.modelId = "or:x/y"111        let q = f.query("phares")112        #expect(q["q"] == "phares"); #expect(q["semantic"] == "0"); #expect(q["provider"] == "openrouter"); #expect(q["favorite"] == "1"); #expect(q["fileType"] == "pdf"); #expect(q["model"] == "or:x/y")113        #expect(f.activeCount == 5)114    }115116    @Test func providerRefusalMessageIsRead() async throws {117        let t = MockTransport(); t.on("PUT", "/api/providers/tavily/key", .json(422, #"{"ok":false,"message":"Clé refusée par Tavily (401)."}"#))118        await #expect { try await makeClient(t).setProviderKey("tavily", key: "tvly-x") } throws: { ($0 as? APIError)?.message == "Clé refusée par Tavily (401)." && ($0 as? APIError)?.status == 422 }119    }120}121122@Suite struct SyncTests {123    static func change(_ seq: Int, _ entity: String, _ id: String? = nil, _ op: SyncChange.Operation = .upsert) -> SyncChange { SyncChange(seq: seq, entity: entity, entityId: id, op: op) }124125    @Test func feedDecodingIsTolerant() throws {126        let j = #"{"events":[{"seq":1,"at":"2026-11-19T14:20:06.869Z","entity":"provider","id":"openrouter","op":"upsert","origin":"abc"},{"seq":"2","entity":"hologram","id":"h1","op":"transmute"},{"entity":"no-seq"}],"head":6,"truncated":false,"runs":[],"serverTime":"2026-11-19T14:27:09.848Z"}"#127        let f = try JSONDecoder.api().decode(SyncFeed.self, from: Data(j.utf8))128        #expect(f.events.count == 2, "a row without sequence number is skipped"); #expect(f.head == 6); #expect(f.events[1].seq == 2); #expect(f.events[1].op == .upsert); #expect(f.events[1].entity == "hologram")129    }130131    @Test func reducerMapsEntitiesToRefreshes() {132        func c(_ seq: Int, _ entity: String, _ id: String? = nil, _ op: SyncChange.Operation = .upsert) -> SyncChange { Self.change(seq, entity, id, op) }133        let inv = SyncInvalidation.reduce([c(1, "conversation", "conv_a"), c(2, "message", "msg_1"), c(3, "model", "claude"), c(4, "settings", "assistant"), c(5, "project", "p"), c(6, "prompt", "pr"),134                                           c(7, "preset", "ps"), c(8, "memory", "m"), c(9, "provider", "openrouter"), c(10, "draft", "conv_a"), c(11, "attachment", "att"), c(12, "hologram", "h")], after: 0)135        #expect(inv.conversationList); #expect(inv.conversations == ["conv_a"]); #expect(inv.messages == ["msg_1"]); #expect(inv.models); #expect(inv.settings); #expect(inv.projects); #expect(inv.prompts)136        #expect(inv.presets); #expect(inv.memory); #expect(inv.providers); #expect(inv.drafts == ["conv_a"]); #expect(inv.attachments); #expect(inv.head == 12, "an unknown entity still advances the cursor")137        #expect(!inv.everything); #expect(inv.touchesConversation("conv_a")); #expect(inv.touchesConversation("conv_other"), "a message change does not say its conversation: open ones are re-read")138        #expect(SyncInvalidation.reduce([c(1, "model")], after: 0).touchesConversation("conv_a") == false)139    }140141    @Test func reducerSkipsAppliedChangesAndIsOrderIndependent() {142        func c(_ seq: Int, _ entity: String, _ id: String? = nil, _ op: SyncChange.Operation = .upsert) -> SyncChange { Self.change(seq, entity, id, op) }143        let batch = [c(5, "conversation", "a"), c(6, "conversation", "a", .delete), c(7, "prompt"), c(3, "model")]144        let inv = SyncInvalidation.reduce(batch, after: 4)145        #expect(!inv.models, "seq 3 was already applied"); #expect(inv.deletedConversations == ["a"]); #expect(inv.conversations.isEmpty, "a deleted conversation is not re-read"); #expect(inv.head == 7)146        #expect(SyncInvalidation.reduce(batch.reversed(), after: 4) == inv)147        #expect(SyncInvalidation.reduce(batch + batch, after: 4) == inv, "a replayed batch gives the same refreshes")148        #expect(SyncInvalidation.reduce([], after: 9).isEmpty); #expect(SyncInvalidation.reduce([], after: 9).head == 9)149    }150151    @Test func truncatedFeedAndMergeReloadEverything() {152        let inv = SyncInvalidation.reduce(SyncFeed(events: [Self.change(40, "prompt")], head: 90, truncated: true), after: 3)153        #expect(inv.everything); #expect(inv.models && inv.settings && inv.conversationList); #expect(inv.head == 90)154        var a = SyncInvalidation.reduce([Self.change(1, "conversation", "x")]); let b = SyncInvalidation.reduce([Self.change(2, "conversation", "x", .delete), Self.change(3, "settings")])155        a.merge(b)156        #expect(a.deletedConversations == ["x"]); #expect(a.conversations.isEmpty); #expect(a.settings); #expect(a.head == 3)157    }158159    @Test func eventStreamParsing() {160        #expect(SyncEvent(SSEEvent(event: "hello", data: #"{"head":6,"runs":[]}"#)) == .hello(head: 6, runs: []))161        #expect(SyncEvent(SSEEvent(event: "resync", data: #"{"head":120}"#)) == .resync(head: 120))162        #expect(SyncEvent(SSEEvent(event: "change", data: #"{"seq":5,"at":"2026-11-19T14:20:47.599Z","entity":"message","id":"msg_x","op":"upsert","origin":null}"#, index: 5))163                == .change(SyncChange(seq: 5, entity: "message", entityId: "msg_x", at: ServerDate.parse("2026-11-19T14:20:47.599Z"))))164        #expect(SyncEvent(SSEEvent(event: "change", data: "garbage")) == .unknown("change")); #expect(SyncEvent(SSEEvent(event: "future", data: "{}")) == .unknown("future"))165    }166167    @Test func clientDeliversChangesReconnectsAndResumesFromTheLastSequence() async throws {168        let t = MockTransport()169        t.on("GET", "/api/events",170             .sse(["retry: 3000\n\n", frame("hello", #"{"head":7,"runs":[]}"#), frame("change", #"{"seq":6,"entity":"conversation","id":"conv_a","op":"upsert"}"#, id: 6), frame("change", #"{"seq":7,"entity":"model","id":"m","op":"upsert"}"#, id: 7)], closes: false),171             .fail(.networkConnectionLost),172             .sse([frame("hello", #"{"head":9,"runs":[]}"#), frame("change", #"{"seq":7,"entity":"model","id":"m","op":"upsert"}"#, id: 7), frame("change", #"{"seq":9,"entity":"prompt","id":"p","op":"delete"}"#, id: 9), frame("resync", #"{"head":30}"#)], hang: true))173        var timing = SyncClient.Timing(); timing.reconnectBase = .milliseconds(5); timing.reconnectCap = .milliseconds(20)174        let client = SyncClient(api: makeClient(t), timing: timing, sleep: { _ in try await Task.sleep(for: .milliseconds(2)) })175        var updates: [SyncUpdate] = []176        for await u in client.events(after: 5) { updates.append(u); if case .invalidate(let inv) = u, inv.everything { break } }177        let invalidations = updates.compactMap { u -> SyncInvalidation? in if case .invalidate(let i) = u { return i }; return nil }178        var merged = SyncInvalidation(); for i in invalidations { merged.merge(i) }179        #expect(updates.contains(.connected(head: 7))); #expect(updates.contains(.connected(head: 9))); #expect(updates.filter { $0 == .disconnected }.count >= 2)180        #expect(merged.conversations == ["conv_a"]); #expect(merged.models); #expect(merged.prompts); #expect(merged.everything); #expect(merged.head == 30)181        #expect(invalidations.filter(\.models).count == 2, "seq 7 replayed after the reconnection is skipped; the resync marks models once more")182        let afters = t.requests.filter { $0.path == "/api/events" }.map { $0.query ?? "" }183        #expect(afters == ["after=5", "after=7", "after=7"], "each reconnection resumes from the last sequence delivered")184    }185186    @Test func clientReportsADeadSession() async {187        let t = MockTransport(); t.on("GET", "/api/events", .json(401, #"{"error":"locked","code":"locked"}"#, headers: ["x-csa-locked": "1"]))188        var updates: [SyncUpdate] = []189        for await u in SyncClient(api: makeClient(t)).events(after: 0) { updates.append(u) }190        #expect(updates == [.sessionEnded])191    }192193    @Test func pullAndPendingDraftArbitration() async throws {194        let t = MockTransport(); t.on("GET", "/api/sync", .json(200, #"{"events":[{"seq":8,"entity":"settings","id":"instructions","op":"upsert"}],"head":8,"truncated":false,"runs":[]}"#))195        let feed = try await SyncClient(api: makeClient(t)).pull(after: 7)196        #expect(t.requests.last?.query == "after=7"); #expect(SyncInvalidation.reduce(feed, after: 7).settings)197        let d = PendingDraft(scope: "conv_a", text: "hors ligne", updatedAt: Date(timeIntervalSince1970: 1000))198        #expect(d.shouldReplace(serverUpdatedAt: nil)); #expect(d.shouldReplace(serverUpdatedAt: Date(timeIntervalSince1970: 900))); #expect(!d.shouldReplace(serverUpdatedAt: Date(timeIntervalSince1970: 1100)), "the newer of local / server wins")199    }200}201202@Suite struct PromptTemplateTests {203    @Test func variablesInOrderWithoutDuplicates() {204        #expect(PromptTemplate.variables(in: "Résume {{ texte }} pour {{public}} ; ton : {{ton}} ; encore {{texte}}.") == ["texte", "public", "ton"])205        #expect(PromptTemplate.variables(in: "Aucune variable, ni {simple} ni {{}} ni {{\n}}").isEmpty)206    }207    @Test func fillKeepsUnfilledPlaceholders() {208        let body = "Traduis {{texte}} en {{langue}} ({{langue}})."209        #expect(PromptTemplate.fill(body, values: ["texte": "« bonjour »", "langue": "anglais"]) == "Traduis « bonjour » en anglais (anglais).")210        #expect(PromptTemplate.fill(body, values: ["langue": "anglais"]) == "Traduis {{texte}} en anglais (anglais).")211        #expect(PromptTemplate.fill("Rien", values: ["a": "b"]) == "Rien")212        #expect(PromptTemplate.fill("{{a}}", values: ["a": "{{b}}", "b": "x"]) == "{{b}}", "a value is never re-expanded")213    }214    @Test func composerTriggers() {215        #expect(ComposerTrigger(draft: "/") == .command(query: "")); #expect(ComposerTrigger(draft: "/résu") == .command(query: "résu"))216        #expect(ComposerTrigger(draft: "/a\nb") == .none, "a multi-line message starting with a slash is a message")217        #expect(ComposerTrigger(draft: "Compare avec @gem") == .mention(query: "gem", location: 13, length: 4))218        #expect(ComposerTrigger(draft: "@") == .mention(query: "", location: 0, length: 1))219        #expect(ComposerTrigger(draft: "écris à contact@spboucher.ai") == .none, "an e-mail address is not a mention")220        #expect(ComposerTrigger(draft: "Bonjour @claude ") == .none, "the mention ends with the word")221        #expect(ComposerTrigger(draft: "Bonjour") == .none); #expect(!ComposerTrigger(draft: "").isActive)222    }223}224225@Suite struct LocalRouteTests {226    static let model = #"""227    {"id":"local:maclustr-qwen3","provider":"local","displayName":"Qwen3-30B-A3B Instruct (MLX 4-bit)","kind":"chat","api":"chat","status":"catalog","available":true,"tested":false,"capabilities":{"text":true,"tools":true,"streaming":true},"contextWindow":32768,"maxOutputTokens":8192,"pricing":{"input":0,"output":0,"notes":"Inférence locale : aucun coût par jeton."},"benchmark":null,"hidden":false,"favorite":false,"route":"local","creator":"qwen","creatorName":"Qwen","logo":"qwen","description":"Modèle servi par MacLustr AI.","categories":["local","open-weight","tools"],"catalog":{"source":"local","slug":"maclustr-qwen3","quantization":"4-bit","license":"apache-2.0","revision":"a1b2c3d","servedBy":"MacLustr AI · M3U96a","huggingFaceId":"mlx-community/Qwen3-30B-A3B-Instruct-4bit","inputModalities":["text"],"outputModalities":["text"],"supportedParameters":["tools","temperature"],"futureLocalField":true},"lastUsedAt":null}228    """#229230    @Test func localModelDecodesWithItsOwnRouteAndFacts() throws {231        let m = try JSONDecoder.api().decode(AIModel.self, from: Data(Self.model.utf8))232        #expect(m.route == "local"); #expect(m.isLocal); #expect(!m.isOpenRouter); #expect(!m.isDirect); #expect(m.provider == "local")233        #expect(m.creator == "qwen"); #expect(m.logo == "qwen"); #expect(m.isCatalogOnly); #expect(m.isSelectableForChat)234        #expect(m.inputPrice == 0); #expect(m.outputPrice == 0); #expect(!m.hasVariablePrice); #expect(m.categories.contains("local")); #expect(m.isOpenWeight)235        #expect(m.catalog?.source == "local"); #expect(m.catalog?.quantization == "4-bit"); #expect(m.catalog?.license == "apache-2.0"); #expect(m.catalog?.revision == "a1b2c3d")236        #expect(m.catalog?.servedBy == "MacLustr AI · M3U96a"); #expect(m.catalog?.huggingFaceId == "mlx-community/Qwen3-30B-A3B-Instruct-4bit")237        let again = try JSONDecoder.api().decode(AIModel.self, from: JSONEncoder.api().encode(m))238        #expect(again == m, "the local facts survive the cache")239    }240241    @Test func routeIsDerivedFromTheIdWhenTheServerDoesNotSendIt() throws {242        let m = try JSONDecoder.api().decode(AIModel.self, from: Data(#"{"id":"local:maclustr-qwen3","displayName":"Qwen3"}"#.utf8))243        #expect(m.route == "local"); #expect(m.creator == "local", "a local id does not name its maker: nothing is guessed")244        #expect(Maker.route(forModelId: "or:x/y") == "openrouter"); #expect(Maker.route(forModelId: "claude-haiku-5-5", provider: "anthropic") == "direct"); #expect(Maker.route(forModelId: "x", provider: "local") == "local")245        #expect(Provider.routeLabel("local") == "Local (MacLustr)"); #expect(Provider.label("local") == "MacLustr AI (local)"); #expect(ModelFacet.label("local") == "Local")246    }247248    @Test func routeFilterAndOrderPlaceLocalBetweenDirectAndOpenRouter() throws {249        let local = try JSONDecoder.api().decode(AIModel.self, from: Data(Self.model.utf8))250        let direct = AIModel(id: "claude-haiku-5-5", provider: "anthropic", displayName: "Claude Haiku 5.5"), or = AIModel(id: "or:google/gemini-4-neon", provider: "openrouter", displayName: "Gemini 4 Neon", status: "catalog")251        let all = [or, local, direct]252        #expect(all.applying(ModelQuery()).map(\.route) == ["direct", "local", "openrouter"])253        var q = ModelQuery(); q.routes = ["local"]254        #expect(all.applying(q).map(\.id) == ["local:maclustr-qwen3"])255        q = ModelQuery(); q.categories = ["local"]; #expect(all.applying(q).map(\.id) == ["local:maclustr-qwen3"])256        q = ModelQuery(); q.text = "qwen3"; #expect(all.applying(q).first?.id == "local:maclustr-qwen3")257        #expect(TurnOptions(modelId: "local:maclustr-qwen3", routingMode: .manual).payload["modelId"] == "local:maclustr-qwen3")258    }259260    @Test func localAnswersAreNeverLabelledEstimated() {261        let m = Message(id: "a", conversationId: "c", role: .assistant, parts: [.text("ok")], modelId: "local:maclustr-qwen3", provider: "local", usage: TokenUsage(input: 20, output: 5), costUsd: 0)262        #expect(m.costLabel(route: "local") == "local · 0 $"); #expect(m.costLabel(route: "direct") == "0 $ estimé")263        var billed = m; billed.costUsd = 0.02; billed.exactCost = true264        #expect(billed.costLabel(route: "openrouter") == "0.02 $ facturé"); #expect(Message(id: "u", conversationId: "c", role: .user, parts: []).costLabel(route: "direct") == nil)265    }266267    @Test func localProviderRowAndKeyManagement() async throws {268        let payload = #"{"providers":[{"id":"openai","name":"OpenAI","kind":"models","route":"direct","logo":"openai","configured":true,"keySource":"env","keyHint":"…0Q8A","manageable":false},{"id":"local","name":"MacLustr AI (local)","kind":"models","route":"local","logo":"","configured":true,"keySource":"stored","keyHint":"…9f2c","manageable":true,"validatedAt":"2026-11-19T16:00:00.000Z","info":{"endpoint":"mlx"},"models":{"total":1,"chat":1},"health":{"state":"ok","recentFailures":0,"retryInSec":0,"active":0}}],"categoryRules":{"local":"Servi par MacLustr AI, le service d'inférence du propriétaire."}}"#269        let o = try JSONDecoder.api().decode(ProvidersOverview.self, from: Data(payload.utf8))270        let local = try #require(o.provider("local"))271        #expect(local.route == "local"); #expect(local.manageable); #expect(local.logo == "", "no artwork: the app draws a monogram"); #expect(local.models?.chat == 1); #expect(local.keyHint == "…9f2c")272        #expect(o.categoryRules["local"]?.isEmpty == false)273        let t = MockTransport()274        t.on("PUT", "/api/providers/local/key", .json(200, #"{"ok":true}"#)); t.on("DELETE", "/api/providers/local/key", .json(200, #"{"removed":true,"fallback":false}"#))275        t.on("POST", "/api/providers/local/test", .json(200, #"{"ok":true,"message":"MacLustr AI répond.","info":null}"#)); t.on("POST", "/api/providers/anthropic/test", .json(200, #"{"ok":true,"message":"Clé valide."}"#))276        let api = makeClient(t)277        try await api.setProviderKey("local", key: "mlx_sk_test")278        #expect(JSONValue.parse(t.requests.last?.body ?? Data())?["key"] == "mlx_sk_test")279        #expect(try await api.removeProviderKey("local") == ProviderKeyRemoval(removed: true, fallback: false))280        #expect(try await api.testProvider("local").ok); let direct = try await api.testProvider("anthropic"); #expect(direct.ok); #expect(direct.message == "Clé valide.")281    }282}283
Files main
Menu

Theme