opencode-quota-gui 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +27 -17
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/dashboard.d.ts +8 -1
  5. package/dist/contracts/dto-guards.js +2 -0
  6. package/dist/contracts/openai-quota.d.ts +3 -0
  7. package/dist/contracts/openai-quota.js +3 -0
  8. package/dist/data/modelsdev-temporal.min.json +57 -0
  9. package/dist/gui/config.d.ts +3 -3
  10. package/dist/gui/config.js +31 -2
  11. package/dist/gui/lifecycle.d.ts +5 -3
  12. package/dist/gui/lifecycle.js +3 -3
  13. package/dist/gui/primary-quota-windows.js +16 -14
  14. package/dist/gui/provider-cards.d.ts +10 -2
  15. package/dist/gui/provider-cards.js +51 -23
  16. package/dist/gui/quota-notification-detector.d.ts +4 -4
  17. package/dist/gui/quota-notification-detector.js +76 -42
  18. package/dist/gui/quota-notification-observer.d.ts +2 -3
  19. package/dist/gui/quota-notification-observer.js +68 -19
  20. package/dist/gui/rpc.d.ts +2 -0
  21. package/dist/gui/rpc.js +11 -3
  22. package/dist/gui/server.js +11 -2
  23. package/dist/gui/snapshot-service.d.ts +3 -1
  24. package/dist/gui/snapshot-service.js +126 -18
  25. package/dist/gui/sources.js +98 -56
  26. package/dist/gui-experimental.cjs +230 -225
  27. package/dist/lib/accounting-format.js +8 -0
  28. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  29. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  30. package/dist/lib/anthropic-auth.d.ts +2 -3
  31. package/dist/lib/anthropic-auth.js +2 -3
  32. package/dist/lib/anthropic.d.ts +48 -12
  33. package/dist/lib/anthropic.js +610 -275
  34. package/dist/lib/api-key-retry-after.d.ts +7 -0
  35. package/dist/lib/api-key-retry-after.js +62 -0
  36. package/dist/lib/atomic-json.d.ts +2 -0
  37. package/dist/lib/atomic-json.js +1 -0
  38. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  39. package/dist/lib/cache-observer-ingestion.js +981 -0
  40. package/dist/lib/cache-observer.d.ts +138 -0
  41. package/dist/lib/cache-observer.js +317 -0
  42. package/dist/lib/canonical-config-lock.d.ts +9 -0
  43. package/dist/lib/canonical-config-lock.js +36 -0
  44. package/dist/lib/chutes.js +62 -51
  45. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  46. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  47. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  48. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  49. package/dist/lib/cli-show.js +5 -3
  50. package/dist/lib/config-write-target.d.ts +1 -1
  51. package/dist/lib/config-write-target.js +5 -2
  52. package/dist/lib/config.d.ts +2 -1
  53. package/dist/lib/config.js +193 -2
  54. package/dist/lib/copilot.js +171 -86
  55. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  56. package/dist/lib/dashboard-web-policy.js +2 -2
  57. package/dist/lib/deepseek.js +25 -13
  58. package/dist/lib/display-sanitize.js +1 -0
  59. package/dist/lib/entries.d.ts +23 -0
  60. package/dist/lib/entries.js +2 -0
  61. package/dist/lib/glm-coding-plan.js +98 -74
  62. package/dist/lib/google-agy.js +90 -12
  63. package/dist/lib/google-gemini-cli.js +84 -11
  64. package/dist/lib/http.d.ts +4 -0
  65. package/dist/lib/http.js +16 -2
  66. package/dist/lib/init-installer.js +5 -3
  67. package/dist/lib/kilo.js +37 -18
  68. package/dist/lib/kimi.js +35 -18
  69. package/dist/lib/mimo.d.ts +2 -0
  70. package/dist/lib/mimo.js +36 -0
  71. package/dist/lib/nanogpt.d.ts +1 -0
  72. package/dist/lib/nanogpt.js +26 -3
  73. package/dist/lib/ollama-cloud.d.ts +1 -1
  74. package/dist/lib/ollama-cloud.js +48 -35
  75. package/dist/lib/openai.js +84 -38
  76. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  77. package/dist/lib/opencode-auth-sqlite.js +2 -2
  78. package/dist/lib/opencode-config-editor.d.ts +1 -0
  79. package/dist/lib/opencode-config-editor.js +6 -1
  80. package/dist/lib/opencode-go.js +29 -2
  81. package/dist/lib/opencode-version-core.d.ts +23 -0
  82. package/dist/lib/opencode-version-core.js +49 -0
  83. package/dist/lib/opencode-version.d.ts +2 -22
  84. package/dist/lib/opencode-version.js +4 -48
  85. package/dist/lib/opencode-zen.d.ts +3 -0
  86. package/dist/lib/opencode-zen.js +71 -5
  87. package/dist/lib/provider-add.js +5 -2
  88. package/dist/lib/provider-registration.d.ts +19 -9
  89. package/dist/lib/provider-registration.js +17 -6
  90. package/dist/lib/quota-command-format.js +1 -1
  91. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  92. package/dist/lib/quota-exhaustion-projection.js +25 -0
  93. package/dist/lib/quota-providers-remote.d.ts +2 -1
  94. package/dist/lib/quota-providers-remote.js +59 -3
  95. package/dist/lib/quota-providers.d.ts +1 -1
  96. package/dist/lib/quota-providers.js +12 -35
  97. package/dist/lib/quota-render-data.d.ts +6 -0
  98. package/dist/lib/quota-render-data.js +43 -17
  99. package/dist/lib/quota-state-codec.js +17 -1
  100. package/dist/lib/quota-state.d.ts +7 -1
  101. package/dist/lib/quota-state.js +208 -34
  102. package/dist/lib/quota-stats.js +21 -0
  103. package/dist/lib/quota-status.js +3 -51
  104. package/dist/lib/scoped-update.d.ts +1 -1
  105. package/dist/lib/synthetic.js +65 -54
  106. package/dist/lib/types.d.ts +31 -1
  107. package/dist/lib/types.js +13 -0
  108. package/dist/lib/xai.js +48 -22
  109. package/dist/plugin.js +261 -13
  110. package/dist/provider-logos/NOTICE.md +1 -1
  111. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  112. package/dist/providers/alibaba-coding-plan.js +107 -104
  113. package/dist/providers/anthropic.d.ts +12 -3
  114. package/dist/providers/anthropic.js +71 -228
  115. package/dist/providers/cache-policies.d.ts +11 -4
  116. package/dist/providers/cache-policies.js +19 -13
  117. package/dist/providers/claude-agent.d.ts +19 -0
  118. package/dist/providers/claude-agent.js +196 -0
  119. package/dist/providers/copilot.js +2 -0
  120. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  121. package/dist/providers/google-account-format.js +1 -0
  122. package/dist/providers/google-agy.d.ts +6 -5
  123. package/dist/providers/google-agy.js +43 -15
  124. package/dist/providers/google-gemini-cli.js +1 -0
  125. package/dist/providers/kilo.js +1 -0
  126. package/dist/providers/kimi-code.js +2 -0
  127. package/dist/providers/mimo.js +1 -0
  128. package/dist/providers/nanogpt.js +1 -0
  129. package/dist/providers/opencode-go.js +3 -0
  130. package/dist/providers/opencode-zen.js +2 -0
  131. package/dist/providers/openrouter.js +1 -0
  132. package/dist/providers/quota-providers.js +16 -5
  133. package/dist/providers/registry.js +2 -0
  134. package/dist/providers/result-helpers.d.ts +2 -0
  135. package/dist/providers/result-helpers.js +2 -0
  136. package/dist/rpc.d.ts +121 -8
  137. package/dist/rpc.js +204 -12
  138. package/dist/ui/assets/{index-cDd9jUVY.css → index-BcueIm3Z.css} +1 -1
  139. package/dist/ui/assets/index-C6qRSoh8.js +10 -0
  140. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-4bFSvRZ7.js} +1 -1
  141. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  142. package/dist/ui/index.html +2 -2
  143. package/package.json +44 -45
  144. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  145. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  146. package/dist/ui/assets/index-DLHeXYff.js +0 -9
