@kortix/ui 0.15.6 → 0.15.7

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 (56) hide show
  1. package/dist/customize/providers/provider-accordion.js +3 -2
  2. package/dist/customize/providers/provider-connect.d.ts +7 -0
  3. package/dist/customize/providers/provider-connect.js +21 -2
  4. package/dist/customize/providers/provider-sheet.js +3 -2
  5. package/dist/customize/sections/gateway-view.d.ts +1 -1
  6. package/dist/customize/sections/gateway-view.js +29 -14
  7. package/dist/customize/sections/llm-provider/chatgpt-subscription-connect.d.ts +3 -1
  8. package/dist/customize/sections/llm-provider/chatgpt-subscription-connect.js +2 -2
  9. package/dist/customize/sections/view/account-secret-resources-panel.js +4 -3
  10. package/dist/customize/sections/view/review-center-connected.js +15 -3
  11. package/dist/customize/sections/view/subscription-usage.d.ts +288 -7
  12. package/dist/customize/sections/view/subscription-usage.js +257 -30
  13. package/dist/i18n/en.d.ts +37 -47
  14. package/dist/i18n/en.js +40 -50
  15. package/dist/i18n/ui-catalog/app-registry-translation-keys.generated.js +5 -0
  16. package/dist/internal/auth/auth-primitives.d.ts +27 -0
  17. package/dist/internal/auth/auth-primitives.js +21 -0
  18. package/dist/internal/billing/index.d.ts +1 -0
  19. package/dist/internal/billing/index.js +2 -0
  20. package/dist/internal/billing/use-free-grant-unspent.d.ts +10 -0
  21. package/dist/internal/billing/use-free-grant-unspent.js +20 -0
  22. package/dist/internal/lib/billing/billing-gate-state.d.ts +20 -0
  23. package/dist/internal/lib/billing/billing-gate-state.js +22 -0
  24. package/dist/internal/lib/error-handler.js +0 -2
  25. package/dist/internal/notifications/notification-inbox.js +1 -1
  26. package/dist/internal/stores/upgrade-dialog-store.d.ts +0 -2
  27. package/dist/internal/stores/upgrade-dialog-store.js +0 -2
  28. package/dist/markdown/setup-links/approval-decision.d.ts +1 -1
  29. package/dist/markdown/setup-links/approval-decision.js +1 -1
  30. package/dist/session/prompts/ask-deck.d.ts +14 -2
  31. package/dist/session/prompts/ask-deck.js +6 -2
  32. package/dist/styles.css +1 -1
  33. package/dist/test-utils/intl.d.ts +37 -47
  34. package/dist/workspace/admin/settings-search.js +4 -12
  35. package/dist/workspace/inbox/workspace-inbox.js +11 -2
  36. package/dist/workspace/layout/new-session-create.d.ts +4 -2
  37. package/dist/workspace/layout/new-session-create.js +11 -0
  38. package/dist/workspace/review/approval-modal.d.ts +6 -6
  39. package/dist/workspace/review/approval-modal.js +10 -14
  40. package/dist/workspace/review/review-center.d.ts +9 -2
  41. package/dist/workspace/review/review-center.js +257 -125
  42. package/dist/workspace/review/review-detail.d.ts +20 -10
  43. package/dist/workspace/review/review-detail.js +39 -44
  44. package/dist/workspace/review/review-meta.d.ts +27 -6
  45. package/dist/workspace/review/review-meta.js +46 -34
  46. package/dist/workspace/sidebar/footer/project-download-app-nav.d.ts +10 -0
  47. package/dist/workspace/sidebar/footer/project-download-app-nav.js +53 -0
  48. package/dist/workspace/sidebar/footer/promo-nav-row.d.ts +2 -1
  49. package/dist/workspace/sidebar/footer/promo-nav-row.js +1 -1
  50. package/dist/workspace/sidebar/project-sidebar.d.ts +6 -1
  51. package/dist/workspace/sidebar/project-sidebar.js +3 -2
  52. package/dist/workspace/sidebar/workspace-menu-model.d.ts +19 -13
  53. package/dist/workspace/sidebar/workspace-menu-model.js +7 -8
  54. package/package.json +3 -3
  55. package/dist/customize/sections/view/subscription-usage-tab.d.ts +0 -25
  56. package/dist/customize/sections/view/subscription-usage-tab.js +0 -121
@@ -1,9 +1,26 @@
1
- import type { AccountSecretResource, SubscriptionAccount, SubscriptionUsage, SubscriptionUsageWindow } from '@kortix/sdk';
1
+ import type { AccountSecretResource, SubscriptionAccount, SubscriptionConnection, SubscriptionUsage, SubscriptionUsageWindow } from '@kortix/sdk';
2
+ import { useTranslations } from '../../../i18n/index.js';
3
+ /** The provider-list row that carries each subscription login's usage. */
4
+ export declare const SUBSCRIPTION_ROW: Readonly<Record<string, string>>;
2
5
  export type UsageTone = 'ok' | 'near' | 'critical' | 'limited';
3
6
  /** Warn at 80%, turn red at 95%, and distinguish a provider-enforced limit. */
4
7
  export declare function usageTone(window: SubscriptionUsageWindow, limited: boolean): UsageTone;
8
+ /**
9
+ * Windows that never stop the login's model calls: code review, paid extra
10
+ * usage, and one model's own limit (ChatGPT `model_*`, Claude `seven_day_opus`,
11
+ * `7d_sonnet`). Claude's OAuth-apps window stays blocking. The server's twin
12
+ * is `isBlockingWindow` in packages/llm-gateway/src/usage/subscription-usage.ts.
13
+ */
14
+ export declare function isBlockingWindow(id: string): boolean;
5
15
  /** The model name of a model-specific weekly window (`seven_day_opus` → `Opus`), or null. */
