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,84 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ /// A decision click brings up the live helm's session; with no live helm it opens the glass card.
6
+ final class HelmRoutingTests: XCTestCase {
7
+ private let glass = URL(string: "http://127.0.0.1:4949")!
8
+ private let now = ISO8601DateFormatter().date(from: "2026-09-30T17:30:00Z")!
9
+ private let card = URL(string: "http://127.0.0.1:4949/#decision/decision%3A0a1b2c3d")!
10
+ private let decision = AttentionItem(id: "abc", verb: "decision", note: "Cut 0.6.1?", key: "decision:0a1b2c3d", kind: "decision")
11
+
12
+ private func helm(heartbeatAgo: TimeInterval = 60, window: HelmWindow?, cwd: String? = "/work/helm") -> HelmRegistration {
13
+ let iso = ISO8601DateFormatter()
14
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
15
+ return HelmRegistration(sessionId: "7e740e13-30ec-454f-8ada-486fcc43b82d", harness: "claude", cwd: cwd,
16
+ heartbeatAt: iso.string(from: now.addingTimeInterval(-heartbeatAgo)), window: window)
17
+ }
18
+
19
+ /// The click's actions, with the helm's ladder expanded into the steps it would try.
20
+ private func click(_ registration: HelmRegistration?) -> [String] {
21
+ var actions: [String] = []
22
+ clickAttentionItem(decision, glass: glass,
23
+ helmLive: helmIsLive(registration, now: now),
24
+ open: { actions.append("open \($0.absoluteString)") },
25
+ focusHelm: { fallback in
26
+ actions.append(contentsOf: helmFocusSteps(registration, glass: fallback, now: self.now).map { "\($0)" })
27
+ },
28
+ acknowledge: { actions.append($0.joined(separator: " ")) })
29
+ return actions
30
+ }
31
+
32
+ func testADesktopHelmBringsUpTheClaudeApp() {
33
+ let desktop = helm(window: HelmWindow(bundleId: "com.anthropic.claudefordesktop"))
34
+ XCTAssertEqual(helmFocusSteps(desktop, glass: card, now: now),
35
+ [.activateApp(bundleId: "com.anthropic.claudefordesktop"), .openGlass(card)])
36
+ XCTAssertEqual(click(desktop), [
37
+ "\(HelmFocusStep.activateApp(bundleId: "com.anthropic.claudefordesktop"))",
38
+ "\(HelmFocusStep.openGlass(card))",
39
+ "attention ack decision:0a1b2c3d --by pet",
40
+ ])
41
+ }
42
+
43
+ func testATerminalHelmKeepsTheTerminalLadder() {
44
+ let iterm = helm(window: HelmWindow(termProgram: "iTerm.app", itermSession: "w0t0p0:ABCD-1234"))
45
+ XCTAssertEqual(helmFocusSteps(iterm, glass: card, now: now), [.itermSession("ABCD-1234"), .openGlass(card)])
46
+ let terminal = helm(window: HelmWindow(bundleId: "com.apple.Terminal", termProgram: "Apple_Terminal", tty: "/dev/ttys004"))
47
+ XCTAssertEqual(helmFocusSteps(terminal, glass: card, now: now),
48
+ [.terminalTab("/dev/ttys004"), .activateApp(bundleId: "com.apple.Terminal"), .openGlass(card)])
49
+ XCTAssertEqual(click(terminal).first, "\(HelmFocusStep.terminalTab("/dev/ttys004"))")
50
+ let editor = helm(window: HelmWindow(bundleId: "com.microsoft.VSCode"))
51
+ XCTAssertEqual(helmFocusSteps(editor, glass: card, now: now), [.editor(bundleId: "com.microsoft.VSCode", cwd: "/work/helm")])
52
+ }
53
+
54
+ func testNoHelmOpensTheDecisionCard() {
55
+ XCTAssertEqual(click(nil), ["open \(card.absoluteString)", "attention ack decision:0a1b2c3d --by pet"])
56
+ XCTAssertEqual(helmFocusSteps(nil, glass: glass, now: now), [.openGlass(glass)])
57
+ }
58
+
59
+ func testAStaleHelmIsNotLiveSoADecisionOpensItsCard() {
60
+ let stale = helm(heartbeatAgo: helmLiveSeconds + 60, window: HelmWindow(bundleId: "com.anthropic.claudefordesktop"))
61
+ XCTAssertFalse(helmIsLive(stale, now: now))
62
+ XCTAssertEqual(click(stale), ["open \(card.absoluteString)", "attention ack decision:0a1b2c3d --by pet"])
63
+ // A question click on a stale helm still resumes it, as before.
64
+ XCTAssertEqual(helmFocusSteps(stale, glass: glass, now: now),
65
+ [.revive(cwd: "/work/helm", command: "claude --resume 7e740e13-30ec-454f-8ada-486fcc43b82d")])
66
+ }
67
+
68
+ func testAQuestionStillFocusesTheHelmWithThePlainGlassAsFallback() {
69
+ let question = AttentionItem(id: "abc", verb: "needs-decision", note: nil, key: "work:abc", kind: "question")
70
+ var fallback: URL?
71
+ clickAttentionItem(question, glass: glass, helmLive: true,
72
+ open: { _ in XCTFail("a question focuses the helm") },
73
+ focusHelm: { fallback = $0 },
74
+ acknowledge: { _ in })
75
+ XCTAssertEqual(fallback, glass)
76
+ }
77
+
78
+ func testTheHelmFileDecodes() throws {
79
+ let json = #"{"sessionId":"7e740e13","grounds":"fleet","repos":["lobstah"],"signedOnAt":"2026-09-28T16:34:04.649Z","heartbeatAt":"2026-09-30T17:24:54.681Z","harness":"claude","cwd":"/x","window":{"bundleId":"com.anthropic.claudefordesktop"}}"#
80
+ let decoded = try JSONDecoder().decode(HelmRegistration.self, from: Data(json.utf8))
81
+ XCTAssertEqual(decoded.window?.bundleId, "com.anthropic.claudefordesktop")
82
+ XCTAssertTrue(helmIsLive(decoded, now: ISO8601DateFormatter().date(from: "2026-09-30T17:30:00Z")!))
83
+ }
84
+ }
@@ -0,0 +1,91 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ final class ReportItemTests: XCTestCase {
6
+ private var previousHome: String?
7
+ private var testHome: URL!
8
+
9
+ override func setUpWithError() throws {
10
+ previousHome = ProcessInfo.processInfo.environment["LOBSTAH_HOME"]
11
+ testHome = FileManager.default.temporaryDirectory.appendingPathComponent("lobstah-report-click-\(UUID().uuidString)")
12
+ try FileManager.default.createDirectory(at: testHome, withIntermediateDirectories: true)
13
+ setenv("LOBSTAH_HOME", testHome.path, 1)
14
+ }
15
+
16
+ override func tearDownWithError() throws {
17
+ if let previousHome { setenv("LOBSTAH_HOME", previousHome, 1) } else { unsetenv("LOBSTAH_HOME") }
18
+ try FileManager.default.removeItem(at: testHome)
19
+ }
20
+
21
+ func testAReportItemLinksToItsModalInTheSpyglass() throws {
22
+ let json = #"{"attention":[{"id":"abc","verb":"report","note":"Tray findings","key":"report:work:abc","kind":"report"}]}"#
23
+ let report = try JSONDecoder().decode(AttentionReport.self, from: Data(json.utf8))
24
+ let item = try XCTUnwrap(report.attention.first)
25
+ XCTAssertEqual(item.bubbleText, "report · Tray findings")
26
+ XCTAssertNil(item.prLink)
27
+ let link = item.reportLink(glass: URL(string: "http://127.0.0.1:4949")!)
28
+ XCTAssertEqual(link?.absoluteString, "http://127.0.0.1:4949/report/report%3Awork%3Aabc")
29
+ }
30
+
31
+ func testOtherKindsHaveNoReportLink() {
32
+ let item = AttentionItem(id: "abc", verb: "done", note: nil, key: "work:abc", kind: "landed")
33
+ XCTAssertNil(item.reportLink(glass: URL(string: "http://127.0.0.1:4949")!))
34
+ }
35
+
36
+ func testReportClickOpensBeforeAcknowledgingThroughThePetCommand() {
37
+ let item = AttentionItem(id: "abc", verb: "report", note: nil, key: "report:work:abc", kind: "report")
38
+ var actions: [String] = []
39
+ var commands: [[String]] = []
40
+ let run: LobstahRunner = { args in
41
+ actions.append("ack")
42
+ commands.append(args)
43
+ return .exited(status: 0, stdout: Data())
44
+ }
45
+ clickAttentionItem(item, glass: URL(string: "http://127.0.0.1:4949")!,
46
+ open: { actions.append($0.absoluteString) },
47
+ focusHelm: { _ in XCTFail("a report opens its glass URL") },
48
+ acknowledge: { _ = ackOutcome(run($0)) })
49
+ XCTAssertEqual(actions, ["http://127.0.0.1:4949/report/report%3Awork%3Aabc", "ack"])
50
+ XCTAssertEqual(commands, [["attention", "ack", "report:work:abc", "--by", "pet"]])
51
+ }
52
+
53
+ func testFailedAcknowledgementDoesNotPreventOpeningTheReport() {
54
+ let item = AttentionItem(id: "abc", verb: "report", note: nil, key: "report:work:abc", kind: "report")
55
+ var opened = false
56
+ var failure: ReadFailure?
57
+ clickAttentionItem(item, glass: URL(string: "http://127.0.0.1:4949")!,
58
+ open: { _ in opened = true },
59
+ focusHelm: { _ in XCTFail("a report opens its glass URL") },
60
+ acknowledge: { _ in
61
+ XCTAssertTrue(opened)
62
+ if case let .failure(why) = ackOutcome(.exited(status: 1, stdout: Data())) { failure = why }
63
+ })
64
+ XCTAssertTrue(opened)
65
+ XCTAssertEqual(failure, .exit(1))
66
+ }
67
+
68
+ func testOtherPetClicksKeepTheirTargetsAndAcknowledge() {
69
+ let glass = URL(string: "http://127.0.0.1:4949")!
70
+ let pr = "https://github.com/example/repo/pull/1"
71
+ for kind in ["question", "landed", "watch", "pr:ready"] {
72
+ let item = AttentionItem(id: "abc", verb: "done", note: nil, key: "work:abc", kind: kind, prUrl: pr)
73
+ var actions: [String] = []
74
+ clickAttentionItem(item, glass: glass,
75
+ open: { actions.append($0.absoluteString) },
76
+ focusHelm: { _ in actions.append("helm") },
77
+ acknowledge: { actions.append($0.joined(separator: " ")) })
78
+ XCTAssertEqual(actions, [kind == "pr:ready" ? pr : "helm", "attention ack work:abc --by pet"], kind)
79
+ }
80
+ }
81
+
82
+ func testLegacyItemWithoutAKeyStillOpensWithoutAnAck() {
83
+ let item = AttentionItem(id: "abc", verb: "needs-decision", note: nil)
84
+ var focused = false
85
+ clickAttentionItem(item, glass: URL(string: "http://127.0.0.1:4949")!,
86
+ open: { _ in XCTFail("a legacy question focuses the helm") },
87
+ focusHelm: { _ in focused = true },
88
+ acknowledge: { _ in XCTFail("an item without a key cannot be acknowledged") })
89
+ XCTAssertTrue(focused)
90
+ }
91
+ }
@@ -0,0 +1,26 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ final class ReviewItemTests: XCTestCase {
6
+ private let glass = URL(string: "http://127.0.0.1:4949")!
7
+
8
+ private func review(_ n: Int) -> AttentionItem {
9
+ AttentionItem(id: "review:acme/web#\(n)", verb: "drafted", note: "acme/web#\(n) Add the thing", key: "review:acme/web#\(n)", kind: "review", prUrl: "https://github.com/acme/web/pull/\(n)", stateHash: "h")
10
+ }
11
+
12
+ func testDraftNotificationTextAndReviewInboxTarget() {
13
+ var item = review(7)
14
+ item.reviewUrl = "linear://review/acme/web/pull/7"
15
+ XCTAssertNil(item.prLink)
16
+ XCTAssertNil(item.kindLabel)
17
+ XCTAssertEqual(item.glassTarget(glass: glass)?.hash, "#review-review%3Aacme%2Fweb%237")
18
+ XCTAssertEqual(item.glassTarget(glass: glass)?.url.absoluteString, "http://127.0.0.1:4949/#review-review%3Aacme%2Fweb%237")
19
+ var commands: [[String]] = []
20
+ var opened: [URL] = []
21
+ clickAttentionItem(item, glass: glass, open: { opened.append($0) }, focusHelm: { _ in }, acknowledge: { commands.append($0) })
22
+ XCTAssertEqual(commands, [["reviews", "seen", "review:acme/web#7"]])
23
+ XCTAssertEqual(opened.first?.fragment, "review-review%3Aacme%2Fweb%237")
24
+ XCTAssertEqual(item.ackArguments, ["attention", "ack", "review:acme/web#7", "--by", "pet"])
25
+ }
26
+ }
@@ -0,0 +1,151 @@
1
+ import Foundation
2
+ import XCTest
3
+ @testable import LobstahPetCore
4
+
5
+ final class RunCommandTests: XCTestCase {
6
+ private let sh = "/bin/sh"
7
+
8
+ func testReturnsAllOfOutputLargerThanThePipe() {
9
+ // About 230 KB: more than three times what a pipe holds. Numbered
10
+ // lines also check that nothing is lost or out of order.
11
+ let expected = (1...40_000).map { "\($0)\n" }.joined()
12
+ XCTAssertGreaterThan(expected.utf8.count, 200 * 1024)
13
+ let out = runCommand(sh, ["-c", "seq 1 40000"], timeout: 10)
14
+ XCTAssertEqual(out?.count, expected.count)
15
+ XCTAssertTrue(out == expected)
16
+ }
17
+
18
+ func testTimeoutTerminatesTheChildAndReturnsNil() {
19
+ let started = Date()
20
+ let result = execute(sh, ["-c", "sleep 30"], timeout: 0.5)
21
+ XCTAssertEqual(result.outcome, .timedOut)
22
+ XCTAssertLessThan(Date().timeIntervalSince(started), 5)
23
+ XCTAssertGreaterThan(result.pid, 0)
24
+ // kill(pid, 0) fails with ESRCH once the child is gone and reaped.
25
+ XCTAssertEqual(kill(result.pid, 0), -1)
26
+ XCTAssertEqual(errno, ESRCH)
27
+ XCTAssertNil(runCommand(sh, ["-c", "sleep 30"], timeout: 0.5))
28
+ }
29
+
30
+ func testTimeoutKillsAChildThatIgnoresSigterm() {
31
+ let result = execute(sh, ["-c", "trap '' TERM; exec sleep 30"], timeout: 0.5)
32
+ XCTAssertEqual(result.outcome, .timedOut)
33
+ XCTAssertEqual(kill(result.pid, 0), -1)
34
+ }
35
+
36
+ func testLargeStandardErrorDoesNotBlockStandardOutput() {
37
+ let out = runCommand(sh, ["-c", "head -c 204800 /dev/zero >&2; printf ok"], timeout: 10)
38
+ XCTAssertEqual(out, "ok")
39
+ }
40
+
41
+ func testNonZeroExitReturnsNilAndItsStatus() {
42
+ XCTAssertNil(runCommand(sh, ["-c", "printf partial; exit 2"]))
43
+ XCTAssertEqual(execute(sh, ["-c", "printf partial; exit 2"]).outcome, .exited(status: 2, stdout: Data("partial".utf8)))
44
+ }
45
+
46
+ func testLaunchFailure() {
47
+ guard case .launchFailed = execute("/nonexistent/lobstah", []).outcome else {
48
+ return XCTFail("expected a launch failure")
49
+ }
50
+ }
51
+ }
52
+
53
+ final class ReadAttentionTests: XCTestCase {
54
+ private let narrow = #"{"attention":[{"id":"a","verb":"needs-decision","note":"which?","key":"work:a","kind":"question"},{"id":"b","verb":"done","note":null,"key":"pr:o/r#1","kind":"pr:ready","prUrl":"https://github.com/o/r/pull/1","acked":{"at":"2026-09-29T00:00:00Z","by":"pet"}}]}"#
55
+ private let tend = #"{"verdict":"needs-attention","stories":[],"attention":[{"id":"a","verb":"needs-decision","note":"which?","key":"work:a","kind":"question"}]}"#
56
+
57
+ func testNarrowCommandFirstAndAcknowledgedItemsSkipped() {
58
+ var calls: [[String]] = []
59
+ let read = readAttention { args in
60
+ calls.append(args)
61
+ return .exited(status: 0, stdout: Data(self.narrow.utf8))
62
+ }
63
+ XCTAssertEqual(calls, [["attention", "--json"]])
64
+ XCTAssertEqual(read.command, "attention --json")
65
+ XCTAssertEqual(read.items?.map(\.id), ["a"])
66
+ XCTAssertEqual(read.items?.first?.kind, "question")
67
+ }
68
+
69
+ func testGlassAndPetAcknowledgmentsBothStopWalking() {
70
+ for by in ["glass", "pet"] {
71
+ let payload = narrow.replacingOccurrences(of: "\"by\":\"pet\"", with: "\"by\":\"\(by)\"")
72
+ for fallback in [false, true] {
73
+ let read = readAttention { args in
74
+ if fallback && args == ["attention", "--json"] { return .exited(status: 2, stdout: Data()) }
75
+ return .exited(status: 0, stdout: Data(payload.utf8))
76
+ }
77
+ XCTAssertEqual(read.items?.map(\.id), ["a"], by)
78
+ }
79
+ }
80
+ }
81
+
82
+ func testOlderCliFallsBackToManTend() {
83
+ let read = readAttention { args in
84
+ args == ["attention", "--json"] ? .exited(status: 2, stdout: Data()) : .exited(status: 0, stdout: Data(self.tend.utf8))
85
+ }
86
+ XCTAssertEqual(read.command, "man tend --json")
87
+ XCTAssertEqual(read.items?.map(\.key), ["work:a"])
88
+ }
89
+
90
+ func testQuietStackChildrenDoNotWalkAndTheStackLinksToItsTop() {
91
+ let json = #"{"attention":[{"id":"child","verb":"pr:ready","kind":"pr:ready","quiet":true},{"id":"stack","verb":"stack-ready","kind":"stack-ready","prUrl":"https://github.com/acme/web/pull/3"}]}"#
92
+ let read = readAttention { _ in .exited(status: 0, stdout: Data(json.utf8)) }
93
+ XCTAssertEqual(read.items?.map(\.id), ["stack"])
94
+ XCTAssertEqual(read.items?.first?.prLink?.absoluteString, "https://github.com/acme/web/pull/3")
95
+ }
96
+
97
+ func testGroupedStackFeedWalksOnceAndFollowsTheChangedTop() {
98
+ for top in [3, 2] {
99
+ let json = """
100
+ {"attention":[{"id":"stack","key":"stack:pr:acme/web#1","verb":"stack-ready","kind":"stack-ready","prUrl":"https://github.com/acme/web/pull/\(top)","stack":{"ready":\(top),"total":\(top),"members":[{"number":1},{"number":2}]}}]}
101
+ """
102
+ let read = readAttention { _ in .exited(status: 0, stdout: Data(json.utf8)) }
103
+ XCTAssertEqual(read.items?.map(\.key), ["stack:pr:acme/web#1"])
104
+ XCTAssertEqual(read.items?.first?.prLink?.absoluteString, "https://github.com/acme/web/pull/\(top)")
105
+ }
106
+ }
107
+
108
+ func testEveryCommandFailingNamesEachReason() {
109
+ let read = readAttention { args in
110
+ args == ["attention", "--json"] ? .exited(status: 0, stdout: Data("not json".utf8)) : .timedOut
111
+ }
112
+ XCTAssertNil(read.items)
113
+ XCTAssertEqual(read.failure, "`lobstah attention --json` output does not decode (8 bytes); `lobstah man tend --json` timed out")
114
+ }
115
+ }
116
+
117
+ final class ReadMonitorTests: XCTestCase {
118
+ private var dir: URL!
119
+
120
+ override func setUpWithError() throws {
121
+ dir = FileManager.default.temporaryDirectory.appendingPathComponent("lobstah-pet-\(UUID().uuidString)")
122
+ }
123
+
124
+ override func tearDownWithError() throws {
125
+ try? FileManager.default.removeItem(at: dir)
126
+ }
127
+
128
+ func testLogsOnceAtTheThresholdAndOnceOnRecovery() throws {
129
+ var lines: [String] = []
130
+ let file = dir.appendingPathComponent("pet/state.json")
131
+ let monitor = ReadMonitor(threshold: 3, stateFile: file) { lines.append($0) }
132
+ let failed = AttentionRead(items: nil, command: nil, failure: "`lobstah man tend --json` timed out")
133
+ for _ in 0..<5 { monitor.record(failed) }
134
+ XCTAssertEqual(lines, ["attention read failed 3 times in a row: `lobstah man tend --json` timed out"])
135
+ var state = try JSONDecoder().decode(PetState.self, from: Data(contentsOf: file))
136
+ XCTAssertFalse(state.ok)
137
+ XCTAssertEqual(state.consecutiveFailures, 5)
138
+ XCTAssertEqual(state.reason, "`lobstah man tend --json` timed out")
139
+ XCTAssertEqual(state.pid, getpid())
140
+
141
+ monitor.record(AttentionRead(items: [], command: "attention --json", failure: nil))
142
+ XCTAssertEqual(lines.count, 3)
143
+ XCTAssertEqual(lines[1], "attention read works again after 5 failures")
144
+ XCTAssertEqual(lines[2], "reading attention with `lobstah attention --json`")
145
+ state = try JSONDecoder().decode(PetState.self, from: Data(contentsOf: file))
146
+ XCTAssertTrue(state.ok)
147
+ XCTAssertEqual(state.items, 0)
148
+ XCTAssertEqual(state.command, "attention --json")
149
+ XCTAssertNotNil(state.lastOkAt)
150
+ }
151
+ }