mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
feat(codex): read the per-credit fields the reset-credits payload already carries
The reset-credits decoder kept only `available_count` and the soonest expiry, and the inline block on the usage payload kept only `available_count`. The response has always carried more: `id`, `reset_type` and `granted_at` per credit, and `applicable_available_count` alongside the total. Those are exactly the fields needed to tell a newly granted credit from one the account was already holding, so they are decoded now instead of discarded. Identity comes first: a credit is reduced to a grant only if it carries an `id` or, failing that, a `granted_at` to be named by. One that carries neither still counts toward the server's authoritative total but never becomes a grant, because it could not be told apart from the next one and would re-announce itself on every refresh. Only `status == "available"` credits become grants, so a redeemed one is spent history rather than news. `applicable_available_count` is unknown when absent, never zero. The companion endpoint does not always send it and the usage payload sometimes does, so the usage response we are already holding fills it in when — and only when — the authoritative source said nothing. No extra request either way.
This commit is contained in:
parent
e0247585df
commit
53dd90a4a7
3 changed files with 215 additions and 25 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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"}"#))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue