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/FactoryWorkspace.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 / FactoryWorkspace.swift` 370 lines · 20067 bytes Raw Blame History 1 import AppKit 2 import Combine 3 import CoreFoundation 4 import Foundation 5 6 private final class FactoryTransport: NSObject, URLSessionTaskDelegate, @unchecked Sendable { 7 static let session: URLSession = { 8 let config = URLSessionConfiguration.ephemeral 9 config.httpCookieStorage = nil 10 config.urlCredentialStorage = nil 11 config.urlCache = nil 12 config.waitsForConnectivity = false 13 return URLSession(configuration: config, delegate: FactoryTransport(), delegateQueue: nil) 14 }() 15 func urlSession(_ session: URLSession, task: URLSessionTask, 16 willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, 17 completionHandler: @escaping @Sendable (URLRequest?) -> Void) { 18 completionHandler(nil) 19 } 20 } 21 // Native OS/JSON adapter. Factory classification, ordering and freshness are in Omega/hopfact.om. 22 // No browser engine, shell polling, model calls or account/configuration writes. 23 struct FactoryBoardJob: Identifiable, Sendable { 24 let id: String 25 let title: String 26 let head: String? 27 let crew: String? 28 } 29 struct FactoryBoardStation: Identifiable, Sendable { 30 let id: String 31 let name: String 32 let about: String 33 let status: String 34 let open: Int? 35 let moving: Int? 36 let done: Int? 37 let jobs: [FactoryBoardJob] 38 } 39 struct FactoryBoardGroup: Identifiable, Sendable { 40 let id: String 41 let label: String 42 let jobs: [FactoryBoardJob] 43 let rowID: Int 44 } 45 struct FactoryBoardAgent: Identifiable, Sendable { 46 let id: String 47 let name: String 48 let station: String 49 let idle: Int? 50 } 51 struct FactoryCoreState: Sendable { 52 let verdict: UInt64 53 let reason: UInt64 54 let order: [Int] 55 let categories: [UInt64] 56 let permitsFreshRead: Bool 57 var label: String { 58 switch verdict { 59 case 2: return "Offline" 60 case 3: return "Unavailable" 61 case 4: return "Source is out of date" 62 case 5: return "Partial factory data" 63 case 6: return "Needs attention" 64 case 7: return "Work in progress" 65 case 8: return "No reported blockers" 66 default: return "Invalid factory data" 67 } 68 } 69 static func evaluate(_ source: [UInt64]) -> FactoryCoreState { 70 var input = source 71 input[3] = UInt64(Date().timeIntervalSince1970 * 1000) 72 var output = [UInt64](repeating: 0, count: 256) 73 var result: UInt64 = 0 74 let status = input.withUnsafeBufferPointer { a in 75 output.withUnsafeMutableBufferPointer { b in 76 omega_hopfact(&result, a.baseAddress, UInt64(a.count), b.baseAddress, UInt64(b.count)) 77 } 78 } 79 guard status == 0, output[0] == `1213157446`, output[1] == 1, output[5] <= 48 else { 80 return FactoryCoreState(verdict: 1, reason: UInt64(status), order: [], categories: [], permitsFreshRead: false) 81 } 82 let count = Int(output[5]) 83 return FactoryCoreState(verdict: result, reason: output[3], 84 order: output[48..<(48 + count)].map(Int.init), 85 categories: Array(output[96..<(96 + count)]), permitsFreshRead: output[45] == 1) 86 } 87 } 88 struct FactoryBoardProjection: Sendable { 89 var input: [UInt64] 90 var core: FactoryCoreState 91 let generated: Date? 92 let stations: [FactoryBoardStation] 93 let groups: [FactoryBoardGroup] 94 let agents: [FactoryBoardAgent] 95 96 static func integer(_ value: Any?) -> Int? { 97 guard let n = value as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(), 98 n.doubleValue.isFinite, n.doubleValue.rounded(.towardZero) == n.doubleValue, 99 n.doubleValue > Double(Int.min), n.doubleValue < Double(Int.max) else { return nil } 100 return n.intValue 101 } 102 static func text(_ value: Any?, fallback: String = "") -> String { 103 guard let s = value as? String else { return fallback } 104 return String(s.prefix(8192)) 105 } 106 static func jobs(_ value: Any?, prefix: String) throws -> [FactoryBoardJob] { 107 guard let value else { return [] } 108 guard let rows = value as? [[String: Any]], rows.count <= 4096 else { throw FactoryWorkspaceError.invalidFrame } 109 return rows.enumerated().map { i, j in 110 FactoryBoardJob(id: "\(prefix):\(i)", title: text(j["title"], fallback: "Untitled item"), 111 head: j["head"] as? String, crew: j["crew"] as? String) 112 } 113 } 114 static func decode(_ frame: [String: Any]) throws -> FactoryBoardProjection { 115 guard let stationRows = frame["stations"] as? [[String: Any]], stationRows.count <= 32, 116 let agentRows = frame["agents"] as? [[String: Any]], agentRows.count <= 4096 else { 117 throw FactoryWorkspaceError.invalidFrame 118 } 119 var input = [UInt64](repeating: 0, count: 256) 120 input[0] = `1213157446`; input[1] = 1; input[5] = 1; input[6] = 1 121 let seconds = integer(frame["generated"]) 122 if let seconds, seconds > 0, UInt64(seconds) <= UInt64.max / 1000 { input[4] = UInt64(seconds) * 1000 } 123 var rowCount = 0 124 func row(kind: UInt64, state: UInt64, count: Int?, valid: Bool) throws -> Int { 125 guard rowCount < 48 else { throw FactoryWorkspaceError.capacity } 126 let id = rowCount, offset = 8 + 5 * rowCount 127 input[offset] = UInt64(id); input[offset + 1] = kind; input[offset + 2] = state 128 input[offset + 3] = UInt64(bitPattern: Int64(count ?? 0)); input[offset + 4] = valid ? 1 : 0 129 rowCount += 1 130 return id 131 } 132 var stationIDs = Set() 133 var stations: [FactoryBoardStation] = [] 134 let states: [String: UInt64] = ["idle": 1, "waiting": 2, "queued": 3, "running": 4, "bottleneck": 5] 135 for s in stationRows { 136 guard let id = s["id"] as? String, !id.isEmpty, stationIDs.insert(id).inserted else { throw FactoryWorkspaceError.invalidFrame } 137 let state = text(s["status"]) 138 let open = integer(s["open"]), moving = integer(s["moving"]), done = integer(s["done24"]) 139 _ = try row(kind: 1, state: states[state] ?? 0, count: open, 140 valid: open != nil && moving != nil && done != nil && (moving ?? -1) >= 0 && (done ?? -1) >= 0) 141 stations.append(FactoryBoardStation(id: id, name: text(s["name"], fallback: id), about: text(s["about"]), status: state, 142 open: open, moving: moving, done: done, jobs: try jobs(s["jobs"], prefix: id))) 143 } 144 var groups: [FactoryBoardGroup] = [] 145 let review: [String: (UInt64, String)] = ["bay": (2, "Waiting for review"), "quota": (3, "Waiting for quota"), "decision": (4, "Review held")] 146 let merge: [String: (UInt64, String)] = ["ready": (5, "Ready for merge desk"), "owner": (6, "Waiting for owner"), "decision": (7, "Merge held"), 147 "elsewhere": (8, "Owned elsewhere"), "superseded": (9, "Superseded"), "triage": (15, "Needs triage")] 148 if let inspection = stationRows.first(where: { text($0["id"]) == "aegis" }) { 149 for (field, labels) in [("reviewGroups", review), ("mergeGroups", merge)] { 150 guard let value = inspection[field], !(value is NSNull) else { continue } 151 guard let groupRows = value as? [String: Any] else { throw FactoryWorkspaceError.invalidFrame } 152 for name in groupRows.keys.sorted() { 153 let id = field + ":" + name 154 let items = try jobs(groupRows[name], prefix: id) 155 let definition = labels[name] ?? (10, "Unrecognized queue: " + name) 156 let index = try row(kind: definition.0, state: 1, count: items.count, valid: true) 157 groups.append(FactoryBoardGroup(id: id, label: definition.1, jobs: items, rowID: index)) 158 } 159 } 160 } 161 var agentIDs = Set() 162 let agents = try agentRows.map { a -> FactoryBoardAgent in 163 guard let id = a["s"] as? String, !id.isEmpty, agentIDs.insert(id).inserted else { throw FactoryWorkspaceError.invalidFrame } 164 return FactoryBoardAgent(id: id, name: text(a["name"], fallback: id), station: text(a["station"]), idle: integer(a["idle"])) 165 } 166 input[2] = UInt64(rowCount) 167 let core = FactoryCoreState.evaluate(input) 168 guard core.verdict != 1 else { throw FactoryWorkspaceError.invalidFrame } 169 let ranks = Dictionary(uniqueKeysWithValues: core.order.enumerated().map { ($0.element, $0.offset) }) 170 groups.sort { (ranks[$0.rowID] ?? Int.max) < (ranks[$1.rowID] ?? Int.max) } 171 return FactoryBoardProjection(input: input, core: core, 172 generated: seconds.flatMap { $0 > 0 ? Date(timeIntervalSince1970: Double($0)) : nil }, 173 stations: stations, groups: groups, agents: agents) 174 } 175 } 176 177 enum FactoryWorkspaceError: LocalizedError { 178 case invalidFrame, capacity, localOnly, response, tooLarge, notCurrent 179 var errorDescription: String? { 180 switch self { 181 case .invalidFrame: return "The factory sent incomplete or invalid data. No state was invented." 182 case .capacity: return "This snapshot exceeds the verified native capacity." 183 case .localOnly: return "Factory access must use the configured loopback SSH tunnel." 184 case .response: return "The factory refused the request or returned an unexpected response." 185 case .tooLarge: return "The response exceeds the native size limit." 186 case .notCurrent: return "Refresh the factory and select a current agent before sending." 187 } 188 } 189 } 190 191 @MainActor 192 final class FactoryWorkspace: ObservableObject { 193 @Published var projection: FactoryBoardProjection? 194 @Published var connected = false 195 @Published var note = "Connect to the factory to load its current state." 196 @Published var screen = "" 197 @Published var screenLoading = false 198 @Published var sending = false 199 @Published var sendNote = "" 200 private var loop: Task? 201 private var transport: URLSessionTask? 202 private var generation = UUID() 203 private var screenGeneration = UUID() 204 private var base = "" 205 206 nonisolated static func url(_ base: String, _ path: String) throws -> URL { 207 guard let c = URLComponents(string: base), c.scheme == "http", ["127.0.0.1", "localhost"].contains(c.host ?? ""), 208 c.user == nil, c.password == nil, c.query == nil, c.fragment == nil, c.path.isEmpty || c.path == "/", 209 let result = URL(string: base.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + path) else { 210 throw FactoryWorkspaceError.localOnly 211 } 212 return result 213 } 214 /// True while the Factory view is open. A dropped stream (network change, factory restart) 215 /// then reconnects by itself with backoff instead of leaving the view dead. 216 private var wanted = false 217 private var retryDelay: UInt64 = 1 218 private var retryTask: Task? 219 220 func connect(_ address: String) { 221 wanted = true 222 retryTask?.cancel(); retryTask = nil 223 guard loop == nil else { return } 224 base = address; note = "Connecting…" 225 let token = UUID(); generation = token 226 loop = Task.detached(priority: .utility) { [weak self] in 227 do { 228 let url = try Self.url(address, "/stream") 229 let (bytes, response) = try await FactoryTransport.session.bytes(for: URLRequest(url: url, timeoutInterval: 40)) 230 defer { bytes.task.cancel() } 231 guard let response = response as? HTTPURLResponse, response.statusCode == 200, 232 response.mimeType == "text/event-stream" else { throw FactoryWorkspaceError.response } 233 await self?.attach(bytes.task, token: token) 234 var line = Data(), event = "", payload = Data(), frame: [String: Any]? 235 line.reserveCapacity(1024) 236 for try await byte in bytes { 237 try Task.checkCancellation() 238 if byte != 10 { 239 guard line.count < 1_048_576 else { throw FactoryWorkspaceError.tooLarge } 240 line.append(byte); continue 241 } 242 if line.last == 13 { line.removeLast() } 243 guard let text = String(data: line, encoding: .utf8) else { throw FactoryWorkspaceError.invalidFrame } 244 line.removeAll(keepingCapacity: true) 245 if text.isEmpty { 246 if !payload.isEmpty && (event == "full" || event == "patch") { 247 guard let object = try JSONSerialization.jsonObject(with: payload) as? [String: Any] else { throw FactoryWorkspaceError.invalidFrame } 248 if event == "full" { frame = object } 249 else if frame != nil { for (key, value) in object { frame?[key] = value } } 250 if let frame { await self?.accept(try FactoryBoardProjection.decode(frame), token: token) } 251 } 252 event = ""; payload.removeAll(keepingCapacity: true) 253 } else if text.hasPrefix("event:") { 254 event = String(text.dropFirst(6)).trimmingCharacters(in: .whitespaces) 255 } else if text.hasPrefix("data:") { 256 var part = text.dropFirst(5); if part.first == " " { part = part.dropFirst() } 257 guard payload.count + part.utf8.count + 1 <= 1_048_576 else { throw FactoryWorkspaceError.tooLarge } 258 if !payload.isEmpty { payload.append(10) }; payload.append(contentsOf: part.utf8) 259 } 260 } 261 if !Task.isCancelled { throw FactoryWorkspaceError.response } 262 } catch { 263 if !Task.isCancelled { await self?.failed(error.localizedDescription, token: token) } 264 } 265 } 266 } 267 private func attach(_ task: URLSessionTask, token: UUID) { 268 guard generation == token else { task.cancel(); return } 269 transport = task 270 } 271 private func accept(_ state: FactoryBoardProjection, token: UUID) { 272 guard generation == token else { return } 273 projection = state; connected = true; note = state.core.label; retryDelay = 1 274 if state.core.permitsFreshRead { FactoryMetrics.firstFreshSnapshot() } 275 } 276 private func failed(_ message: String, token: UUID) { 277 guard generation == token else { return } 278 let keep = wanted 279 stop() 280 guard keep else { note = message; return } 281 wanted = true 282 let delay = retryDelay 283 retryDelay = min(retryDelay * 2, 15) 284 note = "\(message) Reconnecting in \(delay) s…" 285 let address = base 286 retryTask = Task { [weak self] in 287 try? await Task.sleep(nanoseconds: delay * 1_000_000_000) 288 guard !Task.isCancelled, let self, self.wanted, self.loop == nil else { return } 289 self.connect(address) 290 } 291 } 292 /// Explicit stop (view closed or panel hidden): no automatic reconnect. 293 func disconnect() { 294 wanted = false 295 retryTask?.cancel(); retryTask = nil 296 stop() 297 note = projection == nil ? "Not connected" : "Paused. Last received snapshot is retained." 298 } 299 private func stop() { 300 generation = UUID(); loop?.cancel(); loop = nil; transport?.cancel(); transport = nil; connected = false 301 if var state = projection { state.input[5] = 3; state.core = FactoryCoreState.evaluate(state.input); projection = state } 302 } 303 func refresh(_ address: String) { disconnect(); retryDelay = 1; connect(address) } 304 var reconnecting: Bool { wanted && !connected } 305 306 nonisolated static func data(_ request: URLRequest, limit: Int = 1_048_576) async throws -> (Data, HTTPURLResponse) { 307 let (bytes, response) = try await FactoryTransport.session.bytes(for: request) 308 defer { bytes.task.cancel() } 309 guard let response = response as? HTTPURLResponse, response.expectedContentLength <= Int64(limit) else { throw FactoryWorkspaceError.tooLarge } 310 var data = Data(); data.reserveCapacity(4096) 311 for try await byte in bytes { 312 try Task.checkCancellation() 313 guard data.count < limit else { throw FactoryWorkspaceError.tooLarge } 314 data.append(byte) 315 } 316 return (data, response) 317 } 318 func inspect(_ agent: FactoryBoardAgent) { 319 let token = UUID(); screenGeneration = token; screen = ""; screenLoading = true 320 let address = base 321 Task { [weak self] in 322 do { 323 var c = URLComponents(url: try Self.url(address, "/api/screen"), resolvingAgainstBaseURL: false)! 324 c.queryItems = [URLQueryItem(name: "s", value: agent.id)] 325 let (data, response) = try await Self.data(URLRequest(url: c.url!, timeoutInterval: 10)) 326 guard response.statusCode == 200, let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any], obj["ok"] as? Bool == true else { throw FactoryWorkspaceError.response } 327 guard let self, self.screenGeneration == token else { return } 328 guard let lines = obj["lines"] as? [String] else { throw FactoryWorkspaceError.response } 329 self.screen = lines.joined(separator: "\n") 330 } catch { 331 guard let self, self.screenGeneration == token else { return } 332 self.screen = error.localizedDescription 333 } 334 if let self, self.screenGeneration == token { self.screenLoading = false } 335 } 336 } 337 func send(_ message: String, to agent: FactoryBoardAgent, confirmed: Bool) async -> Bool { 338 let text = message.trimmingCharacters(in: .whitespacesAndNewlines) 339 guard confirmed, !sending, !text.isEmpty, connected, let p = projection, 340 p.agents.contains(where: { $0.id == agent.id }), FactoryCoreState.evaluate(p.input).permitsFreshRead else { 341 sendNote = FactoryWorkspaceError.notCurrent.localizedDescription; return false 342 } 343 guard text.utf8.count <= 4096, text.unicodeScalars.allSatisfy({ $0.value >= 32 && $0.value != 127 }) else { 344 sendNote = "Use one line of at most 4096 UTF-8 bytes. The factory refuses control characters." 345 return false 346 } 347 sending = true; defer { sending = false } 348 do { 349 let url = try Self.url(base, "/api/send") 350 var request = URLRequest(url: url, timeoutInterval: 15) 351 request.httpMethod = "POST" 352 request.setValue("application/json", forHTTPHeaderField: "Content-Type") 353 request.setValue(try Self.url(base, "").absoluteString, forHTTPHeaderField: "Origin") 354 // The floor reads the action from "a" (see server.py do_POST /api/send). 355 let body = try JSONSerialization.data(withJSONObject: ["s": agent.id, "a": "line", "t": text]) 356 guard body.count <= 16384 else { throw FactoryWorkspaceError.tooLarge } 357 request.httpBody = body 358 let (data, response) = try await Self.data(request) 359 guard let obj = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw FactoryWorkspaceError.response } 360 guard response.statusCode == 200, obj["ok"] as? Bool == true else { 361 sendNote = FactoryBoardProjection.text(obj["error"], fallback: FactoryWorkspaceError.response.localizedDescription); return false 362 } 363 sendNote = "Delivered to \(agent.name). Delivery is not task completion." 364 return true 365 } catch { 366 sendNote = "Send not confirmed: \(error.localizedDescription) Inspect the agent before retrying. Hop will not resend automatically." 367 return false 368 } 369 } 370 }