6
16
  export declare function weeklyModel(id: string): string | null;
17
+ /** A model limit's id fragment read back as its name: `gpt_5_3_codex_spark` → `GPT-5.3 Codex Spark`. */
18
+ export declare function modelName(slug: string): string;
19
+ type Translate = ReturnType<typeof useTranslations>;
20
+ /** A window's name: `5-hour`, `Weekly`, `Weekly · Opus`, `Code review · Weekly`, `Extra usage`. */
21
+ export declare function windowLabel(id: string, t: Translate, options?: {
22
+ modelWeekly?: boolean;
23
+ }): string;
7
24
  /**
8
25
  * A reset time a person reads at a glance: the clock time today, the weekday
9
26
  * and time within a week, else the date.
@@ -17,18 +34,282 @@ export declare function shownUsage(live: SubscriptionUsage | null | undefined, l
17
34
  */
18
35
  export declare function accountLine(account: SubscriptionAccount | null | undefined, label: string): string | null;
19
36
  /** The login's email and plan, under its name: the live read when it answered, else the list's. */
20
- export declare function SubscriptionAccountLine({ accountId, secret }: {
37
+ export declare function SubscriptionAccountLine({ accountId, projectId, secret }: {
21
38
  accountId: string;
39
+ projectId: string;
22
40
  secret: AccountSecretResource;
23
41
  }): import("react").JSX.Element | null;
24
42
  export declare function isSubscriptionLogin(secret: Pick<AccountSecretResource, 'provider_id'>): boolean;
43
+ /** A login the gateway can route to: active, readable, signed in. */
44
+ export declare function usable(secret: Pick<SubscriptionConnection, 'active' | 'needs_reauth_at' | 'status'>): boolean;
45
+ /** A login that cannot take a model call now, and when that ends (null: unknown). */
46
+ export declare function loginLimit(usage: SubscriptionUsage | null, now: number): {
47
+ limited: boolean;
48
+ until: string | null;
49
+ };
50
+ export interface SubscriptionSummary {
51
+ total: number;
52
+ /** Logins that can take a model call now, by their reported usage. */
53
+ available: number;
54
+ /** Usable logins with no usage reported yet: neither available nor limited. */
55
+ unknown: number;
56
+ limited: number;
57
+ /** When the first limited login gets capacity back. */
58
+ nextBack: string | null;
59
+ /** The fullest blocking window across the available logins. */
60
+ peak: SubscriptionUsageWindow | null;
61
+ }
62
+ /**
63
+ * One provider's logins in one line: how many can work now, when the next
64
+ * one is back, and the fullest window of the ones that can.
65
+ */
66
+ export declare function summarizeSubscriptions(logins: Array<{
67
+ secret: Pick<SubscriptionConnection, 'active' | 'needs_reauth_at' | 'status'>;
68
+ usage: SubscriptionUsage | null;
69
+ }>, now: number): SubscriptionSummary;
70
+ /** Every ChatGPT and Claude login this project can use, by provider-list row. */
71
+ export declare function useSubscriptionLogins(accountId: string | null | undefined, projectId: string): {
72
+ logins: SubscriptionConnection[];
73
+ data: {
74
+ subscriptions: SubscriptionConnection[];
75
+ };
76
+ error: Error;
77
+ isError: true;
78
+ isPending: false;
79
+ isLoading: false;
80
+ isLoadingError: false;
81
+ isRefetchError: true;
82
+ isSuccess: false;
83
+ isPlaceholderData: false;
84
+ status: "error";
85
+ dataUpdatedAt: number;
86
+ errorUpdatedAt: number;
87
+ failureCount: number;
88
+ failureReason: Error | null;
89
+ errorUpdateCount: number;
90
+ isFetched: boolean;
91
+ isFetchedAfterMount: boolean;
92
+ isFetching: boolean;
93
+ isInitialLoading: boolean;
94
+ isPaused: boolean;
95
+ isRefetching: boolean;
96
+ isStale: boolean;
97
+ isEnabled: boolean;
98
+ refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<{
99
+ subscriptions: SubscriptionConnection[];
100
+ }, Error>>;
101
+ fetchStatus: import("@tanstack/react-query").FetchStatus;
102
+ } | {
103
+ logins: SubscriptionConnection[];
104
+ data: {
105
+ subscriptions: SubscriptionConnection[];
106
+ };
107
+ error: null;
108
+ isError: false;
109
+ isPending: false;
110
+ isLoading: false;
111
+ isLoadingError: false;
112
+ isRefetchError: false;
113
+ isSuccess: true;
114
+ isPlaceholderData: false;
115
+ status: "success";
116
+ dataUpdatedAt: number;
117
+ errorUpdatedAt: number;
118
+ failureCount: number;
119
+ failureReason: Error | null;
120
+ errorUpdateCount: number;
121
+ isFetched: boolean;
122
+ isFetchedAfterMount: boolean;
123
+ isFetching: boolean;
124
+ isInitialLoading: boolean;
125
+ isPaused: boolean;
126
+ isRefetching: boolean;
127
+ isStale: boolean;
128
+ isEnabled: boolean;
129
+ refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<{
130
+ subscriptions: SubscriptionConnection[];
131
+ }, Error>>;
132
+ fetchStatus: import("@tanstack/react-query").FetchStatus;
133
+ } | {
134
+ logins: SubscriptionConnection[];
135
+ data: undefined;
136
+ error: Error;
137
+ isError: true;
138
+ isPending: false;
139
+ isLoading: false;
140
+ isLoadingError: true;
141
+ isRefetchError: false;
142
+ isSuccess: false;
143
+ isPlaceholderData: false;
144
+ status: "error";
145
+ dataUpdatedAt: number;
146
+ errorUpdatedAt: number;
147
+ failureCount: number;
148
+ failureReason: Error | null;
149
+ errorUpdateCount: number;
150
+ isFetched: boolean;
151
+ isFetchedAfterMount: boolean;
152
+ isFetching: boolean;
153
+ isInitialLoading: boolean;
154
+ isPaused: boolean;
155
+ isRefetching: boolean;
156
+ isStale: boolean;
157
+ isEnabled: boolean;
158
+ refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<{
159
+ subscriptions: SubscriptionConnection[];
160
+ }, Error>>;
161
+ fetchStatus: import("@tanstack/react-query").FetchStatus;
162
+ } | {
163
+ logins: SubscriptionConnection[];
164
+ data: undefined;
165
+ error: null;
166
+ isError: false;
167
+ isPending: true;
168
+ isLoading: true;
169
+ isLoadingError: false;
170
+ isRefetchError: false;
171
+ isSuccess: false;
172
+ isPlaceholderData: false;
173
+ status: "pending";
174
+ dataUpdatedAt: number;
175
+ errorUpdatedAt: number;
176
+ failureCount: number;
177
+ failureReason: Error | null;
178
+ errorUpdateCount: number;
179
+ isFetched: boolean;
180
+ isFetchedAfterMount: boolean;
181
+ isFetching: boolean;
182
+ isInitialLoading: boolean;
183
+ isPaused: boolean;
184
+ isRefetching: boolean;
185
+ isStale: boolean;
186
+ isEnabled: boolean;
187
+ refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<{
188
+ subscriptions: SubscriptionConnection[];
189
+ }, Error>>;
190
+ fetchStatus: import("@tanstack/react-query").FetchStatus;
191
+ } | {
192
+ logins: SubscriptionConnection[];
193
+ data: undefined;
194
+ error: null;
195
+ isError: false;
196
+ isPending: true;
197
+ isLoadingError: false;
198
+ isRefetchError: false;
199
+ isSuccess: false;
200
+ isPlaceholderData: false;
201
+ status: "pending";
202
+ dataUpdatedAt: number;
203
+ errorUpdatedAt: number;
204
+ failureCount: number;
205
+ failureReason: Error | null;
206
+ errorUpdateCount: number;
207
+ isFetched: boolean;
208
+ isFetchedAfterMount: boolean;
209
+ isFetching: boolean;
210
+ isLoading: boolean;
211
+ isInitialLoading: boolean;
212
+ isPaused: boolean;
213
+ isRefetching: boolean;
214
+ isStale: boolean;
215
+ isEnabled: boolean;
216
+ refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<{
217
+ subscriptions: SubscriptionConnection[];
218
+ }, Error>>;
219
+ fetchStatus: import("@tanstack/react-query").FetchStatus;
220
+ } | {
221
+ logins: SubscriptionConnection[];
222
+ data: {
223
+ subscriptions: SubscriptionConnection[];
224
+ };
225
+ isError: false;
226
+ error: null;
227
+ isPending: false;
228
+ isLoading: false;
229
+ isLoadingError: false;
230
+ isRefetchError: false;
231
+ isSuccess: true;
232
+ isPlaceholderData: true;
233
+ status: "success";
234
+ dataUpdatedAt: number;
235
+ errorUpdatedAt: number;
236
+ failureCount: number;
237
+ failureReason: Error | null;
238
+ errorUpdateCount: number;
239
+ isFetched: boolean;
240
+ isFetchedAfterMount: boolean;
241
+ isFetching: boolean;
242
+ isInitialLoading: boolean;
243
+ isPaused: boolean;
244
+ isRefetching: boolean;
245
+ isStale: boolean;
246
+ isEnabled: boolean;
247
+ refetch: (options?: import("@tanstack/react-query").RefetchOptions) => Promise<import("@tanstack/react-query").QueryObserverResult<{
248
+ subscriptions: SubscriptionConnection[];
249
+ }, Error>>;
250
+ fetchStatus: import("@tanstack/react-query").FetchStatus;
251
+ };
25
252
  /**
26
- * The plan usage of one ChatGPT or Claude login, under its name in the account
27
- * list: one bar per window (5-hour, weekly, a model's weekly), each with its
28
- * reset time. It shows the snapshot the list carried at once and asks the
29
- * server for a fresh read every minute while it is on screen.
253
+ * The provider list's line for ChatGPT or Claude: `70% weekly · resets Wed`,
254
+ * `1 of 3 at limit · back Fri 4:30 AM`, or null when nothing is reported.
30
255
  */
31
- export declare function SubscriptionUsageMeters({ accountId, secret }: {
256
+ export declare function useSubscriptionRowSummary(): (summary: SubscriptionSummary | undefined, now: number) => {
257
+ text: string;
258
+ percent: number;
259
+ tone: UsageTone;
260
+ } | null;
261
+ /** The provider list's mini meter beside its summary line. */
262
+ export declare function SubscriptionRowMeter({ text, percent, tone }: {
263
+ text: string;
264
+ percent: number;
265
+ tone: UsageTone;
266
+ }): import("react").JSX.Element;
267
+ /** Every window of one login, one per line, with the states around them. Props only: the design-system preview can use it. */
268
+ export declare function SubscriptionLoginWindows({ providerId, usage, loading, error, now, }: {
269
+ providerId: string | null | undefined;
270
+ usage: SubscriptionUsage | null;
271
+ loading: boolean;
272
+ error: boolean;
273
+ now: number;
274
+ }): import("react").JSX.Element;
275
+ /**
276
+ * The usage under one ChatGPT or Claude account in the provider sheet's
277
+ * account list: the limit state, then every window. The row above it already
278
+ * names the login.
279
+ */
280
+ export declare function SubscriptionAccountUsage({ accountId, projectId, secret }: {
32
281
  accountId: string;
282
+ projectId: string;
33
283
  secret: AccountSecretResource;
34
284
  }): import("react").JSX.Element | null;
285
+ /**
286
+ * Every login's shown usage for a summary: the live read when it answered
287
+ * (a project-stored login's list snapshot stays empty), else the list's.
288
+ */
289
+ export declare function useLiveSubscriptionUsages(accountId: string | null | undefined, projectId: string, logins: SubscriptionConnection[]): {
290
+ usages: {
291
+ secret: SubscriptionConnection;
292
+ usage: SubscriptionUsage | null;
293
+ }[];
294
+ updatedAt: number;
295
+ };
296
+ /**
297
+ * "Subscription usage" on top of the ChatGPT (OpenAI) or Claude (Anthropic)
298
+ * provider sheet: how many logins can work now and when the next one is back,
299
+ * shown once there is more than one login or one is at its limit. Each
300
+ * account's own windows sit under it in the account list; a project-stored
301
+ * login that list does not carry is shown here.
302
+ */
303
+ export declare function SubscriptionUsageSection({ accountId, projectId, providerId, compact }: {
304
+ accountId: string;
305
+ projectId: string;
306
+ providerId: 'codex' | 'claude-agent';
307
+ /** The quick dialog's accordion: headings there are `text-xs`. */
308
+ compact?: boolean;
309
+ }): import("react").JSX.Element | null;
310
+ /** The windows of the project-stored ChatGPT login, for its legacy card in the OpenAI sheet. */
311
+ export declare function LegacyChatGptUsage({ accountId, projectId }: {
312
+ accountId: string;
313
+ projectId: string;
314
+ }): import("react").JSX.Element | null;
315
+ export {};
@@ -1,10 +1,15 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useSubscriptionUsage } from '@kortix/sdk/react';
3
+ import { useCallback } from 'react';
4
+ import { useSubscriptionConnections, useSubscriptionUsage, useSubscriptionUsages } from '@kortix/sdk/react';
4
5
  import { useLocale, useTranslations } from '../../../i18n/index.js';
6
+ import { cn } from '../../../lib/utils.js';
7
+ import { Badge } from '../../../primitives/badge.js';
5
8
  import { Progress } from '../../../primitives/progress.js';
6
9
  /** Providers whose stored value is a subscription login with plan windows. */
7
10
  const SUBSCRIPTION_PROVIDERS = new Set(['codex', 'claude-agent']);
11
+ /** The provider-list row that carries each subscription login's usage. */
12
+ export const SUBSCRIPTION_ROW = { codex: 'openai', 'claude-agent': 'anthropic' };
8
13
  /** A snapshot older than this says when it was observed. */
9
14
  const STALE_MS = 10 * 60 * 1000;
10
15
  /** Warn at 80%, turn red at 95%, and distinguish a provider-enforced limit. */
@@ -16,11 +21,55 @@ export function usageTone(window, limited) {
16
21
  return window.used_percent >= 80 ? 'near' : 'ok';
17
22
  }
18
23
  const TONE_BAR = { ok: 'bg-primary', near: 'bg-kortix-orange', critical: 'bg-kortix-red', limited: 'bg-kortix-red' };
24
+ /**
25
+ * Windows that never stop the login's model calls: code review, paid extra
26
+ * usage, and one model's own limit (ChatGPT `model_*`, Claude `seven_day_opus`,
27
+ * `7d_sonnet`). Claude's OAuth-apps window stays blocking. The server's twin
28
+ * is `isBlockingWindow` in packages/llm-gateway/src/usage/subscription-usage.ts.
29
+ */
30
+ export function isBlockingWindow(id) {
31
+ return !/^(?:code_review|extra_usage|model_|seven_day_(?!oauth_apps$)|7d_(?!oauth_apps$))/.test(id);
32
+ }
19
33
  /** The model name of a model-specific weekly window (`seven_day_opus` → `Opus`), or null. */
20
34
  export function weeklyModel(id) {
21
35
  const model = /^(?:seven_day|7d)_([a-z]+)$/.exec(id)?.[1];
22
36
  return model ? model[0].toUpperCase() + model.slice(1) : null;
23
37
  }
38
+ const title = (value) => value.replaceAll('_', ' ').replace(/^./, (first) => first.toUpperCase());
39
+ /** A model limit's id fragment read back as its name: `gpt_5_3_codex_spark` → `GPT-5.3 Codex Spark`. */
40
+ export function modelName(slug) {
41
+ const words = [];
42
+ for (const token of slug.split('_').filter(Boolean)) {
43
+ const last = words.at(-1);
44
+ if (/^\d+$/.test(token) && last && /\d$/.test(last))
45
+ words[words.length - 1] = `${last}.${token}`;
46
+ else
47
+ words.push(token === 'gpt' ? 'GPT' : /^\d/.test(token) ? token : token[0].toUpperCase() + token.slice(1));
48
+ }
49
+ return words.join(' ').replace(/^GPT (\d)/, 'GPT-$1');
50
+ }
51
+ /** A window's name: `5-hour`, `Weekly`, `Weekly · Opus`, `Code review · Weekly`, `Extra usage`. */
52
+ export function windowLabel(id, t, options = {}) {
53
+ if (id === 'five_hour')
54
+ return t('fiveHour');
55
+ // Beside `Weekly · Opus`, the plain weekly window is the one every model shares.
56
+ if (id === 'weekly')
57
+ return options.modelWeekly ? t('weeklyAll') : t('weekly');
58
+ if (id === 'extra_usage')
59
+ return t('extraUsage');
60
+ if (id === 'seven_day_oauth_apps' || id === '7d_oauth_apps')
61
+ return t('weeklyModel', { model: t('apps') });
62
+ const model = weeklyModel(id);
63
+ if (model)
64
+ return t('weeklyModel', { model });
65
+ const scoped = /^(code_review|model_[a-z0-9_]+?)_(five_hour|weekly|primary|secondary)$/.exec(id);
66
+ if (scoped) {
67
+ const scope = scoped[1] === 'code_review' ? t('codeReview') : modelName(scoped[1].slice('model_'.length));
68
+ const span = scoped[2] === 'five_hour' ? t('fiveHour') : scoped[2] === 'weekly' ? t('weekly') : null;
69
+ return span ? `${scope} · ${span}` : scope;
70
+ }
71
+ return title(id);
72
+ }
24
73
  /**
25
74
  * A reset time a person reads at a glance: the clock time today, the weekday
26
75
  * and time within a week, else the date.
@@ -54,45 +103,223 @@ export function accountLine(account, label) {
54
103
  return [email, plan].filter(Boolean).join(' · ') || null;
55
104
  }
56
105
  /** The login's email and plan, under its name: the live read when it answered, else the list's. */
57
- export function SubscriptionAccountLine({ accountId, secret }) {
58
- const live = useSubscriptionUsage(accountId, secret.secret_id, { enabled: isSubscriptionLogin(secret) });
106
+ export function SubscriptionAccountLine({ accountId, projectId, secret }) {
107
+ const live = useSubscriptionUsage(accountId, secret.secret_id, { projectId, storage: 'account_resource', enabled: isSubscriptionLogin(secret) && usable(secret) });
59
108
  const line = accountLine(live.data?.provider_account ?? secret.provider_account, secret.label);
60
109
  return line ? _jsx("span", { className: "text-muted-foreground block truncate text-xs font-normal", children: line }) : null;
61
110
  }
62
111
  export function isSubscriptionLogin(secret) {
63
112
  return Boolean(secret.provider_id && SUBSCRIPTION_PROVIDERS.has(secret.provider_id));
64
113
  }
65
- function UsageWindowMeter({ window, limited, now }) {
66
- const t = useTranslations('pooledSecrets');
114
+ /** A login the gateway can route to: active, readable, signed in. */
115
+ export function usable(secret) {
116
+ return secret.active && !secret.needs_reauth_at && secret.status !== 'undecryptable';
117
+ }
118
+ /** The windows still in force: a window whose reset passed no longer limits anything. */
119
+ function current(usage, now) {
120
+ return usage.windows.filter((window) => !window.resets_at || Date.parse(window.resets_at) > now);
121
+ }
122
+ /** A login that cannot take a model call now, and when that ends (null: unknown). */
123
+ export function loginLimit(usage, now) {
124
+ if (!usage)
125
+ return { limited: false, until: null };
126
+ const blocking = current(usage, now).filter((window) => isBlockingWindow(window.id));
127
+ const full = blocking.filter((window) => window.used_percent >= 100);
128
+ // A rejection whose window already reset is history, not a limit.
129
+ const rejected = usage.limited && blocking.length === usage.windows.filter((window) => isBlockingWindow(window.id)).length;
130
+ if (!full.length && !rejected)
131
+ return { limited: false, until: null };
132
+ const resets = (full.length ? full : blocking).map((window) => window.resets_at).filter((at) => Boolean(at));
133
+ // Capacity is back only when the LAST full window resets.
134
+ return { limited: true, until: resets.length ? resets.reduce((a, b) => (Date.parse(a) > Date.parse(b) ? a : b)) : null };
135
+ }
136
+ /**
137
+ * One provider's logins in one line: how many can work now, when the next
138
+ * one is back, and the fullest window of the ones that can.
139
+ */
140
+ export function summarizeSubscriptions(logins, now) {
141
+ let available = 0;
142
+ let unknown = 0;
143
+ let limited = 0;
144
+ let nextBack = null;
145
+ let peak = null;
146
+ for (const { secret, usage } of logins) {
147
+ if (!usable(secret))
148
+ continue;
149
+ // Only a plan window says whether the login can work; extra usage or code review alone does not.
150
+ if (!usage || !current(usage, now).some((window) => isBlockingWindow(window.id))) {
151
+ unknown += 1;
152
+ continue;
153
+ }
154
+ const limit = loginLimit(usage, now);
155
+ if (limit.limited) {
156
+ limited += 1;
157
+ if (limit.until && (!nextBack || Date.parse(limit.until) < Date.parse(nextBack)))
158
+ nextBack = limit.until;
159
+ continue;
160
+ }
161
+ available += 1;
162
+ for (const window of usage ? current(usage, now) : []) {
163
+ if (isBlockingWindow(window.id) && (!peak || window.used_percent > peak.used_percent))
164
+ peak = window;
165
+ }
166
+ }
167
+ return { total: logins.length, available, unknown, limited, nextBack, peak };
168
+ }
169
+ /** Every ChatGPT and Claude login this project can use, by provider-list row. */
170
+ export function useSubscriptionLogins(accountId, projectId) {
171
+ const resources = useSubscriptionConnections(accountId, projectId);
172
+ const logins = (resources.data?.subscriptions ?? []).filter((secret) => secret.can_use && isSubscriptionLogin(secret));
173
+ return { ...resources, logins };
174
+ }
175
+ /**
176
+ * The provider list's line for ChatGPT or Claude: `70% weekly · resets Wed`,
177
+ * `1 of 3 at limit · back Fri 4:30 AM`, or null when nothing is reported.
178
+ */
179
+ export function useSubscriptionRowSummary() {
180
+ const t = useTranslations('subscriptionUsage');
67
181
  const locale = useLocale();
68
- const model = weeklyModel(window.id);
69
- const label = window.id === 'five_hour' ? t('usageFiveHour')
70
- : window.id === 'weekly' ? t('usageWeekly')
71
- : model ? t('usageWeeklyModel', { model }) : window.id;
72
- const tone = usageTone(window, limited);
73
- const percent = Math.round(window.used_percent);
74
- const reset = window.resets_at && Date.parse(window.resets_at) > now ? formatReset(window.resets_at, now, locale) : null;
75
- const detail = tone === 'limited'
76
- ? reset ? t('usageLimitResets', { time: reset }) : t('usageLimitReached')
77
- : reset ? t('usagePercentResets', { percent, time: reset }) : t('usagePercent', { percent });
78
- return (_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("div", { className: "flex items-baseline justify-between gap-3 text-xs", children: [_jsx("span", { className: "text-muted-foreground shrink-0", children: label }), _jsx("span", { className: tone === 'limited' ? 'text-foreground min-w-0 truncate tabular-nums' : 'text-muted-foreground min-w-0 truncate tabular-nums', children: detail })] }), _jsx(Progress, { value: Math.min(100, window.used_percent), "aria-label": t('usageAriaLabel', { window: label, percent }), className: "bg-muted h-1", indicatorClassName: TONE_BAR[tone] })] }));
182
+ return useCallback((summary, now) => {
183
+ if (!summary || summary.total === 0)
184
+ return null;
185
+ const back = summary.nextBack ? formatReset(summary.nextBack, now, locale) : null;
186
+ if (summary.limited > 0 && summary.available === 0 && summary.unknown === 0) {
187
+ return { text: back ? t('rowAllLimitedBack', { time: back }) : t('rowAllLimited'), percent: 100, tone: 'limited' };
188
+ }
189
+ if (summary.limited > 0) {
190
+ const text = back ? t('rowSomeLimitedBack', { limited: summary.limited, total: summary.total, time: back })
191
+ : t('rowSomeLimited', { limited: summary.limited, total: summary.total });
192
+ // The bar is the logins that still work: their fullest window.
193
+ return { text, percent: Math.round(summary.peak?.used_percent ?? 0), tone: summary.peak ? usageTone(summary.peak, false) : 'ok' };
194
+ }
195
+ if (!summary.peak)
196
+ return null;
197
+ const percent = Math.round(summary.peak.used_percent);
198
+ return {
199
+ text: t('rowPeak', { percent, window: windowLabel(summary.peak.id, t) }),
200
+ percent,
201
+ tone: usageTone(summary.peak, false),
202
+ };
203
+ }, [t, locale]);
204
+ }
205
+ /** The provider list's mini meter beside its summary line. */
206
+ export function SubscriptionRowMeter({ text, percent, tone }) {
207
+ return (_jsxs("span", { className: "text-muted-foreground flex shrink-0 items-center gap-2 text-xs tabular-nums", "data-subscription-usage-row": "", children: [_jsx("span", { className: "bg-muted block h-1 w-10 overflow-hidden rounded-full", "aria-hidden": true, children: _jsx("span", { className: cn('block h-full', TONE_BAR[tone]), style: { width: `${Math.min(100, percent)}%` } }) }), _jsx("span", { className: "max-w-72 truncate", children: text })] }));
208
+ }
209
+ function UsageWindowMeter({ window, limited, now, modelWeekly }) {
210
+ const t = useTranslations('subscriptionUsage');
211
+ const locale = useLocale();
212
+ const label = windowLabel(window.id, t, { modelWeekly });
213
+ const percent = Math.round(Math.min(100, Math.max(0, window.used_percent)));
214
+ const passed = Boolean(window.resets_at && Date.parse(window.resets_at) <= now);
215
+ const blocking = isBlockingWindow(window.id);
216
+ // A full window that stops nothing else (code review, extra usage, one
217
+ // model) is red, but says when it resets, not that the login is back.
218
+ const tone = blocking ? usageTone(window, limited) : window.used_percent >= 95 ? 'critical' : usageTone(window, false);
219
+ const reset = window.resets_at && !passed ? formatReset(window.resets_at, now, locale) : null;
220
+ const detail = passed ? t('resetPassed')
221
+ : tone === 'limited' && reset ? t('percentBack', { percent, time: reset })
222
+ : reset ? t('percentResets', { percent, time: reset }) : t('percent', { percent });
223
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-1.5", "data-usage-window": window.id, children: [_jsxs("div", { className: "flex items-baseline justify-between gap-3 text-xs", children: [_jsx("span", { className: "text-foreground min-w-0 truncate", children: label }), _jsx("span", { className: cn('shrink-0 tabular-nums', tone === 'limited' && !passed ? 'text-foreground' : 'text-muted-foreground'), children: detail })] }), _jsx(Progress, { value: passed ? 0 : percent, "aria-label": t('meterLabel', { label, percent }), className: "bg-muted h-1", indicatorClassName: passed ? 'bg-muted-foreground' : TONE_BAR[tone] })] }));
224
+ }
225
+ /** Claude reports no 5-hour window until a message opens one: say so instead of hiding the limit. */
226
+ function NotStartedWindow({ id }) {
227
+ const t = useTranslations('subscriptionUsage');
228
+ const label = windowLabel(id, t);
229
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-1.5", "data-usage-window": id, children: [_jsxs("div", { className: "flex items-baseline justify-between gap-3 text-xs", children: [_jsx("span", { className: "text-foreground min-w-0 truncate", children: label }), _jsx("span", { className: "text-muted-foreground shrink-0", children: t('notStarted') })] }), _jsx(Progress, { value: 0, "aria-label": t('meterLabel', { label, percent: 0 }), className: "bg-muted h-1" })] }));
230
+ }
231
+ /** Every window of one login, one per line, with the states around them. Props only: the design-system preview can use it. */
232
+ export function SubscriptionLoginWindows({ providerId, usage, loading, error, now, }) {
233
+ const t = useTranslations('subscriptionUsage');
234
+ const locale = useLocale();
235
+ const limit = loginLimit(usage, now);
236
+ const windows = usage?.windows ?? [];
237
+ const missingFiveHour = providerId === 'claude-agent' && usage?.source === 'usage_endpoint' && windows.length > 0
238
+ && !windows.some((window) => window.id === 'five_hour');
239
+ const stale = usage && now - Date.parse(usage.observed_at) > STALE_MS;
240
+ const modelWeekly = windows.some((window) => weeklyModel(window.id) !== null);
241
+ if (!windows.length) {
242
+ return _jsx("p", { className: "text-muted-foreground text-xs", children: loading ? t('checking') : error ? t('loadFailed') : t('noUsageYet') });
243
+ }
244
+ return (_jsxs("div", { className: "flex flex-col gap-3", "data-subscription-windows": "", children: [missingFiveHour ? _jsx(NotStartedWindow, { id: "five_hour" }) : null, windows.map((window) => _jsx(UsageWindowMeter, { window: window, limited: limit.limited, now: now, modelWeekly: modelWeekly }, window.id)), error ? _jsx("p", { className: "text-muted-foreground text-xs", children: t('refreshFailed') })
245
+ : stale ? _jsx("p", { className: "text-muted-foreground text-xs", children: t('observed', { time: formatReset(usage.observed_at, now, locale) }) }) : null] }));
246
+ }
247
+ /** One login's live read: the same query the sheet's summary and the provider list read. */
248
+ function useLoginUsage(accountId, projectId, secretId, storage, enabled) {
249
+ return useSubscriptionUsage(accountId, secretId, { projectId, storage, enabled });
250
+ }
251
+ /**
252
+ * The usage under one ChatGPT or Claude account in the provider sheet's
253
+ * account list: the limit state, then every window. The row above it already
254
+ * names the login.
255
+ */
256
+ export function SubscriptionAccountUsage({ accountId, projectId, secret }) {
257
+ const t = useTranslations('subscriptionUsage');
258
+ const live = useLoginUsage(accountId, projectId, secret.secret_id, 'account_resource', usable(secret));
259
+ const usage = shownUsage(live.data?.usage, secret.usage);
260
+ // The clock of the newest read, the account list's included: a failed live
261
+ // read must not keep a passed reset looking current.
262
+ const listed = useSubscriptionLogins(accountId, projectId).dataUpdatedAt;
263
+ const now = Math.max(live.dataUpdatedAt, listed);
264
+ if (!usable(secret))
265
+ return null;
266
+ return (_jsxs("div", { className: "mt-2.5 flex flex-col gap-2.5 font-normal", "data-subscription-login": "", children: [loginLimit(usage, now).limited ? _jsx(Badge, { size: "sm", variant: "destructive", className: "self-start", children: t('limitReached') }) : null, _jsx(SubscriptionLoginWindows, { providerId: secret.provider_id, usage: usage, loading: live.isFetching, error: live.isError, now: now })] }));
267
+ }
268
+ /** A project-stored login (made before pooled accounts) has no row in the account list: it gets its own block here. */
269
+ function LegacyLogin({ accountId, projectId, secret, now }) {
270
+ const t = useTranslations('subscriptionUsage');
271
+ const live = useLoginUsage(accountId, projectId, secret.secret_id, secret.storage, secret.can_use && usable(secret));
272
+ const usage = shownUsage(live.data?.usage, secret.usage);
273
+ const line = accountLine(live.data?.provider_account ?? secret.provider_account, secret.label);
274
+ const at = Math.max(now, live.dataUpdatedAt);
275
+ return (_jsxs("li", { className: "border-border flex min-w-0 flex-col gap-2.5 rounded-md border px-3 py-2", "data-subscription-login": "", children: [_jsxs("div", { className: "flex min-w-0 items-start justify-between gap-3", children: [_jsxs("p", { className: "min-w-0 text-sm", children: [_jsx("span", { className: "text-foreground font-medium", children: secret.label }), line ? _jsx("span", { className: "text-muted-foreground block truncate text-xs", children: line }) : null] }), !usable(secret) ? _jsx("span", { className: "text-muted-foreground shrink-0 text-xs", children: secret.active ? t('reconnectToSee') : t('inactive') })
276
+ : loginLimit(usage, at).limited ? _jsx(Badge, { size: "sm", variant: "destructive", children: t('limitReached') }) : null] }), usable(secret) ? _jsx(SubscriptionLoginWindows, { providerId: secret.provider_id, usage: usage, loading: live.isFetching, error: live.isError, now: at }) : null] }));
277
+ }
278
+ /**
279
+ * Every login's shown usage for a summary: the live read when it answered
280
+ * (a project-stored login's list snapshot stays empty), else the list's.
281
+ */
282
+ export function useLiveSubscriptionUsages(accountId, projectId, logins) {
283
+ const reads = useSubscriptionUsages(accountId, projectId, logins);
284
+ const usages = logins.map((secret, index) => ({ secret, usage: shownUsage(reads[index]?.data?.usage, secret.usage) }));
285
+ const updatedAt = Math.max(0, ...reads.map((read) => read.dataUpdatedAt));
286
+ return { usages, updatedAt };
79
287
  }
80
288
  /**
81
- * The plan usage of one ChatGPT or Claude login, under its name in the account
82
- * list: one bar per window (5-hour, weekly, a model's weekly), each with its
83
- * reset time. It shows the snapshot the list carried at once and asks the
84
- * server for a fresh read every minute while it is on screen.
289
+ * "Subscription usage" on top of the ChatGPT (OpenAI) or Claude (Anthropic)
290
+ * provider sheet: how many logins can work now and when the next one is back,
291
+ * shown once there is more than one login or one is at its limit. Each
292
+ * account's own windows sit under it in the account list; a project-stored
293
+ * login that list does not carry is shown here.
85
294
  */
86
- export function SubscriptionUsageMeters({ accountId, secret }) {
87
- const t = useTranslations('pooledSecrets');
295
+ export function SubscriptionUsageSection({ accountId, projectId, providerId, compact = false }) {
296
+ const t = useTranslations('subscriptionUsage');
88
297
  const locale = useLocale();
89
- const live = useSubscriptionUsage(accountId, secret.secret_id, { enabled: isSubscriptionLogin(secret) });
298
+ const { logins: all, dataUpdatedAt } = useSubscriptionLogins(accountId, projectId);
299
+ const logins = all.filter((secret) => secret.provider_id === providerId);
300
+ const live = useLiveSubscriptionUsages(accountId, projectId, logins);
301
+ // A project-stored ChatGPT login has its own card below (its windows sit in
302
+ // it); a project-stored Claude login has no other row.
303
+ const legacy = providerId === 'claude-agent' ? logins.filter((secret) => secret.storage === 'project') : [];
304
+ const now = Math.max(dataUpdatedAt, live.updatedAt);
305
+ const summary = summarizeSubscriptions(live.usages, now);
306
+ const showSummary = logins.length > 1 || summary.limited > 0;
307
+ if (!showSummary && !legacy.length)
308
+ return null;
309
+ return (_jsxs("section", { className: "space-y-3", "aria-label": t('title'), "data-subscription-usage": providerId, children: [_jsx("p", { className: cn('text-foreground font-medium', compact ? 'text-xs' : 'text-sm'), children: t('title') }), showSummary ? (_jsxs("div", { className: "bg-muted/60 flex flex-wrap gap-x-8 gap-y-2 rounded-md px-3 py-2.5", children: [_jsxs("div", { className: "min-w-0", children: [_jsx("p", { className: "text-muted-foreground text-xs", children: t('availableNow') }), _jsx("p", { className: "text-foreground text-sm font-medium tabular-nums", children: t('availableCount', { available: summary.available, total: summary.total }) })] }), summary.unknown > 0 ? (_jsxs("div", { className: "min-w-0", children: [_jsx("p", { className: "text-muted-foreground text-xs", children: t('notReported') }), _jsx("p", { className: "text-foreground text-sm font-medium tabular-nums", children: summary.unknown })] })) : null, summary.nextBack ? (_jsxs("div", { className: "min-w-0", children: [_jsx("p", { className: "text-muted-foreground text-xs", children: t('nextBack') }), _jsx("p", { className: "text-foreground text-sm font-medium tabular-nums", children: formatReset(summary.nextBack, now, locale) })] })) : null] })) : null, legacy.length ? (_jsx("ul", { className: "space-y-1", children: legacy.map((secret) => (_jsx(LegacyLogin, { accountId: accountId, projectId: projectId, secret: secret, now: now }, `${secret.storage}:${secret.secret_id}`))) })) : null] }));
310
+ }
311
+ /** The windows of the project-stored ChatGPT login, for its legacy card in the OpenAI sheet. */
312
+ export function LegacyChatGptUsage({ accountId, projectId }) {
313
+ const { logins, dataUpdatedAt } = useSubscriptionLogins(accountId, projectId);
314
+ const secret = logins.find((login) => login.provider_id === 'codex' && login.storage === 'project');
315
+ return secret ? _jsx(LegacyWindows, { accountId: accountId, projectId: projectId, secret: secret, now: dataUpdatedAt }) : null;
316
+ }
317
+ function LegacyWindows({ accountId, projectId, secret, now }) {
318
+ const t = useTranslations('subscriptionUsage');
319
+ const live = useLoginUsage(accountId, projectId, secret.secret_id, secret.storage, secret.can_use && usable(secret));
90
320
  const usage = shownUsage(live.data?.usage, secret.usage);
91
- const now = Math.max(Date.now(), live.dataUpdatedAt);
92
- if (!usage) {
93
- // Nothing to say while the first read runs; after it, say when numbers appear.
94
- return live.isFetching ? null : _jsx("span", { className: "text-muted-foreground block text-xs font-normal", children: t('usageNotSeen') });
95
- }
96
- const observed = Date.parse(usage.observed_at);
97
- return (_jsxs("div", { className: "mt-1.5 flex flex-col gap-1.5 font-normal", children: [usage.windows.map((window) => _jsx(UsageWindowMeter, { window: window, limited: usage.limited, now: now }, window.id)), now - observed > STALE_MS && (_jsx("span", { className: "text-muted-foreground text-xs", children: t('usageObserved', { time: formatReset(usage.observed_at, now, locale) }) }))] }));
321
+ const at = Math.max(now, live.dataUpdatedAt);
322
+ if (!usable(secret))
323
+ return null;
324
+ return (_jsxs("div", { className: "flex flex-col gap-2.5", "data-subscription-login": "", children: [loginLimit(usage, at).limited ? _jsx(Badge, { size: "sm", variant: "destructive", className: "self-start", children: t('limitReached') }) : null, _jsx(SubscriptionLoginWindows, { providerId: secret.provider_id, usage: usage, loading: live.isFetching, error: live.isError, now: at })] }));
98
325
  }