From 865bbe5e3fda671d6277c9d1cafd64dc8a73aaa1 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Thu, 19 Nov 2026 16:51:32 +0000 Subject: [PATCH 1/2] feat(usage): refresh every Claude login on the machine --- PRIVACY.md | 5 +- .../ClaudeCliQuotaProbeTests.swift | 2 +- .../ClaudeConfigDirsTests.swift | 128 ++++++++++++++++++ .../ClaudeUsageCacheTests.swift | 14 ++ docs/panel.md | 2 + panel/ClaudeCliQuotaProbe.swift | 56 ++++++-- panel/ClaudeConfigDirs.swift | 73 ++++++++++ panel/ClaudeUsageCache.swift | 16 ++- panel/Panel.swift | 29 ++++ 9 files changed, 309 insertions(+), 16 deletions(-) create mode 100644 Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift create mode 100644 panel/ClaudeConfigDirs.swift diff --git a/PRIVACY.md b/PRIVACY.md index 375f699..d1c1d33 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -57,7 +57,10 @@ Usage tracking (`STACKNUDGE_QUOTA_TRACKING`) reads your quota by shelling out to the `claude` and `codex` CLIs you already have installed, and by asking Antigravity's language server on `127.0.0.1`. The first two make their own calls to their own vendors, under those vendors' privacy policies, exactly as they -would if you ran them yourself. +would if you ran them yourself. If you sign in to Claude Code from more than one +config dir (any `~/.claude-*` directory with a login, or one listed in +`STACKNUDGE_CLAUDE_CONFIG_DIRS`), it runs `claude /usage` for each of those as +well, with `CLAUDE_CONFIG_DIR` set to that dir, at most every five minutes. ## What is never sent, anywhere diff --git a/Tests/StackNudgePanelCoreTests/ClaudeCliQuotaProbeTests.swift b/Tests/StackNudgePanelCoreTests/ClaudeCliQuotaProbeTests.swift index 5fe316e..c9a2e15 100644 --- a/Tests/StackNudgePanelCoreTests/ClaudeCliQuotaProbeTests.swift +++ b/Tests/StackNudgePanelCoreTests/ClaudeCliQuotaProbeTests.swift @@ -271,7 +271,7 @@ final class ClaudeCliQuotaProbeTests: XCTestCase { // Claude replaces BOTH '/' and '.' with '-' (double dash for the // dot-prefix). The probe directory must match that encoding exactly, // or the cleanup-by-path will silently miss. - let dir = ClaudeCliQuotaProbe.probeSessionsDir + let dir = ClaudeCliQuotaProbe.probeSessionsDir() let encoded = ClaudeCliQuotaProbe.probeCwd .replacingOccurrences(of: "/", with: "-") .replacingOccurrences(of: ".", with: "-") diff --git a/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift new file mode 100644 index 0000000..a0f3323 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift @@ -0,0 +1,128 @@ +import XCTest + +@testable import StackNudgePanelCore + +// Which other Claude logins get probed. A dir missed here is an account whose +// usage nothing ever refreshes; a dir wrongly included is a `claude` spawned +// for nothing on every poll, or the default account counted twice. +final class ClaudeConfigDirsTests: XCTestCase { + + private func makeHome() throws -> String { + let home = NSTemporaryDirectory() + "claude-config-dirs-\(UUID().uuidString)" + try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(atPath: home) } + return (home as NSString).resolvingSymlinksInPath + } + + @discardableResult + private func makeDir(_ path: String, account: String?, organization: String? = nil) throws -> String { + try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true) + let org = organization.map { #","organizationUuid":"\#($0)""# } ?? "" + let login = account.map { #","oauthAccount":{"accountUuid":"\#($0)"\#(org)}"# } ?? "" + try Data(#"{"numStartups":1\#(login)}"#.utf8) + .write(to: URL(fileURLWithPath: "\(path)/.claude.json")) + return path + } + + func testFindsEverySignedInClaudeDashDirInNameOrder() throws { + let home = try makeHome() + try makeDir("\(home)/.claude-work", account: "work") + try makeDir("\(home)/.claude-org-publisher", account: "org") + let actual = ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: "me") + XCTAssertEqual(actual, [ + .init(path: "\(home)/.claude-org-publisher", account: "org"), + .init(path: "\(home)/.claude-work", account: "work"), + ]) + } + + func testSkipsADirWithNoLogin() throws { + let home = try makeHome() + try makeDir("\(home)/.claude-empty", account: nil) + try FileManager.default.createDirectory(atPath: "\(home)/.claude-nofile", + withIntermediateDirectories: true) + XCTAssertEqual(ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: nil), []) + } + + // ~/.claude.json.backup.* and friends sit beside the dirs; only dirs count. + func testIgnoresFilesThatShareThePrefix() throws { + let home = try makeHome() + try Data("{}".utf8).write(to: URL(fileURLWithPath: "\(home)/.claude-notes.json")) + XCTAssertEqual(ClaudeConfigDirs.candidates(home: home, setting: nil), []) + } + + // The default login is probed already; a second dir signed in to the same + // account would only repeat its numbers. Two dirs on one account likewise. + func testSkipsADirSignedInToAnAccountAlreadyCounted() throws { + let home = try makeHome() + try makeDir("\(home)/.claude-a", account: "me") + try makeDir("\(home)/.claude-b", account: "other") + try makeDir("\(home)/.claude-c", account: "other") + let actual = ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: "me") + XCTAssertEqual(actual.map(\.path), ["\(home)/.claude-b"]) + } + + // The case that started this: your own plan by default and a team seat in + // another dir, both signed in as you. + func testKeepsTheSameAccountSignedInToAnotherOrganization() throws { + let home = try makeHome() + try makeDir("\(home)/.claude-team", account: "me", organization: "team") + let actual = ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: "me/personal") + XCTAssertEqual(actual, [.init(path: "\(home)/.claude-team", account: "me/team")]) + } + + func testReadsTheSettingFirstAndOnlyOnce() throws { + let home = try makeHome() + let elsewhere = try makeDir("\(home)/accounts/work", account: "work") + try makeDir("\(home)/.claude-x", account: "x") + let actual = ClaudeConfigDirs.discover( + home: home, setting: "~/accounts/work, ~/.claude-x", defaultAccount: nil) + XCTAssertEqual(actual.map(\.path), [elsewhere, "\(home)/.claude-x"]) + } + + func testNeverProbesTheDefaultDirAsAnotherLogin() throws { + let home = try makeHome() + try makeDir("\(home)/.claude", account: "inside") + XCTAssertEqual(ClaudeConfigDirs.discover(home: home, setting: "~/.claude", + defaultAccount: nil), []) + } + + func testExpandsTildeAndDropsRelativeEntries() { + XCTAssertEqual(ClaudeConfigDirs.entries(" ~/.claude-work ,relative, /abs/dir,,~", home: "/h"), + ["/h/.claude-work", "/abs/dir", "/h"]) + XCTAssertEqual(ClaudeConfigDirs.entries(nil, home: "/h"), []) + } + + // MARK: - Probing another dir + + func testTheDefaultLoginInheritsTheEnvironmentUnchanged() { + XCTAssertNil(ClaudeCliQuotaProbe.environment(configDir: nil, inherited: ["PATH": "/bin"])) + } + + func testAnotherLoginRunsWithItsConfigDirAndKeepsTheRest() { + let actual = ClaudeCliQuotaProbe.environment(configDir: "/h/.claude-work", + inherited: ["PATH": "/bin", "HOME": "/h"]) + XCTAssertEqual(actual, ["PATH": "/bin", "HOME": "/h", "CLAUDE_CONFIG_DIR": "/h/.claude-work"]) + } + + func testReadsAnotherLoginsUsageFromItsOwnDir() { + XCTAssertEqual(ClaudeUsageCache.path(configDir: "/h/.claude-work"), "/h/.claude-work/.claude.json") + XCTAssertEqual(ClaudeUsageCache.path(configDir: nil), ClaudeUsageCache.path) + } + + // The probe's own rollout goes to the projects dir of the login it ran as, + // so the scrub has to look there or every extra-account probe leaves a file. + func testScrubsAnotherLoginsRolloutFromItsOwnProjectsDir() throws { + let home = try makeHome() + let configDir = "\(home)/.claude-work" + let dir = ClaudeCliQuotaProbe.probeSessionsDir(configDir: configDir) + XCTAssertTrue(dir.hasPrefix("\(configDir)/projects/")) + try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) + let session = "0f0e5c7a-1111-2222-3333-444455556666" + let file = "\(dir)/\(session).jsonl" + try Data().write(to: URL(fileURLWithPath: file)) + + ClaudeCliQuotaProbe.removeSessionFile(session, configDir: configDir) + + XCTAssertFalse(FileManager.default.fileExists(atPath: file)) + } +} diff --git a/Tests/StackNudgePanelCoreTests/ClaudeUsageCacheTests.swift b/Tests/StackNudgePanelCoreTests/ClaudeUsageCacheTests.swift index 3d3666b..d692317 100644 --- a/Tests/StackNudgePanelCoreTests/ClaudeUsageCacheTests.swift +++ b/Tests/StackNudgePanelCoreTests/ClaudeUsageCacheTests.swift @@ -129,6 +129,20 @@ final class ClaudeUsageCacheTests: XCTestCase { XCTAssertEqual(ClaudeUsageCache.currentAccount(path: path), owner) } + // Your own plan and a team seat share an accountUuid; the quota is the seat's, + // so signing in to the other one has to read as a different login. + func testTellsTwoOrganizationsOfOneAccountApart() throws { + func login(_ organization: String) throws -> String? { + let path = try writeFixture(Data(#"{"oauthAccount":{"accountUuid":"\#(owner)","organizationUuid":"\#(organization)"}}"#.utf8)) + return ClaudeUsageCache.currentAccount(path: path) + } + let personal = try login("org-personal") + let team = try login("org-team") + XCTAssertEqual(personal, "\(owner)/org-personal") + XCTAssertNotEqual(personal, team) + XCTAssertTrue(ClaudeCliQuotaProbe.isAccountSwitch(from: personal, to: team)) + } + func testReadsNoAccountWhenLoggedOutOrTheFileIsAbsent() throws { let path = try writeFixture(json(loggedIn: nil)) XCTAssertNil(ClaudeUsageCache.currentAccount(path: path)) diff --git a/docs/panel.md b/docs/panel.md index d463731..b64a372 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -98,6 +98,8 @@ Reachable from the tab strip or `Cmd+3`. Renders your Claude Code subscription q Bars are color-coded: green below 50%, yellow 50–80%, red 80%+. Reset times shown per tier. +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: every `~/.claude-*` directory signed in to a different account or organization, plus any dir listed comma-separated in `STACKNUDGE_CLAUDE_CONFIG_DIRS` in `~/.stack-nudge/config`. 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 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/ClaudeCliQuotaProbe.swift b/panel/ClaudeCliQuotaProbe.swift index c2107c1..6692871 100644 --- a/panel/ClaudeCliQuotaProbe.swift +++ b/panel/ClaudeCliQuotaProbe.swift @@ -18,6 +18,18 @@ import Foundation // ok — at least one Current bucket line parsed. final class ClaudeCliQuotaProbe { + // The account's config dir, or nil for the default login. Another dir is + // probed by running the same `claude` with CLAUDE_CONFIG_DIR pointing at it, + // which is how Claude Code itself is told to use that login. + let configDir: String? + private let cacheMaxAge: TimeInterval + + init(configDir: String? = nil, cacheMaxAge: TimeInterval = ClaudeCliQuotaProbe.cacheMaxAge) { + self.configDir = configDir + self.cacheMaxAge = cacheMaxAge + probeQueue = DispatchQueue(label: "stack-nudge.claude-cli-quota\(configDir.map { "." + $0 } ?? "")") + } + // Main-queue only (mirrors QuotaProbe's threading model). private(set) var lastProbeFailed = false // True when the last fetch found no `claude` on PATH, as distinct from the @@ -49,6 +61,10 @@ final class ClaudeCliQuotaProbe { // 6%/62% against the CLI's 9%/63%. Widening this buys a spawn back in // exchange for numbers that are wrong during active use. static let cacheMaxAge: TimeInterval = 60 + // For a login other than the default one. Each spawn is a few seconds of a + // whole `claude` starting up, and every extra account pays it, so they + // refresh at most this often however fast the panel is polling. + static let otherAccountCacheMaxAge: TimeInterval = 300 // When the snapshot was measured: Date() for a CLI read, the cache's // `fetchedAt` when it came from disk. The panel dates the Usage tab from @@ -61,7 +77,7 @@ final class ClaudeCliQuotaProbe { } // CLI shell-out runs off-main; completion fires on main. - private let probeQueue = DispatchQueue(label: "stack-nudge.claude-cli-quota") + private let probeQueue: DispatchQueue func fetch(completion: @escaping (QuotaSnapshot?) -> Void) { // Reset before the early-return gates so a rate-limited tick reports the @@ -84,9 +100,13 @@ final class ClaudeCliQuotaProbe { // Captured on main like the ones above; the latch is written back on main // in the completion, matching this class's threading model. let strictSupported = strictMcpConfigSupported + let configDir = configDir + let cacheFile = ClaudeUsageCache.path(configDir: configDir) + let cacheMaxAge = cacheMaxAge + let env = Self.environment(configDir: configDir) probeQueue.async { [weak self] in - let account = ClaudeUsageCache.currentAccount() + let account = ClaudeUsageCache.currentAccount(path: cacheFile) let switched = Self.isAccountSwitch(from: priorAccount, to: account) // The plan is fetched until the CLI answers and then not again, so a // switch has to refetch it or the new account keeps the old one's plan. @@ -95,7 +115,7 @@ final class ClaudeCliQuotaProbe { var subscriptionAnswered = false if needsSubscriptionFetch { let status = Self.parseAuthStatus(ProcessOutput.read( - path, ["auth", "status", "--json"], timeout: 5, cwd: Self.probeCwd)) + path, ["auth", "status", "--json"], timeout: 5, cwd: Self.probeCwd, env: env)) subscriptionAnswered = status.answered if let plan = status.plan { fetchedPlan = plan } } @@ -104,7 +124,7 @@ final class ClaudeCliQuotaProbe { var strictRejected = false var measuredAt = Date() let result: ParseResult - if let cached = ClaudeUsageCache.read(maxAge: Self.cacheMaxAge) { + if let cached = ClaudeUsageCache.read(maxAge: cacheMaxAge, path: cacheFile) { result = .ok(cached.snapshot) measuredAt = cached.fetchedAt } else { @@ -118,7 +138,7 @@ final class ClaudeCliQuotaProbe { // edge. runUsage drops the flag and retries once if this CLI is too // old to know it (see strictMcpConfigSupported). let (raw, rejected) = Self.runUsage(strictMcpConfig: strictSupported) { - ProcessOutput.read(path, $0, timeout: 20, cwd: Self.probeCwd) + ProcessOutput.read(path, $0, timeout: 20, cwd: Self.probeCwd, env: env) } strictRejected = rejected result = Self.parseEnvelope(raw) @@ -129,7 +149,7 @@ final class ClaudeCliQuotaProbe { // cwd above means we know the exact directory; this scrubs the // single file the probe just produced. if let sid = Self.extractSessionId(raw) { - Self.removeSessionFile(sid) + Self.removeSessionFile(sid, configDir: configDir) } } @@ -141,7 +161,7 @@ final class ClaudeCliQuotaProbe { var fallback: ClaudeUsageCache.Reading? switch result { case .ok: break - case .softFail, .hardFail: fallback = ClaudeUsageCache.read(maxAge: .infinity) + case .softFail, .hardFail: fallback = ClaudeUsageCache.read(maxAge: .infinity, path: cacheFile) } DispatchQueue.main.async { @@ -227,6 +247,17 @@ final class ClaudeCliQuotaProbe { // MARK: - Invocation + // nil inherits ours unchanged, which is what the default login has always + // run with. Otherwise ours plus CLAUDE_CONFIG_DIR: ProcessOutput replaces the + // child's environment rather than merging, so PATH and HOME come along. + static func environment(configDir: String?, + inherited: [String: String] = ProcessInfo.processInfo.environment) -> [String: String]? { + guard let configDir else { return nil } + var env = inherited + env["CLAUDE_CONFIG_DIR"] = configDir + return env + } + // Args for `claude --print /usage`. --strict-mcp-config loads zero MCP // servers, which the intercept never needs — see the call site in fetch(). static func usageArgs(strictMcpConfig: Bool) -> [String] { @@ -271,12 +302,13 @@ final class ClaudeCliQuotaProbe { // Claude derives the projects-subdirectory name by replacing every "/" // AND every "." in the cwd with "-". So "/Users/me/.stack-nudge" becomes - // "-Users-me--stack-nudge" (double dash for the dot-prefix). - static var probeSessionsDir: String { + // "-Users-me--stack-nudge" (double dash for the dot-prefix). The projects + // dir belongs to the config dir, so another login's rollouts land under it. + static func probeSessionsDir(configDir: String? = nil) -> String { let encoded = probeCwd .replacingOccurrences(of: "/", with: "-") .replacingOccurrences(of: ".", with: "-") - return "\(NSHomeDirectory())/.claude/projects/\(encoded)" + return "\(configDir ?? "\(NSHomeDirectory())/.claude")/projects/\(encoded)" } static func extractSessionId(_ raw: String?) -> String? { @@ -287,13 +319,13 @@ final class ClaudeCliQuotaProbe { return obj["session_id"] as? String } - static func removeSessionFile(_ sessionId: String) { + static func removeSessionFile(_ sessionId: String, configDir: String? = nil) { // Guard against a malformed session_id that could escape the // intended directory — only accept the UUID shape Claude actually // emits (lower-hex + hyphens, no separators). guard sessionId.range(of: "^[0-9a-f-]+$", options: .regularExpression) != nil else { return } - let path = "\(probeSessionsDir)/\(sessionId).jsonl" + let path = "\(probeSessionsDir(configDir: configDir))/\(sessionId).jsonl" try? FileManager.default.removeItem(atPath: path) } diff --git a/panel/ClaudeConfigDirs.swift b/panel/ClaudeConfigDirs.swift new file mode 100644 index 0000000..ce5af95 --- /dev/null +++ b/panel/ClaudeConfigDirs.swift @@ -0,0 +1,73 @@ +import Foundation + +// The Claude Code config dirs on this machine besides the default one. Claude +// Code keeps a login per config dir: run with CLAUDE_CONFIG_DIR=~/.claude-work +// it reads ~/.claude-work/.claude.json and that dir's own Keychain entry, so a +// second account lives in its own dir and the default `claude /usage` never +// sees it. +// +// Found two ways: every ~/.claude-* directory with a signed-in .claude.json, +// which is how people name them, and STACKNUDGE_CLAUDE_CONFIG_DIRS for one kept +// anywhere else. Only dirs with a login count; a dir someone made and never +// signed in from has no usage to read. +enum ClaudeConfigDirs { + + static let configKey = "STACKNUDGE_CLAUDE_CONFIG_DIRS" + + struct Dir: Equatable { + let path: String + // ClaudeUsageCache.currentAccount: the account and its organization. + let account: String + } + + // The default login is passed in so a dir signed in to the same account and + // organization isn't probed twice: it would only repeat the default's + // numbers. The same account in another organization is another seat with + // its own quota, and counts. + static func discover(home: String = NSHomeDirectory(), + setting: String? = ConfigFile.read()[configKey], + defaultAccount: String?, + fileManager: FileManager = .default) -> [Dir] { + var seenPaths: Set = [] + var seenAccounts: Set = defaultAccount.map { [$0] } ?? [] + var found: [Dir] = [] + let defaultDir = ("\(home)/.claude" as NSString).resolvingSymlinksInPath + for candidate in candidates(home: home, setting: setting, fileManager: fileManager) { + let path = (candidate as NSString).resolvingSymlinksInPath + guard path != defaultDir, seenPaths.insert(path).inserted, + let account = ClaudeUsageCache.currentAccount( + path: ClaudeUsageCache.path(configDir: path)), + seenAccounts.insert(account).inserted + else { continue } + found.append(Dir(path: path, account: account)) + } + return found + } + + // The setting's entries first, in the order written, then ~/.claude-* by + // name, so the order rows appear in doesn't move between polls. + static func candidates(home: String, setting: String?, + fileManager: FileManager = .default) -> [String] { + var paths = entries(setting, home: home) + let names = (try? fileManager.contentsOfDirectory(atPath: home)) ?? [] + for name in names.sorted() where name.hasPrefix(".claude-") { + var isDirectory: ObjCBool = false + let path = "\(home)/\(name)" + if fileManager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue { + paths.append(path) + } + } + return paths + } + + // Comma-separated, `~` expanded. Anything else relative is dropped: it would + // resolve against whatever directory the app happened to launch from. + static func entries(_ setting: String?, home: String) -> [String] { + (setting ?? "").split(separator: ",").compactMap { raw in + let entry = raw.trimmingCharacters(in: .whitespaces) + if entry == "~" { return home } + if entry.hasPrefix("~/") { return home + entry.dropFirst() } + return entry.hasPrefix("/") ? entry : nil + } + } +} diff --git a/panel/ClaudeUsageCache.swift b/panel/ClaudeUsageCache.swift index 7fcc9e2..441ea16 100644 --- a/panel/ClaudeUsageCache.swift +++ b/panel/ClaudeUsageCache.swift @@ -17,6 +17,12 @@ enum ClaudeUsageCache { static var path: String { "\(NSHomeDirectory())/.claude.json" } + // Under CLAUDE_CONFIG_DIR the file moves into that dir; nil is the default + // login, whose file sits beside ~/.claude rather than in it. + static func path(configDir: String?) -> String { + configDir.map { "\($0)/.claude.json" } ?? path + } + // `maxAge` is the caller's poll interval: within it the cache is no staler // than the value a fresh shell-out would have returned. static func read(maxAge: TimeInterval, now: Date = Date(), @@ -38,11 +44,17 @@ enum ClaudeUsageCache { // The logged-in account, so the probe can tell when the user switches login // and drop numbers that belong to the previous one. Read with no freshness // gate: the login is current however old the usage cache beside it is. + // + // The account and the organization together: one person signed in to their + // 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? { guard let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), - let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let account = account(in: root) else { return nil } - return account(in: root) + let organization = (root["oauthAccount"] as? [String: Any])?["organizationUuid"] as? String + return organization.map { "\(account)/\($0)" } ?? account } private static func account(in root: [String: Any]) -> String? { diff --git a/panel/Panel.swift b/panel/Panel.swift index 28c760d..68334e2 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1197,6 +1197,9 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, private var updateChecker: UpdateChecker? private var updater: Updater? private let claudeCliQuotaProbe = ClaudeCliQuotaProbe() + // Claude logins other than the default one, by config dir. See + // refreshOtherClaudeAccounts. + private var otherClaudeProbes: [String: ClaudeCliQuotaProbe] = [:] private let codexQuotaProbe = CodexQuotaProbe() private let antigravityUsageProbe = AntigravityUsageProbe() // Lazy because it shares the nav's history store rather than opening its @@ -2408,6 +2411,32 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, } } refreshPiUsage() + refreshOtherClaudeAccounts() + } + + // 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. + private func refreshOtherClaudeAccounts() { + // Discovery reads a .claude.json per dir, hundreds of KB each, so off main. + DispatchQueue.global(qos: .utility).async { [weak self] in + let dirs = ClaudeConfigDirs.discover(defaultAccount: ClaudeUsageCache.currentAccount()) + DispatchQueue.main.async { + guard let self, 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 } + } + } + } } // Pi budget, read from pi's own transcripts with no network and no CLI. From c0e18ed45ae29b775cd4df61995963ff907f4b80 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Thu, 19 Nov 2026 19:23:02 +0000 Subject: [PATCH 2/2] feat(usage): find claude logins by .claude.json, not dir name --- PRIVACY.md | 11 +- .../ClaudeConfigDirsTests.swift | 87 ++++++++--- docs/panel.md | 2 +- panel/ClaudeConfigDirs.swift | 142 ++++++++++++++---- panel/Panel.swift | 20 ++- 5 files changed, 205 insertions(+), 57 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index d1c1d33..ea227cc 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -58,9 +58,14 @@ the `claude` and `codex` CLIs you already have installed, and by asking Antigravity's language server on `127.0.0.1`. The first two make their own calls to their own vendors, under those vendors' privacy policies, exactly as they would if you ran them yourself. If you sign in to Claude Code from more than one -config dir (any `~/.claude-*` directory with a login, or one listed in -`STACKNUDGE_CLAUDE_CONFIG_DIRS`), it runs `claude /usage` for each of those as -well, with `CLAUDE_CONFIG_DIR` set to that dir, at most every five minutes. +config dir, it runs `claude /usage` for each of those as well, with +`CLAUDE_CONFIG_DIR` set to that dir, at most every five minutes. To find them it +looks for a `.claude.json` up to two levels under your home folder (never inside +Desktop, Documents, Downloads, Library or the media folders), reads +`CLAUDE_CONFIG_DIR` from the environment of any `claude` you have running, and +reads `STACKNUDGE_CLAUDE_CONFIG_DIRS`. Dirs found from a running `claude` are +listed in `~/.stack-nudge/claude-config-dirs`, and nothing about them leaves your +Mac. ## What is never sent, anywhere diff --git a/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift index a0f3323..14690de 100644 --- a/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift +++ b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift @@ -24,30 +24,48 @@ final class ClaudeConfigDirsTests: XCTestCase { return path } - func testFindsEverySignedInClaudeDashDirInNameOrder() throws { + private func discover(_ home: String, setting: String? = nil, + defaultAccount: String?) -> [ClaudeConfigDirs.Dir] { + ClaudeConfigDirs.discover(home: home, setting: setting, + found: ClaudeConfigDirs.scan(home: home), + defaultAccount: defaultAccount) + } + + // Named however anyone likes: the .claude.json is what marks one. + func testFindsEverySignedInDirWhateverItIsCalled() throws { let home = try makeHome() - try makeDir("\(home)/.claude-work", account: "work") try makeDir("\(home)/.claude-org-publisher", account: "org") - let actual = ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: "me") + 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)/.claude-work", account: "work"), + .init(path: "\(home)/accounts/side", account: "side"), + .init(path: "\(home)/work-claude", account: "work"), ]) } + func testScansTwoLevelsDownAndNoFurther() throws { + let home = try makeHome() + try makeDir("\(home)/a/b/c", account: "deep") + XCTAssertEqual(ClaudeConfigDirs.scan(home: home), []) + } + + // Looking inside Documents and friends raises a macOS permission prompt. + func testNeverLooksInsideTheFoldersMacOSGuards() throws { + let home = try makeHome() + try makeDir("\(home)/Documents/claude", account: "docs") + try makeDir("\(home)/Library/claude", account: "lib") + try makeDir("\(home)/code/node_modules", account: "pkg") + XCTAssertEqual(ClaudeConfigDirs.scan(home: home), []) + } + func testSkipsADirWithNoLogin() throws { let home = try makeHome() try makeDir("\(home)/.claude-empty", account: nil) try FileManager.default.createDirectory(atPath: "\(home)/.claude-nofile", withIntermediateDirectories: true) - XCTAssertEqual(ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: nil), []) - } - - // ~/.claude.json.backup.* and friends sit beside the dirs; only dirs count. - func testIgnoresFilesThatShareThePrefix() throws { - let home = try makeHome() - try Data("{}".utf8).write(to: URL(fileURLWithPath: "\(home)/.claude-notes.json")) - XCTAssertEqual(ClaudeConfigDirs.candidates(home: home, setting: nil), []) + XCTAssertEqual(discover(home, defaultAccount: nil), []) } // The default login is probed already; a second dir signed in to the same @@ -57,8 +75,7 @@ final class ClaudeConfigDirsTests: XCTestCase { try makeDir("\(home)/.claude-a", account: "me") try makeDir("\(home)/.claude-b", account: "other") try makeDir("\(home)/.claude-c", account: "other") - let actual = ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: "me") - XCTAssertEqual(actual.map(\.path), ["\(home)/.claude-b"]) + XCTAssertEqual(discover(home, defaultAccount: "me").map(\.path), ["\(home)/.claude-b"]) } // The case that started this: your own plan by default and a team seat in @@ -66,26 +83,56 @@ final class ClaudeConfigDirsTests: XCTestCase { func testKeepsTheSameAccountSignedInToAnotherOrganization() throws { let home = try makeHome() try makeDir("\(home)/.claude-team", account: "me", organization: "team") - let actual = ClaudeConfigDirs.discover(home: home, setting: nil, defaultAccount: "me/personal") + let actual = discover(home, defaultAccount: "me/personal") XCTAssertEqual(actual, [.init(path: "\(home)/.claude-team", account: "me/team")]) } func testReadsTheSettingFirstAndOnlyOnce() throws { let home = try makeHome() - let elsewhere = try makeDir("\(home)/accounts/work", account: "work") + let elsewhere = try makeDir("\(home)/Documents/work", account: "work") try makeDir("\(home)/.claude-x", account: "x") - let actual = ClaudeConfigDirs.discover( - home: home, setting: "~/accounts/work, ~/.claude-x", defaultAccount: nil) + let actual = discover(home, setting: "~/Documents/work, ~/.claude-x", defaultAccount: nil) XCTAssertEqual(actual.map(\.path), [elsewhere, "\(home)/.claude-x"]) } - func testNeverProbesTheDefaultDirAsAnotherLogin() throws { + // Home holds the default login's .claude.json, and ~/.claude is its dir. + func testNeverProbesTheDefaultLoginAsAnotherOne() throws { let home = try makeHome() + try makeDir(home, account: "me") try makeDir("\(home)/.claude", account: "inside") - XCTAssertEqual(ClaudeConfigDirs.discover(home: home, setting: "~/.claude", + XCTAssertEqual(ClaudeConfigDirs.discover(home: home, setting: "~, ~/.claude", + found: [home, "\(home)/.claude"], defaultAccount: nil), []) } + // MARK: - Running and remembered + + func testFindsTheClaudeProcessesAndNothingElse() { + let ps = """ + 101 /Users/me/.local/bin/claude --resume abc + 102 claude + 103 /usr/bin/vim notes.md + 104 /Users/me/.local/bin/claude daemon run + 105 /bin/zsh -c claude-ish + """ + XCTAssertEqual(ClaudeConfigDirs.claudePids(psOutput: ps), [101, 102]) + } + + // The point of remembering: a dir found only because a session was using it + // keeps its row after the session ends. + func testRemembersARunningDirUntilItsDeleted() throws { + let home = try makeHome() + let file = "\(home)/remembered" + let work = try makeDir("\(home)/anywhere/work", account: "work") + ClaudeConfigDirs.remember([work], path: file) + ClaudeConfigDirs.remember([], path: file) + XCTAssertEqual(ClaudeConfigDirs.remembered(path: file), [work]) + + try FileManager.default.removeItem(atPath: work) + ClaudeConfigDirs.remember([], path: file) + XCTAssertEqual(ClaudeConfigDirs.remembered(path: file), []) + } + func testExpandsTildeAndDropsRelativeEntries() { XCTAssertEqual(ClaudeConfigDirs.entries(" ~/.claude-work ,relative, /abs/dir,,~", home: "/h"), ["/h/.claude-work", "/abs/dir", "/h"]) diff --git a/docs/panel.md b/docs/panel.md index b64a372..39b1409 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -98,7 +98,7 @@ Reachable from the tab strip or `Cmd+3`. Renders your Claude Code subscription q Bars are color-coded: green below 50%, yellow 50–80%, red 80%+. Reset times shown per tier. -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: every `~/.claude-*` directory signed in to a different account or organization, plus any dir listed comma-separated in `STACKNUDGE_CLAUDE_CONFIG_DIRS` in `~/.stack-nudge/config`. 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. +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 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. diff --git a/panel/ClaudeConfigDirs.swift b/panel/ClaudeConfigDirs.swift index ce5af95..5078cad 100644 --- a/panel/ClaudeConfigDirs.swift +++ b/panel/ClaudeConfigDirs.swift @@ -1,19 +1,31 @@ import Foundation // The Claude Code config dirs on this machine besides the default one. Claude -// Code keeps a login per config dir: run with CLAUDE_CONFIG_DIR=~/.claude-work -// it reads ~/.claude-work/.claude.json and that dir's own Keychain entry, so a -// second account lives in its own dir and the default `claude /usage` never -// sees it. +// Code keeps a login per config dir: run with CLAUDE_CONFIG_DIR= it reads +// /.claude.json and that dir's own Keychain entry, so a second account +// lives in its own dir and the default `claude /usage` never sees it. // -// Found two ways: every ~/.claude-* directory with a signed-in .claude.json, -// which is how people name them, and STACKNUDGE_CLAUDE_CONFIG_DIRS for one kept -// anywhere else. Only dirs with a login count; a dir someone made and never -// signed in from has no usage to read. +// A dir can be called anything and live anywhere, so nothing here goes by its +// name. What every one has is a .claude.json with a login in it, and three +// sources look for that: +// - scan: the dirs under home, two levels down, every so often; +// - running: CLAUDE_CONFIG_DIR in the environment of any `claude` running +// now, which finds a dir wherever it is, and is remembered so the login +// keeps its row once that session ends; +// - STACKNUDGE_CLAUDE_CONFIG_DIRS, for a dir neither would find. +// Only dirs with a login count; a dir someone made and never signed in from +// has no usage to read. enum ClaudeConfigDirs { static let configKey = "STACKNUDGE_CLAUDE_CONFIG_DIRS" + // Dirs seen in a running `claude`'s environment, one path per line. + static let rememberedPath = "\(NSHomeDirectory())/.stack-nudge/claude-config-dirs" + + // A config dir is made by hand and rarely moves, so the scan runs at launch + // and then hourly rather than on every poll. + static let scanInterval: TimeInterval = 3600 + struct Dir: Equatable { let path: String // ClaudeUsageCache.currentAccount: the account and its organization. @@ -26,38 +38,30 @@ enum ClaudeConfigDirs { // its own quota, and counts. static func discover(home: String = NSHomeDirectory(), setting: String? = ConfigFile.read()[configKey], - defaultAccount: String?, - fileManager: FileManager = .default) -> [Dir] { + found: [String], + defaultAccount: String?) -> [Dir] { var seenPaths: Set = [] var seenAccounts: Set = defaultAccount.map { [$0] } ?? [] - var found: [Dir] = [] - let defaultDir = ("\(home)/.claude" as NSString).resolvingSymlinksInPath - for candidate in candidates(home: home, setting: setting, fileManager: fileManager) { + var dirs: [Dir] = [] + // Home holds the default login's .claude.json, so it would otherwise + // read as one more signed-in dir. + let defaults = Set([home, "\(home)/.claude"].map { ($0 as NSString).resolvingSymlinksInPath }) + for candidate in candidates(home: home, setting: setting, found: found) { let path = (candidate as NSString).resolvingSymlinksInPath - guard path != defaultDir, seenPaths.insert(path).inserted, + guard !defaults.contains(path), seenPaths.insert(path).inserted, let account = ClaudeUsageCache.currentAccount( path: ClaudeUsageCache.path(configDir: path)), seenAccounts.insert(account).inserted else { continue } - found.append(Dir(path: path, account: account)) + dirs.append(Dir(path: path, account: account)) } - return found + return dirs } - // The setting's entries first, in the order written, then ~/.claude-* by - // name, so the order rows appear in doesn't move between polls. - static func candidates(home: String, setting: String?, - fileManager: FileManager = .default) -> [String] { - var paths = entries(setting, home: home) - let names = (try? fileManager.contentsOfDirectory(atPath: home)) ?? [] - for name in names.sorted() where name.hasPrefix(".claude-") { - var isDirectory: ObjCBool = false - let path = "\(home)/\(name)" - if fileManager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue { - paths.append(path) - } - } - return paths + // The setting's entries first, in the order written, then everything else + // by path, so the order rows appear in doesn't move as sessions come and go. + static func candidates(home: String, setting: String?, found: [String]) -> [String] { + entries(setting, home: home) + Set(found).sorted() } // Comma-separated, `~` expanded. Anything else relative is dropped: it would @@ -70,4 +74,82 @@ enum ClaudeConfigDirs { return entry.hasPrefix("/") ? entry : nil } } + + // MARK: - Scan + + // Never listed. The folders macOS guards (Desktop, Documents, Downloads and + // the media ones) would each raise a permission prompt the moment we looked + // inside; Library and the package and VCS dirs are large and never hold a + // login. A dir in any of them is found once it runs, or from the setting. + static let skippedNames: Set = [ + "Desktop", "Documents", "Downloads", "Movies", "Music", "Pictures", + "Library", ".Trash", "node_modules", ".git", + ] + + // Every dir up to two levels under home holding a .claude.json: home's own + // children (~/.claude-work) and theirs (~/accounts/work). It only looks for + // the file; whether there's a login in it is discover's question. + static func scan(home: String = NSHomeDirectory(), + fileManager: FileManager = .default) -> [String] { + var found: [String] = [] + var level = [home] + for _ in 0..<2 { + var next: [String] = [] + for parent in level { + let names = (try? fileManager.contentsOfDirectory(atPath: parent)) ?? [] + for name in names where !skippedNames.contains(name) { + let path = "\(parent)/\(name)" + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory), + isDirectory.boolValue + else { continue } + if fileManager.fileExists(atPath: "\(path)/.claude.json") { found.append(path) } + next.append(path) + } + } + level = next + } + return found + } + + // MARK: - Running + + // CLAUDE_CONFIG_DIR of every `claude` running now, from one `ps` for the + // pids and one `ps eww` for their environments. Only our own processes' + // environments are readable, which are the only ones we want. + static func running() -> [String] { + let table = ProcessOutput.read("/bin/ps", ["-axo", "pid=,args="], timeout: 2) ?? "" + let values = EnvVarTerminalIntegration.envValueMap( + forPids: claudePids(psOutput: table), envVar: "CLAUDE_CONFIG_DIR") + return Set(values.values).filter { $0.hasPrefix("/") }.sorted() + } + + // Pids of the `claude` lines in `ps -axo pid=,args=` output, by + // SessionStore's definition of one. + static func claudePids(psOutput: String) -> [Int] { + psOutput.split(separator: "\n").compactMap { raw in + let line = raw.trimmingCharacters(in: .whitespaces) + guard let space = line.firstIndex(of: " "), let pid = Int(line[.. [String] { + let text = (try? String(contentsOfFile: path, encoding: .utf8)) ?? "" + return text.split(separator: "\n").map(String.init).filter { $0.hasPrefix("/") } + } + + // Adds what's running to what was remembered, and drops a dir that's been + // deleted. One that's only signed out stays: signing back in brings its row + // back without waiting for that session to run again. + static func remember(_ running: [String], path: String = rememberedPath, + fileManager: FileManager = .default) { + let previous = remembered(path: path) + let kept = Set(previous + running).filter { fileManager.fileExists(atPath: $0) }.sorted() + guard kept != previous else { return } + try? (kept.joined(separator: "\n") + "\n").write(toFile: path, atomically: true, encoding: .utf8) + } } diff --git a/panel/Panel.swift b/panel/Panel.swift index 68334e2..095ec2e 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1200,6 +1200,9 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // Claude logins other than the default one, by config dir. See // refreshOtherClaudeAccounts. private var otherClaudeProbes: [String: ClaudeCliQuotaProbe] = [:] + // The last ClaudeConfigDirs.scan, kept between polls since it only reruns + // every scanInterval. + private var claudeConfigDirScan: (at: Date, dirs: [String])? private let codexQuotaProbe = CodexQuotaProbe() private let antigravityUsageProbe = AntigravityUsageProbe() // Lazy because it shares the nav's history store rather than opening its @@ -2422,11 +2425,22 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, // anything else reading usage on this machine, the claude-usage extension // included, picks it up. private func refreshOtherClaudeAccounts() { - // Discovery reads a .claude.json per dir, hundreds of KB each, so off main. + let lastScan = claudeConfigDirScan + // Discovery lists dirs, runs ps and reads a .claude.json per dir, + // hundreds of KB each, so off main. DispatchQueue.global(qos: .utility).async { [weak self] in - let dirs = ClaudeConfigDirs.discover(defaultAccount: ClaudeUsageCache.currentAccount()) + let scan = lastScan.flatMap { + Date().timeIntervalSince($0.at) < ClaudeConfigDirs.scanInterval ? $0 : nil + } ?? (at: Date(), dirs: ClaudeConfigDirs.scan()) + let running = ClaudeConfigDirs.running() + ClaudeConfigDirs.remember(running) + let dirs = ClaudeConfigDirs.discover( + found: scan.dirs + ClaudeConfigDirs.remembered() + running, + defaultAccount: ClaudeUsageCache.currentAccount()) DispatchQueue.main.async { - guard let self, self.quotaTrackingEnabled else { return } + 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 {