SPB Git

Repository Public

SpacesTests.swift 18.9 KB 302 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Tests/SpacesTests.swift4//  Description: Command Center index, force layout, constellation decoding, search filters and quick actions — plus5//               live checks of the constellation and of the filtered search against the development backend.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import CoreGraphics12import Foundation13import Testing14@testable import SPChat1516private func json(_ s: String) -> JSONValue { (try? JSONDecoder().decode(JSONValue.self, from: Data(s.utf8))) ?? .null }1718@Suite struct CommandCenterIndexTests {19    private func conversation(_ id: String, _ title: String) throws -> Conversation {20        try JSONDecoder().decode(Conversation.self, from: Data(Fixtures.conversationJSON(id: id, title: title).utf8))21    }22    private func input() throws -> CommandCenterInput {23        var i = CommandCenterInput()24        i.conversations = [try conversation("conv_a", "Histoire de Gatineau"), try conversation("conv_b", "Modèle de régression hédonique"), try conversation("conv_c", "Recette de pain")]25        var opus = AIModel(id: "claude-opus-5-5", provider: "anthropic", displayName: "Claude Opus 5.5")26        opus.favorite = true27        let haiku = AIModel(id: "claude-haiku-5-5", provider: "anthropic", displayName: "Claude Haiku 5.5")28        let neon = AIModel(id: "or:google/gemini-4-neon", provider: "openrouter", displayName: "Gemini 4 Neon", creator: "google", creatorName: "Google", status: "catalog")29        i.models = [haiku, neon, opus]30        i.preferredModelIds = ["claude-opus-5-5"]31        i.currentModelId = "claude-haiku-5-5"32        i.prompts = [SavedPrompt(id: "pr_1", title: "Relecture", body: "Relis {{texte}}"), SavedPrompt(id: "pr_2", title: "Résumé exécutif", body: "Résume", favorite: true)]33        i.tools = [ServerTool(name: "web_search", description: nil, category: "web", permission: "auto"), ServerTool(name: "python", description: nil, category: "code", permission: "auto")]34        i.disabledTools = ["python"]35        return i36    }3738    @Test func withoutAQueryEverySectionShowsItsFirstItemsInOrder() throws {39        let groups = CommandCenterIndex(try input()).results(for: "")40        #expect(groups.map(\.section) == [.actions, .conversations, .models, .projects, .prompts, .settings])41        #expect(groups.first?.items.first?.action == .newConversation)42        #expect(groups.first { $0.section == .conversations }?.items.map(\.title) == ["Histoire de Gatineau", "Modèle de régression hédonique", "Recette de pain"])43        // the owner's preferred models come before the rest of the catalogue; favourite prompts before the others44        #expect(groups.first { $0.section == .models }?.items.first?.action == .selectModel("claude-opus-5-5"))45        #expect(groups.first { $0.section == .prompts }?.items.first?.action == .insertPrompt("pr_2"))46        for g in groups { #expect(g.items.count <= CommandCenterIndex.limit(g.section, searching: false)) }47    }4849    @Test func typingFiltersEverySectionAndIgnoresAccentsAndCase() throws {50        let index = CommandCenterIndex(try input())51        let gat = index.results(for: "GATINEAU")52        #expect(gat.count == 1)53        #expect(gat.first?.items.first?.action == .openConversation("conv_a"))54        let modele = index.results(for: "modele")55        #expect(modele.contains { $0.section == .conversations && $0.items.first?.action == .openConversation("conv_b") })56        #expect(modele.contains { $0.section == .actions && $0.items.contains { $0.action == .panel("models") } })57        #expect(index.results(for: "zzzz-rien").isEmpty)58        // several words must all match59        #expect(index.results(for: "histoire pain").isEmpty)60        #expect(index.results(for: "claude opus").first?.items.first?.action == .selectModel("claude-opus-5-5"))61    }6263    @Test func theBestMatchIsFirstSoReturnRunsIt() throws {64        let index = CommandCenterIndex(try input())65        // a model id, a maker and a route are all searchable; the section of the best item leads66        #expect(index.results(for: "gemini").first?.items.first?.action == .selectModel("or:google/gemini-4-neon"))67        #expect(index.results(for: "openrouter").flatMap(\.items).contains { $0.action == .selectModel("or:google/gemini-4-neon") })68        #expect(index.results(for: "arène").first?.items.first?.action == .arena)69        #expect(index.results(for: "nouvelle conv").first?.items.first?.action == .newConversation)70        #expect(index.results(for: "relecture").first?.items.first?.action == .insertPrompt("pr_1"))71        #expect(index.results(for: "réglages").first?.items.first?.action == .space("settings"))72    }7374    @Test func switchesReportTheirStateAndPanelsNeedAnOpenConversation() throws {75        var i = try input()76        let items = CommandCenterIndex(i).items77        #expect(items.first { $0.action == .toggleWebSearch }?.isOn == false)78        #expect(items.first { $0.action == .toggleTool("python") }?.isOn == false)79        #expect(items.first { $0.action == .toggleTool("web_search") }?.isOn == true)80        #expect(items.first { $0.action == .selectModel("claude-haiku-5-5") }?.isOn == true)81        #expect(items.first { $0.action == .selectModel("claude-opus-5-5") }?.isOn == nil)82        #expect(!items.contains { $0.action == .panel("timeline") })83        #expect(Set(items.map(\.id)).count == items.count)84        i.hasOpenConversation = true; i.currentConversationId = "conv_a"; i.toolsEnabled = false; i.webSearch = true85        let next = CommandCenterIndex(i).items86        #expect(next.contains { $0.action == .panel("timeline") } && next.contains { $0.action == .panel("lens") })87        // the conversation on screen is not proposed again; single tools disappear when tools are off88        #expect(!next.contains { $0.action == .openConversation("conv_a") })89        #expect(!next.contains { if case .toggleTool = $0.action { return true } else { return false } })90        #expect(next.first { $0.action == .toggleWebSearch }?.isOn == true)91    }92}9394@Suite struct ForceLayoutTests {95    private func chain(_ n: Int) -> [ForceLayout.Edge] { (0..<(n - 1)).map { ForceLayout.Edge(a: $0, b: $0 + 1, length: 60, strength: 1) } }9697    @Test func theSameGraphAlwaysSettlesInTheSameShape() {98        var a = ForceLayout(count: 14, edges: chain(14)), b = ForceLayout(count: 14, edges: chain(14))99        #expect(a == b)100        a.settle(); b.settle()101        #expect(a.positions == b.positions)102        var c = ForceLayout(count: 14, edges: chain(14), seed: 42)103        c.settle()104        #expect(c.positions != a.positions)105    }106107    @Test func itConvergesWithoutNaNAndKeepsNodesApart() {108        var l = ForceLayout(count: 40, edges: chain(40) + [ForceLayout.Edge(a: 0, b: 39, length: 120, strength: 0.4)])109        var steps = 0110        while !l.isSettled && steps < 2000 { l.step(); steps += 1 }111        #expect(l.isSettled && steps < 600)112        #expect(l.positions.allSatisfy { $0.x.isFinite && $0.y.isFinite })113        var closest = Double.infinity114        for i in 0..<40 { for j in (i + 1)..<40 { closest = min(closest, hypot(Double(l.positions[i].x - l.positions[j].x), Double(l.positions[i].y - l.positions[j].y))) } }115        #expect(closest > 8)116        #expect(l.bounds.width < 3000 && l.bounds.height < 3000)117        // a settled layout does not move any more118        let frozen = l.positions119        l.step()120        #expect(l.positions == frozen)121    }122123    @Test func linkedNodesEndCloserThanUnlinkedOnes() {124        // two triangles with no link between them125        let edges = [(0, 1), (1, 2), (0, 2), (3, 4), (4, 5), (3, 5)].map { ForceLayout.Edge(a: $0.0, b: $0.1, length: 60, strength: 1) }126        var l = ForceLayout(count: 6, edges: edges)127        l.settle()128        func d(_ a: Int, _ b: Int) -> Double { hypot(Double(l.positions[a].x - l.positions[b].x), Double(l.positions[a].y - l.positions[b].y)) }129        let linked = [d(0, 1), d(1, 2), d(0, 2), d(3, 4), d(4, 5), d(3, 5)].reduce(0, +) / 6130        let unlinked = [d(0, 3), d(0, 4), d(0, 5), d(1, 3), d(1, 4), d(1, 5), d(2, 3), d(2, 4), d(2, 5)].reduce(0, +) / 9131        #expect(linked < unlinked)132    }133134    @Test func degenerateInputsAreHarmless() {135        var empty = ForceLayout(count: 0, edges: [])136        empty.settle()137        #expect(empty.positions.isEmpty && empty.isSettled && empty.bounds == .zero)138        var one = ForceLayout(count: 1, edges: [ForceLayout.Edge(a: 0, b: 0, length: 10, strength: 1)])139        one.settle()140        #expect(one.positions.count == 1 && one.edges.isEmpty)141        // out-of-range edges are dropped; coincident nodes separate instead of dividing by zero142        var same = ForceLayout(positions: [CGPoint(x: 5, y: 5), CGPoint(x: 5, y: 5), CGPoint(x: CGFloat.nan, y: 0)], edges: [ForceLayout.Edge(a: 0, b: 9, length: 10, strength: 1)], alpha: 1)143        #expect(same.edges.isEmpty)144        same.settle()145        #expect(same.positions.allSatisfy { $0.x.isFinite && $0.y.isFinite })146        #expect(same.positions[0] != same.positions[1])147    }148149    @Test func aPinnedNodeStaysWhereTheFingerLeftIt() {150        var l = ForceLayout(count: 8, edges: chain(8))151        l.settle()152        var again = ForceLayout(positions: l.positions, edges: l.edges, alpha: 0.3)153        again.move(3, to: CGPoint(x: 400, y: -250))154        again.pinned = [3]155        again.settle()156        #expect(again.positions[3] == CGPoint(x: 400, y: -250))157        // its neighbours followed it158        #expect(hypot(Double(again.positions[2].x) - 400, Double(again.positions[2].y) + 250) < hypot(Double(l.positions[2].x) - 400, Double(l.positions[2].y) + 250))159    }160161    @Test func aTallCanvasStretchesTheGraphVertically() {162        var tall = ForceLayout(count: 30, edges: [], aspect: 1.9), wide = ForceLayout(count: 30, edges: [], aspect: 0.55)163        tall.settle(); wide.settle()164        #expect(tall.bounds.height > tall.bounds.width)165        #expect(wide.bounds.width > wide.bounds.height)166    }167}168169@Suite struct ConstellationDecodingTests {170    static let payload = #"""171    {"nodes":[{"id":"conv_a","title":"A","projectId":"prj_1","projectName":"Thèse","projectColor":"#8F80FF","modelId":"or:google/gemini-4-neon","messages":"12","costUsd":"0.0196","parentId":null,"branchLabel":null,"pinned":true,"favorite":false,"lastAt":"2026-11-19T14:20:30.259Z","createdAt":"2026-11-19T14:20:28.451Z"},172              {"id":"conv_b","title":"B","projectId":null,"modelId":"claude-opus-5-5","messages":2,"costUsd":0.12,"parentId":"conv_a","branchLabel":"essai"},173              {"title":"sans identifiant"}],174     "links":[{"source":"conv_a","target":"conv_b","kind":"branch","weight":1},{"source":"conv_a","target":"conv_zz","kind":"topic","weight":0.9},{"source":"conv_b","target":"conv_b","kind":"topic","weight":0.9},{"source":"conv_b","target":"conv_a","kind":"hologram"}],175     "projects":[{"id":"prj_1","name":"Thèse","color":"#8F80FF"}],176     "basis":{"topic":"Proximité sémantique.","branch":"Lien de bifurcation enregistré.","project":"Même projet.","futur":42}}177    """#178179    @Test func nodesAreTolerantAndDanglingLinksAreDropped() {180        let g = Constellation(json(Self.payload))181        #expect(g.nodes.map(\.id) == ["conv_a", "conv_b"])182        #expect(g.nodes.first?.messages == 12 && g.nodes.first?.costUsd == 0.0196 && g.nodes.first?.pinned == true && g.nodes.first?.lastAt != nil)183        #expect(g.nodes.last?.parentId == "conv_a" && g.nodes.last?.branchLabel == "essai")184        // a link to a conversation that is not in the graph, and a link from a node to itself, are not drawn185        #expect(g.links.map(\.id) == ["conv_a>conv_b>branch", "conv_b>conv_a>hologram"])186        #expect(g.links.last?.weight == 0.5)187        #expect(g.projects.first?.name == "Thèse")188        #expect(g.basis == ["topic": "Proximité sémantique.", "branch": "Lien de bifurcation enregistré.", "project": "Même projet."])189    }190191    @Test func springsFollowTheKindOfLink() {192        let g = Constellation(json(Self.payload))193        let edges = ForceLayout.edges(for: g)194        #expect(edges.count == 2)195        #expect(edges.first == ForceLayout.Edge(a: 0, b: 1, length: 60, strength: 1))196        // an unknown kind is treated as a topic link of its weight197        #expect(edges.last?.a == 1 && edges.last?.b == 0 && (edges.last?.length ?? 0) > 60)198        #expect(Constellation(.null).nodes.isEmpty && ForceLayout.edges(for: Constellation(.null)).isEmpty)199    }200201    @MainActor @Test func projectColoursComeFromTheServerOrStayNeutral() {202        #expect(ConstellationView.rgb(hex: "#8F80FF")?.r == Double(0x8F) / 255)203        #expect(ConstellationView.rgb(hex: "fff")?.b == 1)204        #expect(ConstellationView.rgb(hex: "iris") == nil && ConstellationView.rgb(hex: "#12345") == nil && ConstellationView.rgb(hex: "") == nil)205        #expect(ConstellationView.projectColor(nil, id: nil) == nil)206        #expect(ConstellationView.projectColor("iris", id: "prj_1") != nil)207        #expect(ConstellationView.projectColor("iris", id: "prj_1") == ConstellationView.projectColor(nil, id: "prj_1"))208    }209}210211@Suite struct SearchFiltersTests {212    @Test func anEmptyFilterSendsOnlyTheQuery() {213        let f = SearchFilters()214        #expect(!f.isActive && f.activeCount == 0)215        #expect(f.queryItems("pain") == [URLQueryItem(name: "q", value: "pain")])216    }217218    @Test func everyFilterMapsToItsServerParameter() {219        var f = SearchFilters()220        f.modelId = "or:google/gemini-4-neon"; f.provider = "openrouter"; f.projectId = "prj_1"; f.fileType = "pdf"; f.favoritesOnly = true; f.role = "assistant"; f.semantic = false221        f.from = Date(timeIntervalSince1970: 1_795_000_000); f.to = Date(timeIntervalSince1970: 1_795_090_000)222        let items = Dictionary(uniqueKeysWithValues: f.queryItems("version").map { ($0.name, $0.value ?? "") })223        #expect(items["q"] == "version" && items["model"] == "or:google/gemini-4-neon" && items["provider"] == "openrouter" && items["project"] == "prj_1")224        #expect(items["fileType"] == "pdf" && items["favorite"] == "1" && items["role"] == "assistant" && items["semantic"] == "0")225        #expect(items["from"].flatMap(ISO8601.parse) == f.from && items["to"].flatMap(ISO8601.parse) == f.to)226        #expect(f.isActive && f.activeCount == 9)227        f.semantic = true; f.favoritesOnly = false228        #expect(f.activeCount == 7 && !f.queryItems("x").contains { $0.name == "semantic" || $0.name == "favorite" })229    }230}231232@Suite struct QuickActionsTests {233    @Test func shortcutTypesMapToDeepLinksAndUnknownTypesAreRefused() {234        #expect(QuickActions.url(forType: "ai.spboucher.spchat.shortcut.new")?.absoluteString == "spchat://new")235        #expect(QuickActions.url(forType: "ai.spboucher.spchat.shortcut.search")?.absoluteString == "spchat://search")236        #expect(QuickActions.url(forType: "ai.spboucher.spchat.shortcut.arena")?.absoluteString == "spchat://arena")237        #expect(QuickActions.url(forType: "ai.spboucher.spchat.shortcut.settings") == nil)238        #expect(QuickActions.url(forType: "com.example.shortcut.new") == nil)239    }240241    @Test func theInfoPlistDeclaresTheThreeShortcuts() throws {242        let items = try #require(Bundle.main.object(forInfoDictionaryKey: "UIApplicationShortcutItems") as? [[String: Any]])243        let types = items.compactMap { $0["UIApplicationShortcutItemType"] as? String }244        #expect(types == ["ai.spboucher.spchat.shortcut.new", "ai.spboucher.spchat.shortcut.search", "ai.spboucher.spchat.shortcut.arena"])245        #expect(types.allSatisfy { QuickActions.url(forType: $0) != nil })246        #expect(items.allSatisfy { ($0["UIApplicationShortcutItemTitle"] as? String)?.isEmpty == false && ($0["UIApplicationShortcutItemSymbolName"] as? String)?.isEmpty == false })247    }248}249250@Suite(.serialized, .enabled(if: Live.enabled)) @MainActor struct SpacesLiveTests {251    @Test func theConstellationDecodesWithNodesLinksAndBasisTexts() async throws {252        let env = Live.environment()253        let g = try await env.api.constellation(limit: 60)254        #expect(!g.nodes.isEmpty)255        #expect(g.nodes.allSatisfy { $0.id.hasPrefix("conv_") && !$0.title.isEmpty })256        // every link joins two nodes of the graph, and every kind of link present has its explanation257        let ids = Set(g.nodes.map(\.id))258        #expect(g.links.allSatisfy { ids.contains($0.source) && ids.contains($0.target) })259        for kind in Set(g.links.map(\.kind)) { #expect(g.basis[kind]?.isEmpty == false, "pas de texte « basis » pour \(kind)") }260        #expect(g.basis["topic"]?.isEmpty == false && g.basis["branch"]?.isEmpty == false && g.basis["project"]?.isEmpty == false)261        // the real graph lays out262        var layout = ForceLayout(count: g.nodes.count, edges: ForceLayout.edges(for: g), aspect: 1.6)263        layout.settle()264        #expect(layout.isSettled && layout.positions.count == g.nodes.count && layout.positions.allSatisfy { $0.x.isFinite && $0.y.isFinite })265        // the view model loads the same graph and ends with one position per node266        let model = ConstellationModel(api: env.api)267        await model.load(reduceMotion: true)268        #expect(await TestEnv.wait(timeout: 10) { !model.isSettling && model.positions.count == model.nodes.count && !model.nodes.isEmpty })269        #expect(model.error == nil)270    }271272    @Test func theFilteredSearchHonoursModelRoleAndExactWords() async throws {273        let env = Live.environment()274        // its own data: one short exchange carrying a unique word (the shared dev database is emptied by other suites)275        let marker = "zq" + UUID().uuidString.prefix(8).lowercased()276        let session = env.newSession()277        session.composerText = "Réponds exactement par : marqueur \(marker)"278        session.sendComposer(options: Live.options)279        let sent = await TestEnv.wait(timeout: 60) { session.phase == .idle && session.messages.count == 2 }280        #expect(sent)281        let created = try #require(session.conversationId)282        defer { Task { try? await env.api.deleteConversation(created) } }283        let all = try await env.api.search(marker, filters: SearchFilters())284        #expect(!all.isEmpty)285        var exact = SearchFilters(); exact.semantic = false286        let words = try await env.api.search(marker, filters: exact)287        #expect(!words.isEmpty && words.count <= all.count + 0)288        #expect(words.allSatisfy { ($0.snippet + $0.title).localizedCaseInsensitiveContains(marker) })289        let modelId = try #require(words.compactMap(\.modelId).first)290        var byModel = exact; byModel.modelId = modelId; byModel.role = "assistant"291        let answers = try await env.api.search(marker, filters: byModel)292        #expect(!answers.isEmpty)293        #expect(answers.allSatisfy { $0.modelId == modelId && $0.role == "assistant" })294        var mine = exact; mine.role = "user"295        #expect(try await env.api.search(marker, filters: mine).allSatisfy { $0.role == "user" })296        var none = exact; none.modelId = "modele-qui-n-existe-pas"297        #expect(try await env.api.search(marker, filters: none).isEmpty)298        var future = exact; future.from = Date().addingTimeInterval(86_400)299        #expect(try await env.api.search(marker, filters: future).isEmpty)300    }301}302
Files main
Menu

Theme