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,94 @@
1
+ import Foundation
2
+
3
+ /// One line to the pet's standard output, which the LaunchAgent sends to
4
+ /// `~/.lobstah/logs/pet.log`. Unbuffered: a log file is not a terminal, and
5
+ /// a buffered line may never reach the disk.
6
+ public func petLog(_ message: String) {
7
+ let stamp = ISO8601DateFormatter().string(from: Date())
8
+ FileHandle.standardOutput.write(Data("\(stamp) lobstah pet: \(message)\n".utf8))
9
+ }
10
+
11
+ /// What `lobstah doctor` reads: `~/.lobstah/pet/state.json`.
12
+ public struct PetState: Codable, Equatable {
13
+ public let pid: Int32
14
+ /// When the last read finished (ISO 8601).
15
+ public let at: String
16
+ /// Whether the last read produced an attention list.
17
+ public let ok: Bool
18
+ /// The command that worked, as typed after `lobstah`.
19
+ public let command: String?
20
+ /// Why the last read failed.
21
+ public let reason: String?
22
+ public let consecutiveFailures: Int
23
+ /// Items walking after the last good read.
24
+ public let items: Int?
25
+ /// When a read last worked (ISO 8601).
26
+ public let lastOkAt: String?
27
+ }
28
+
29
+ public func petStateFile(home: URL = lobstahHome()) -> URL {
30
+ home.appendingPathComponent("pet").appendingPathComponent("state.json")
31
+ }
32
+
33
+ /// Tracks reads in a row. It logs one line when failures reach the
34
+ /// threshold, one line when reads work again, and one line when the
35
+ /// working command changes. It writes the state file after every read.
36
+ public final class ReadMonitor {
37
+ public let threshold: Int
38
+ public private(set) var consecutiveFailures = 0
39
+ private var lastOkAt: Date?
40
+ private var lastCommand: String?
41
+ private let log: (String) -> Void
42
+ private let stateFile: URL?
43
+ private var writeFailed = false
44
+
45
+ public init(threshold: Int = 3, stateFile: URL? = petStateFile(), log: @escaping (String) -> Void = petLog) {
46
+ self.threshold = threshold
47
+ self.stateFile = stateFile
48
+ self.log = log
49
+ }
50
+
51
+ public func record(_ read: AttentionRead, now: Date = Date()) {
52
+ if let items = read.items {
53
+ if consecutiveFailures >= threshold {
54
+ log("attention read works again after \(consecutiveFailures) failures")
55
+ }
56
+ if read.command != lastCommand, let command = read.command {
57
+ log("reading attention with `lobstah \(command)`")
58
+ lastCommand = command
59
+ }
60
+ consecutiveFailures = 0
61
+ lastOkAt = now
62
+ write(PetState(pid: getpid(), at: iso(now), ok: true, command: read.command, reason: nil,
63
+ consecutiveFailures: 0, items: items.count, lastOkAt: iso(now)))
64
+ } else {
65
+ consecutiveFailures += 1
66
+ let reason = read.failure ?? "unknown"
67
+ if consecutiveFailures == threshold {
68
+ log("attention read failed \(consecutiveFailures) times in a row: \(reason)")
69
+ }
70
+ write(PetState(pid: getpid(), at: iso(now), ok: false, command: nil, reason: reason,
71
+ consecutiveFailures: consecutiveFailures, items: nil, lastOkAt: lastOkAt.map(iso)))
72
+ }
73
+ }
74
+
75
+ private func iso(_ date: Date) -> String {
76
+ let f = ISO8601DateFormatter()
77
+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
78
+ return f.string(from: date)
79
+ }
80
+
81
+ private func write(_ state: PetState) {
82
+ guard let stateFile else { return }
83
+ do {
84
+ try FileManager.default.createDirectory(at: stateFile.deletingLastPathComponent(), withIntermediateDirectories: true)
85
+ let encoder = JSONEncoder()
86
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
87
+ try encoder.encode(state).write(to: stateFile, options: .atomic)
88
+ writeFailed = false
89
+ } catch {
90
+ if !writeFailed { log("cannot write \(stateFile.path): \(error.localizedDescription)") }
91
+ writeFailed = true
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,157 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ final class ClickRoutingTests: XCTestCase {
6
+ func testWharfReportsAndDecisionsUseTheirOwnGlassUnderEveryRoute() {
7
+ let local = URL(string: "http://127.0.0.1:63169")!
8
+ for kind in ["report", "decision"] {
9
+ for route in ["tab", "app", "helm"] {
10
+ for delivered in [true, false] {
11
+ let url = URL(string: "https://glass.example/#\(kind)/remote")!
12
+ var item = AttentionItem(id: "remote", verb: kind, note: nil, key: "\(kind):remote", kind: kind, grounds: "away", glass: url.absoluteString)
13
+ item.petOpen = route
14
+ var actions: [String] = []
15
+ clickAttentionItem(item, glass: local, helmLive: true,
16
+ open: { XCTAssertEqual($0, url); actions.append("tab") },
17
+ focusHelm: { XCTAssertEqual($0, url); actions.append("helm") },
18
+ showGlass: { _, _ in XCTFail("hosted clicks never move a local page") },
19
+ showApp: { target, otherwise in
20
+ XCTAssertEqual(target, GlassTarget(hash: "#\(kind)/remote", url: url))
21
+ XCTAssertFalse(usesLocalGlassShow(target, local: local))
22
+ actions.append("app")
23
+ if !delivered { otherwise() }
24
+ }, acknowledge: { _ in actions.append("ack") })
25
+ let expected = route == "app" ? (delivered ? ["app", "ack"] : ["app", "tab", "ack"]) : [route, "ack"]
26
+ XCTAssertEqual(actions, expected)
27
+ }
28
+ }
29
+ }
30
+ }
31
+
32
+ func testInstalledAppMatchesHostedOriginAndLocalShowStaysLocal() {
33
+ let hosted = URL(string: "https://glass.example/#report/r")!
34
+ var info: [String: Any] = ["CrBundleIdentifier": "com.google.Chrome", "CFBundleIdentifier": "com.google.Chrome.app.abc", "CrAppModeShortcutURL": "https://glass.example/"]
35
+ XCTAssertTrue(isInstalledChromeGlass(info, glass: hosted))
36
+ for other in ["https://other.example/", "http://glass.example/", "https://glass.example:8443/", "http://127.0.0.1:63169/", "https://user@glass.example/", "https://glass.example/?redirect=elsewhere"] {
37
+ info["CrAppModeShortcutURL"] = other
38
+ XCTAssertFalse(isInstalledChromeGlass(info, glass: hosted))
39
+ }
40
+ let local = URL(string: "http://127.0.0.1:63169")!
41
+ XCTAssertTrue(usesLocalGlassShow(GlassTarget(hash: "#report/r", url: local.appendingPathComponent("report/r")), local: local))
42
+ XCTAssertFalse(usesLocalGlassShow(GlassTarget(hash: "#report/r", url: hosted), local: local))
43
+ }
44
+
45
+ func testAppAttemptSuccessAndFallback() {
46
+ let glass = URL(string: "http://127.0.0.1:63169")!
47
+ for kind in ["report", "decision"] {
48
+ for succeeds in [true, false] {
49
+ var item = AttentionItem(id: "a", verb: kind, note: nil, key: "\(kind):a", kind: kind)
50
+ item.petOpen = "app"
51
+ var actions: [String] = []
52
+ clickAttentionItem(item, glass: glass,
53
+ open: { _ in actions.append("tab") }, focusHelm: { _ in XCTFail("app never focuses helm") },
54
+ showApp: { target, otherwise in
55
+ XCTAssertEqual(target, item.glassTarget(glass: glass))
56
+ actions.append("app")
57
+ if !succeeds { otherwise() }
58
+ }, acknowledge: { _ in actions.append("ack") })
59
+ XCTAssertEqual(actions, succeeds ? ["app", "ack"] : ["app", "tab", "ack"])
60
+ }
61
+ }
62
+ }
63
+
64
+ func testInstalledChromeGlassUsesMetadataAndExactOrigin() {
65
+ let glass = URL(string: "http://127.0.0.1:63169")!
66
+ var info: [String: Any] = ["CrBundleIdentifier": "com.google.Chrome", "CFBundleIdentifier": "com.google.Chrome.app.abc", "CrAppModeShortcutURL": "http://127.0.0.1:63169/"]
67
+ XCTAssertTrue(isInstalledChromeGlass(info, glass: glass))
68
+ for bad in ["http://127.0.0.1:4949/", "http://localhost:63169/", "https://127.0.0.1:63169/", "http://127.0.0.1:63169/elsewhere", "http://user@127.0.0.1:63169/"] {
69
+ info["CrAppModeShortcutURL"] = bad
70
+ XCTAssertFalse(isInstalledChromeGlass(info, glass: glass))
71
+ }
72
+ info["CrAppModeShortcutURL"] = glass.absoluteString
73
+ info["CrBundleIdentifier"] = "com.apple.Safari"
74
+ XCTAssertFalse(isInstalledChromeGlass(info, glass: glass))
75
+ XCTAssertEqual(glassShowArguments("#prs", port: 63169, installedOnly: true), ["glass", "show", "#prs", "--port", "63169", "--json", "--app"])
76
+ }
77
+
78
+ func testReviewDestinationIsSeparateFromCanonicalPRIdentity() throws {
79
+ let data = Data(#"{"attention":[{"id":"a","verb":"pr:ready","kind":"pr:ready","prUrl":"https://github.com/acme/web/pull/42","reviewUrl":"https://linear.review/acme/web/pull/42","petOpen":"helm"}]}"#.utf8)
80
+ let item = try XCTUnwrap(JSONDecoder().decode(AttentionReport.self, from: data).attention.first)
81
+ XCTAssertEqual(item.prLink?.absoluteString, "https://linear.review/acme/web/pull/42")
82
+ XCTAssertEqual(item.prUrl, "https://github.com/acme/web/pull/42")
83
+ }
84
+ func testLinearDesktopReviewOpensDirectlyForEveryReportDecisionRoute() throws {
85
+ for route in ["tab", "app", "helm"] {
86
+ let data = Data("{\"attention\":[{\"id\":\"a\",\"verb\":\"pr:ready\",\"kind\":\"pr:ready\",\"prUrl\":\"https://github.com/acme/web/pull/42\",\"reviewUrl\":\"linear://review/acme/web/pull/42\",\"petOpen\":\"\(route)\"}]}".utf8)
87
+ let item = try XCTUnwrap(JSONDecoder().decode(AttentionReport.self, from: data).attention.first)
88
+ var hostedItem = item
89
+ hostedItem.grounds = "away"
90
+ hostedItem.glass = "https://glass.example/#job/remote"
91
+ var opened: URL?
92
+ clickAttentionItem(hostedItem, glass: URL(string: "http://127.0.0.1:63169")!,
93
+ open: { opened = $0 }, focusHelm: { _ in XCTFail("PRs never focus helm") },
94
+ showApp: { _, _ in XCTFail("PRs never open the glass app") }, acknowledge: { _ in })
95
+ XCTAssertEqual(opened?.absoluteString, "linear://review/acme/web/pull/42")
96
+ XCTAssertEqual(item.prUrl, "https://github.com/acme/web/pull/42")
97
+ }
98
+ }
99
+ func testStackPetShowsItsHeadlineAndOpensTheLinearApp() throws {
100
+ let data = Data(#"{"attention":[{"id":"a","verb":"stack-ready","kind":"stack-ready","note":"stack ready to merge: Heavy-check queue (#326 → #329, 4 PRs, all green)","headline":"Heavy-check queue (4 PRs, all green)","prUrl":"https://github.com/base-research-ai/homebase/pull/329","reviewUrl":"linear://review/base-research-ai/homebase/pull/329"}]}"#.utf8)
101
+ let item = try XCTUnwrap(JSONDecoder().decode(AttentionReport.self, from: data).attention.first)
102
+ XCTAssertEqual(item.bubbleText, "stack ready · Heavy-check queue (4 PRs, all green)")
103
+ XCTAssertEqual(item.prLink?.absoluteString, "linear://review/base-research-ai/homebase/pull/329")
104
+ var opened: URL?
105
+ clickAttentionItem(item, glass: URL(string: "http://127.0.0.1:63169")!,
106
+ open: { opened = $0 }, focusHelm: { _ in XCTFail("PRs never focus helm") },
107
+ showApp: { _, _ in XCTFail("PRs never open the glass app") }, acknowledge: { _ in })
108
+ XCTAssertEqual(opened?.absoluteString, "linear://review/base-research-ai/homebase/pull/329")
109
+ }
110
+ func testPrPetWithNoReviewToolOpensGitHub() throws {
111
+ let data = Data(##"{"attention":[{"id":"a","verb":"pr:ready","kind":"pr:ready","note":"#7 Put job photos first · ready to merge","prUrl":"https://github.com/acme/web/pull/7","reviewUrl":"https://github.com/acme/web/pull/7"}]}"##.utf8)
112
+ let item = try XCTUnwrap(JSONDecoder().decode(AttentionReport.self, from: data).attention.first)
113
+ XCTAssertEqual(item.bubbleText, "ready · #7 Put job photos first · ready to merge")
114
+ XCTAssertEqual(item.prLink?.absoluteString, "https://github.com/acme/web/pull/7")
115
+ }
116
+ func testAPetStandingForMoreKeepsItsTargetAndHeadline() throws {
117
+ let data = Data(#"{"attention":[{"id":"a","verb":"stack-ready","kind":"stack-ready","note":"the long line","headline":"Heavy-check queue (4 PRs, all green)","prUrl":"https://github.com/acme/web/pull/9","reviewUrl":"linear://review/acme/web/pull/9"}]}"#.utf8)
118
+ let item = try XCTUnwrap(JSONDecoder().decode(AttentionReport.self, from: data).attention.first)
119
+ let standing = item.standingFor(extra: 2)
120
+ XCTAssertEqual(standing.bubbleText, "stack ready · Heavy-check queue (4 PRs, all green) (+2 more)")
121
+ XCTAssertEqual(standing.prLink?.absoluteString, "linear://review/acme/web/pull/9")
122
+ }
123
+ func testALongBubbleIsCutToFit() {
124
+ var item = AttentionItem(id: "a", verb: "pr:ready", note: String(repeating: "x", count: 200), kind: "pr:ready")
125
+ XCTAssertEqual(item.bubbleLine.count, 80)
126
+ XCTAssertTrue(item.bubbleLine.hasSuffix("…"))
127
+ item.headline = "short"
128
+ XCTAssertEqual(item.bubbleLine, "ready · short")
129
+ }
130
+ func testConfiguredRoutesForReportsAndDecisions() {
131
+ let glass = URL(string: "http://127.0.0.1:63169")!
132
+ for kind in ["report", "decision"] {
133
+ for route in ["tab", "app", "helm"] {
134
+ var item = AttentionItem(id: "a", verb: kind, note: nil, key: "\(kind):a", kind: kind)
135
+ item.petOpen = route
136
+ var actions: [String] = []
137
+ clickAttentionItem(item, glass: glass, helmLive: true,
138
+ open: { actions.append("open:\($0.absoluteString)") },
139
+ focusHelm: { actions.append("helm:\($0.absoluteString)") },
140
+ showGlass: { _, _ in XCTFail("configured clicks never select a browser tab") },
141
+ acknowledge: { _ in actions.append("ack") })
142
+ XCTAssertEqual(actions, ["\(route == "helm" ? "helm" : "open"):\(item.glassTarget(glass: glass)!.url.absoluteString)", "ack"])
143
+ }
144
+ }
145
+ }
146
+
147
+ func testPRIgnoresReportDecisionRouting() {
148
+ for route in ["tab", "app", "helm"] {
149
+ var item = AttentionItem(id: "a", verb: "pr:ready", note: nil, kind: "pr:ready", prUrl: "https://github.com/a/b/pull/1")
150
+ item.petOpen = route
151
+ var opened: URL?
152
+ clickAttentionItem(item, glass: URL(string: "http://127.0.0.1:63169")!,
153
+ open: { opened = $0 }, focusHelm: { _ in XCTFail("PRs never route to helm") }, acknowledge: { _ in })
154
+ XCTAssertEqual(opened?.absoluteString, item.prUrl)
155
+ }
156
+ }
157
+ }
@@ -0,0 +1,46 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ final class ClickedItemsTests: XCTestCase {
6
+ private func ready(_ hash: String?) -> AttentionItem {
7
+ AttentionItem(id: "p", verb: "pr:ready", note: "#9 ready to merge", key: "pr:acme/web#9", kind: "pr:ready",
8
+ prUrl: "https://github.com/acme/web/pull/9", stateHash: hash)
9
+ }
10
+ private let report = AttentionItem(id: "r", verb: "report", note: "findings", key: "report:work:r", kind: "report", stateHash: "r1")
11
+
12
+ func testTheReadDecodesStateHash() throws {
13
+ let json = #"{"attention":[{"id":"p","verb":"pr:ready","key":"pr:acme/web#9","kind":"pr:ready","stateHash":"h1"}]}"#
14
+ let item = try XCTUnwrap(try JSONDecoder().decode(AttentionReport.self, from: Data(json.utf8)).attention.first)
15
+ XCTAssertEqual(item.stateHash, "h1")
16
+ }
17
+
18
+ /// The ack timed out, so every read still lists the item unacked: the click alone keeps it hidden.
19
+ func testAClickedItemStaysHiddenWhileItsStateIsUnchanged() {
20
+ var clicked = ClickedItems()
21
+ clicked.hide(ready("h1"))
22
+ XCTAssertEqual(clicked.walking([ready("h1"), report]), [report])
23
+ XCTAssertEqual(clicked.walking([ready("h1"), report]), [report])
24
+ }
25
+
26
+ func testANewStateHashWalksAgain() {
27
+ var clicked = ClickedItems()
28
+ clicked.hide(ready("h1"))
29
+ XCTAssertEqual(clicked.walking([ready("h2")]), [ready("h2")])
30
+ // The hide is forgotten: the old hash coming back does not hide it again.
31
+ XCTAssertEqual(clicked.walking([ready("h1")]), [ready("h1")])
32
+ }
33
+
34
+ func testOnceTheAckLandsTheHideIsForgotten() {
35
+ var clicked = ClickedItems()
36
+ clicked.hide(ready("h1"))
37
+ XCTAssertEqual(clicked.walking([]), []) // the read drops the acked item
38
+ XCTAssertEqual(clicked.walking([ready("h1")]), [ready("h1")]) // `attention unack` walks it again
39
+ }
40
+
41
+ func testAnItemWithoutAStateHashWaitsForTheCliAck() {
42
+ var clicked = ClickedItems()
43
+ clicked.hide(ready(nil))
44
+ XCTAssertEqual(clicked.walking([ready(nil)]), [ready(nil)])
45
+ }
46
+ }
@@ -0,0 +1,35 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ final class DecisionItemTests: XCTestCase {
6
+ private let glass = URL(string: "http://127.0.0.1:4949")!
7
+
8
+ func testADecisionShowsItsTitleOnly() throws {
9
+ let json = #"{"attention":[{"id":"abc","verb":"decision","note":"Cut 0.6.0?","key":"decision:0a1b2c3d","kind":"decision","stateHash":"h"}]}"#
10
+ let report = try JSONDecoder().decode(AttentionReport.self, from: Data(json.utf8))
11
+ let item = try XCTUnwrap(report.attention.first)
12
+ XCTAssertNil(item.kindLabel)
13
+ XCTAssertEqual(item.bubbleText, "Cut 0.6.0?")
14
+ }
15
+
16
+ func testADecisionLinksToItsCardInTheSpyglass() {
17
+ let item = AttentionItem(id: "abc", verb: "decision", note: "Cut 0.6.0?", key: "decision:0a1b2c3d", kind: "decision")
18
+ XCTAssertEqual(item.decisionLink(glass: glass)?.absoluteString, "http://127.0.0.1:4949/#decision/decision%3A0a1b2c3d")
19
+ let question = AttentionItem(id: "abc", verb: "needs-decision", note: nil, key: "work:abc", kind: "question")
20
+ XCTAssertNil(question.decisionLink(glass: glass))
21
+ }
22
+
23
+ func testADecisionClickOpensTheCardThenAcknowledges() {
24
+ let item = AttentionItem(id: "abc", verb: "decision", note: "Cut 0.6.0?", key: "decision:0a1b2c3d", kind: "decision")
25
+ var actions: [String] = []
26
+ clickAttentionItem(item, glass: glass,
27
+ open: { actions.append($0.absoluteString) },
28
+ focusHelm: { _ in XCTFail("a decision opens its glass card") },
29
+ acknowledge: { actions.append($0.joined(separator: " ")) })
30
+ XCTAssertEqual(actions, [
31
+ "http://127.0.0.1:4949/#decision/decision%3A0a1b2c3d",
32
+ "attention ack decision:0a1b2c3d --by pet",
33
+ ])
34
+ }
35
+ }
@@ -0,0 +1,76 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ /// An item of a grounds on a wharf opens the wharf's hosted glass; every
6
+ /// other item opens the local glass. The item says which, not a setting.
7
+ final class GlassAddressTests: XCTestCase {
8
+ private let local = URL(string: "http://127.0.0.1:4949")!
9
+ private let hostedJob = "https://glass.example/#job/remote-job"
10
+
11
+ /// What a click did, in order.
12
+ private func click(_ item: AttentionItem, helmLive: Bool = false) -> [String] {
13
+ var actions: [String] = []
14
+ clickAttentionItem(item, glass: local, helmLive: helmLive,
15
+ open: { actions.append("open \($0.absoluteString)") },
16
+ focusHelm: { actions.append("helm, else \($0.absoluteString)") },
17
+ showGlass: { target, _ in actions.append("show \(target.hash)") },
18
+ acknowledge: { actions.append($0.joined(separator: " ")) })
19
+ return actions
20
+ }
21
+
22
+ func testTheAttentionReadCarriesAWharfItemsGroundsAndGlass() throws {
23
+ let json = #"{"attention":[{"id":"srv-1","verb":"needs-decision","note":"[away@cloud] which?","key":"work:srv-1","kind":"question","stateHash":"h","grounds":"away","wharf":"cloud","glass":"https://glass.example/#job/remote-job"},{"id":"abc","verb":"blocked","note":"stuck","key":"work:abc","kind":"question","stateHash":"h"}]}"#
24
+ let items = try JSONDecoder().decode(AttentionReport.self, from: Data(json.utf8)).attention
25
+ XCTAssertEqual(items[0].grounds, "away")
26
+ XCTAssertEqual(items[0].glassAddress(local: local), GlassAddress(url: URL(string: hostedJob)!, hosted: true))
27
+ XCTAssertNil(items[1].grounds)
28
+ XCTAssertEqual(items[1].glassAddress(local: local), GlassAddress(url: local, hosted: false))
29
+ }
30
+
31
+ func testAWharfQuestionOpensItsHostedGlassAndALocalOneGoesToTheHelm() {
32
+ // This boat holds no helm registration for a wharf grounds: a live local helm is another grounds'.
33
+ let hosted = AttentionItem(id: "srv-1", verb: "needs-decision", note: "which?", key: "work:srv-1", kind: "question", grounds: "away", glass: hostedJob)
34
+ XCTAssertEqual(click(hosted), ["open \(hostedJob)", "attention ack work:srv-1 --by pet"])
35
+ XCTAssertEqual(click(hosted, helmLive: true), ["open \(hostedJob)", "attention ack work:srv-1 --by pet"])
36
+ let home = AttentionItem(id: "abc", verb: "needs-decision", note: "which?", key: "work:abc", kind: "question")
37
+ XCTAssertEqual(click(home), ["helm, else http://127.0.0.1:4949", "attention ack work:abc --by pet"])
38
+ }
39
+
40
+ func testAWharfItemWithoutAGlassYetKeepsTodaysClick() {
41
+ // The wharf has not named its glass (an older wharf, or no answer yet).
42
+ let item = AttentionItem(id: "srv-1", verb: "done", note: "landed", key: "work:srv-1", kind: "landed", grounds: "away")
43
+ XCTAssertEqual(item.glassAddress(local: local), GlassAddress(url: local, hosted: false))
44
+ XCTAssertEqual(click(item), ["helm, else http://127.0.0.1:4949", "attention ack work:srv-1 --by pet"])
45
+ }
46
+
47
+ func testAHostedReportOrDecisionOpensItsLinkAndNeverMovesALocalGlassPage() {
48
+ let report = AttentionItem(id: "r", verb: "report", note: "Findings", key: "report:r1", kind: "report", grounds: "away", glass: "https://glass.example/#report/r1")
49
+ XCTAssertEqual(click(report), ["open https://glass.example/#report/r1", "attention ack report:r1 --by pet"])
50
+ let decision = AttentionItem(id: "d", verb: "decision", note: "Cut it?", key: "decision:d1", kind: "decision", grounds: "away", glass: "https://glass.example/#decision/d1")
51
+ XCTAssertEqual(click(decision), ["open https://glass.example/#decision/d1", "attention ack decision:d1 --by pet"])
52
+ XCTAssertEqual(click(decision, helmLive: true), ["open https://glass.example/#decision/d1", "attention ack decision:d1 --by pet"])
53
+ // The local ones still ask an open local page first.
54
+ let home = AttentionItem(id: "d", verb: "decision", note: "Cut it?", key: "decision:d1", kind: "decision")
55
+ XCTAssertEqual(click(home), ["show #decision/decision%3Ad1", "attention ack decision:d1 --by pet"])
56
+ }
57
+
58
+ func testOnlyAnHTTPSOrLoopbackLinkCountsAsAHostedGlass() {
59
+ func address(_ glass: String) -> GlassAddress {
60
+ AttentionItem(id: "x", verb: "done", note: nil, key: "work:x", kind: "landed", glass: glass).glassAddress(local: local)
61
+ }
62
+ XCTAssertTrue(address("https://glass.example/#job/a").hosted)
63
+ XCTAssertTrue(address("http://127.0.0.1:8788/#job/a").hosted)
64
+ XCTAssertTrue(address("http://localhost:8788/#job/a").hosted)
65
+ for refused in ["http://glass.example/#job/a", "file:///etc/passwd", "javascript:alert(1)", "claude://claude.ai/x",
66
+ "https://user:secret@glass.example/#job/a", "not a url", ""] {
67
+ XCTAssertEqual(address(refused), GlassAddress(url: local, hosted: false), refused)
68
+ }
69
+ }
70
+
71
+ func testAPullRequestOnAWharfGroundsStillOpensThePullRequest() {
72
+ let pr = AttentionItem(id: "p", verb: "pr", note: nil, key: "pr:o/r#1", kind: "pr:ready", prUrl: "https://github.com/o/r/pull/1", grounds: "away", glass: hostedJob)
73
+ XCTAssertNil(pr.glassTarget(glass: local))
74
+ XCTAssertEqual(click(pr), ["open https://github.com/o/r/pull/1", "attention ack pr:o/r#1 --by pet"])
75
+ }
76
+ }
@@ -0,0 +1,158 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ /// A report or decision click shows the item in a glass that is already open
6
+ /// and brings that page's app forward; only with no open page does it open a
7
+ /// new tab (the old click).
8
+ final class GlassShowTests: XCTestCase {
9
+ private let glass = URL(string: "http://127.0.0.1:4949")!
10
+ private let decision = AttentionItem(id: "abc", verb: "decision", note: "Cut 0.6.0?", key: "decision:0a1b2c3d", kind: "decision")
11
+ private let report = AttentionItem(id: "r", verb: "report", note: "Tray findings", key: "fleet/r1", kind: "report")
12
+ private let desktopHelm = HelmRegistration(sessionId: "s", harness: "claude", heartbeatAt: "2026-10-01T16:00:00.000Z",
13
+ window: HelmWindow(bundleId: "com.anthropic.claudefordesktop"),
14
+ link: "claude://claude.ai/code/session_01abc")
15
+
16
+ /// Everything a click did, in order.
17
+ private final class Recorder {
18
+ var shown: [String] = []
19
+ var activated: [[String]] = []
20
+ var opened: [String] = []
21
+ var fellBack = 0
22
+ /// The apps that are running, for `activate`.
23
+ var running: Set<String> = []
24
+ }
25
+
26
+ private func click(_ item: AttentionItem, answer: GlassShowResult?, helm: HelmRegistration? = nil,
27
+ defaultBrowser: String? = "com.google.Chrome", running: Set<String>) -> (Recorder, GlassClickOutcome?, [String]) {
28
+ let r = Recorder()
29
+ r.running = running
30
+ var outcome: GlassClickOutcome?
31
+ var newTabs: [String] = []
32
+ clickAttentionItem(item, glass: glass,
33
+ open: { newTabs.append($0.absoluteString) },
34
+ focusHelm: { _ in XCTFail("no live helm in these clicks") },
35
+ showGlass: { target, otherwise in
36
+ outcome = showInGlass(target, helm: helm, defaultBrowser: defaultBrowser,
37
+ show: { r.shown.append($0); return answer },
38
+ activate: { bundles in
39
+ r.activated.append(bundles)
40
+ return bundles.first { r.running.contains($0) }
41
+ },
42
+ open: { r.opened.append($0.absoluteString) },
43
+ otherwise: { r.fellBack += 1; otherwise() })
44
+ },
45
+ acknowledge: { _ in })
46
+ return (r, outcome, newTabs)
47
+ }
48
+
49
+ func testTargetsCarryTheHashAnOpenPageReadsAndTheURLANewTabOpens() {
50
+ XCTAssertEqual(decision.glassTarget(glass: glass),
51
+ GlassTarget(hash: "#decision/decision%3A0a1b2c3d", url: URL(string: "http://127.0.0.1:4949/#decision/decision%3A0a1b2c3d")!))
52
+ XCTAssertEqual(report.glassTarget(glass: glass),
53
+ GlassTarget(hash: "#report/fleet%2Fr1", url: URL(string: "http://127.0.0.1:4949/report/fleet%2Fr1")!))
54
+ let pr = AttentionItem(id: "p", verb: "pr", note: nil, key: "pr:o/r#1", kind: "pr:draft", prUrl: "https://github.com/o/r/pull/1")
55
+ XCTAssertNil(pr.glassTarget(glass: glass))
56
+ }
57
+
58
+ func testARecentDesktopPageRaisesClaudeAndOpensTheHelmSessionWithNoNewTab() {
59
+ let (r, outcome, newTabs) = click(decision, answer: GlassShowResult(delivered: true, host: "claude", visible: false, seenAgoMs: 20_000),
60
+ helm: desktopHelm, running: ["com.anthropic.claudefordesktop", "com.google.Chrome"])
61
+ XCTAssertEqual(r.shown, ["#decision/decision%3A0a1b2c3d"])
62
+ XCTAssertEqual(r.activated, [["com.anthropic.claudefordesktop"]])
63
+ XCTAssertEqual(r.opened, ["claude://claude.ai/code/session_01abc"])
64
+ XCTAssertEqual(outcome, .raised("com.anthropic.claudefordesktop"))
65
+ XCTAssertEqual(newTabs, [])
66
+ XCTAssertEqual(r.fellBack, 0)
67
+ }
68
+
69
+ func testADesktopPageWithNoHelmLinkOnlyRaisesClaude() {
70
+ let (r, outcome, newTabs) = click(report, answer: GlassShowResult(delivered: true, host: "claude", visible: true, seenAgoMs: 1_000),
71
+ running: ["com.anthropic.claudefordesktop"])
72
+ XCTAssertEqual(r.shown, ["#report/fleet%2Fr1"])
73
+ XCTAssertEqual(r.activated, [["com.anthropic.claudefordesktop"]])
74
+ XCTAssertEqual(r.opened, [])
75
+ XCTAssertEqual(outcome, .raised("com.anthropic.claudefordesktop"))
76
+ XCTAssertEqual(newTabs, [])
77
+ }
78
+
79
+ func testARecentChromePageRaisesChromeOnlyAndNeverTheHelmLink() {
80
+ let (r, outcome, newTabs) = click(report, answer: GlassShowResult(delivered: true, host: "chrome", visible: true, seenAgoMs: 1_500),
81
+ helm: desktopHelm, defaultBrowser: "com.google.Chrome",
82
+ running: ["com.anthropic.claudefordesktop", "com.google.Chrome"])
83
+ XCTAssertEqual(r.activated.first?.first, "com.google.Chrome")
84
+ XCTAssertEqual(r.opened, [])
85
+ XCTAssertEqual(outcome, .raised("com.google.Chrome"))
86
+ XCTAssertEqual(newTabs, [])
87
+ }
88
+
89
+ func testNoRecentPageOpensANewTabAsBefore() {
90
+ let (r, outcome, newTabs) = click(report, answer: GlassShowResult(delivered: false),
91
+ helm: desktopHelm, running: ["com.anthropic.claudefordesktop", "com.google.Chrome"])
92
+ XCTAssertEqual(r.activated, [])
93
+ XCTAssertEqual(r.opened, [])
94
+ XCTAssertEqual(outcome, .fellBack)
95
+ XCTAssertEqual(newTabs, ["http://127.0.0.1:4949/report/fleet%2Fr1"])
96
+ }
97
+
98
+ func testNoGlassAnsweringOpensANewTabAsBefore() {
99
+ let (_, outcome, newTabs) = click(decision, answer: nil, running: [])
100
+ XCTAssertEqual(outcome, .fellBack)
101
+ XCTAssertEqual(newTabs, ["http://127.0.0.1:4949/#decision/decision%3A0a1b2c3d"])
102
+ }
103
+
104
+ func testAPageWhoseAppIsNotRunningFallsBackToANewTab() {
105
+ let (r, outcome, newTabs) = click(report, answer: GlassShowResult(delivered: true, host: "safari"), running: ["com.google.Chrome"])
106
+ XCTAssertEqual(r.activated, [["com.apple.Safari", "com.apple.SafariTechnologyPreview"]])
107
+ XCTAssertEqual(outcome, .fellBack)
108
+ XCTAssertEqual(newTabs, ["http://127.0.0.1:4949/report/fleet%2Fr1"])
109
+ }
110
+
111
+ func testADecisionWithNoOpenPageStillBringsUpALiveHelm() {
112
+ var helmFocused: [String] = []
113
+ clickAttentionItem(decision, glass: glass, helmLive: true,
114
+ open: { _ in XCTFail("a live helm frames the decision") },
115
+ focusHelm: { helmFocused.append($0.absoluteString) },
116
+ showGlass: { target, otherwise in
117
+ showInGlass(target, helm: nil, defaultBrowser: nil, show: { _ in GlassShowResult(delivered: false) },
118
+ activate: { _ in nil }, open: { _ in }, otherwise: otherwise)
119
+ },
120
+ acknowledge: { _ in })
121
+ XCTAssertEqual(helmFocused, ["http://127.0.0.1:4949/#decision/decision%3A0a1b2c3d"])
122
+ }
123
+
124
+ func testPRClicksNeverAskTheGlass() {
125
+ let pr = AttentionItem(id: "p", verb: "pr", note: nil, key: "pr:o/r#1", kind: "pr:draft", prUrl: "https://github.com/o/r/pull/1")
126
+ var opened: [String] = []
127
+ clickAttentionItem(pr, glass: glass,
128
+ open: { opened.append($0.absoluteString) },
129
+ focusHelm: { _ in XCTFail("a PR opens its URL") },
130
+ showGlass: { _, _ in XCTFail("a PR never asks the glass") },
131
+ acknowledge: { _ in })
132
+ XCTAssertEqual(opened, ["https://github.com/o/r/pull/1"])
133
+ }
134
+
135
+ func testRouteForEachHost() {
136
+ XCTAssertEqual(glassRoute(GlassShowResult(delivered: true, host: "chrome"), helm: nil, defaultBrowser: "company.thebrowser.Browser"),
137
+ .raise(bundleIds: ["company.thebrowser.Browser", "com.google.Chrome", "com.brave.Browser", "com.vivaldi.Vivaldi",
138
+ "com.operasoftware.Opera", "org.chromium.Chromium", "com.google.Chrome.canary"], sessionLink: nil))
139
+ XCTAssertEqual(glassRoute(GlassShowResult(delivered: true, host: "other"), helm: nil, defaultBrowser: "org.example.Browser"),
140
+ .raise(bundleIds: ["org.example.Browser"], sessionLink: nil))
141
+ // A link that is not a Claude desktop session link is never opened.
142
+ var helm = desktopHelm
143
+ helm.link = "https://example.com"
144
+ XCTAssertEqual(glassRoute(GlassShowResult(delivered: true, host: "claude"), helm: helm),
145
+ .raise(bundleIds: ["com.anthropic.claudefordesktop"], sessionLink: nil))
146
+ XCTAssertEqual(glassRoute(nil, helm: helm), .fallback)
147
+ }
148
+
149
+ func testTheCLICallAndItsAnswer() throws {
150
+ XCTAssertEqual(glassShowArguments("#report/x", port: 4949), ["glass", "show", "#report/x", "--port", "4949", "--json"])
151
+ let json = #"{"delivered":true,"id":"abc","page":"p1","host":"claude","visible":false,"seenAgoMs":20000,"userAgent":"ua"}"#
152
+ XCTAssertEqual(decodeGlassShow(.exited(status: 0, stdout: Data(json.utf8))),
153
+ GlassShowResult(delivered: true, host: "claude", visible: false, seenAgoMs: 20_000))
154
+ XCTAssertNil(decodeGlassShow(.exited(status: 1, stdout: Data())))
155
+ XCTAssertNil(decodeGlassShow(.exited(status: 0, stdout: Data("not json".utf8))))
156
+ XCTAssertNil(decodeGlassShow(.timedOut))
157
+ }
158
+ }