Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 45 additions & 6 deletions Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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"])
Expand Down
69 changes: 68 additions & 1 deletion Tests/StackNudgePanelCoreTests/UsageAvailabilityTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
}
}
17 changes: 15 additions & 2 deletions Tests/StackNudgePanelCoreTests/WidgetQuotaTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down Expand Up @@ -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")
}
}
2 changes: 2 additions & 0 deletions docs/panel.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
24 changes: 20 additions & 4 deletions panel/ClaudeConfigDirs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<email>'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
Expand All @@ -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
}
Expand Down
18 changes: 16 additions & 2 deletions panel/ClaudeUsageCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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? {
Expand Down
8 changes: 5 additions & 3 deletions panel/CompactView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion panel/Companion/CompanionController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading