diff --git a/PRIVACY.md b/PRIVACY.md index 375f699..ea227cc 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -57,7 +57,15 @@ 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, 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/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..14690de --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/ClaudeConfigDirsTests.swift @@ -0,0 +1,175 @@ +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 + } + + 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-org-publisher", account: "org") + 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"), + ]) + } + + 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(discover(home, defaultAccount: 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") + 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 + // 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 = 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)/Documents/work", account: "work") + try makeDir("\(home)/.claude-x", account: "x") + let actual = discover(home, setting: "~/Documents/work, ~/.claude-x", defaultAccount: nil) + XCTAssertEqual(actual.map(\.path), [elsewhere, "\(home)/.claude-x"]) + } + + // 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", + 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"]) + 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..39b1409 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 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. 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..5078cad --- /dev/null +++ b/panel/ClaudeConfigDirs.swift @@ -0,0 +1,155 @@ +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=