opencode-quota-gui 1.3.1 → 1.3.2

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 (155) hide show
  1. package/README.md +16 -12
  2. package/dist/contracts/build-identity.js +1 -1
  3. package/dist/contracts/card-order.d.ts +2 -0
  4. package/dist/contracts/card-order.js +2 -2
  5. package/dist/contracts/card-visibility.d.ts +2 -1
  6. package/dist/contracts/card-visibility.js +2 -1
  7. package/dist/contracts/dashboard.d.ts +87 -5
  8. package/dist/contracts/dashboard.js +10 -0
  9. package/dist/contracts/dto-guards.d.ts +4 -0
  10. package/dist/contracts/dto-guards.js +29 -7
  11. package/dist/contracts/guards.js +3 -1
  12. package/dist/contracts/identity.d.ts +37 -5
  13. package/dist/contracts/identity.js +43 -0
  14. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  15. package/dist/contracts/provider-auto-resume.js +24 -0
  16. package/dist/contracts/provider-failure.d.ts +22 -0
  17. package/dist/contracts/provider-failure.js +25 -1
  18. package/dist/contracts/row-order.d.ts +13 -0
  19. package/dist/contracts/row-order.js +34 -0
  20. package/dist/contracts/row-visibility.d.ts +53 -0
  21. package/dist/contracts/row-visibility.js +130 -0
  22. package/dist/data/modelsdev-pricing.min.json +1 -1
  23. package/dist/data/modelsdev-temporal.min.json +3 -634
  24. package/dist/gui/aggregation.d.ts +29 -1
  25. package/dist/gui/aggregation.js +157 -4
  26. package/dist/gui/analytics-bridge.d.ts +8 -9
  27. package/dist/gui/analytics-bridge.js +197 -54
  28. package/dist/gui/analytics-engine.d.ts +7 -15
  29. package/dist/gui/analytics-engine.js +246 -106
  30. package/dist/gui/analytics-model.d.ts +7 -0
  31. package/dist/gui/analytics-model.js +75 -9
  32. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  33. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  34. package/dist/gui/analytics-protocol.d.ts +17 -7
  35. package/dist/gui/analytics-protocol.js +1 -0
  36. package/dist/gui/analytics-service.d.ts +10 -0
  37. package/dist/gui/analytics-service.js +30 -9
  38. package/dist/gui/analytics-state.d.ts +30 -5
  39. package/dist/gui/analytics-state.js +46 -7
  40. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  41. package/dist/gui/analytics-worker-runtime.js +9 -1
  42. package/dist/gui/analytics-worker.js +11 -0
  43. package/dist/gui/config.d.ts +2 -2
  44. package/dist/gui/config.js +46 -5
  45. package/dist/gui/identity.d.ts +6 -20
  46. package/dist/gui/identity.js +6 -54
  47. package/dist/gui/primary-quota-windows.js +55 -34
  48. package/dist/gui/provider-cards.d.ts +12 -8
  49. package/dist/gui/provider-cards.js +12 -53
  50. package/dist/gui/quota-notification-detector.d.ts +25 -2
  51. package/dist/gui/quota-notification-detector.js +60 -5
  52. package/dist/gui/quota-notification-observer.d.ts +1 -1
  53. package/dist/gui/quota-notification-observer.js +5 -1
  54. package/dist/gui/quota-observation.d.ts +4 -0
  55. package/dist/gui/quota-observation.js +18 -0
  56. package/dist/gui/rpc.js +3 -0
  57. package/dist/gui/server.js +6 -1
  58. package/dist/gui/snapshot-service.d.ts +3 -17
  59. package/dist/gui/snapshot-service.js +159 -9
  60. package/dist/gui/sources.js +84 -11
  61. package/dist/gui/temporal-status.d.ts +3 -2
  62. package/dist/gui/temporal-status.js +10 -6
  63. package/dist/gui-experimental.cjs +228 -228
  64. package/dist/lib/accounting-format.d.ts +8 -0
  65. package/dist/lib/accounting-format.js +12 -2
  66. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  67. package/dist/lib/anthropic-api-auth.js +27 -0
  68. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  69. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  70. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  71. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  72. package/dist/lib/anthropic.d.ts +22 -4
  73. package/dist/lib/anthropic.js +498 -180
  74. package/dist/lib/cache-observer-ingestion.js +27 -0
  75. package/dist/lib/cache-observer.d.ts +3 -0
  76. package/dist/lib/cache-observer.js +9 -3
  77. package/dist/lib/cli-show.d.ts +5 -0
  78. package/dist/lib/cli-show.js +16 -5
  79. package/dist/lib/cli-status.js +3 -6
  80. package/dist/lib/config.d.ts +1 -1
  81. package/dist/lib/config.js +64 -2
  82. package/dist/lib/dashboard-visibility.d.ts +5 -0
  83. package/dist/lib/dashboard-visibility.js +11 -10
  84. package/dist/lib/display-sanitize.js +1 -0
  85. package/dist/lib/entries.d.ts +10 -1
  86. package/dist/lib/entries.js +4 -0
  87. package/dist/lib/grouped-entry-normalization.js +1 -1
  88. package/dist/lib/maintainer-announcements.js +2 -2
  89. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  90. package/dist/lib/modelsdev-pricing.js +457 -63
  91. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  92. package/dist/lib/modelsdev-temporal.js +16 -2
  93. package/dist/lib/opencode-config-providers.js +2 -2
  94. package/dist/lib/opencode-storage.d.ts +20 -0
  95. package/dist/lib/opencode-storage.js +89 -2
  96. package/dist/lib/opencode-version-core.d.ts +7 -0
  97. package/dist/lib/opencode-version-core.js +10 -0
  98. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  99. package/dist/lib/opencode-warming-refresh.js +95 -0
  100. package/dist/lib/provider-metadata.d.ts +11 -3
  101. package/dist/lib/provider-metadata.js +20 -2
  102. package/dist/lib/provider-registration.d.ts +342 -3
  103. package/dist/lib/provider-registration.js +409 -27
  104. package/dist/lib/quota-auto-resume.d.ts +74 -0
  105. package/dist/lib/quota-auto-resume.js +539 -0
  106. package/dist/lib/quota-command-format.js +22 -9
  107. package/dist/lib/quota-identity.d.ts +64 -0
  108. package/dist/lib/quota-identity.js +111 -0
  109. package/dist/lib/quota-providers.js +2 -2
  110. package/dist/lib/quota-render-data.js +2 -2
  111. package/dist/lib/quota-reset-notifications.js +11 -155
  112. package/dist/lib/quota-retry-wait.d.ts +106 -5
  113. package/dist/lib/quota-retry-wait.js +301 -34
  114. package/dist/lib/quota-runtime-context.js +1 -0
  115. package/dist/lib/quota-state-codec.d.ts +2 -0
  116. package/dist/lib/quota-state-codec.js +14 -1
  117. package/dist/lib/quota-state.d.ts +1 -1
  118. package/dist/lib/quota-state.js +60 -28
  119. package/dist/lib/quota-stats.d.ts +26 -0
  120. package/dist/lib/quota-stats.js +19 -1
  121. package/dist/lib/quota-surface-data.js +18 -3
  122. package/dist/lib/quota-telemetry.js +2 -2
  123. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  124. package/dist/lib/resolved-auth-identity.js +44 -0
  125. package/dist/lib/state-file-lock.d.ts +26 -0
  126. package/dist/lib/state-file-lock.js +205 -0
  127. package/dist/lib/toast-format-grouped.js +7 -4
  128. package/dist/lib/tui-compact-format.js +29 -16
  129. package/dist/lib/types.d.ts +20 -0
  130. package/dist/lib/types.js +4 -1
  131. package/dist/plugin.js +67 -1
  132. package/dist/providers/alibaba-coding-plan.js +21 -3
  133. package/dist/providers/alibaba-token-plan.js +9 -5
  134. package/dist/providers/anthropic.d.ts +6 -2
  135. package/dist/providers/anthropic.js +123 -14
  136. package/dist/providers/chutes.js +2 -0
  137. package/dist/providers/claude-agent.js +24 -5
  138. package/dist/providers/copilot.js +5 -4
  139. package/dist/providers/glm-coding-plan-provider.js +30 -23
  140. package/dist/providers/ollama-cloud.js +10 -0
  141. package/dist/providers/openai.js +24 -23
  142. package/dist/providers/opencode-go.js +7 -6
  143. package/dist/providers/opencode-zen.js +1 -1
  144. package/dist/providers/result-helpers.d.ts +4 -2
  145. package/dist/providers/result-helpers.js +5 -1
  146. package/dist/providers/synthetic.js +4 -0
  147. package/dist/providers/xai.js +9 -8
  148. package/dist/rpc.d.ts +8 -0
  149. package/dist/rpc.js +15 -2
  150. package/dist/ui/assets/{index-BcueIm3Z.css → index-6_g1FHs-.css} +1 -1
  151. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  152. package/dist/ui/assets/{popover-4bFSvRZ7.js → popover-C4ZLYe9E.js} +1 -1
  153. package/dist/ui/index.html +2 -2
  154. package/package.json +3 -3
  155. package/dist/ui/assets/index-C6qRSoh8.js +0 -10
