From e798b9dab8ecae00a2fc7e83377265754acf304f Mon Sep 17 00:00:00 2001 From: StuBehan Date: Thu, 19 Nov 2026 17:00:14 +0000 Subject: [PATCH] feat(usage): give every Claude login its own usage row --- .../ClaudeConfigDirsTests.swift | 51 ++++++++-- .../UsageAvailabilityTests.swift | 69 +++++++++++++- .../WidgetQuotaTests.swift | 17 +++- docs/panel.md | 2 + panel/ClaudeConfigDirs.swift | 24 ++++- panel/ClaudeUsageCache.swift | 18 +++- panel/CompactView.swift | 8 +- panel/Companion/CompanionController.swift | 2 +- panel/Panel.swift | 95 +++++++++++++++---- panel/PanelNav.swift | 45 ++++++++- panel/SessionUsage.swift | 53 ++++++++--- panel/UsageHistory.swift | 10 +- panel/WidgetQuota.swift | 11 ++- 13 files changed, 347 insertions(+), 58 deletions(-) diff --git a/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift index 14690de..039a401 100644 --- a/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift +++ b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift @@ -38,11 +38,9 @@ final class ClaudeConfigDirsTests: XCTestCase { try makeDir("\(home)/work-claude", account: "work") try makeDir("\(home)/accounts/side", account: "side") let actual = discover(home, defaultAccount: "me") - XCTAssertEqual(actual, [ - .init(path: "\(home)/.claude-org-publisher", account: "org"), - .init(path: "\(home)/accounts/side", account: "side"), - .init(path: "\(home)/work-claude", account: "work"), - ]) + XCTAssertEqual(actual.map(\.path), ["\(home)/.claude-org-publisher", "\(home)/accounts/side", + "\(home)/work-claude"]) + XCTAssertEqual(actual.map(\.account), ["org", "side", "work"]) } func testScansTwoLevelsDownAndNoFurther() throws { @@ -84,7 +82,8 @@ final class ClaudeConfigDirsTests: XCTestCase { let home = try makeHome() try makeDir("\(home)/.claude-team", account: "me", organization: "team") let actual = discover(home, defaultAccount: "me/personal") - XCTAssertEqual(actual, [.init(path: "\(home)/.claude-team", account: "me/team")]) + XCTAssertEqual(actual.map(\.path), ["\(home)/.claude-team"]) + XCTAssertEqual(actual.map(\.account), ["me/team"]) } func testReadsTheSettingFirstAndOnlyOnce() throws { @@ -133,6 +132,46 @@ final class ClaudeConfigDirsTests: XCTestCase { XCTAssertEqual(ClaudeConfigDirs.remembered(path: file), []) } + // MARK: - Labels + + private func login(_ organizationName: String?) -> ClaudeUsageCache.Login { + ClaudeUsageCache.Login(id: "x", organizationName: organizationName, email: "a@b.c") + } + + func testNamesALoginByItsOrganization() { + XCTAssertEqual(ClaudeConfigDirs.label(for: login("Stackone"), path: "/h/.claude-org-publisher"), + "Stackone") + } + + // A personal plan's organization is named after the email, which says + // nothing the row needs; the dir's own name does. + func testNamesAPersonalPlanByItsDir() { + XCTAssertEqual(ClaudeConfigDirs.label(for: login("a@b.c's Organization"), path: "/h/.claude-side"), + "side") + XCTAssertEqual(ClaudeConfigDirs.label(for: login(nil), path: "/h/elsewhere/work"), "work") + XCTAssertEqual(ClaudeConfigDirs.label(for: login(" "), path: "/h/.claude-x"), "x") + } + + func testLabelsTheDirsItFinds() throws { + let home = try makeHome() + let path = try makeDir("\(home)/.claude-team", account: "me", organization: "team") + let file = "\(path)/.claude.json" + try Data(#"{"oauthAccount":{"accountUuid":"me","organizationUuid":"team","organizationName":"Stackone"}}"#.utf8) + .write(to: URL(fileURLWithPath: file)) + let actual = discover(home, defaultAccount: nil) + XCTAssertEqual(actual.map(\.label), ["Stackone"]) + } + + // MARK: - History + + // Another login's transcripts are under its own dir, and parse as Claude's. + func testReadsAnotherLoginsHistoryFromItsOwnDir() { + XCTAssertEqual(UsageHistoryStore.Source.claudeLogin(configDir: "/h/.claude-team").defaultRoot, + "/h/.claude-team/projects") + XCTAssertEqual(UsageClient.claudeLogin(ClaudeLogin(configDir: "/h/.claude-team", label: "t")).historySource, + .claudeLogin(configDir: "/h/.claude-team")) + } + func testExpandsTildeAndDropsRelativeEntries() { XCTAssertEqual(ClaudeConfigDirs.entries(" ~/.claude-work ,relative, /abs/dir,,~", home: "/h"), ["/h/.claude-work", "/abs/dir", "/h"]) diff --git a/Tests/StackNudgePanelCoreTests/UsageAvailabilityTests.swift b/Tests/StackNudgePanelCoreTests/UsageAvailabilityTests.swift index 73454dd..5e3c3f0 100644 --- a/Tests/StackNudgePanelCoreTests/UsageAvailabilityTests.swift +++ b/Tests/StackNudgePanelCoreTests/UsageAvailabilityTests.swift @@ -85,7 +85,7 @@ final class UsageAvailabilityTests: XCTestCase { XCTAssertEqual(nav.availableUsageClients, [.codex]) } - // Listing order follows UsageClient.allCases (claude, codex, antigravity), + // Listing order follows UsageClient.fixedCases (claude, codex, antigravity), // so a mix of data and errors stays in a stable order. func test_ordering_followsDeclarationOrder() { let nav = PanelNav() @@ -94,4 +94,71 @@ final class UsageAvailabilityTests: XCTestCase { nav.quota = claudeSnapshot() XCTAssertEqual(nav.availableUsageClients, [.claude, .codex, .antigravity]) } + + // MARK: - Other Claude logins + + private let team = ClaudeLogin(configDir: "/h/.claude-team", label: "Stackone") + private let work = ClaudeLogin(configDir: "/h/.claude-work", label: "work") + + // Each login gets its own row, in the order found, straight after the + // default Claude row and before every other client. + func test_otherLoginsAreListedAfterTheDefaultClaudeRow() { + let nav = PanelNav() + nav.quota = claudeSnapshot() + nav.codexQuota = codexSnapshot() + nav.claudeLogins = [team, work] + nav.claudeLoginQuotas = [team.configDir: claudeSnapshot(), work.configDir: claudeSnapshot()] + XCTAssertEqual(nav.availableUsageClients, + [.claude, .claudeLogin(team), .claudeLogin(work), .codex]) + } + + // Found but not yet probed: no row until there's something or an error to show. + func test_aLoginWithNothingToShowIsNotListed() { + let nav = PanelNav() + nav.claudeLogins = [team] + XCTAssertEqual(nav.availableUsageClients, []) + nav.quotaErrors[.claudeLogin(team)] = "failed" + XCTAssertEqual(nav.availableUsageClients, [.claudeLogin(team)]) + } + + // A login is its config dir: its label changing doesn't make it another row. + func test_aLoginIsTheSameRowWhateverItsLabel() { + XCTAssertEqual(UsageClient.claudeLogin(team), + .claudeLogin(ClaudeLogin(configDir: team.configDir, label: "Renamed"))) + } + + func test_eachClaudeRowReadsItsOwnSnapshot() { + let nav = PanelNav() + nav.quota = claudeSnapshot(five: 10) + nav.claudeLogins = [team] + nav.claudeLoginQuotas = [team.configDir: claudeSnapshot(five: 90)] + XCTAssertEqual(nav.claudeQuota(for: .claude)?.fiveHour?.utilization, 10) + XCTAssertEqual(nav.claudeQuota(for: .claudeLogin(team))?.fiveHour?.utilization, 90) + XCTAssertNil(nav.claudeQuota(for: .codex)) + } + + // MARK: - Stress + + // With a Claude row selected, a team seat running hot shows on the mascot + // even though the pill is showing your own plan. + func test_stressTakesTheHottestClaudeLoginWhileClaudeIsSelected() { + let nav = PanelNav() + nav.quota = claudeSnapshot(five: 10) + nav.claudeLogins = [team] + nav.claudeLoginQuotas = [team.configDir: claudeSnapshot(five: 90)] + nav.usageClientIndex = 0 + XCTAssertEqual(nav.selectedUsageClient, .claude) + XCTAssertEqual(nav.widgetQuota.peakUtilization, 10) + XCTAssertEqual(nav.stressPeakUtilization, 90) + } + + // Any other client keeps its own stress, as before there were extra logins. + func test_stressIsTheSelectedClientsOwnOtherwise() { + let nav = PanelNav() + nav.quota = claudeSnapshot(five: 95) + nav.codexQuota = codexSnapshot() + nav.usageClientIndex = 1 + XCTAssertEqual(nav.selectedUsageClient, .codex) + XCTAssertEqual(nav.stressPeakUtilization, 20) + } } diff --git a/Tests/StackNudgePanelCoreTests/WidgetQuotaTests.swift b/Tests/StackNudgePanelCoreTests/WidgetQuotaTests.swift index 89876c0..7904d31 100644 --- a/Tests/StackNudgePanelCoreTests/WidgetQuotaTests.swift +++ b/Tests/StackNudgePanelCoreTests/WidgetQuotaTests.swift @@ -152,8 +152,11 @@ final class WidgetQuotaTests: XCTestCase { // The same property for every client: a selected client with no snapshot // still names itself. + private let teamLogin = UsageClient.claudeLogin( + ClaudeLogin(configDir: "/h/.claude-team", label: "Stackone")) + func test_everyClientKeepsItsIdentityWithNoSnapshot() { - for client in UsageClient.allCases { + for client in UsageClient.fixedCases + [teamLogin] { XCTAssertEqual(make(client).client, client, "\(client) lost its identity") } } @@ -219,8 +222,18 @@ final class WidgetQuotaTests: XCTestCase { XCTAssertEqual(UsageClient.claude.widgetTag, "Claude") XCTAssertEqual(UsageClient.codex.widgetTag, "Codex") XCTAssertEqual(UsageClient.antigravity.widgetTag, "Agy") - for client in UsageClient.allCases { + for client in UsageClient.fixedCases + [teamLogin] { XCTAssertFalse(client.widgetTag.isEmpty, "\(client) has no widget tag") } } + + // Another Claude login draws the same rings from its own snapshot, under its + // own identity and named by the login, so the legend says whose they are. + func test_anotherClaudeLogin_drawsItsOwnSnapshot() { + let actual = make(teamLogin, claude: claudeSnapshot(five: 2, seven: 80)) + XCTAssertEqual(actual.client, teamLogin) + XCTAssertEqual(actual.short?.utilization, 2) + XCTAssertEqual(actual.long?.utilization, 80) + XCTAssertEqual(teamLogin.widgetTag, "Stackone") + } } diff --git a/docs/panel.md b/docs/panel.md index 39b1409..fc52ad3 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -100,6 +100,8 @@ Bars are color-coded: green below 50%, yellow 50–80%, red 80%+. Reset times sh Claude Code keeps one login per config dir, so a second account run with `CLAUDE_CONFIG_DIR` (a team seat beside your own plan, say) never shows up in a plain `claude /usage`. stack-nudge looks for them by the `.claude.json` every one has, whatever it's called: any dir up to two levels under home holding one (rescanned hourly, skipping Desktop, Documents, Downloads, Library and the media folders, which macOS would prompt for), any dir in the `CLAUDE_CONFIG_DIR` of a `claude` running now (remembered in `~/.stack-nudge/claude-config-dirs`, so its row stays after the session ends), and any dir listed comma-separated in `STACKNUDGE_CLAUDE_CONFIG_DIRS` in `~/.stack-nudge/config`. Only dirs signed in to a different account or organization from the default count. Each gets the same `/usage` probe with `CLAUDE_CONFIG_DIR` set to it, at most every five minutes, which also keeps that dir's own usage cache current for anything else reading it. +Each of those logins also gets its own row in the client list, straight under the default Claude one: titled Claude, with the organization (or the dir's name, for a second personal plan) and plan underneath. Its History pane reads that login's own transcripts. Quota alerts fire for every login, and name it. While any Claude row is selected, the mascot's stress takes the hottest Claude login, so a team seat running out shows even while you're looking at your own plan. + Each bar is really two: a pale bar showing how far through the window you are, with the solid usage bar inset inside it. Compare the two right-hand edges — usage short of elapsed means you're spending quota slower than the clock is running it down; usage past elapsed means you'll hit the cap before the reset. It answers “am I above 50% usage with 50% of the window left?” at a glance. When usage leads the clock by five points or more, the row also says so outright — *“22% ahead of pace”*. Only that direction is called out: there's no “on track” line to learn to ignore, so the warning still means something when it shows up. The pale bar needs both a reset time and a window length, so it's absent where either is missing: Antigravity publishes a reset time per model but never a window length, and its monthly credit pool has neither. It's also absent once a tier's reset time has passed, since a snapshot that outlived its own window can't be placed on one. Numbers come from the vendor's own CLI, never from a provider API directly. For Claude, stack-nudge reads the usage payload Claude Code caches to `~/.claude.json` when that cache is under a minute old, and otherwise shells out to `claude --print /usage`. Because the CLI holds its *own* keychain grant, **stack-nudge never touches your keychain or calls the Anthropic API, so there's no password prompt**. If `claude` isn't on your `PATH` or you're signed out, the tab shows *"Claude usage unavailable — run `claude /usage` to check your session"* rather than falling back to any other source; if the CLI breaks with a usable reading still on disk, the tab shows that reading dated to when it was taken rather than nothing at all. diff --git a/panel/ClaudeConfigDirs.swift b/panel/ClaudeConfigDirs.swift index 5078cad..34ab523 100644 --- a/panel/ClaudeConfigDirs.swift +++ b/panel/ClaudeConfigDirs.swift @@ -30,6 +30,23 @@ enum ClaudeConfigDirs { let path: String // ClaudeUsageCache.currentAccount: the account and its organization. let account: String + // How the Usage tab names it. See label(for:path:). + var label: String = "" + } + + // The organization's name, which is what tells a team seat from your own + // plan. Claude Code names a personal plan's organization "'s + // Organization", which says nothing a row needs, so that falls back to the + // dir's own name ("org-publisher" for ~/.claude-org-publisher), as does a + // login with no name at all. + static func label(for login: ClaudeUsageCache.Login, path: String) -> String { + if let name = login.organizationName?.trimmingCharacters(in: .whitespaces), !name.isEmpty, + !name.hasSuffix("'s Organization") { + return name + } + let base = (path as NSString).lastPathComponent + let trimmed = base.hasPrefix(".claude-") ? String(base.dropFirst(".claude-".count)) : base + return trimmed.isEmpty ? base : trimmed } // The default login is passed in so a dir signed in to the same account and @@ -49,11 +66,10 @@ enum ClaudeConfigDirs { for candidate in candidates(home: home, setting: setting, found: found) { let path = (candidate as NSString).resolvingSymlinksInPath guard !defaults.contains(path), seenPaths.insert(path).inserted, - let account = ClaudeUsageCache.currentAccount( - path: ClaudeUsageCache.path(configDir: path)), - seenAccounts.insert(account).inserted + let login = ClaudeUsageCache.login(path: ClaudeUsageCache.path(configDir: path)), + seenAccounts.insert(login.id).inserted else { continue } - dirs.append(Dir(path: path, account: account)) + dirs.append(Dir(path: path, account: login.id, label: label(for: login, path: path))) } return dirs } diff --git a/panel/ClaudeUsageCache.swift b/panel/ClaudeUsageCache.swift index 441ea16..045919b 100644 --- a/panel/ClaudeUsageCache.swift +++ b/panel/ClaudeUsageCache.swift @@ -49,12 +49,26 @@ enum ClaudeUsageCache { // own plan and to a team seat has the same accountUuid in both, but the // quota belongs to the seat, so the two are different logins. static func currentAccount(path: String = ClaudeUsageCache.path) -> String? { + login(path: path)?.id + } + + struct Login: Equatable { + // What currentAccount returns. + let id: String + let organizationName: String? + let email: String? + } + + static func login(path: String = ClaudeUsageCache.path) -> Login? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let account = account(in: root) else { return nil } - let organization = (root["oauthAccount"] as? [String: Any])?["organizationUuid"] as? String - return organization.map { "\(account)/\($0)" } ?? account + let oauth = root["oauthAccount"] as? [String: Any] + let organization = oauth?["organizationUuid"] as? String + return Login(id: organization.map { "\(account)/\($0)" } ?? account, + organizationName: oauth?["organizationName"] as? String, + email: oauth?["emailAddress"] as? String) } private static func account(in root: [String: Any]) -> String? { diff --git a/panel/CompactView.swift b/panel/CompactView.swift index aee9b5b..516797a 100644 --- a/panel/CompactView.swift +++ b/panel/CompactView.swift @@ -309,9 +309,11 @@ struct CompactView: View { } // Passive quota-stress signal for the mascot. True when either window of - // the selected client is ≥75%. The mascot shows a tired/worried expression - // so the user sees the budget pressure without opening the Usage tab. - private var quotaStressed: Bool { quota.peakUtilization >= 75 } + // the selected client is ≥75%, or of any Claude login while a Claude row is + // selected (PanelNav.stressPeakUtilization). The mascot shows a + // tired/worried expression so the user sees the budget pressure without + // opening the Usage tab. + private var quotaStressed: Bool { nav.stressPeakUtilization >= 75 } private var botState: BotState { if let _ = recentEvent { diff --git a/panel/Companion/CompanionController.swift b/panel/Companion/CompanionController.swift index d8c7f0b..0299104 100644 --- a/panel/Companion/CompanionController.swift +++ b/panel/Companion/CompanionController.swift @@ -99,7 +99,7 @@ final class CompanionController { preview: nav.companionPreviewPose, muted: nav.isMuted, permissionWaiting: waiting.contains { $0.kind == .permission }, - quotaStressed: nav.widgetQuota.peakUtilization >= Double(nav.quotaAlertThreshold), + quotaStressed: nav.stressPeakUtilization >= Double(nav.quotaAlertThreshold), eventWaiting: !waiting.isEmpty, sessionBusy: live.contains { $0.liveStatus == "busy" }, quietFor: now.timeIntervalSince(quietSince)) diff --git a/panel/Panel.swift b/panel/Panel.swift index 095ec2e..9fe1483 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -2326,7 +2326,9 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, self.nav.quotaClaudeLastUpdated = nil self.nav.quotaUpdatedAt[.claude] = nil self.nav.quotaErrors[.claude] = nil - self.quotaLastFired.removeAll() + // The default login's own keys: the others are prefixed (see + // quotaAlertKeyPrefix) and didn't switch. + self.quotaLastFired = self.quotaLastFired.filter { $0.key.contains("|") } } if let snapshot { // When the numbers were measured, not when they arrived: a @@ -2418,12 +2420,12 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, } // Every other Claude login on this machine (see ClaudeConfigDirs) gets the - // same probe as the default one, run with CLAUDE_CONFIG_DIR. Nothing else - // refreshes those accounts' usage: Claude Code only writes it to a dir's - // .claude.json when something asks, and the default probe only ever asks - // for the default login. The answer lands in that file, which is where - // anything else reading usage on this machine, the claude-usage extension - // included, picks it up. + // same probe as the default one, run with CLAUDE_CONFIG_DIR, and its own row + // in the Usage tab. Nothing else refreshes those accounts' usage: Claude + // Code only writes it to a dir's .claude.json when something asks, and the + // default probe only ever asks for the default login. The answer also lands + // in that file, which is where anything else reading usage on this machine, + // the claude-usage extension included, picks it up. private func refreshOtherClaudeAccounts() { let lastScan = claudeConfigDirScan // Discovery lists dirs, runs ps and reads a .claude.json per dir, @@ -2441,18 +2443,70 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, guard let self else { return } self.claudeConfigDirScan = scan guard self.quotaTrackingEnabled else { return } - let paths = Set(dirs.map(\.path)) - self.otherClaudeProbes = self.otherClaudeProbes.filter { paths.contains($0.key) } - for dir in dirs { - let probe = self.otherClaudeProbes[dir.path] ?? ClaudeCliQuotaProbe( - configDir: dir.path, cacheMaxAge: ClaudeCliQuotaProbe.otherAccountCacheMaxAge) - self.otherClaudeProbes[dir.path] = probe - probe.fetch { _ in } + self.adoptClaudeLogins(dirs) + for login in self.nav.claudeLogins { + let probe = self.otherClaudeProbes[login.configDir] ?? ClaudeCliQuotaProbe( + configDir: login.configDir, cacheMaxAge: ClaudeCliQuotaProbe.otherAccountCacheMaxAge) + self.otherClaudeProbes[login.configDir] = probe + probe.fetch { [weak self] snapshot in + self?.applyClaudeLoginProbe(login, probe: probe, snapshot: snapshot) + } } } } } + // A login that's gone (signed out, dir removed, or now the same account as + // the default) takes its row, its numbers and its alert state with it. + private func adoptClaudeLogins(_ dirs: [ClaudeConfigDirs.Dir]) { + let logins = dirs.map { ClaudeLogin(configDir: $0.path, label: $0.label) } + let kept = Set(logins.map(\.configDir)) + for gone in nav.claudeLogins where !kept.contains(gone.configDir) { + forgetClaudeLogin(gone) + } + otherClaudeProbes = otherClaudeProbes.filter { kept.contains($0.key) } + // Compared with the labels, which == ignores, so a renamed organization + // still reaches the row. + if logins.map(\.label) != nav.claudeLogins.map(\.label) || logins != nav.claudeLogins { + nav.claudeLogins = logins + } + } + + private func forgetClaudeLogin(_ login: ClaudeLogin) { + let client = UsageClient.claudeLogin(login) + nav.claudeLoginQuotas[login.configDir] = nil + nav.quotaUpdatedAt[client] = nil + nav.quotaErrors[client] = nil + quotaLastFired = quotaLastFired.filter { !$0.key.hasPrefix(Self.quotaAlertKeyPrefix(login)) } + } + + // The default probe's handling, per login. No missing-CLI branch: the + // default probe reports that once for every Claude row, and a login whose + // dir can't be probed has no row until it can. + private func applyClaudeLoginProbe(_ login: ClaudeLogin, probe: ClaudeCliQuotaProbe, + snapshot: QuotaSnapshot?) { + // Gone while the probe ran. + guard nav.claudeLogins.contains(login) else { return } + let client = UsageClient.claudeLogin(login) + if probe.accountChanged { forgetClaudeLogin(login) } + if let snapshot { + let measuredAt = probe.snapshotAsOf ?? Date() + nav.claudeLoginQuotas[login.configDir] = snapshot + nav.quotaErrors[client] = nil + nav.quotaUpdatedAt[client] = measuredAt + evaluateQuotaThresholds(snapshot, login: login) + } else if probe.cliMissing { + return + } else if probe.isRateLimited { + if nav.claudeLoginQuotas[login.configDir] == nil { + nav.quotaErrors[client] = "Claude Code didn't report this login's limits. Retrying shortly." + } + } else { + nav.quotaErrors[client] = + "Couldn't refresh. Run `CLAUDE_CONFIG_DIR=\(login.configDir) claude /usage` to check this login." + } + } + // Pi budget, read from pi's own transcripts with no network and no CLI. // Unlike the probes above there's no failure to surface: the denominators // are the user's own (see PiBudget). Also run on a budget change in @@ -2551,7 +2605,13 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, private static let quotaBucketSize: Int = 5 private static let quotaResetDropThreshold: Double = 30 // pp - private func evaluateQuotaThresholds(_ snapshot: QuotaSnapshot) { + // An extra login's alert state is kept beside the default one's under its + // own prefix, so each login climbs through the buckets on its own numbers. + static func quotaAlertKeyPrefix(_ login: ClaudeLogin) -> String { "\(login.configDir)|" } + + // `login` is nil for the default one, whose banners stay as they were; any + // other names itself, or two logins at 80% would read as one. + private func evaluateQuotaThresholds(_ snapshot: QuotaSnapshot, login: ClaudeLogin? = nil) { guard nav.quotaAlertsEnabled else { return } // Respect the global Banner notifications toggle — quota alerts // are system-level banners and shouldn't bypass it. @@ -2567,8 +2627,11 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, let bucketSize = Self.quotaBucketSize - for (name, label, tier) in tiers { + let keyPrefix = login.map(Self.quotaAlertKeyPrefix) ?? "" + for (tierName, tierLabel, tier) in tiers { guard let tier else { continue } + let name = keyPrefix + tierName + let label = login.map { "\($0.label) · \(tierLabel)" } ?? tierLabel var state = quotaLastFired[name] ?? (maxBucketFired: 0, peakUtil: 0) // Heuristic period-rollover: a >30 pp drop from our running diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 0547428..3307fb9 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -436,6 +436,11 @@ final class PanelNav: ObservableObject { // poller in PanelController. nil before the first probe completes, or // when the probe failed (no `claude` on PATH, not signed in, parse error). @Published var quota: QuotaSnapshot? { didSet { widgetQuotaCache = nil } } + // Claude logins other than the default one, in the order they were found + // (ClaudeConfigDirs), and the latest snapshot for each by config dir. Each + // gets its own row straight after the default Claude one. + @Published var claudeLogins: [ClaudeLogin] = [] { didSet { widgetQuotaCache = nil } } + @Published var claudeLoginQuotas: [String: QuotaSnapshot] = [:] { didSet { widgetQuotaCache = nil } } // Any client's quota — all three stamp it — so "Updated Xm ago" describes the // pane as a whole. @Published var quotaLastUpdated: Date? @@ -797,9 +802,22 @@ final class PanelNav: ObservableObject { private var usageSeriesScannedAt: Date? private var usageSeriesScanning = false - // Connected clients that currently have quota to show, in display order. + // Connected clients that currently have quota to show, in display order: + // the default Claude login, then every other one, then the rest. var availableUsageClients: [UsageClient] { - UsageClient.allCases.filter(isUsageClientAvailable) + let clients = UsageClient.fixedCases.flatMap { client in + client == .claude ? [client] + claudeLogins.map(UsageClient.claudeLogin) : [client] + } + return clients.filter(isUsageClientAvailable) + } + + // Either Claude row's snapshot; nil for any other client. + func claudeQuota(for client: UsageClient) -> QuotaSnapshot? { + switch client { + case .claude: return quota + case .claudeLogin(let login): return claudeLoginQuotas[login.configDir] + default: return nil + } } // A client earns a row when it has a drawable tier, or when it has an error @@ -811,7 +829,7 @@ final class PanelNav: ObservableObject { private func isUsageClientAvailable(_ client: UsageClient) -> Bool { if quotaErrors[client] != nil { return true } switch client { - case .claude: return quota?.hasTier == true + case .claude, .claudeLogin: return claudeQuota(for: client)?.hasTier == true case .codex: return codexQuota?.hasTier == true case .antigravity: return antigravityQuota?.hasTier == true case .pi: return piQuota?.hasTier == true @@ -854,14 +872,14 @@ final class PanelNav: ObservableObject { // Memoised because CompactView reads it from ~16 places per body pass and // the pill re-renders at 10Hz while an agent is busy — recomputing meant // rebuilding availableUsageClients every time. Invalidated by didSet on each - // of the five inputs it reads (the three snapshots, usageClientIndex, and + // input it reads (every snapshot, the Claude logins, usageClientIndex, and // quotaErrors), so the cache can't outlive its sources. private var widgetQuotaCache: WidgetQuota? var widgetQuota: WidgetQuota { if let widgetQuotaCache { return widgetQuotaCache } let value = WidgetQuota.make(client: selectedUsageClient, - claude: quota, + claude: selectedUsageClient.flatMap(claudeQuota(for:)), codex: codexQuota, antigravity: antigravityQuota, pi: piQuota) @@ -869,6 +887,23 @@ final class PanelNav: ObservableObject { return value } + // The mascots' quota-stress signal: the selected client's tighter window, as + // the pill shows. With a Claude row selected it's every Claude login's + // instead, so a team seat running hot still shows while you're looking at + // your own plan, and the other way round. + var stressPeakUtilization: Double { + let selected = widgetQuota.peakUtilization + switch selectedUsageClient { + case .claude, .claudeLogin: + let logins = ([quota] + claudeLogins.map { claudeLoginQuotas[$0.configDir] }) + .compactMap { $0 } + .map { max($0.fiveHour?.utilization ?? 0, $0.sevenDay?.utilization ?? 0) } + return max(selected, logins.max() ?? 0) + default: + return selected + } + } + // The cached series, but only when it belongs to the client on screen — a // scan that finished for a previous selection must not render under a new one. func usageSeries(for client: UsageClient) -> UsageSeries? { diff --git a/panel/SessionUsage.swift b/panel/SessionUsage.swift index 0cd44d7..647ac6c 100644 --- a/panel/SessionUsage.swift +++ b/panel/SessionUsage.swift @@ -47,18 +47,28 @@ struct QuotaSnapshot: Equatable { // A connected client shown in the Usage tab's left-hand list. Each renders its // own quota tiers; ↑/↓ switches between the ones that currently have data. -enum UsageClient: String, CaseIterable, Hashable { +enum UsageClient: Hashable { case claude + // A Claude login other than the default one, signed in from its own config + // dir (see ClaudeConfigDirs). Listed straight after the default Claude row. + case claudeLogin(ClaudeLogin) case codex case antigravity case pi + // Every client but the extra Claude logins, which are only known at run + // time, in display order. + static let fixedCases: [UsageClient] = [.claude, .codex, .antigravity, .pi] + + // The row title. An extra login is still "Claude"; which one it is goes on + // the line under it (see UsageView.planLabel), since the client column is + // too narrow for both. var displayName: String { switch self { - case .claude: return "Claude" - case .codex: return "Codex" - case .antigravity: return "Antigravity" - case .pi: return "Pi" + case .claude, .claudeLogin: return "Claude" + case .codex: return "Codex" + case .antigravity: return "Antigravity" + case .pi: return "Pi" } } @@ -72,16 +82,29 @@ enum UsageClient: String, CaseIterable, Hashable { // client can't silently inherit another agent's transcript format. var historySource: UsageHistoryStore.Source? { switch self { - case .claude: return .claude - case .codex: return .codex - case .antigravity: return nil - case .pi: return .pi + case .claude: return .claude + case .claudeLogin(let login): return .claudeLogin(configDir: login.configDir) + case .codex: return .codex + case .antigravity: return nil + case .pi: return .pi } } var hasReplayableHistory: Bool { historySource != nil } } +// A Claude login other than the default one. Identified by its config dir +// alone: the label is read from the login and may change under it (an +// organization renamed), which must not make it a different row. +struct ClaudeLogin: Hashable { + let configDir: String + // The organization's name, or what stands in for one (see ClaudeConfigDirs). + let label: String + + static func == (lhs: ClaudeLogin, rhs: ClaudeLogin) -> Bool { lhs.configDir == rhs.configDir } + func hash(into hasher: inout Hasher) { hasher.combine(configDir) } +} + // Panes of the Usage tab's inner carousel, in step order. → walks forward while // the detail holds focus; ← walks back and then out to the client list. enum UsagePane: CaseIterable { @@ -275,6 +298,7 @@ struct UsageView: View { private func hasTier(_ client: UsageClient) -> Bool { switch client { case .claude: return nav.quota?.hasTier ?? false + case .claudeLogin(let login): return nav.claudeLoginQuotas[login.configDir]?.hasTier ?? false case .codex: return nav.codexQuota?.hasTier ?? false case .antigravity: return nav.antigravityQuota?.hasTier ?? false case .pi: return nav.piQuota?.hasTier ?? false @@ -357,8 +381,8 @@ struct UsageView: View { @ViewBuilder private func tiers(for client: UsageClient) -> some View { switch client { - case .claude: - if let snapshot = nav.quota { + case .claude, .claudeLogin: + if let snapshot = nav.claudeQuota(for: client) { if let tier = snapshot.fiveHour { section("Current session") { tierRow(tier) } } @@ -528,10 +552,15 @@ struct UsageView: View { .padding(.horizontal, 6) } - // Subscription tier shown under the client name (e.g. "Max", "Plus"). + // Subscription tier shown under the client name (e.g. "Max", "Plus"). An + // extra Claude login leads with which one it is, since its title is the + // same "Claude" as the default row's. private func planLabel(for client: UsageClient) -> String? { switch client { case .claude: return nav.quota?.planType?.capitalized + case .claudeLogin(let login): + let plan = nav.claudeLoginQuotas[login.configDir]?.planType?.capitalized + return plan.map { "\(login.label) · \($0)" } ?? login.label case .codex: return nav.codexQuota?.planType?.capitalized case .antigravity: return nav.antigravityQuota?.planType?.capitalized case .pi: return nav.piQuota?.planType?.capitalized diff --git a/panel/UsageHistory.swift b/panel/UsageHistory.swift index 77d6e31..7370d8e 100644 --- a/panel/UsageHistory.swift +++ b/panel/UsageHistory.swift @@ -210,14 +210,18 @@ extension UsageEntry { // where the last complete line ended. final class UsageHistoryStore { - enum Source { + enum Source: Hashable { case claude + // Another Claude login's transcripts, which Claude Code writes under that + // login's own config dir rather than ~/.claude. + case claudeLogin(configDir: String) case codex case pi var defaultRoot: String { switch self { case .claude: return "\(NSHomeDirectory())/.claude/projects" + case .claudeLogin(let configDir): return "\(configDir)/projects" case .codex: return "\(NSHomeDirectory())/.codex/sessions" case .pi: return "\(NSHomeDirectory())/.pi/agent/sessions" } @@ -227,7 +231,7 @@ final class UsageHistoryStore { // JSON parsing. var marker: StaticString { switch self { - case .claude: return "\"assistant\"" + case .claude, .claudeLogin: return "\"assistant\"" case .codex: return "token_count" case .pi: return "\"assistant\"" } @@ -451,7 +455,7 @@ final class UsageHistoryStore { private static func parse(line: Data, source: Source) -> UsageEntry? { switch source { - case .claude: return parseClaude(line: line) + case .claude, .claudeLogin: return parseClaude(line: line) case .codex: return parseCodex(line: line) case .pi: return parsePi(line: line) } diff --git a/panel/WidgetQuota.swift b/panel/WidgetQuota.swift index b0a83fb..b2f275a 100644 --- a/panel/WidgetQuota.swift +++ b/panel/WidgetQuota.swift @@ -74,22 +74,24 @@ struct WidgetQuota: Equatable { return QuotaWindow.shortName(length) } + // `claude` is the selected Claude row's snapshot, the default login's or + // another's; the caller resolves which. static func make(client: UsageClient?, claude: QuotaSnapshot?, codex: CodexQuotaSnapshot?, antigravity: AntigravityQuotaSnapshot?, pi: PiQuotaSnapshot?) -> WidgetQuota { switch client { - case .claude: + case .claude, .claudeLogin: // A verified Ultra account has no session window: the usage API // reports `five_hour: null`. The week is then the window that blocks // you first, so it takes the inner ring, and with it the countdown // and the border, as Codex's weekly-only window already does. if claude?.fiveHour == nil, let week = claude?.sevenDay { - return WidgetQuota(client: .claude, short: week, long: nil, + return WidgetQuota(client: client, short: week, long: nil, shortLabel: ringLabel(week, fallback: "7d"), longLabel: "7d") } - return WidgetQuota(client: .claude, + return WidgetQuota(client: client, short: claude?.fiveHour, long: claude?.sevenDay, shortLabel: "5h", longLabel: "7d") case .codex: @@ -148,6 +150,9 @@ extension UsageClient { var widgetTag: String { switch self { case .claude: return "Claude" + // Which login, since "Claude" would read the same as the default one. + // Cut short: the legend slot is narrow. + case .claudeLogin(let login): return String(login.label.prefix(10)) case .codex: return "Codex" case .antigravity: return "Agy" case .pi: return "Pi"