lobstah 0.8.5 → 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.
- package/dist/main.js +3338 -2103
- package/dist/runner.js +367 -330
- package/docs/configuration.md +1 -0
- package/docs/design.md +30 -16
- package/docs/man.md +7 -1
- package/package.json +2 -1
- package/pet/Package.swift +26 -0
- package/pet/Sources/LobstahPet/Resources/lob-sprite.png +0 -0
- package/pet/Sources/LobstahPet/Resources/star.png +0 -0
- package/pet/Sources/LobstahPet/main.swift +584 -0
- package/pet/Sources/LobstahPetCore/Attention.swift +321 -0
- package/pet/Sources/LobstahPetCore/Command.swift +105 -0
- package/pet/Sources/LobstahPetCore/GlassShow.swift +156 -0
- package/pet/Sources/LobstahPetCore/Helm.swift +104 -0
- package/pet/Sources/LobstahPetCore/ReadMonitor.swift +94 -0
- package/pet/Tests/LobstahPetCoreTests/ClickRoutingTests.swift +157 -0
- package/pet/Tests/LobstahPetCoreTests/ClickedItemsTests.swift +46 -0
- package/pet/Tests/LobstahPetCoreTests/DecisionItemTests.swift +35 -0
- package/pet/Tests/LobstahPetCoreTests/GlassAddressTests.swift +76 -0
- package/pet/Tests/LobstahPetCoreTests/GlassShowTests.swift +158 -0
- package/pet/Tests/LobstahPetCoreTests/HelmRoutingTests.swift +84 -0
- package/pet/Tests/LobstahPetCoreTests/ReportItemTests.swift +91 -0
- package/pet/Tests/LobstahPetCoreTests/ReviewItemTests.swift +26 -0
- package/pet/Tests/LobstahPetCoreTests/RunCommandTests.swift +151 -0
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
// The lobstah pet: attention questions crawl across the desktop.
|
|
2
|
+
//
|
|
3
|
+
// One small transparent always-on-top window per attention item (capped),
|
|
4
|
+
// each walking the pixel lobster with a star speech bubble. Clicking a
|
|
5
|
+
// question pet runs the focus ladder against the helm registration lobstah
|
|
6
|
+
// already keeps: exact iTerm pane -> Terminal tab by tty -> VS Code window
|
|
7
|
+
// by cwd -> app by bundle id -> resume-if-stale -> the spyglass. Clicking a
|
|
8
|
+
// report or decision pet first shows it in a glass page that is already open
|
|
9
|
+
// (the Claude desktop Browser pane or a browser tab) and brings that app
|
|
10
|
+
// forward. With no open page, a decision brings up a live helm the same way
|
|
11
|
+
// (the Claude desktop app for a desktop helm), else the decision's glass
|
|
12
|
+
// card, and a report opens its page in a new tab. Clicking a
|
|
13
|
+
// draft-PR pet opens the PR. The pet only ever reads lobstah state
|
|
14
|
+
// (`attention --json`, or `man tend --json` from an older lobstah, plus the
|
|
15
|
+
// helm files); it steers nothing. Its one write is ~/.lobstah/pet/state.json,
|
|
16
|
+
// the last read's result, for `lobstah doctor`.
|
|
17
|
+
|
|
18
|
+
import AppKit
|
|
19
|
+
import LobstahPetCore
|
|
20
|
+
|
|
21
|
+
// MARK: - lobstah state
|
|
22
|
+
|
|
23
|
+
// HelmRegistration and HelmWindow live in LobstahPetCore (Helm.swift).
|
|
24
|
+
|
|
25
|
+
/** The spyglass's port: $LOBSTAH_GLASS_PORT (shared with `lobstah glass`), else 4949. */
|
|
26
|
+
let glassPort: Int = ProcessInfo.processInfo.environment["LOBSTAH_GLASS_PORT"].flatMap { Int($0) } ?? 4949
|
|
27
|
+
let glassURL = URL(string: "http://127.0.0.1:\(glassPort)")!
|
|
28
|
+
|
|
29
|
+
// MARK: - showing an item in an open glass
|
|
30
|
+
|
|
31
|
+
/** The bundle id of the app that opens http URLs: the default browser. */
|
|
32
|
+
func defaultBrowserBundle() -> String? {
|
|
33
|
+
guard let app = NSWorkspace.shared.urlForApplication(toOpen: glassURL) else { return nil }
|
|
34
|
+
return Bundle(url: app)?.bundleIdentifier
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Bring the first running app of `bundles` forward; its bundle id, or nil when none runs. */
|
|
38
|
+
func activateFirstRunning(_ bundles: [String]) -> String? {
|
|
39
|
+
for bundle in bundles {
|
|
40
|
+
if let app = NSRunningApplication.runningApplications(withBundleIdentifier: bundle).first, app.activate() {
|
|
41
|
+
return bundle
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return nil
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Show `target` in a glass page that is already open (the Claude desktop
|
|
49
|
+
* app's Browser pane, or a browser tab) and bring that app forward; run
|
|
50
|
+
* `otherwise` (a new tab, as before) when no page was seen recently. The
|
|
51
|
+
* show runs `lobstah glass show` off the main thread; the rest runs on it.
|
|
52
|
+
*/
|
|
53
|
+
func showGlass(_ target: GlassTarget, otherwise: @escaping () -> Void) {
|
|
54
|
+
DispatchQueue.global().async {
|
|
55
|
+
let result = decodeGlassShow(execute("/usr/bin/env", ["lobstah"] + glassShowArguments(target.hash, port: glassPort), timeout: 4).outcome)
|
|
56
|
+
DispatchQueue.main.async {
|
|
57
|
+
showInGlass(target, helm: readHelm(), defaultBrowser: defaultBrowserBundle(),
|
|
58
|
+
show: { _ in result },
|
|
59
|
+
activate: activateFirstRunning,
|
|
60
|
+
open: { NSWorkspace.shared.open($0) },
|
|
61
|
+
otherwise: otherwise)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Raise an installed Chrome glass, then hand it the item. Never select tabs. */
|
|
67
|
+
func showInstalledGlass(_ target: GlassTarget, otherwise: @escaping () -> Void) {
|
|
68
|
+
let roots = [FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications/Chrome Apps.localized"),
|
|
69
|
+
FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications"),
|
|
70
|
+
URL(fileURLWithPath: "/Applications")]
|
|
71
|
+
DispatchQueue.global().async {
|
|
72
|
+
let apps = roots.flatMap { (try? FileManager.default.contentsOfDirectory(at: $0, includingPropertiesForKeys: nil)) ?? [] }
|
|
73
|
+
let candidate = apps.sorted { $0.path < $1.path }.first { app in
|
|
74
|
+
guard app.pathExtension == "app", let info = NSDictionary(contentsOf: app.appendingPathComponent("Contents/Info.plist")) as? [String: Any] else { return false }
|
|
75
|
+
return isInstalledChromeGlass(info, glass: target.url)
|
|
76
|
+
}
|
|
77
|
+
DispatchQueue.main.async {
|
|
78
|
+
guard let candidate else { otherwise(); return }
|
|
79
|
+
var finished = false
|
|
80
|
+
func finish(_ delivered: Bool) {
|
|
81
|
+
guard !finished else { return }
|
|
82
|
+
finished = true
|
|
83
|
+
if !delivered { otherwise() }
|
|
84
|
+
}
|
|
85
|
+
// Also bound a launch callback that never arrives. Main-thread owned.
|
|
86
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 8) { finish(false) }
|
|
87
|
+
let config = NSWorkspace.OpenConfiguration()
|
|
88
|
+
config.activates = true
|
|
89
|
+
if !usesLocalGlassShow(target, local: glassURL) {
|
|
90
|
+
// The hosted glass has no local presence endpoint. Deliver the URL to
|
|
91
|
+
// its installed app directly; never move an unrelated local glass.
|
|
92
|
+
NSWorkspace.shared.open([target.url], withApplicationAt: candidate, configuration: config) { app, error in
|
|
93
|
+
DispatchQueue.main.async {
|
|
94
|
+
guard !finished else { return }
|
|
95
|
+
guard error == nil, let app, app.activate() else { finish(false); return }
|
|
96
|
+
finish(NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
NSWorkspace.shared.openApplication(at: candidate, configuration: config) { app, error in
|
|
102
|
+
DispatchQueue.main.async {
|
|
103
|
+
guard !finished else { return }
|
|
104
|
+
guard error == nil, let app, app.activate() else { finish(false); return }
|
|
105
|
+
DispatchQueue.global().async {
|
|
106
|
+
let deadline = Date().addingTimeInterval(5)
|
|
107
|
+
var delivered = false
|
|
108
|
+
while Date() < deadline {
|
|
109
|
+
let result = decodeGlassShow(execute("/usr/bin/env", ["lobstah"] + glassShowArguments(target.hash, port: glassPort, installedOnly: true), timeout: 2).outcome)
|
|
110
|
+
if result?.delivered == true { delivered = true; break }
|
|
111
|
+
Thread.sleep(forTimeInterval: 0.25)
|
|
112
|
+
}
|
|
113
|
+
DispatchQueue.main.async { finish(delivered && NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier) }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The spyglass, from a menu: an open glass page comes forward as it is, else a new tab. */
|
|
122
|
+
func openSpyglass() {
|
|
123
|
+
showGlass(GlassTarget(hash: "", url: glassURL)) { NSWorkspace.shared.open(glassURL) }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Acknowledge through lobstah's own write path — the pet never writes
|
|
128
|
+
* ~/.lobstah itself. Off the main thread; a failure is logged, never shown
|
|
129
|
+
* as a blocker (the click still opened its target).
|
|
130
|
+
*/
|
|
131
|
+
func ackItem(_ item: AttentionItem) {
|
|
132
|
+
guard let args = item.ackArguments else { return }
|
|
133
|
+
ackAttention(args)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
func ackAttention(_ args: [String]) {
|
|
137
|
+
DispatchQueue.global().async {
|
|
138
|
+
if case let .failure(why) = ackOutcome(defaultRunner(args)) {
|
|
139
|
+
petLog("ack failed for \(args[2]): `lobstah attention ack` \(why)")
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
func readHelm() -> HelmRegistration? {
|
|
145
|
+
let dir = lobstahHome().appendingPathComponent("helm")
|
|
146
|
+
guard let files = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else { return nil }
|
|
147
|
+
for f in files where f.pathExtension == "json" {
|
|
148
|
+
if let data = try? Data(contentsOf: f),
|
|
149
|
+
let helm = try? JSONDecoder().decode(HelmRegistration.self, from: data) {
|
|
150
|
+
return helm
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return nil
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// MARK: - focus ladder
|
|
157
|
+
|
|
158
|
+
func osascript(_ source: String) -> Bool {
|
|
159
|
+
var error: NSDictionary?
|
|
160
|
+
let script = NSAppleScript(source: source)
|
|
161
|
+
script?.executeAndReturnError(&error)
|
|
162
|
+
return error == nil
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Bring up the helm's session: run the ladder from helmFocusSteps (Helm.swift)
|
|
167
|
+
* until a step works. `fallback` is the spyglass URL to open when none does.
|
|
168
|
+
*/
|
|
169
|
+
func focusHelm(fallback: URL = glassURL) {
|
|
170
|
+
for step in helmFocusSteps(readHelm(), glass: fallback) {
|
|
171
|
+
if runFocusStep(step) { return }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/// One ladder step; true when it brought something up.
|
|
176
|
+
func runFocusStep(_ step: HelmFocusStep) -> Bool {
|
|
177
|
+
switch step {
|
|
178
|
+
case .itermSession(let uuid):
|
|
179
|
+
return osascript("""
|
|
180
|
+
tell application "iTerm2"
|
|
181
|
+
repeat with w in windows
|
|
182
|
+
repeat with t in tabs of w
|
|
183
|
+
repeat with s in sessions of t
|
|
184
|
+
if id of s contains "\(uuid)" then
|
|
185
|
+
select t
|
|
186
|
+
select w
|
|
187
|
+
activate
|
|
188
|
+
return
|
|
189
|
+
end if
|
|
190
|
+
end repeat
|
|
191
|
+
end repeat
|
|
192
|
+
end repeat
|
|
193
|
+
end tell
|
|
194
|
+
""")
|
|
195
|
+
case .terminalTab(let tty):
|
|
196
|
+
return osascript("""
|
|
197
|
+
tell application "Terminal"
|
|
198
|
+
repeat with w in windows
|
|
199
|
+
repeat with t in tabs of w
|
|
200
|
+
if (tty of t as string) ends with "\(tty)" then
|
|
201
|
+
set selected of t to true
|
|
202
|
+
set frontmost of w to true
|
|
203
|
+
activate
|
|
204
|
+
return
|
|
205
|
+
end if
|
|
206
|
+
end repeat
|
|
207
|
+
end repeat
|
|
208
|
+
end tell
|
|
209
|
+
""")
|
|
210
|
+
case .editor(let bundle, let cwd):
|
|
211
|
+
// VS Code family: one window per folder, cwd is the window
|
|
212
|
+
let p = Process()
|
|
213
|
+
p.executableURL = URL(fileURLWithPath: "/usr/bin/open")
|
|
214
|
+
p.arguments = ["-b", bundle, cwd]
|
|
215
|
+
try? p.run()
|
|
216
|
+
return true
|
|
217
|
+
case .activateApp(let bundle):
|
|
218
|
+
// The Claude desktop app for a desktop helm, or any recorded app.
|
|
219
|
+
guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: bundle).first else { return false }
|
|
220
|
+
app.activate()
|
|
221
|
+
return true
|
|
222
|
+
case .revive(let cwd, let command):
|
|
223
|
+
// stale helm: revive it in a fresh Terminal window
|
|
224
|
+
_ = osascript("""
|
|
225
|
+
tell application "Terminal"
|
|
226
|
+
do script "cd \(cwd) && \(command)"
|
|
227
|
+
activate
|
|
228
|
+
end tell
|
|
229
|
+
""")
|
|
230
|
+
return true
|
|
231
|
+
case .openGlass(let url):
|
|
232
|
+
NSWorkspace.shared.open(url)
|
|
233
|
+
return true
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// MARK: - pet window
|
|
238
|
+
|
|
239
|
+
final class PetView: NSView {
|
|
240
|
+
weak var pet: Pet?
|
|
241
|
+
override func mouseDown(with event: NSEvent) {
|
|
242
|
+
guard let item = pet?.item else { focusHelm(); return }
|
|
243
|
+
if item.kind != "review" { delegate.hideClicked(item) }
|
|
244
|
+
clickAttentionItem(item, glass: glassURL,
|
|
245
|
+
helmLive: helmIsLive(readHelm()),
|
|
246
|
+
open: { NSWorkspace.shared.open($0) },
|
|
247
|
+
focusHelm: { focusHelm(fallback: $0) },
|
|
248
|
+
showGlass: showGlass,
|
|
249
|
+
showApp: showInstalledGlass,
|
|
250
|
+
acknowledge: ackAttention)
|
|
251
|
+
}
|
|
252
|
+
override func updateTrackingAreas() {
|
|
253
|
+
trackingAreas.forEach(removeTrackingArea)
|
|
254
|
+
addTrackingArea(NSTrackingArea(rect: bounds, options: [.cursorUpdate, .mouseEnteredAndExited, .activeAlways], owner: self, userInfo: nil))
|
|
255
|
+
super.updateTrackingAreas()
|
|
256
|
+
}
|
|
257
|
+
override func cursorUpdate(with event: NSEvent) { NSCursor.pointingHand.set() }
|
|
258
|
+
/** Ack without opening anything. */
|
|
259
|
+
@objc func acknowledge() {
|
|
260
|
+
guard let item = pet?.item else { return }
|
|
261
|
+
delegate.hideClicked(item)
|
|
262
|
+
ackItem(item)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
override func rightMouseDown(with event: NSEvent) {
|
|
266
|
+
let menu = NSMenu()
|
|
267
|
+
if let url = pet?.item.prLink {
|
|
268
|
+
let open = NSMenuItem(title: "Open PR", action: #selector(NSApplication.petOpenURL(_:)), keyEquivalent: "")
|
|
269
|
+
open.target = NSApp
|
|
270
|
+
open.representedObject = url
|
|
271
|
+
menu.addItem(open)
|
|
272
|
+
}
|
|
273
|
+
if pet?.item.key != nil {
|
|
274
|
+
let ack = NSMenuItem(title: "Acknowledge", action: #selector(PetView.acknowledge), keyEquivalent: "")
|
|
275
|
+
ack.target = self
|
|
276
|
+
menu.addItem(ack)
|
|
277
|
+
}
|
|
278
|
+
let glass = NSMenuItem(title: "Open spyglass", action: #selector(NSApplication.petOpenGlass), keyEquivalent: "")
|
|
279
|
+
glass.target = NSApp
|
|
280
|
+
menu.addItem(glass)
|
|
281
|
+
menu.addItem(.separator())
|
|
282
|
+
let quit = NSMenuItem(title: "Quit Lobstah Pet", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "")
|
|
283
|
+
quit.target = NSApp
|
|
284
|
+
menu.addItem(quit)
|
|
285
|
+
NSMenu.popUpContextMenu(menu, with: event, for: self)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
extension NSApplication {
|
|
290
|
+
@objc func petOpenGlass() {
|
|
291
|
+
openSpyglass()
|
|
292
|
+
}
|
|
293
|
+
@objc func petOpenURL(_ sender: NSMenuItem) {
|
|
294
|
+
if let url = sender.representedObject as? URL { NSWorkspace.shared.open(url) }
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
final class Pet {
|
|
299
|
+
static let spriteSheet: NSImage? = Bundle.module.url(forResource: "lob-sprite", withExtension: "png").flatMap { NSImage(contentsOf: $0) }
|
|
300
|
+
static let starImage: NSImage? = Bundle.module.url(forResource: "star", withExtension: "png").flatMap { NSImage(contentsOf: $0) }
|
|
301
|
+
|
|
302
|
+
var item: AttentionItem
|
|
303
|
+
let panel: NSPanel
|
|
304
|
+
let spriteLayer = CALayer()
|
|
305
|
+
var x: CGFloat
|
|
306
|
+
let speed: CGFloat
|
|
307
|
+
/** Delay only a new entrance; an existing pet never returns to this state. */
|
|
308
|
+
var entryAfter: Date?
|
|
309
|
+
var frame = 0
|
|
310
|
+
/** All displays, left to right; the pet crosses each in turn. */
|
|
311
|
+
let screens: [NSScreen]
|
|
312
|
+
var screenIndex = 0
|
|
313
|
+
/** Between displays the pet is simply gone for a beat, then re-enters. */
|
|
314
|
+
var hiddenUntil: Date?
|
|
315
|
+
/** Where the current entrance began — drives the fade-in. */
|
|
316
|
+
var entryX: CGFloat = -10_000
|
|
317
|
+
/** Hovered: the walk pauses, the bubble reveals; the arms keep waving. */
|
|
318
|
+
var hovered = false { didSet { bubble?.isHidden = !hovered } }
|
|
319
|
+
weak var bubble: NSView?
|
|
320
|
+
weak var label: NSTextField?
|
|
321
|
+
|
|
322
|
+
/** FNV-1a over UTF-8: unlike Swift's Hasher, stable across processes. */
|
|
323
|
+
static func walkingSpeed(for key: String) -> CGFloat {
|
|
324
|
+
var hash: UInt32 = 2_166_136_261
|
|
325
|
+
for byte in key.utf8 { hash = (hash ^ UInt32(byte)) &* 16_777_619 }
|
|
326
|
+
return CGFloat(90 + hash % 71)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
init(item: AttentionItem, entryIndex: Int) {
|
|
330
|
+
self.item = item
|
|
331
|
+
self.screens = NSScreen.screens.sorted { $0.frame.minX < $1.frame.minX }
|
|
332
|
+
self.speed = Pet.walkingSpeed(for: item.identity)
|
|
333
|
+
// Keep a little spatial separation as well as a 0...2s stagger, so
|
|
334
|
+
// simultaneous arrivals do not start with their sprites on top of one another.
|
|
335
|
+
let delay = Double.random(in: 0...2)
|
|
336
|
+
self.entryAfter = Date().addingTimeInterval(delay)
|
|
337
|
+
let first = screens.first?.frame ?? .zero
|
|
338
|
+
self.x = first.minX - 200 - CGFloat(entryIndex) * 140
|
|
339
|
+
self.entryX = self.x
|
|
340
|
+
|
|
341
|
+
let panelW: CGFloat = 300
|
|
342
|
+
let panelH: CGFloat = 150
|
|
343
|
+
panel = NSPanel(
|
|
344
|
+
contentRect: NSRect(x: x, y: 0, width: panelW, height: panelH),
|
|
345
|
+
styleMask: [.borderless, .nonactivatingPanel],
|
|
346
|
+
backing: .buffered, defer: false
|
|
347
|
+
)
|
|
348
|
+
panel.level = .floating
|
|
349
|
+
panel.backgroundColor = .clear
|
|
350
|
+
panel.isOpaque = false
|
|
351
|
+
panel.hasShadow = false
|
|
352
|
+
panel.ignoresMouseEvents = false
|
|
353
|
+
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
|
|
354
|
+
panel.acceptsMouseMovedEvents = true
|
|
355
|
+
|
|
356
|
+
let root = PetView(frame: NSRect(x: 0, y: 0, width: panelW, height: panelH))
|
|
357
|
+
root.wantsLayer = true
|
|
358
|
+
panel.contentView = root
|
|
359
|
+
|
|
360
|
+
// sprite: one frame of the 4-frame sheet, pixel-crisp at 1.5x
|
|
361
|
+
let spriteW: CGFloat = 108, spriteH: CGFloat = 84
|
|
362
|
+
spriteLayer.frame = CGRect(x: 168, y: 0, width: spriteW, height: spriteH)
|
|
363
|
+
if let sheet = Pet.spriteSheet {
|
|
364
|
+
var rect = CGRect(origin: .zero, size: sheet.size)
|
|
365
|
+
spriteLayer.contents = sheet.cgImage(forProposedRect: &rect, context: nil, hints: nil)
|
|
366
|
+
}
|
|
367
|
+
spriteLayer.contentsRect = CGRect(x: 0, y: 0, width: 0.25, height: 1)
|
|
368
|
+
spriteLayer.magnificationFilter = .nearest
|
|
369
|
+
root.layer?.addSublayer(spriteLayer)
|
|
370
|
+
|
|
371
|
+
// the question is a hover reveal, fully above the lobster, sized to fit
|
|
372
|
+
let bubble = NSView(frame: NSRect(x: 40, y: 88, width: 236, height: 58))
|
|
373
|
+
bubble.isHidden = true
|
|
374
|
+
bubble.wantsLayer = true
|
|
375
|
+
bubble.layer?.backgroundColor = NSColor(calibratedRed: 0.086, green: 0.106, blue: 0.133, alpha: 0.96).cgColor
|
|
376
|
+
bubble.layer?.borderColor = NSColor(calibratedWhite: 0.35, alpha: 1).cgColor
|
|
377
|
+
bubble.layer?.borderWidth = 1
|
|
378
|
+
bubble.layer?.cornerRadius = 10
|
|
379
|
+
|
|
380
|
+
// the star rides above the claw — the glass's geometry scaled 1.5x
|
|
381
|
+
let star = NSImageView(frame: NSRect(x: 168 + 82, y: spriteH - 9, width: 22, height: 22))
|
|
382
|
+
star.image = Pet.starImage
|
|
383
|
+
star.imageScaling = .scaleProportionallyUpOrDown
|
|
384
|
+
star.wantsLayer = true
|
|
385
|
+
star.layer?.magnificationFilter = .nearest
|
|
386
|
+
|
|
387
|
+
let label = NSTextField(wrappingLabelWithString: item.bubbleLine)
|
|
388
|
+
label.font = NSFont.monospacedSystemFont(ofSize: 10, weight: .regular)
|
|
389
|
+
let fitted = label.sizeThatFits(NSSize(width: 216, height: 120))
|
|
390
|
+
bubble.setFrameSize(NSSize(width: min(236, fitted.width + 20), height: fitted.height + 12))
|
|
391
|
+
bubble.setFrameOrigin(NSPoint(x: 276 - bubble.frame.width, y: 88))
|
|
392
|
+
label.frame = NSRect(x: 10, y: 6, width: fitted.width, height: fitted.height)
|
|
393
|
+
label.textColor = NSColor(calibratedRed: 0.86, green: 0.89, blue: 0.92, alpha: 1)
|
|
394
|
+
label.maximumNumberOfLines = 3
|
|
395
|
+
label.cell?.truncatesLastVisibleLine = true
|
|
396
|
+
bubble.addSubview(label)
|
|
397
|
+
root.addSubview(bubble)
|
|
398
|
+
root.addSubview(star)
|
|
399
|
+
root.pet = self
|
|
400
|
+
self.bubble = bubble
|
|
401
|
+
self.label = label
|
|
402
|
+
|
|
403
|
+
panel.orderOut(nil)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
func update(item: AttentionItem) {
|
|
407
|
+
guard self.item != item else { return }
|
|
408
|
+
self.item = item
|
|
409
|
+
guard let label, let bubble else { return }
|
|
410
|
+
label.stringValue = item.bubbleLine
|
|
411
|
+
let fitted = label.sizeThatFits(NSSize(width: 216, height: 120))
|
|
412
|
+
bubble.setFrameSize(NSSize(width: min(236, fitted.width + 20), height: fitted.height + 12))
|
|
413
|
+
bubble.setFrameOrigin(NSPoint(x: 276 - bubble.frame.width, y: 88))
|
|
414
|
+
label.frame = NSRect(x: 10, y: 6, width: fitted.width, height: fitted.height)
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
func tick(_ dt: CGFloat) {
|
|
418
|
+
if let until = entryAfter {
|
|
419
|
+
if Date() < until { return }
|
|
420
|
+
entryAfter = nil
|
|
421
|
+
panel.orderFrontRegardless()
|
|
422
|
+
}
|
|
423
|
+
// Tracking areas miss a window that walks under a stationary cursor, in
|
|
424
|
+
// both directions — poll instead.
|
|
425
|
+
let inside = panel.frame.contains(NSEvent.mouseLocation) && panel.isVisible
|
|
426
|
+
if inside != hovered {
|
|
427
|
+
hovered = inside
|
|
428
|
+
if !inside { NSCursor.arrow.set() }
|
|
429
|
+
}
|
|
430
|
+
if inside { NSCursor.pointingHand.set() }
|
|
431
|
+
if let until = hiddenUntil {
|
|
432
|
+
if Date() < until { return }
|
|
433
|
+
hiddenUntil = nil
|
|
434
|
+
panel.orderFrontRegardless()
|
|
435
|
+
}
|
|
436
|
+
if !hovered { x += speed * dt }
|
|
437
|
+
let current = screens[screenIndex]
|
|
438
|
+
// Leaving a display: fade over the last stretch, vanish before leaking
|
|
439
|
+
// onto the neighbor, pause a beat offstage, then fade in at the next
|
|
440
|
+
// display's edge.
|
|
441
|
+
let cutoff = current.frame.maxX - panel.frame.width
|
|
442
|
+
if x > cutoff {
|
|
443
|
+
panel.orderOut(nil)
|
|
444
|
+
screenIndex = (screenIndex + 1) % screens.count
|
|
445
|
+
x = screens[screenIndex].frame.minX + 2
|
|
446
|
+
entryX = x
|
|
447
|
+
hiddenUntil = Date().addingTimeInterval(2.5)
|
|
448
|
+
return
|
|
449
|
+
}
|
|
450
|
+
let fadeOut = max(0, min(1, (cutoff - x) / 110))
|
|
451
|
+
let fadeIn = max(0, min(1, (x - entryX) / 40))
|
|
452
|
+
panel.alphaValue = min(fadeOut, fadeIn)
|
|
453
|
+
// visibleFrame keeps the walk above the Dock
|
|
454
|
+
panel.setFrameOrigin(NSPoint(x: x, y: screens[screenIndex].visibleFrame.minY + 2))
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
func step() {
|
|
458
|
+
frame = (frame + 1) % 4
|
|
459
|
+
CATransaction.begin()
|
|
460
|
+
CATransaction.setDisableActions(true)
|
|
461
|
+
spriteLayer.contentsRect = CGRect(x: CGFloat(frame) / 4, y: 0, width: 0.25, height: 1)
|
|
462
|
+
CATransaction.commit()
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
func close() { panel.orderOut(nil) }
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// MARK: - app
|
|
469
|
+
|
|
470
|
+
final class AppDelegate: NSObject, NSApplicationDelegate {
|
|
471
|
+
var petsByKey: [String: Pet] = [:]
|
|
472
|
+
/** Clicked items stay hidden while their state is unchanged, even if the ack fails. */
|
|
473
|
+
var clicked = ClickedItems()
|
|
474
|
+
var statusItem: NSStatusItem?
|
|
475
|
+
var preview = ProcessInfo.processInfo.environment["LOBSTAH_PET_PREVIEW"] != nil
|
|
476
|
+
let diagnostics = ProcessInfo.processInfo.environment["LOBSTAH_PET_DIAGNOSTICS"] != nil
|
|
477
|
+
var polling = false
|
|
478
|
+
/** Logs repeated read failures and writes the state file `lobstah doctor` reads. */
|
|
479
|
+
let monitor = ReadMonitor()
|
|
480
|
+
|
|
481
|
+
var activity: NSObjectProtocol?
|
|
482
|
+
|
|
483
|
+
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
484
|
+
NSApp.setActivationPolicy(.accessory)
|
|
485
|
+
// Accessory apps get App-Napped and their timers throttled — which
|
|
486
|
+
// reads as the pet walking in slow motion. Hold an activity assertion.
|
|
487
|
+
activity = ProcessInfo.processInfo.beginActivity(options: .userInitiated, reason: "pet animation")
|
|
488
|
+
|
|
489
|
+
// No menu-bar presence by default: the pet IS the UI (right-click it
|
|
490
|
+
// for spyglass/quit). LOBSTAH_PET_MENUBAR=1 restores the status item.
|
|
491
|
+
if ProcessInfo.processInfo.environment["LOBSTAH_PET_MENUBAR"] != nil {
|
|
492
|
+
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
|
|
493
|
+
statusItem?.button?.title = "🦞"
|
|
494
|
+
let menu = NSMenu()
|
|
495
|
+
menu.addItem(NSMenuItem(title: "Preview pet", action: #selector(togglePreview), keyEquivalent: "p"))
|
|
496
|
+
menu.addItem(NSMenuItem(title: "Open spyglass", action: #selector(openGlass), keyEquivalent: "g"))
|
|
497
|
+
menu.addItem(.separator())
|
|
498
|
+
menu.addItem(NSMenuItem(title: "Quit Lobstah Pet", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
|
|
499
|
+
for item in menu.items { item.target = self }
|
|
500
|
+
statusItem?.menu = menu
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// walk + frame-step + poll timers. The walk uses measured elapsed
|
|
504
|
+
// time: runloop timers drift, and a fixed nominal dt turns every
|
|
505
|
+
// dropped tick into lost distance.
|
|
506
|
+
var lastTick = CACurrentMediaTime()
|
|
507
|
+
let walker = Timer.scheduledTimer(withTimeInterval: 1.0 / 60, repeats: true) { _ in
|
|
508
|
+
let now = CACurrentMediaTime()
|
|
509
|
+
let dt = CGFloat(min(0.35, now - lastTick))
|
|
510
|
+
lastTick = now
|
|
511
|
+
for pet in self.petsByKey.values { pet.tick(dt) }
|
|
512
|
+
}
|
|
513
|
+
walker.tolerance = 0.002
|
|
514
|
+
Timer.scheduledTimer(withTimeInterval: 0.14, repeats: true) { _ in
|
|
515
|
+
for pet in self.petsByKey.values { pet.step() }
|
|
516
|
+
}
|
|
517
|
+
Timer.scheduledTimer(withTimeInterval: 6, repeats: true) { _ in self.poll() }
|
|
518
|
+
poll()
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Stop walking a clicked item now; the next read keeps it hidden. */
|
|
522
|
+
func hideClicked(_ item: AttentionItem) {
|
|
523
|
+
clicked.hide(item)
|
|
524
|
+
guard item.stateHash != nil else { return }
|
|
525
|
+
// After the click handler returns: the window being clicked closes.
|
|
526
|
+
DispatchQueue.main.async { self.petsByKey.removeValue(forKey: item.identity)?.close() }
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
@objc func togglePreview() {
|
|
530
|
+
preview.toggle()
|
|
531
|
+
poll()
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
@objc func openGlass() {
|
|
535
|
+
openSpyglass()
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
func poll() {
|
|
539
|
+
guard !polling else { return }
|
|
540
|
+
polling = true
|
|
541
|
+
DispatchQueue.global().async {
|
|
542
|
+
// One read at a time (the polling flag), so the monitor needs no lock.
|
|
543
|
+
let read = readAttention()
|
|
544
|
+
self.monitor.record(read)
|
|
545
|
+
let snapshot = read.items
|
|
546
|
+
DispatchQueue.main.async {
|
|
547
|
+
self.polling = false
|
|
548
|
+
// A failed read is not an empty attention queue. Keep every current
|
|
549
|
+
// window in place and try again on the next six-second poll.
|
|
550
|
+
guard let fresh = snapshot else { return }
|
|
551
|
+
var items = self.clicked.walking(fresh)
|
|
552
|
+
if items.isEmpty && self.preview {
|
|
553
|
+
items = [AttentionItem(id: "preview", verb: "needs-decision", note: "the lobster preview — questions crawl in here")]
|
|
554
|
+
}
|
|
555
|
+
let extra = items.count > 4 ? items.count - 4 : 0
|
|
556
|
+
var shown = Array(items.prefix(4))
|
|
557
|
+
if extra > 0 {
|
|
558
|
+
let last = shown.removeLast()
|
|
559
|
+
shown.append(last.standingFor(extra: extra))
|
|
560
|
+
}
|
|
561
|
+
let visibleKeys = Set(shown.map(\.identity))
|
|
562
|
+
for key in self.petsByKey.keys.filter({ !visibleKeys.contains($0) }) {
|
|
563
|
+
self.petsByKey.removeValue(forKey: key)?.close()
|
|
564
|
+
}
|
|
565
|
+
let entering = shown.filter { self.petsByKey[$0.identity] == nil }
|
|
566
|
+
for (index, item) in entering.enumerated() {
|
|
567
|
+
self.petsByKey[item.identity] = Pet(item: item, entryIndex: index)
|
|
568
|
+
}
|
|
569
|
+
for item in shown {
|
|
570
|
+
self.petsByKey[item.identity]?.update(item: item)
|
|
571
|
+
if self.diagnostics, let pet = self.petsByKey[item.identity] {
|
|
572
|
+
NSLog("lobstah pet: %@ window=%@ speed=%@ label=%@", item.identity,
|
|
573
|
+
String(pet.panel.windowNumber), String(format: "%.1f", Double(pet.speed)), item.bubbleText)
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
let app = NSApplication.shared
|
|
582
|
+
let delegate = AppDelegate()
|
|
583
|
+
app.delegate = delegate
|
|
584
|
+
app.run()
|