Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@
- Codex: avoid full SQLite cost-cache rewrites for unchanged scans while preserving retention, freshness, and concurrent saves (#2852). Thanks @Yuxin-Qiao!
- Azure OpenAI: allow enough v1 completion budget for reasoning-capable deployment validation while keeping the probe bounded (#2867). Thanks @yilinxia!
- Codex: preserve request-level pricing tiers while reconciling forked usage, preventing day aggregates from triggering long-context rates (#2858). Thanks @thomaschow19!
- Claude: keep 100% claude-swap usage bars when cswap defers polling at a limit, and name the exhausted window and reset instead of showing "Usage fetch failed." (#3081).
- CLI: stop standalone version lookup from walking past the filesystem root and hanging with unbounded memory on affected macOS versions (#2856). Thanks @Manwholikespie!
- Cost store: prevent launch-time executor-assumption crashes on macOS 15 by keeping synchronous SQLite cache bridges on their validated serial queue (#2857). Thanks @Manwholikespie!

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ extension UsageStore {

do {
let list = try await ClaudeSwapAccountReader.readAccountList(executablePath: executablePath)
let snapshots = ClaudeSwapAccountProjection.accountSnapshots(from: list)
let snapshots = ClaudeSwapAccountProjection.accountSnapshots(
from: list,
previousAccounts: self.claudeSwapAccountSnapshots)
Comment thread
sf-jin-ku marked this conversation as resolved.
Resolved
guard self.isCurrentClaudeSwapRefresh(executablePath: executablePath, generation: generation) else {
return
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,41 @@ public enum ClaudeSwapAccountProjection {
public static let sourceLabel = "claude-swap"
static let fiveHourWindowMinutes = 5 * 60
static let sevenDayWindowMinutes = 7 * 24 * 60
static let exhaustedUsedPercent = 100.0
static let deferredPollingNote = "Polling deferred until a limit resets."

public static func shouldPresentAccounts(accountCount: Int, showSingleAccount: Bool) -> Bool {
accountCount >= (showSingleAccount ? 1 : 2)
}

public static func accountSnapshots(
from list: ClaudeSwapAccountList,
previousAccounts: [ProviderAccountUsageSnapshot] = [],
Comment thread
sf-jin-ku marked this conversation as resolved.
Resolved
now: Date = Date()) -> [ProviderAccountUsageSnapshot]
{
let previousByID = Dictionary(
previousAccounts.map { ($0.id, $0) },
uniquingKeysWith: { first, _ in first })
let ordered = list.accounts.sorted { lhs, rhs in
if lhs.isActive != rhs.isActive {
return lhs.isActive
}
return lhs.number < rhs.number
}
return ordered.map { row in
ProviderAccountUsageSnapshot(
id: ProviderAccountIdentity(source: self.sourceName, opaqueID: String(row.number)),
let id = ProviderAccountIdentity(source: self.sourceName, opaqueID: String(row.number))
let snapshot = self.usageSnapshot(
for: row,
previous: previousByID[id],
now: now)
return ProviderAccountUsageSnapshot(
id: id,
provider: .claude,
displayLabel: self.displayLabel(for: row),
isActive: row.isActive,
canActivate: !row.isActive && self.canActivate(row),
snapshot: self.usageSnapshot(for: row, now: now),
error: self.errorText(for: row),
snapshot: snapshot,
error: self.errorText(for: row, snapshot: snapshot, now: now),
sourceLabel: self.sourceLabel)
}
}
Expand All @@ -50,8 +61,48 @@ public enum ClaudeSwapAccountProjection {
row.email.isEmpty ? "Account \(row.number)" : row.email
}

private static func usageSnapshot(for row: ClaudeSwapAccountRow, now: Date) -> UsageSnapshot? {
guard row.usageStatus == .ok else { return nil }
private static func usageSnapshot(
for row: ClaudeSwapAccountRow,
previous: ProviderAccountUsageSnapshot?,
now: Date) -> UsageSnapshot?
{
switch row.usageStatus {
case .ok, .unavailable:
if let projected = self.projectedUsageSnapshot(for: row, now: now) {
return projected
Comment thread
sf-jin-ku marked this conversation as resolved.
Resolved
}
guard row.usageStatus == .unavailable else { return nil }
return self.retainedAtLimitSnapshot(previous, matching: row, now: now)
case .tokenExpired, .reloginRequired, .apiKey, .keychainUnavailable, .noCredentials, .unknown:
return nil
}
}

private static func retainedAtLimitSnapshot(
_ previous: ProviderAccountUsageSnapshot?,
matching row: ClaudeSwapAccountRow,
now: Date) -> UsageSnapshot?
{
guard let previous, let snapshot = previous.snapshot else { return nil }
let previousEmail = previous.snapshot?.identity?.accountEmail ?? previous.displayLabel
let rowEmail = self.displayLabel(for: row)
if !previousEmail.isEmpty, !rowEmail.isEmpty, previousEmail != rowEmail {
return nil
}
guard self.hasApplicableExhaustedWindow(snapshot, now: now) else { return nil }
return snapshot
Comment thread
sf-jin-ku marked this conversation as resolved.
Resolved
}

private static func hasApplicableExhaustedWindow(_ snapshot: UsageSnapshot, now: Date) -> Bool {
let windows = [snapshot.primary, snapshot.secondary].compactMap(\.self)
+ (snapshot.extraRateWindows ?? []).map(\.window)
return windows.contains { window in
window.usedPercent >= self.exhaustedUsedPercent
&& (window.resetsAt.map { $0 > now } ?? true)
}
}

private static func projectedUsageSnapshot(for row: ClaudeSwapAccountRow, now: Date) -> UsageSnapshot? {
let primary = row.fiveHour.map { window in
RateWindow(
usedPercent: window.usedPercent,
Expand Down Expand Up @@ -92,12 +143,10 @@ public enum ClaudeSwapAccountProjection {
})
}

private static func errorText(for row: ClaudeSwapAccountRow) -> String? {
private static func errorText(for row: ClaudeSwapAccountRow, snapshot: UsageSnapshot?, now: Date) -> String? {
switch row.usageStatus {
case .ok:
row.fiveHour == nil && row.sevenDay == nil && self.scopedRateWindows(for: row).isEmpty
? "No usage windows reported."
: nil
snapshot == nil ? "No usage windows reported." : nil
case .tokenExpired:
"Token expired. Switch to this account in claude-swap to refresh it."
case .reloginRequired:
Expand All @@ -109,12 +158,48 @@ public enum ClaudeSwapAccountProjection {
case .noCredentials:
"No stored credentials for this account slot."
case .unavailable:
"Usage fetch failed."
self.atLimitNote(from: snapshot, now: now) ?? self.deferredPollingNote
Comment thread
sf-jin-ku marked this conversation as resolved.
Resolved
case let .unknown(raw):
"Unrecognized claude-swap status: \(raw)"
}
}

private static func atLimitNote(from snapshot: UsageSnapshot?, now: Date) -> String? {
guard let snapshot else { return nil }
var parts: [String] = []
if let primary = snapshot.primary {
self.appendLimit(named: "Session", window: primary, now: now, to: &parts)
}
if let secondary = snapshot.secondary {
self.appendLimit(named: "Weekly", window: secondary, now: now, to: &parts)
}
for extra in snapshot.extraRateWindows ?? [] {
self.appendLimit(named: self.scopedLimitName(extra.title), window: extra.window, now: now, to: &parts)
}
guard !parts.isEmpty else { return nil }
return parts.joined(separator: " ")
}

private static func appendLimit(
named name: String,
window: RateWindow,
now: Date,
to parts: inout [String])
{
guard window.usedPercent >= self.exhaustedUsedPercent else { return }
if let reset = UsageFormatter.resetLine(for: window, style: .countdown, now: now) {
parts.append("\(name) limit reached. \(reset).")
} else {
parts.append("\(name) limit reached.")
}
}

private static func scopedLimitName(_ title: String) -> String {
let suffix = " only"
guard title.hasSuffix(suffix) else { return title }
return String(title.dropLast(suffix.count))
}

private static func canActivate(_ row: ClaudeSwapAccountRow) -> Bool {
switch row.usageStatus {
case .ok, .apiKey, .unavailable:
Expand Down
40 changes: 38 additions & 2 deletions Tests/CodexBarTests/CLICardsClaudeSwapTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,15 @@ struct CLICardsClaudeSwapTests {
"Re-login required. Re-authenticate this account in claude-swap.",
"claude-swap could not read the active account's Keychain entry.",
"No stored credentials for this account slot.",
"Usage fetch failed.",
"Polling deferred until a limit resets.",
"Unrecognized claude-swap status: future_status",
"No usage windows reported.",
])
}

@Test
func `active sentinel account remains active and metrics less in full and brief cards`() async {
let problem = "Usage fetch failed."
let problem = "Polling deferred until a limit resets."
let output = await CLIClaudeSwapCards.fetch(
eligible: true,
executablePath: "/fake/cswap",
Expand Down Expand Up @@ -315,6 +315,42 @@ struct CLICardsClaudeSwapTests {
#expect(rows.first?.usedPercent == nil)
}

@Test
func `unavailable at limit windows keep metrics and name the exhausted window`() async {
let reset = Date(timeIntervalSince1970: 1_700_003_600)
let output = await CLIClaudeSwapCards.fetch(
eligible: true,
executablePath: "/fake/cswap",
renderOptions: self.renderOptions(),
ambientFetch: { self.ambientOutput(failed: true) },
accountListReader: { _ in
ClaudeSwapAccountList(activeAccountNumber: 1, accounts: [
ClaudeSwapAccountRow(
number: 1,
email: "limited@example.com",
isActive: true,
usageStatus: .unavailable,
fiveHour: ClaudeSwapUsageWindow(usedPercent: 100, resetsAt: reset),
sevenDay: ClaudeSwapUsageWindow(usedPercent: 100, resetsAt: reset)),
self.row(number: 2),
])
})

#expect(output.exitCode == .success)
let activeCard = output.cards.first
#expect(activeCard?.accountLine == "limited@example.com")
#expect(activeCard?.isActive == true)
#expect(activeCard?.accountProblem ==
"Session limit reached. Resets in 1h. Weekly limit reached. Resets in 1h.")
#expect(activeCard?.metrics.isEmpty == false)
#expect(activeCard?.metrics.contains { $0.remainingPercent == 0 } == true)
#expect(activeCard?.accountProblem?.contains("Usage fetch failed") != true)

let rows = CLICardsBriefRenderer.makeRows(cards: activeCard.map { [$0] } ?? [])
#expect(rows.first?.accountProblem?.contains("Session limit reached") == true)
#expect(rows.first?.usedPercent == 100)
}

@Test
func `blank executable path preserves ambient output and fails distinctly`() async {
let ambient = self.ambientOutput()
Expand Down
64 changes: 64 additions & 0 deletions Tests/CodexBarTests/ClaudeProviderRuntimeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,48 @@ struct ClaudeProviderRuntimeTests {
#expect(store.claudeSwapTransientState.lastErrorAccountID == nil)
}

@Test
func `unavailable refresh retains previous at limit snapshot`() async throws {
let (settings, store) = self.makeStore()
let executable = try self.makeUnavailableListExecutable()
let metadata = try #require(ProviderRegistry.shared.metadata[.claude])
settings.setProviderEnabled(provider: .claude, metadata: metadata, enabled: true)
settings.claudeSwapExecutablePath = executable
settings.claudeSwapEnabled = true
let now = Date(timeIntervalSince1970: 1_782_000_000)
let previous = ClaudeSwapAccountProjection.accountSnapshots(
from: ClaudeSwapAccountList(
activeAccountNumber: 1,
accounts: [
ClaudeSwapAccountRow(
number: 1,
email: "a@b.c",
isActive: true,
usageStatus: .ok,
fiveHour: ClaudeSwapUsageWindow(
usedPercent: 100,
resetsAt: now.addingTimeInterval(3600)),
sevenDay: ClaudeSwapUsageWindow(
usedPercent: 100,
resetsAt: now.addingTimeInterval(86400))),
]),
now: now)
store.claudeSwapAccountSnapshots = previous

await store.refreshClaudeSwapAccounts()

let account = try #require(store.claudeSwapAccountSnapshots.first)
#expect(account.id == ProviderAccountIdentity(source: "claude-swap", opaqueID: "1"))
#expect(account.snapshot?.primary?.usedPercent == 100)
#expect(account.snapshot?.secondary?.usedPercent == 100)
#expect(account.snapshot?.updatedAt == now)
let error = try #require(account.error)
#expect(error.contains("Session limit reached"))
#expect(error.contains("Weekly limit reached"))
#expect(!error.contains("Usage fetch failed"))
#expect(store.claudeSwapLastError == nil)
}

private func makeStore() -> (SettingsStore, UsageStore) {
let suite = "ClaudeProviderRuntimeTests-\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suite)!
Expand Down Expand Up @@ -242,6 +284,28 @@ struct ClaudeProviderRuntimeTests {
return url.path
}

private func makeUnavailableListExecutable() throws -> String {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("claude-unavailable-runtime-tests-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let url = directory.appendingPathComponent("cswap")
let script = """
#!/bin/sh
if [ "$1" = "--version" ]; then
echo 'cswap 0.22.0'
exit 0
fi
cat <<'EOF'
{"schemaVersion":1,"activeAccountNumber":1,"accounts":[
{"number":1,"email":"a@b.c","active":true,"usageStatus":"unavailable","usage":null}
]}
EOF
"""
try script.write(to: url, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: url.path)
return url.path
}

private func makeFailedSwitchExecutable() throws -> String {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("claude-failed-switch-runtime-tests-\(UUID().uuidString)", isDirectory: true)
Expand Down
Loading
Loading