@@ -1,5 +1,5 @@
1
1
  import type { QuotaCardRow } from "../contracts/dashboard.js";
2
- import type { ProviderFailureCategory } from "../contracts/provider-failure.js";
2
+ import type { ProviderFailureCategory, QuotaAttemptOutcome } from "../contracts/provider-failure.js";
3
3
  import { type ResetObservation } from "../lib/quota-reset-notifications.js";
4
4
  import type { NativeQuotaNotificationPolicy } from "../lib/types.js";
5
5
  export declare const QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION: 1;
@@ -78,14 +78,33 @@ export interface QuotaNotificationCardObservation {
78
78
  accountLabel?: string;
79
79
  /** Bare provider-scope hash used by normalized legacy hidden-card semantics. */
80
80
  providerScopeHash?: string;
81
+ /**
82
+ * True when the card's rows are retained last-good data rather than this
83
+ * cycle's measurement. A transient failed poll never raises a provider-error
84
+ * notification for retained readings; the card still shows the error.
85
+ */
86
+ stale?: boolean;
81
87
  rows: readonly QuotaNotificationRowObservation[];
88
+ /**
89
+ * Declared optional-row controls. Their stable ids and aliases make a hidden
90
+ * field silent regardless of which shape the provider emitted this cycle.
91
+ */
92
+ visibilityRows?: readonly {
93
+ rowId: string;
94
+ aliases?: readonly string[];
95
+ }[];
82
96
  errors?: readonly QuotaNotificationProviderErrorObservation[];
83
97
  }