@@ -170,6 +170,8 @@ export function createSnapshotService(options) {
170
170
  const logger = options.logger ?? createGuiLogger();
171
171
  const now = options.now ?? Date.now;
172
172
  const cache = new Map();
173
+ let quotaRefresh;
174
+ let quotaPoll;
173
175
  const computes = new Map();
174
176
  const inflight = new Map();
175
177
  const listeners = new Set();
@@ -199,6 +201,9 @@ export function createSnapshotService(options) {
199
201
  /** Explicit UI signal outranks read-request inference for this viewer session. */
200
202
  let viewScopeExplicit = false;
201
203
  let quotaTimer;
204
+ let quotaRetryTimer;
205
+ let quotaRetried = false;
206
+ let pollerEpoch = 0;
202
207
  let analyticsTimer;
203
208
  let quotaTicking = false;
204
209
  let analyticsTicking = false;
@@ -346,7 +351,7 @@ export function createSnapshotService(options) {
346
351
  }
347
352
  return version;
348
353
  }
349
- function load(key, compute) {
354
+ function load(key, compute, force = false) {
350
355
  const epoch = viewerEpoch;
351
356
  const generation = sourceGeneration;
352
357
  // A closed service does not track, register, or cache: the caller still
@@ -356,7 +361,11 @@ export function createSnapshotService(options) {
356
361
  if (!closed)
357
362
  computes.set(key, compute);
358
363
  const existing = cache.get(key);
359
- if (existing && !existing.stale && existing.sourceGeneration === sourceGeneration) {
364
+ if (!force &&
365
+ existing &&
366
+ existing.sourceGeneration === sourceGeneration &&
367
+ (!existing.stale ||
368
+ (isQuotaKey(key) && !existing.invalidated && payloadIsStale(existing.snapshot)))) {
360
369
  // SAFETY: `load<T>` is only called with a key built from `(kind, resourceId,
361
370
  // range)`, and the entry under this key was stored by a compute of that key.
362
371
  return Promise.resolve(existing.snapshot);
@@ -450,7 +459,7 @@ export function createSnapshotService(options) {
450
459
  * Polls one registered key. Returns false when the viewer session ended or
451
460
  * the service closed and the tick must stop.
452
461
  */
453
- async function pollOne(key, compute, epoch, changed) {
462
+ async function pollOne(key, compute, epoch, changed, onSnapshot) {
454
463
  const generation = sourceGeneration;
455
464
  if (closed || viewerEpoch !== epoch || viewers === 0)
456
465
  return false;
@@ -492,33 +501,87 @@ export function createSnapshotService(options) {
492
501
  return true;
493
502
  const substantive = substantiveOf(snapshot);
494
503
  const entry = cache.get(key);
495
- const changedNow = entry === undefined || entry.stale || entry.substantive !== substantive;
496
- cache.set(key, { snapshot, substantive, stale: false, sourceGeneration: generation });
504
+ const stale = payloadIsStale(snapshot);
505
+ const changedNow = entry === undefined ||
506
+ entry.stale !== stale ||
507
+ entry.substantive !== substantive ||
508
+ (isQuotaKey(key) &&
509
+ entry.snapshot.providers.polledAtMs !==
510
+ snapshot.providers.polledAtMs);
511
+ cache.set(key, {
512
+ snapshot,
513
+ substantive,
514
+ stale,
515
+ sourceGeneration: generation,
516
+ });
517
+ onSnapshot?.(snapshot);
497
518
  if (changedNow)
498
519
  changed.add(topicFor(key));
499
520
  return true;
500
521
  }
501
- async function tickQuota() {
502
- if (quotaTicking || closed || viewers === 0)
522
+ async function tickQuota(earlyRetry = false) {
523
+ if (quotaTicking || quotaRefresh || closed || viewers === 0)
503
524
  return;
525
+ if (!earlyRetry && quotaRetryTimer) {
526
+ clearTimeout(quotaRetryTimer);
527
+ quotaRetryTimer = undefined;
528
+ quotaRetried = true;
529
+ }
504
530
  quotaTicking = true;
505
531
  const epoch = viewerEpoch;
532
+ const tickPollerEpoch = pollerEpoch;
533
+ const generation = sourceGeneration;
506
534
  const changed = new Set();
535
+ let polledSnapshot;
507
536
  try {
508
537
  // Copy before the async body: `load` can register new computes while a
509
538
  // tick awaits, and one tick must not grow while it runs.
510
539
  for (const [key, compute] of Array.from(computes)) {
511
540
  if (kindOf(key) !== "quota")
512
541
  continue;
513
- if (!(await pollOne(key, compute, epoch, changed)))
514
- break;
542
+ const poll = pollOne(key, compute, epoch, changed, (snapshot) => {
543
+ polledSnapshot = snapshot;
544
+ });
545
+ quotaPoll = poll;
546
+ try {
547
+ if (!(await poll))
548
+ break;
549
+ }
550
+ finally {
551
+ if (quotaPoll === poll)
552
+ quotaPoll = undefined;
553
+ }
515
554
  }
516
555
  }
517
556
  finally {
518
557
  quotaTicking = false;
519
558
  }
520
- if (closed || viewerEpoch !== epoch)
559
+ if (closed || viewerEpoch !== epoch || pollerEpoch !== tickPollerEpoch)
560
+ return;
561
+ if (sourceGeneration !== generation)
521
562
  return;
563
+ if (polledSnapshot) {
564
+ const eligible = polledSnapshot.providers.cards.some((card) => card.errors.some((error) => error.kind !== "intentional-filter" &&
565
+ (error.failureCategory === "provider_api" ||
566
+ error.failureCategory === "discovery" ||
567
+ error.failureCategory === "local") &&
568
+ !(error.retryAtMs !== undefined && error.retryAtMs > now())));
569
+ if (!eligible) {
570
+ quotaRetried = false;
571
+ if (quotaRetryTimer)
572
+ clearTimeout(quotaRetryTimer);
573
+ quotaRetryTimer = undefined;
574
+ }
575
+ else if (!earlyRetry && !quotaRetried && !quotaRetryTimer && !quotaRefresh) {
576
+ // quota-state caches per provider, so healthy accounts within the failed provider may also be re-requested once per episode.
577
+ quotaRetryTimer = setTimeout(() => {
578
+ quotaRetryTimer = undefined;
579
+ quotaRetried = true;
580
+ void tickQuota(true);
581
+ }, Math.min(10_000, quotaIntervalMs()));
582
+ quotaRetryTimer.unref();
583
+ }
584
+ }
522
585
  if (changed.has("quota.changed"))
523
586
  emit({ topic: "quota.changed", at: now() });
524
587
  }
@@ -595,6 +658,11 @@ export function createSnapshotService(options) {
595
658
  analyticsTimer.unref();
596
659
  }
597
660
  function stopPollers() {
661
+ pollerEpoch += 1;
662
+ if (quotaRetryTimer)
663
+ clearTimeout(quotaRetryTimer);
664
+ quotaRetryTimer = undefined;
665
+ quotaRetried = false;
598
666
  if (quotaTimer) {
599
667
  clearInterval(quotaTimer);
600
668
  quotaTimer = undefined;
@@ -612,17 +680,51 @@ export function createSnapshotService(options) {
612
680
  startPollers();
613
681
  }
614
682
  function dirty() {
615
- for (const entry of cache.values())
683
+ for (const entry of cache.values()) {
616
684
  entry.stale = true;
685
+ entry.invalidated = true;
686
+ }
617
687
  }
618
688
  return {
619
689
  home: (input) => load(homeKey(input.range), () => options.source.home({ range: input.range })),
620
- quota: () => load(quotaKey(), () => {
621
- if (!options.source.quota) {
622
- return Promise.reject(new Error("Quota source unavailable"));
623
- }
624
- return options.source.quota();
625
- }),
690
+ quota: (input) => {
691
+ const compute = () => {
692
+ if (!options.source.quota) {
693
+ return Promise.reject(new Error("Quota source unavailable"));
694
+ }
695
+ return options.source.quota();
696
+ };
697
+ if (!input?.refresh)
698
+ return load(quotaKey(), compute);
699
+ if (quotaRefresh)
700
+ return quotaRefresh;
701
+ const refresh = (async () => {
702
+ await quotaPoll;
703
+ await inflight.get(quotaKey())?.promise.catch(() => undefined);
704
+ const cached = cache.get(quotaKey());
705
+ if (cached)
706
+ cached.stale = true;
707
+ const forcedCompute = () => options.source.quota({ refresh: true });
708
+ try {
709
+ const result = await load(quotaKey(), forcedCompute, true);
710
+ if (!closed)
711
+ emit({ topic: "quota.changed", at: now() });
712
+ return result;
713
+ }
714
+ finally {
715
+ if (!closed && computes.get(quotaKey()) === forcedCompute)
716
+ computes.set(quotaKey(), compute);
717
+ }
718
+ })();
719
+ quotaRefresh = refresh;
720
+ void refresh
721
+ .finally(() => {
722
+ if (quotaRefresh === refresh)
723
+ quotaRefresh = undefined;
724
+ })
725
+ .catch(() => undefined);
726
+ return refresh;
727
+ },
626
728
  project: (input) => load(projectKey(input.projectId, input.range), () => options.source.project({ projectId: input.projectId, range: input.range })),
627
729
  session: (input) => load(sessionKey(input.sessionId), () => options.source.session({ sessionId: input.sessionId })),
628
730
  groups: (query) => load(groupsKey(query), () => {
@@ -671,8 +773,10 @@ export function createSnapshotService(options) {
671
773
  if (settingsOptions?.scope !== "visibility") {
672
774
  for (const [key, entry] of cache) {
673
775
  const kind = kindOf(key);
674
- if (kind === "quota" || kind === "home" || kind === "project")
776
+ if (kind === "quota" || kind === "home" || kind === "project") {
675
777
  entry.stale = true;
778
+ entry.invalidated = true;
779
+ }
676
780
  }
677
781
  // Re-read both interval getters from live settings (R16).
678
782
  restartPollers();
@@ -695,6 +799,10 @@ export function createSnapshotService(options) {
695
799
  sourceChanged() {
696
800
  if (closed)
697
801
  return;
802
+ if (quotaRetryTimer)
803
+ clearTimeout(quotaRetryTimer);
804
+ quotaRetryTimer = undefined;
805
+ quotaRetried = false;
698
806
  // The cached payloads remain useful as last-good fallback, but they must
699
807
  // never be served as fresh data from the previous owner.
700
808
  sourceGeneration += 1;
@@ -1,12 +1,13 @@
1
1
  import { createLoadConfigMeta, loadConfig } from "../lib/config.js";
2
2
  import { rawAssistantRowHasTokenUsage } from "../lib/opencode-storage.js";
3
3
  import { collectQuotaDashboardProviderResults, } from "../lib/quota-render-data.js";
4
+ import { withoutClaudeAgentSavedResets } from "../lib/quota-state.js";
4
5
  import { getProviders } from "../providers/registry.js";
5
6
  import { AnalyticsNotFoundError, createUsageAnalytics, } from "./aggregation.js";
6
7
  import { createAnalyticsModel } from "./analytics-model.js";
7
8
  import { createAnalyticsReadService } from "./analytics-service.js";
8
9
  import { buildCardId, hashQuotaCardIdentity } from "./identity.js";
9
- import { buildProviderCards, openAiOptionalVisibilityRows, } from "./provider-cards.js";
10
+ import { buildProviderCards, cardSourceKey, openAiOptionalVisibilityRows, UNSCOPED, } from "./provider-cards.js";
10
11
  import { TEMPORAL_QUOTA_POLICIES } from "./temporal-quota-policy-data.js";
11
12
  import { buildTemporalStatus, listTemporalProviderSources, readBundledTemporalCatalog, } from "./temporal-status.js";
12
13
  import { resolveHostTimeZone } from "./time-zone.js";
@@ -38,13 +39,6 @@ function translateAnalyticsError(error) {
38
39
  function createDefaultAnalyticsService() {
39
40
  return createAnalyticsReadService();
40
41
  }
41
- /**
42
- * A successful measurement is at least one quota entry. Discovered account
43
- * descriptors alone (an error-only account list) are not a measurement.
44
- */
45
- function hasMeasurements(probe) {
46
- return probe.result.entries.length > 0;
47
- }
48
42
  /**
49
43
  * A readable Console login whose workspace has no Go entitlement is a valid
50
44
  * current result, not a transient failure. Keeping the previous measurement in
@@ -120,8 +114,6 @@ function cardPreferences(config) {
120
114
  providerOrder: config.dashboard.providerOrder,
121
115
  cardOrder: config.dashboard.cardOrder,
122
116
  };
123
- if (config.quotaProjection !== undefined)
124
- preferences.quotaProjection = config.quotaProjection;
125
117
  if (config.resetTimeDecimals !== undefined) {
126
118
  preferences.resetTimeDecimals = config.resetTimeDecimals;
127
119
  }
@@ -259,7 +251,7 @@ export function createDashboardReadSource(options) {
259
251
  globalConfigDir: options.configDir,
260
252
  });
261
253
  }
262
- async function collect(config, nowMs, providers) {
254
+ async function collect(config, nowMs, providers, refresh = false) {
263
255
  const openaiResetDetailsVisible = createOpenAiResetDetailsVisibility(config);
264
256
  if (options.collectProviderResults) {
265
257
  return options.collectProviderResults({
@@ -276,22 +268,11 @@ export function createDashboardReadSource(options) {
276
268
  config,
277
269
  workspaceRoot: options.workspaceRoot,
278
270
  providers,
271
+ forceProviderRefresh: refresh,
279
272
  openaiResetDetailsVisible,
280
273
  });
281
274
  }
282
- /**
283
- * Merge one cycle with the per-provider last-good map (checkpoint review
284
- * finding 9):
285
- *
286
- * - New entries are the only successful measurement; refreshed accounts are
287
- * taken from the measurement snapshot, never from a descriptor-only result.
288
- * - A provider without new measurements keeps its last-good entries/accounts
289
- * but surfaces the *current* cycle's errors.
290
- * - A selected provider missing from the cycle (slow/unavailable probe) keeps
291
- * its last-good probe.
292
- * - Any substitution is reported so the snapshot can be marked stale and the
293
- * last successful poll timestamp is not advanced.
294
- */
275
+ /** Keep last-good entries scoped to the current credential and card identity. */
295
276
  function mergeProviderResults(probes, selected) {
296
277
  const selectedIds = new Set(selected.map((provider) => provider.id));
297
278
  for (const providerId of lastGoodProbes.keys()) {
@@ -300,66 +281,102 @@ export function createDashboardReadSource(options) {
300
281
  }
301
282
  const merged = [];
302
283
  const seen = new Set();
303
- let substituted = false;
284
+ let anyFresh = false;
285
+ let anyError = false;
286
+ let dropped = false;
287
+ let anyRetained = false;
304
288
  for (const probe of probes) {
305
289
  seen.add(probe.providerId);
306
- if (hasMeasurements(probe)) {
307
- lastGoodProbes.set(probe.providerId, probe);
308
- merged.push(probe);
309
- continue;
310
- }
311
290
  if (hasRevokedOpenCodeGoEntitlement(probe)) {
312
291
  // A revoked entitlement replaces the measurement instead of falling
313
292
  // back to it; the current result (possibly descriptor-only) is fresh.
314
293
  lastGoodProbes.delete(probe.providerId);
294
+ anyFresh = true;
315
295
  merged.push(probe);
316
296
  continue;
317
297
  }
318
- const lastGood = lastGoodProbes.get(probe.providerId);
319
- if (!lastGood) {
320
- // Nothing was ever measured for this provider: expose the current
321
- // error/no-data result as-is.
322
- merged.push(probe);
323
- continue;
298
+ let store = lastGoodProbes.get(probe.providerId);
299
+ if (!probe.cacheScope || store?.cacheScope !== probe.cacheScope) {
300
+ lastGoodProbes.delete(probe.providerId);
301
+ store = undefined;
324
302
  }
325
- substituted = true;
303
+ const accountIds = new Set((probe.result.accounts ?? []).map((account) => account.sourceId));
304
+ const entries = new Map();
305
+ for (const entry of probe.result.entries) {
306
+ const key = cardSourceKey(entry.accounting.sourceId, accountIds);
307
+ const group = entries.get(key) ?? [];
308
+ group.push(entry);
309
+ entries.set(key, group);
310
+ }
311
+ const errors = probe.result.errors.filter((error) => error.kind !== "intentional-filter");
312
+ anyError ||= errors.length > 0;
313
+ const failed = new Set(errors.map((error) => cardSourceKey(error.sourceId, accountIds)));
314
+ const rateLimited = new Set(errors
315
+ .filter((error) => error.retryAtMs !== undefined)
316
+ .map((error) => cardSourceKey(error.sourceId, accountIds)));
317
+ const freshKeys = [...entries.keys()].filter((key) => !rateLimited.has(key));
318
+ anyFresh ||= freshKeys.length > 0;
319
+ const next = new Map();
320
+ const retained = new Set();
321
+ for (const key of freshKeys)
322
+ next.set(key, entries.get(key));
323
+ for (const key of rateLimited)
324
+ if (entries.has(key)) {
325
+ retained.add(key);
326
+ // A failed refresh proves neither eligibility nor expiry, so retained rows drop saved resets.
327
+ const old = withoutClaudeAgentSavedResets(store?.bySource.get(key) ?? []);
328
+ if (old.length > 0)
329
+ next.set(key, old);
330
+ }
331
+ for (const [key, old] of store?.bySource ?? []) {
332
+ if (entries.has(key) || (freshKeys.length > 0 && !failed.has(key)))
333
+ continue;
334
+ if (key !== UNSCOPED && !accountIds.has(key))
335
+ continue;
336
+ const safe = withoutClaudeAgentSavedResets(old).filter((entry) => cardSourceKey(entry.accounting.sourceId, accountIds) === key);
337
+ if (safe.length === 0)
338
+ continue;
339
+ entries.set(key, safe);
340
+ next.set(key, safe);
341
+ retained.add(key);
342
+ }
343
+ if (probe.cacheScope)
344
+ lastGoodProbes.set(probe.providerId, { cacheScope: probe.cacheScope, bySource: next });
345
+ anyRetained ||= retained.size > 0;
326
346
  merged.push({
327
- providerId: probe.providerId,
328
- result: { ...lastGood.result, errors: probe.result.errors },
347
+ ...probe,
348
+ result: { ...probe.result, entries: [...entries.values()].flat() },
349
+ retainedSourceIds: new Set([...retained].filter((key) => key !== UNSCOPED)),
350
+ retainedUnscoped: retained.has(UNSCOPED),
329
351
  });
330
352
  }
331
353
  for (const provider of selected) {
332
354
  if (seen.has(provider.id))
333
355
  continue;
334
- const lastGood = lastGoodProbes.get(provider.id);
335
- if (!lastGood)
336
- continue;
337
- substituted = true;
338
- merged.push(lastGood);
356
+ lastGoodProbes.delete(provider.id);
357
+ dropped = true;
339
358
  }
340
- return { probes: merged, substituted };
359
+ return { probes: merged, substituted: !anyFresh && (anyRetained || anyError || dropped) };
341
360
  }
342
- async function runQuotaCycle() {
361
+ async function runQuotaCycle(refresh = false) {
343
362
  const nowMs = now();
344
363
  try {
345
364
  const config = await loadDashboardConfig();
346
365
  const allProviders = options.providers ?? getProviders();
347
366
  const selected = selectQuotaProviders(config, allProviders);
348
- const probes = await collect(config, nowMs, selected);
367
+ const probes = await collect(config, nowMs, selected, refresh);
349
368
  const merged = mergeProviderResults(probes, selected);
369
+ // OpenAI's observation timestamp is captured after its usage body is
370
+ // consumed. Project and timestamp the completed collection together.
371
+ const projectionNowMs = now();
350
372
  // No hidden-card id filters this list: hidden cards remain collected and
351
373
  // are hidden by the browser. Ordering is still applied to assembled cards.
352
374
  const cards = buildProviderCards({
353
375
  probes: merged.probes,
354
376
  preferences: cardPreferences(config),
355
- nowMs,
377
+ nowMs: projectionNowMs,
356
378
  providerLabel: options.providerLabel,
357
379
  });
358
- // A substituted provider is cached data: mark the snapshot stale and do
359
- // not advance the successful poll timestamp (checkpoint review finding 9).
360
- const polledAtMs = merged.substituted
361
- ? (lastQuotaSnapshot?.providers.polledAtMs ?? nowMs)
362
- : nowMs;
363
380
  const snapshot = {
364
381
  generatedAtMs: nowMs,
365
382
  stale: merged.substituted,
@@ -367,7 +384,7 @@ export function createDashboardReadSource(options) {
367
384
  providers: {
368
385
  cards,
369
386
  enabledProviders: config.enabledProviders,
370
- polledAtMs,
387
+ polledAtMs: projectionNowMs,
371
388
  },
372
389
  };
373
390
  const temporal = temporalStatusForCards(cards, nowMs);
@@ -378,13 +395,38 @@ export function createDashboardReadSource(options) {
378
395
  }
379
396
  catch (error) {
380
397
  if (lastQuotaSnapshot) {
381
- return { ...lastQuotaSnapshot, generatedAtMs: nowMs, stale: true };
398
+ return {
399
+ ...lastQuotaSnapshot,
400
+ generatedAtMs: nowMs,
401
+ stale: true,
402
+ temporal: undefined,
403
+ providers: { ...lastQuotaSnapshot.providers, cards: [] },
404
+ };
382
405
  }
383
406
  throw error;
384
407
  }
385
408
  }
386
- function quota() {
409
+ let quotaRefresh;
410
+ function quota(input) {
411
+ if (input?.refresh) {
412
+ if (quotaRefresh)
413
+ return quotaRefresh;
414
+ const refresh = (async () => {
415
+ await quotaCycle?.catch(() => undefined);
416
+ return runQuotaCycle(true);
417
+ })();
418
+ quotaRefresh = refresh;
419
+ void refresh
420
+ .finally(() => {
421
+ if (quotaRefresh === refresh)
422
+ quotaRefresh = undefined;
423
+ })
424
+ .catch(() => undefined);
425
+ return refresh;
426
+ }
387
427
  // Every selected provider starts in one cycle; concurrent readers share it.
428
+ if (quotaRefresh)
429
+ return quotaRefresh;
388
430
  if (quotaCycle)
389
431
  return quotaCycle;
390
432
  const cycle = runQuotaCycle().finally(() => {