cost-bubble 0.1.3 → 0.2.0

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.
@@ -1,170 +0,0 @@
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
- }
@@ -1,134 +0,0 @@
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
- }
@@ -1,116 +0,0 @@
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
- }