Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
29 changes: 26 additions & 3 deletions Sources/PokeTokenBar/Core/CompanionStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1318,10 +1318,14 @@ final class CompanionStore {
var grants: [CandyGrant] = []
for w in windows {
if let epoch = w.epoch {
if let previousEpoch = windowEpoch[w.key], previousEpoch != epoch {
grantTier[w.key] = nil
if let previousEpoch = windowEpoch[w.key] {
if isNewCandyWindow(previous: previousEpoch, current: epoch) {
grantTier[w.key] = nil
windowEpoch[w.key] = epoch
}
} else {
windowEpoch[w.key] = epoch
}
windowEpoch[w.key] = epoch
}
guard w.utilization >= 100 else { grantTier[w.key] = nil; continue }
let previous = grantTier[w.key] ?? 0
Expand All @@ -1333,6 +1337,25 @@ final class CompanionStore {
return grants
}

/// Claude `resets_at` carries sub-second digits that change on every response
/// ("...14:59:59.988942" then "...14:59:59.912345") for the same window. A new window moves the
/// reset by at least the shortest window length (hours), so anything closer is the same window.
static let candyEpochTolerance: TimeInterval = 10 * 60

/// Compares reset times, not strings. Falls back to string equality when either side is not a
/// timestamp (ISO 8601 or unix seconds).
static func isNewCandyWindow(previous: String, current: String) -> Bool {
guard let before = candyEpochDate(previous), let after = candyEpochDate(current) else {
return previous != current
}
return abs(after.timeIntervalSince(before)) > candyEpochTolerance
}

private static func candyEpochDate(_ epoch: String) -> Date? {
if let seconds = TimeInterval(epoch) { return Date(timeIntervalSince1970: seconds) }
return ISO8601Parser.date(from: epoch)
}

/// 한도 창 상태로부터 사탕 지급(엣지·영속). AppDelegate 가 매 refresh 완료 시(한도 로드 후) 호출.
/// - 첫 실행: 현재 100% 창을 지급 없이 tier 시드만 → 이후 "새로 넘어서는" 순간부터 지급(소급 차단).
/// - limitsReady=false(한도 미로딩)면 시드/지급 모두 대기(다음 refresh 에 재시도).
Expand Down
53 changes: 53 additions & 0 deletions Tests/PokeTokenBarTests/RareCandyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,47 @@ final class CandyGrantEvaluationTests: XCTestCase {
XCTAssertEqual(epochs["claude.fiveHour"], "2026-09-17T15:00:00Z")
}

/// The usage API returns the same window's `resets_at` with different sub-second digits on every
/// poll. Treating each string as a new window granted a candy per poll while at 100%.
func testSubSecondResetJitterIsTheSameWindow() {
var tier: [String: Int] = [:]
var epochs: [String: String] = [:]
_ = CompanionStore.evaluateCandyGrants(
windows: [w("claude.fiveHour", .session, 100, epoch: "2026-10-09T14:59:59.988942+00:00")],
grantTier: &tier, windowEpoch: &epochs)
for jittered in ["2026-10-09T14:59:59.912345+00:00", "2026-10-09T15:00:00.004211+00:00"] {
let grants = CompanionStore.evaluateCandyGrants(
windows: [w("claude.fiveHour", .session, 100, epoch: jittered)],
grantTier: &tier, windowEpoch: &epochs)
XCTAssertTrue(grants.isEmpty, "\(jittered) is the same window")
}
XCTAssertEqual(epochs["claude.fiveHour"], "2026-10-09T14:59:59.988942+00:00",
"jitter must not rewrite the stored epoch (a save per poll)")

let grants = CompanionStore.evaluateCandyGrants(
windows: [w("claude.fiveHour", .session, 100, epoch: "2026-10-09T19:59:59.901122+00:00")],
grantTier: &tier, windowEpoch: &epochs)
XCTAssertEqual(grants.map(\.count), [1], "the next 5h window still grants")
XCTAssertEqual(epochs["claude.fiveHour"], "2026-10-09T19:59:59.901122+00:00")
}

/// Codex sends unix seconds. A one-second drift is the same window, a 5h move is a new one.
func testUnixSecondEpochsCompareAsTimes() {
var tier: [String: Int] = [:]
var epochs: [String: String] = [:]
_ = CompanionStore.evaluateCandyGrants(
windows: [w("codex.codex.primary", .session, 100, epoch: "1791949300")],
grantTier: &tier, windowEpoch: &epochs)
let drift = CompanionStore.evaluateCandyGrants(
windows: [w("codex.codex.primary", .session, 100, epoch: "1791949301")],
grantTier: &tier, windowEpoch: &epochs)
XCTAssertTrue(drift.isEmpty)
let next = CompanionStore.evaluateCandyGrants(
windows: [w("codex.codex.primary", .session, 100, epoch: "1791967300")],
grantTier: &tier, windowEpoch: &epochs)
XCTAssertEqual(next.map(\.count), [1])
}

/// epoch 를 처음 알게 된 것만으로 재지급하지 않는다(구세이브 → 신규 필드 도입 시 폭탄 방지).
func testLearningEpochForFirstTimeDoesNotRegrant() {
var tier: [String: Int] = ["claude.fiveHour": 1]
Expand Down Expand Up @@ -187,6 +228,18 @@ final class RareCandyStoreTests: XCTestCase {
XCTAssertEqual(s.state.candyWindowEpoch["claude.fiveHour"], "E2")
}

/// The reported bug end to end: polls at 100% with jittered `resets_at` grant nothing after the seed.
func testPollsAtFullLimitWithJitteredResetGrantNothing() {
let s = store(rcLinear3)
s.grantCandies(from: [w("claude.fiveHour", .session, 100,
epoch: "2026-10-09T14:59:59.988942+00:00")], limitsReady: true) // 시드
for micros in ["912345", "954001", "990310"] {
s.grantCandies(from: [w("claude.fiveHour", .session, 100,
epoch: "2026-10-09T14:59:59.\(micros)+00:00")], limitsReady: true)
}
XCTAssertEqual(s.rareCandyCount, 0)
}

/// 시드+지급 헬퍼 — 빈 창으로 시드 완료 후, 유니크 세션 창을 100%로 올려 n개 지급.
private func giveCandies(_ s: CompanionStore, _ n: Int) {
s.grantCandies(from: [], limitsReady: true) // 시드(지급 0)
Expand Down
9 changes: 9 additions & 0 deletions docs/reference/defect-log.md
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,15 @@ read_when:
key 에서 epoch 가 바뀌면 util 과 무관하게 tier 를 비운 뒤 100%면 재지급. nil→첫 epoch 는 재무장이
아니다(구세이브 업그레이드 폭탄 방지). 회귀: `testRearmWhenWindowEpochAdvancesWhileStillAt100`·
`testGrantAfterSeedWhenEpochAdvancesWithoutUtilDip`·`testLearningEpochForFirstTimeDoesNotRegrant`.
**epoch 는 문자열이 아니라 시각으로 비교한다.** #334 는 원본 문자열을 비교했는데, Claude `resets_at` 은
같은 창이어도 응답마다 초 미만 자릿수가 바뀐다(`14:59:59.988942` → `.912345`). 그래서 100%가 유지되는
동안 폴마다 새 창으로 오판해 사탕과 알림이 1분 간격으로 쏟아졌다. 아래 "휘발성 필드" 항목이 이미 같은
필드의 휘발성을 적어 두었는데, #334 테스트는 `"E1"`→`"E2"` 같은 합성 epoch 만 써서 실제 API 형태를
밟지 않았다. 해결: `CompanionStore.isNewCandyWindow` 가 ISO 8601·unix 초를 파싱해
`candyEpochTolerance`(10분)보다 크게 움직일 때만 새 창으로 보고, 지터로는 저장값도 갱신하지 않는다.
회귀: `testSubSecondResetJitterIsTheSameWindow`·`testUnixSecondEpochsCompareAsTimes`·
`testPollsAtFullLimitWithJitteredResetGrantNothing`. **외부 API 값으로 동등 비교하는 테스트는 실제 응답
모양의 픽스처를 쓴다.**

- **휘발성 필드를 dedup/identity 키에 쓰지 마라.** 매 fetch/refresh 마다 값이 변하는 필드(예: rolling
한도 창의 `resets_at`)를 알림 중복방지 키에 넣으면 매번 새 키가 되어 dedup 이 무력화된다 — 주간 한도
Expand Down
Loading