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/SelfTest.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 / SelfTest.swift` 941 lines · 88757 bytes Raw Blame History 1 import Foundation 2 import Network 3 4 /// A tiny web server on this Mac's own address, for the self-test only. By default it answers every request with an 5 /// empty Cortex result, so "reachable" and "not reachable" can both be shown without any real server. A `respond` 6 /// function (given the request's first line) can answer instead with a status, content type and body; so can 7 /// `respondToBody`, which is asked first and is given the request's body too (nil from it: `respond` answers). 8 final class SelfTestServer: @unchecked Sendable { 9 private let listener: NWListener 10 private let lock = NSLock() 11 private var seen: [String] = [], sent: [String] = [] 12 typealias Answer = (status: Int, type: String, body: String) 13 private let respond: (@Sendable (String) -> Answer)? 14 private let respondToBody: (@Sendable (String, String) -> Answer?)? 15 /// The first line of every request received so far, e.g. "POST /api/cortex/write HTTP/1.1". 16 var requests: [String] { lock.lock(); defer { lock.unlock() }; return seen } 17 /// The body of every request received so far, in the same order ("" for one without a body). 18 var bodies: [String] { lock.lock(); defer { lock.unlock() }; return sent } 19 init?(respondToBody: (@Sendable (String, String) -> Answer?)? = nil, respond: (@Sendable (String) -> Answer)? = nil) { 20 self.respond = respond; self.respondToBody = respondToBody 21 let p = NWParameters.tcp 22 p.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any) // loopback only 23 guard let l = try? NWListener(using: p) else { return nil } 24 listener = l 25 } 26 /// Reads one request to its end (the head, then as many bytes of body as the head announces), then answers it. 27 private func serve(_ conn: NWConnection, _ soFar: Data) { 28 conn.receive(minimumIncompleteLength: 1, maximumLength: 1 << 20) { [weak self] data, _, isLast, error in 29 var all = soFar 30 if let data { all.append(data) } 31 let gap = Data("\r\n\r\n".utf8) 32 var whole = isLast || error != nil 33 var head = String(decoding: all, as: UTF8.self), body = "" 34 if let cut = all.range(of: gap) { 35 head = String(decoding: all[all.startIndex..= announced { whole = true } 40 body = String(decoding: rest, as: UTF8.self) 41 } 42 guard whole else { self?.serve(conn, all); return } 43 let first = head.split(separator: "\r\n").first.map(String.init) ?? "" 44 if let self, !first.isEmpty { self.lock.lock(); self.seen.append(first); self.sent.append(body); self.lock.unlock() } 45 let a: Answer = self?.respondToBody?(first, body) ?? self?.respond?(first) ?? (200, "application/json", "{\"results\":[]}") 46 let reason = a.status == 200 ? "OK" : "Error" 47 let reply = "HTTP/1.1 \(a.status) \(reason)\r\nContent-Type: \(a.type)\r\nContent-Length: \(a.body.utf8.count)\r\nConnection: close\r\n\r\n" + a.body 48 conn.send(content: Data(reply.utf8), completion: .contentProcessed { _ in conn.cancel() }) 49 } 50 } 51 func start() async -> Int? { 52 await withCheckedContinuation { (c: CheckedContinuation) in 53 let once = OnceFlag(), l = listener 54 l.newConnectionHandler = { [weak self] conn in 55 conn.start(queue: .global()) 56 self?.serve(conn, Data()) 57 } 58 l.stateUpdateHandler = { st in 59 switch st { 60 case .ready: if once.take() { c.resume(returning: l.port.map { Int($0.rawValue) }) } 61 case .failed, .cancelled: if once.take() { c.resume(returning: nil) } 62 default: break 63 } 64 } 65 l.start(queue: .global()) 66 } 67 } 68 func stop() { listener.cancel() } 69 } 70 71 /// `Hop --selftest`: exercises every part against the real Mac and Keychain. The optional parts (tunnels, factory, 72 /// model servers, other machines, Cortex) are checked only when they are set up in the config file, and say SKIP 73 /// with the reason otherwise. No action is ever sent to a factory (its status is read, nothing more). Prints one line per check. 74 @MainActor 75 enum SelfTest { 76 static func run() async -> Int32 { 77 var failures = 0, skipped = 0 78 func report(_ name: String, _ ok: Bool, _ detail: String) { 79 print("\(ok ? "PASS" : "FAIL") \(name): \(detail)") 80 if !ok { failures += 1 } 81 } 82 func skip(_ name: String, _ why: String) { print("SKIP \(name): \(why)"); skipped += 1 } 83 var warned = 0 84 func warn(_ name: String, _ what: String) { print("WARN \(name): \(what)"); warned += 1 } // worth knowing, not a failure 85 func portOpen(_ p: Int) async -> Bool { 86 await withCheckedContinuation { (c: CheckedContinuation) in TunnelManager.portOpen(p) { c.resume(returning: $0) } } 87 } 88 func installed(_ tool: String) async -> Bool { 89 await withCheckedContinuation { c in 90 CommandRun(["sh", "-c", "command -v \(Shell.quote(tool)) >/dev/null 2>&1"]).start(onLine: { _ in }, onExit: { c.resume(returning: $0 == 0) }) 91 } 92 } 93 let cfg = HopConfig.load() 94 print("config: \(HopConfig.url.path)") 95 report("Screens shown", Tab.shown(cfg).contains(.factory) == cfg.factoryEnabled && Tab.shown(cfg).count == (cfg.factoryEnabled ? 7 : 6) && Tab.shown(cfg).first == .all, 96 Tab.shown(cfg).map(\.rawValue).joined(separator: ", ")) 97 98 do { 99 // A conversation is kept oldest first and drawn newest first. Each rule has a control that must fail it. 100 let said = ["one", "two", "three"].map { ChatMessage(role: "user", text: $0) } 101 func texts(_ l: [ChatMessage]) -> String { l.map(\.text).joined(separator: " ") } 102 func newestOnTop(_ drawn: [ChatMessage], of log: [ChatMessage]) -> Bool { 103 drawn.count == log.count && drawn.first?.id == log.last?.id && zip(drawn, drawn.dropFirst()).allSatisfy { a, b in 104 (log.firstIndex { $0.id == a.id } ?? -1) > (log.firstIndex { $0.id == b.id } ?? log.count) 105 } 106 } 107 let four = said + [ChatMessage(role: "assistant", text: "four")] 108 report("The newest message is drawn on top, and a new one takes the top; the stored order is not that order", 109 newestOnTop(SpiritOrder.newestFirst(said), of: said) && newestOnTop(SpiritOrder.newestFirst(four), of: four) 110 && texts(SpiritOrder.newestFirst(four)) == "four three two one" && !newestOnTop(said, of: said) && texts(four) == "one two three four", 111 "drawn: \(texts(SpiritOrder.newestFirst(four))); stored: \(texts(four)); stored order passes the check: \(newestOnTop(said, of: said))") 112 let fades = (0...200).map { SpiritOrder.fade(depth: $0) } 113 report("Older messages dim as they sink, never below 0.70, and the newest is at full strength", 114 fades[0] == 1 && (fades.min() ?? 0) >= 0.70 && fades.last == SpiritOrder.fadeFloor && zip(fades, fades.dropFirst()).allSatisfy { $0 >= $1 } 115 && SpiritOrder.fade(depth: -3) == 1 && fades[3] < fades[0], 116 "depth 0: \(fades[0]); depth 3: \(fades[3]); lowest of 201: \(fades.min() ?? 0)") 117 // Digging: the reader's place, and what is on show there. 118 var hold = SpiritOrder.Hold() 119 var talk = said 120 hold.moved(to: SpiritOrder.place(offset: 10, newestHeight: 300), log: talk) 121 let atTop = !hold.digging && texts(hold.shown(talk)) == "three two one" 122 hold.moved(to: SpiritOrder.place(offset: 120, newestHeight: 300), log: talk) // further down the newest message 123 talk[2].text = "three and more" // which is still being written 124 let reading = hold.digging && hold.frozen == nil && texts(hold.shown(talk)) == "three and more two one" 125 // What Ask does when the model is busy: a note goes in BEFORE the answer being written. The answer on 126 // show must stay the answer, and the note waits. 127 talk.insert(ChatMessage(role: "note", text: "busy"), at: 2) 128 let noteWaits = texts(hold.shown(talk)) == "three and more two one" && hold.waiting(talk) == 1 && !hold.sentSince(talk) 129 hold.moved(to: SpiritOrder.place(offset: 900, newestHeight: 300), log: talk) // down among older messages 130 talk[3].text = "three and more and more" 131 talk.append(ChatMessage(role: "assistant", text: "four")) 132 let dug = texts(hold.shown(talk)) == "three and more two one" && hold.waiting(talk) == 2 && !hold.sentSince(talk) 133 hold.settle(talk) 134 let kept = hold.digging 135 talk.remove(at: 1) // a held message is taken out 136 let goneIsGone = texts(hold.shown(talk)) == "three and more one" 137 // What Ask does when you send: your message and an empty answer are added in one step. 138 talk.append(contentsOf: [ChatMessage(role: "user", text: "five"), ChatMessage(role: "assistant", text: "")]) 139 let sent = hold.sentSince(talk) && talk.last?.role == "assistant" 140 hold.moved(to: .top, log: talk) 141 let back = !hold.digging && texts(hold.shown(talk)) == " five four three and more and more busy one" && hold.waiting(talk) == 0 && !hold.sentSince(talk) 142 var cleared = SpiritOrder.Hold(); cleared.moved(to: .older, log: said); cleared.settle([]) 143 var replaced = SpiritOrder.Hold(); replaced.moved(to: .older, log: said); replaced.settle(["a", "b", "c", "d"].map { ChatMessage(role: "user", text: $0) }) 144 report("While you dig into older messages nothing is put in above them; a long answer you are reading keeps growing; sending brings the top back", 145 atTop && reading && noteWaits && dug && kept && goneIsGone && sent && back && !cleared.digging && !replaced.digging 146 && SpiritOrder.place(offset: 24, newestHeight: 0) == .top && SpiritOrder.place(offset: 25, newestHeight: 0) == .older 147 && SpiritOrder.place(offset: 25, newestHeight: 300) == .inNewest, 148 "top=\(atTop) reading a growing answer=\(reading) a busy note put in before it waits=\(noteWaits) among older ones=\(dug) held=\(kept) a removed message goes=\(goneIsGone) your message with an empty answer after it counts as sent=\(sent) back on top=\(back) cleared lets go=\(!cleared.digging) new conversation lets go=\(!replaced.digging)") 149 // The sky. The same stars every time, in brand strengths, and cheap enough to draw 20 times a second. 150 let sky = SpiritStars.make(), again = SpiritStars.make(), other = SpiritStars.make(seed: 7) 151 report("The stars are the same on every call, and a different number gives different stars", 152 sky == again && sky.count == SpiritStars.count && sky != other && sky.allSatisfy { (0..<1).contains($0.x) && (0..<1).contains($0.y) && $0.size > 0 }, 153 "\(sky.count) stars; first at \(String(format: "%.4f, %.4f", sky.first?.x ?? -1, sky.first?.y ?? -1))") 154 let strengths = stride(from: 0.0, through: 1.0, by: 0.01).map { SpiritPaint.rippleStrength($0) } 155 report("Ripples run from 22 percent at the point to 4 percent at the rim and are gone at the edge", 156 abs(strengths[0] - 0.22) < 1e-9 && abs(strengths[90] - 0.0418) < 1e-3 && strengths[100] == 0 && (strengths.max() ?? 1) <= 0.22 + 1e-9 157 && strengths.prefix(91).allSatisfy { $0 >= 0.04 }, 158 String(format: "at the point %.3f, nine tenths out %.4f, at the edge %.3f", strengths[0], strengths[90], strengths[100])) 159 if let ms = SpiritPaint.averageFrameMilliseconds() { 160 // An alarm, not a limit: the sky must never cost a whole 60-a-second frame. It is drawn 20 times a second. 161 report("A frame of the sky is drawn in well under 16 ms", ms < 16, String(format: "%.3f ms of processor time a frame, average of 60 frames at 1640 x 1040", ms)) 162 } else { report("A frame of the sky is drawn in well under 16 ms", false, "could not make an off-screen picture to draw into") } 163 } 164 165 // The one box. Names are matched the way people type them, and each rule has a control that must not match. 166 let catalog = AppCatalog.scan(AppCatalog.standardRoots) 167 func top(_ q: String) -> String { AppCatalog.match(q, apps: catalog).first?.app.name ?? "nothing" } 168 let system = ["/System/Applications/TextEdit.app", "/System/Applications/Calculator.app", "/System/Applications/Utilities/Terminal.app", "/System/Library/CoreServices/Finder.app"] 169 let missing = system.filter { p in !catalog.contains { $0.path == p } } 170 report("The app list has this Mac's apps, Utilities and Finder included", missing.isEmpty && !catalog.contains { $0.path.contains("/.") }, 171 "\(catalog.count) apps; missing: \(missing.isEmpty ? "none" : missing.joined(separator: ", "))") 172 let typed = [("textedit", "TextEdit"), ("calc", "Calculator"), ("termi", "Terminal"), ("clacul", "Calculator"), ("fin", "Finder")] 173 let mistyped = typed.filter { top($0.0) != $0.1 }.map { "\($0.0) gave \(top($0.0))" } 174 report("Typing a name, part of it, or a slip of it finds the app; nonsense finds none", mistyped.isEmpty && top("zq7zq7") == "nothing", 175 mistyped.isEmpty ? "textedit, calc, termi, clacul, fin; zq7zq7 gave \(top("zq7zq7"))" : mistyped.joined(separator: "; ")) 176 report("Initials and word starts match; scattered letters do not", 177 Fuzzy.score("vsc", in: "Visual Studio Code") != nil && Fuzzy.score("code", in: "Visual Studio Code") != nil 178 && (Fuzzy.score("saf", in: "Safari") ?? 0) > (Fuzzy.score("saf", in: "Disk Safety") ?? 0) && Fuzzy.score("xyz", in: "Safari") == nil 179 && Fuzzy.score("sri", in: "Screen Sharing Remote Desktop Viewer") == nil, 180 "vsc=\(Fuzzy.score("vsc", in: "Visual Studio Code") ?? -1) prefix=\(Fuzzy.score("saf", in: "Safari") ?? -1) inside=\(Fuzzy.score("saf", in: "Disk Safety") ?? -1)") 181 func first(_ q: String, enter: Bool = false, apps: [String] = []) -> String { 182 let found = apps.map { (app: AppCatalog.App(path: "/Applications/\($0).app", name: $0, alt: ""), score: 150, running: false) } 183 guard let r = Smart.rank(query: q, apps: found, boost: { _ in 0 }, clips: [], files: [], accounts: [], tabs: Tab.allCases, enterSendsToAgent: enter).first else { return "nothing" } 184 switch r.kind { case .app: return "app"; case .agent: return "agent"; case .screen(let t): return "screen " + t.rawValue; default: return "other" } 185 } 186 func agentLines(_ q: String, enter: Bool = false) -> Int { 187 Smart.rank(query: q, apps: [], boost: { _ in 0 }, clips: [], files: [], accounts: [], tabs: Tab.allCases, enterSendsToAgent: enter) 188 .filter { if case .agent = $0.kind { return true }; return false }.count 189 } 190 // Nothing typed: the guesses come from the moment. Made-up apps A and B are both open; B was in front before A. 191 let appA = AppCatalog.App(path: "/Applications/A.app", name: "A", alt: ""), appB = AppCatalog.App(path: "/Applications/B.app", name: "B", alt: "") 192 func offered(front: String = "", id: String = "com.example.x", launches: [Habits.Launch] = [], clip: ClipItem? = nil) -> String { 193 Smart.suggest(context: HopContext(frontID: id, frontName: "X", frontPath: front, previousPath: "", hour: 9), apps: [appA, appB], 194 running: [appA.path: "A", appB.path: "B"], recent: [appB.path, appA.path], launches: launches, boost: { _ in 0 }, 195 latest: clip, clips: clip.map { [$0] } ?? [], clipboardPaused: false, exclude: []) 196 .map { r in switch r.kind { case .app(let x, _): return x.name; case .clip: return "paste"; case .url: return "open"; default: return "other" } } 197 .joined(separator: " ") 198 } 199 let once = [Habits.Launch(app: appA.path, from: "com.example.x", hour: 9, at: Date())] 200 report("Nothing typed: the app you were just in comes first, the one in front is not offered, and a habit starts at the second time", 201 offered() == "B A" && offered(front: appA.path) == "B" && offered(launches: once) == "B A" && offered(launches: once + once) == "A B" 202 && offered(id: "com.example.elsewhere", launches: once + once) == "B A", 203 "plain: \(offered()); A in front: \(offered(front: appA.path)); opened A from here once: \(offered(launches: once)); twice: \(offered(launches: once + once)); twice, but from another app: \(offered(id: "com.example.elsewhere", launches: once + once))") 204 let note = ClipItem(date: Date(), text: "a note"), link = ClipItem(date: Date(), text: "https://example.com/a"), stale = ClipItem(date: Date().addingTimeInterval(-1200), text: "a note") 205 report("Nothing typed: a fresh copy is offered to paste first, a copied web address to open, and an old copy waits behind the apps", 206 offered(clip: note) == "paste B A" && offered(clip: link) == "open paste B A" && offered(id: "com.apple.Safari", clip: link) == "paste open B A" 207 && offered(clip: stale) == "B paste A", 208 "text: \(offered(clip: note)); address: \(offered(clip: link)); address, in a browser: \(offered(id: "com.apple.Safari", clip: link)); 20 minutes old: \(offered(clip: stale))") 209 report("A web address is told from a file name or a sentence", 210 Smart.webAddress("example.com/docs") == "https://example.com/docs" && Smart.webAddress("https://a.example/x?y=1") == "https://a.example/x?y=1" 211 && Smart.webAddress("notes.txt") == nil && Smart.webAddress("hello world.com") == nil && Smart.webAddress("https://") == nil, 212 "example.com/docs → \(Smart.webAddress("example.com/docs") ?? "no"); notes.txt → \(Smart.webAddress("notes.txt") ?? "no")") 213 // Review r6/r7 (one box): "Notes.app" is an app on a Mac, never a website; a bare address waits behind a file or 214 // folder of exactly that name at any path length, and is not offered before the file search for it is done; typed 215 // with its scheme it is a web address first. Scores as the file index gives them (name prefix 60, exact name 40, 216 // .app 25, minus the path length / 20). 217 func firstOf(_ q: String, file: String, score: Int, searched: Bool = true) -> String { 218 guard let r = Smart.rank(query: q, apps: [], boost: { _ in 0 }, clips: [], files: searched ? [FileIndex.Hit(id: file, score: score)] : [], accounts: [], 219 tabs: Tab.allCases, enterSendsToAgent: false, searched: searched).first else { return "nothing" } 220 switch r.kind { case .file: return "file"; case .url: return "open"; case .agent: return "agent"; default: return "other" } 221 } 222 let deep = "/Users/x/Library/Mobile Documents/com~apple~CloudDocs/Clients/2026/Brand refresh/Exports/final/print/logo.ai" 223 let appText = ["Notes.app", "Safari.app", "Xcode.app/Contents"].filter { Smart.webAddress($0) != nil } 224 let byName = [firstOf("Notes.app", file: "/System/Applications/Notes.app", score: 124), firstOf("example.com", file: "/Users/x/example.com", score: 99), 225 firstOf("https://example.com", file: "/Users/x/example.com", score: 99), firstOf("example.com", file: "/Users/x/Documents/old/example notes.txt", score: 63), 226 firstOf("logo.ai", file: deep, score: 100 - deep.utf8.count / 20), firstOf("example.com", file: "/Users/x/Sites/example.com/", score: 94), 227 firstOf("logo.ai", file: deep, score: 94, searched: false), firstOf("https://logo.ai", file: deep, score: 94, searched: false)] 228 report("An app's file name is not a web address; a bare address waits behind a file of that exact name and for the search", 229 appText.isEmpty && Smart.webAddress("https://hopbot.app") == "https://hopbot.app" && byName == ["file", "file", "open", "open", "file", "file", "agent", "open"], 230 "taken as web addresses: \(appText); https://hopbot.app → \(Smart.webAddress("https://hopbot.app") ?? "no"); first rows: \(byName)") 231 report("The one box: an app name puts the app first; a question and a request both put the agent line first, with the switch on or off", 232 first("safari", apps: ["Safari"]) == "app" && first("how do I resize a window?", apps: ["Safari"]) == "agent" 233 && first("zq7 make the dock smaller") == "agent" && first("zq7 make the dock smaller", enter: true) == "agent" 234 && first("what is a dock", enter: true) == "agent" && first("voice") == "screen Voice" && first(" ") == "nothing", 235 "app=\(first("safari", apps: ["Safari"])) question=\(first("how do I resize a window?", apps: ["Safari"])) sentence=\(first("zq7 make the dock smaller")) sentence+switch=\(first("zq7 make the dock smaller", enter: true))") 236 let lines = [agentLines("how do I resize a window?"), agentLines("zq7 make the dock smaller"), agentLines("zq7 make the dock smaller", enter: true), agentLines("safari")] 237 report("Ask and Agent are one: no screen is named Ask, the words ask, chat and agent all offer the Agent screen, and the box lists one agent line for a message, never two", 238 !Tab.allCases.contains { $0.rawValue == "Ask" } && first("ask") == "screen Agent" && first("chat") == "screen Agent" && first("agent") == "screen Agent" 239 && lines.allSatisfy { $0 == 1 }, 240 "screens: \(Tab.allCases.map(\.rawValue).joined(separator: ", ")); ask=\(first("ask")) chat=\(first("chat")) agent=\(first("agent")); agent lines for a question, a request, a request with the switch on, an app name: \(lines)") 241 242 // The Swarm section of the Factory screen: its rules on made-up boards, each with a control (SwarmChecks.swift). 243 SwarmChecks.run(report) 244 245 // Safe defaults for someone who has never set Hop up. Each has a control that must come out the other way. 246 let fresh = HopConfig() 247 let failedSearch = "quarterly budget draft" 248 // The switch is for a search that found nothing, on the screens that search. The agent line of the Everything 249 // screen is a line the person picks, and Enter on it sends whatever the switch says (UITest covers that). 250 report("The enterSendsToAgent switch is off by default, and decides only for a failed search of several words", 251 !fresh.enterSendsToAgent && !AppModel.sentenceGoesToAgent(failedSearch, enabled: fresh.enterSendsToAgent) 252 && AppModel.sentenceGoesToAgent(failedSearch, enabled: true) && !AppModel.sentenceGoesToAgent("budget", enabled: true), 253 "default off: “\(failedSearch)” is not sent; switched on it is; one word never is; this config: \(cfg.enterSendsToAgent ? "on" : "off")") 254 let loose = fresh.agentEngines.filter { !Set($0.command).isDisjoint(with: HopConfig.unattendedFlags) }.map(\.name) 255 let control = !Set(["codex", "exec", "--dangerously-bypass-approvals-and-sandbox", "{prompt}"]).isDisjoint(with: HopConfig.unattendedFlags) 256 report("Built-in agent commands keep the tools' own approval prompts", loose.isEmpty && control, 257 loose.isEmpty ? "\(fresh.agentEngines.count) built-in commands, none with an auto-approve or no-sandbox flag (a command with one is caught: \(control))" : "flags found in: \(loose.joined(separator: ", "))") 258 report("First agent run asks first", !fresh.agentConfirmed, "default: asks once; this config: \(cfg.agentConfirmed ? "already answered yes" : "will ask")") 259 report("Dictation is off until turned on", !DictationSettings().enabled, 260 "default off, so no speech model is fetched or loaded at launch; this config: \(DictationSettings.load().enabled ? "on" : "off")") 261 // Hop says where a request goes, never what it costs. A paid service behind a forwarded port has this Mac's own address. 262 func place(_ u: String) -> ModelEndpoint.Place { ModelEndpoint(name: "x", baseURL: u, model: "m").place } 263 func decoded(_ json: String) -> ModelEndpoint? { try? JSONDecoder().decode(ModelEndpoint.self, from: Data(json.utf8)) } 264 let forward = decoded("{\"name\":\"Paid provider via forward\",\"baseURL\":\"http://127.0.0.1:8080/v1\",\"model\":\"m\"}") 265 let saysPaid = decoded("{\"name\":\"p\",\"baseURL\":\"http://127.0.0.1:8080/v1\",\"model\":\"m\",\"cost\":\"paid\"}") 266 let saysFree = decoded("{\"name\":\"f\",\"baseURL\":\"https://api.example.com/v1\",\"model\":\"m\",\"cost\":\"free\"}") 267 let saysOther = decoded("{\"name\":\"o\",\"baseURL\":\"http://127.0.0.1:8080/v1\",\"model\":\"m\",\"cost\":\"cheap\"}") 268 let badge = forward.map { AppModel.answerMeta($0, tokens: 123, seconds: 1) } ?? "?" 269 var day = Savings.Day(); day.local = 123; day.network = 45; day.used = 67; day.saved = 8 270 let usage = Savings.headline(day) 271 func costWord(_ s: String) -> Bool { s.lowercased().contains("free") || s.lowercased().contains("paid") } 272 let paidBadge = saysPaid.map { AppModel.answerMeta($0, tokens: 123, seconds: 1) } ?? "?" 273 let freeBadge = saysFree.map { AppModel.answerMeta($0, tokens: 123, seconds: 1) } ?? "?" 274 report("Hop says where a request goes, never what it costs unless you wrote it", 275 !costWord(badge) && badge.contains("on this Mac") && !costWord(usage) && usage.contains("123 on this Mac") && usage.contains("45 on your network") && usage.contains("67 online") 276 && paidBadge.contains("on this Mac · paid") && freeBadge.contains("online · free") && saysOther?.cost == nil 277 && place("http://127.0.0.1:8080/v1") == .thisMac && place("http://localhost:8080/v1") == .thisMac && place("http://model-server.local:8080/v1") == .network 278 && place("https://api.example.com/v1") == .online && ModelEndpoint(name: "c", baseURL: "", model: "sonnet", kind: "claude-cli").place == .online, 279 "a forwarded port without `cost`: “\(badge)”; usage line: “\(usage)”; control with cost written: “\(paidBadge)” and “\(freeBadge)”; any other cost word is ignored") 280 let chatMind = Fusion.Seat(id: 1, seat: FusionSeat(name: "m", model: "m", act: false), endpoint: nil, ready: true) 281 let toolMind = Fusion.Seat(id: 2, seat: FusionSeat(name: "t", command: ["t", "{prompt}"], act: true), endpoint: nil, ready: true) 282 let plainAsk = Fusion.system(for: chatMind, Fusion.Ask(text: "q", brief: "BRIEF")), knownAsk = Fusion.system(for: chatMind, Fusion.Ask(text: "q", brief: "BRIEF", notes: "[Note] the answer is 42")) 283 let toolAsk = Fusion.system(for: toolMind, Fusion.Ask(text: "q", brief: "BRIEF", notes: "[Note] the answer is 42")) 284 report("A mind is told what Cortex knows only when there is something, and only an agent tool gets the briefing", 285 !plainAsk.contains("knowledge base") && !plainAsk.contains("BRIEF") && knownAsk.contains("knowledge base") && knownAsk.contains("the answer is 42") && !knownAsk.contains("BRIEF") 286 && toolAsk.hasPrefix("BRIEF") && toolAsk.contains("the answer is 42"), 287 "no notes: the short-answer rule alone; with notes: they ride in front; a tool: briefing first, then the notes") 288 289 // The settings Hop is really running on (the file named above), not only the built-in ones. 290 for n in SettingsFile.notices { warn("Settings file", n) } 291 let looseNow = cfg.unattendedEngines 292 if looseNow.isEmpty { 293 report("Agent commands in this config", true, "none switches a tool's approval prompts or sandbox off" 294 + (cfg.migratedEngines.isEmpty ? "" : "; brought to the new built-in commands on load: \(cfg.migratedEngines.joined(separator: ", "))")) 295 } else { 296 warn("Agent commands in this config", "\(looseNow.joined(separator: ", ")) run with a flag that switches approval prompts or the sandbox off" 297 + (cfg.keepAgentFlags ? " (kept on purpose: keepAgentFlags is true)" : " (commands you wrote yourself; Hop leaves them alone)")) 298 } 299 300 // Regression checks on throwaway files. Each has a control that must come out the other way. 301 let scratch = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("hop-selftest-\(ProcessInfo.processInfo.processIdentifier)-\(Int(Date().timeIntervalSince1970))", isDirectory: true) 302 try? FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) 303 defer { try? FileManager.default.removeItem(at: scratch) } 304 func file(_ name: String, _ text: String) -> URL { let u = scratch.appendingPathComponent(name); try? Data(text.utf8).write(to: u); return u } 305 func badCopies(of u: URL) -> [String] { ((try? FileManager.default.contentsOfDirectory(atPath: scratch.path)) ?? []).filter { $0.hasPrefix(u.lastPathComponent + ".bad-") } } 306 307 // A settings file with a mistake in it is never overwritten. 308 let brokenText = "{\n \"hotkey\": \"opt+space\",\n \"clipboardLimit\": 77\n \"models\": []\n}\n" // one missing comma 309 let brokenURL = file("broken.json", brokenText) 310 let b1 = HopConfig.read(brokenURL), b2 = HopConfig.read(brokenURL) 311 let copies = badCopies(of: brokenURL) 312 let untouched = (try? String(contentsOf: brokenURL, encoding: .utf8)) == brokenText 313 let copySame = copies.count == 1 && (try? String(contentsOf: scratch.appendingPathComponent(copies[0]), encoding: .utf8)) == brokenText 314 let goodURL = file("good.json", "{ \"hotkey\": \"opt+space\", \"clipboardLimit\": 77 }") 315 let g = HopConfig.read(goodURL) 316 report("A broken settings file is kept, copied and reported, never overwritten", 317 b1.problem != nil && b2.problem != nil && untouched && copySame && SettingsFile.isBroken(brokenURL) && b1.config.hotkey == HopConfig().hotkey 318 && g.problem == nil && g.config.hotkey == "opt+space" && g.config.clipboardLimit == 77 && badCopies(of: goodURL).isEmpty && !SettingsFile.isBroken(goodURL), 319 "missing comma: \(b1.problem == nil ? "READ WITHOUT COMPLAINT" : "refused"), file unchanged=\(untouched), one copy \(copies.first ?? "-"), running on built-in settings, saving blocked=\(SettingsFile.isBroken(brokenURL)); control (valid file): read as written, no copy") 320 321 // Built-in agent commands saved by an older Hop lose their auto-approve flags on load; a command the user wrote is left alone. 322 func enginesJSON(_ extra: String) -> String { 323 let old = HopConfig.oldUnattendedBuiltins.sorted { $0.key < $1.key }.map { "{\"name\":\"\($0.key)\",\"command\":[\($0.value.map { "\"\($0)\"" }.joined(separator: ","))]}" } 324 return "{\(extra)\"agentEngines\":[" + (old + ["{\"name\":\"Mine\",\"command\":[\"mytool\",\"--yolo\",\"{prompt}\"]}"]).joined(separator: ",") + "]}" 325 } 326 let up = HopConfig.read(file("upgrade.json", enginesJSON(""))), kept = HopConfig.read(file("kept.json", enginesJSON("\"keepAgentFlags\":true,"))) 327 report("Agent commands saved by an older Hop are brought to the safe ones on load", 328 up.config.unattendedEngines == ["Mine"] && up.config.migratedEngines.count == HopConfig.oldUnattendedBuiltins.count && !up.notes.isEmpty 329 && kept.config.unattendedEngines.count == HopConfig.oldUnattendedBuiltins.count + 1 && kept.config.migratedEngines.isEmpty, 330 "\(up.config.migratedEngines.count) old built-in entries changed, the user's own “Mine --yolo” left alone and reported; control (keepAgentFlags true): all \(kept.config.unattendedEngines.count) kept as written") 331 332 // A port that is not a port is skipped with a message; it never stops Hop. 333 let ports = HopConfig.read(file("ports.json", "{\"tunnels\":[{\"localPort\":70000,\"remotePort\":80,\"sshHost\":\"a\"},{\"localPort\":8080,\"remotePort\":0,\"sshHost\":\"b\"},{\"localPort\":8081,\"remotePort\":8081,\"sshHost\":\"c\"}]}")) 334 let badOpen = await portOpen(70000), negOpen = await portOpen(-5) 335 _ = TunnelManager([Tunnel(localPort: 70000, remotePort: 80, sshHost: "a")]) // used to stop the app; must be harmless 336 report("Ports outside 1..65535 are skipped, not fatal", 337 ports.config.tunnels.map(\.localPort) == [8081] && ports.notes.count == 2 && !badOpen && !negOpen && ports.config.links.count == 1, 338 "2 bad entries skipped with a message, port 70000 and -5 read as closed; control: the valid entry 8081 is kept") 339 340 // Tools are found in the usual install folders even when the shell's PATH does not list them. 341 let toolDir = scratch.appendingPathComponent("bin", isDirectory: true), toolName = "hop-selftest-tool-\(ProcessInfo.processInfo.processIdentifier)" 342 try? FileManager.default.createDirectory(at: toolDir, withIntermediateDirectories: true) 343 let toolURL = toolDir.appendingPathComponent(toolName) 344 try? Data("#!/bin/sh\necho ok\n".utf8).write(to: toolURL) 345 try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: toolURL.path) 346 let usual = CommandRun.extraPath 347 let without = await installed(toolName) 348 CommandRun.extraPath = usual + [toolDir.path] 349 let with = await installed(toolName) 350 let stillMissing = await installed("hop-no-such-tool-xyz") 351 CommandRun.extraPath = usual 352 report("Tools are found in the usual install folders, beyond the shell's PATH", with && !without && !stillMissing, 353 "a tool in a listed folder is found (\(with)); control: the same tool with its folder not listed is not (\(!without)); \(usual.count) folders are searched after the login shell's own PATH") 354 355 // A shortcut that would take a typing key away from every app is never registered. 356 let refused = ["", "space", "shift+a", "a", "qwerty!!", "cmd+nosuchkey", "cmd+", "cmd+a+b", "cmd", "shift+space", "f21"] 357 let accepted = ["cmd+space", "f5", "opt+space", "ctrl+shift+k", "shift+f5", "Cmd + Space", "alt+1"] 358 let wrongRefused = refused.filter { let r = Hotkey.resolve($0); return r.problem == nil || r.use != Hotkey.fallback || r.keys != Hotkey.resolve(Hotkey.fallback).keys || !(r.problem ?? "").contains("“\($0)”") } 359 let wrongAccepted = accepted.filter { let r = Hotkey.resolve($0); return r.problem != nil || r.use != $0 } 360 let bareFile = HopConfig.read(file("hotkey-bare.json", "{\"hotkey\":\"a\"}")), goodFile = HopConfig.read(file("hotkey-good.json", "{\"hotkey\":\"opt+space\"}")) 361 report("A shortcut without Command, Control or Option is refused, never registered", 362 wrongRefused.isEmpty && wrongAccepted.isEmpty && Hotkey.check(Hotkey.fallback).keys != nil 363 && bareFile.config.effectiveHotkey == Hotkey.fallback && bareFile.config.hotkey == "a" && bareFile.notes.contains { $0.contains("“a”") } 364 && goodFile.config.effectiveHotkey == "opt+space" && goodFile.notes.isEmpty, 365 wrongRefused.isEmpty && wrongAccepted.isEmpty 366 ? "refused with a message, \(Hotkey.fallback) used instead: \(refused.map { "“\($0)”" }.joined(separator: " ")); control, accepted as written: \(accepted.joined(separator: ", "))" 367 : "wrongly accepted: \(wrongRefused); wrongly refused: \(wrongAccepted)") 368 369 // An index with nothing in it must be an empty index, not a crash (this build is the optimised one users get). 370 func indexed(_ roots: [String], _ name: String, existing: Data? = nil) async -> (count: Int, hits: Int, built: Bool, bytes: Int) { 371 let f = scratch.appendingPathComponent("index-\(name).bin") 372 if let existing { try? existing.write(to: f) } 373 let ix = FileIndex(roots: roots, skipNames: [], file: f) 374 _ = ix.search("anything at all") // a search before the first build 375 await withCheckedContinuation { (c: CheckedContinuation) in ix.rebuild { c.resume() } } 376 let size = ((try? FileManager.default.attributesOfItem(atPath: f.path))?[.size] as? Int) ?? -1 377 return (ix.count, ix.search("hop-index-probe").count + ix.search("anything at all").count, ix.builtAt != nil, size) 378 } 379 let emptyDir = scratch.appendingPathComponent("empty-root", isDirectory: true), fullDir = scratch.appendingPathComponent("full-root", isDirectory: true) 380 try? FileManager.default.createDirectory(at: emptyDir, withIntermediateDirectories: true) 381 try? FileManager.default.createDirectory(at: fullDir, withIntermediateDirectories: true) 382 try? Data("x".utf8).write(to: fullDir.appendingPathComponent("hop-index-probe.txt")) 383 let noRoots = await indexed([], "none") 384 let emptyRoot = await indexed([emptyDir.path], "emptydir") 385 let goneRoot = await indexed([scratch.appendingPathComponent("no-such-root").path], "missing") 386 let wasEmptyFile = await indexed([], "zero", existing: Data()) // a 0-byte index file left by an earlier run 387 let oneFile = await indexed([fullDir.path], "one") 388 func empty(_ r: (count: Int, hits: Int, built: Bool, bytes: Int)) -> Bool { r.count == 0 && r.hits == 0 && r.built && r.bytes == 0 } 389 report("An index with nothing in it is an empty index, not a crash", 390 empty(noRoots) && empty(emptyRoot) && empty(goneRoot) && empty(wasEmptyFile) && oneFile.count == 1 && oneFile.hits == 1 && oneFile.bytes > 0, 391 "no folders listed, an empty folder, a folder that does not exist, a 0-byte index file: 0 items and 0 hits each; control: a folder with one file gives \(oneFile.count) item and \(oneFile.hits) hit") 392 393 // A legacy custom command with no listed agents must be found and must really run. The expected result does not 394 // come from Hop's lookup: /bin/echo is checked on disk, and its output is a word made up here. 395 let marker = "hop-legacy-\(ProcessInfo.processInfo.processIdentifier)" 396 var legacyOnly = HopConfig(); legacyOnly.agentEngines = []; legacyOnly.agentCommand = ["/bin/echo", marker] 397 let legacyFound = await AppModel.detectEngines(legacyOnly) 398 let legacyPick = legacyFound.first 399 let legacyOut = LineBox() 400 var legacyExit: Int32 = -1 401 if let argv = legacyPick?.command { 402 legacyExit = await withCheckedContinuation { c in CommandRun(argv).start(onLine: { legacyOut.add($0) }, onExit: { c.resume(returning: $0) }) } 403 } 404 var legacyGone = legacyOnly; legacyGone.agentCommand = ["/nonexistent/hop-no-such-agent", marker] 405 let goneFound = await AppModel.detectEngines(legacyGone) 406 let printed = legacyOut.text.trimmingCharacters(in: .whitespacesAndNewlines) 407 report("A legacy agentCommand with no listed agents is found and runs", 408 FileManager.default.isExecutableFile(atPath: "/bin/echo") && legacyFound.map(\.command) == [["/bin/echo", marker]] && legacyExit == 0 && printed == marker && goneFound.isEmpty, 409 "agentEngines empty, agentCommand /bin/echo: found \(legacyFound.count), exit \(legacyExit), printed “\(printed)” (expected “\(marker)”); control: a command that is not on disk is found \(goneFound.count) times") 410 411 // Queued Cortex notes are sent only while learning is on; with it off the queue file stays exactly as it is. 412 if let server = SelfTestServer(), let port = await server.start() { 413 let queue = scratch.appendingPathComponent("cortex-outbox.jsonl") 414 let queuedLine = "{\"title\":\"selftest\",\"content\":\"queued note\",\"source\":\"hop/selftest\",\"savedAt\":\"2026-01-01T00:00:00Z\"}\n" 415 try? Data(queuedLine.utf8).write(to: queue) 416 var cc = CortexConfig() 417 cc.enabled = true; cc.url = "http://127.0.0.1:\(port)"; cc.tokenCommand = "echo selftesttoken"; cc.readSpaces = ["selftest"]; cc.learnSpace = "selftest" 418 func writes() -> Int { server.requests.filter { $0.hasPrefix("POST /api/cortex/write") }.count } 419 cc.learn = false 420 let off = Cortex(cc, outbox: queue) 421 off.flush(); off.learn(title: "t", content: "must not be queued", source: "hop/selftest") 422 let reachable = await off.check(timeout: 3) // the server is there and this Cortex can reach it, so silence is a choice 423 try? await Task.sleep(nanoseconds: 1_500_000_000) 424 let offWrites = writes(), offKept = (try? String(contentsOf: queue, encoding: .utf8)) == queuedLine 425 cc.learn = true 426 let on = Cortex(cc, outbox: queue) 427 on.flush() 428 var waited = 0 429 while FileManager.default.fileExists(atPath: queue.path), waited < 50 { try? await Task.sleep(nanoseconds: 100_000_000); waited += 1 } 430 let onWrites = writes(), onGone = !FileManager.default.fileExists(atPath: queue.path) 431 server.stop() 432 report("Queued Cortex notes are sent only while learning is on", 433 reachable && offWrites == 0 && offKept && onWrites == 1 && onGone, 434 "learn off: \(offWrites) sent, queue file unchanged=\(offKept) (server reachable=\(reachable)); control, learn on: \(onWrites) sent, queue emptied=\(onGone)") 435 } else { report("Queued Cortex notes are sent only while learning is on", false, "could not start the test server on this Mac") } 436 437 // "Cortex works" must mean a real answer came back. 438 if let server = SelfTestServer(), let port = await server.start() { 439 var cc = CortexConfig() 440 cc.enabled = true; cc.url = "http://127.0.0.1:\(port)"; cc.tokenCommand = "echo selftesttoken"; cc.readSpaces = ["selftest"] 441 let up = await Cortex(cc).check(timeout: 3) 442 server.stop() 443 try? await Task.sleep(nanoseconds: 300_000_000) 444 let downCortex = Cortex(cc) 445 let down = await downCortex.check(timeout: 2) 446 report("Cortex check passes only when the server answers", up && !down, 447 "a test server on this Mac answered: \(up); control: the same address after the server stopped: \(down ? "still passed" : "failed with “\(downCortex.state)”")") 448 } else { report("Cortex check passes only when the server answers", false, "could not start the test server on this Mac") } 449 450 if let lic = Bundle.main.url(forResource: "LICENSE", withExtension: nil), let text = try? String(contentsOf: lic, encoding: .utf8) { 451 report("Licence inside the app", text.contains("Apache License") && text.contains("END OF TERMS AND CONDITIONS"), "\(text.utf8.count) bytes in Contents/Resources/LICENSE") 452 } else { report("Licence inside the app", false, "Contents/Resources/LICENSE is missing") } 453 454 // Keychain round trip 455 let acct = "hop-selftest-\(Int(Date().timeIntervalSince1970))" 456 let saved = Vault.save(account: acct, secret: "s3cret", kind: "test", note: "selftest") 457 let back = Vault.secret(acct) 458 let listed = Vault.list().contains { $0.account == acct } 459 Vault.delete(acct) 460 report("Keychain", saved && back == "s3cret" && listed && Vault.secret(acct) == nil, "save, read, list, delete") 461 462 // Clipboard encryption key 463 do { 464 let k1 = try Vault.storageKey(), k2 = try Vault.storageKey() 465 report("Clipboard key", k1 == k2, "stable 256-bit key in Keychain") 466 } catch { report("Clipboard key", false, error.localizedDescription) } 467 468 // File index 469 let idx = FileIndex(roots: cfg.indexRoots, skipNames: cfg.indexSkipNames) 470 let t0 = Date() 471 await withCheckedContinuation { (c: CheckedContinuation) in idx.rebuild { c.resume() } } 472 let secs = Date().timeIntervalSince(t0) 473 let s0 = Date() 474 let hits = idx.search("calculator app") 475 let ms = Int(Date().timeIntervalSince(s0) * 1000) 476 let appHits = idx.search("textedit") 477 let standardRoots = Set(HopConfig().indexRoots).isSubset(of: Set(cfg.indexRoots)) // the built-in folders are all listed 478 if cfg.indexRoots.isEmpty { 479 skip("File index", "indexRoots is empty in the config; Find shows no files from this Mac") 480 skip("App search", "indexRoots is empty in the config") 481 } else if idx.count == 0 { 482 warn("File index", "the folders in indexRoots hold nothing Hop can read (\(cfg.indexRoots.joined(separator: ", "))); Find shows no files from this Mac") 483 skip("App search", "the index is empty") 484 } else if !standardRoots { 485 report("File index", true, "\(idx.count) items in \(Int(secs))s from your own indexRoots; a search took \(ms)ms") 486 skip("App search", "indexRoots does not include the built-in folders, so the built-in apps are not expected in it") 487 } else { 488 report("File index", idx.count > 1000 && !hits.isEmpty, 489 "\(idx.count) items in \(Int(secs))s; search 'calculator app' -> \(hits.count) hits in \(ms)ms; top: \(hits.first?.path ?? "-")") 490 report("App search", appHits.contains { $0.path.hasSuffix("TextEdit.app") }, appHits.first?.path ?? "no hit") 491 } 492 493 // Forwarded ports (optional) 494 let links = cfg.links // the same list the app keeps open, the Cortex one included 495 let tm = TunnelManager(links) 496 if links.isEmpty { skip("Forwarded ports", "no tunnels in the config") } 497 else { try? await Task.sleep(nanoseconds: 6_000_000_000) } 498 for t in links { 499 let open = await portOpen(t.localPort) 500 report("Link to \(t.sshHost) :\(t.localPort)", open, open ? "open" : "closed") 501 } 502 503 // Factory (optional, read-only) 504 if cfg.factoryEnabled { 505 let snap = await FactoryClient.snapshot(cfg.factoryURL) 506 report("Factory status", snap.reachable && !snap.stations.isEmpty, 507 "\(snap.stations.count) stations, \(snap.agentsWorking)/\(snap.agentsTotal) droids working, \(snap.usage.count) providers, \(snap.accounts.count) sign-ins, dispatcher \(snap.dispatcher)") 508 } else { skip("Factory status", "no factoryURL in the config; the Factory screen is not shown") } 509 510 // Swarm section (optional, read-only): the newest swarm folder on this Mac, and the factory's board when a factory host is set. 511 let swarmOwners = SwarmStore.ownerNames(cfg), swarms = SwarmReader.scan(roots: cfg.swarmFolders) 512 if let newest = swarms.sources.first, case .folder(let dir) = newest.kind { 513 let r = SwarmReader.folder(dir, owners: swarmOwners, now: Date(), cache: SwarmTranscriptCache()) 514 report("Swarm on this Mac", r.snapshot != nil, 515 r.snapshot.map { "\(swarms.sources.count + swarms.more) found; newest “\($0.title)”: \($0.posts.count) posts, \($0.members.count) members (\($0.working) working, \($0.waiting) waiting, \($0.stopped) stopped)" } ?? r.problem) 516 } else { skip("Swarm on this Mac", "no swarm folder under \(cfg.swarmFolders.joined(separator: ", "))") } 517 if let fb = SwarmStore.boardSource(cfg) { 518 switch await SwarmReader.fetch(fb.machine, path: cfg.factoryBoard, known: nil) { 519 case .text(let text, let size, let total): 520 let r = SwarmReader.board(text: text, totalLines: total, title: "Factory board", owners: swarmOwners, now: Date()) 521 var again = "it had grown, so the end was sent again" 522 if case .unchanged = await SwarmReader.fetch(fb.machine, path: cfg.factoryBoard, known: size) { again = "nothing was sent" } 523 report("Factory board on \(fb.machine.name)", (r.snapshot?.posts.count ?? 0) > 0 && text.utf8.count <= size, 524 r.snapshot.map { "read \(text.utf8.count / 1024) KB from the end of a \(size / 1024) KB file of \(total) lines: \($0.posts.count) posts, \($0.members.count) members, newest #\($0.head); asked again with the size: \(again)" } ?? r.problem) 525 case .missing: skip("Factory board on \(fb.machine.name)", "no file at \(cfg.factoryBoard) there; set factoryBoard in the config, or \"\" to switch it off") 526 default: report("Factory board on \(fb.machine.name)", false, "\(fb.machine.name) did not answer over ssh") 527 } 528 } else { skip("Factory board", "no factoryHost in the config; the Swarm section reads swarm folders on this Mac only") } 529 530 // Models 531 if !cfg.models.contains(where: { $0.kind == "openai" }) { skip("Model servers", "no OpenAI-compatible model in the config") } 532 for ep in cfg.models where ep.kind == "openai" { 533 var reply = "" 534 let start = Date() 535 do { 536 let tok = try await ModelClient.stream(ep, history: [ChatMessage(role: "user", text: "Reply with just the word: ready")]) { reply += $0 } 537 report("Model \(ep.name)", !reply.isEmpty, "\"\(reply.prefix(60))\" in \(String(format: "%.1f", Date().timeIntervalSince(start)))s, \(tok > 0 ? "\(tok) tokens reported" : "tokens estimated")") 538 } catch is ModelClient.Busy { 539 report("Model \(ep.name)", true, "reachable but busy with other work (Hop waits up to a minute)") 540 } catch { 541 report("Model \(ep.name)", false, error.localizedDescription) 542 } 543 } 544 if let ep = cfg.models.first(where: { $0.kind == "claude-cli" }), !(await installed("claude")) { 545 skip("Model \(ep.name)", "the Claude CLI is not installed on this Mac") 546 } else if let ep = cfg.models.first(where: { $0.kind == "claude-cli" }) { 547 let box = LineBox() 548 let code: Int32 = await withCheckedContinuation { c in 549 CommandRun(["claude", "-p", "Reply with just the word: ready", "--output-format", "stream-json", "--verbose", 550 "--tools", "", "--strict-mcp-config", "--model", ep.model], 551 cwd: HopConfig.dir.path).start(onLine: { box.add($0) }, onExit: { c.resume(returning: $0) }) 552 } 553 let out = box.text 554 let text = out.split(separator: "\n").compactMap { l -> String? in 555 guard let j = try? JSONSerialization.jsonObject(with: Data(l.utf8)) as? [String: Any], 556 j["type"] as? String == "result", j["is_error"] as? Bool != true else { return nil } 557 return j["result"] as? String 558 }.first 559 report("Model \(ep.name)", code == 0 && text != nil, text.map { "\"\($0.prefix(60))\"" } ?? "exit \(code): \(out.prefix(160))") 560 } 561 // Most-used items: opening a file puts it on the empty Find screen and ranks it higher. 562 let probe = FileIndex.Hit(id: "/System/Applications/TextEdit.app", score: 0) 563 let before = Recents.shared.boost(probe) 564 Recents.shared.record(probe) 565 let after = Recents.shared.boost(probe), onTop = Recents.shared.top(9).contains { $0.path == probe.path } 566 if before == 0 { Recents.shared.forget(probe) } 567 report("Most-used items", after > before && onTop, "boost \(before) -> \(after), shown on empty Find screen") 568 569 // Live model state for the picker dots. 570 await ModelStatus.shared.refresh(cfg.models) 571 report("Model status", cfg.models.allSatisfy { ModelStatus.shared.state[$0.name] != nil }, 572 cfg.models.map { "\(ModelStatus.shared.dot($0.name)) \($0.name.prefix(18)) \(ModelStatus.shared.word($0.name))" }.joined(separator: " · ")) 573 574 // Who answers: your own model first, the next mind, Stronger, and who answered (stub servers on loopback and 575 // stand-in tools only). 576 await PickChecks.run(report) 577 578 // Answer cache: same question + same conversation = same key; different wording case/space = same key. 579 let k1 = Savings.key(model: "m", history: [ChatMessage(role: "user", text: "What is 2+2?")]) 580 let k2 = Savings.key(model: "m", history: [ChatMessage(role: "user", text: " what is 2+2? ")]) 581 let k3 = Savings.key(model: "other", history: [ChatMessage(role: "user", text: "What is 2+2?")]) 582 Savings.shared.store(k1, "4") 583 report("Answer cache", k1 == k2 && k1 != k3 && Savings.shared.lookup(k2) == "4" && Savings.shared.lookup(k3) == nil, 584 "repeat question answered from memory; other model not reused") 585 // Dictation: the cleanup rules, with a negative control (clean text must come back untouched). 586 var set = DictationSettings() 587 set.fixes = [.init(heard: "kuda", write: "CUDA")]; set.snippets = [.init(say: "my sign off", insert: "Thanks, Sam")] 588 let cases: [(String, String)] = [ 589 ("Um, okay so I think the the kuda build is gonna pass.", "I think the CUDA build is going to pass."), 590 ("Send it Thursday. Scratch that, send it Friday.", "Send it Friday."), 591 ("First point, new line, second point. My sign off.", "First point\nSecond point. Thanks, Sam"), 592 ("Ship the build to the server today.", "Ship the build to the server today."), 593 ("I like the plan and so does she.", "I like the plan and so does she."), 594 ] 595 let wrong = cases.filter { Cleanup.apply($0.0, set) != $0.1 } 596 report("Dictation cleanup", wrong.isEmpty, wrong.isEmpty ? "\(cases.count) cases, 2 of them must stay untouched" : "got “\(Cleanup.apply(wrong[0].0, set))” for “\(wrong[0].0)”") 597 598 // Dictation learns from the user's corrections: synthetic before/after fields, no app or microphone involved. 599 do { 600 let said = "I published it on Zendoto with my ocid." 601 let field = "Notes: " + said + " " 602 func fix(_ after: String) -> [String] { FixLearner.corrections(dictated: said, before: field, after: after).map { "\($0.heard)>\($0.write)" } } 603 let one = fix("Notes: I published it on Zenodo with my ORCID. Then I kept typing") 604 let rewrite = fix("Notes: Uploaded to the archive last night. ") 605 let reword = fix("Notes: I posted it on Zendoto with my ocid. ") 606 let outside = fix("Memo: I published it on Zendoto with my ocid. ") 607 let gone = FixLearner.corrections(dictated: said, before: "something else", after: "something other") 608 // Most of a short dictation redone, each word spelled alike: still a rewrite, not mishearings. 609 let redone = FixLearner.corrections(dictated: "Send the file to Ben.", before: "Send the file to Ben. ", after: "Sent a fill to Ken. ").map { "\($0.heard)>\($0.write)" } 610 report("Learning: a respelled word inside the dictation is a fix; rewording, rewrites and edits outside it are not", 611 one == ["Zendoto>Zenodo", "ocid>ORCID"] && rewrite.isEmpty && reword.isEmpty && outside.isEmpty && gone.isEmpty && redone.isEmpty, 612 "fixed=\(one) rewrite=\(rewrite) redone word by word=\(redone) reworded=\(reword) outside=\(outside) not-found=\(gone)") 613 var s = DictationSettings() 614 let known: (String) -> Bool = { $0 != "recieve" }, name: (String) -> Bool = { $0 == "Gandi" } 615 let first = s.learn([("recieve", "receive")], isNewName: { _ in false }, isKnownWords: known).count, fixesAfterFirst = s.fixes.count 616 let second = s.learn([("recieve", "receive")], isNewName: { _ in false }, isKnownWords: known).count 617 let named = s.learn([("Gandhi", "Gandi")], isNewName: name, isKnownWords: known) 618 let applied = Cleanup.apply("my domain is at gandhi", s) 619 s.undoLearned(named[0]) 620 let afterUndo = Cleanup.apply("my domain is at gandhi", s), again = s.learn([("Gandhi", "Gandi")], isNewName: name, isKnownWords: known).count 621 report("Learning: a misspelled word needs two sightings, a new name one; undo removes it and it is not learned again", 622 first == 0 && fixesAfterFirst == 0 && second == 1 && named.count == 1 && s.words.isEmpty && applied == "My domain is at Gandi" 623 && afterUndo == "My domain is at gandhi" && again == 0 && s.fixes.map(\.write) == ["receive"], 624 "first=\(first) second=\(second) name=\(named.count) typed “\(applied)”; after undo “\(afterUndo)”, relearned=\(again), fixes=\(s.fixes.map(\.write)), words=\(s.words)") 625 report("Learning: a new name is told from a dictionary word", FixLearner.isNewName("Zenodo") && !FixLearner.isNewName("Paris") && !FixLearner.isNewName("toe"), 626 "Zenodo=\(FixLearner.isNewName("Zenodo")) Paris=\(FixLearner.isNewName("Paris")) toe=\(FixLearner.isNewName("toe"))") 627 // Review R1: grammar, homophones and capitals depend on the sentence. With the real spell checker, seen 628 // three times each, none may become a fix, and later dictations stay as said; names are still learned. 629 var g = DictationSettings() 630 let grammar: [(heard: String, write: String)] = [("a", "an"), ("then", "Then"), ("its", "it's"), ("there", "their"), ("then", "than")] 631 for _ in 0..<3 { g.learn(grammar, isNewName: FixLearner.isNewName, isKnownWords: FixLearner.isKnownWords) } 632 // A new name ("Zenodo") is learned at once; an all-caps one ("ORCID") the spell checker skips, so the second time. 633 let names = g.learn([("Zendoto", "Zenodo"), ("ocid", "ORCID")], isNewName: FixLearner.isNewName, isKnownWords: FixLearner.isKnownWords).count 634 + g.learn([("ocid", "ORCID")], isNewName: FixLearner.isNewName, isKnownWords: FixLearner.isKnownWords).count 635 let later = Cleanup.apply("I saw a cat and then its owner went there", g) 636 report("Learning: grammar, homophone and capital edits never become fixes; names still do", 637 g.fixes.map { "\($0.heard)>\($0.write)" } == ["Zendoto>Zenodo", "ocid>ORCID"] && names == 2 && later == "I saw a cat and then its owner went there", 638 "fixes=\(g.fixes.map { "\($0.heard)>\($0.write)" }) waiting=\(g.learning.count); later dictation “\(later)”") 639 // Review r2 R3: another form of a name (possessive, contraction, plural) is not a mishearing either. 640 // Made-up names, so words this Mac's spell checker has learned ("Gandi", "GrokBot" here) cannot decide it. 641 var f = DictationSettings() 642 let forms: [(heard: String, write: String)] = [("Zenodo", "Zenodo's"), ("Zenodo is", "Zenodo's"), ("Vrexalbot", "Vrexalbots"), ("Zenodo's", "Zenodo"), 643 ("Vrexalbots", "Vrexalbot's"), ("Zenodo", "Zenodo-based"), ("Zenodo", "non-Zenodo"), ("Zenodo", "Zenodo.org"), 644 ("Zendoto", "Zenodo's"), ("ocid", "ORCID's"), ("Hop bot is", "Hopbot's")] 645 for _ in 0..<3 { f.learn(forms, isNewName: FixLearner.isNewName, isKnownWords: FixLearner.isKnownWords) } 646 let kept = f.learn([("Zendoto", "Zenodo"), ("Vrex al bot", "Vrexalbot"), ("vrexalbot", "VrexalBot")], isNewName: FixLearner.isNewName, isKnownWords: FixLearner.isKnownWords).count 647 let typed = Cleanup.apply("zenodo is down and the zenodo API answers", f) 648 report("Learning: possessives, contractions and plurals of a name never become fixes; respellings, spacing and capitals still do", 649 !f.fixes.contains { $0.heard.lowercased().hasPrefix("zenodo") || $0.heard.hasPrefix("Vrexalbot") } && kept == 3 650 && Set(f.fixes.map { "\($0.heard)>\($0.write)" }) == ["Zendoto>Zenodo", "Vrex al bot>Vrexalbot", "vrexalbot>VrexalBot"] && typed == "Zenodo is down and the zenodo API answers", 651 "fixes=\(f.fixes.map { "\($0.heard)>\($0.write)" }) learned now=\(kept) waiting=\(f.learning.count); later dictation “\(typed)”") 652 // Round 3: a different ending is a different word the recogniser split or misheard, and is still learnable. 653 let learnable = [("Forge Joe", "Forgejo"), ("Vrexal", "Vrexalbot"), ("Zen Odo", "Zenodo"), ("oconner", "O'Connor"), ("grock bot", "GrokBot"), ("Hop bot", "Hopbot")] 654 .filter { FixLearner.isOtherForm(heard: $0.0, write: $0.1, isKnownWords: FixLearner.isKnownWords) || FixLearner.changesOrdinaryWords(heard: $0.0, write: $0.1, isKnownWords: FixLearner.isKnownWords) } 655 let dont = FixLearner.isOtherForm(heard: "dont", write: "don't", isKnownWords: { $0 == "don't" }) 656 report("Learning: a new ending that is not an inflection is still a mishearing, and an apostrophe that makes an ordinary word is a fix", 657 learnable.isEmpty && !dont, "wrongly refused: \(learnable.map { "\($0.0)>\($0.1)" }), dont>don't refused=\(dont)") 658 // Round 4 R5: ordinary words next to the misheard one that the edit changed or dropped are never part of a fix. 659 // Round 4 R6: a name written with a plural or joined ending, or with a possessive removed, is never learned at 660 // the first sighting (plural, joined) or at all (possessive). 661 var m = DictationSettings() 662 let ln: (String) -> Bool = FixLearner.isNewName, lk: (String) -> Bool = FixLearner.isKnownWords 663 // Round 5 R7: a homophone swap of the neighbouring word ("then" -> "than", "there" -> "their") rides along neither. 664 for _ in 0..<3 { m.learn([("Zendoto is", "Zenodo"), ("ocid then", "ORCID Then"), ("Zendoto's", "Zenodo"), 665 ("ocid then", "ORCID than"), ("Zendoto there", "Zenodo their")], isNewName: ln, isKnownWords: lk) } 666 let r5 = m.fixes.map { "\($0.heard)>\($0.write)" } 667 var e = DictationSettings() 668 let firstTime = e.learn([("Zendoto", "Zenodos"), ("Vrexalbat", "Vrexalbot.io")], isNewName: ln, isKnownWords: lk).count 669 let secondTime = e.learn([("Zendoto", "Zenodos"), ("Vrexalbat", "Vrexalbot.io")], isNewName: ln, isKnownWords: lk).count 670 report("Learning: changed neighbouring words never ride along; a name with a plural or joined ending waits for a second time", 671 r5.isEmpty && firstTime == 0 && secondTime == 2, 672 "neighbours learned=\(r5); plural/joined name: first time \(firstTime), second time \(secondTime)") 673 // Round 5 R7: a neighbouring word only counts as kept when it is written as itself or merged into a name; 674 // another dictionary word one letter away ("than", "their") is a change. Names still learn their parts. 675 let swaps = [("ocid then", "ORCID than"), ("Zendoto there", "Zenodo their"), ("Zendoto there", "Zenodo thereof"), ("ocid then", "ORCID Than"), ("ocid then", "ORCID then.")] 676 .map { FixLearner.changesOrdinaryWords(heard: $0.0, write: $0.1, isKnownWords: lk) } 677 let kept7 = [("ocid then", "ORCID then"), ("Zendoto is", "Zenodo is"), ("Forge Joe", "Forgejo"), ("grock bot", "GrokBot"), ("Hop bot", "Hopbot"), ("Zen Odo", "Zenodo")] 678 .filter { FixLearner.changesOrdinaryWords(heard: $0.0, write: $0.1, isKnownWords: lk) } 679 var h = DictationSettings() 680 for _ in 0..<2 { h.learn([("ocid then", "ORCID than"), ("Zendoto there", "Zenodo their")], isNewName: ln, isKnownWords: lk) } 681 let swapTyped = Cleanup.apply("My ocid then nothing, put it on Zendoto there", h) 682 var p = DictationSettings() 683 for _ in 0..<2 { p.learn([("ocid then", "ORCID then")], isNewName: ln, isKnownWords: lk) } 684 report("Learning: a homophone swap beside a misheard name never becomes a fix; a kept neighbour or a merged name still does", 685 swaps == [true, true, true, true, false] && kept7.isEmpty && h.fixes.isEmpty && h.learning.isEmpty 686 && swapTyped == "My ocid then nothing, put it on Zendoto there" && p.fixes.map { "\($0.heard)>\($0.write)" } == ["ocid then>ORCID then"], 687 "swaps refused=\(swaps) wrongly refused=\(kept7.map { "\($0.0)>\($0.1)" }) fixes=\(h.fixes.map { "\($0.heard)>\($0.write)" }) waiting=\(h.learning.count); later “\(swapTyped)”; kept neighbour fixes=\(p.fixes.map { "\($0.heard)>\($0.write)" })") 688 // Round 6 R8: an ordinary word written but never heard is a change, even when its letters sit inside the name 689 // ("to" in "Zenoto", "then" in "Hopbothen"). End to end, the pair the field comparison finds is not learned. 690 let r8: [(heard: String, write: String)] = [("Zentoto to", "Zenoto too"), ("Protonmale to", "ProtonMail too"), ("Zenthenix then", "Zenthenix than"), 691 ("Vrexthere there", "Vrexthere their"), ("Hop bot then", "Hopbothen than"), ("Zendoto then", "Zenodo then than")] 692 let r8Kept = r8.filter { !FixLearner.changesOrdinaryWords(heard: $0.heard, write: $0.write, isKnownWords: lk) }.map { "\($0.heard)>\($0.write)" } 693 var q = DictationSettings() 694 for _ in 0..<3 { q.learn(r8, isNewName: ln, isKnownWords: lk) } 695 let said8 = "I put it on Zentoto to." 696 let pairs8 = FixLearner.corrections(dictated: said8, before: "Notes: " + said8 + " ", after: "Notes: I put it on Zenoto too. ") 697 var e8 = DictationSettings() 698 let learned8 = e8.learn(pairs8, isNewName: ln, isKnownWords: lk).count + e8.learn(pairs8, isNewName: ln, isKnownWords: lk).count 699 let later8 = Cleanup.apply("Send it via Zentoto to Bob", e8) 700 report("Learning: an ordinary word written but never heard is never part of a fix, even inside a name's letters", 701 r8Kept.isEmpty && q.fixes.isEmpty && q.learning.isEmpty && !pairs8.isEmpty && learned8 == 0 && later8 == "Send it via Zentoto to Bob", 702 "not refused: \(r8Kept); fixes=\(q.fixes.map { "\($0.heard)>\($0.write)" }) waiting=\(q.learning.count); field edit gave \(pairs8.map { "\($0.heard)>\($0.write)" }), learned \(learned8); later “\(later8)”") 703 // Round 8 R8b, R8c: the same in capitals ("TOO"), and for one heard word written as a name plus an ordinary word. 704 // Splits into ordinary words alone and plain respellings of one word are still fixes. 705 let r8b: [(heard: String, write: String)] = [("Zentoto to", "Zenoto TOO"), ("ocid then", "ORCID THAN"), ("Zentoto", "Zenoto too"), ("Zentoto", "Zenoto TOO")] 706 let r8bKept = r8b.filter { !FixLearner.changesOrdinaryWords(heard: $0.heard, write: $0.write, isKnownWords: lk) }.map { "\($0.heard)>\($0.write)" } 707 let stillFixes = [("alot", "a lot"), ("ocid", "ORCID"), ("Zendoto", "Zenodo"), ("recieve", "receive"), ("dont", "don't")] 708 .filter { FixLearner.changesOrdinaryWords(heard: $0.0, write: $0.1, isKnownWords: lk) }.map { "\($0.0)>\($0.1)" } 709 let pairs8b = FixLearner.corrections(dictated: said8, before: "Notes: " + said8 + " ", after: "Notes: I put it on Zenoto TOO. ") 710 var e8b = DictationSettings() 711 let learned8b = e8b.learn(pairs8b, isNewName: ln, isKnownWords: lk).count + e8b.learn(pairs8b, isNewName: ln, isKnownWords: lk).count 712 report("Learning: an unheard ordinary word in capitals, or added to a single misheard word, is never part of a fix", 713 r8bKept.isEmpty && stillFixes.isEmpty && !pairs8b.isEmpty && learned8b == 0, 714 "not refused: \(r8bKept); wrongly refused: \(stillFixes); field edit gave \(pairs8b.map { "\($0.heard)>\($0.write)" }), learned \(learned8b)") 715 } 716 // Review R2: comparing a field near the 200,000-character cap must not hold up the main actor (Hop's window and 717 // the start of the next dictation). The call returns at once; the work finishes in the background. 718 do { 719 let d = Dictation(); d.testMode = true; d.settings.learnFromFixes = true 720 let filler = String(repeating: "a ", count: 99_500) // 199,000 characters of one-letter words, the slowest case 721 let said = "I published it on Zendoto today." 722 let before = filler + said + " ", after = filler + "I published it on Zenodo today. " 723 let t0 = Date() 724 let task = d.learnFrom(said, before: before, after: after) 725 let onMain = Date().timeIntervalSince(t0) 726 final class Ticks: @unchecked Sendable { var n = 0 } 727 let ticks = Ticks() 728 let ticker = Task { @MainActor in while !Task.isCancelled { ticks.n += 1; try? await Task.sleep(nanoseconds: 10_000_000) } } 729 let t1 = Date() 730 await task.value 731 let total = Date().timeIntervalSince(t1); ticker.cancel() 732 let learnedIt = d.settings.fixes.contains { $0.heard == "Zendoto" && $0.write == "Zenodo" } 733 report("Learning: a field near the size cap is compared off the main thread", 734 before.count >= 199_000 && onMain < 0.05 && total < 0.5 && learnedIt && (total < 0.05 || ticks.n >= Int(total / 0.01) / 2), 735 "\(before.count) chars; main thread busy \(String(format: "%.4f", onMain)) s; background \(String(format: "%.2f", total)) s while the main thread ran \(ticks.n) 10 ms ticks; learned=\(learnedIt)") 736 } 737 738 // Dictation: the on-device recogniser hears a sentence spoken by the Mac's own voice. 739 let clip = NSTemporaryDirectory() + "hop-selftest-\(ProcessInfo.processInfo.processIdentifier).wav" 740 let sayIt = Process(); sayIt.executableURL = URL(fileURLWithPath: "/usr/bin/say") 741 sayIt.arguments = ["-o", clip, "--data-format=LEI16@16000", "The quick brown fox jumps over the lazy dog near the river bank."] 742 try? sayIt.run(); sayIt.waitUntilExit() 743 let ear = SpeechEngine() 744 let h0 = Date() 745 var heardText = "" 746 do { try await ear.start(.file(URL(fileURLWithPath: clip))); heardText = await ear.finish() } catch { heardText = "error: \(error.localizedDescription)" } 747 let want = ["quick", "brown", "fox", "jumps", "lazy", "dog", "river"] 748 let hit = want.filter { heardText.lowercased().contains($0) }.count 749 report("Dictation hears speech on this Mac", hit >= 6, "\(hit) of \(want.count) words in \(String(format: "%.1f", Date().timeIntervalSince(h0))) s (includes loading the model): “\(heardText.prefix(70))”") 750 try? FileManager.default.removeItem(atPath: clip) 751 752 // A fixed signing identity: an ad-hoc one makes macOS forget clipboard and paste permission on every update. 753 var codeRef: SecCode?, staticRef: SecStaticCode?, req: SecRequirement?, reqText: CFString? 754 SecCodeCopySelf([], &codeRef) 755 if let codeRef { SecCodeCopyStaticCode(codeRef, [], &staticRef) } 756 if let staticRef { SecCodeCopyDesignatedRequirement(staticRef, [], &req) } 757 if let req { SecRequirementCopyString(req, [], &reqText) } 758 let dr = (reqText as String?) ?? "" 759 // Two separate questions, both answered from this build's own signature and nothing else on the Mac: 760 // is the signature intact (a broken one always fails), and is it a fixed identity or an ad-hoc one. 761 let intact = staticRef.map { SecStaticCodeCheckValidity($0, SecCSFlags(rawValue: kSecCSCheckAllArchitectures), nil) } ?? errSecCSUnsigned 762 report("Signature intact", intact == errSecSuccess, intact == errSecSuccess ? "the app matches its signature" : "check failed (OSStatus \(intact)): the app was changed after signing, or is unsigned") 763 if dr.contains("certificate leaf") { report("Stable signature", true, dr) } 764 else { skip("Stable signature", "this build is signed ad-hoc (as public releases are); macOS asks for Hop's permissions again after each update. tools/signing-setup.sh makes a fixed local identity for your own builds") } 765 let brief = Remote.agentBriefing(cfg) 766 // The Agent screen's levels, on the Claude CLI's own event lines (shapes as the CLI printed them on 2026-11-12). 767 do { 768 let lines = [ 769 #"{"type":"system","subtype":"init","model":"m"}"#, 770 #"{"type":"assistant","message":{"content":[{"type":"text","text":"Looking."},{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"echo *hi* && ls","description":"Print"}}]}}"#, 771 #"{"type":"user","message":{"content":[{"tool_use_id":"t1","type":"tool_result","content":"hi\nfile_a","is_error":false}]}}"#, 772 #"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"t2","name":"Read","input":{"file_path":"/tmp/x.txt"}}]}}"#, 773 #"{"type":"user","message":{"content":[{"tool_use_id":"t2","type":"tool_result","content":[{"type":"text","text":"\#((1...70).map { "l\($0)" }.joined(separator: "\\n"))"}],"is_error":true}]}}"#, 774 #"{"type":"assistant","message":{"content":[{"type":"text","text":"done"}]}}"#, 775 "plain line from another agent", 776 ] 777 let log = lines.flatMap(AgentEvents.messages) 778 func texts(_ d: AgentDetail) -> [String] { d.shown(log).map(\.text) } 779 let answers = texts(.answers), steps = texts(.steps), commands = texts(.commands), output = texts(.output) 780 let long = output.first { $0.hasPrefix("◂ Read") } ?? "" 781 // One event with two text blocks is one answer, on the screen and for what Hop remembers of the run. 782 let two = #"{"type":"assistant","message":{"content":[{"type":"text","text":"Do not deploy."},{"type":"text","text":"Tests passed."}]}}"# 783 let joined = AgentEvents.messages(two).map(\.text) == ["Do not deploy.\nTests passed."] && AgentEvents.said(two) == "Do not deploy.\nTests passed." 784 && AgentEvents.said(lines[2]) == nil && AgentEvents.said("plain") == "plain" && AgentEvents.said("! bad") == nil 785 // Two tools at once, results in the other order: each output is headed by its own command. 786 let pair = [#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"a","name":"Bash","input":{"command":"pwd"}},{"type":"tool_use","id":"b","name":"Bash","input":{"command":"whoami"}}]}}"#, 787 #"{"type":"user","message":{"content":[{"tool_use_id":"b","type":"tool_result","content":"me"}]}}"#, 788 #"{"type":"user","message":{"content":[{"tool_use_id":"a","type":"tool_result","content":"/tmp"}]}}"#].flatMap(AgentEvents.messages) 789 let crossed = Array(AgentDetail.output.shown(pair).map(\.text).suffix(2)) == ["◂ Bash: whoami\nme", "◂ Bash: pwd\n/tmp"] 790 // A result that is a picture is named, not called empty. 791 let img = AgentEvents.messages(#"{"type":"user","message":{"content":[{"tool_use_id":"z","type":"tool_result","content":[{"type":"image","source":{"type":"base64","data":"AA"}}]}]}}"#) 792 let picture = AgentDetail.output.shown(img).first?.text.contains("(image content, not shown)") == true 793 let ok = answers == ["Looking.", "done", "plain line from another agent"] 794 && steps == ["Looking.", "▸ Bash", "▸ Read", "done", "plain line from another agent"] 795 && commands == ["Looking.", "▸ Bash\necho *hi* && ls", "▸ Read\n/tmp/x.txt", "done", "plain line from another agent"] 796 && output.count == 7 && output[2] == "◂ Bash: echo *hi* && ls\nhi\nfile_a" 797 && long.hasPrefix("◂ Read: /tmp/x.txt\nfailed\nl1\nl2") && long.contains("\nl60\n(10 more lines)") && !long.contains("l61") 798 && joined && crossed && picture 799 && AgentDetail(setting: "COMMANDS") == .commands && AgentDetail(setting: "bash") == .steps 800 && HopConfig().agentDetail == "steps" 801 report("Agent detail levels", ok, ok ? "answers \(answers.count), steps \(steps.count), commands \(commands.count), output \(output.count) messages from one run; a long output keeps \(AgentEvents.outputLines) lines and counts the rest" 802 : "answers \(answers) | steps \(steps) | commands \(commands) | output \(output)") 803 } 804 report("Agent briefing size", brief.count < 400, "\(brief.count) chars ≈ \(Savings.estimate(brief)) tokens per agent call") 805 806 // Who Hop can hand a request to on this Mac: the installed agent tools and the model servers, as it would 807 // pick among them (none is fine; Hop then says so). Nobody is asked anything here. 808 let found = await AppModel.detectEngines(cfg) 809 let minds = await Fusion.seats(cfg, installed: found) 810 let mindList = minds.map { "\($0.seat.name) (tier \($0.seat.tier), \($0.seat.family), \($0.ready ? "ready" : "not ready"), \($0.acts ? "acts" : "answers"))" }.joined(separator: "; ") 811 if minds.isEmpty { skip("Minds Hop can pick from", "no agent tool of \(cfg.agentEngines.map(\.tool).joined(separator: ", ")) is installed and no model server is set; Hop says so when asked") } 812 else if !minds.contains(where: \.ready) { warn("Minds Hop can pick from", "none of them is ready right now, so a message would get no answer: \(mindList)") } 813 else { 814 // The table itself must be one the chooser can take: seats numbered from 1 without a gap, 16 at most, each 815 // a model server or a command. 816 let sound = minds.map(\.id) == Array(1...minds.count) && minds.count <= Fusion.mostSeats 817 && minds.allSatisfy { $0.endpoint != nil || !$0.seat.command.isEmpty } 818 report("Minds Hop can pick from make a table the chooser can take", sound, mindList) 819 } 820 // The chooser core is linked and fails closed, and the host reads records and sums strictly 821 // (Omega/tests/check-fuse-mac.sh checks the core itself, with its mutant). 822 let fast = FuseCore.Row(id: 1, tier: 1, family: 1, cost: 1, state: 1, caps: 1), strong = FuseCore.Row(id: 2, tier: 4, family: 2, cost: 100, state: 1, caps: 3) 823 let unknown = FuseCore.plan([fast, strong], kind: 1, difficulty: 0, stakes: 2, confidence: 900_000, most: 3, escalations: 0, flags: 0) 824 let easy = FuseCore.plan([fast, strong], kind: 1, difficulty: 1, stakes: 2, confidence: 900_000, most: 3, escalations: 0, flags: 0) 825 let downOnly = FuseCore.plan([FuseCore.Row(id: 1, tier: 4, family: 2, cost: 1, state: 3, caps: 3)], kind: 1, difficulty: 3, stakes: 2, confidence: 900_000, most: 3, escalations: 0, flags: 0) 826 report("Hop picks: an unsorted request is never given to the weakest mind; a trivial one is; nothing is chosen when no mind is ready", 827 unknown.verdict == 4 && unknown.chosen == [2] && unknown.flags & 1 == 1 && easy.chosen == [1] && downOnly.verdict == 2 && downOnly.reason == 80 && downOnly.chosen.isEmpty, 828 "unsorted: seat \(unknown.chosen) (flags \(unknown.flags)); trivial: seat \(easy.chosen); only a mind that is down: verdict \(downOnly.verdict) reason \(downOnly.reason)") 829 let rec = FusionRecord.parse("Paris.\n\nnote hop record\nfn confidence to ulong\nret 910000\nend\n") 830 let notRec = FusionRecord.parse("fn confidence to ulong\nret 910000\nend\n"), bad = FusionRecord.parse("x\nnote hop record\nfn confidence to ulong\nret many\nend\n") 831 report("Hop picks: a reply's record is read only after its marker line, and only as written", 832 rec.body == "Paris." && rec.fields == ["confidence": 910_000] && !notRec.present && !bad.present, 833 "with marker: body “\(rec.body)”, fields \(rec.fields.count); without the marker: \(notRec.fields.count) fields; a word in place of a number: \(bad.fields.count) fields") 834 report("Hop picks: plain sums are done here, and only plain sums", 835 Fusion.arithmetic("what is 17 * 23?") == "391" && Fusion.arithmetic("(2+2)/8") == "0.5" && Fusion.arithmetic("1/0") == nil 836 && Fusion.arithmetic("call 911") == nil && Fusion.arithmetic("2 + two") == nil && Fusion.arithmetic("10") == nil 837 && Fusion.arithmetic("what is 2026-11-10") == nil && Fusion.arithmetic("1/3") == nil && Fusion.arithmetic("0.1 + 0.2") == "0.3" && Fusion.arithmetic("10 - 3 - 2") == "5" 838 && Fusion.arithmetic("what is 555-0199") == nil && Fusion.arithmetic("1.`0000000000001` * 1") == nil 839 && Fusion.arithmetic("`9007199254740993` - `9007199254740992`") == nil && Fusion.arithmetic("`1234567890123456` + 1") == nil 840 && Fusion.arithmetic("`99999999` * `99999999` * `99999999` / `99999999` / `99999999`") == nil && Fusion.arithmetic("`123456789012345` + 1") == "`123456789012346`" 841 && Fusion.floor("How do I delete a branch?").kind == 0 && Fusion.floor("delete the old branch").kind == 3 && Fusion.floor("Can you delete the old branch?").kind == 3 842 && Fusion.floor("Is the build green? If so, deploy it.").kind == 3 && Fusion.floor("How annoying.\nDelete the old branch").kind == 3, 843 "17 * 23 = \(Fusion.arithmetic("what is 17 * 23?") ?? "-"); (2+2)/8 = \(Fusion.arithmetic("(2+2)/8") ?? "-"); 1/0, 1/3, a date, a phone number, words and a bare number: left to a mind; a question about deleting is not a request to delete, a question followed by a request is") 844 845 // Cortex (optional): off unless switched on in the config. 846 if cfg.cortex.enabled { 847 let cx = Cortex(cfg.cortex) 848 let answered = await cx.check(timeout: 8) // through the same forwarded port the app uses (opened above) 849 let hits = answered ? await cx.search("hop", limit: 3, timeout: 6) : [] 850 report("Cortex", answered, answered ? "the server at \(cfg.cortex.url) answered; a search returned \(hits.count) entries" : cx.state) 851 } else { skip("Cortex", "not enabled in the config; nothing is read from or sent to a knowledge base") } 852 let voice = DictationSettings.load() 853 report("Dictation takeover is opt-in", DictationSettings().takeOverFromWispr == false && DictationSettings().autoTakeOverFromWispr == false, 854 "defaults: takeOverFromWispr=false, autoTakeOverFromWispr=false; this config: \(voice.takeOverFromWispr), \(voice.autoTakeOverFromWispr)") 855 856 // Factory workspace (the native Factory tab): live stream, Omega verdict, agent screen read. 857 if cfg.factoryEnabled { 858 let board = FactoryWorkspace() 859 board.connect(cfg.factoryURL) 860 var waitedF = 0 861 while board.projection == nil && waitedF < 20 { try? await Task.sleep(nanoseconds: 500_000_000); waitedF += 1 } 862 if let p = board.projection { 863 report("Factory stream", board.connected && p.core.permitsFreshRead, 864 "\(p.stations.count) stations, \(p.groups.count) queues, \(p.agents.count) agents; Omega says “\(p.core.label)”; fresh=\(p.core.permitsFreshRead)") 865 if let a = p.agents.first { 866 board.inspect(a) 867 var w = 0 868 while board.screenLoading && w < 30 { try? await Task.sleep(nanoseconds: 500_000_000); w += 1 } 869 // The screen is the agent's own text and may hold any word; only Hop's own refusal message means it failed. 870 // An agent that has printed nothing gives an empty screen: the read worked, so that is worth knowing, not a failure. 871 if !board.screenLoading && board.screen.isEmpty { 872 warn("Factory agent screen", "\(a.name): the factory answered with an empty screen (the agent has printed nothing); the read itself worked") 873 } else { 874 report("Factory agent screen", !board.screen.isEmpty && board.screen != FactoryWorkspaceError.response.localizedDescription, 875 "\(a.name): \(board.screen.split(separator: "\n").count) lines") 876 } 877 } 878 } else { report("Factory stream", false, board.note) } 879 board.disconnect() 880 881 } else { skip("Factory stream", "no factoryURL in the config") } 882 883 // Reconnect after the link drops: private test link on :4798, cut it, bring it back. 884 // Needs the factory to be reached through one of the configured tunnels. 885 let factoryPort = URL(string: cfg.factoryURL)?.port 886 if cfg.factoryEnabled, let via = cfg.tunnels.first(where: { $0.localPort == factoryPort }) { 887 func link() -> Process { 888 let p = Process() 889 p.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") 890 p.arguments = ["-N", "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "BatchMode=yes", 891 "-o", "ExitOnForwardFailure=yes", "-L", "127.0.0.1:4798:127.0.0.1:\(via.remotePort)", via.sshHost] 892 p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice 893 try? p.run(); return p 894 } 895 var l = link() 896 try? await Task.sleep(nanoseconds: 3_000_000_000) 897 let rb = FactoryWorkspace() 898 rb.connect("http://127.0.0.1:4798") 899 var wr = 0 900 while !rb.connected && wr < 20 { try? await Task.sleep(nanoseconds: 500_000_000); wr += 1 } 901 let firstUp = rb.connected 902 l.terminate(); l.waitUntilExit() 903 var wd = 0 904 while rb.connected && wd < 20 { try? await Task.sleep(nanoseconds: 500_000_000); wd += 1 } 905 let sawDrop = !rb.connected, dropNote = rb.note 906 l = link() 907 var wu = 0 908 while !rb.connected && wu < 60 { try? await Task.sleep(nanoseconds: 500_000_000); wu += 1 } 909 report("Factory reconnects by itself", firstUp && sawDrop && rb.connected, 910 "up=\(firstUp), drop seen=\(sawDrop) (“\(dropNote)”), back after \(Double(wu) / 2) s=\(rb.connected)") 911 rb.disconnect(); l.terminate() 912 } else { skip("Factory reconnects by itself", "no factory reached through a configured tunnel") } 913 914 // One box: every machine's route, file list and search 915 if cfg.machines.isEmpty { skip("Other machines", "no machines in the config; Find does not search other computers") } 916 for m in cfg.machines { 917 let route = Cli.resolvedHost(m.ssh) 918 let r = await Remote.run(m, "hostname", timeout: 10) 919 report("Route to \(m.name)", r.code == 0, "ssh \(m.ssh) -> \(route) -> host \(r.out)") 920 await Remote.refreshIndex(m) 921 var res = await Remote.search(m, "AGENTS.md") 922 var waited = 0 923 while res.error?.contains("building") == true && waited < 1800 { 924 try? await Task.sleep(nanoseconds: 15_000_000_000); waited += 15 925 res = await Remote.search(m, "AGENTS.md") 926 } 927 let t0 = Date() 928 res = await Remote.search(m, "agents md") 929 let ms = Int(Date().timeIntervalSince(t0) * 1000) 930 let lines = await Remote.run(m, "cat \(Remote.shardDir)/s* | wc -l") 931 report("\(m.name) file search", !res.hits.isEmpty && ms < 1500, 932 "\(lines.out.trimmingCharacters(in: .whitespaces)) items listed; 'agents md' -> \(res.hits.count) hits in \(ms)ms; top: \(res.hits.first?.path ?? res.error ?? "-")") 933 } 934 report("Agent briefing", cfg.machines.allSatisfy { brief.contains("ssh \($0.ssh)") } && brief.contains("hop find") == !cfg.machines.isEmpty 935 && brief.contains("Factory:") == cfg.factoryEnabled, "names \(cfg.machines.map(\.name)), for \(cfg.owner)") 936 tm.stopAll() 937 let extra = "\(skipped) skipped" + (warned > 0 ? ", \(warned) to look at" : "") 938 print(failures == 0 ? "ALL PASS (\(extra))" : "\(failures) FAILED (\(extra))") 939 return failures == 0 ? 0 : 1 940 } 941 }