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,360 +0,0 @@
1
- import AppKit
2
- import ApplicationServices
3
-
4
- final class Controller: NSObject, NSApplicationDelegate {
5
- let panel = NSPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel],
6
- backing: .buffered, defer: false)
7
- let dragSurface = DragSurface()
8
- let header = NSView(), controls = NSView(), headerText = NSTextField(labelWithString: "")
9
- let detailPanel = NSPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
10
- let breakdown = BreakdownView()
11
- var lines: [ChatLine] = []
12
- var currentTitle = ""
13
- var rowChats: [RecentChat] = []
14
- var tokenDetails: [String: (time: Date, detail: TokenDetail?)] = [:]
15
- var detailPending = Set<String>()
16
- var notice: (text: String, until: Date)?
17
- var navigationTicket = 0
18
- var lastPickerShortcut = Date.distantPast
19
- var pinned = false, todayPrices = false, fitTitles = false
20
- var scopeButton = NSButton(title: "", target: nil, action: nil)
21
- var pillFrame = CGRect.zero
22
- var suppressHover = false, showAll = false
23
- var order = SessionOrder.recent, renderedOrder = SessionOrder.recent
24
- var lockedDetail: RowTarget?
25
- var spending: [String: (time: Date, value: SpendDetail?)] = [:]
26
- var spendInFlight = false
27
- var activity: [String: [String: SpendDetail]] = [:]
28
- var renderedZoom: CGFloat = 0
29
- var zoomSteps = min(4, max(-2, UserDefaults.standard.integer(forKey: "listZoomSteps")))
30
- var dailyReports: [String: [String: Usage]] = [:]
31
- var displayedRows: [DisplayRow] = []
32
- var recentChats: [RecentChat] = []
33
- var nextList = Date.distantPast
34
- var pendingList: Int?
35
- let surfaceReader = SurfaceReader()
36
- var active: String?, scope: String?
37
- var revision = 0, pendingIdentity: Int?
38
- var nextIdentity = Date.distantPast
39
- var reports: [String: [String: Usage]] = [:]
40
- var reportTime: [String: Date] = [:]
41
- var reportPending = Set<String>()
42
- var activeProvider: String? { active?.components(separatedBy: "/").first }
43
- var statusItem: NSStatusItem?
44
- func applicationDidFinishLaunching(_ note: Notification) {
45
- NSApp.setActivationPolicy(.accessory)
46
- let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "Session HUD"
47
- let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
48
- item.button?.image = NSImage(systemSymbolName: "gauge.medium", accessibilityDescription: name)
49
- if item.button?.image == nil { item.button?.title = "Σ" }
50
- item.button?.toolTip = name
51
- let menu = NSMenu()
52
- menu.addItem(withTitle: name, action: nil, keyEquivalent: "")
53
- menu.addItem(withTitle: "Open Accessibility Settings…", action: #selector(openPermissions), keyEquivalent: "").target = self
54
- menu.addItem(withTitle: "Quit " + name, action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
55
- item.menu = menu
56
- statusItem = item
57
- configurePanels()
58
- NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(tick),
59
- name: NSWorkspace.didActivateApplicationNotification, object: nil)
60
- Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [weak self] _ in self?.tick() }
61
- let trusted = AXIsProcessTrusted()
62
- let previouslyTrusted = UserDefaults.standard.bool(forKey: "accessibilityAvailable")
63
- UserDefaults.standard.set(trusted, forKey: "accessibilityAvailable")
64
- if !trusted && (previouslyTrusted || !UserDefaults.standard.bool(forKey: "didRequestAccessibility")) {
65
- UserDefaults.standard.set(true, forKey: "didRequestAccessibility")
66
- let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true]
67
- _ = AXIsProcessTrustedWithOptions(options as CFDictionary)
68
- }
69
- tick()
70
- }
71
-
72
- func configurePanels() {
73
- panel.backgroundColor = .clear
74
- panel.isOpaque = false
75
- panel.hasShadow = true
76
- panel.level = .floating
77
- panel.becomesKeyOnlyIfNeeded = true
78
- panel.hidesOnDeactivate = false
79
- panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary, .ignoresCycle]
80
- let bg = dragSurface
81
- bg.wantsLayer = true
82
- bg.appearance = NSAppearance(named: .darkAqua)
83
- bg.layer?.backgroundColor = NSColor(srgbRed: 0.13, green: 0.13, blue: 0.14, alpha: 1).cgColor
84
- bg.layer?.borderColor = NSColor.white.withAlphaComponent(0.22).cgColor
85
- bg.layer?.borderWidth = 1
86
- bg.layer?.cornerRadius = 8
87
- bg.layer?.masksToBounds = true
88
- panel.contentView = bg
89
- detailPanel.isOpaque = false
90
- detailPanel.backgroundColor = .clear
91
- detailPanel.hasShadow = true
92
- detailPanel.level = .floating
93
- detailPanel.hidesOnDeactivate = false
94
- detailPanel.ignoresMouseEvents = true
95
- detailPanel.collectionBehavior = panel.collectionBehavior
96
- let detail = NSVisualEffectView()
97
- detail.material = .hudWindow
98
- detail.blendingMode = .behindWindow
99
- detail.state = .active
100
- detail.appearance = bg.appearance
101
- detail.wantsLayer = true
102
- detail.layer?.cornerRadius = 8
103
- detail.layer?.masksToBounds = true
104
- detailPanel.contentView = detail
105
- detail.layer?.borderColor = NSColor.white.withAlphaComponent(0.14).cgColor
106
- detail.layer?.borderWidth = 1
107
- breakdown.wantsLayer = true
108
- breakdown.layer?.backgroundColor = NSColor(srgbRed: 0.065, green: 0.069, blue: 0.080, alpha: 0.92).cgColor
109
- detail.addSubview(breakdown)
110
- configureHeader()
111
- header.isHidden = true
112
- bg.addSubview(header)
113
- dragSurface.rowAt = { [weak self] in self?.target(at: $0) }
114
- dragSurface.openRow = { [weak self] in self?.openChat($0) }
115
- dragSurface.zoomBy = { [weak self] in self?.changeZoom($0) }
116
- dragSurface.hoverChanged = { [weak self] in self?.updateHover() }
117
- }
118
-
119
- @objc func openPermissions() {
120
- if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") {
121
- NSWorkspace.shared.open(url)
122
- }
123
- }
124
-
125
- func updateHover() {
126
- guard let scope, let provider = activeProvider, !pillFrame.isEmpty else { return }
127
- let inside = panel.frame.contains(NSEvent.mouseLocation)
128
- if !inside { suppressHover = false }
129
- if let lockedDetail, lockedDetail.chat.id != scope && !recentChats.contains(where: { $0.id == lockedDetail.chat.id }) {
130
- self.lockedDetail = nil
131
- }
132
- let expanded = (inside || pinned || lockedDetail != nil) && !suppressHover && !dragSurface.dragging && panel.isVisible
133
- if expanded { refreshList(provider) }
134
- let daily = dailyReports[provider]
135
- let prices = reports[provider]
136
- let displayedPrices = todayPrices ? daily : prices
137
- let current = recentChats.first { $0.id == scope }
138
- let selected = RecentChat(id: scope, title: currentTitle, updated: current?.updated)
139
- let now = Date().timeIntervalSince1970
140
- let candidates = recentChats.filter { $0.id != scope }
141
- var others = candidates
142
- func metrics(_ id: String) -> SpendDetail? {
143
- spending[provider + "/" + id]?.value ?? activity[provider]?[id]
144
- }
145
- if expanded && !showAll {
146
- others = candidates.filter { chat in
147
- daily?[chat.id] != nil || (metrics(chat.id)?.recentCost(seconds: 300, now: now) ?? 0) > 0 ||
148
- chat.updated.map { Calendar.current.isDateInToday(Date(timeIntervalSince1970: $0)) } == true
149
- }
150
- }
151
- if order == .activity && expanded {
152
- others.sort { a, b in
153
- let left = metrics(a.id)?.recentCost(seconds: 300, now: now) ?? 0
154
- let right = metrics(b.id)?.recentCost(seconds: 300, now: now) ?? 0
155
- return left == right ? (a.updated ?? 0) > (b.updated ?? 0) : left > right
156
- }
157
- } else if order == .cost {
158
- others.sort { a,b in
159
- let left = displayedPrices?[a.id]?.cost ?? -1, right = displayedPrices?[b.id]?.cost ?? -1
160
- return left == right ? (a.updated ?? 0) > (b.updated ?? 0) : left > right
161
- }
162
- }
163
- let z = zoom
164
- let rowH = (20*z).rounded()
165
- let visible = panel.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? pillFrame
166
- let capacity = max(1, Int((visible.height - 32*z)/rowH))
167
- let compact = SessionPresentation.compact(others, now: now, metrics: metrics)
168
- let chats = [selected] + (expanded ? Array(others.prefix(min(capacity-1,11))) : Array(compact.prefix(capacity-1)))
169
- if let lockedDetail, !chats.contains(where: { $0.id == lockedDetail.chat.id }) {
170
- self.lockedDetail = nil
171
- updateHover()
172
- return
173
- }
174
- refreshTokenDetails(provider, chats: chats)
175
- let rows = chats.map { chat -> DisplayRow in
176
- let stats = displayedPrices?[chat.id]
177
- let amount = stats?.displayCost ?? formattedCost(nil, pending: displayedPrices == nil)
178
- let fraction = tokenDetails[provider + "/" + chat.id]?.detail?.fraction
179
- return DisplayRow(amount: amount, title: chat.title, tooltip: usageTip(stats, amount: amount),
180
- current: chat.id == scope, contextFraction: fraction, agentCount: helpers(provider, chat.id).filter { !$0.reviewer }.count)
181
- }
182
- let h = expanded ? (32*z).rounded()+rowH*CGFloat(rows.count) : pillFrame.height + rowH * CGFloat(rows.count-1)
183
- let idealTop = pillFrame.midY + (26*z).rounded() + rowH/2
184
- let y = expanded ? min(max(idealTop - h, visible.minY), max(visible.minY, visible.maxY-h)) : min(max(pillFrame.maxY-h, visible.minY), visible.maxY-h)
185
- let frame = NSRect(x:pillFrame.minX, y:y, width:pillFrame.width, height:h)
186
- let needsLayout = frame.size != panel.frame.size || header.isHidden == expanded || renderedZoom != z
187
- if panel.frame != frame { panel.setFrame(frame, display: true) }
188
- header.isHidden = !expanded
189
- if expanded {
190
- func total(_ report: [String: Usage]?) -> String {
191
- guard let report else { return "…" }
192
- let values = chats.compactMap { report[$0.id]?.cost }
193
- guard !values.isEmpty else { return "—" }
194
- let partial = chats.contains { report[$0.id]?.partialCost == true }
195
- return (partial ? "≥" : "") + formattedCost(values.reduce(0,+), pending: false)
196
- }
197
- let today = total(daily)
198
- let totals = today + " / " + total(prices)
199
- let totalText = notice.flatMap { $0.until > Date() ? $0.text : nil } ?? totals
200
- if headerText.stringValue != totalText || renderedZoom != z || (scopeButton.state == .on) != todayPrices {
201
- let text = NSMutableAttributedString(string: totalText, attributes: [
202
- .font: NSFont.systemFont(ofSize: 12.5*z, weight: .semibold),
203
- .foregroundColor: NSColor(srgbRed: 0.77, green: 0.86, blue: 0.98, alpha: 0.77)])
204
- text.addAttribute(.font, value: NSFont.systemFont(ofSize: 14.5*z, weight: .bold),
205
- range: NSRange(location: 0, length: min((totalText as NSString).length, (today as NSString).length)))
206
- if totalText == totals {
207
- let selected = todayPrices ? NSRange(location: 0,length: (today as NSString).length) :
208
- NSRange(location: (today as NSString).length+3, length: (total(prices) as NSString).length)
209
- text.addAttribute(.foregroundColor, value: NSColor.white, range: selected)
210
- }
211
- scopeButton.state = todayPrices ? .on : .off
212
- headerText.attributedStringValue = text
213
- }
214
- }
215
- if needsLayout || displayedRows != rows || renderedOrder != order {
216
- while lines.count < rows.count {
217
- let view = ChatLine()
218
- dragSurface.addSubview(view)
219
- lines.append(view)
220
- }
221
- for (index, line) in lines.enumerated() {
222
- line.isHidden = index >= rows.count
223
- if !line.isHidden {
224
- line.show(rows[index], zoom: z)
225
- line.label.openSession = { [weak self, weak line] in
226
- guard let self, let line, !line.isHidden, self.rowChats.indices.contains(index) else { return }
227
- self.openChat(RowTarget(part: .title, revision: self.revision, chat: self.rowChats[index]))
228
- }
229
- line.frame = NSRect(x: 10*z, y: expanded ? h-26*z-rowH*CGFloat(index+1) : h-(pillFrame.height+rowH)/2-rowH*CGFloat(index),
230
- width: frame.width-19*z, height: rowH)
231
- }
232
- }
233
- header.frame = NSRect(x: 10*z, y:h-26*z, width:frame.width-16*z, height:20*z)
234
- if expanded { positionHeader(header.frame.width, z) }
235
- displayedRows = rows
236
- renderedZoom = z
237
- renderedOrder = order
238
- }
239
- rowChats = chats
240
- updateCostDetail(chats, provider: provider, expanded: expanded)
241
- if provider == "claude" {
242
- let candidates = ([selected] + others).filter {
243
- max($0.updated ?? 0, prices?[$0.id]?.ended ?? 0) >= now - 3600
244
- }
245
- let oldest = candidates.min {
246
- (spending[provider + "/" + $0.id]?.time ?? .distantPast) <
247
- (spending[provider + "/" + $1.id]?.time ?? .distantPast)
248
- }
249
- if let oldest { _ = requestSpend(provider, chat: oldest) }
250
- }
251
- }
252
-
253
- func updateCostDetail(_ chats: [RecentChat], provider: String, expanded: Bool) {
254
- let lockedIndex = lockedDetail.flatMap { locked in chats.firstIndex { $0.id == locked.chat.id } }
255
- let hovered = lockedIndex != nil ? (lockedDetail?.part == .tokens ? lockedIndex : nil) : expanded ? lines.indices.first(where: { i in
256
- guard i < chats.count else { return false }
257
- let line = lines[i]
258
- let point = line.convert(panel.mouseLocationOutsideOfEventStream, from: nil)
259
- return line.bars.frame.insetBy(dx: -2, dy: -2).contains(point)
260
- }) : nil
261
- for (i,line) in lines.enumerated() {
262
- let hidden = i != hovered
263
- if hidden != line.tokenLabel.isHidden { line.tokenLabel.isHidden = hidden; line.needsLayout = true }
264
- }
265
- guard expanded, let index = lockedIndex ?? lines.indices.first(where: { index in
266
- guard index < chats.count else { return false }
267
- let row = lines[index]
268
- let point = row.convert(panel.mouseLocationOutsideOfEventStream, from: nil)
269
- return row.price.frame.contains(point) || index == hovered
270
- }) else {
271
- detailPanel.orderOut(nil)
272
- return
273
- }
274
- let chat = chats[index]
275
- let stats = (todayPrices ? dailyReports : reports)[provider]?[chat.id]
276
- let detail = tokenDetails[provider + "/" + chat.id]?.detail
277
- if index == hovered {
278
- let line = lines[index]
279
- let inline = inlineTokens(detail, helpers: helpers(provider, chat.id), loading: detailPending.contains(provider + "/" + chat.id))
280
- if line.tokenLabel.stringValue != inline { line.tokenLabel.stringValue = inline; line.needsLayout = true }
281
- }
282
- let content: CostBreakdown
283
- if index == hovered {
284
- content = CostBreakdown(title: "Latest request input tokens", total: detail?.context?.formatted() ?? "—",
285
- model: detail?.model, windowDescription: detail?.windowDescription ?? "Context window unavailable")
286
- } else {
287
- let spend = provider == "claude" ? requestSpend(provider, chat: chat) : activity[provider]?[chat.id]
288
- let other = (todayPrices ? reports : dailyReports)[provider]
289
- let counterpart = other?[chat.id]?.displayCost ?? formattedCost(nil, pending: other == nil)
290
- content = CostBreakdown.estimate(amount: displayedRows[index].amount, today: todayPrices,
291
- counterpart: counterpart, stats: stats, model: detail?.model, spend: spend,
292
- helpers: helpers(provider, chat.id), now: Date().timeIntervalSince1970)
293
- }
294
- let visible = panel.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? panel.frame
295
- let width = min(max(panel.frame.width, 336*zoom), visible.width)
296
- let h = breakdown.show(content, width: width, zoom: zoom)
297
- let y = panel.frame.minY - h - 4
298
- let frame = NSRect(x: min(panel.frame.minX, visible.maxX-width),
299
- y: y >= visible.minY ? y : min(panel.frame.maxY+4, visible.maxY-h),
300
- width: width, height: h)
301
- if detailPanel.frame != frame { detailPanel.setFrame(frame, display: true) }
302
- if !detailPanel.isVisible { detailPanel.orderFrontRegardless() }
303
- }
304
-
305
- func target(at point: CGPoint) -> RowTarget? {
306
- guard let i = lines.indices.first(where: { !lines[$0].isHidden && lines[$0].frame.contains(point) }),
307
- rowChats.indices.contains(i) else { return nil }
308
- let line = lines[i]
309
- let local = line.convert(point, from: dragSurface)
310
- let part: RowPart = line.bars.frame.insetBy(dx: -2, dy: -2).contains(local) ? .tokens :
311
- (line.price.frame.contains(local) ? .price : .title)
312
- return RowTarget(part: part, revision: revision, chat: rowChats[i])
313
- }
314
-
315
- @objc func tick() {
316
- guard let app = NSWorkspace.shared.frontmostApplication,
317
- let id = app.bundleIdentifier, [codex, agy, claude].contains(id),
318
- AXIsProcessTrusted(), let s = surfaceReader.surface(app) else {
319
- setActive(nil); return
320
- }
321
- if !UserDefaults.standard.bool(forKey: "accessibilityAvailable") {
322
- UserDefaults.standard.set(true, forKey: "accessibilityAvailable")
323
- }
324
- guard let route = s.route else { setActive(nil); return }
325
- let provider = id == codex ? "codex" : (id == agy ? "antigravity" : "claude")
326
- let key = provider + "/" + route
327
- setActive(key)
328
- let longest = fitTitles ? ([currentTitle] + recentChats.map(\.title)).map {
329
- ($0 as NSString).size(withAttributes: [.font: NSFont.systemFont(ofSize: 12.5, weight: .bold)]).width
330
- }.max() ?? 0 : 0
331
- let width = min(max(preferredWidth(), longest+115)*zoom, s.frame.width - 12)
332
- let top = (NSScreen.screens.first?.frame.maxY ?? 0) - s.frame.minY - 10
333
- let height = (32*zoom).rounded()
334
- let anchor = CGPoint(x: targetX(s, width: width), y: top - height)
335
- let pref = "dragOffset." + id
336
- let offset = UserDefaults.standard.dictionary(forKey: pref) as? [String: Double]
337
- let hostTop = top + 10
338
- func bounded(_ point: CGPoint) -> CGPoint {
339
- CGPoint(x: min(max(point.x, s.frame.minX), s.frame.maxX - width),
340
- y: max(min(point.y, hostTop - height), hostTop - s.frame.height))
341
- }
342
- let origin = bounded(CGPoint(x: anchor.x + (offset?["x"] ?? 0), y: anchor.y + (offset?["y"] ?? 0)))
343
- let frame = NSRect(origin: origin, size: NSSize(width: width, height: height))
344
- pillFrame = frame
345
- dragSurface.pillOrigin = frame.origin
346
- if scope == nil, panel.frame != frame { panel.setFrame(frame, display: true) }
347
- dragSurface.moveTo = { [weak self] point in
348
- guard let self, self.active == key,
349
- NSWorkspace.shared.frontmostApplication?.bundleIdentifier == id else { return }
350
- let destination = bounded(point)
351
- self.pillFrame.origin = destination
352
- self.dragSurface.pillOrigin = destination
353
- self.panel.setFrameOrigin(destination)
354
- UserDefaults.standard.set(["x": destination.x - anchor.x, "y": destination.y - anchor.y], forKey: pref)
355
- }
356
- updateIdentity(provider: provider, route: route, appID: id)
357
- updateReport(provider)
358
- updateHover()
359
- }
360
- }
@@ -1,100 +0,0 @@
1
- import AppKit
2
-
3
- extension Controller {
4
- var zoom: CGFloat { CGFloat(pow(1.12, Double(zoomSteps))) }
5
- @objc func zoomIn() { changeZoom(1) }
6
- @objc func zoomOut() { changeZoom(-1) }
7
- func changeZoom(_ step: Int) {
8
- zoomSteps = min(4, max(-2, zoomSteps + step))
9
- UserDefaults.standard.set(zoomSteps, forKey: "listZoomSteps")
10
- tick()
11
- }
12
- @objc func toggleOrder() {
13
- switch order {
14
- case .recent: order = .cost
15
- case .cost: order = .activity
16
- case .activity: order = .recent
17
- }
18
- updateHover()
19
- }
20
- @objc func toggleHistory() { showAll.toggle(); updateHover() }
21
- @objc func togglePin() { pinned.toggle(); suppressHover = false; updateHover() }
22
- @objc func toggleScope() { todayPrices.toggle(); updateHover() }
23
- @objc func toggleFit() { fitTitles.toggle(); tick() }
24
- @objc func actualSize() { changeZoom(-zoomSteps) }
25
- @objc func resetPosition() {
26
- guard let app = NSWorkspace.shared.frontmostApplication?.bundleIdentifier, [claude,agy,codex].contains(app) else { return }
27
- UserDefaults.standard.removeObject(forKey: "dragOffset." + app)
28
- tick()
29
- }
30
- @objc func closeList() { pinned = false; lockedDetail = nil; suppressHover = true; updateHover() }
31
- @objc func options(_ sender: NSButton) {
32
- let menu = NSMenu()
33
- let item = menu.addItem(withTitle: showAll ? "Show today’s chats" : "Show 12 recent chats", action: #selector(toggleHistory), keyEquivalent: "")
34
- item.target = self
35
- let order = menu.addItem(withTitle: order == .recent ? "Sort by session cost" : (order == .cost ? "Sort by recent spend" : "Sort by most recent"), action: #selector(toggleOrder), keyEquivalent: "")
36
- order.target = self
37
- for (label, selector) in [(pinned ? "Unlock list" : "Lock list open", #selector(togglePin)),
38
- (todayPrices ? "Use lifetime estimates" : "Use today’s estimates", #selector(toggleScope)),
39
- (fitTitles ? "Use saved width" : "Auto-fit titles", #selector(toggleFit)),
40
- ("Actual size", #selector(actualSize)), ("Reset position", #selector(resetPosition))] {
41
- menu.addItem(withTitle: label, action: selector, keyEquivalent: "").target = self
42
- }
43
- menu.popUp(positioning: nil, at: NSPoint(x: 0, y: -2), in: sender)
44
- }
45
-
46
- func configureHeader() {
47
- headerText.font = .monospacedDigitSystemFont(ofSize: 13, weight: .bold)
48
- headerText.textColor = NSColor(srgbRed: 0.77, green: 0.86, blue: 0.98, alpha: 1)
49
- headerText.lineBreakMode = .byTruncatingTail
50
- headerText.toolTip = "Today's estimates / lifetime estimates for the listed chats. Totals include priced sessions."
51
- header.addSubview(headerText)
52
- scopeButton.isBordered = false
53
- scopeButton.isTransparent = true
54
- scopeButton.target = self
55
- scopeButton.action = #selector(toggleScope)
56
- scopeButton.toolTip = "Switch row estimates between today and lifetime"
57
- scopeButton.setAccessibilityLabel("Switch cost period")
58
- header.addSubview(scopeButton)
59
- controls.wantsLayer = true
60
- controls.layer?.cornerRadius = 6
61
- controls.layer?.backgroundColor = NSColor.black.withAlphaComponent(0.65).cgColor
62
- header.addSubview(controls)
63
- let specs: [(String, Selector, String)] = [
64
- ("⇅ Recent", #selector(toggleOrder), "Change session order"),
65
- ("−", #selector(zoomOut), "Zoom out"), ("+", #selector(zoomIn), "Zoom in"),
66
- ("≡", #selector(options(_:)), "List options"), ("×", #selector(closeList), "Collapse list")
67
- ]
68
- for (label, action, tip) in specs {
69
- let button = NSButton(title: label, target: self, action: action)
70
- button.isBordered = false
71
- button.setButtonType(.momentaryChange)
72
- if controls.subviews.isEmpty {
73
- button.wantsLayer = true
74
- button.layer?.cornerRadius = 5
75
- button.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.10).cgColor
76
- }
77
- button.toolTip = tip
78
- controls.addSubview(button)
79
- }
80
- }
81
-
82
- func positionHeader(_ width: CGFloat, _ z: CGFloat) {
83
- let h = 20*z
84
- let buttonWidths = [74, 18, 18, 20, 18].map { CGFloat($0)*z }
85
- let w = buttonWidths.reduce(0,+)
86
- controls.frame = NSRect(x: width-w, y: 0, width: w, height: h)
87
- var x: CGFloat = 0
88
- for (index, view) in controls.subviews.enumerated() {
89
- guard let button = view as? NSButton else { continue }
90
- let text = index == 0 ? ("⇅ " + order.rawValue) : button.title
91
- button.attributedTitle = NSAttributedString(string: text, attributes: [
92
- .font: NSFont.systemFont(ofSize: (index == 0 ? 11.5 : 14)*z, weight: .bold),
93
- .foregroundColor: NSColor.white.withAlphaComponent(0.86)])
94
- button.frame = NSRect(x: x, y: 0, width: buttonWidths[index], height: h)
95
- x += buttonWidths[index]
96
- }
97
- headerText.frame = NSRect(x: 0, y: 0, width: max(0,width-w-3*z), height: h)
98
- scopeButton.frame = headerText.frame
99
- }
100
- }
@@ -1,81 +0,0 @@
1
- import AppKit
2
- import ApplicationServices
3
-
4
- enum RowPart { case title, tokens, price }
5
- enum SessionOrder: String { case recent = "Recent", cost = "Cost", activity = "Activity" }
6
-
7
- struct RowTarget: Equatable {
8
- let part: RowPart
9
- let revision: Int
10
- let chat: RecentChat
11
- }
12
-
13
- final class DragSurface: NSView {
14
- var moveTo: ((CGPoint) -> Void)?
15
- var pillOrigin = CGPoint.zero
16
- var rowAt: ((CGPoint) -> RowTarget?)?
17
- var openRow: ((RowTarget) -> Void)?
18
- var zoomBy: ((Int) -> Void)?
19
- private var pressed: RowTarget?
20
- private var start = CGPoint.zero
21
- private var magnificationDelta: CGFloat = 0
22
- override func magnify(with event: NSEvent) {
23
- if event.phase == .began { magnificationDelta = 0 }
24
- magnificationDelta += event.magnification
25
- if abs(magnificationDelta) >= 0.10 {
26
- zoomBy?(magnificationDelta > 0 ? 1 : -1)
27
- magnificationDelta = 0
28
- }
29
- }
30
- private var grabOffset: CGPoint?
31
- private var tracking: NSTrackingArea?
32
- private(set) var dragging = false
33
- var hoverChanged: (() -> Void)?
34
-
35
- override func updateTrackingAreas() {
36
- super.updateTrackingAreas()
37
- if let tracking { removeTrackingArea(tracking) }
38
- let area = NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect],
39
- owner: self, userInfo: nil)
40
- addTrackingArea(area)
41
- tracking = area
42
- }
43
-
44
- override func mouseEntered(with event: NSEvent) { hoverChanged?() }
45
- override func mouseExited(with event: NSEvent) { hoverChanged?() }
46
-
47
- // The labels fill most of the pill. The whole row is one drag target.
48
- override func hitTest(_ point: NSPoint) -> NSView? {
49
- guard let hit = super.hitTest(point) else { return nil }
50
- if let button = hit as? NSButton { return button }
51
- return self
52
- }
53
-
54
- override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
55
-
56
- override func mouseDown(with event: NSEvent) {
57
- let cursor = NSEvent.mouseLocation
58
- pressed = rowAt?(convert(event.locationInWindow, from: nil))
59
- start = cursor
60
- grabOffset = CGPoint(x: cursor.x - pillOrigin.x, y: cursor.y - pillOrigin.y)
61
- }
62
-
63
- override func mouseDragged(with event: NSEvent) {
64
- guard let grabOffset else { return }
65
- let cursor = NSEvent.mouseLocation
66
- guard dragging || hypot(cursor.x-start.x, cursor.y-start.y) >= 4 else { return }
67
- dragging = true
68
- pressed = nil
69
- hoverChanged?()
70
- moveTo?(CGPoint(x: cursor.x - grabOffset.x, y: cursor.y - grabOffset.y))
71
- }
72
-
73
- override func mouseUp(with event: NSEvent) {
74
- let released = rowAt?(convert(event.locationInWindow, from: nil))
75
- if !dragging, let pressed, released == pressed { openRow?(pressed) }
76
- pressed = nil
77
- grabOffset = nil
78
- dragging = false
79
- hoverChanged?()
80
- }
81
- }
@@ -1,99 +0,0 @@
1
- import AppKit
2
- import ApplicationServices
3
-
4
- struct Snapshot: Decodable {
5
- let id: String?
6
- let title: String?
7
- }
8
-
9
- struct Usage: Decodable {
10
- let cost: Double?
11
- let ended: Double?
12
- let calls: Int?
13
- let inputTokens: Int?
14
- let outputTokens: Int?
15
- let cacheReadTokens: Int?
16
- var cacheWriteTokens: Int? = nil
17
- var partialCost: Bool? = nil
18
-
19
- var displayCost: String {
20
- (partialCost == true && cost != nil ? "≥" : "") + formattedCost(cost, pending: false)
21
- }
22
-
23
- func including(_ children: [Usage]) -> Usage {
24
- guard !children.isEmpty else { return self }
25
- func total<T: AdditiveArithmetic>(_ field: KeyPath<Usage, T?>) -> T? {
26
- guard let parent = self[keyPath: field] else { return nil }
27
- return children.compactMap { $0[keyPath: field] }.reduce(parent, +)
28
- }
29
- let known = ([self] + children).compactMap(\.cost)
30
- let partial = known.count < children.count + 1
31
- let sum = known.reduce(0, +)
32
- let estimated = known.isEmpty || (partial && sum == 0) ? nil : sum
33
- return Usage(cost: estimated, ended: ended, calls: total(\.calls), inputTokens: total(\.inputTokens),
34
- outputTokens: total(\.outputTokens), cacheReadTokens: total(\.cacheReadTokens),
35
- cacheWriteTokens: total(\.cacheWriteTokens), partialCost: partial)
36
- }
37
- }
38
-
39
- struct TokenDetail: Decodable {
40
- let context: Int?
41
- let model: String?
42
- let contextWindow: Int?
43
-
44
- var fraction: Double? {
45
- guard let context, context >= 0, let contextWindow, contextWindow > 0 else { return nil }
46
- return min(1, Double(context) / Double(contextWindow))
47
- }
48
-
49
- var windowDescription: String {
50
- guard let fraction, let contextWindow else { return "Context window unavailable" }
51
- return "\(fraction.formatted(.percent.precision(.fractionLength(0)))) of \(contextWindow.formatted()) tokens"
52
- }
53
- }
54
-
55
- struct RecentChat: Decodable, Equatable {
56
- let id: String
57
- let title: String
58
- let updated: Double?
59
- var route: String? = nil
60
- }
61
-
62
- struct DisplayRow: Equatable {
63
- let amount: String
64
- let title: String
65
- let tooltip: String
66
- let current: Bool
67
- let contextFraction: Double?
68
- let agentCount: Int
69
- }
70
-
71
- func usageTip(_ usage: Usage?, amount: String) -> String {
72
- var parts = ["Session estimate " + amount]
73
- if let calls = usage?.calls { parts.append("\(calls.formatted()) model calls") }
74
- if let input = usage?.inputTokens, let output = usage?.outputTokens {
75
- parts.append("\(input.formatted()) input · \(output.formatted()) output tokens")
76
- }
77
- if let cached = usage?.cacheReadTokens, cached > 0 { parts.append("\(cached.formatted()) cache-read tokens") }
78
- return parts.joined(separator: "\n")
79
- }
80
-
81
- func formattedCost(_ value: Double?, pending: Bool) -> String {
82
- guard let value else { return pending ? "…" : "—" }
83
- if value == 0 { return "$0.00" }
84
- return value < 0.01 ? "<$0.01" : String(format: "$%.2f", value)
85
- }
86
-
87
- func readSnapshot<T: Decodable>(_ arguments: [String]) -> T? {
88
- guard let reader = Bundle.main.url(forResource: "session_cost", withExtension: "py") else { return nil }
89
- let process = Process(), pipe = Pipe()
90
- process.executableURL = URL(fileURLWithPath: "/usr/bin/python3")
91
- process.arguments = ["-B", reader.path] + arguments
92
- process.standardOutput = pipe
93
- process.standardError = FileHandle.nullDevice
94
- do { try process.run() } catch { return nil }
95
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
96
- process.waitUntilExit()
97
- guard process.terminationStatus == 0 else { return nil }
98
- return try? JSONDecoder().decode(T.self, from: data)
99
- }