Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/hop/blob/main/Sources/AskRouteChecks.swift # hop Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key. Brought by drakestapleton Sign in to star 1 stars 1 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `hop / Sources / AskRouteChecks.swift` 161 lines 路 11113 bytes Raw Blame History 1 import Foundation 2 3 /// Self-test rows for Ask's own-model-first choice and the "answered by" line (`AskRoute`). The servers here are 4 /// stubs on this Mac's loopback address started inside the test; nothing else is contacted and no setting is read 5 /// or written. `tools/check-ask-route.sh` builds changed copies of the code and requires these rows to fail on them. 6 @MainActor 7 enum AskRouteChecks { 8 static let own = "Own test model", claude = "Claude (your subscription)" 9 10 /// A stub model server. `health` is the status `/health` answers with; `reports` is the model id its 11 /// chat stream names (nil: none). 12 static func stub(health: Int, reports: String?) -> SelfTestServer? { 13 let named = reports.map { ",\"model\":\"\($0)\"" } ?? "" 14 let sse = "data: {\"object\":\"chat.completion.chunk\"\(named),\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ready\"}}]}\n\n" 15 + "data: {\"object\":\"chat.completion.chunk\"\(named),\"choices\":[],\"usage\":{\"total_tokens\":7}}\n\n" 16 + "data: [DONE]\n\n" 17 return SelfTestServer { line in 18 if line.hasPrefix("GET /health ") { return (health, "application/json", "{\"status\":\"ok\"}") } 19 if line.hasPrefix("POST /v1/chat/completions ") { return (200, "text/event-stream", sse) } 20 return (404, "text/plain", "not here") 21 } 22 } 23 24 static func ownModel(_ port: Int, host: String = "127.0.0.1") -> ModelEndpoint { 25 ModelEndpoint(name: own, baseURL: "http://\(host):\(port)/v1", model: "configured-id") 26 } 27 28 static func run(_ report: (String, Bool, String) -> Void) async { 29 // 1. A fresh install: no own model, so nothing is chosen, nothing is asked and nothing is written. 30 let fresh = HopConfig() 31 var asked = 0 32 let freshChoice = await AskRoute.choose(fresh) { _ in asked += 1; return true } 33 let freshJSON = (try? JSONEncoder().encode(fresh)).map { String(decoding: $0, as: UTF8.self) } ?? "" 34 let before = fresh.defaultModel ?? fresh.models.first?.name ?? "" 35 report("Ask on a fresh install is unchanged", 36 !AskRoute.applies(fresh) && freshChoice == AskRoute.Choice(name: before, note: nil) && before == claude 37 && asked == 0 && !freshJSON.isEmpty && !freshJSON.contains("preferOwnModel"), 38 "uses \(freshChoice.name), note \(freshChoice.note ?? "none"), /health asked \(asked) times, settings file gains no key") 39 40 // 2. An own model on this Mac that answers /health is used, with no defaultModel set. 41 guard let well = stub(health: 200, reports: "stub-reported-7b"), let wp = await well.start() else { 42 report("Ask uses your own model when it answers", false, "could not start a stub server on this Mac's loopback address") 43 return 44 } 45 defer { well.stop() } 46 var cfg = HopConfig(); cfg.models.append(ownModel(wp)) 47 let ownChoice = await AskRoute.choose(cfg, answers: AskRoute.answers) 48 report("Ask uses your own model when it answers", 49 ownChoice == AskRoute.Choice(name: own, note: nil) && well.requests.contains { $0.hasPrefix("GET /health ") }, 50 "uses \(ownChoice.name); stub saw \(well.requests.joined(separator: ", "))") 51 52 // 3. It does not answer (an error status, then nothing listening): what Ask used before, and one plain line. 53 var falls: [String] = [] 54 if let sick = stub(health: 503, reports: nil), let sp = await sick.start() { 55 var c = HopConfig(); c.models.append(ownModel(sp)) 56 let a = await AskRoute.choose(c, answers: AskRoute.answers) 57 sick.stop() 58 try? await Task.sleep(nanoseconds: 200_000_000) 59 let b = await AskRoute.choose(c, answers: AskRoute.answers) // the port is closed now 60 for x in [a, b] { 61 let n = x.note ?? "" 62 if x.name == claude, n.contains(own), n.contains("did not answer"), n.contains("uses \(claude)"), !n.contains("\n") { 63 falls.append(n) 64 } 65 } 66 } 67 report("Your own model silent: Ask falls back and says so in one line", falls.count == 2, 68 falls.first ?? "no fallback line (expected for an error status and for a closed port)") 69 70 // 4. An explicit defaultModel always wins, and no /health request is made for the choice. 71 var pinned = cfg; pinned.defaultModel = claude 72 let n4 = well.requests.count 73 let pinnedChoice = await AskRoute.choose(pinned, answers: AskRoute.answers) 74 report("An explicit defaultModel always wins", 75 pinnedChoice == AskRoute.Choice(name: claude, note: nil) && well.requests.count == n4 && !AskRoute.applies(pinned), 76 "uses \(pinnedChoice.name); requests during the choice: \(well.requests.count - n4)") 77 78 // 5. The switch: "preferOwnModel": false in the settings file turns it off; absent means on. 79 let modelsJSON = "[{\"name\":\"\(claude)\",\"baseURL\":\"\",\"model\":\"sonnet\",\"kind\":\"claude-cli\"}," 80 + "{\"name\":\"\(own)\",\"baseURL\":\"http://127.0.0.1:\(wp)/v1\",\"model\":\"configured-id\"}]" 81 let off = try? JSONDecoder().decode(HopConfig.self, from: Data("{\"preferOwnModel\":false,\"models\":\(modelsJSON)}".utf8)) 82 let on = try? JSONDecoder().decode(HopConfig.self, from: Data("{\"models\":\(modelsJSON)}".utf8)) 83 let n5 = well.requests.count 84 var offChoice: AskRoute.Choice?, onChoice: AskRoute.Choice? 85 if let off { offChoice = await AskRoute.choose(off, answers: AskRoute.answers) } 86 if let on { onChoice = await AskRoute.choose(on, answers: AskRoute.answers) } 87 report("\"preferOwnModel\": false switches it off", 88 off?.preferOwnModel == false && offChoice == AskRoute.Choice(name: claude, note: nil) 89 && on?.preferOwnModel == nil && onChoice?.name == own && well.requests.count == n5 + 1, 90 "off: \(offChoice?.name ?? "did not decode"); absent: \(onChoice?.name ?? "did not decode"); requests \(well.requests.count - n5)") 91 92 // 6. Only an address on this Mac or the person's network counts; an online model is never preferred. 93 var mixed = HopConfig() 94 mixed.models += [ModelEndpoint(name: "Online", baseURL: "https://api.example.com/v1", model: "m"), 95 ModelEndpoint(name: "Box", baseURL: "http://box.local:8080/v1", model: "m"), 96 ModelEndpoint(name: "Here", baseURL: "http://localhost:9/v1", model: "m")] 97 var online = HopConfig(); online.models.append(ModelEndpoint(name: "Online", baseURL: "https://api.example.com/v1", model: "m")) 98 var asked6 = 0 99 let onlineChoice = await AskRoute.choose(online) { _ in asked6 += 1; return true } 100 let owned = AskRoute.ownModels(mixed).map(\.name) 101 report("Only a model on this Mac or your network counts as your own", 102 owned == ["Box", "Here"] && !AskRoute.applies(online) && onlineChoice == AskRoute.Choice(name: claude, note: nil) && asked6 == 0, 103 "own: \(owned.joined(separator: ", ")); with only an online model Ask uses \(onlineChoice.name), /health asked \(asked6) times") 104 105 // 7. Under an answer: the model id as the server reported it, and where it ran. 106 let ep = ownModel(wp) 107 var said = "" 108 do { 109 let r = try await ModelClient.streamReply(ep, history: [ChatMessage(role: "user", text: "hi")]) { said += $0 } 110 let meta = AppModel.answerMeta(ep, tokens: r.tokens, seconds: 1, who: AskRoute.who(ep, reported: r.model)) 111 report("Under an answer: the model the server named, and where it ran", 112 said == "ready" && r.model == "stub-reported-7b" && meta.hasPrefix("馃彔 on this Mac") 113 && meta.contains("answered by stub-reported-7b") && !meta.contains("configured") 114 && well.requests.contains { $0.hasPrefix("POST /v1/chat/completions ") }, 115 meta) 116 } catch { 117 report("Under an answer: the model the server named, and where it ran", false, error.localizedDescription) 118 } 119 120 // 8. A server that names no model: the configured name, and the line says it is the configured name. 121 if let quiet = stub(health: 200, reports: nil), let qp = await quiet.start() { 122 let q = ownModel(qp) 123 do { 124 let r = try await ModelClient.streamReply(q, history: [ChatMessage(role: "user", text: "hi")]) { _ in } 125 let meta = AppModel.answerMeta(q, tokens: r.tokens, seconds: 1, who: AskRoute.who(q, reported: r.model)) 126 report("No model id reported: the configured name, said to be that", 127 r.model == nil && meta.contains("answered by \(own) (the configured name; the server reported no model id)"), meta) 128 } catch { 129 report("No model id reported: the configured name, said to be that", false, error.localizedDescription) 130 } 131 quiet.stop() 132 } else { 133 report("No model id reported: the configured name, said to be that", false, "could not start a stub server") 134 } 135 136 // 9. The Claude CLI names its model in its first event; the line says so, and says "online". 137 func j(_ s: String) -> [String: Any] { (try? JSONSerialization.jsonObject(with: Data(s.utf8)) as? [String: Any]) ?? [:] } 138 let cli = HopConfig().models[0] 139 let initID = AskRoute.reportedModel(j("{\"type\":\"system\",\"subtype\":\"init\",\"model\":\"claude-test-model-1\",\"session_id\":\"s\"}")) 140 let startID = AskRoute.reportedModel(j("{\"type\":\"stream_event\",\"event\":{\"type\":\"message_start\",\"message\":{\"model\":\"claude-test-model-2\"}}}")) 141 let resultID = AskRoute.reportedModel(j("{\"type\":\"result\",\"result\":\"ready\",\"modelUsage\":{\"claude-x\":{}}}")) 142 let named = AppModel.claudeMeta(cli, reported: initID, tokens: 12, seconds: 1.5) 143 let unnamed = AppModel.claudeMeta(cli, reported: nil, tokens: 12, seconds: nil) 144 report("Claude CLI answers name the model it reported", 145 initID == "claude-test-model-1" && startID == "claude-test-model-2" && resultID == nil 146 && named == "online 路 12 tokens 路 1.5 s 路 answered by claude-test-model-1" 147 && unnamed == "online 路 12 tokens 路 answered by \(claude) (the configured name; the Claude CLI reported no model id)", 148 "\(named) | \(unnamed)") 149 } 150 151 /// `Hop --selftest-ask`: these rows alone (used by tools/check-ask-route.sh for the changed copies). 152 static func runAlone() async -> Int32 { 153 var failures = 0, passes = 0 154 await run { name, ok, detail in 155 print("\(ok ? "PASS" : "FAIL") \(name): \(detail)") 156 if ok { passes += 1 } else { failures += 1 } 157 } 158 print(failures == 0 ? "ASK-ROUTE PASS \(passes)" : "ASK-ROUTE FAIL \(failures) of \(passes + failures)") 159 return failures == 0 ? 0 : 1 160 } 161 }