lobstah 0.8.6 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,321 @@
1
+ import Foundation
2
+
3
+ // MARK: - lobstah state
4
+
5
+ public struct AckInfo: Decodable, Equatable {
6
+ public let at: String
7
+ public let by: String
8
+ }
9
+
10
+ public struct AttentionItem: Decodable, Equatable {
11
+ public let id: String
12
+ public let verb: String
13
+ public let note: String?
14
+ /** The stable item key `lobstah attention ack` takes — absent from an older lobstah. */
15
+ public var key: String? = nil
16
+ /** Acknowledged for display: the pet skips it (the helm's wakes never do). */
17
+ public var acked: AckInfo? = nil
18
+ public var quiet: Bool? = nil
19
+ /** question | decision | landed | watch | pr:draft | pr:review | pr:checks | pr:conflict | pr:ready | report — absent from an older lobstah. */
20
+ public var kind: String? = nil
21
+ /** pr:* kinds: the PR this pet walks for. */
22
+ public var prUrl: String? = nil
23
+ public var reviewUrl: String? = nil
24
+ /** A stack's short line: its title, count and state. Absent otherwise, and from an older lobstah. */
25
+ public var headline: String? = nil
26
+ public var petOpen: String? = nil
27
+ /** The hash of the state the item stands on; a new one re-stands an acked item. */
28
+ public var stateHash: String? = nil
29
+ /** An item of a grounds on a wharf: that grounds. Absent for local grounds, and from an older lobstah. */
30
+ public var grounds: String? = nil
31
+ /** An item of a grounds on a wharf: the hosted glass at this item. Absent for local grounds. */
32
+ public var glass: String? = nil
33
+
34
+ public init(id: String, verb: String, note: String?, key: String? = nil, acked: AckInfo? = nil, kind: String? = nil, prUrl: String? = nil, stateHash: String? = nil, grounds: String? = nil, glass: String? = nil) {
35
+ self.id = id
36
+ self.verb = verb
37
+ self.note = note
38
+ self.key = key
39
+ self.acked = acked
40
+ self.kind = kind
41
+ self.prUrl = prUrl
42
+ self.stateHash = stateHash
43
+ self.grounds = grounds
44
+ self.glass = glass
45
+ }
46
+
47
+ /** The identity stays fixed when labels, order, or acknowledgements change. */
48
+ public var identity: String { "\(kind ?? "question"):\(key ?? id)" }
49
+
50
+ /** PR pets open the repo review tool; review notifications open their row in the glass. */
51
+ public var prLink: URL? { ((kind?.hasPrefix("pr:") ?? false) || kind == "stack-ready" ) ? (reviewUrl ?? prUrl).flatMap(URL.init(string:)) : nil }
52
+
53
+ /**
54
+ * The glass this item belongs to: the one place that picks between the
55
+ * hosted glass and the local one. An item of a grounds on a wharf names its
56
+ * hosted glass, already at the item (lobstah builds the link; the wharf
57
+ * keeps that grounds' state, so the local glass has little to show). Every
58
+ * other item, and a link that is not HTTPS (HTTP on loopback only), gets
59
+ * `local`. No setting chooses between them.
60
+ */
61
+ public func glassAddress(local: URL) -> GlassAddress {
62
+ guard let glass, let url = URL(string: glass), let host = url.host, url.user == nil, url.password == nil else {
63
+ return GlassAddress(url: local, hosted: false)
64
+ }
65
+ let loopback = url.scheme == "http" && ["localhost", "127.0.0.1", "::1"].contains(host)
66
+ guard url.scheme == "https" || loopback else { return GlassAddress(url: local, hosted: false) }
67
+ return GlassAddress(url: url, hosted: true)
68
+ }
69
+
70
+ /** A report pet clicks through to the report's own page on the spyglass (/report/<key>). */
71
+ public func reportLink(glass: URL) -> URL? {
72
+ guard kind == "report", let key, let encoded = key.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { return nil }
73
+ return URL(string: "\(glass.absoluteString)/report/\(encoded)")
74
+ }
75
+
76
+ /**
77
+ * A decision pet clicks through to the spyglass at the decision's card
78
+ * (#decision/<key>). The card stays until the decision is answered or
79
+ * withdrawn; the click's ack only stops this pet walking.
80
+ */
81
+ public func decisionLink(glass: URL) -> URL? {
82
+ guard kind == "decision", let key, let encoded = key.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { return nil }
83
+ return URL(string: "\(glass.absoluteString)/#decision/\(encoded)")
84
+ }
85
+
86
+ /**
87
+ * Where a report or decision pet shows in the glass: the hash an open glass
88
+ * page moves to (`#report/<key>`, `#decision/<key>`), and the URL a new tab
89
+ * opens when none is open. Nil for every other kind.
90
+ */
91
+ public func glassTarget(glass: URL) -> GlassTarget? {
92
+ let address = glassAddress(local: glass)
93
+ if address.hosted && (kind == "report" || kind == "decision") {
94
+ return GlassTarget(hash: address.url.fragment.map { "#\($0)" } ?? "", url: address.url)
95
+ }
96
+ guard let key, let encoded = key.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else { return nil }
97
+ if kind == "review", let url = URL(string: "\(glass.absoluteString)/#review-\(encoded)") { return GlassTarget(hash: "#review-\(encoded)", url: url) }
98
+ if let url = reportLink(glass: glass) { return GlassTarget(hash: "#report/\(encoded)", url: url) }
99
+ if let url = decisionLink(glass: glass) { return GlassTarget(hash: "#decision/\(encoded)", url: url) }
100
+ return nil
101
+ }
102
+
103
+
104
+ /** The CLI acknowledgement for a pet click or its Acknowledge menu entry. */
105
+ public var ackArguments: [String]? {
106
+ key.map { ["attention", "ack", $0, "--by", "pet"] }
107
+ }
108
+
109
+ /** The short kind label shown before the note; nothing for a question or a decision (its title only). */
110
+ public var kindLabel: String? {
111
+ switch kind {
112
+ case "pr:draft": return "draft"
113
+ case "pr:review": return "review"
114
+ case "pr:checks": return "checks"
115
+ case "pr:conflict": return "conflicts"
116
+ case "pr:ready": return "ready"
117
+ case "stack-ready": return "stack ready"
118
+ case "landed": return "landed"
119
+ case "watch": return "watch"
120
+ case "report": return "report"
121
+ case "review": return nil
122
+ default: return nil
123
+ }
124
+ }
125
+
126
+ /** Bubble text: the label, then the headline or the note. */
127
+ public var bubbleText: String {
128
+ let body = headline ?? note ?? verb
129
+ return kindLabel.map { "\($0) · \(body)" } ?? body
130
+ }
131
+
132
+ /** Bubble text as it fits three lines of the bubble. */
133
+ public var bubbleLine: String {
134
+ let text = bubbleText
135
+ return text.count > 80 ? String(text.prefix(79)) + "…" : text
136
+ }
137
+
138
+ /** The item standing for this one and `extra` more when too many walk: same target, shorter text. */
139
+ public func standingFor(extra: Int) -> AttentionItem {
140
+ var item = AttentionItem(id: id, verb: verb, note: (headline ?? note ?? verb) + " (+\(extra) more)", key: key, kind: kind, prUrl: prUrl, stateHash: stateHash)
141
+ item.petOpen = petOpen
142
+ item.reviewUrl = reviewUrl
143
+ return item
144
+ }
145
+ }
146
+
147
+ /// Opens a pet's target before acknowledging it. A report or a decision first
148
+ /// asks `showGlass` to show it in a glass page that is already open (and to
149
+ /// bring that page's app forward); `showGlass` runs the given fallback when
150
+ /// no page is open. The fallback is the old click: a decision brings up the
151
+ /// live helm's session, which frames it, or with no live helm opens its glass
152
+ /// card; a report opens its page. PRs open their URLs. Other items focus the
153
+ /// helm. `focusHelm` gets the glass URL to open when no helm step works.
154
+ /// Reports and decisions use the configured route with their own glass
155
+ /// (`glassAddress`). Other hosted items open that glass directly; PRs always
156
+ /// use the repo's review tool. `glass` is the local glass.
157
+ public func clickAttentionItem(
158
+ _ item: AttentionItem,
159
+ glass: URL,
160
+ helmLive: Bool = false,
161
+ open: @escaping (URL) -> Void,
162
+ focusHelm: @escaping (URL) -> Void,
163
+ showGlass: (GlassTarget, @escaping () -> Void) -> Void = { _, otherwise in otherwise() },
164
+ showApp: (GlassTarget, @escaping () -> Void) -> Void = { _, otherwise in otherwise() },
165
+ acknowledge: ([String]) -> Void
166
+ ) {
167
+ let address = item.glassAddress(local: glass)
168
+ if let url = item.prLink {
169
+ open(url)
170
+ } else if let target = item.glassTarget(glass: glass) {
171
+ let isDecision = item.kind == "decision"
172
+ switch item.petOpen {
173
+ case "tab":
174
+ open(target.url)
175
+ case "app":
176
+ showApp(target) { open(target.url) }
177
+ case "helm":
178
+ focusHelm(target.url)
179
+ default:
180
+ // An older CLI has no setting: preserve its existing routing.
181
+ if address.hosted {
182
+ open(target.url)
183
+ } else {
184
+ showGlass(target) {
185
+ if isDecision && helmLive { focusHelm(target.url) } else { open(target.url) }
186
+ }
187
+ }
188
+ }
189
+ } else if address.hosted {
190
+ open(address.url)
191
+ } else {
192
+ focusHelm(glass)
193
+ }
194
+ if item.kind == "review", let key = item.key { acknowledge(["reviews", "seen", key]) }
195
+ else if let args = item.ackArguments { acknowledge(args) }
196
+ }
197
+
198
+ /// Items this pet clicked or acknowledged: identity → the stateHash it hid,
199
+ /// as the glass hides a clicked lob per browser. A clicked pet stops walking
200
+ /// at once, without waiting for `lobstah attention ack` to land (it can time
201
+ /// out) or for the next read to see it. A new stateHash walks it again.
202
+ public struct ClickedItems {
203
+ private var hidden: [String: String] = [:]
204
+
205
+ public init() {}
206
+
207
+ /// An item with no stateHash (an older lobstah) waits for the CLI's ack.
208
+ public mutating func hide(_ item: AttentionItem) {
209
+ if let hash = item.stateHash { hidden[item.identity] = hash }
210
+ }
211
+
212
+ /// The items still to walk. A hide is kept only while its item is read
213
+ /// with the same stateHash; once the CLI's ack lands (the read drops the
214
+ /// item) or the state moves, the hide is forgotten.
215
+ public mutating func walking(_ items: [AttentionItem]) -> [AttentionItem] {
216
+ var read: [String: String] = [:]
217
+ for item in items { if let hash = item.stateHash { read[item.identity] = hash } }
218
+ hidden = hidden.filter { read[$0.key] == $0.value }
219
+ return items.filter { item in item.stateHash == nil || hidden[item.identity] != item.stateHash }
220
+ }
221
+ }
222
+
223
+ /// The shape both reads share: `lobstah attention --json` prints
224
+ /// `{ "attention": [...] }`, and `lobstah man tend --json` prints the whole
225
+ /// report with the same list under `attention`.
226
+ public struct AttentionReport: Decodable {
227
+ public let attention: [AttentionItem]
228
+ }
229
+
230
+ public func lobstahHome() -> URL {
231
+ if let home = ProcessInfo.processInfo.environment["LOBSTAH_HOME"] {
232
+ return URL(fileURLWithPath: home)
233
+ }
234
+ return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".lobstah")
235
+ }
236
+
237
+ // MARK: - the attention read
238
+
239
+ /// Runs `lobstah <args>` and returns how it ended.
240
+ public typealias LobstahRunner = ([String]) -> CommandOutcome
241
+
242
+ /// Seconds each lobstah read may take.
243
+ public let readTimeout: TimeInterval = 10
244
+
245
+ public let defaultRunner: LobstahRunner = { args in
246
+ execute("/usr/bin/env", ["lobstah"] + args, timeout: readTimeout).outcome
247
+ }
248
+
249
+ /// The narrow command first. An older lobstah has no `attention --json`
250
+ /// (it exits 2 on the unknown flag), so the whole report is the fallback.
251
+ public let attentionCommands: [[String]] = [
252
+ ["attention", "--json"],
253
+ ["man", "tend", "--json"],
254
+ ]
255
+
256
+ public struct AttentionRead: Equatable {
257
+ /// Items to walk (acknowledged items removed); nil when every command failed.
258
+ public let items: [AttentionItem]?
259
+ /// The command that worked, as typed after `lobstah`.
260
+ public let command: String?
261
+ /// Why each command failed, when all failed.
262
+ public let failure: String?
263
+ }
264
+
265
+ /// Why one outcome is not an attention list, or the list.
266
+ public func decodeAttention(_ outcome: CommandOutcome) -> Result<[AttentionItem], ReadFailure> {
267
+ switch outcome {
268
+ case .timedOut:
269
+ return .failure(.timeout)
270
+ case .launchFailed(let why):
271
+ return .failure(.launch(why))
272
+ case let .exited(status, data):
273
+ if status != 0 { return .failure(.exit(status)) }
274
+ guard let report = try? JSONDecoder().decode(AttentionReport.self, from: data) else {
275
+ return .failure(.undecodable(data.count))
276
+ }
277
+ return .success(report.attention)
278
+ }
279
+ }
280
+
281
+ public enum ReadFailure: Error, Equatable, CustomStringConvertible {
282
+ case timeout
283
+ case exit(Int32)
284
+ case undecodable(Int)
285
+ case launch(String)
286
+
287
+ public var description: String {
288
+ switch self {
289
+ case .timeout: return "timed out"
290
+ case .exit(let status): return "exited with status \(status)"
291
+ case .undecodable(let bytes): return "output does not decode (\(bytes) bytes)"
292
+ case .launch(let why): return "did not start (\(why))"
293
+ }
294
+ }
295
+ }
296
+
297
+ /// Reads the attention list: the narrow command, then the fallback.
298
+ /// Acknowledgements are display-only: an acked item stays in lobstah's
299
+ /// attention (the helm still needs it) but no longer walks.
300
+ public func readAttention(run: LobstahRunner = defaultRunner) -> AttentionRead {
301
+ var reasons: [String] = []
302
+ for args in attentionCommands {
303
+ let label = args.joined(separator: " ")
304
+ switch decodeAttention(run(args)) {
305
+ case .success(let items):
306
+ return AttentionRead(items: items.filter { $0.acked == nil && $0.quiet != true }, command: label, failure: nil)
307
+ case .failure(let why):
308
+ reasons.append("`lobstah \(label)` \(why)")
309
+ }
310
+ }
311
+ return AttentionRead(items: nil, command: nil, failure: reasons.joined(separator: "; "))
312
+ }
313
+
314
+ /// A write command (`attention ack`) works when it exits 0; its output is not read.
315
+ public func ackOutcome(_ outcome: CommandOutcome) -> Result<Void, ReadFailure> {
316
+ switch outcome {
317
+ case .timedOut: return .failure(.timeout)
318
+ case .launchFailed(let why): return .failure(.launch(why))
319
+ case let .exited(status, _): return status == 0 ? .success(()) : .failure(.exit(status))
320
+ }
321
+ }
@@ -0,0 +1,105 @@
1
+ import Foundation
2
+
3
+ /// How a child process ended.
4
+ public enum CommandOutcome: Equatable {
5
+ /// The child exited (or died on a signal: status 128 + signal) and its
6
+ /// standard output reached end of file.
7
+ case exited(status: Int32, stdout: Data)
8
+ /// The child ran past the timeout, or held its standard output open past
9
+ /// it. The child was terminated.
10
+ case timedOut
11
+ /// The child did not start.
12
+ case launchFailed(String)
13
+ }
14
+
15
+ public struct CommandResult {
16
+ public let outcome: CommandOutcome
17
+ /// The child's pid; 0 when it did not start.
18
+ public let pid: Int32
19
+ }
20
+
21
+ /// Collects standard output as it arrives. The readability handler runs on
22
+ /// a Foundation queue; the lock guards the buffer and the end-of-file flag.
23
+ private final class OutputCollector {
24
+ private let lock = NSLock()
25
+ private var data = Data()
26
+ private var ended = false
27
+ let eof = DispatchSemaphore(value: 0)
28
+
29
+ func append(_ chunk: Data) {
30
+ lock.lock()
31
+ defer { lock.unlock() }
32
+ if chunk.isEmpty {
33
+ if !ended { ended = true; eof.signal() }
34
+ } else {
35
+ data.append(chunk)
36
+ }
37
+ }
38
+
39
+ var collected: Data {
40
+ lock.lock()
41
+ defer { lock.unlock() }
42
+ return data
43
+ }
44
+ }
45
+
46
+ /// Runs `launch args` and reads its standard output while it runs, so
47
+ /// output of any size works: a pipe holds only about 64 KB, and a child
48
+ /// that fills it blocks until someone reads. Standard error and standard
49
+ /// input go to the null device, so neither can block the child.
50
+ ///
51
+ /// After `timeout` seconds the child gets SIGTERM, then SIGKILL one second
52
+ /// later if it is still alive, and the result is `.timedOut`.
53
+ public func execute(_ launch: String, _ args: [String], timeout: TimeInterval = 10) -> CommandResult {
54
+ let p = Process()
55
+ p.executableURL = URL(fileURLWithPath: launch)
56
+ p.arguments = args
57
+ let out = Pipe()
58
+ p.standardOutput = out
59
+ p.standardError = FileHandle.nullDevice
60
+ p.standardInput = FileHandle.nullDevice
61
+ let exited = DispatchSemaphore(value: 0)
62
+ p.terminationHandler = { _ in exited.signal() }
63
+
64
+ let collector = OutputCollector()
65
+ let reader = out.fileHandleForReading
66
+ reader.readabilityHandler = { handle in collector.append(handle.availableData) }
67
+ let stopReading = {
68
+ reader.readabilityHandler = nil
69
+ try? reader.close()
70
+ }
71
+
72
+ do { try p.run() } catch {
73
+ stopReading()
74
+ return CommandResult(outcome: .launchFailed(error.localizedDescription), pid: 0)
75
+ }
76
+ let pid = p.processIdentifier
77
+ let deadline = DispatchTime.now() + timeout
78
+
79
+ if exited.wait(timeout: deadline) == .timedOut {
80
+ p.terminate()
81
+ if exited.wait(timeout: .now() + 1) == .timedOut {
82
+ kill(pid, SIGKILL)
83
+ _ = exited.wait(timeout: .now() + 1)
84
+ }
85
+ stopReading()
86
+ return CommandResult(outcome: .timedOut, pid: pid)
87
+ }
88
+ // The child is gone. The end of file can trail its exit by a moment; a
89
+ // descendant that still holds the pipe open counts as a timeout.
90
+ let eofDeadline = max(deadline, DispatchTime.now() + 1)
91
+ if collector.eof.wait(timeout: eofDeadline) == .timedOut {
92
+ stopReading()
93
+ return CommandResult(outcome: .timedOut, pid: pid)
94
+ }
95
+ stopReading()
96
+ let status = p.terminationReason == .uncaughtSignal ? 128 + p.terminationStatus : p.terminationStatus
97
+ return CommandResult(outcome: .exited(status: status, stdout: collector.collected), pid: pid)
98
+ }
99
+
100
+ /// Standard output as UTF-8 when the child exits 0; nil on a timeout, a
101
+ /// non-zero exit, a launch failure, or output that is not UTF-8.
102
+ public func runCommand(_ launch: String, _ args: [String], timeout: TimeInterval = 10) -> String? {
103
+ guard case let .exited(status, data) = execute(launch, args, timeout: timeout).outcome, status == 0 else { return nil }
104
+ return String(data: data, encoding: .utf8)
105
+ }
@@ -0,0 +1,156 @@
1
+ import Foundation
2
+
3
+ // MARK: - showing an item in a glass that is already open
4
+
5
+ /// What `lobstah glass show <hash> --json` prints: whether a glass page was
6
+ /// seen recently, and the app it runs in (apps/cli/src/glass-presence.ts).
7
+ public struct GlassShowResult: Decodable, Equatable {
8
+ public var delivered: Bool
9
+ /// claude | chrome | edge | firefox | safari | electron | other
10
+ public var host: String?
11
+ public var visible: Bool?
12
+ public var seenAgoMs: Double?
13
+
14
+ public init(delivered: Bool, host: String? = nil, visible: Bool? = nil, seenAgoMs: Double? = nil) {
15
+ self.delivered = delivered
16
+ self.host = host
17
+ self.visible = visible
18
+ self.seenAgoMs = seenAgoMs
19
+ }
20
+ }
21
+
22
+ /// The glass an item belongs to: the hosted glass of its wharf (already at the
23
+ /// item), or the local glass.
24
+ public struct GlassAddress: Equatable {
25
+ public let url: URL
26
+ public let hosted: Bool
27
+
28
+ public init(url: URL, hosted: Bool) {
29
+ self.url = url
30
+ self.hosted = hosted
31
+ }
32
+ }
33
+
34
+ /// A pet click's glass target: the hash an open glass page moves to, and the
35
+ /// URL a new tab opens when no page is open.
36
+ public struct GlassTarget: Equatable {
37
+ public let hash: String
38
+ public let url: URL
39
+
40
+ public init(hash: String, url: URL) {
41
+ self.hash = hash
42
+ self.url = url
43
+ }
44
+ }
45
+
46
+ public let claudeDesktopBundle = "com.anthropic.claudefordesktop"
47
+
48
+ /// The apps a page's host can be, most likely first. Arc and Brave send
49
+ /// Chrome's user agent, so `chrome` lists them too; the first one running wins.
50
+ public func glassHostBundles(_ host: String?) -> [String] {
51
+ switch host {
52
+ case "claude": return [claudeDesktopBundle]
53
+ case "chrome":
54
+ return ["com.google.Chrome", "company.thebrowser.Browser", "com.brave.Browser", "com.vivaldi.Vivaldi",
55
+ "com.operasoftware.Opera", "org.chromium.Chromium", "com.google.Chrome.canary"]
56
+ case "edge": return ["com.microsoft.edgemac"]
57
+ case "firefox": return ["org.mozilla.firefox", "org.mozilla.firefoxdeveloperedition", "org.mozilla.nightly"]
58
+ case "safari": return ["com.apple.Safari", "com.apple.SafariTechnologyPreview"]
59
+ default: return []
60
+ }
61
+ }
62
+
63
+ /// How a click reaches the glass.
64
+ public enum GlassRoute: Equatable {
65
+ /// A page was seen recently and will show the item: bring the first running
66
+ /// app of these to the front, then open the helm's session link if there is one.
67
+ case raise(bundleIds: [String], sessionLink: URL?)
68
+ /// No page was seen recently, or the glass did not answer: today's path.
69
+ case fallback
70
+ }
71
+
72
+ /// The route for a show's answer. A Claude desktop page raises the Claude app
73
+ /// and, when the helm recorded a `claude://` session link, opens it so the
74
+ /// helm's session (with its Browser pane) comes forward. A browser page raises
75
+ /// that browser only: the default browser first when it fits the user agent,
76
+ /// and the default browser alone when the user agent names none.
77
+ public func glassRoute(_ result: GlassShowResult?, helm: HelmRegistration?, defaultBrowser: String? = nil) -> GlassRoute {
78
+ guard let result, result.delivered else { return .fallback }
79
+ if result.host == "claude" {
80
+ let link = helm?.link.flatMap { $0.hasPrefix("claude://claude.ai/") ? URL(string: $0) : nil }
81
+ return .raise(bundleIds: [claudeDesktopBundle], sessionLink: link)
82
+ }
83
+ var bundles = glassHostBundles(result.host)
84
+ if let defaultBrowser {
85
+ if bundles.isEmpty { bundles = [defaultBrowser] }
86
+ else if let at = bundles.firstIndex(of: defaultBrowser) { bundles.insert(bundles.remove(at: at), at: 0) }
87
+ }
88
+ return .raise(bundleIds: bundles, sessionLink: nil)
89
+ }
90
+
91
+ /// The CLI call behind a click: ask the glass on `port` to show `hash`.
92
+ public func glassShowArguments(_ hash: String, port: Int, installedOnly: Bool = false) -> [String] {
93
+ ["glass", "show", hash, "--port", String(port), "--json"] + (installedOnly ? ["--app"] : [])
94
+ }
95
+
96
+ /// Match Chrome's installed-app metadata to this item's exact glass origin, not
97
+ /// an app's user-chosen name or a browser tab. Safari launching is unverified.
98
+ public func isInstalledChromeGlass(_ info: [String: Any], glass: URL) -> Bool {
99
+ guard info["CrBundleIdentifier"] as? String == "com.google.Chrome",
100
+ let bundle = info["CFBundleIdentifier"] as? String, bundle.hasPrefix("com.google.Chrome.app."),
101
+ let shortcut = info["CrAppModeShortcutURL"] as? String, let url = URL(string: shortcut) else { return false }
102
+ let safe = url.scheme == "https" || (url.scheme == "http" && ["localhost", "127.0.0.1", "::1"].contains(url.host ?? ""))
103
+ return safe && url.scheme == glass.scheme && url.host == glass.host && url.port == glass.port
104
+ && (url.path.isEmpty || url.path == "/") && url.user == nil && url.password == nil && url.query == nil
105
+ }
106
+
107
+ /// Only the local glass accepts the local CLI's presence/show handoff.
108
+ /// A hosted installed app receives its own URL, never a command to a local page.
109
+ public func usesLocalGlassShow(_ target: GlassTarget, local: URL) -> Bool {
110
+ target.url.scheme == local.scheme && target.url.host == local.host && target.url.port == local.port
111
+ }
112
+
113
+ /// A show's answer, or nil when the CLI failed (no glass, an older lobstah).
114
+ public func decodeGlassShow(_ outcome: CommandOutcome) -> GlassShowResult? {
115
+ guard case let .exited(status, data) = outcome, status == 0 else { return nil }
116
+ return try? JSONDecoder().decode(GlassShowResult.self, from: data)
117
+ }
118
+
119
+ /// What a glass click did, for the log and the tests.
120
+ public enum GlassClickOutcome: Equatable {
121
+ /// An open page shows the item; this app came forward.
122
+ case raised(String)
123
+ /// No open page (or its app would not come forward): the fallback ran.
124
+ case fellBack
125
+ }
126
+
127
+ /// Show `target` in a glass page that is already open, and bring that page's
128
+ /// app forward; open nothing new. With no page seen recently, or when no app
129
+ /// of the route comes forward, run `otherwise` (a new tab, as before).
130
+ ///
131
+ /// - `show` runs `lobstah glass show` (blocking: call off the main thread).
132
+ /// - `activate` brings the first running app of the list forward, returning its bundle id.
133
+ /// - `open` opens a URL (the helm's session link).
134
+ @discardableResult
135
+ public func showInGlass(
136
+ _ target: GlassTarget,
137
+ helm: HelmRegistration?,
138
+ defaultBrowser: String?,
139
+ show: (String) -> GlassShowResult?,
140
+ activate: ([String]) -> String?,
141
+ open: (URL) -> Void,
142
+ otherwise: () -> Void
143
+ ) -> GlassClickOutcome {
144
+ switch glassRoute(show(target.hash), helm: helm, defaultBrowser: defaultBrowser) {
145
+ case .fallback:
146
+ otherwise()
147
+ return .fellBack
148
+ case let .raise(bundles, link):
149
+ guard let raised = activate(bundles) else {
150
+ otherwise()
151
+ return .fellBack
152
+ }
153
+ if let link { open(link) }
154
+ return .raised(raised)
155
+ }
156
+ }
@@ -0,0 +1,104 @@
1
+ import Foundation
2
+
3
+ // MARK: - the helm registration the pet reads
4
+
5
+ public struct HelmWindow: Decodable, Equatable {
6
+ public var bundleId: String?
7
+ public var termProgram: String?
8
+ public var tty: String?
9
+ public var itermSession: String?
10
+ public var tmuxPane: String?
11
+
12
+ public init(bundleId: String? = nil, termProgram: String? = nil, tty: String? = nil, itermSession: String? = nil, tmuxPane: String? = nil) {
13
+ self.bundleId = bundleId
14
+ self.termProgram = termProgram
15
+ self.tty = tty
16
+ self.itermSession = itermSession
17
+ self.tmuxPane = tmuxPane
18
+ }
19
+ }
20
+
21
+ public struct HelmRegistration: Decodable, Equatable {
22
+ public var sessionId: String
23
+ public var harness: String?
24
+ public var cwd: String?
25
+ public var heartbeatAt: String
26
+ public var window: HelmWindow?
27
+ /** The helm's own session link (`claude://claude.ai/...`), when its registration carries one. */
28
+ public var link: String?
29
+
30
+ public init(sessionId: String, harness: String? = nil, cwd: String? = nil, heartbeatAt: String, window: HelmWindow? = nil, link: String? = nil) {
31
+ self.sessionId = sessionId
32
+ self.harness = harness
33
+ self.cwd = cwd
34
+ self.heartbeatAt = heartbeatAt
35
+ self.window = window
36
+ self.link = link
37
+ }
38
+ }
39
+
40
+ /// A helm is live while its heartbeat is under 30 minutes old.
41
+ public let helmLiveSeconds: TimeInterval = 1800
42
+
43
+ public func helmIsLive(_ helm: HelmRegistration?, now: Date = Date()) -> Bool {
44
+ guard let helm else { return false }
45
+ let iso = ISO8601DateFormatter()
46
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
47
+ guard let beat = iso.date(from: helm.heartbeatAt) ?? ISO8601DateFormatter().date(from: helm.heartbeatAt) else { return false }
48
+ return now.timeIntervalSince(beat) < helmLiveSeconds
49
+ }
50
+
51
+ // MARK: - the focus ladder
52
+
53
+ /// One way to bring up the helm's session, tried in order until one works.
54
+ public enum HelmFocusStep: Equatable {
55
+ /// The exact iTerm2 session, by its id.
56
+ case itermSession(String)
57
+ /// The exact Terminal.app tab, by its tty.
58
+ case terminalTab(String)
59
+ /// A VS Code-family window: its bundle opened on the helm's folder.
60
+ case editor(bundleId: String, cwd: String)
61
+ /// The app the helm runs in (the Claude desktop app, or any recorded app), brought to the front.
62
+ case activateApp(bundleId: String)
63
+ /// A stale helm: resume its session in a new Terminal window.
64
+ case revive(cwd: String, command: String)
65
+ /// No helm step worked: open the spyglass at this URL.
66
+ case openGlass(URL)
67
+ }
68
+
69
+ private func isEditor(_ bundle: String) -> Bool {
70
+ bundle.contains("VSCode") || bundle.contains("Cursor") || bundle.contains("windsurf")
71
+ }
72
+
73
+ /// The helm's focus ladder, as steps: the exact iTerm2 pane, the Terminal tab
74
+ /// by tty, a VS Code-family window by folder, then the app by bundle id (the
75
+ /// Claude desktop app for a desktop helm), then the spyglass. A stale helm is
76
+ /// resumed in a new Terminal window instead. With no helm, only the spyglass.
77
+ public func helmFocusSteps(_ helm: HelmRegistration?, glass: URL, now: Date = Date()) -> [HelmFocusStep] {
78
+ guard let helm else { return [.openGlass(glass)] }
79
+ guard helmIsLive(helm, now: now) else {
80
+ if let cwd = helm.cwd {
81
+ let resume = helm.harness == "codex" ? "codex resume" : "claude --resume"
82
+ return [.revive(cwd: cwd, command: "\(resume) \(helm.sessionId)")]
83
+ }
84
+ return [.openGlass(glass)]
85
+ }
86
+ var steps: [HelmFocusStep] = []
87
+ let win = helm.window
88
+ if let sess = win?.itermSession, let uuid = sess.split(separator: ":").last {
89
+ steps.append(.itermSession(String(uuid)))
90
+ }
91
+ if let tty = win?.tty, win?.termProgram == "Apple_Terminal" {
92
+ steps.append(.terminalTab(tty))
93
+ }
94
+ if let bundle = win?.bundleId, let cwd = helm.cwd, isEditor(bundle) {
95
+ // An editor window is its folder: opening it is the last step that can run.
96
+ steps.append(.editor(bundleId: bundle, cwd: cwd))
97
+ return steps
98
+ }
99
+ if let bundle = win?.bundleId {
100
+ steps.append(.activateApp(bundleId: bundle))
101
+ }
102
+ steps.append(.openGlass(glass))
103
+ return steps
104
+ }