cost-bubble 0.0.0-stage → 0.1.2

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/Info.plist ADDED
@@ -0,0 +1,26 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>CFBundleDisplayName</key>
6
+ <string>Cost Bubble</string>
7
+ <key>CFBundleExecutable</key>
8
+ <string>SessionHUD</string>
9
+ <key>CFBundleIdentifier</key>
10
+ <string>io.github.anopows.cost-bubble</string>
11
+ <key>CFBundleName</key>
12
+ <string>Cost Bubble</string>
13
+ <key>CFBundlePackageType</key>
14
+ <string>APPL</string>
15
+ <key>CFBundleShortVersionString</key>
16
+ <string>0.1.2</string>
17
+ <key>CFBundleVersion</key>
18
+ <string>3</string>
19
+ <key>LSMinimumSystemVersion</key>
20
+ <string>14.0</string>
21
+ <key>LSUIElement</key>
22
+ <true/>
23
+ <key>NSAccessibilityUsageDescription</key>
24
+ <string>Identify the open desktop chat, position its cost pill, and open the conversation you click in the HUD.</string>
25
+ </dict>
26
+ </plist>
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 anopows and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # Cost Bubble
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See the estimated cost of the chat you have open in Codex, Claude Code or Antigravity on macOS. One native floating pill sits beside the active app’s sidebar. The arrow marks the open chat. Up to two other recent chats appear beneath it when they have a positive recorded cost in the last five minutes, largest recent spend first. Each row shows its selected-period estimate. Claude Code uses the current signed-in desktop catalog, which can include chats from different working directories. Hover to see recent chats, or click a title to switch to it.
4
+
5
+ ![Current chat and another chat with recent spend](docs/compact.png)
6
+
7
+ ## Install on macOS 14 or later
8
+
9
+ With Node.js 22.15 or later and Apple’s Command Line Tools installed, run the [npm installer](https://www.npmjs.com/package/cost-bubble) in Terminal:
10
+
11
+ ```sh
12
+ npx cost-bubble@latest install
13
+ ```
14
+
15
+ This installs the Cost Bubble app, its CodeBurn pricing reader and its login item for your Mac account. Once it launches, enable **Cost Bubble** under **System Settings → Privacy & Security → Accessibility** and open a supported chat.
16
+
17
+ Prefer a globally installed command? Run `npm install --global cost-bubble`, then `cost-bubble install`.
18
+
19
+ You can also install the pinned GitHub release with `npx --allow-git=root github:anopows/cost-bubble#v0.1.2 install`.
20
+
21
+ If you need the prerequisites, [install Node.js](https://nodejs.org/), then run `xcode-select --install` and let it finish. The installer builds and signs the app locally. To install from source, download and extract the [release archive](https://github.com/anopows/cost-bubble/releases), then run `./install.sh --with-codeburn` in the extracted folder.
22
+
23
+ ## Enable Accessibility
24
+
25
+ 1. Click the gauge in the macOS menu bar and choose **Open Accessibility Settings…**. You can also open **System Settings → Privacy & Security → Accessibility**. Some macOS versions label this pane **Device Control and Data Access**.
26
+ 2. Turn on **Cost Bubble**. If it is missing, click **+**, press **Command–Shift–G**, enter `~/Applications/Cost Bubble.app` and click **Open**. Authenticate if macOS asks.
27
+ 3. Bring an existing chat to the front in Codex, the Code section of Claude Desktop, or Antigravity Desktop. Look for its title beside the sidebar. Home screens and ordinary Claude chats do not show a session estimate.
28
+
29
+ Accessibility lets the app identify the focused chat, measure the sidebar and open a chat you click. If a rebuild stops recognizing chats even though the switch is on, remove its old entry with **−**, then add the installed app again. Restart the helper from Terminal if needed.
30
+
31
+ ```sh
32
+ launchctl kickstart -k "gui/$(id -u)/io.github.anopows.cost-bubble"
33
+ ```
34
+
35
+ ## Use the pill
36
+
37
+ | Action | What you see |
38
+ | --- | --- |
39
+ | Hover over the pill | The arrow marks your open chat. The list initially includes other chats active today among the 12 most recent. |
40
+ | Click a chat title | Opens the chat in the same desktop app. Antigravity leaves the picker open if several titles match. |
41
+ | Hover over the token bars | Shows the latest request’s input tokens, including cached input. Bar fill shows the fraction of the reported context window used by those tokens. When the provider omits the limit, the bars stay gray and hover still shows the recorded count. |
42
+ | Hover over a price | Compares the last five minutes and hour, shows the input/output share, and separates cache reads and writes. The lifetime row compares the latest, average and peak request or turn. Click to keep the breakdown open. |
43
+ | Click the total | Switches between today and lifetime. The total covers listed chats with estimates. |
44
+ | Drag the pill or use − / + | Moves or resizes it. Each app remembers its own position. |
45
+
46
+ ![Cost expansion showing ordinary subagents and automatic reviews separately](docs/cost-detail.png)
47
+
48
+ ![Example session list with the current chat first and estimates beside each title](docs/preview.png)
49
+
50
+ ## How estimates work
51
+
52
+ Cost Bubble matches the selected chat to local session metadata and looks up that session’s estimate in [CodeBurn](https://github.com/getagentseal/codeburn). A dash means pricing is unavailable. A ≥ amount is the priced portion of a session with incomplete cost data. When a refresh fails, the HUD keeps its last successful reading and continues to age recent spend out of the five-minute window. Subscription invoices and API bills can differ from the estimate. The cost expansion shows recorded spend in the last five minutes and hour. A session’s average, peak and latest amounts use Claude turns or individual Codex and Antigravity requests. Purple dots represent ordinary subagents (up to four dots). Automatic reviewers appear only in the cost expansion. Their usage contributes to the estimate where the provider prices it. A dash beside a group means some of its pricing is unavailable. The HUD identifies automatic reviewers from recorded roles and models. If a provider omits request-level prices or timestamps, that usage cannot qualify a chat for a recent-spend row.
53
+
54
+ The Swift app uses the same rows, gestures, sorting and cost expansion across all three apps. Local readers normalize desktop records and transcripts. Codex reviewer metadata is cached by file identity so older compressed rollouts are read only when they change. The installer preserves custom `CODEX_HOME`, `CLAUDE_CONFIG_DIR` and `CODEBURN_CACHE_DIR` paths set in your shell. Desktop updates that change local storage or sidebar navigation can affect detection.
55
+
56
+ ## Update or remove
57
+
58
+ If you previously used Desktop Session HUD, install Cost Bubble and grant it Accessibility. Once you see the new pill, unload the earlier login agent with `launchctl bootout "gui/$(id -u)/local.costhud.desktop"`. Move the earlier agent plist out of `~/Library/LaunchAgents/` to prevent a second pill at the next login. You can keep the earlier app as a backup. The new app has its own saved positions and zoom setting.
59
+
60
+ To update, run the new release’s installer. To stop the helper for this login, use its menu bar **Quit** command. To remove it, unload the login agent with the following command, then use Finder’s **Go → Go to Folder…** to locate and move the listed items to the Trash.
61
+
62
+ ```sh
63
+ launchctl bootout "gui/$(id -u)/io.github.anopows.cost-bubble"
64
+ ```
65
+
66
+ - `~/Applications/Cost Bubble.app`
67
+ - `~/Library/LaunchAgents/io.github.anopows.cost-bubble.plist`
68
+ - `~/Library/Application Support/Cost Bubble/` (the pricing reader installed by the npm command)
69
+
70
+ You can also remove the Accessibility entry in System Settings.
71
+
72
+ ## Development
73
+
74
+ Run `/usr/bin/python3 -B -m unittest -v` for session-reader tests. Use `./build.sh /absolute/path/Cost Bubble.app` to build without installing. Run the resulting app’s `Contents/MacOS/SessionHUD --check-bundle` to verify that its bundled reader loads. Released under the [MIT License](LICENSE).
@@ -0,0 +1,101 @@
1
+ import AppKit
2
+ import ApplicationServices
3
+
4
+ final class SignalBars: NSView {
5
+ var agentCount = 0 { didSet { if oldValue != agentCount { needsDisplay = true } } }
6
+ var contextFraction: Double? { didSet { if oldValue != contextFraction { needsDisplay = true } } }
7
+ override func draw(_ dirtyRect: NSRect) {
8
+ let unit = bounds.width / 17
9
+ for index in 0..<4 {
10
+ let height = CGFloat(4 + index * 3) * unit
11
+ NSColor.white.withAlphaComponent(0.18).setFill()
12
+ let rect = NSRect(x: CGFloat(index) * 4.5 * unit, y: agentCount > 0 ? 4 * unit : unit, width: 2.8 * unit, height: agentCount > 0 ? height * 0.78 : height)
13
+ let shape = NSBezierPath(roundedRect: rect, xRadius: unit, yRadius: unit)
14
+ shape.fill()
15
+ let portion = min(1, max(0, (contextFraction ?? 0) * 4 - Double(index)))
16
+ if portion > 0 {
17
+ NSGraphicsContext.saveGraphicsState()
18
+ NSBezierPath(rect: NSRect(x: rect.minX, y: rect.minY, width: rect.width,
19
+ height: rect.height * CGFloat(portion))).addClip()
20
+ NSColor.systemCyan.setFill()
21
+ shape.fill()
22
+ NSGraphicsContext.restoreGraphicsState()
23
+ }
24
+ }
25
+ NSColor.systemPurple.setFill()
26
+ for index in 0..<min(4, agentCount) {
27
+ NSBezierPath(ovalIn: CGRect(x: CGFloat(index)*4.5*unit, y: 0, width: 2.8*unit, height: 2.8*unit)).fill()
28
+ }
29
+ }
30
+ }
31
+
32
+ final class SessionTitle: NSTextField {
33
+ var openSession: (() -> Void)?
34
+ override func accessibilityPerformPress() -> Bool {
35
+ guard let openSession else { return false }
36
+ openSession()
37
+ return true
38
+ }
39
+ override func resetCursorRects() {
40
+ super.resetCursorRects()
41
+ addCursorRect(bounds, cursor: .pointingHand)
42
+ }
43
+ }
44
+
45
+ final class ChatLine: NSView {
46
+ let price = NSTextField(labelWithString: "")
47
+ let bars = SignalBars()
48
+ let tokenLabel = NSTextField(labelWithString: "")
49
+ let arrow = NSTextField(labelWithString: "▸")
50
+ let label = SessionTitle(labelWithString: "")
51
+ var zoom: CGFloat = 1
52
+ override init(frame: NSRect) {
53
+ super.init(frame: frame)
54
+ for view in [price, bars, tokenLabel, arrow, label] { addSubview(view) }
55
+ tokenLabel.textColor = .systemCyan
56
+ tokenLabel.isHidden = true
57
+ label.lineBreakMode = .byTruncatingTail
58
+ label.cell?.usesSingleLineMode = true
59
+ label.maximumNumberOfLines = 1
60
+ label.setAccessibilityRole(.button)
61
+ arrow.textColor = .systemCyan
62
+ }
63
+ required init?(coder: NSCoder) { nil }
64
+
65
+ func show(_ row: DisplayRow, zoom: CGFloat) {
66
+ self.zoom = zoom
67
+ price.stringValue = row.amount
68
+ price.font = .monospacedDigitSystemFont(ofSize: 15 * zoom, weight: .bold)
69
+ price.textColor = row.current ? .systemYellow : NSColor.white.withAlphaComponent(0.76)
70
+ price.toolTip = row.tooltip
71
+ label.stringValue = row.title.split(whereSeparator: \.isWhitespace).joined(separator: " ")
72
+ label.font = .systemFont(ofSize: 12.5 * zoom, weight: row.current ? .bold : .semibold)
73
+ label.textColor = row.current ? .white : NSColor.white.withAlphaComponent(0.73)
74
+ label.toolTip = row.title
75
+ bars.agentCount = row.agentCount
76
+ bars.contextFraction = row.contextFraction
77
+ bars.setAccessibilityLabel(row.agentCount == 0 ? "Session tokens" : "Session tokens, \(row.agentCount) subagents")
78
+ bars.setAccessibilityValue(row.contextFraction?.formatted(.percent) ?? "Context window unavailable")
79
+ bars.setAccessibilityElement(true)
80
+ tokenLabel.font = .monospacedDigitSystemFont(ofSize: 12*zoom, weight: .semibold)
81
+ arrow.isHidden = !row.current
82
+ arrow.font = .systemFont(ofSize: 9 * zoom, weight: .bold)
83
+ needsLayout = true
84
+ }
85
+ override func layout() {
86
+ super.layout()
87
+ func fit(_ field: NSTextField, at x: CGFloat, width: CGFloat? = nil) -> CGFloat {
88
+ let size = field.intrinsicContentSize
89
+ let height = min(bounds.height, size.height)
90
+ field.frame = CGRect(x: x, y: ((bounds.height-height)/2).rounded(),
91
+ width: width ?? ceil(size.width), height: height)
92
+ return field.frame.maxX
93
+ }
94
+ var x = fit(price, at: 0) + 9 * zoom
95
+ bars.frame = CGRect(x: x, y: (bounds.height - 15 * zoom)/2, width: 17 * zoom, height: 15 * zoom)
96
+ x = bars.frame.maxX + 7 * zoom
97
+ if !tokenLabel.isHidden { x = fit(tokenLabel, at: x, width: min(tokenLabel.intrinsicContentSize.width, bounds.width*0.46)) + 4*zoom }
98
+ if !arrow.isHidden { x = fit(arrow, at: x) }
99
+ _ = fit(label, at: x, width: max(0, bounds.width-x))
100
+ }
101
+ }
@@ -0,0 +1,170 @@
1
+ import AppKit
2
+
3
+ struct BreakdownMetric: Equatable {
4
+ let label: String
5
+ let value: String
6
+ init(_ label: String, _ value: String) { self.label = label; self.value = value }
7
+ }
8
+
9
+ struct CostBreakdown: Equatable {
10
+ let title: String
11
+ let total: String
12
+ let model: String?
13
+ var windowDescription: String?
14
+ var calls: String?
15
+ var windows: [BreakdownMetric] = []
16
+ var tokens: [BreakdownMetric] = []
17
+ var inputShare: Double?
18
+ var cache: [BreakdownMetric] = []
19
+ var unit: String?
20
+ var rates: [BreakdownMetric] = []
21
+ var helpers: [BreakdownMetric] = []
22
+
23
+ static func estimate(amount: String, today: Bool, counterpart: String, stats: Usage?,
24
+ model: String?, spend: SpendDetail?, helpers: [SessionHelper], now: Double) -> Self {
25
+ var content = Self(title: today ? "Today’s estimate" : "Session estimate", total: amount, model: model)
26
+ content.calls = stats?.calls.map { "\($0.formatted()) " + ($0 == 1 ? "call" : "calls") }
27
+ if let spend, spend.recent != nil {
28
+ for (seconds, label) in [(300.0, "Last 5 min"), (3600, "Last hour")] {
29
+ content.windows.append(.init(label, formattedCost(spend.recentCost(seconds: seconds, now: now), pending: false)))
30
+ }
31
+ }
32
+ content.windows.append(.init(today ? "Overall" : "Today", counterpart))
33
+ if stats?.inputTokens != nil || stats?.outputTokens != nil {
34
+ content.tokens = [.init("Input", stats?.inputTokens?.formatted() ?? "—"),
35
+ .init("Output", stats?.outputTokens?.formatted() ?? "—")]
36
+ }
37
+ if let input = stats?.inputTokens, let output = stats?.outputTokens, input > 0 || output > 0 {
38
+ content.inputShare = Double(input) / (Double(input) + Double(output))
39
+ }
40
+ if stats?.cacheReadTokens != nil || stats?.cacheWriteTokens != nil {
41
+ content.cache = [.init("Cache read", stats?.cacheReadTokens?.formatted() ?? "—"),
42
+ .init("Cache written", stats?.cacheWriteTokens?.formatted() ?? "—")]
43
+ }
44
+ if let spend, let unit = spend.unit, let latest = spend.last, let average = spend.average, let peak = spend.peak {
45
+ content.unit = unit == "turns" ? "Cost per turn" : "Cost per request"
46
+ content.rates = [.init("Latest", formattedCost(latest, pending: false)),
47
+ .init("Average", formattedCost(average, pending: false)),
48
+ .init("Peak", formattedCost(peak, pending: false))]
49
+ }
50
+ content.helpers = SessionPresentation.helperRows(helpers)
51
+ return content
52
+ }
53
+ }
54
+
55
+ // Rebuild the text fields only when their content, available width or zoom changes.
56
+ // Native labels preserve the exact values for accessibility.
57
+ final class BreakdownView: NSView {
58
+ override var isFlipped: Bool { true }
59
+ private(set) var content: CostBreakdown?
60
+ private var lastWidth: CGFloat = 0
61
+ private var lastZoom: CGFloat = 0
62
+
63
+ func show(_ next: CostBreakdown, width: CGFloat, zoom z: CGFloat) -> CGFloat {
64
+ if content == next && lastWidth == width && lastZoom == z { return frame.height }
65
+ content = next
66
+ lastWidth = width
67
+ lastZoom = z
68
+ subviews.forEach { $0.removeFromSuperview() }
69
+ let w = width/z, inset: CGFloat = 14, inner = w - 2*inset
70
+ let quiet = NSColor(white: 0.75, alpha: 1)
71
+ let ink = NSColor(white: 0.96, alpha: 1)
72
+ let cyan = NSColor.systemCyan, purple = NSColor(srgbRed: 0.75, green: 0.64, blue: 1.0, alpha: 1)
73
+ var y: CGFloat = 10
74
+ func text(_ value: String, _ x: CGFloat, _ top: CGFloat, _ length: CGFloat, _ size: CGFloat,
75
+ _ weight: NSFont.Weight, _ color: NSColor, right: Bool = false, digits: Bool = false,
76
+ label: String? = nil, caption: Bool = false) {
77
+ let field = NSTextField(labelWithString: value)
78
+ field.font = digits ? .monospacedDigitSystemFont(ofSize: size*z, weight: weight)
79
+ : .systemFont(ofSize: size*z, weight: weight)
80
+ field.textColor = color
81
+ field.alignment = right ? .right : .left
82
+ field.lineBreakMode = .byTruncatingTail
83
+ field.maximumNumberOfLines = 1
84
+ field.frame = NSRect(x:x*z, y:top*z, width:length*z, height:ceil((size+5)*z))
85
+ if caption { field.setAccessibilityElement(false) }
86
+ if let label { field.setAccessibilityLabel(label + ", " + value) }
87
+ addSubview(field)
88
+ }
89
+ func strip(_ x: CGFloat, _ top: CGFloat, _ length: CGFloat, _ height: CGFloat, _ color: NSColor) {
90
+ guard length > 0 else { return }
91
+ let view = NSView(frame: NSRect(x:x*z,y:top*z,width:length*z,height:height*z))
92
+ view.wantsLayer = true
93
+ view.layer?.backgroundColor = color.cgColor
94
+ view.setAccessibilityElement(false)
95
+ addSubview(view)
96
+ }
97
+ func divider() {
98
+ y += 6
99
+ strip(inset, y, inner, 1, NSColor(white: 1, alpha: 0.14))
100
+ y += 8
101
+ }
102
+ func grid(_ metrics: [BreakdownMetric], colors: [NSColor] = []) {
103
+ guard !metrics.isEmpty else { return }
104
+ let column = inner/CGFloat(metrics.count)
105
+ for (i, metric) in metrics.enumerated() {
106
+ let x = inset + CGFloat(i)*column
107
+ text(metric.label, x, y, column-3, 11, .medium, quiet, caption: true)
108
+ text(metric.value, x, y+15, column-3, 13, .semibold, i < colors.count ? colors[i] : ink,
109
+ digits: true, label: metric.label)
110
+ }
111
+ y += 34
112
+ }
113
+ let measured = (next.total as NSString).size(withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 22, weight: .bold)]).width
114
+ let left = next.windows.isEmpty || next.model == nil ? inner : min(inner*0.68, ceil(measured)+8)
115
+ text(next.title, inset, y, inner*0.65, 12, .medium, quiet)
116
+ if let calls = next.calls { text(calls, inset+inner*0.65, y, inner*0.35, 12, .semibold, cyan, right:true) }
117
+ y += 16
118
+ text(next.total, inset, y, left, 22, .bold, .systemYellow,
119
+ digits: true, label: next.title)
120
+ if let model = next.model {
121
+ if next.windows.isEmpty {
122
+ y += 28
123
+ text(model, inset, y, inner, 12, .medium, quiet, label: "Latest model")
124
+ y += 16
125
+ } else {
126
+ text(model, inset+left, y+8, inner-left, 11.5, .medium, quiet, right:true, label:"Latest model")
127
+ y += 28
128
+ }
129
+ } else { y += 28 }
130
+ if let window = next.windowDescription {
131
+ text(window, inset, y, inner, 12, .medium, cyan, label: "Context window")
132
+ y += 17
133
+ }
134
+ if !next.windows.isEmpty { y += 3; grid(next.windows) }
135
+ if !next.tokens.isEmpty || !next.cache.isEmpty {
136
+ divider()
137
+ text("Tokens", inset, y, inner*0.55, 12, .semibold, ink)
138
+ if let share = next.inputShare {
139
+ text(share.formatted(.percent.precision(.fractionLength(0))) + " of I/O is input", inset+inner*0.4, y,
140
+ inner*0.6, 11, .medium, quiet, right:true)
141
+ strip(inset, y+20, inner, 4, purple)
142
+ strip(inset, y+20, inner*share, 4, cyan)
143
+ y += 29
144
+ } else { y += 20 }
145
+ grid(next.tokens, colors:[cyan, purple])
146
+ grid(next.cache)
147
+ }
148
+ if let unit = next.unit {
149
+ divider()
150
+ text(unit, inset, y, inner*0.7, 12, .semibold, ink)
151
+ text("Lifetime", inset+inner*0.7, y, inner*0.3, 11, .medium, quiet, right:true)
152
+ y += 20
153
+ grid(next.rates)
154
+ }
155
+ if !next.helpers.isEmpty {
156
+ divider()
157
+ text("Helpers", inset, y, inner*0.7, 12, .semibold, ink)
158
+ text("Lifetime", inset+inner*0.7, y, inner*0.3, 11, .medium, quiet, right:true)
159
+ y += 20
160
+ for metric in next.helpers {
161
+ text(metric.label, inset, y, inner*0.45, 12, .medium, quiet)
162
+ text(metric.value, inset+inner*0.45, y, inner*0.55, 12, .semibold, ink, right:true,
163
+ digits:true, label:metric.label)
164
+ y += 19
165
+ }
166
+ }
167
+ frame = NSRect(x:0,y:0,width:width,height:ceil((y+7)*z))
168
+ return frame.height
169
+ }
170
+ }
@@ -0,0 +1,134 @@
1
+ import AppKit
2
+ import ApplicationServices
3
+
4
+ // Search only the supplied sidebar or picker subtree.
5
+ func matchingControls(in root: AXUIElement, matching match: (AXUIElement) -> Bool) -> [AXUIElement] {
6
+ var queue = [root], index = 0, result: [AXUIElement] = []
7
+ while index < queue.count && index < 1400 {
8
+ let element = queue[index]
9
+ index += 1
10
+ if match(element) { result.append(element) }
11
+ queue += attribute(element, "AXChildren") as? [AXUIElement] ?? []
12
+ }
13
+ return result
14
+ }
15
+
16
+ func pickerLabel(_ value: String, represents title: String) -> Bool {
17
+ guard !title.isEmpty, value.hasPrefix(title) else { return false }
18
+ let suffix = String(value.dropFirst(title.count))
19
+ return suffix.isEmpty || suffix.range(of: #"^ (?:[0-9]+(?:s|m|h|d|w|mo|y)|now|just now)$"#,
20
+ options: .regularExpression) != nil
21
+ }
22
+
23
+ func conversationPicker(_ app: NSRunningApplication) -> AXUIElement? {
24
+ let ax = accessibilityApp(app)
25
+ guard let focus = attribute(ax, "AXFocusedUIElement") else { return nil }
26
+ var element = focus as! AXUIElement
27
+ for _ in 0..<12 {
28
+ if attribute(element, "AXSubrole") as? String == "AXApplicationDialog" {
29
+ let fields = matchingControls(in: element) {
30
+ attribute($0, "AXRole") as? String == "AXComboBox" &&
31
+ (attribute($0, "AXPlaceholderValue") as? String)?.lowercased().contains("conversation") == true
32
+ }
33
+ return fields.isEmpty ? nil : element
34
+ }
35
+ guard let parent = attribute(element, "AXParent") else { return nil }
36
+ element = parent as! AXUIElement
37
+ }
38
+ return nil
39
+ }
40
+
41
+
42
+ extension Controller {
43
+ func openChat(_ target: RowTarget) {
44
+ guard revision == target.revision, let provider = activeProvider,
45
+ let app = NSWorkspace.shared.frontmostApplication,
46
+ app.bundleIdentifier == (provider == "codex" ? codex : (provider == "claude" ? claude : agy)),
47
+ let route = surfaceReader.surface(app)?.route, active == provider + "/" + route,
48
+ panel.isVisible else { return }
49
+ navigationTicket += 1
50
+ let ticket = navigationTicket
51
+ if target.part != .title {
52
+ let same = lockedDetail?.chat.id == target.chat.id && lockedDetail?.part == target.part
53
+ lockedDetail = same ? nil : target
54
+ updateHover()
55
+ return
56
+ }
57
+ lockedDetail = nil
58
+ guard target.chat.id != scope else { updateHover(); return }
59
+ let chat = target.chat
60
+ if provider == "claude" || provider == "codex" {
61
+ let route = provider == "codex" ? chat.id : chat.route
62
+ let prefix = provider == "codex" ? "codex://threads/" : "claude://claude.ai/epitaxy/local_"
63
+ guard let route, UUID(uuidString: route) != nil, let appURL = app.bundleURL,
64
+ let url = URL(string: prefix + route) else { return }
65
+ NSWorkspace.shared.open([url], withApplicationAt: appURL, configuration: NSWorkspace.OpenConfiguration()) { _,error in
66
+ if error != nil { DispatchQueue.main.async { self.navigationMessage("Couldn’t open this chat", target) } }
67
+ }
68
+ return
69
+ }
70
+ if let sidebar = surfaceReader.sidebar {
71
+ let links = matchingControls(in: sidebar) {
72
+ guard attribute($0,"AXRole") as? String == "AXLink", let url = attribute($0,"AXURL") as? URL else { return false }
73
+ return url.scheme == "https" && url.host == "127.0.0.1" && url.path == "/c/" + chat.id
74
+ }
75
+ if let link = links.first, AXUIElementPerformAction(link, "AXPress" as CFString) == .success { return }
76
+ }
77
+ DispatchQueue.global(qos: .userInitiated).async {
78
+ let pickerTitle: String? = readSnapshot(["--picker-title", chat.id])
79
+ DispatchQueue.main.async {
80
+ guard self.navigationTicket == ticket, self.revision == target.revision,
81
+ NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier,
82
+ self.surfaceReader.surface(app)?.route == route else { return }
83
+ self.openPicker(app, target, titleVerified: pickerTitle == chat.title, ticket: ticket, sourceRoute: route)
84
+ }
85
+ }
86
+ }
87
+
88
+ func openPicker(_ app: NSRunningApplication, _ target: RowTarget, titleVerified: Bool, ticket: Int, sourceRoute: String) {
89
+ if conversationPicker(app) == nil && Date().timeIntervalSince(lastPickerShortcut) >= 1 {
90
+ lastPickerShortcut = Date()
91
+ for down in [true,false] {
92
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: 40, keyDown: down)
93
+ event?.flags = .maskCommand
94
+ event?.postToPid(app.processIdentifier)
95
+ }
96
+ }
97
+ finishPicker(app, target, titleVerified: titleVerified, ticket: ticket, sourceRoute: sourceRoute, attempts: 6)
98
+ }
99
+
100
+ func finishPicker(_ app: NSRunningApplication, _ target: RowTarget, titleVerified: Bool, ticket: Int, sourceRoute: String, attempts: Int) {
101
+ guard revision == target.revision, ticket == navigationTicket,
102
+ NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier,
103
+ surfaceReader.surface(app)?.route == sourceRoute else { return }
104
+ if let dialog = conversationPicker(app) {
105
+ if titleVerified {
106
+ let matches = matchingControls(in: dialog) { element in
107
+ guard attribute(element,"AXRole") as? String == "AXStaticText",
108
+ let value = attribute(element,"AXValue") as? String else { return false }
109
+ return pickerLabel(value, represents: target.chat.title)
110
+ }
111
+ if matches.count == 1, AXUIElementPerformAction(matches[0], "AXPress" as CFString) == .success { return }
112
+ }
113
+ if attempts == 3 {
114
+ let search = matchingControls(in: dialog) {
115
+ attribute($0,"AXRole") as? String == "AXComboBox" &&
116
+ (attribute($0,"AXPlaceholderValue") as? String)?.lowercased().contains("conversation") == true
117
+ }
118
+ if search.count == 1, (attribute(search[0], "AXValue") as? String ?? "").isEmpty {
119
+ _ = AXUIElementSetAttributeValue(search[0], "AXValue" as CFString, target.chat.title as CFString)
120
+ }
121
+ }
122
+ if attempts == 0 { navigationMessage("Choose the chat in Antigravity’s picker", target); return }
123
+ }
124
+ if attempts > 0 {
125
+ DispatchQueue.main.asyncAfter(deadline: .now()+0.13) { self.finishPicker(app, target, titleVerified: titleVerified, ticket: ticket, sourceRoute: sourceRoute, attempts: attempts-1) }
126
+ } else { navigationMessage("Conversation picker unavailable", target) }
127
+ }
128
+
129
+ func navigationMessage(_ message: String, _ target: RowTarget) {
130
+ guard revision == target.revision else { return }
131
+ notice = (message, Date().addingTimeInterval(2))
132
+ updateHover()
133
+ }
134
+ }
@@ -0,0 +1,116 @@
1
+ import AppKit
2
+ import ApplicationServices
3
+
4
+ let codex = "com.openai.codex"
5
+ let agy = "com.google.antigravity"
6
+ let claude = "com.anthropic.claudefordesktop"
7
+
8
+ func attribute(_ element: AXUIElement, _ key: String) -> CFTypeRef? {
9
+ var result: CFTypeRef?
10
+ return AXUIElementCopyAttributeValue(element, key as CFString, &result) == .success ? result : nil
11
+ }
12
+
13
+ func bounds(_ element: AXUIElement) -> CGRect? {
14
+ guard let position = attribute(element, "AXPosition"), let size = attribute(element, "AXSize"),
15
+ CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(size) == AXValueGetTypeID() else { return nil }
16
+ var point = CGPoint.zero, dimensions = CGSize.zero
17
+ guard AXValueGetValue(position as! AXValue, .cgPoint, &point),
18
+ AXValueGetValue(size as! AXValue, .cgSize, &dimensions) else { return nil }
19
+ return CGRect(origin: point, size: dimensions)
20
+ }
21
+
22
+ func accessibilityApp(_ app: NSRunningApplication) -> AXUIElement {
23
+ let ax = AXUIElementCreateApplication(app.processIdentifier)
24
+ AXUIElementSetMessagingTimeout(ax, 0.25)
25
+ return ax
26
+ }
27
+
28
+ // Traverse structural containers only. Never read chat messages or form values.
29
+ func firstMatch(_ root: AXUIElement, _ match: (AXUIElement, String) -> Bool,
30
+ enterWeb: Bool) -> AXUIElement? {
31
+ var queue = [root], index = 0
32
+ while index < queue.count && index < 350 {
33
+ let e = queue[index]
34
+ index += 1
35
+ let role = attribute(e, "AXRole") as? String ?? ""
36
+ if match(e, role) { return e }
37
+ if ["AXWindow", "AXGroup", "AXScrollArea", "AXSplitGroup", "AXTabGroup", "AXUnknown"].contains(role)
38
+ || (role == "AXWebArea" && enterWeb) {
39
+ queue += attribute(e, "AXChildren") as? [AXUIElement] ?? []
40
+ }
41
+ }
42
+ return nil
43
+ }
44
+
45
+ struct Surface {
46
+ let frame: CGRect
47
+ let sidebarEdge: CGFloat
48
+ let route: String?
49
+ }
50
+
51
+ // Reuse the web area, but read its URL every time so navigation is visible immediately.
52
+ final class SurfaceReader {
53
+ private var lastWindow: AXUIElement?
54
+ private var lastWeb: AXUIElement?
55
+ private var lastSidebar: AXUIElement?
56
+ private var lastScan = Date.distantPast
57
+ var sidebar: AXUIElement? { lastSidebar }
58
+ private var lastFrame = CGRect.zero
59
+
60
+ func surface(_ app: NSRunningApplication) -> Surface? {
61
+ guard let id = app.bundleIdentifier else { return nil }
62
+ let ax = accessibilityApp(app)
63
+ AXUIElementSetAttributeValue(ax, "AXManualAccessibility" as CFString, kCFBooleanTrue)
64
+ guard let win = attribute(ax, "AXFocusedWindow"), CFGetTypeID(win) == AXUIElementGetTypeID() else { return nil }
65
+ let window = win as! AXUIElement
66
+ guard let frame = bounds(window), frame.width > 300 else { return nil }
67
+ let windowChanged = lastWindow.map { !CFEqual($0, window) } ?? true
68
+ if windowChanged || lastFrame != frame
69
+ || Date().timeIntervalSince(lastScan) >= 1 {
70
+ lastScan = Date()
71
+ lastFrame = frame
72
+ lastWindow = window
73
+ lastWeb = firstMatch(window, { e, role in
74
+ guard role == "AXWebArea", let url = attribute(e, "AXURL") as? URL else { return false }
75
+ switch id {
76
+ case codex: return url.scheme == "app"
77
+ case agy: return url.scheme == "https" && url.host == "127.0.0.1"
78
+ && (attribute(e, "AXTitle") as? String ?? "").contains("Antigravity")
79
+ case claude: return url.scheme == "https" && url.host == "claude.ai"
80
+ default: return false
81
+ }
82
+ }, enterWeb: false)
83
+ lastSidebar = lastWeb.flatMap { web in
84
+ firstMatch(web, { e, role in
85
+ guard role == "AXGroup", let rect = bounds(e), rect.width >= 100,
86
+ rect.width < frame.width * 0.7, rect.height > frame.height * 0.65,
87
+ abs(rect.minX - frame.minX) < 15 else { return false }
88
+ return id == codex || attribute(e, "AXDescription") as? String == "Sidebar"
89
+ || attribute(e, "AXTitle") as? String == "Sidebar"
90
+ }, enterWeb: true)
91
+ }
92
+ }
93
+ guard let web = lastWeb else { return nil }
94
+ let sidebar = lastSidebar
95
+ let edge = sidebar.flatMap(bounds)?.maxX ?? frame.minX
96
+ guard let url = attribute(web, "AXURL") as? URL else {
97
+ lastScan = .distantPast
98
+ return nil
99
+ }
100
+ let path = url.pathComponents
101
+ var route: String?
102
+ if path.count == 3 && id == agy && url.host == "127.0.0.1" && url.scheme == "https" && path[1] == "c" {
103
+ route = UUID(uuidString: path[2])?.uuidString.lowercased()
104
+ } else if path.count == 3 && id == claude && url.host == "claude.ai" && url.scheme == "https" && ["epitaxy", "code"].contains(path[1]) && path[2].hasPrefix("local_") {
105
+ route = UUID(uuidString: String(path[2].dropFirst(6)))?.uuidString.lowercased()
106
+ }
107
+ if id == codex {
108
+ if path.count >= 3, path[1] == "local", let uuid = UUID(uuidString: path[2]) {
109
+ route = uuid.uuidString.lowercased()
110
+ } else {
111
+ route = "current"
112
+ }
113
+ }
114
+ return Surface(frame: frame, sidebarEdge: edge, route: route)
115
+ }
116
+ }