diff --git a/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift index 0110ab63..05bfa118 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift @@ -339,40 +339,74 @@ enum CodexSubscriptionService { } /// Reset-credit inventory carried inline on the usage payload. Nil means - /// absent. - static func inlineResetCredits(data: Data) -> CodexUsage.ResetCredits? { + /// absent. The inline block has carried no per-credit list in anything we + /// have observed, but it is decoded through the same parser so that if one + /// ever appears the inline path reports grants too — same response, no extra + /// request. + static func inlineResetCredits(data: Data, now: Date = Date()) -> CodexUsage.ResetCredits? { struct InlineDTO: Decodable { - struct Block: Decodable { let available_count: Int? } - let rate_limit_reset_credits: Block? + let rate_limit_reset_credits: ResetCreditsDTO? } - guard let count = (try? JSONDecoder().decode(InlineDTO.self, from: data))? - .rate_limit_reset_credits?.available_count, count >= 0 + guard let block = (try? JSONDecoder().decode(InlineDTO.self, from: data))?.rate_limit_reset_credits else { return nil } - return CodexUsage.ResetCredits(availableCount: count, nextExpiresAt: nil) + return makeResetCredits(block, now: now) + } + + /// The reset-credits document, in both the places it is served: as the body + /// of `/wham/rate-limit-reset-credits` and as the `rate_limit_reset_credits` + /// block inline on `/wham/usage`. + struct ResetCreditsDTO: Decodable { + struct CreditDTO: Decodable { + let id: String? + let reset_type: String? + let status: String? + let granted_at: String? + let expires_at: String? + } + let credits: [CreditDTO]? + let available_count: Int? + /// How many of the available credits can be applied right now. Absent on + /// some shapes; absent is unknown, not zero. + let applicable_available_count: Int? } /// Internal (not private) so tests can drive it with fixture payloads. /// Returns nil on any unexpected shape — the caller treats nil as /// "feature unavailable", never as an error. static func parseResetCredits(data: Data, now: Date = Date()) -> CodexUsage.ResetCredits? { - struct CreditDTO: Decodable { - let status: String? - let expires_at: String? - } - struct ResponseDTO: Decodable { - let credits: [CreditDTO]? - let available_count: Int? - } - guard let root = try? JSONDecoder().decode(ResponseDTO.self, from: data), - let count = root.available_count, count >= 0 else { - return nil - } - let nextExpiry = (root.credits ?? []) - .filter { ($0.status ?? "").lowercased() == "available" } + guard let root = try? JSONDecoder().decode(ResetCreditsDTO.self, from: data) else { return nil } + return makeResetCredits(root, now: now) + } + + /// Server counts are authoritative; everything else is derived from the + /// credits the payload actually lists. + private static func makeResetCredits(_ root: ResetCreditsDTO, now: Date) -> CodexUsage.ResetCredits? { + guard let count = root.available_count, count >= 0 else { return nil } + let available = (root.credits ?? []).filter { ($0.status ?? "").lowercased() == "available" } + let nextExpiry = available .compactMap { $0.expires_at.flatMap(parseISO8601) } .filter { $0 > now } .min() - return CodexUsage.ResetCredits(availableCount: count, nextExpiresAt: nextExpiry) + // Identity first, and only then a grant: a credit we cannot name is a + // credit we could re-announce on every refresh. + let grants: [CodexUsage.ResetCredits.Grant] = available.compactMap { credit in + let identity = [credit.id, credit.granted_at] + .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } + .first { !$0.isEmpty } + guard let identity else { return nil } + return .init( + id: identity, + resetType: credit.reset_type, + grantedAt: credit.granted_at.flatMap(parseISO8601) + ) + } + let applicable = root.applicable_available_count.flatMap { $0 >= 0 ? $0 : nil } + return CodexUsage.ResetCredits( + availableCount: count, + applicableAvailableCount: applicable, + grants: grants, + nextExpiresAt: nextExpiry + ) } /// chatgpt.com serializes these timestamps as ISO-8601, sometimes with @@ -389,6 +423,11 @@ enum CodexSubscriptionService { /// Internal (not private) so tests can drive it with fixture payloads. static func decodeUsage(data: Data, resetCredits: CodexUsage.ResetCredits? = nil) throws -> CodexUsage { let root = try JSONDecoder().decode(UsageDTO.self, from: data) + // The companion endpoint does not always carry + // `applicable_available_count`; the usage payload we are already holding + // sometimes does. Fill it in from there rather than from a second + // request, and only when the authoritative source said nothing. + let credits = mergedApplicableCount(resetCredits, usageData: data) let additional: [CodexUsage.AdditionalLimit] = (root.additional_rate_limits ?? []).compactMap { dto in guard let name = dto.limit_name, !name.isEmpty else { return nil } return CodexUsage.AdditionalLimit( @@ -409,11 +448,27 @@ enum CodexSubscriptionService { hasCredits: root.credits?.hasCredits ?? false, creditsUnlimited: root.credits?.unlimited ?? false, creditLimit: makeCreditLimit(limitDTO, reached: root.spend_control?.reached ?? false), - resetCredits: resetCredits, + resetCredits: credits, fetchedAt: Date() ) } + private static func mergedApplicableCount( + _ credits: CodexUsage.ResetCredits?, + usageData: Data + ) -> CodexUsage.ResetCredits? { + guard let credits, credits.applicableAvailableCount == nil, + let inline = inlineResetCredits(data: usageData), + let applicable = inline.applicableAvailableCount + else { return credits } + return CodexUsage.ResetCredits( + availableCount: credits.availableCount, + applicableAvailableCount: applicable, + grants: credits.grants, + nextExpiresAt: credits.nextExpiresAt + ) + } + private static func makeCreditLimit( _ dto: UsageDTO.IndividualLimit?, reached: Bool diff --git a/mac/Sources/CodeBurnMenubar/Data/CodexUsage.swift b/mac/Sources/CodeBurnMenubar/Data/CodexUsage.swift index 2fbbdbf1..fcf7f02e 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CodexUsage.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CodexUsage.swift @@ -74,11 +74,51 @@ struct CodexUsage: Sendable, Equatable { } /// Account-level limit-reset credits: grants that restore a rate-limit - /// window early, each with its own expiry. Only what the popover renders — - /// the available count and the soonest expiry among available credits. + /// window early, each with its own expiry. Carries what the popover renders + /// (the available count and the soonest expiry among available credits) plus + /// the per-credit identities a newly banked grant is detected from. struct ResetCredits: Sendable, Equatable { + /// One available credit, reduced to the three things a notice needs. + struct Grant: Sendable, Equatable, Codable { + /// Stable identity: the payload's `id`, else its raw `granted_at` + /// string. A credit carrying neither is left out entirely — it + /// cannot be told apart from the next one, so it must never be + /// announced as new. + let id: String + /// `reset_type` verbatim ("weekly", …). Nil when the payload omits it. + let resetType: String? + let grantedAt: Date? + } + let availableCount: Int + /// `applicable_available_count`: how many of the available credits can be + /// applied right now. Nil when the payload omits it — which is not the + /// same as zero, so it is never defaulted. + let applicableAvailableCount: Int? + /// Available credits that carry a stable identity, in payload order. + let grants: [Grant] let nextExpiresAt: Date? + + init( + availableCount: Int, + applicableAvailableCount: Int? = nil, + grants: [Grant] = [], + nextExpiresAt: Date? = nil + ) { + self.availableCount = availableCount + self.applicableAvailableCount = applicableAvailableCount + self.grants = grants + self.nextExpiresAt = nextExpiresAt + } + + /// The most recently granted credit. Only credits that say when they were + /// granted can compete: "most recent" is a claim about time, and a credit + /// with no timestamp cannot support it. + var latestGrant: Grant? { + grants + .filter { $0.grantedAt != nil } + .max { ($0.grantedAt ?? .distantPast) < ($1.grantedAt ?? .distantPast) } + } } /// The monthly allowance an admin sets. Credit-metered workspaces report diff --git a/mac/Tests/CodeBurnMenubarTests/CodexResetCreditsTests.swift b/mac/Tests/CodeBurnMenubarTests/CodexResetCreditsTests.swift index 48b8ca7b..de3cfbae 100644 --- a/mac/Tests/CodeBurnMenubarTests/CodexResetCreditsTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/CodexResetCreditsTests.swift @@ -67,6 +67,101 @@ final class CodexResetCreditsTests: XCTestCase { XCTAssertNil(result?.nextExpiresAt) } + func testGrantsCarryIdentityTypeAndGrantTime() { + let result = parse(#""" + { + "credits": [ + {"id": "c1", "reset_type": "weekly", "status": "available", + "granted_at": "2027-01-02T00:00:00Z", "expires_at": "2027-01-25T12:00:00Z"}, + {"id": "c3", "reset_type": "weekly", "status": "redeemed", + "granted_at": "2026-06-01T00:00:00Z"} + ], + "available_count": 1, + "applicable_available_count": 1 + } + """#) + // Only available credits become grants: a redeemed one is spent history. + XCTAssertEqual(result?.grants.map(\.id), ["c1"]) + XCTAssertEqual(result?.grants.first?.resetType, "weekly") + XCTAssertEqual(result?.grants.first?.grantedAt, + ISO8601DateFormatter().date(from: "2027-01-02T00:00:00Z")) + XCTAssertEqual(result?.applicableAvailableCount, 1) + } + + func testApplicableCountIsUnknownRatherThanZeroWhenAbsent() { + XCTAssertNil(parse(#"{"credits": [], "available_count": 0}"#)?.applicableAvailableCount) + XCTAssertNil(parse(#"{"credits": [], "available_count": 0, "applicable_available_count": -1}"#)? + .applicableAvailableCount) + XCTAssertEqual(parse(#"{"credits": [], "available_count": 0, "applicable_available_count": 0}"#)? + .applicableAvailableCount, 0) + } + + func testGrantedAtIsTheIdentityWhenNoIdIsPresent() { + let result = parse(#""" + { + "credits": [{"status": "available", "granted_at": "2027-01-02T00:00:00Z"}], + "available_count": 1 + } + """#) + XCTAssertEqual(result?.grants.map(\.id), ["2027-01-02T00:00:00Z"]) + } + + func testCreditWithNoStableIdentityIsNotAGrant() { + let result = parse(#"{"credits": [{"status": "available"}], "available_count": 1}"#) + // Still counted — the server said one is available — but never announced, + // because a second unidentifiable credit could not be told from this one. + XCTAssertEqual(result?.availableCount, 1) + XCTAssertTrue(result?.grants.isEmpty == true) + } + + func testLatestGrantIgnoresCreditsThatCannotSayWhenTheyLanded() { + let result = parse(#""" + { + "credits": [ + {"id": "c1", "status": "available", "granted_at": "2027-01-02T00:00:00Z"}, + {"id": "c2", "status": "available", "granted_at": "2027-01-04T00:00:00Z"}, + {"id": "c3", "status": "available"} + ], + "available_count": 3 + } + """#) + XCTAssertEqual(result?.latestGrant?.id, "c2") + } + + func testInlineBlockCarriesBothCounts() { + let usage = #""" + {"plan_type": "plus", + "rate_limit_reset_credits": {"available_count": 2, "applicable_available_count": 1}} + """# + let inline = CodexSubscriptionService.inlineResetCredits(data: Data(usage.utf8), now: now) + XCTAssertEqual(inline?.availableCount, 2) + XCTAssertEqual(inline?.applicableAvailableCount, 1) + // Non-zero, so the companion fetch still runs: the inline block has no + // per-credit list to detect a new grant from. + XCTAssertNil(CodexSubscriptionService.inlineResetCreditsShortcut(data: Data(usage.utf8))) + } + + func testUsagePayloadFillsInAMissingApplicableCount() throws { + let usage = #""" + {"plan_type": "plus", + "rate_limit_reset_credits": {"available_count": 2, "applicable_available_count": 1}} + """# + // The companion endpoint answered without an applicable count; the usage + // payload we already hold has one. + let fromEndpoint = CodexUsage.ResetCredits(availableCount: 2, grants: []) + let decoded = try CodexSubscriptionService.decodeUsage( + data: Data(usage.utf8), resetCredits: fromEndpoint + ) + XCTAssertEqual(decoded.resetCredits?.applicableAvailableCount, 1) + + // An authoritative count from the endpoint is never overwritten. + let authoritative = CodexUsage.ResetCredits(availableCount: 2, applicableAvailableCount: 2) + let kept = try CodexSubscriptionService.decodeUsage( + data: Data(usage.utf8), resetCredits: authoritative + ) + XCTAssertEqual(kept.resetCredits?.applicableAvailableCount, 2) + } + func testMalformedDocumentReturnsNil() { XCTAssertNil(parse("not json")) XCTAssertNil(parse(#"{"credits": "wrong-shape"}"#))