hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Sources / SwarmStore.swift
| 1 | import Combine |
| 2 | import Foundation |
| 3 | |
| 4 | // Adapter for the Swarm section: finds swarms, reads their files (or one board file on another computer over |
| 5 | // ssh), decodes JSON and hands plain numbers and bytes to SwarmCore. Every decision is made there; this file |
| 6 | // only fetches, decodes and words the result. It never writes to a swarm and never posts to a board. |
| 7 | |
| 8 | /// Where a swarm's data comes from. |
| 9 | struct SwarmSource: Identifiable, Hashable, Sendable { |
| 10 | enum Kind: Hashable, Sendable { |
| 11 | case folder(String) // a folder holding board.jsonl and members.json |
| 12 | case board(host: String, path: String) // one text file on another computer, read over ssh |
| 13 | } |
| 14 | let id: String |
| 15 | let kind: Kind |
| 16 | var title: String |
| 17 | var place: String // "this Mac", or the other computer's name |
| 18 | var modified: Date? |
| 19 | } |
| 20 | |
| 21 | struct SwarmMember: Identifiable, Sendable { |
| 22 | let id: Int // its index in the snapshot |
| 23 | let name: String |
| 24 | let role: String // as the roster writes it; "" on a board with no roster |
| 25 | let model: String |
| 26 | let detail: String // the bracket after its name on a plain board: tool, computer, ledger number |
| 27 | let alsoCalled: String |
| 28 | let wake: Int |
| 29 | let state: Int |
| 30 | let attention: Int |
| 31 | let group: Int |
| 32 | let helper: Bool |
| 33 | let idleSeconds: Int // -1 not known |
| 34 | let unread: Int // -1 not known |
| 35 | let lastRead: Int |
| 36 | let posts: Int |
| 37 | let lastSeq: Int // 0: no post in view |
| 38 | let lastPostTime: Date? |
| 39 | let activity: String // what it is doing now, or the start of its newest post |
| 40 | let activityIsLive: Bool |
| 41 | let waitingOn: String // "" none |
| 42 | let waitingSeq: Int |
| 43 | let asksYouSeq: Int |
| 44 | let failureText: String |
| 45 | let steps: Int |
| 46 | } |
| 47 | |
| 48 | struct SwarmPost: Identifiable, Sendable { |
| 49 | let id: Int // the sequence number |
| 50 | let senderIndex: Int // -1: not a listed member |
| 51 | let sender: String |
| 52 | let with: [String] // others who signed the same post |
| 53 | let to: [Int] // members it addresses by name |
| 54 | let all: Bool |
| 55 | let time: Date? |
| 56 | let text: [UInt8] |
| 57 | let spans: [Int] // [start, length, kind, value] per marked part, byte offsets into text |
| 58 | let startsGroup: Bool |
| 59 | } |
| 60 | |
| 61 | struct SwarmSnapshot: Sendable { |
| 62 | var title = "" |
| 63 | var hasRoster = false |
| 64 | var members: [SwarmMember] = [] |
| 65 | var posts: [SwarmPost] = [] |
| 66 | var overviewOrder: [Int] = [] |
| 67 | var memberOrder: [Int] = [] |
| 68 | var working = 0, waiting = 0, stopped = 0 |
| 69 | var head = 0 |
| 70 | var lastPostTime: Date? |
| 71 | var notices: [String] = [] |
| 72 | // What the graph is drawn from (member indexes per post), kept as the core gave them. |
| 73 | var helper: [Int] = [] |
| 74 | var postSender: [Int] = [] |
| 75 | var postWith: [[Int]] = [] |
| 76 | var postDirect: [[Int]] = [] |
| 77 | var postAll: [Int] = [] |
| 78 | } |
| 79 | |
| 80 | /// What one member's transcript says, remembered until the file changes. |
| 81 | final class SwarmTranscriptCache: @unchecked Sendable { |
| 82 | struct Summary: Sendable { |
| 83 | var turn = SwarmCore.turnUnknown |
| 84 | var activity = "" |
| 85 | var lastKind = SwarmCore.stepOther |
| 86 | var lastStatus = SwarmCore.statusOther |
| 87 | var lastError = "" |
| 88 | var steps = 0 |
| 89 | var moved = 0 // seconds since 1970 when the file last changed |
| 90 | } |
| 91 | private let lock = NSLock() |
| 92 | private var entries: [String: (key: String, summary: Summary)] = [:] |
| 93 | func get(_ path: String, key: String) -> Summary? { |
| 94 | lock.lock(); defer { lock.unlock() } |
| 95 | guard let e = entries[path], e.key == key else { return nil } |
| 96 | return e.summary |
| 97 | } |
| 98 | func put(_ path: String, key: String, _ s: Summary) { |
| 99 | lock.lock(); defer { lock.unlock() } |
| 100 | if entries.count > 512 { entries.removeAll() } |
| 101 | entries[path] = (key, s) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | enum SwarmReader { |
| 106 | static let boardFileLimit = 4_194_304 // bytes read from the end of board.jsonl |
| 107 | static let rosterFileLimit = 1_048_576 |
| 108 | static let transcriptTail = 262_144 // bytes read from the end of one member's transcript |
| 109 | static let folderLimit = 20 // newest swarm folders listed |
| 110 | static let boardTailLines = SwarmCore.maxPosts |
| 111 | |
| 112 | static func bytes(_ s: String) -> [UInt8] { Array(s.utf8) } |
| 113 | static func string(_ b: [UInt8]) -> String { String(decoding: b, as: UTF8.self) } |
| 114 | static func integer(_ v: Any?) -> Int? { |
| 115 | guard let n = v as? NSNumber, n.doubleValue.isFinite, abs(n.doubleValue) < 9e15 else { return nil } |
| 116 | return n.intValue |
| 117 | } |
| 118 | |
| 119 | /// One line, no code marks, at most `limit` characters. |
| 120 | static func oneLine(_ s: String, _ limit: Int) -> String { |
| 121 | let flat = s.replacingOccurrences(of: "`", with: "").replacingOccurrences(of: "**", with: "") |
| 122 | .split(whereSeparator: { $0 == " " || $0 == "\n" || $0 == "\t" || $0 == "\r" }).joined(separator: " ") |
| 123 | return flat.count > limit ? String(flat.prefix(limit - 1)).trimmingCharacters(in: .whitespaces) + "…" : flat |
| 124 | } |
| 125 | |
| 126 | /// The end of a file: at most `limit` bytes, starting at a line start when the beginning was left out. |
| 127 | static func tail(_ path: String, limit: Int) -> (data: Data, cut: Bool)? { |
| 128 | guard let h = FileHandle(forReadingAtPath: path) else { return nil } |
| 129 | defer { try? h.close() } |
| 130 | let size = (try? h.seekToEnd()) ?? 0 |
| 131 | let start = size > UInt64(limit) ? size - UInt64(limit) : 0 |
| 132 | guard (try? h.seek(toOffset: start)) != nil, var d = try? h.readToEnd() ?? Data() else { return nil } |
| 133 | if start > 0 { |
| 134 | if let nl = d.firstIndex(of: 10) { d = d.subdata(in: d.index(after: nl)..<d.endIndex) } else { d = Data() } |
| 135 | } |
| 136 | return (d, start > 0) |
| 137 | } |
| 138 | |
| 139 | static func stamp(_ path: String) -> (key: String, modified: Date)? { |
| 140 | guard let a = try? FileManager.default.attributesOfItem(atPath: path), let m = a[.modificationDate] as? Date else { return nil } |
| 141 | return ("\(m.timeIntervalSince1970):\(a[.size] as? Int ?? 0)", m) |
| 142 | } |
| 143 | |
| 144 | // MARK: Finding swarms |
| 145 | |
| 146 | /// Swarm folders under each root, newest first: <root>/<conversation>/.system_generated/swarm/members.json. |
| 147 | static func scan(roots: [String]) -> (sources: [SwarmSource], more: Int) { |
| 148 | let fm = FileManager.default |
| 149 | var found: [SwarmSource] = [] |
| 150 | for root in roots { |
| 151 | let base = (root as NSString).expandingTildeInPath |
| 152 | guard let names = try? fm.contentsOfDirectory(atPath: base) else { continue } |
| 153 | for name in names.prefix(20_000) { |
| 154 | let dir = base + "/" + name + "/.system_generated/swarm" |
| 155 | guard let roster = stamp(dir + "/members.json") else { continue } |
| 156 | let when = max(roster.modified, stamp(dir + "/board.jsonl")?.modified ?? .distantPast) |
| 157 | found.append(SwarmSource(id: "folder:" + dir, kind: .folder(dir), title: String(name.prefix(8)), place: "this Mac", modified: when)) |
| 158 | } |
| 159 | } |
| 160 | found.sort { ($0.modified ?? .distantPast) > ($1.modified ?? .distantPast) } |
| 161 | let more = max(0, found.count - folderLimit) |
| 162 | var shown = Array(found.prefix(folderLimit)) |
| 163 | for i in shown.indices { // the roster's own title, when it has one |
| 164 | guard case .folder(let dir) = shown[i].kind, let d = try? Data(contentsOf: URL(fileURLWithPath: dir + "/members.json")), |
| 165 | d.count <= rosterFileLimit, let j = try? JSONSerialization.jsonObject(with: d) as? [String: Any], |
| 166 | let t = j["title"] as? String, !t.trimmingCharacters(in: .whitespaces).isEmpty else { continue } |
| 167 | shown[i].title = oneLine(t, 60) |
| 168 | } |
| 169 | return (shown, more) |
| 170 | } |
| 171 | |
| 172 | /// What tells whether a swarm folder changed since it was last read. |
| 173 | static func folderSignature(_ dir: String) -> String { |
| 174 | (stamp(dir + "/members.json")?.key ?? "-") + "|" + (stamp(dir + "/board.jsonl")?.key ?? "-") |
| 175 | } |
| 176 | |
| 177 | // MARK: A swarm folder |
| 178 | |
| 179 | /// A short label for one tool call in a member's transcript. |
| 180 | static func toolLabel(_ call: [String: Any]) -> String { |
| 181 | let name = call["name"] as? String ?? "" |
| 182 | switch name { |
| 183 | case "": return "" |
| 184 | case "swarm_wait": return "Waiting for a post" |
| 185 | case "read_board": return "Reading posts" |
| 186 | case "post_message": return "Writing a post" |
| 187 | default: break |
| 188 | } |
| 189 | let args = call["args"] as? [String: Any] ?? [:] |
| 190 | func plain(_ key: String) -> String { |
| 191 | guard var s = args[key] as? String else { return "" } |
| 192 | s = s.trimmingCharacters(in: .whitespacesAndNewlines) |
| 193 | if s.count >= 2, s.hasPrefix("\""), s.hasSuffix("\"") { |
| 194 | if let d = s.data(using: .utf8), let v = try? JSONSerialization.jsonObject(with: d, options: .fragmentsAllowed) as? String { return v } |
| 195 | return String(s.dropFirst().dropLast()) |
| 196 | } |
| 197 | return s |
| 198 | } |
| 199 | for key in ["toolSummary", "toolAction"] { let s = plain(key); if !s.isEmpty { return oneLine(s, 96) } } |
| 200 | for key in ["Path", "AbsolutePath", "TargetFile"] { |
| 201 | let s = plain(key) |
| 202 | if !s.isEmpty { return oneLine(name.replacingOccurrences(of: "_", with: " ") + " " + (s as NSString).lastPathComponent, 96) } |
| 203 | } |
| 204 | return name.replacingOccurrences(of: "_", with: " ") |
| 205 | } |
| 206 | |
| 207 | /// The last line of a thinking note that is written as a bold heading. |
| 208 | static func thinkingHeading(_ thinking: String) -> String { |
| 209 | for line in thinking.split(separator: "\n").reversed().prefix(200) { |
| 210 | let t = line.trimmingCharacters(in: .whitespaces) |
| 211 | if t.count >= 7, t.count <= 100, t.hasPrefix("**"), t.hasSuffix("**"), !t.dropFirst(2).dropLast(2).contains("*") { return oneLine(t, 96) } |
| 212 | } |
| 213 | return "" |
| 214 | } |
| 215 | |
| 216 | /// Reads the end of one member's transcript and lets the core say whether its run has stopped and which |
| 217 | /// step tells what it is doing. |
| 218 | static func transcript(_ path: String, cache: SwarmTranscriptCache) -> SwarmTranscriptCache.Summary? { |
| 219 | guard let st = stamp(path) else { return nil } |
| 220 | if let hit = cache.get(path, key: st.key) { return hit } |
| 221 | guard let t = tail(path, limit: transcriptTail) else { return nil } |
| 222 | let lines = t.data.split(separator: 10).suffix(SwarmCore.maxSteps) |
| 223 | var kinds: [Int] = [], statuses: [Int] = [], tools: [Int] = [], waits: [Int] = [], labelled: [Int] = [] |
| 224 | var labels: [String] = [] |
| 225 | var s = SwarmTranscriptCache.Summary() |
| 226 | s.moved = Int(st.modified.timeIntervalSince1970) |
| 227 | for line in lines { |
| 228 | guard let step = try? JSONSerialization.jsonObject(with: line) as? [String: Any] else { |
| 229 | kinds.append(SwarmCore.stepTorn); statuses.append(SwarmCore.statusOther); tools.append(0); waits.append(-1); labelled.append(0); labels.append("") |
| 230 | continue |
| 231 | } |
| 232 | let type = step["type"] as? String ?? "" |
| 233 | let kind = type == "PLANNER_RESPONSE" ? SwarmCore.stepPlanner : type == "GENERIC" ? SwarmCore.stepResult |
| 234 | : type == "USER_INPUT" ? SwarmCore.stepUser : type == "ERROR_MESSAGE" ? SwarmCore.stepError : SwarmCore.stepOther |
| 235 | let status = step["status"] as? String ?? "" |
| 236 | let calls = step["tool_calls"] as? [[String: Any]] ?? [] |
| 237 | var label = "" |
| 238 | if kind == SwarmCore.stepPlanner { |
| 239 | label = calls.reversed().lazy.map(toolLabel).first { !$0.isEmpty } ?? "" |
| 240 | if label.isEmpty, let th = step["thinking"] as? String { label = thinkingHeading(th) } |
| 241 | } |
| 242 | kinds.append(kind) |
| 243 | statuses.append(status == "DONE" ? SwarmCore.statusDone : status == "ERROR" ? SwarmCore.statusError : status == "RUNNING" ? SwarmCore.statusRunning : SwarmCore.statusOther) |
| 244 | tools.append(calls.count) |
| 245 | waits.append(calls.firstIndex { $0["name"] as? String == "swarm_wait" } ?? -1) |
| 246 | labelled.append(label.isEmpty ? 0 : 1) |
| 247 | labels.append(label) |
| 248 | if let i = integer(step["step_index"]) { s.steps = max(s.steps, i + 1) } |
| 249 | s.lastError = step["error"] as? String ?? "" |
| 250 | } |
| 251 | s.steps = max(s.steps, lines.count) |
| 252 | s.turn = SwarmCore.turn(kinds: kinds, statuses: statuses, tools: tools, waits: waits) |
| 253 | let at = SwarmCore.activityStep(kinds: kinds, waits: waits, labelled: labelled) |
| 254 | s.activity = at >= 0 ? labels[at] : "" |
| 255 | s.lastKind = kinds.last ?? SwarmCore.stepOther |
| 256 | s.lastStatus = statuses.last ?? SwarmCore.statusOther |
| 257 | cache.put(path, key: st.key, s) |
| 258 | return s |
| 259 | } |
| 260 | |
| 261 | /// Reads a swarm folder (board.jsonl and members.json, plus each member's transcript beside it). |
| 262 | /// nil with a reason when the folder is not a swarm Hop can read. |
| 263 | static func folder(_ dir: String, owners: [String], now: Date, cache: SwarmTranscriptCache) -> (snapshot: SwarmSnapshot?, problem: String) { |
| 264 | guard let rosterData = try? Data(contentsOf: URL(fileURLWithPath: dir + "/members.json")), rosterData.count <= rosterFileLimit, |
| 265 | let roster = try? JSONSerialization.jsonObject(with: rosterData) as? [String: Any] else { |
| 266 | return (nil, "I can't read this swarm's member list (members.json).") |
| 267 | } |
| 268 | var notices: [String] = [] |
| 269 | let rows = (roster["members"] as? [String: Any] ?? [:]).compactMap { k, v in (v as? [String: Any]).map { (name: k, row: $0) } } |
| 270 | var listed = rows.map { (name: $0.name, row: $0.row, role: SwarmCore.roleCode(role: bytes($0.row["role"] as? String ?? ""), name: bytes($0.name))) } |
| 271 | listed.sort { a, b in |
| 272 | if (a.role == SwarmCore.roleCoordinator) != (b.role == SwarmCore.roleCoordinator) { return a.role == SwarmCore.roleCoordinator } |
| 273 | return SwarmCore.compareFold(bytes(a.name), bytes(b.name)) < 0 |
| 274 | } |
| 275 | if listed.count > SwarmCore.maxMembers { |
| 276 | notices.append("This swarm lists \(listed.count) members. I show the first \(SwarmCore.maxMembers); posts from the others still appear on the Board.") |
| 277 | listed = Array(listed.prefix(SwarmCore.maxMembers)) |
| 278 | } |
| 279 | |
| 280 | var input = SwarmCore.Input() |
| 281 | input.hasRoster = true |
| 282 | input.now = Int(now.timeIntervalSince1970) |
| 283 | var failureTexts: [String] = [], activities: [String] = [], steps: [Int] = [], models: [String] = [], roles: [String] = [] |
| 284 | // <brain>/<conversation>/.system_generated/swarm: each member's transcript is under <brain>/<its conversation>. |
| 285 | let brain = URL(fileURLWithPath: dir).standardizedFileURL.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().path |
| 286 | let nameOK = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_") |
| 287 | for m in listed { |
| 288 | let killed = m.row["killed"] as? Bool ?? false |
| 289 | let wake = m.row["wake_mode"] as? String ?? "" |
| 290 | var summary: SwarmTranscriptCache.Summary? |
| 291 | let conv = m.row["conversation_id"] as? String ?? "" |
| 292 | if !killed, !conv.isEmpty, conv.count <= 64, conv.unicodeScalars.allSatisfy(nameOK.contains) { |
| 293 | summary = transcript(brain + "/" + conv + "/.system_generated/logs/transcript.jsonl", cache: cache) |
| 294 | } |
| 295 | let idle = summary.map { max(0, input.now - $0.moved) } ?? -1 |
| 296 | let failed = summary.map { SwarmCore.failure(lastKind: $0.lastKind, lastStatus: $0.lastStatus, idleSeconds: idle, |
| 297 | quota: SwarmCore.looksLikeQuota(bytes($0.lastError))) } ?? SwarmCore.attentionNone |
| 298 | input.names.append(bytes(m.name)) |
| 299 | input.roles.append(m.role) |
| 300 | input.killed.append(killed ? 1 : 0) |
| 301 | input.wake.append(wake == "working" ? SwarmCore.wakeWorking : wake == "mentions" ? SwarmCore.wakeMentions |
| 302 | : wake == "anything" ? SwarmCore.wakeAnything : SwarmCore.wakeUnknown) |
| 303 | input.turn.append(summary?.turn ?? SwarmCore.turnUnknown) |
| 304 | input.lastRead.append(integer(m.row["last_read_seq"]) ?? -1) |
| 305 | input.lastMove.append(summary?.moved ?? 0) |
| 306 | input.failure.append(failed) |
| 307 | input.channels.append(((m.row["channels"] as? [Any]) ?? []).compactMap { $0 as? String }.prefix(SwarmCore.maxRecipients).map(bytes)) |
| 308 | input.owner.append(owners.contains { SwarmCore.equalFold(bytes($0), bytes(m.name)) } ? 1 : 0) |
| 309 | failureTexts.append(failed == SwarmCore.attentionNone ? "" : oneLine(summary?.lastError ?? "", 200)) |
| 310 | activities.append(summary?.activity ?? "") |
| 311 | steps.append(summary?.steps ?? 0) |
| 312 | models.append(m.row["model"] as? String ?? "") |
| 313 | roles.append(m.row["role"] as? String ?? "") |
| 314 | } |
| 315 | |
| 316 | // Posts: one JSON object per line. A line that does not parse is left out and counted (the newest line can be half written). |
| 317 | var senderNames: [[UInt8]] = [] |
| 318 | var unreadable = 0, system = 0, clipped = 0 |
| 319 | if let t = tail(dir + "/board.jsonl", limit: boardFileLimit) { |
| 320 | if t.cut { notices.append("This board is larger than \(boardFileLimit / 1_048_576) MB. I read its newest part only.") } |
| 321 | var all: [(seq: Int, agent: String, text: String, time: String)] = [] |
| 322 | var last = 0 |
| 323 | for line in t.data.split(separator: 10) { |
| 324 | guard let j = try? JSONSerialization.jsonObject(with: line) as? [String: Any], let seq = integer(j["seq"]), seq > last else { unreadable += 1; continue } |
| 325 | last = seq |
| 326 | if j["control"] is [String: Any] { system += 1; continue } // a channel change, not a post |
| 327 | all.append((seq, j["agent"] as? String ?? "", j["text"] as? String ?? "", j["time"] as? String ?? "")) |
| 328 | } |
| 329 | if all.count > SwarmCore.maxPosts { |
| 330 | notices.append("I show the newest \(SwarmCore.maxPosts) posts. \(all.count - SwarmCore.maxPosts) older ones are not shown.") |
| 331 | all = Array(all.suffix(SwarmCore.maxPosts)) |
| 332 | } |
| 333 | input.citeHead = last |
| 334 | for p in all { |
| 335 | var text = bytes(p.text) |
| 336 | if text.count > SwarmCore.maxTextBytes { text = SwarmCore.clip(text, SwarmCore.maxTextBytes); clipped += 1 } |
| 337 | let stampBytes = bytes(p.time) |
| 338 | let read = SwarmCore.parseTime(stampBytes, 0) |
| 339 | var epoch = read.ok ? read.epoch : 0 |
| 340 | // Board times carry no zone: they are this Mac's local time. |
| 341 | if read.ok && !read.zoned { epoch -= TimeZone.current.secondsFromGMT(for: Date(timeIntervalSince1970: TimeInterval(epoch))) } |
| 342 | input.postSeq.append(p.seq) |
| 343 | input.postTime.append(epoch) |
| 344 | input.postSender.append(input.names.firstIndex(of: bytes(p.agent)) ?? -1) |
| 345 | input.postWith.append([]); input.postTo.append([]); input.postAll.append(0) |
| 346 | input.postText.append(text) |
| 347 | senderNames.append(bytes(p.agent)) |
| 348 | } |
| 349 | } |
| 350 | if unreadable > 0 { notices.append("I left out \(unreadable) board \(unreadable == 1 ? "line" : "lines") I could not read.") } |
| 351 | if clipped > 0 { notices.append("\(clipped) long \(clipped == 1 ? "post is" : "posts are") cut at \(SwarmCore.maxTextBytes) bytes.") } |
| 352 | if system > 0 { notices.append("I do not show \(system) channel \(system == 1 ? "change" : "changes") (who follows which channel). They are not posts.") } |
| 353 | |
| 354 | let title = oneLine(roster["title"] as? String ?? "", 80) |
| 355 | return finish(input, title: title.isEmpty ? "Swarm" : title, senderNames: senderNames, notices: notices, |
| 356 | roles: roles, models: models, details: [], alsoCalled: [], activities: activities, failureTexts: failureTexts, steps: steps) |
| 357 | } |
| 358 | |
| 359 | // MARK: A plain-text board |
| 360 | |
| 361 | /// Turns the text of a board file (its last lines) into a snapshot. `totalLines` is the length of the whole |
| 362 | /// file, so every post keeps its real line number. |
| 363 | static func board(text: String, totalLines: Int, title: String, owners: [String], now: Date) -> (snapshot: SwarmSnapshot?, problem: String) { |
| 364 | var lines = text.split(separator: "\n", omittingEmptySubsequences: false).map { Array($0.utf8) } |
| 365 | if lines.last?.isEmpty == true { lines.removeLast() } |
| 366 | let b = SwarmCore.assemble(lines: lines, firstSeq: max(1, totalLines - lines.count + 1)) |
| 367 | var notices: [String] = [] |
| 368 | if b.olderLinesDropped > 0 { notices.append("I read the newest \(SwarmCore.maxPosts) lines only. \(b.olderLinesDropped) older ones in this fetch are not shown.") } |
| 369 | if b.skippedLines > 0 { notices.append("I left out \(b.skippedLines) \(b.skippedLines == 1 ? "line that is not a post" : "lines that are not posts") (no time at the start).") } |
| 370 | if b.clippedLines > 0 { notices.append("\(b.clippedLines) long \(b.clippedLines == 1 ? "post is" : "posts are") cut to fit my limits.") } |
| 371 | if b.membersDropped + b.spellingsDropped > 0 { |
| 372 | notices.append("This part of the board names " + (b.spellingsDropped > 0 ? "many" : "\(b.membersDropped)") + " more agents than the \(SwarmCore.maxMembers) I list. Their posts still appear on the Board.") |
| 373 | } |
| 374 | var input = SwarmCore.Input() |
| 375 | let n = b.names.count |
| 376 | input.hasRoster = false |
| 377 | input.now = Int(now.timeIntervalSince1970) |
| 378 | input.citeHead = 0 // "#123" on this board is a ticket number, not a line number |
| 379 | input.names = b.names |
| 380 | input.roles = [Int](repeating: SwarmCore.roleWorker, count: n) |
| 381 | input.killed = [Int](repeating: 0, count: n) |
| 382 | input.wake = [Int](repeating: SwarmCore.wakeUnknown, count: n) |
| 383 | input.turn = [Int](repeating: SwarmCore.turnUnknown, count: n) |
| 384 | input.lastRead = [Int](repeating: -1, count: n) |
| 385 | input.lastMove = [Int](repeating: 0, count: n) |
| 386 | input.failure = [Int](repeating: SwarmCore.attentionNone, count: n) |
| 387 | input.channels = [[[UInt8]]](repeating: [], count: n) |
| 388 | input.owner = b.names.map { name in owners.contains { SwarmCore.equalFold(bytes($0), name) } ? 1 : 0 } |
| 389 | input.postSeq = b.postSeq; input.postTime = b.postTime; input.postSender = b.postSender; input.postWith = b.postWith |
| 390 | input.postTo = b.postTo; input.postAll = b.postAll; input.postText = b.postText |
| 391 | let blank = [String](repeating: "", count: n) |
| 392 | return finish(input, title: title, senderNames: b.postSenderName, notices: notices, roles: blank, models: blank, |
| 393 | details: b.details.map(string), alsoCalled: b.alsoCalled.map(string), activities: blank, failureTexts: blank, |
| 394 | steps: [Int](repeating: 0, count: n)) |
| 395 | } |
| 396 | |
| 397 | /// The start of a post, without the names it opens with. |
| 398 | static func gist(_ text: [UInt8]) -> String { |
| 399 | var s = string(Array(text.prefix(400))) |
| 400 | for _ in 0..<8 { |
| 401 | let t = s.drop { $0 == " " || $0 == "," || $0 == ":" } |
| 402 | guard t.first == "@", let end = t.firstIndex(where: { $0 == " " || $0 == "\n" }) else { s = String(t); break } |
| 403 | s = String(t[end...]) |
| 404 | } |
| 405 | return oneLine(s, 140) |
| 406 | } |
| 407 | |
| 408 | static func finish(_ input: SwarmCore.Input, title: String, senderNames: [[UInt8]], notices: [String], roles: [String], models: [String], |
| 409 | details: [String], alsoCalled: [String], activities: [String], failureTexts: [String], steps: [Int]) -> (snapshot: SwarmSnapshot?, problem: String) { |
| 410 | let d = SwarmCore.derive(input) |
| 411 | guard d.refused == 0 else { return (nil, "I can't show this swarm: its data does not fit what I can read (reason \(d.refused)).") } |
| 412 | var snap = SwarmSnapshot() |
| 413 | snap.title = title |
| 414 | snap.hasRoster = input.hasRoster |
| 415 | snap.notices = notices |
| 416 | if d.postsWithClippedSpans > 0 { snap.notices.append("\(d.postsWithClippedSpans) \(d.postsWithClippedSpans == 1 ? "post has" : "posts have") more mentions than I mark (\(SwarmCore.maxSpans)).") } |
| 417 | snap.head = d.head |
| 418 | snap.working = d.working; snap.waiting = d.waiting; snap.stopped = d.stopped |
| 419 | snap.overviewOrder = d.overviewOrder; snap.memberOrder = d.memberOrder |
| 420 | snap.helper = d.helper; snap.postSender = input.postSender; snap.postWith = input.postWith; snap.postDirect = d.postDirect; snap.postAll = d.postAll |
| 421 | func date(_ epoch: Int) -> Date? { epoch > 0 ? Date(timeIntervalSince1970: TimeInterval(epoch)) : nil } |
| 422 | let names = input.names.map(string) |
| 423 | for i in input.postSeq.indices { |
| 424 | let s = input.postSender[i] |
| 425 | snap.posts.append(SwarmPost(id: input.postSeq[i], senderIndex: s, sender: s >= 0 ? names[s] : string(i < senderNames.count ? senderNames[i] : []), |
| 426 | with: input.postWith[i].map { names[$0] }, to: d.postDirect[i], all: d.postAll[i] == 1, |
| 427 | time: date(input.postTime[i]), text: input.postText[i], spans: d.postSpans[i], startsGroup: d.postStartsGroup[i] == 1)) |
| 428 | } |
| 429 | snap.lastPostTime = snap.posts.last?.time |
| 430 | for m in names.indices { |
| 431 | let last = d.lastPost[m] |
| 432 | let live = d.state[m] == SwarmCore.stateWorking && m < activities.count && !activities[m].isEmpty |
| 433 | snap.members.append(SwarmMember( |
| 434 | id: m, name: names[m], role: m < roles.count ? roles[m] : "", model: m < models.count ? models[m] : "", |
| 435 | detail: m < details.count ? details[m] : "", alsoCalled: m < alsoCalled.count ? alsoCalled[m] : "", |
| 436 | wake: input.wake[m], state: d.state[m], attention: d.attention[m], group: d.group[m], helper: d.helper[m] == 1, |
| 437 | idleSeconds: d.idleSeconds[m], unread: d.unread[m], lastRead: input.lastRead[m], posts: d.postCount[m], |
| 438 | lastSeq: last >= 0 ? input.postSeq[last] : 0, lastPostTime: last >= 0 ? date(input.postTime[last]) : nil, |
| 439 | activity: live ? activities[m] : (last >= 0 ? gist(input.postText[last]) : ""), activityIsLive: live, |
| 440 | waitingOn: d.waitingOn[m] >= 0 ? names[d.waitingOn[m]] : "", waitingSeq: d.waitingSeq[m], asksYouSeq: d.asksYouSeq[m], |
| 441 | failureText: m < failureTexts.count ? failureTexts[m] : "", steps: m < steps.count ? steps[m] : 0)) |
| 442 | } |
| 443 | return (snap, "") |
| 444 | } |
| 445 | |
| 446 | // MARK: A board on another computer |
| 447 | |
| 448 | enum Fetched: Sendable { |
| 449 | case unchanged |
| 450 | case text(String, size: Int, total: Int) |
| 451 | case missing |
| 452 | case unreachable |
| 453 | } |
| 454 | |
| 455 | /// How the file is named in the remote command: "~/" is the home folder there, everything else is quoted. |
| 456 | static func remotePath(_ path: String) -> String { |
| 457 | path.hasPrefix("~/") ? "\"$HOME\"/" + Shell.quote(String(path.dropFirst(2))) : Shell.quote(path) |
| 458 | } |
| 459 | |
| 460 | /// The remote command: say how big the file is, and send its last lines only when the size differs from `known`. |
| 461 | static func fetchCommand(path: String, known: Int?) -> String { |
| 462 | "f=\(remotePath(path)); [ -r \"$f\" ] || { echo HOP-BOARD-MISSING; exit 0; }; " + |
| 463 | "s=$(wc -c < \"$f\" | tr -d ' '); n=$(wc -l < \"$f\" | tr -d ' '); echo \"HOP-BOARD $s $n\"; " + |
| 464 | "[ \"$s\" = \"\(known.map(String.init) ?? "-")\" ] || head -n \"$n\" \"$f\" | tail -n \(boardTailLines)" |
| 465 | } |
| 466 | |
| 467 | /// Reads the end of the board file over the same ssh route Hop uses for its other machines. Only the tail is |
| 468 | /// ever fetched, and nothing at all when the file has not grown. |
| 469 | static func fetch(_ machine: Machine, path: String, known: Int?) async -> Fetched { |
| 470 | let r = await Remote.run(machine, fetchCommand(path: path, known: known), timeout: 12) |
| 471 | guard r.code == 0 else { return .unreachable } |
| 472 | var lines = r.out.split(separator: "\n", omittingEmptySubsequences: false) |
| 473 | guard let at = lines.firstIndex(where: { $0.hasPrefix("HOP-BOARD") }) else { return .unreachable } |
| 474 | if lines[at] == "HOP-BOARD-MISSING" { return .missing } |
| 475 | let head = lines[at].split(separator: " ") |
| 476 | guard head.count == 3, let size = Int(head[1]), let total = Int(head[2]) else { return .unreachable } |
| 477 | if let known, known == size { return .unchanged } |
| 478 | lines.removeFirst(at + 1) |
| 479 | return .text(lines.joined(separator: "\n"), size: size, total: total) |
| 480 | } |
| 481 | |
| 482 | // MARK: Plain text (for `hop swarm`) |
| 483 | |
| 484 | static func stateWord(_ m: SwarmMember) -> String { |
| 485 | switch m.state { |
| 486 | case SwarmCore.stateWorking: return "working" |
| 487 | case SwarmCore.stateWaiting: return "waiting" |
| 488 | default: return "stopped" |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | /// One sentence on why a member is where it is in the Overview. |
| 493 | static func reason(_ m: SwarmMember, hasRoster: Bool) -> String { |
| 494 | if m.state == SwarmCore.stateStopped { return "Stopped." } |
| 495 | switch m.attention { |
| 496 | case SwarmCore.attentionStuck: return "No movement for \(max(1, m.idleSeconds / 60)) min, and it is not waiting for a post." |
| 497 | case SwarmCore.attentionQuota: return "Its last step failed: out of quota or rate limited." + (m.failureText.isEmpty ? "" : " " + m.failureText) |
| 498 | case SwarmCore.attentionError: return "Its last step failed." + (m.failureText.isEmpty ? "" : " " + m.failureText) |
| 499 | default: break |
| 500 | } |
| 501 | if m.asksYouSeq > 0 { return "Wrote to you in #\(m.asksYouSeq). No answer yet." } |
| 502 | if m.group == SwarmCore.groupWaitingOn { return "Wrote to \(m.waitingOn) in #\(m.waitingSeq). No answer yet." } |
| 503 | if m.state == SwarmCore.stateWorking { |
| 504 | if m.activityIsLive { return m.activity } |
| 505 | if hasRoster { return "Working." } |
| 506 | return m.activity.isEmpty ? "Posted in the last \(SwarmCore.activeSeconds / 60) minutes." : "Just posted: " + m.activity |
| 507 | } |
| 508 | return m.lastSeq > 0 ? "Nothing open. Last post #\(m.lastSeq)." : "No post in view." |
| 509 | } |
| 510 | |
| 511 | static func groupTitle(_ g: Int) -> String { |
| 512 | switch g { |
| 513 | case SwarmCore.groupNeedsYou: return "Needs you" |
| 514 | case SwarmCore.groupWorking: return "Working" |
| 515 | case SwarmCore.groupWaitingOn: return "Waiting on someone" |
| 516 | default: return "Parked" |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | static func report(_ s: SwarmSnapshot) -> String { |
| 521 | var out = ["\(s.title): \(s.posts.count) posts, \(s.members.count) members (\(s.working) working, \(s.waiting) waiting, \(s.stopped) stopped), newest #\(s.head)"] |
| 522 | var group = 0 |
| 523 | for i in s.overviewOrder { |
| 524 | let m = s.members[i] |
| 525 | if m.group != group { group = m.group; out.append("[\(groupTitle(group))]") } |
| 526 | out.append(" \(m.name)\t\(stateWord(m))\t\(m.posts) \(m.posts == 1 ? "post" : "posts")\(m.unread > 0 ? ", \(m.unread) unread" : "")\t\(reason(m, hasRoster: s.hasRoster))") |
| 527 | } |
| 528 | let helper = s.helper |
| 529 | let edges = SwarmCore.edges(memberCount: s.members.count, helper: helper, postSender: s.postSender, postWith: s.postWith, |
| 530 | postDirect: s.postDirect, postAll: s.postAll, upTo: s.posts.count) |
| 531 | var rows: [(Int, String)] = [] |
| 532 | var e = 0 |
| 533 | while e + 4 < edges.count { |
| 534 | if edges[e + 3] > 0 { rows.append((edges[e + 3], "\(s.members[edges[e]].name) -> \(s.members[edges[e + 1]].name)")) } |
| 535 | e += 5 |
| 536 | } |
| 537 | out.append("[Who writes to whom, by name] \(rows.count) links") |
| 538 | for r in rows.sorted(by: { $0.0 > $1.0 }).prefix(12) { out.append(" \(r.0)x\t\(r.1)") } |
| 539 | for n in s.notices { out.append("note: " + n) } |
| 540 | return out.joined(separator: "\n") |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | /// What the Swarm section shows: the list of swarms, the chosen one, and its latest snapshot. Reading happens |
| 545 | /// off the main thread, and only while the section is open. |
| 546 | @MainActor |
| 547 | final class SwarmStore: ObservableObject { |
| 548 | @Published private(set) var sources: [SwarmSource] = [] |
| 549 | @Published private(set) var selectedID: String? |
| 550 | @Published private(set) var snapshot: SwarmSnapshot? |
| 551 | @Published private(set) var note = "Looking for swarms…" |
| 552 | @Published private(set) var live = false |
| 553 | @Published private(set) var read: Date? |
| 554 | |
| 555 | private var loop: Task<Void, Never>? |
| 556 | private var roots: [String] = [] |
| 557 | private var boardSource: SwarmSource? |
| 558 | private var boardMachine: Machine? |
| 559 | private var owners: [String] = [] |
| 560 | private var picked = false // the user chose a source: never switch away by myself |
| 561 | private var generation = 0 |
| 562 | private var signature = "" |
| 563 | private var builtAt = Date.distantPast |
| 564 | private var boardText: (text: String, size: Int, total: Int)? |
| 565 | private var boardAskedAt = Date.distantPast |
| 566 | private let cache = SwarmTranscriptCache() |
| 567 | |
| 568 | static let pickKey = "swarmSource" // the swarm picked last time, remembered across openings |
| 569 | |
| 570 | static func ownerNames(_ cfg: HopConfig) -> [String] { |
| 571 | ([cfg.ownerName.trimmingCharacters(in: .whitespaces)] + ["user", "human"]).filter { !$0.isEmpty } |
| 572 | } |
| 573 | |
| 574 | /// The factory's own board, when a factory host and a board file are set. |
| 575 | static func boardSource(_ cfg: HopConfig) -> (source: SwarmSource, machine: Machine)? { |
| 576 | let host = cfg.factoryHost.trimmingCharacters(in: .whitespaces), path = cfg.factoryBoard.trimmingCharacters(in: .whitespaces) |
| 577 | guard !host.isEmpty, !path.isEmpty else { return nil } |
| 578 | let machine = cfg.machines.first { $0.ssh == host } ?? Machine(name: host, ssh: host, roots: []) |
| 579 | return (SwarmSource(id: "board:\(host):\(path)", kind: .board(host: host, path: path), title: "Factory board", place: machine.name, modified: nil), machine) |
| 580 | } |
| 581 | |
| 582 | func start(_ cfg: HopConfig) { |
| 583 | roots = cfg.swarmFolders |
| 584 | owners = Self.ownerNames(cfg) |
| 585 | if let b = Self.boardSource(cfg) { boardSource = b.source; boardMachine = b.machine } else { boardSource = nil; boardMachine = nil } |
| 586 | guard loop == nil else { return } |
| 587 | loop = Task { [weak self] in |
| 588 | var tick = 0 |
| 589 | while !Task.isCancelled { |
| 590 | guard let self else { return } |
| 591 | if tick % 5 == 0 { await self.rescan() } |
| 592 | await self.refresh() |
| 593 | tick += 1 |
| 594 | try? await Task.sleep(nanoseconds: 2_000_000_000) |
| 595 | } |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | /// The section was closed or Hop was hidden: stop reading. The last snapshot stays. |
| 600 | func stop() { loop?.cancel(); loop = nil } |
| 601 | |
| 602 | func select(_ id: String) { |
| 603 | guard id != selectedID else { return } |
| 604 | picked = true |
| 605 | UserDefaults.standard.set(id, forKey: Self.pickKey) |
| 606 | choose(id) |
| 607 | Task { await refresh() } |
| 608 | } |
| 609 | |
| 610 | func reload() { signature = ""; builtAt = .distantPast; boardAskedAt = .distantPast; boardText = nil; Task { await rescan(); await refresh() } } |
| 611 | |
| 612 | private func choose(_ id: String?) { |
| 613 | selectedID = id |
| 614 | generation += 1 |
| 615 | snapshot = nil; signature = ""; builtAt = .distantPast; boardAskedAt = .distantPast; read = nil; live = false |
| 616 | note = id == nil ? "I found no swarm on this Mac yet." : "Reading…" |
| 617 | } |
| 618 | |
| 619 | private func rescan() async { |
| 620 | let roots = roots |
| 621 | let found = await Task.detached(priority: .utility) { SwarmReader.scan(roots: roots) }.value |
| 622 | var list = found.sources |
| 623 | if let b = boardSource { list.append(b) } |
| 624 | if list != sources { sources = list } |
| 625 | if let id = selectedID, list.contains(where: { $0.id == id }) { return } |
| 626 | // Nothing chosen yet: the one picked last time if it is still there; else a swarm on this Mac that moved within |
| 627 | // the last hour, else the factory board, else the newest swarm. |
| 628 | let fresh = found.sources.first { ($0.modified ?? .distantPast) > Date().addingTimeInterval(-3600) } |
| 629 | let last = UserDefaults.standard.string(forKey: Self.pickKey).flatMap { id in list.first { $0.id == id } } |
| 630 | picked = false |
| 631 | choose((last ?? fresh ?? boardSource ?? found.sources.first)?.id) |
| 632 | } |
| 633 | |
| 634 | private func refresh() async { |
| 635 | guard let id = selectedID, let source = sources.first(where: { $0.id == id }) else { return } |
| 636 | let token = generation, owners = owners, cache = cache, now = Date() |
| 637 | switch source.kind { |
| 638 | case .folder(let dir): |
| 639 | let sig = await Task.detached(priority: .utility) { SwarmReader.folderSignature(dir) }.value |
| 640 | guard token == generation else { return } |
| 641 | // Members move without the board changing, so look again every 10 seconds; unchanged transcripts are not read again. |
| 642 | guard sig != signature || now.timeIntervalSince(builtAt) >= 10 else { return } |
| 643 | let result = await Task.detached(priority: .utility) { SwarmReader.folder(dir, owners: owners, now: now, cache: cache) }.value |
| 644 | guard token == generation else { return } |
| 645 | signature = sig; builtAt = now |
| 646 | show(result) |
| 647 | case .board(_, let path): |
| 648 | guard let machine = boardMachine else { return } |
| 649 | if now.timeIntervalSince(boardAskedAt) >= 20 { |
| 650 | boardAskedAt = now |
| 651 | let fetched = await SwarmReader.fetch(machine, path: path, known: boardText?.size) |
| 652 | guard token == generation else { return } |
| 653 | switch fetched { |
| 654 | case .unchanged: live = true; read = Date() |
| 655 | case .text(let text, let size, let total): boardText = (text, size, total); builtAt = .distantPast |
| 656 | case .missing: |
| 657 | boardText = nil; snapshot = nil; live = false |
| 658 | note = "There is no board file at \(path) on \(machine.name)." |
| 659 | return |
| 660 | case .unreachable: |
| 661 | live = false |
| 662 | if snapshot == nil { note = "I can't reach \(machine.name) right now. I'll keep trying." } |
| 663 | return |
| 664 | } |
| 665 | } |
| 666 | // "Working" on this board means "posted lately", so the same text is worked out again once a minute. |
| 667 | guard let held = boardText, now.timeIntervalSince(builtAt) >= 60 else { return } |
| 668 | let title = source.title + " on " + source.place |
| 669 | let result = await Task.detached(priority: .utility) { |
| 670 | SwarmReader.board(text: held.text, totalLines: held.total, title: title, owners: owners, now: now) |
| 671 | }.value |
| 672 | guard token == generation else { return } |
| 673 | builtAt = now |
| 674 | show(result) |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | private func show(_ result: (snapshot: SwarmSnapshot?, problem: String)) { |
| 679 | if let s = result.snapshot { |
| 680 | snapshot = s; live = true; read = Date(); note = "" |
| 681 | } else { |
| 682 | snapshot = nil; live = false; note = result.problem |
| 683 | } |
| 684 | } |
| 685 | } |