84
98
  /** Only the safe structured category is read; labels and messages are ignored. */
85
99
  export interface QuotaNotificationProviderErrorObservation {
86
100
  failureCategory?: ProviderFailureCategory;
101
+ /** A cooldown skip made no request and is never a failure observation. */
102
+ attemptOutcome?: QuotaAttemptOutcome;
87
103
  }
88
- /** Unknown or absent categories are never notifiable. */
104
+ /**
105
+ * Unknown or absent categories are never notifiable. A cooldown skip is a
106
+ * timing decision, not a provider failure, so it is also not notifiable.
107
+ */
89
108
  export declare function isNotifiableProviderError(error: QuotaNotificationProviderErrorObservation): boolean;
90
109
  /** Exact reset observation shared with the legacy notifier. */
91
110
  export type QuotaNotificationResetObservation = ResetObservation;
@@ -100,6 +119,10 @@ export interface QuotaNotificationRowState {
100
119
  export interface QuotaNotificationProviderState {
101
120
  status: "healthy" | "error";
102
121
  observedAtMs: number;
122
+ /** Consecutive observations that carried a notifiable provider error. */
123
+ consecutiveErrors?: number;
124
+ /** The latest error observation was suppressed because its rows were retained. */
125
+ staleError?: boolean;
103
126
  }
104
127
  /** Memory-only detector state. Do not persist rows/providers across restarts. */
105
128
  export interface QuotaNotificationDetectorState {
@@ -20,6 +20,9 @@
20
20
  * - `provider-error`: a proven healthy -> error transition, only when the
21
21
  * caller supplies safe structured failure provenance. Error labels and
22
22
  * messages are never inspected.
23
+ * - Retained last-good rows (a `stale` card) keep their previous observation
24
+ * state and are never evaluated for low/exhausted/reset transitions; live
25
+ * provider errors on that card still count.
23
26
  * - Cooldown always applies to the exact fingerprint and is never bypassed.
24
27
  * - First startup and newly visible cards or rows silently baseline.
25
28
  *
@@ -49,6 +52,7 @@
49
52
  */
50
53
  import { createHash } from "node:crypto";
51
54
  import { isCardHidden } from "../contracts/card-visibility.js";
55
+ import { effectiveHiddenRowIds } from "../contracts/row-visibility.js";
52
56
  import { MAX_TRANSITION_AGE_MS, updateObservation as updateLegacyResetObservation, } from "../lib/quota-reset-notifications.js";
53
57
  export const QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION = 1;
54
58
  /** Shared proven reset-transition age limit re-exported for detector consumers. */
@@ -59,8 +63,13 @@ export const RESET_TRANSITION_MAX_AGE_MS = MAX_TRANSITION_AGE_MS;
59
63
  */
60
64
  export const QUOTA_NOTIFICATION_PROVIDER_ERROR_CATEGORY = "provider_api";
61
65
  const FINGERPRINT_DOMAIN = "ocq-quota-notification-v1";
62
- /** Unknown or absent categories are never notifiable. */
66
+ /**
67
+ * Unknown or absent categories are never notifiable. A cooldown skip is a
68
+ * timing decision, not a provider failure, so it is also not notifiable.
69
+ */
63
70
  export function isNotifiableProviderError(error) {
71
+ if (error.attemptOutcome === "cooldown")
72
+ return false;
64
73
  return error.failureCategory === QUOTA_NOTIFICATION_PROVIDER_ERROR_CATEGORY;
65
74
  }
66
75
  /**
@@ -150,7 +159,7 @@ function resetWindowForRow(row) {
150
159
  export function detectQuotaNotifications(input) {
151
160
  const nowMs = input.nowMs;
152
161
  const hiddenCards = new Set(input.hiddenCards ?? []);
153
- const hiddenRows = new Set(input.hiddenRows ?? []);
162
+ const configuredHiddenRows = input.hiddenRows ?? [];
154
163
  const previousState = input.state?.version === QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION ? input.state : undefined;
155
164
  const cooldowns = { ...(input.cooldowns ?? {}) };
156
165
  const notifications = [];
@@ -171,9 +180,26 @@ export function detectQuotaNotifications(input) {
171
180
  if (seenCards.has(card.cardId) || isCardHidden(card, hiddenCards))
172
181
  continue;
173
182
  seenCards.add(card.cardId);
183
+ const hiddenRows = effectiveHiddenRowIds(card.rows.map((row) => row.rowId), configuredHiddenRows, card.visibilityRows ?? []);
184
+ const cardRowsRetained = card.stale === true;
185
+ if (cardRowsRetained) {
186
+ // Retained last-good rows stay out of threshold/reset evaluation. Keep
187
+ // their previous observation state so the next fresh reading still
188
+ // compares against the last real measurement.
189
+ const prefix = `${card.cardId}\u001f`;
190
+ for (const [key, state] of Object.entries(previousState?.rows ?? {})) {
191
+ if (!key.startsWith(prefix) || nextRows.has(key))
192
+ continue;
193
+ if (hiddenRows.has(key.slice(prefix.length)))
194
+ continue;
195
+ nextRows.set(key, cloneRowState(state));
196
+ }
197
+ }
174
198
  for (const row of card.rows) {
175
199
  if (hiddenRows.has(row.rowId))
176
200
  continue;
201
+ if (cardRowsRetained)
202
+ continue;
177
203
  if (!isEligiblePercentRow(row))
178
204
  continue;
179
205
  const key = rowStateKey(card.cardId, row.rowId);
@@ -287,11 +313,40 @@ export function detectQuotaNotifications(input) {
287
313
  nextProviders.set(card.cardId, { ...previousProvider });
288
314
  continue;
289
315
  }
290
- const status = (card.errors?.some(isNotifiableProviderError) ?? false) ? "error" : "healthy";
291
- nextProviders.set(card.cardId, { status, observedAtMs: nowMs });
292
- if (!previousProvider || previousProvider.status !== "healthy" || status !== "error") {
316
+ const isError = card.errors?.some(isNotifiableProviderError) ?? false;
317
+ // A cooldown skip made no request: it is neither a failure observation nor
318
+ // a recovery, so an existing failure streak and its retained-error
319
+ // suppression stay intact until a real attempt reports.
320
+ const isCooldownSkip = !isError && (card.errors?.some((error) => error.attemptOutcome === "cooldown") ?? false);
321
+ if (isCooldownSkip && previousProvider !== undefined) {
322
+ nextProviders.set(card.cardId, { ...previousProvider });
293
323
  continue;
294
324
  }
325
+ const status = isError ? "error" : "healthy";
326
+ const consecutiveErrors = isError
327
+ ? previousProvider?.status === "error"
328
+ ? (previousProvider.consecutiveErrors ?? 1) + 1
329
+ : 1
330
+ : 0;
331
+ const providerState = { status, observedAtMs: nowMs };
332
+ if (isError) {
333
+ providerState.consecutiveErrors = consecutiveErrors;
334
+ providerState.staleError = card.stale === true;
335
+ }
336
+ nextProviders.set(card.cardId, providerState);
337
+ if (!previousProvider || status !== "error") {
338
+ continue;
339
+ }
340
+ // One transient poll failure on a card that still shows retained last-good
341
+ // rows is silent; the second consecutive failing observation is a proven
342
+ // persistent error and alerts. A fresh error without retained rows alerts
343
+ // immediately. The card shows the error either way.
344
+ const freshTransition = previousProvider.status === "healthy" && card.stale !== true;
345
+ const persistentAfterSuppressed = previousProvider.status === "error" &&
346
+ previousProvider.staleError === true &&
347
+ consecutiveErrors === 2;
348
+ if (!freshTransition && !persistentAfterSuppressed)
349
+ continue;
295
350
  if (policy.enabled && policy.providerError.enabled) {
296
351
  const fingerprint = quotaNotificationFingerprint({
297
352
  kind: "provider-error",
@@ -22,7 +22,7 @@ export interface QuotaNotificationObserverOptions {
22
22
  }
23
23
  export interface QuotaNotificationObserver {
24
24
  /**
25
- * Queue one observation of a fresh quota snapshot. A caller with an
25
+ * Queue one observation of a completed quota source cycle. A caller with an
26
26
  * asynchronous source read must capture `epoch()` before that read and pass
27
27
  * it here; an observation whose captured epoch no longer matches is dropped.
28
28
  * Never rejects.
@@ -24,6 +24,7 @@ import { getGuiPrivateStatePath } from "../lib/private-state-paths.js";
24
24
  import { DEFAULT_CONFIG, } from "../lib/types.js";
25
25
  import { createGuiLogger } from "./log.js";
26
26
  import { detectQuotaNotifications, QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION, } from "./quota-notification-detector.js";
27
+ import { isLiveQuotaObservation } from "./quota-observation.js";
27
28
  const PERSISTED_STATE_VERSION = 1;
28
29
  const DEFAULT_STATE_FILE = "quota-notifications.json";
29
30
  const MAX_LABEL_LENGTH = 80;
@@ -309,7 +310,10 @@ export function createQuotaNotificationObserver(options) {
309
310
  async function observeNow(snapshot, epoch) {
310
311
  if (closed || epoch !== sourceEpoch)
311
312
  return;
312
- if (snapshot.stale === true)
313
+ // Cached replays are synthesized from an earlier snapshot and carry no live
314
+ // observation. A stale live cycle still carries fresh error observations and
315
+ // retained rows; the detector excludes those rows from transitions.
316
+ if (snapshot.stale === true && !isLiveQuotaObservation(snapshot))
313
317
  return;
314
318
  let settings;
315
319
  try {
@@ -0,0 +1,4 @@
1
+ import type { QuotaSnapshot } from "../contracts/dashboard.js";
2
+ export declare function markQuotaObservationLive(snapshot: QuotaSnapshot): QuotaSnapshot;
3
+ export declare function isLiveQuotaObservation(snapshot: QuotaSnapshot): boolean;
4
+ //# sourceMappingURL=quota-observation.d.ts.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Live-cycle identity for quota observations.
3
+ *
4
+ * The notification observer must tell a just-finished source cycle from a
5
+ * cached replay of an earlier snapshot. A live cycle can be marked
6
+ * `stale: true` because it retained last-good rows; a cached replay is
7
+ * synthesized separately and is never registered here. WeakSet membership
8
+ * keeps this internal signal out of the DTO and never survives serialization.
9
+ */
10
+ const liveQuotaObservations = new WeakSet();
11
+ export function markQuotaObservationLive(snapshot) {
12
+ liveQuotaObservations.add(snapshot);
13
+ return snapshot;
14
+ }
15
+ export function isLiveQuotaObservation(snapshot) {
16
+ return liveQuotaObservations.has(snapshot);
17
+ }
18
+ //# sourceMappingURL=quota-observation.js.map
package/dist/gui/rpc.js CHANGED
@@ -89,6 +89,9 @@ function mapRpcError(error) {
89
89
  details: sanitizeDashboardErrorDetails(safeCode, errorDetails(error)) ?? {},
90
90
  };
91
91
  }
92
+ // The analytics worker's own `timeout`, `unavailable`, and `closed` codes land
93
+ // here as `internal`: they are terminal for that worker read, not the host's
94
+ // transport deadline, so a client must not re-join them as a timed-out RPC.
92
95
  return {
93
96
  code: "internal",
94
97
  message: DASHBOARD_ERROR_MESSAGES.internal,
@@ -451,7 +451,12 @@ export function createDashboardServer(options) {
451
451
  return;
452
452
  }
453
453
  snapshots.setViewScope("analytics", "request");
454
- sendJson(res, 200, await snapshots.home({ range }));
454
+ const background = url.searchParams.get("background");
455
+ if (background !== null && background !== "true" && background !== "false") {
456
+ sendError(res, "bad-request");
457
+ return;
458
+ }
459
+ sendJson(res, 200, await snapshots.home({ range, ...(background === "true" ? { background: true } : {}) }));
455
460
  return;
456
461
  }
457
462
  if (rest.length === 2 && rest[0] === "projects") {
@@ -40,8 +40,7 @@
40
40
  *
41
41
  * No TTL, sequence, watermark, or budget machinery exists (R9).
42
42
  */
43
- import type { AnalyticsGroupQuery, AnalyticsGroupSnapshot, DashboardDataSource, DashboardEvent, HomeSnapshot, ProjectSnapshot, QuotaSnapshot, SessionSnapshot } from "../contracts/dashboard.js";
44
- import type { RangeKey } from "../contracts/ranges.js";
43
+ import type { DashboardDataSource, DashboardEvent } from "../contracts/dashboard.js";
45
44
  import { type GuiLogger } from "./log.js";
46
45
  /** Default quota/provider poll interval (spec §4.2; existing config overrides). */
47
46
  export declare const DEFAULT_QUOTA_INTERVAL_MS = 60000;
@@ -67,6 +66,7 @@ export declare const MAX_TRACKED_PAGES = 16;
67
66
  * `refreshAnalytics` is an optional shared worker refresh seam, and `close` is
68
67
  * closed by the lifecycle when the last lease disposes, not by this service.
69
68
  */
69
+ /** Same-key home reads must coalesce, including foreground priority joins. */
70
70
  export type SnapshotSource = Pick<DashboardDataSource, "home" | "project" | "session"> & {
71
71
  quota?: DashboardDataSource["quota"];
72
72
  groups?: DashboardDataSource["groups"];
@@ -102,21 +102,7 @@ export type SnapshotViewScope = "analytics" | "quota";
102
102
  export interface SnapshotViewer {
103
103
  release(): void;
104
104
  }
105
- export interface SnapshotService {
106
- home(input: {
107
- range: RangeKey;
108
- }): Promise<HomeSnapshot>;
109
- quota(input?: {
110
- refresh?: boolean;
111
- }): Promise<QuotaSnapshot>;
112
- project(input: {
113
- projectId: string;
114
- range: RangeKey;
115
- }): Promise<ProjectSnapshot>;
116
- session(input: {
117
- sessionId: string;
118
- }): Promise<SessionSnapshot>;
119
- groups(query: AnalyticsGroupQuery): Promise<AnalyticsGroupSnapshot>;
105
+ export interface SnapshotService extends Pick<DashboardDataSource, "home" | "quota" | "project" | "session" | "groups"> {
120
106
  /** Invalidations broadcast over SSE (three topics, never raw snapshots). */
121
107
  subscribe(listener: (event: DashboardEvent) => void): () => void;
122
108
  /**
@@ -41,6 +41,8 @@
41
41
  * No TTL, sequence, watermark, or budget machinery exists (R9).
42
42
  */
43
43
  import { encodeAnalyticsGroupQueryKey } from "../contracts/analytics-entity.js";
44
+ import { isRecord } from "../contracts/dto-guards.js";
45
+ import { isTransientProviderFailureCategory } from "../contracts/provider-failure.js";
44
46
  import { createGuiLogger } from "./log.js";
45
47
  /** Default quota/provider poll interval (spec §4.2; existing config overrides). */
46
48
  export const DEFAULT_QUOTA_INTERVAL_MS = 60_000;
@@ -102,11 +104,15 @@ const DERIVED_NOISE_KEYS = new Set([
102
104
  "untilMs",
103
105
  "startMs",
104
106
  "endMs",
107
+ // A provisional first paint is replaced by the same numbers: the marker is
108
+ // presentation state, and the unconditional replacement event below clears it.
109
+ "provisional",
110
+ "exactError",
105
111
  ]);
106
112
  function stripDerivedNoise(value) {
107
113
  if (Array.isArray(value))
108
114
  return value.map(stripDerivedNoise);
109
- if (typeof value === "object" && value !== null) {
115
+ if (isRecord(value)) {
110
116
  const out = {};
111
117
  for (const [key, child] of Object.entries(value)) {
112
118
  if (DERIVED_NOISE_KEYS.has(key))
@@ -123,6 +129,18 @@ function substantiveOf(snapshot) {
123
129
  function staleFlag(value) {
124
130
  return typeof value === "object" && value !== null && "stale" in value && value.stale === true;
125
131
  }
132
+ /** A provisional first paint whose exact replacement is still computing. */
133
+ function isProvisional(value) {
134
+ return isRecord(value) && value.provisional === true;
135
+ }
136
+ /** Terminal exact-read failure marker on a provisional payload. */
137
+ function hasExactError(cause) {
138
+ return isRecord(cause) && "exactError" in cause && cause.exactError !== undefined;
139
+ }
140
+ /** Terminal exact-read failure carrying the still-useful provisional payload. */
141
+ function withExactFailure(snapshot, message) {
142
+ return { ...snapshot, exactError: message };
143
+ }
126
144
  /**
127
145
  * True when the source payload itself reports stale data. Such a payload must
128
146
  * not enter the cache as fresh: the next read revalidates instead of serving it
@@ -170,6 +188,15 @@ export function createSnapshotService(options) {
170
188
  const logger = options.logger ?? createGuiLogger();
171
189
  const now = options.now ?? Date.now;
172
190
  const cache = new Map();
191
+ /**
192
+ * A just-settled rejected compute. The host's final probe can arrive right
193
+ * after the worker died; joining this outcome briefly avoids starting a
194
+ * second full scan for the same logical read.
195
+ */
196
+ const settledFailures = new Map();
197
+ /** One announcement per exact payload object; joined exact reads share it. */
198
+ const announcedExact = new WeakSet();
199
+ const SETTLED_FAILURE_GRACE_MS = 5_000;
173
200
  let quotaRefresh;
174
201
  let quotaPoll;
175
202
  const computes = new Map();
@@ -351,7 +378,45 @@ export function createSnapshotService(options) {
351
378
  }
352
379
  return version;
353
380
  }
354
- function load(key, compute, force = false) {
381
+ const notifiedLoads = new WeakSet();
382
+ /**
383
+ * Foreground analytics read, stale-while-revalidate. The single analytics
384
+ * worker cannot answer while a synchronous scan runs, so a stale entry returns
385
+ * the last-good DTO immediately flagged stale. A key with no DTO awaits its compute. The compute stays
386
+ * single-flight and commits when it lands; `sessions.changed` is emitted only
387
+ * when a changed result was actually stored, so clients refetch exactly once.
388
+ */
389
+ function load(key, compute, force = false, promote, foreground = false) {
390
+ const prior = cache.get(key);
391
+ const fresh = loadSingleFlight(key, compute, force, promote, foreground);
392
+ if (force || closed || isQuotaKey(key) || !inflight.has(key))
393
+ return fresh;
394
+ const lastGood = prior && prior.sourceGeneration === sourceGeneration && hasStaleMarker(prior.snapshot)
395
+ ? markStale(prior.snapshot)
396
+ : undefined;
397
+ if (lastGood === undefined)
398
+ return fresh;
399
+ const epoch = viewerEpoch;
400
+ void fresh.then((value) => {
401
+ if (closed ||
402
+ epoch !== viewerEpoch ||
403
+ cache.get(key)?.snapshot !== value ||
404
+ notifiedLoads.has(fresh) ||
405
+ // The exact-replacement path owns this announcement when the prior
406
+ // paint was provisional; the scheduler emits once for the payload.
407
+ (prior !== undefined && isProvisional(prior.snapshot)) ||
408
+ // A provisional entry must always announce its exact replacement,
409
+ // even when the substantive payload is unchanged: that event is the
410
+ // only way the UI learns the exact result has landed.
411
+ (prior && !isProvisional(prior.snapshot) && substantiveOf(value) === prior.substantive)) {
412
+ return;
413
+ }
414
+ notifiedLoads.add(fresh);
415
+ emit({ topic: topicFor(key), at: now() });
416
+ }, () => { });
417
+ return Promise.resolve(lastGood);
418
+ }
419
+ function loadSingleFlight(key, compute, force = false, promote, foreground = false) {
355
420
  const epoch = viewerEpoch;
356
421
  const generation = sourceGeneration;
357
422
  // A closed service does not track, register, or cache: the caller still
@@ -372,6 +437,10 @@ export function createSnapshotService(options) {
372
437
  }
373
438
  const pending = inflight.get(key);
374
439
  if (pending && pending.epoch === epoch && pending.sourceGeneration === generation) {
440
+ if (foreground && pending.promote) {
441
+ pending.promote();
442
+ pending.promote = undefined;
443
+ }
375
444
  // The key was requested again in the same viewer session and source
376
445
  // generation while its compute was still pending: preserve single-flight
377
446
  // and let it cache again.
@@ -383,6 +452,16 @@ export function createSnapshotService(options) {
383
452
  }
384
453
  // A pending task from an ended viewer session or a previous source identity
385
454
  // is disowned: this caller runs its own compute instead.
455
+ const settled = settledFailures.get(key);
456
+ if (settled !== undefined) {
457
+ if (!force &&
458
+ settled.epoch === epoch &&
459
+ settled.sourceGeneration === generation &&
460
+ settled.untilMs > now()) {
461
+ return Promise.reject(settled.error);
462
+ }
463
+ settledFailures.delete(key);
464
+ }
386
465
  let computation;
387
466
  try {
388
467
  computation = compute();
@@ -391,6 +470,7 @@ export function createSnapshotService(options) {
391
470
  computation = Promise.reject(error);
392
471
  }
393
472
  const task = {
473
+ promote,
394
474
  epoch,
395
475
  sourceGeneration: generation,
396
476
  promise: Promise.resolve(),
@@ -403,12 +483,19 @@ export function createSnapshotService(options) {
403
483
  }
404
484
  catch (error) {
405
485
  const fallback = tracked.get(key) === task.version ? cache.get(key) : undefined;
406
- if (!fallback)
407
- throw error;
408
486
  // A previous owner's last-good entry may be served only when the DTO
409
487
  // can carry the stale marker. Session snapshots cannot, so their
410
488
  // failure is surfaced rather than presented as fresh old-owner data.
411
- if (fallback.sourceGeneration !== sourceGeneration && !hasStaleMarker(fallback.snapshot)) {
489
+ if (!fallback ||
490
+ (fallback.sourceGeneration !== sourceGeneration && !hasStaleMarker(fallback.snapshot))) {
491
+ if (!closed) {
492
+ settledFailures.set(key, {
493
+ error,
494
+ epoch: task.epoch,
495
+ sourceGeneration: task.sourceGeneration,
496
+ untilMs: now() + SETTLED_FAILURE_GRACE_MS,
497
+ });
498
+ }
412
499
  throw error;
413
500
  }
414
501
  if (!closed && task.epoch === viewerEpoch && task.sourceGeneration === sourceGeneration) {
@@ -419,6 +506,7 @@ export function createSnapshotService(options) {
419
506
  // of the same `(kind, resourceId, range)` key, so it is a T snapshot.
420
507
  return markStale(fallback.snapshot);
421
508
  }
509
+ settledFailures.delete(key);
422
510
  // A commit belongs to the viewer session and source identity that started
423
511
  // the load: a disconnect or owner handoff already dirtied the entries, so
424
512
  // an old result never re-freshens them.
@@ -562,9 +650,7 @@ export function createSnapshotService(options) {
562
650
  return;
563
651
  if (polledSnapshot) {
564
652
  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") &&
653
+ isTransientProviderFailureCategory(error.failureCategory) &&
568
654
  !(error.retryAtMs !== undefined && error.retryAtMs > now())));
569
655
  if (!eligible) {
570
656
  quotaRetried = false;
@@ -680,13 +766,76 @@ export function createSnapshotService(options) {
680
766
  startPollers();
681
767
  }
682
768
  function dirty() {
769
+ settledFailures.clear();
683
770
  for (const entry of cache.values()) {
684
771
  entry.stale = true;
685
772
  entry.invalidated = true;
686
773
  }
687
774
  }
688
775
  return {
689
- home: (input) => load(homeKey(input.range), () => options.source.home({ range: input.range })),
776
+ home: (input) => {
777
+ const key = homeKey(input.range);
778
+ const request = load(key, () => {
779
+ const homeRequest = input.background && input.exact === true
780
+ ? { range: input.range, background: true, exact: true }
781
+ : input.background
782
+ ? { range: input.range, background: true }
783
+ : input.exact === true
784
+ ? { range: input.range, exact: true }
785
+ : { range: input.range };
786
+ return options.source.home(homeRequest);
787
+ },
788
+ // An exact read is an explicit revalidation request and must not be
789
+ // satisfied by a cached provisional/marker entry.
790
+ input.exact === true, input.background
791
+ ? () => {
792
+ void options.source.home({ range: input.range }).catch(() => { });
793
+ }
794
+ : undefined, !input.background);
795
+ void request.then((snapshot) => {
796
+ if (!isProvisional(snapshot) ||
797
+ hasExactError(snapshot) ||
798
+ cache.get(key)?.snapshot !== snapshot ||
799
+ closed)
800
+ return;
801
+ const exact = load(key, () => options.source.home({ range: input.range, exact: true, background: true }),
802
+ // An exact replacement is explicitly requested; a still-cached
803
+ // provisional paint must never satisfy it.
804
+ true, () => {
805
+ void options.source.home({ range: input.range, exact: true }).catch(() => { });
806
+ });
807
+ const settle = () => {
808
+ const current = cache.get(key);
809
+ if (closed || !current || !isProvisional(current.snapshot))
810
+ return;
811
+ if (hasExactError(current.snapshot))
812
+ return;
813
+ const failed = withExactFailure(current.snapshot, "The exact analytics read failed. Retry to finish this range.");
814
+ cache.set(key, {
815
+ ...current,
816
+ snapshot: failed,
817
+ substantive: substantiveOf(failed),
818
+ // Keep the provisional data as a cache hit, but advertise the
819
+ // terminal status. A manual exact retry forces a fresh compute.
820
+ stale: false,
821
+ });
822
+ emit({ topic: topicFor(key), at: now() });
823
+ };
824
+ void exact.then((value) => {
825
+ if (isProvisional(value)) {
826
+ settle();
827
+ return;
828
+ }
829
+ if (isRecord(value)) {
830
+ if (announcedExact.has(value))
831
+ return;
832
+ announcedExact.add(value);
833
+ }
834
+ emit({ topic: topicFor(key), at: now() });
835
+ }, () => settle());
836
+ }, () => { });
837
+ return request;
838
+ },
690
839
  quota: (input) => {
691
840
  const compute = () => {
692
841
  if (!options.source.quota) {
@@ -824,6 +973,7 @@ export function createSnapshotService(options) {
824
973
  computes.clear();
825
974
  cache.clear();
826
975
  inflight.clear();
976
+ settledFailures.clear();
827
977
  tracked.clear();
828
978
  scopedViewers.clear();
829
979
  },