Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/MacLogicTests.swift3// Description: Unit tests of the Mac shell's pure logic: window layout ↔ synced workspace mapping (both ways), the shortcut table's collision check, notification routes, the audit CSV, and the wording of unpriced costs.4import Foundation5import Testing6import VQuantCore7import VQuantKit8@testable import VQuantAppLogic910@Suite struct WorkspaceMappingTests {11 private func layout(_ windows: [SavedWorkspace.Window], name: String = "mac-test-layout") -> SavedWorkspace { SavedWorkspace(name: name, windows: windows) }1213 @Test func roundTripKeepsSectionSymbolFrameAndKind() {14 let windows = [15 SavedWorkspace.Window(section: "research", symbol: "AAPL", frame: [10, 20, 1320, 840], kind: "main"),16 SavedWorkspace.Window(section: "chart", symbol: "MSFT", frame: [1400, 60, 900, 600], kind: "chart"),17 SavedWorkspace.Window(section: "statements", symbol: "NVDA", frame: nil, kind: "main"),18 ]19 let w = WorkspaceMapping.workspace(from: layout(windows))20 #expect(w != nil)21 #expect(w?.name == "mac-test-layout")22 #expect(w?.layout.panelIds == ["w1", "w2", "w3"])23 #expect(w?.panels["w1"]?.type.known == .chat && w?.panels["w2"]?.type.known == .chart && w?.panels["w3"]?.type.known == .statements)24 #expect(w.map(WorkspaceMapping.windows(of:)) == windows)25 // through the JSON the server stores (what another device receives)26 let wire = try? VQJSON.parse(w!.json.data())27 let back = wire?.objectValue.map(VQWorkspace.init(raw:))28 #expect(back.map(WorkspaceMapping.windows(of:)) == windows)29 }3031 @Test func singleWindowIsOnePanelNotASplit() {32 let w = WorkspaceMapping.workspace(from: layout([.init(section: "quant", symbol: "SPY", frame: nil, kind: "main")]))33 #expect(w?.layout.kind == .panel && w?.layout.panelIds == ["w1"] && w?.validationIssues().isEmpty == true)34 }3536 @Test func everySectionWithAPanelTypeMapsAndTheOthersDoNot() {37 for s in ["research", "studio", "overview", "markets", "watchlists", "charting", "statements", "quant", "portfolio", "data", "risk"] {38 #expect(WorkspaceMapping.panelType(section: s, kind: "main") != nil, "\(s)")39 }40 for s in ["agent", "jobs", "documents", "something-new"] {41 #expect(WorkspaceMapping.panelType(section: s, kind: "main") == nil, "\(s)")42 // one unmapped window keeps the whole layout on this Mac43 #expect(WorkspaceMapping.workspace(from: layout([.init(section: "research", symbol: "AAPL", frame: nil, kind: "main"), .init(section: s, symbol: nil, frame: nil, kind: "main")])) == nil)44 }45 #expect(WorkspaceMapping.workspace(from: layout([])) == nil)46 }4748 @Test func foreignPanelsOpenAsTheNearestSection() {49 func panel(_ t: String, _ symbol: String? = nil) -> VQuantKit.VQPanel {50 var raw: VQJSONObject = ["type": .string(t), "title": .string(t)]51 if let symbol { raw["config"] = .object(["symbol": .string(symbol)]) }52 return VQuantKit.VQPanel(raw: raw)53 }54 let expected: [(String, String)] = [("chart", "charting"), ("watchlist", "watchlists"), ("chat", "research"), ("notebook", "research"), ("quant", "quant"), ("options", "quant"),55 ("portfolio", "portfolio"), ("risk", "risk"), ("statements", "statements"), ("table", "data"), ("macro", "overview"), ("quote", "overview"),56 ("news", "overview"), ("note", "studio"), ("a-panel-of-2027", "overview")]57 var panels: [String: VQuantKit.VQPanel] = [:]58 for (i, e) in expected.enumerated() { panels["p\(i)"] = panel(e.0, i == 0 ? "TSLA" : nil) }59 let w = VQWorkspace(name: "From the web", layout: .split(.row, children: expected.indices.map { .panel("p\($0)") }), panels: panels)60 let windows = WorkspaceMapping.windows(of: w)61 #expect(windows.map(\.section) == expected.map(\.1))62 #expect(windows.allSatisfy { $0.kind == "main" && $0.frame == nil })63 #expect(windows[0].symbol == "TSLA" && windows[1].symbol == nil)64 }6566 @Test func aLayoutWrittenByTheMacFollowsTheWebConventions() {67 let w = WorkspaceMapping.workspace(from: layout([.init(section: "charting", symbol: "AAPL", frame: nil, kind: "main"), .init(section: "research", symbol: "AAPL", frame: nil, kind: "main"),68 .init(section: "quant", symbol: nil, frame: nil, kind: "main")]))!69 // split sizes are percentages that sum to 100, one per child70 #expect(w.layout.sizes == [33.33, 33.33, 33.34] && w.layout.sizes.reduce(0, +) == 100)71 #expect(WorkspaceMapping.equalSizes(2) == [50, 50] && WorkspaceMapping.equalSizes(4) == [25, 25, 25, 25] && WorkspaceMapping.equalSizes(0).isEmpty)72 #expect(abs(WorkspaceMapping.equalSizes(7).reduce(0, +) - 100) < 1e-9)73 #expect(w.panels["w1"]?.config["symbol"]?.stringValue == "AAPL" && w.panels["w3"]?.config["symbol"] == nil)74 #expect(WorkspaceMapping.isMacLayout(w) && w.validationIssues().isEmpty)75 }7677 /// A workspace as the web app stores it (CONTRACT §1.1): `activeSymbol`, `template`, percentage sizes, nested78 /// splits, panels that follow the active symbol, one that has its own, one that is unlinked.79 @Test func aWorkspaceMadeOnTheWebOpensOnTheMac() throws {80 let json = """81 { "name": "Earnings desk", "icon": "chart", "activeSymbol": "NVDA", "template": "earnings",82 "layout": { "type": "split", "direction": "row", "sizes": [60, 40], "children": [83 { "type": "panel", "panelId": "p-chart" },84 { "type": "split", "direction": "column", "sizes": [50, 25, 25], "children": [85 { "type": "panel", "panelId": "p-fin" }, { "type": "panel", "panelId": "p-own" }, { "type": "panel", "panelId": "p-free" } ] } ] },86 "panels": {87 "p-chart": { "type": "chart", "title": "Chart", "config": { "interval": "1d", "indicators": ["sma50"] } },88 "p-fin": { "type": "statements", "title": "Financials", "config": { "linked": true, "period": "quarter" } },89 "p-own": { "type": "quote", "title": "Peer", "config": { "symbol": "AMD" } },90 "p-free": { "type": "watchlist", "title": "List", "config": { "linked": false, "watchlistId": "wl-1" } } } }91 """92 let web = VQWorkspace(raw: try VQJSON.parse(Data(json.utf8)).objectValue ?? [:])93 #expect(!WorkspaceMapping.isMacLayout(web))94 #expect(WorkspaceMapping.windows(of: web) == [95 SavedWorkspace.Window(section: "charting", symbol: "NVDA", frame: nil, kind: "main"), // follows activeSymbol96 SavedWorkspace.Window(section: "statements", symbol: "NVDA", frame: nil, kind: "main"), // linked: true97 SavedWorkspace.Window(section: "overview", symbol: "AMD", frame: nil, kind: "main"), // its own symbol wins98 SavedWorkspace.Window(section: "watchlists", symbol: nil, frame: nil, kind: "main"), // linked: false does not follow99 ])100 // without an active symbol nothing is invented101 var none = web; none.raw["activeSymbol"] = .null102 #expect(WorkspaceMapping.windows(of: none).map(\.symbol) == [nil, nil, "AMD", nil])103 }104105 @Test func savingAgainEditsTheStoredWorkspaceAndKeepsUnknownKeys() {106 let first = WorkspaceMapping.workspace(from: layout([.init(section: "charting", symbol: "AAPL", frame: [0, 0, 900, 600], kind: "main"), .init(section: "research", symbol: "AAPL", frame: nil, kind: "main")]))!107 // another client (or a later version) added keys at every level108 var stored = first109 stored.raw["template"] = "duo"; stored.raw["activeSymbol"] = "AAPL"; stored.raw["futureKey"] = .object(["a": 1])110 var panels = stored.panels111 var p1 = panels["w1"]!; p1.raw["pinned"] = true112 var c = p1.config; c["interval"] = "1h"; c["linked"] = false113 var mac = c["mac"]!.objectValue!; mac["space"] = 2; c["mac"] = .object(mac)114 p1.config = c; panels["w1"] = p1; stored.panels = panels115116 let again = WorkspaceMapping.workspace(from: layout([.init(section: "charting", symbol: "MSFT", frame: nil, kind: "main")], name: "Renamed"), existing: stored)!117 #expect(again.name == "Renamed" && again.icon == "macwindow.on.rectangle")118 #expect(again.raw["template"]?.stringValue == "duo" && again.raw["activeSymbol"]?.stringValue == "AAPL" && again.raw["futureKey"] == .object(["a": 1]))119 #expect(again.layout.panelIds == ["w1"] && again.panels.count == 1) // the window that was closed is gone120 let p = again.panels["w1"]!121 #expect(p.raw["pinned"]?.boolValue == true && p.config["interval"]?.stringValue == "1h" && p.config["linked"]?.boolValue == false)122 #expect(p.config["symbol"]?.stringValue == "MSFT" && p.title == "MSFT")123 #expect(p.config["mac"]?.objectValue?["space"]?.doubleValue == 2 && p.config["mac"]?.objectValue?["frame"] == nil)124 #expect(WorkspaceMapping.windows(of: again) == [SavedWorkspace.Window(section: "charting", symbol: "MSFT", frame: nil, kind: "main")])125 }126127 @Test func aLeafWithoutItsPanelIsSkippedAndABadFrameIsDropped() {128 var w = VQWorkspace(name: "x", layout: .split(.row, children: [.panel("a"), .panel("ghost")]),129 panels: ["a": VQuantKit.VQPanel(type: .chart, title: "AAPL", config: ["symbol": .string("AAPL"), "mac": .object(["section": .string("charting"), "kind": .string("main"), "frame": .array([.number(1), .number(2)])])])])130 #expect(WorkspaceMapping.windows(of: w) == [SavedWorkspace.Window(section: "charting", symbol: "AAPL", frame: nil, kind: "main")])131 w.removePanel("a")132 #expect(WorkspaceMapping.windows(of: w).isEmpty)133 }134}135136@Suite struct ShortcutTests {137 @Test func noShortcutCollidesWithAnotherOrWithTheSystem() {138 let c = AppShortcuts.collisions()139 #expect(c.isEmpty, "\(c.map { "\($0.0.id) = \($0.1.id) (\($0.1.display))" })")140 #expect(AppShortcuts.all.count == 24 && Set(AppShortcuts.all.map(\.id)).count == 24)141 }142143 @Test func theCheckSeesACollision() {144 // ⌃⌘S is the standard "Show/Hide Sidebar" of a NavigationSplitView window: 1.0.1 used it for "Save Window Layout"145 let old = AppShortcut(id: "file.saveLayout", title: "Save the window layout", key: "s", modifiers: [.command, .control])146 #expect(AppShortcuts.collisions([old]).map(\.0.id) == ["sys.sidebar"])147 #expect(AppShortcuts.collisions([AppShortcuts.palette, AppShortcut(id: "x", title: "x", key: "K", modifiers: .command)]).count == 1)148 }149150 @Test func displayUsesTheSystemOrderOfModifiers() {151 #expect(AppShortcuts.palette.display == "⌘K" && AppShortcuts.findSymbol.display == "⌥⌘F" && AppShortcuts.lock.display == "⌃⌘L")152 #expect(AppShortcut(id: "x", title: "x", key: "return", modifiers: [.command, .shift, .option, .control]).display == "⌃⌥⇧⌘↩")153 }154}155156@Suite struct NotificationRouteTests {157 @Test func roundTripThroughUserInfo() {158 for r in [NotificationRoute.conversation("s-1"), .conversation(nil), .approval(sessionId: "s-2"), .quantJob("j-3")] {159 #expect(NotificationRoute(userInfo: r.userInfo) == r)160 }161 }162 @Test func unknownOrIncompletePayloadsRouteNowhere() {163 #expect(NotificationRoute(userInfo: [:]) == nil)164 #expect(NotificationRoute(userInfo: ["vq.kind": "approval"]) == nil)165 #expect(NotificationRoute(userInfo: ["vq.kind": "quantJob", "vq.id": ""]) == nil)166 #expect(NotificationRoute(userInfo: ["vq.kind": "wire-transfer", "vq.id": "1"]) == nil)167 }168 @Test func launchArgument() {169 #expect(NotificationRoute(argument: "approval:abc:def") == .approval(sessionId: "abc:def"))170 #expect(NotificationRoute(argument: "conversation") == .conversation(nil))171 #expect(NotificationRoute(argument: "nonsense:1") == nil)172 }173}174175@Suite struct AuditAndUsageTextTests {176 @Test func auditCSVQuotesAndKeepsOrder() {177 let events: [VQAuditEvent] = [178 VQAuditEvent(json: ["id": 23, "at": 1795214781040, "device": "373332f4", "action": "object.delete", "target": "note/a,b", "ip": "127.0.0.1", "detail": ["rev": 2]]),179 VQAuditEvent(json: ["id": 22, "at": 1795214781022, "action": "signin.native", "detail": .null]),180 ]181 let lines = AuditCSV.export(events).components(separatedBy: "\r\n")182 #expect(lines.count == 4 && lines[3].isEmpty)183 #expect(lines[0] == "id,time_utc,action,target,device,ip,detail")184 #expect(lines[1] == "23,2026-11-20T22:46:21Z,object.delete,\"note/a,b\",373332f4,127.0.0.1,\"{\"\"rev\"\":2}\"")185 #expect(lines[2] == "22,2026-11-20T22:46:21Z,signin.native,,,,")186 }187188 @Test func anUnpricedTotalIsNeverGivenAsANumber() {189 let priced = VQUsageCounters(json: ["calls": 9, "inputTokens": 448468, "outputTokens": 7655, "costUsd": 0.246109, "knownCostUsd": 0.246109, "unpricedCalls": 0])190 #expect(UsageText.cost(priced) == "$0.2461" && UsageText.unpricedNote(priced) == nil)191 let partly = VQUsageCounters(json: ["calls": 3, "inputTokens": 10, "outputTokens": 5, "costUsd": .null, "knownCostUsd": 1.5, "unpricedCalls": 2])192 #expect(UsageText.cost(partly) == "not priced")193 #expect(UsageText.unpricedNote(partly) == "2 calls went to a model with no published price; the priced calls add up to $1.500.")194 let none = VQUsageCounters(json: ["inputTokens": 10, "outputTokens": 5, "costUsd": .null])195 #expect(UsageText.unpricedNote(none) == "at least one call went to a model with no published price; nothing is estimated in its place.")196 }197198 @Test func registryWording() {199 #expect(UsageText.context(1_000_000) == "1 M" && UsageText.context(1_048_576) == "1.05 M" && UsageText.context(200_000) == "200 k" && UsageText.context(nil) == "not stated")200 #expect(UsageText.pricing(nil) == "not stated")201 #expect(UsageText.pricing(VQModelInfo.Pricing(json: ["inputPerMTok": 2, "outputPerMTok": 10])) == "$2 in · $10 out")202 #expect(UsageText.pricing(VQModelInfo.Pricing(json: ["inputPerMTok": 0.1, "outputPerMTok": 0.5])) == "$0.10 in · $0.50 out")203 #expect(UsageText.tokens(448468) == "448.5 k" && UsageText.tokens(2_500_000) == "2.50 M")204 let listedOnly = VQModelInfo(json: ["id": "x", "provider": "openai", "available": true, "selectable": false, "capabilities": ["tools": true]])205 #expect(UsageText.notSelectableReason(listedOnly, providerConfigured: true) == "not validated with the agent's tool loop")206 #expect(UsageText.notSelectableReason(listedOnly, providerConfigured: false) == "no key for this provider on the server")207 }208}209