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/Factory.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 / Factory.swift` 210 lines ยท 10971 bytes Raw Blame History 1 import Foundation 2 import Network 3 4 /// Optional: talks to a factory dashboard server through a loopback address (usually a forwarded port). 5 /// Read-only calls: /health, /stream, /api/chat, /api/usage, /api/settings. 6 /// The only write Hop makes is /api/ask: the factory's own natural-language entry point. 7 struct FactoryStation: Identifiable, Hashable { 8 let id: String; let name: String; let open: Int; let moving: Int; let backlog: Int; let done24: Int 9 } 10 struct FactoryUsage: Identifiable, Hashable { 11 var id: String { provider } 12 let provider: String; let accounts: Int; let windows: [(String, Double)] 13 static func == (a: Self, b: Self) -> Bool { a.provider == b.provider } 14 func hash(into h: inout Hasher) { h.combine(provider) } 15 } 16 struct FactoryAccount: Identifiable, Hashable { 17 let id: String; let service: String; let label: String; let status: String 18 } 19 struct FactorySnapshot { 20 var reachable = false 21 var stations: [FactoryStation] = [] 22 var agentsWorking = 0, agentsTotal = 0 23 var usage: [FactoryUsage] = [] 24 var accounts: [FactoryAccount] = [] 25 var dispatcher = "", advisor = "" 26 var error: String? 27 } 28 29 enum FactoryClient { 30 static func get(_ base: String, _ path: String, timeout: TimeInterval = 8) async throws -> Any { 31 guard let u = URL(string: base + path) else { throw URLError(.badURL) } 32 let (d, r) = try await Net.session.data(for: URLRequest(url: u, timeoutInterval: timeout)) 33 guard (r as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } 34 return try JSONSerialization.jsonObject(with: d) 35 } 36 37 static func snapshot(_ base: String) async -> FactorySnapshot { 38 var s = FactorySnapshot() 39 guard let u = URL(string: base + "/health"), 40 let res = try? await Net.session.data(for: URLRequest(url: u, timeoutInterval: 5)), 41 String(decoding: res.0, as: UTF8.self).contains("ok") else { 42 s.error = "Can't reach the factory. Check its address in Settings and any SSH tunnel or VPN you use to reach it." 43 return s 44 } 45 s.reachable = true 46 async let floor = fullFloor(base) 47 async let usage = try? get(base, "/api/usage") 48 async let settings = try? get(base, "/api/settings", timeout: 12) 49 if let f = await floor { 50 s.stations = (f["stations"] as? [[String: Any]] ?? []).map { 51 FactoryStation(id: $0["id"] as? String ?? UUID().uuidString, name: $0["name"] as? String ?? "?", 52 open: $0["open"] as? Int ?? 0, moving: $0["moving"] as? Int ?? 0, 53 backlog: $0["backlog"] as? Int ?? 0, done24: $0["done24"] as? Int ?? 0) 54 } 55 let agents = f["agents"] as? [[String: Any]] ?? [] 56 s.agentsTotal = agents.count 57 s.agentsWorking = agents.filter { ($0["idle"] as? Double ?? Double($0["idle"] as? Int ?? 999)) < 90 }.count 58 } 59 if let list = await usage as? [[String: Any]] { 60 s.usage = list.map { p in 61 FactoryUsage(provider: p["provider"] as? String ?? "?", accounts: p["accountCount"] as? Int ?? 0, 62 windows: (p["windows"] as? [[String: Any]] ?? []).map { ($0["label"] as? String ?? "", $0["remainingPercent"] as? Double ?? 0) }) 63 } 64 } 65 if let st = await settings as? [String: Any] { 66 let roles = st["roles"] as? [String: [String: Any]] ?? [:] 67 s.dispatcher = roles["dispatcher"]?["model"] as? String ?? "" 68 s.advisor = roles["advisor"]?["model"] as? String ?? "" 69 for sub in st["subscriptions"] as? [[String: Any]] ?? [] { 70 for a in sub["accounts"] as? [[String: Any]] ?? [] { 71 s.accounts.append(FactoryAccount(id: (sub["id"] as? String ?? "") + "/" + (a["id"] as? String ?? UUID().uuidString), 72 service: sub["label"] as? String ?? "?", label: a["label"] as? String ?? "", 73 status: a["status"] as? String ?? "")) 74 } 75 } 76 for p in st["providers"] as? [[String: Any]] ?? [] where (p["kind"] as? String) != "subscription" { 77 s.accounts.append(FactoryAccount(id: p["id"] as? String ?? UUID().uuidString, service: p["label"] as? String ?? "?", 78 label: "API key", status: (p["has_key"] as? Bool ?? false) ? "saved" : "missing")) 79 } 80 } 81 return s 82 } 83 84 /// First "full" event of the floor's server-sent event stream. 85 private static func fullFloor(_ base: String) async -> [String: Any]? { 86 guard let u = URL(string: base + "/stream") else { return nil } 87 guard let res = try? await Net.session.bytes(for: URLRequest(url: u, timeoutInterval: 10)) else { return nil } 88 let bytes = res.0 89 var sawFull = false 90 do { 91 for try await line in bytes.lines { 92 if line.hasPrefix("event:") { sawFull = line.contains("full") } 93 else if sawFull, line.hasPrefix("data:"), let d = line.dropFirst(5).data(using: .utf8) { 94 return try? JSONSerialization.jsonObject(with: d) as? [String: Any] 95 } 96 } 97 } catch {} 98 return nil 99 } 100 101 /// Sends a plain-English request to the factory dispatcher. Returns the chat item id. 102 static func ask(_ base: String, text: String, answerTo: String?) async throws -> String { 103 guard let u = URL(string: base + "/api/ask") else { throw URLError(.badURL) } 104 var req = URLRequest(url: u, timeoutInterval: 15) 105 req.httpMethod = "POST" 106 req.setValue("application/json", forHTTPHeaderField: "Content-Type") 107 let origin = URLComponents(string: base).map { "\($0.scheme ?? "http")://\($0.host ?? "127.0.0.1")" + ($0.port.map { ":\($0)" } ?? "") } ?? base 108 req.setValue(origin, forHTTPHeaderField: "Origin") 109 var body: [String: Any] = ["t": text] 110 if let a = answerTo { body["answer_to"] = a } 111 req.httpBody = try JSONSerialization.data(withJSONObject: body) 112 let (d, _) = try await Net.session.data(for: req) 113 let j = try JSONSerialization.jsonObject(with: d) as? [String: Any] ?? [:] 114 guard j["ok"] as? Bool == true, let id = j["id"] as? String else { 115 throw NSError(domain: "Hop", code: 1, userInfo: [NSLocalizedDescriptionKey: j["error"] as? String ?? "The factory refused the request."]) 116 } 117 return id 118 } 119 120 /// Current state of one chat item: "thinking", "sending", "ask", "delivered", "error". 121 static func chatItem(_ base: String, id: String) async -> [String: Any]? { 122 guard let j = try? await get(base, "/api/chat") as? [String: Any] else { return nil } 123 return (j["items"] as? [[String: Any]])?.first { $0["id"] as? String == id } 124 } 125 } 126 127 /// Keeps the configured ssh port-forwards alive. If something else already serves a port, Hop leaves it alone. 128 @MainActor 129 final class TunnelManager { 130 private var procs: [Int: Process] = [:] 131 private var timer: Timer? 132 private let tunnels: [Tunnel] 133 134 private let pathMonitor = NWPathMonitor() 135 private var lastPath = "" 136 137 init(_ tunnels: [Tunnel]) { 138 self.tunnels = tunnels.filter(\.valid) 139 check() 140 timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.check() } } 141 // Seamless network changes: when Wi-Fi, Ethernet or a VPN changes, drop the old links and 142 // reconnect at once (ssh picks the right route for the new network) instead of waiting to time out. 143 pathMonitor.pathUpdateHandler = { [weak self] path in 144 let sig = "\(path.status)|" + path.availableInterfaces.map(\.name).joined(separator: ",") 145 DispatchQueue.main.async { self?.networkChanged(sig) } 146 } 147 pathMonitor.start(queue: .global(qos: .utility)) 148 } 149 150 private func networkChanged(_ sig: String) { 151 defer { lastPath = sig } 152 guard !lastPath.isEmpty, sig != lastPath else { return } 153 for p in procs.values where p.isRunning { p.terminate() } 154 procs.removeAll() 155 for host in Set(tunnels.map(\.sshHost)) { // close shared connections that used the old route 156 let p = Process() 157 p.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") 158 p.arguments = ["-O", "exit", host] 159 p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice 160 try? p.run() 161 } 162 DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in self?.check() } 163 } 164 165 private func check() { 166 for t in tunnels { 167 if let p = procs[t.localPort], p.isRunning { continue } 168 Self.portOpen(t.localPort) { [weak self] open in 169 guard !open else { return } 170 DispatchQueue.main.async { self?.start(t) } 171 } 172 } 173 } 174 175 private func start(_ t: Tunnel) { 176 if let p = procs[t.localPort], p.isRunning { return } 177 let p = Process() 178 p.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") 179 // Each link owns its own connection (not the shared one), so it dies cleanly on a network change. 180 p.arguments = ["-N", "-o", "ControlMaster=no", "-o", "ControlPath=none", 181 "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=15", 182 "-o", "ServerAliveCountMax=3", "-o", "ConnectTimeout=8", 183 "-L", "127.0.0.1:\(t.localPort):127.0.0.1:\(t.remotePort)", t.sshHost] 184 p.standardOutput = FileHandle.nullDevice; p.standardError = FileHandle.nullDevice 185 try? p.run() 186 procs[t.localPort] = p 187 } 188 189 func stopAll() { procs.values.forEach { if $0.isRunning { $0.terminate() } } } 190 191 nonisolated static func portOpen(_ port: Int, _ done: @escaping @Sendable (Bool) -> Void) { 192 guard Tunnel.validPort(port), let p = NWEndpoint.Port(rawValue: UInt16(port)) else { done(false); return } // not a port: closed, never a trap 193 let c = NWConnection(host: "127.0.0.1", port: p, using: .tcp) 194 let once = OnceFlag() 195 c.stateUpdateHandler = { st in 196 switch st { 197 case .ready: if once.take() { c.cancel(); done(true) } 198 case .failed, .waiting: if once.take() { c.cancel(); done(false) } 199 default: break 200 } 201 } 202 c.start(queue: .global(qos: .utility)) 203 DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if once.take() { c.cancel(); done(false) } } 204 } 205 } 206 207 final class OnceFlag: @unchecked Sendable { 208 private let l = NSLock(); private var used = false 209 func take() -> Bool { l.lock(); defer { l.unlock() }; if used { return false }; used = true; return true } 210 }