diff --git a/devlog/_plan/261112_account_probe_and_model_discovery/010_design.md b/devlog/_plan/261112_account_probe_and_model_discovery/010_design.md new file mode 100644 index 00000000000..1dc983c138d --- /dev/null +++ b/devlog/_plan/261112_account_probe_and_model_discovery/010_design.md @@ -0,0 +1,86 @@ +# Per-account probe and manual model discovery + +Status: implemented on `feat/antigravity-account-probe`. + +## Problem + +1. `POST /api/providers/test` resolves only the active account's token, so an operator with a + pool of Google Antigravity accounts cannot tell which individual accounts still work. Accounts + that started returning `permission_denied` could only be checked with an out-of-tree script. +2. Model discovery runs implicitly (catalog convergence, `liveModels`). There is no per-provider + "discover now" action, and recent arrivals only show as small NEW badges on the Models page. + +## 1. Per-account probe + +`POST /api/oauth/accounts/probe` — body `{ "provider": "google-antigravity", "accountId"?: string }`. +Omitting `accountId` probes every stored account (concurrency 4). Response: + +```json +{ "provider": "google-antigravity", "probedAt": "", + "results": [{ "accountId": "…", "maskedLabel": "a***b@example.com", "active": true, "paused": false, + "status": "ok", "httpStatus": 200, "reason": null, "message": null, + "expiresAt": 0, "latencyMs": 412, "quota": { "customWindows": [] } }] } +``` + +`status` is one of: + +| status | meaning | rule | +| --- | --- | --- | +| `ok` | usable | HTTP 200 | +| `paused` | account is paused by the operator; not tested | `account.paused === true`; no request is sent | +| `token_expired` | stored access token expired, not refreshed | `credential.expires <= now`; no request is sent | +| `suspended` | upstream says the account is suspended/disabled | 403 whose reason/message names suspension, disablement or ToS | +| `verification_required` | upstream asks the user to verify the account | 403 with `details[].reason == VALIDATION_REQUIRED` or "verify your account" wording | +| `rate_limited` | throttled / quota exhausted | 429 or `RESOURCE_EXHAUSTED` | +| `permission_denied` | other 403 | 403 | +| `error` | anything else (401, 5xx, transport, missing project) | `httpStatus` and `reason` carry the detail | + +Read-only by construction: + +- Uses the account's stored access token exactly as read through `getAccountSet()`; never calls + `getValidAccessToken`, never refreshes, never writes the auth store, never changes pause, + active, cooldown or health state. Paused accounts are skipped with status `paused` and no + request: an operator who parked an account has said not to use it, and a probe is still a use. + To test one, resume it first. +- One request: `POST https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary` + with `{ "project": }` and `User-Agent: antigravityCliUserAgent()`. Unlike the quota + poller there is no 403 retry under the IDE UA and no `fetchAvailableModels` fallback: the + first answer is the evidence, and the CLI fingerprint is the one that reports the Gemini group. +- Goes through the pinned provider-outbound transport used by the quota poller. +- The response carries no token. `message` is Google's error message passed through + `sanitizeUpstreamErrorText` and truncated to 300 characters. + +Only `google-antigravity` is supported for now; other providers get HTTP 400 +`account probe is not supported for this provider`. The request/response shape is provider-neutral +so another provider can plug in a probe function later. + +CLI: `ocx account probe [] [--json]` (capability registered in +`src/cli/capabilities-accounts.ts`). + +GUI: Providers → Google Antigravity → Available accounts. Each account row gets a **Test** button; +the result renders under the row as a coloured badge plus `HTTP · · `. +The section head gets **Test all**. + +## 2. Manual model discovery + +`POST /api/model-discovery/refresh` — body `{ "provider": "" }`. + +1. 404 for an unknown provider; `{ ok: false, applicable: false, reason: "static_catalog" }` when the + provider has `liveModels: false` (no live endpoint to ask). +2. Snapshot the provider's `recentArrivals` ids, `clearModelCache(provider)`, then run the normal + catalog convergence (`convergeCodexCatalog`), which re-fetches the provider and records new + arrivals through the existing new-model policy. +3. Respond with `{ ok, provider, discovery, liveModelCount, newArrivals, recentArrivals, catalogRefresh }`, + where `newArrivals` are the arrivals recorded by this call and `discovery` is the provider's + discovery status (`ok` / `failed` + reason / http status). + +CLI: `ocx models discover [--json]`. + +GUI: provider settings, directly under the "Discover models from provider" toggle: a +**Discover now** button and a "Recently added" list (newest first, with date and whether the model +was auto-disabled by the new-model policy). + +## Not changed + +- `POST /api/providers/test` and the active-account path. +- Token refresh, re-login, pause/resume semantics. diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index 28f525b0618..28ea7951dff 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -985,6 +985,24 @@ token re-login or a plain account-list re-read. `--json` returns failures exit 1; an upstream quota probe that fails or times out degrades to a null or stale report instead (exit 0), matching the dashboard's quota bars. +### `ocx account probe google-antigravity [id|alias] [--json]` + +Read-only per-account check for Google Antigravity. Each account gets one +`retrieveUserQuotaSummary` request with its own stored access token, under the CLI fingerprint, and +the result is classified as `ok`, `rate_limited`, `verification_required`, `suspended`, +`permission_denied` or `error` (with the HTTP status and Google's reason). Two outcomes are decided +locally and send nothing: `paused` (the account is paused; resume it to test it) and `token_expired` +(the stored token has expired). The probe never refreshes a token, never writes the auth store and +never changes pause, active, cooldown or health state. The dashboard's **Test** and **Test all** +buttons on Antigravity account rows call the same endpoint, `POST /api/oauth/accounts/probe`. + +### `ocx models discover [--json]` + +Runs the provider's live model discovery now instead of waiting for the next scheduled refresh, and +prints how many live models it saw and which ones are new. It is the same action as **Discover now** +under the provider's settings (`POST /api/model-discovery/refresh`). Providers without live +discovery report that discovery is off. + ### `ocx account auto-switch > [--json]` Controls the `openai` Codex pool threshold, or stores a threshold for a generic OAuth pool. `on` stores 80%, `off` stores 0%, and `threshold ` accepts 0–100. A generic pool threshold steers selection only while `pool.kernel` is on with `strategy: "fill-first"`; with the flag off, saving one does not enable threshold-based switching. It never changes the provider enablement override or disables reactive 429 rotation. `status` and mutation output for generic pools use the confirmed server response. For generic pools, `poolEnabled` is the stored provider override (`null` means unspecified), not inherited effective state; `inert: true` means the threshold is stored but not applied, `inert: false` means the pool is applying it, and an absent `inert` is an unknown capability, which never reports `enabled: true`. API-key providers and invalid values are rejected. diff --git a/gui/src/components/provider-workspace/AccountProbe.tsx b/gui/src/components/provider-workspace/AccountProbe.tsx new file mode 100644 index 00000000000..8af55e07e91 --- /dev/null +++ b/gui/src/components/provider-workspace/AccountProbe.tsx @@ -0,0 +1,53 @@ +import { useT } from "../../i18n/shared"; +import type { AccountProbeController, AccountProbeEntry, AccountProbeStatus } from "../../hooks/useAccountProbe"; + +function statusBadgeClass(status: AccountProbeStatus): string { + if (status === "ok") return "badge badge-green"; + if (status === "token_expired" || status === "paused") return "badge badge-muted"; + return "badge badge-amber"; +} + +export function AccountProbeButton({ controller, accountId, label, disabled }: { + controller: AccountProbeController; accountId: string; label: string; disabled?: boolean; +}) { + const t = useT(); + const pending = controller.isPending(accountId); + return ( + + ); +} + +/** One line under the account row: verdict badge, then HTTP code, reason and upstream message. */ +export function AccountProbeResultLine({ entry }: { entry: AccountProbeEntry | undefined }) { + const t = useT(); + if (!entry) return null; + const time = new Date(entry.at).toLocaleTimeString(); + if ("failed" in entry) { + return
{`${t("acctProbe.failed")} · ${time}`}
; + } + const { result } = entry; + const evidence = [ + result.httpStatus !== null ? `HTTP ${result.httpStatus}` : null, + result.reason, + result.message, + ].filter((part): part is string => Boolean(part)).join(" · "); + const windows = (result.quota?.customWindows ?? []) + .map(window => `${window.label} ${Math.max(0, Math.round(100 - window.percent))}%`) + .join(" · "); + return ( +
+ {t(`acctProbe.status.${result.status}`)} + {evidence && {evidence}} + {windows && {windows}} + {time} +
+ ); +} diff --git a/gui/src/components/provider-workspace/AccountQuotaTable.tsx b/gui/src/components/provider-workspace/AccountQuotaTable.tsx new file mode 100644 index 00000000000..80da2fdbd9c --- /dev/null +++ b/gui/src/components/provider-workspace/AccountQuotaTable.tsx @@ -0,0 +1,124 @@ +import { useEffect, useState, type CSSProperties, type ReactNode } from "react"; +import { useT, type TKey } from "../../i18n/shared"; +import { + buildQuotaTable, formatCountdown, + type AccountFlag, type PoolCell, type PoolKey, type QuotaTableAccount, type QuotaTableRow, +} from "../../provider-workspace/account-quota-table"; +import "./account-quota-table.css"; + +const FLAG_TONE: Record = { + ok: "ok", slow: "warn", stale: "muted", warning: "warn", probeFailed: "warn", + rateLimited: "warn", quotaLimited: "warn", reauth: "warn", paused: "muted", +}; + +function useMinuteClock(): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const id = window.setInterval(() => setNow(Date.now()), 30_000); + return () => window.clearInterval(id); + }, []); + return now; +} + +function PoolBar({ label, cell, now }: { label: string; cell: PoolCell; now: number }) { + const t = useT(); + const remaining = Math.round(cell.remaining); + const tone = remaining <= 20 ? "bar-warn" : "bar-green"; + const countdown = cell.resetAt === undefined ? null : formatCountdown(cell.resetAt, now); + return ( +
+ {label} +
+ {remaining}% + {countdown ? t("acctTable.resetsIn", { time: countdown }) : ""} +
+ ); +} + +export interface AccountQuotaTableProps { + accounts: readonly QuotaTableAccount[]; + /** Pause/resume through the provider's existing account API; omitted hides the button. */ + onTogglePause?: (accountId: string, paused: boolean) => void; + pauseDisabled?: boolean; + /** Per-account probe button (the existing read-only probe), when the provider supports it. */ + renderProbe?: (account: QuotaTableAccount) => ReactNode; +} + +/** + * Every account of one provider side by side: plan, each quota pool's 5-hour and weekly + * remaining with a reset countdown, and one status flag. Actions reuse the existing account + * APIs; the table adds no endpoint. + */ +export function AccountQuotaTable({ accounts, onTogglePause, pauseDisabled, renderProbe }: AccountQuotaTableProps) { + const t = useT(); + const now = useMinuteClock(); + const table = buildQuotaTable(accounts, now); + if (table.rows.length === 0 || table.pools.length === 0) return null; + const flagText = (row: QuotaTableRow) => row.flag === "probeFailed" + ? t(`acctProbe.status.${row.probeStatus}` as TKey) + : t(`acctTable.flag.${row.flag}` as TKey); + const poolLabel = (key: PoolKey) => t(`acctTable.pool.${key}` as TKey); + return ( +
+

{t("acctTable.policy")}

+
+ + + + + + {table.pools.map(pool => ( + + ))} + + {(onTogglePause || renderProbe) && } + + + + {table.rows.map(row => ( + + + + {table.pools.map(pool => { + const cell = row.cells[pool.key]; + return ( + + ); + })} + + {(onTogglePause || renderProbe) && ( + + )} + + ))} + +
{t("acctTable.account")}{t("acctTable.plan")} + {poolLabel(pool.key)} + {pool.scarce && {t("acctTable.scarce")}} + {t("acctTable.status")}{t("acctTable.actions")}
+ + {row.plan + ? {row.plan} + : {t("acctTable.unknownPlan")}} + + {cell ? <> + {cell.fiveHour && } + {cell.weekly && } + {row.next.includes(pool.key) && {t("acctTable.next")}} + : {t("acctTable.noReading")}} + {flagText(row)} + {onTogglePause && ( + + )} + {renderProbe?.(row.account)} +
+
+
+ ); +} diff --git a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx index af2a579915b..1d69fddbf56 100644 --- a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx +++ b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx @@ -25,6 +25,10 @@ import AnthropicAccountPoolSettings from "./AnthropicAccountPoolSettings"; import { LoginHint as LoginHintView } from "../login-url-block"; import { OpenBrowserPrefToggle } from "../open-browser-pref-toggle"; import ProviderAccountQuota from "./ProviderAccountQuota"; +import { AccountProbeButton, AccountProbeResultLine } from "./AccountProbe"; +import { ACCOUNT_PROBE_PROVIDERS, useAccountProbe } from "../../hooks/useAccountProbe"; +import { AccountQuotaTable } from "./AccountQuotaTable"; +import { accountQuotaFromReport } from "../../provider-workspace/report"; import { GrokCouponBadge, GrokResetCouponModal } from "./GrokResetCoupons"; import { AnthropicGrantBadge, AnthropicResetGrantModal } from "./AnthropicResetGrants"; import type { CodexAccountPoolController } from "../../hooks/useCodexAccountPool"; @@ -273,6 +277,9 @@ export default function ProviderAuthPanel({ const setGrantAccount = (account: OAuthAccountRow | null) => { setGrantSelection(account ? { scope: grantScope, account } : null); }; + // Read-only per-account probe (stored token, no refresh); only providers the server implements. + const accountProbe = useAccountProbe(apiBase, item.name); + const probeEnabled = isOauth && ACCOUNT_PROBE_PROVIDERS.has(item.name) && accounts.length > 0; const refreshQuota = async () => { if (!onRefreshQuota || refreshingQuota) return; const generation = ++quotaRefreshGeneration.current; @@ -293,6 +300,21 @@ export default function ProviderAuthPanel({

{t("pws.availableAccounts")}

+ {codexController && codexController.accounts.length > 1 && ( + ({ + id: account.id, label: account.alias ?? (account.email || t("codexAuth.mainAccount")), plan: account.plan ?? null, + active: account.id === codexController.activeId, paused: account.paused, needsReauth: account.needsReauth, health: account.health, + quota: account.quota && { + ...account.quota, + fiveHourPercent: account.quota.fiveHourPercent ?? account.quota.shortPercent, + fiveHourResetAt: account.quota.fiveHourResetAt ?? account.quota.shortResetAt, + }, + }))} + onTogglePause={(id, paused) => { void codexController.setAccountPaused(id, paused); }} + pauseDisabled={codexController.pauseUpdatingId !== null || codexController.switchingId !== null} + /> + )}
)} + {probeEnabled && ( +
+ +
+ )}
{item.name === "xai" && ( @@ -582,6 +613,28 @@ export default function ProviderAuthPanel({ )}
)} + {accounts.length > 1 && ( + { + const probe = accountProbe.entries[account.id]; + return { + id: account.id, label: oauthAccountDisplayLabel(accounts, account, t), plan: account.plan, + planLabel: isAnthropicPool ? anthropicSubscriptionLabel(account.plan) : undefined, + active: account.active, paused: account.paused === true, needsReauth: accountShowsReauth(account), + health: account.health, quota: accountQuotaFromReport({ quota: account.quota }), quotaUnavailable: account.quotaUnavailable, + ...(probe && "result" in probe ? { probe: { status: probe.result.status, latencyMs: probe.result.latencyMs } } : {}), + }; + })} + onTogglePause={authHandlers.onPauseAccount ? (id, paused) => { + const account = accounts.find(row => row.id === id); + if (account) void authHandlers.onPauseAccount!(item.name, account, paused); + } : undefined} + pauseDisabled={busy || Boolean(switchingAccountId) || Boolean(pausingAccountId)} + renderProbe={probeEnabled ? account => ( + + ) : undefined} + /> + )} {accounts.length > 0 && (
    {accounts.map(account => { @@ -659,6 +712,10 @@ export default function ProviderAuthPanel({ {claudeGrantsEnabled && !showReauth && ( setGrantAccount(account)} /> )} + {probeEnabled && ( + + )}
    + {probeEnabled && } {isAnthropicPool && account.autoSwitchThresholdOverride !== undefined && account.autoSwitchThreshold !== undefined && authHandlers.onAccountThreshold && ( !!row && typeof row === "object" + && typeof (row as ArrivalRow).id === "string" && typeof (row as ArrivalRow).at === "string") + : []; +} + +function formatArrivalTime(at: string): string { + const time = Date.parse(at); + return Number.isFinite(time) ? new Date(time).toLocaleString() : at; +} + +/** + * Manual "discover now" for one provider plus its recent arrivals. Sits under the + * "Discover models from provider" setting so the action is next to the switch that governs it. + */ +export default function ProviderModelDiscovery({ apiBase, provider, enabled }: { + apiBase: string; provider: string; enabled: boolean; +}) { + const t = useT(); + const [recent, setRecent] = useState([]); + const [run, setRun] = useState({ kind: "idle" }); + + useEffect(() => { + // The parent keys this component by server and provider, so state starts fresh per provider. + let cancelled = false; + fetch(`${apiBase}/api/model-discovery`) + .then(response => response.ok ? response.json() : null) + .then((json: { recentArrivals?: Record } | null) => { + if (!cancelled) setRecent(arrivalRows(json?.recentArrivals?.[provider])); + }) + .catch(() => { /* The list is informational; the button still works. */ }); + return () => { cancelled = true; }; + }, [apiBase, provider]); + + const discover = async () => { + setRun({ kind: "running" }); + try { + const response = await fetch(`${apiBase}/api/model-discovery/refresh`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ provider }), + }); + const json = await response.json().catch(() => null) as RefreshResponse | null; + if (!response.ok || !json) { setRun({ kind: "failed" }); return; } + if (json.applicable === false) { setRun({ kind: "static" }); return; } + setRecent(arrivalRows(json.recentArrivals)); + if (json.discovery?.status === "failed") { + const detail = [json.discovery.reason, json.discovery.httpStatus ? `HTTP ${json.discovery.httpStatus}` : null].filter(Boolean).join(" · "); + setRun({ kind: "failed", ...(detail ? { detail } : {}) }); + return; + } + setRun({ kind: "done", liveModelCount: json.liveModelCount ?? null, added: arrivalRows(json.newArrivals).map(row => row.id) }); + } catch { + setRun({ kind: "failed" }); + } + }; + + const added = run.kind === "done" ? new Set(run.added) : new Set(); + const listed = [...recent].reverse().slice(0, MAX_LISTED); + return ( +
    +
    +
    +

    {t("modelDiscover.recent")}

    +

    + {run.kind === "done" && t("modelDiscover.result", { count: run.liveModelCount ?? "?", added: run.added.length })} + {run.kind === "static" && t("modelDiscover.static")} + {run.kind === "failed" && `${t("modelDiscover.failed")}${run.detail ? ` · ${run.detail}` : ""}`} +

    +
    + +
    + {listed.length === 0 ? ( +

    {t("modelDiscover.none")}

    + ) : ( +
      + {listed.map(row => ( +
    • + {added.has(row.id) && {t("modelDiscover.new")}} + {row.id} + {formatArrivalTime(row.at)} + {row.state === "auto-disabled" && {t("modelDiscover.autoDisabled")}} +
    • + ))} +
    + )} +
    + ); +} diff --git a/gui/src/components/provider-workspace/ProviderSettings.tsx b/gui/src/components/provider-workspace/ProviderSettings.tsx index 383ef4617d9..587ae8d5de6 100644 --- a/gui/src/components/provider-workspace/ProviderSettings.tsx +++ b/gui/src/components/provider-workspace/ProviderSettings.tsx @@ -26,6 +26,7 @@ import { isVertexProvider, providerSupportsLiveModelDiscovery } from "../../prov import type { CatalogPreset } from "../provider-catalog/provider-presets"; import { authModeLabel } from "./ProviderRail"; import { ProviderProtocolPanel } from "./ProviderProtocolPanel"; +import ProviderModelDiscovery from "./ProviderModelDiscovery"; import { ProviderKeyPacing, type KeyPacingDraft, type KeyPacingStatus } from "./ProviderKeyPacing"; import type { WorkspaceItem, ProviderUpdateCallback } from "./types"; import { @@ -674,6 +675,9 @@ function ProviderSettingsForm({ {t("pws.liveModelsDesc")} + {apiBase !== undefined && liveModelDiscoverySupported && ( + + )}

    {t("pws.pacingTitle")}

    {t("pws.pacingDesc")}

    diff --git a/gui/src/components/provider-workspace/account-quota-table.css b/gui/src/components/provider-workspace/account-quota-table.css new file mode 100644 index 00000000000..5cef0b49e81 --- /dev/null +++ b/gui/src/components/provider-workspace/account-quota-table.css @@ -0,0 +1,102 @@ +/* Imported by its component, so it sits in the `legacy` cascade layer itself: + unlayered CSS would outrank design/bridge.css and every Tailwind utility. */ +@layer legacy { +.aqt { + display: grid; + gap: var(--space-2); + margin-bottom: var(--space-3); +} +.aqt-policy { + margin: 0; + font-size: var(--text-caption); +} +.aqt-scroll { + overflow-x: auto; + border: 1px solid var(--border); + border-radius: var(--radius-sm, 6px); +} +.aqt-table { + width: 100%; + border-collapse: collapse; + font-size: var(--text-label); +} +.aqt-table th, +.aqt-table td { + padding: var(--space-2); + text-align: left; + vertical-align: top; + border-bottom: 1px solid var(--border); +} +.aqt-table thead th { + font-weight: 500; + color: var(--muted); + white-space: nowrap; +} +.aqt-table tbody tr:last-child > * { + border-bottom: 0; +} +.aqt-row--active { + background: color-mix(in oklab, var(--green) 6%, transparent); +} +.aqt-account { + font-weight: 500; + white-space: nowrap; +} +.aqt-account .pwi-auth-dot { + display: inline-block; + margin-right: var(--space-2); + vertical-align: middle; +} +.aqt-scarce { + margin-left: var(--space-1); + padding: 0 4px; + border-radius: 4px; + font-size: var(--text-caption); + color: var(--amber); + border: 1px solid color-mix(in oklab, var(--amber) 40%, transparent); +} +.aqt-pool { + min-width: 8.5rem; +} +.aqt-table .badge { + white-space: nowrap; +} +.aqt-bar { + display: grid; + grid-template-columns: 2.4rem minmax(2.5rem, 1fr) 2.4rem; + align-items: center; + column-gap: var(--space-2); +} +.aqt-bar + .aqt-bar { + margin-top: 2px; +} +.aqt-bar-label, +.aqt-bar-reset { + color: var(--muted); + font-size: var(--text-caption); + white-space: nowrap; +} +.aqt-bar-reset { + grid-column: 2 / 4; +} +.aqt-bar-reset:empty { + display: none; +} +.aqt-bar-value { + text-align: right; + font-variant-numeric: tabular-nums; +} +.aqt-next { + margin-top: var(--space-1); +} +.aqt-flag { + white-space: nowrap; +} +.aqt-flag--ok { color: var(--green); } +.aqt-flag--warn { color: var(--amber); } +.aqt-flag--muted { color: var(--muted); } +.aqt-actions .btn { + display: block; + white-space: nowrap; +} +} diff --git a/gui/src/hooks/useAccountProbe.ts b/gui/src/hooks/useAccountProbe.ts new file mode 100644 index 00000000000..9475387c059 --- /dev/null +++ b/gui/src/hooks/useAccountProbe.ts @@ -0,0 +1,81 @@ +import { useCallback, useState } from "react"; + +/** Mirrors `AccountProbeStatus` in src/providers/quota/antigravity-account-probe.ts. */ +export const ACCOUNT_PROBE_STATUSES = [ + "ok", "paused", "token_expired", "suspended", "verification_required", "rate_limited", "permission_denied", "error", +] as const; +export type AccountProbeStatus = typeof ACCOUNT_PROBE_STATUSES[number]; + +export interface AccountProbeResultDto { + accountId: string; + status: AccountProbeStatus; + httpStatus: number | null; + reason: string | null; + message: string | null; + latencyMs?: number; + quota?: { customWindows?: Array<{ label: string; percent: number }> } | null; +} + +/** Providers whose management API implements `POST /api/oauth/accounts/probe`. */ +export const ACCOUNT_PROBE_PROVIDERS: ReadonlySet = new Set(["google-antigravity"]); + +export type AccountProbeEntry = { result: AccountProbeResultDto; at: number } | { failed: true; at: number }; + +function isProbeResult(value: unknown): value is AccountProbeResultDto { + if (!value || typeof value !== "object") return false; + const row = value as Partial; + return typeof row.accountId === "string" && typeof row.status === "string" + && (ACCOUNT_PROBE_STATUSES as readonly string[]).includes(row.status); +} + +/** Probe state for one provider's account list; results stay in memory for this view only. */ +export function useAccountProbe(apiBase: string, provider: string) { + const [entries, setEntries] = useState>({}); + const [pending, setPending] = useState>(new Set()); + const [allPending, setAllPending] = useState(false); + + const probe = useCallback(async (accountIds: readonly string[], all: boolean) => { + setPending(previous => new Set([...previous, ...accountIds])); + if (all) setAllPending(true); + const at = Date.now(); + try { + const response = await fetch(`${apiBase}/api/oauth/accounts/probe`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ provider, ...(all ? {} : { accountId: accountIds[0] }) }), + }); + const json = response.ok ? await response.json().catch(() => null) as { results?: unknown } | null : null; + const results = Array.isArray(json?.results) ? json.results.filter(isProbeResult) : []; + setEntries(previous => { + const next = { ...previous }; + for (const id of accountIds) next[id] = { failed: true, at }; + for (const result of results) next[result.accountId] = { result, at }; + return next; + }); + } catch { + setEntries(previous => { + const next = { ...previous }; + for (const id of accountIds) next[id] = { failed: true, at }; + return next; + }); + } finally { + setPending(previous => { + const next = new Set(previous); + for (const id of accountIds) next.delete(id); + return next; + }); + if (all) setAllPending(false); + } + }, [apiBase, provider]); + + return { + entries, + isPending: (accountId: string) => pending.has(accountId), + allPending, + probeOne: (accountId: string) => probe([accountId], false), + probeAll: (accountIds: readonly string[]) => probe(accountIds, true), + }; +} + +export type AccountProbeController = ReturnType; + diff --git a/gui/src/i18n/account-probe-copy.ts b/gui/src/i18n/account-probe-copy.ts new file mode 100644 index 00000000000..8c649ffc70f --- /dev/null +++ b/gui/src/i18n/account-probe-copy.ts @@ -0,0 +1,63 @@ +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; + +/** Per-account probe and manual model discovery copy, one row per key in `locales` order. */ +const rows = { + "acctProbe.test": ["Test", "테스트", "Testen", "Tester", "测试", "測試", "Проверить", "テスト", "Test et", "Kiểm tra", "Testar"], + "acctProbe.testing": ["Testing…", "테스트 중…", "Wird getestet…", "Test en cours…", "测试中…", "測試中…", "Проверка…", "テスト中…", "Test ediliyor…", "Đang kiểm tra…", "Testando…"], + "acctProbe.testAll": ["Test all", "모두 테스트", "Alle testen", "Tout tester", "全部测试", "全部測試", "Проверить все", "すべてテスト", "Tümünü test et", "Kiểm tra tất cả", "Testar todas"], + "acctProbe.hint": ["Read-only: sends one quota request with this account's stored token. Expired tokens are reported, never refreshed.", "읽기 전용: 이 계정에 저장된 토큰으로 할당량 요청을 한 번 보냅니다. 만료된 토큰은 갱신하지 않고 그대로 보고합니다.", "Nur lesend: sendet eine Kontingentanfrage mit dem gespeicherten Token dieses Kontos. Abgelaufene Tokens werden gemeldet, nie erneuert.", "Lecture seule : envoie une requête de quota avec le jeton enregistré de ce compte. Un jeton expiré est signalé, jamais renouvelé.", "只读:用该账号已存的 token 发一次额度查询。token 已过期时只报告,不刷新。", "唯讀:用該帳號已存的 Token 送出一次額度查詢。Token 已過期時只回報,不刷新。", "Только чтение: один запрос квоты с сохранённым токеном аккаунта. Истёкший токен только отмечается, не обновляется.", "読み取り専用:このアカウントの保存済みトークンでクォータ要求を 1 回送ります。期限切れトークンは報告のみで更新しません。", "Salt okunur: bu hesabın kayıtlı belirteciyle bir kota isteği gönderir. Süresi dolmuş belirteç yenilenmez, yalnızca bildirilir.", "Chỉ đọc: gửi một yêu cầu hạn mức bằng token đã lưu của tài khoản. Token hết hạn chỉ được báo, không làm mới.", "Somente leitura: envia uma consulta de cota com o token salvo desta conta. Tokens expirados são informados, nunca renovados."], + "acctProbe.failed": ["Test request failed", "테스트 요청 실패", "Testanfrage fehlgeschlagen", "La requête de test a échoué", "测试请求失败", "測試請求失敗", "Запрос проверки не выполнен", "テスト要求に失敗しました", "Test isteği başarısız", "Yêu cầu kiểm tra thất bại", "Falha na solicitação de teste"], + "acctProbe.status.ok": ["Usable", "사용 가능", "Nutzbar", "Utilisable", "可用", "可用", "Работает", "利用可能", "Kullanılabilir", "Dùng được", "Utilizável"], + "acctProbe.status.paused": ["Paused (not tested)", "일시 중지됨(테스트 안 함)", "Pausiert (nicht getestet)", "En pause (non testé)", "已暂停(未测试)", "已暫停(未測試)", "Приостановлен (не проверялся)", "一時停止中(未テスト)", "Duraklatıldı (test edilmedi)", "Đã tạm dừng (không kiểm tra)", "Pausada (não testada)"], + "acctProbe.status.token_expired": ["Token expired (not refreshed)", "토큰 만료(갱신 안 함)", "Token abgelaufen (nicht erneuert)", "Jeton expiré (non renouvelé)", "token 已过期(未刷新)", "Token 已過期(未刷新)", "Токен истёк (не обновлён)", "トークン期限切れ(未更新)", "Belirteç süresi doldu (yenilenmedi)", "Token hết hạn (chưa làm mới)", "Token expirado (não renovado)"], + "acctProbe.status.suspended": ["Suspended", "정지됨", "Gesperrt", "Suspendu", "已暂停", "已暫停", "Приостановлен", "停止中", "Askıya alındı", "Bị đình chỉ", "Suspensa"], + "acctProbe.status.verification_required": ["Verification required", "인증 필요", "Verifizierung erforderlich", "Vérification requise", "要求验证", "需要驗證", "Требуется подтверждение", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária"], + "acctProbe.status.rate_limited": ["Rate limited", "요청 제한", "Ratenlimit", "Limite de débit", "限流", "限流", "Ограничение частоты", "レート制限", "Hız sınırı", "Bị giới hạn tốc độ", "Limite de taxa"], + "acctProbe.status.permission_denied": ["Permission denied (403)", "권한 거부(403)", "Zugriff verweigert (403)", "Accès refusé (403)", "权限拒绝(403)", "權限遭拒(403)", "Доступ запрещён (403)", "権限拒否(403)", "İzin reddedildi (403)", "Bị từ chối quyền (403)", "Permissão negada (403)"], + "acctProbe.status.error": ["Other error", "기타 오류", "Anderer Fehler", "Autre erreur", "其他错误", "其他錯誤", "Другая ошибка", "その他のエラー", "Diğer hata", "Lỗi khác", "Outro erro"], + "modelDiscover.now": ["Discover now", "지금 검색", "Jetzt abrufen", "Découvrir maintenant", "立即发现", "立即探索", "Найти сейчас", "今すぐ検出", "Şimdi keşfet", "Khám phá ngay", "Descobrir agora"], + "modelDiscover.running": ["Discovering…", "검색 중…", "Wird abgerufen…", "Découverte…", "发现中…", "探索中…", "Поиск…", "検出中…", "Keşfediliyor…", "Đang khám phá…", "Descobrindo…"], + "modelDiscover.recent": ["Recently added models", "최근 추가된 모델", "Kürzlich hinzugekommene Modelle", "Modèles ajoutés récemment", "最近新增的模型", "最近新增的模型", "Недавно добавленные модели", "最近追加されたモデル", "Son eklenen modeller", "Mô hình mới thêm gần đây", "Modelos adicionados recentemente"], + "modelDiscover.none": ["No new models recorded yet.", "아직 기록된 새 모델이 없습니다.", "Noch keine neuen Modelle erfasst.", "Aucun nouveau modèle enregistré pour l’instant.", "还没有记录到新模型。", "尚未記錄到新模型。", "Новые модели пока не обнаружены.", "新しいモデルはまだ記録されていません。", "Henüz yeni model kaydedilmedi.", "Chưa ghi nhận mô hình mới nào.", "Nenhum modelo novo registrado ainda."], + "modelDiscover.result": ["{count} live models, {added} new", "실시간 모델 {count}개, 새 모델 {added}개", "{count} Live-Modelle, {added} neu", "{count} modèles en direct, {added} nouveaux", "共 {count} 个在线模型,新增 {added} 个", "共 {count} 個線上模型,新增 {added} 個", "Моделей: {count}, новых: {added}", "ライブモデル {count} 件、新規 {added} 件", "{count} canlı model, {added} yeni", "{count} mô hình trực tiếp, {added} mới", "{count} modelos ativos, {added} novos"], + "modelDiscover.failed": ["Discovery failed", "검색 실패", "Abruf fehlgeschlagen", "Échec de la découverte", "发现失败", "探索失敗", "Поиск не удался", "検出に失敗しました", "Keşif başarısız", "Khám phá thất bại", "Falha na descoberta"], + "modelDiscover.static": ["Live discovery is off for this provider.", "이 공급자는 실시간 검색이 꺼져 있습니다.", "Live-Abruf ist für diesen Anbieter aus.", "La découverte en direct est désactivée pour ce fournisseur.", "该供应商未开启在线发现。", "此供應商未開啟線上探索。", "Для этого провайдера поиск моделей отключён.", "このプロバイダーはライブ検出がオフです。", "Bu sağlayıcı için canlı keşif kapalı.", "Nhà cung cấp này đang tắt khám phá trực tiếp.", "A descoberta ao vivo está desativada para este provedor."], + "modelDiscover.autoDisabled": ["hidden by new-model policy", "새 모델 정책으로 숨김", "durch Neu-Modell-Richtlinie ausgeblendet", "masqué par la règle des nouveaux modèles", "按新模型策略已隐藏", "依新模型政策已隱藏", "скрыта политикой новых моделей", "新モデルポリシーで非表示", "yeni model politikasıyla gizlendi", "bị ẩn theo chính sách mô hình mới", "oculto pela política de novos modelos"], + "modelDiscover.new": ["NEW", "NEW", "NEU", "NOUVEAU", "新", "新", "НОВАЯ", "NEW", "YENİ", "MỚI", "NOVO"], + "acctTable.title": ["Account quotas", "계정 할당량", "Kontingente je Konto", "Quotas par compte", "账号额度", "帳號額度", "Квоты аккаунтов", "アカウント別クォータ", "Hesap kotaları", "Hạn mức theo tài khoản", "Cotas por conta"], + "acctTable.account": ["Account", "계정", "Konto", "Compte", "账号", "帳號", "Аккаунт", "アカウント", "Hesap", "Tài khoản", "Conta"], + "acctTable.plan": ["Plan", "플랜", "Tarif", "Forfait", "套餐", "方案", "План", "プラン", "Plan", "Gói", "Plano"], + "acctTable.status": ["Status", "상태", "Status", "État", "状态", "狀態", "Статус", "状態", "Durum", "Trạng thái", "Status"], + "acctTable.actions": ["Actions", "작업", "Aktionen", "Actions", "操作", "操作", "Действия", "操作", "İşlemler", "Thao tác", "Ações"], + "acctTable.unknownPlan": ["Unknown plan", "알 수 없는 플랜", "Tarif unbekannt", "Forfait inconnu", "未知套餐", "未知方案", "План неизвестен", "プラン不明", "Plan bilinmiyor", "Không rõ gói", "Plano desconhecido"], + "acctTable.planSource": ["Upstream tier: {tier}", "업스트림 등급: {tier}", "Upstream-Stufe: {tier}", "Niveau amont : {tier}", "上游套餐字段:{tier}", "上游方案欄位:{tier}", "Тариф от провайдера: {tier}", "上流の階層: {tier}", "Üst kaynak katmanı: {tier}", "Hạng từ nhà cung cấp: {tier}", "Nível do provedor: {tier}"], + "acctTable.pool.gemini": ["Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini"], + "acctTable.pool.claudeGpt": ["Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT"], + "acctTable.pool.argon": ["Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon"], + "acctTable.pool.subscription": ["Subscription", "구독", "Abo", "Abonnement", "订阅额度", "訂閱額度", "Подписка", "サブスク", "Abonelik", "Gói đăng ký", "Assinatura"], + "acctTable.scarce": ["scarce", "희소", "knapp", "rare", "稀缺", "稀缺", "дефицит", "希少", "kıt", "khan hiếm", "escassa"], + "acctTable.fiveHour": ["5h", "5시간", "5 Std.", "5 h", "5 小时", "5 小時", "5 ч", "5時間", "5 sa", "5 giờ", "5 h"], + "acctTable.weekly": ["Week", "주간", "Woche", "Semaine", "每周", "每週", "Неделя", "週", "Hafta", "Tuần", "Semana"], + "acctTable.resetsIn": ["resets in {time}", "{time} 후 초기화", "Reset in {time}", "réinit. dans {time}", "{time} 后重置", "{time} 後重置", "сброс через {time}", "{time} 後リセット", "{time} sonra sıfırlanır", "đặt lại sau {time}", "reinicia em {time}"], + "acctTable.next": ["next", "다음", "als Nächstes", "suivant", "优先", "優先", "следующий", "次", "sıradaki", "kế tiếp", "próxima"], + "acctTable.nextHint": ["Resets soonest among usable accounts, so reset-first spends it first", "사용 가능한 계정 중 가장 먼저 초기화되어 reset-first가 먼저 사용합니다", "Wird unter nutzbaren Konten zuerst zurückgesetzt, daher nutzt reset-first es zuerst", "Se réinitialise en premier parmi les comptes utilisables : reset-first l’utilise d’abord", "在可用账号里最先重置,「最快重置优先」会先用它", "在可用帳號中最先重置,「最快重置優先」會先用它", "Сбрасывается раньше других доступных аккаунтов, поэтому reset-first расходует его первым", "使用可能なアカウントで最も早くリセットされるため、reset-first が先に使います", "Kullanılabilir hesaplar arasında ilk sıfırlanan; reset-first önce bunu kullanır", "Đặt lại sớm nhất trong các tài khoản dùng được, nên reset-first dùng trước", "Reinicia antes entre as contas utilizáveis, então reset-first a usa primeiro"], + "acctTable.noReading": ["No quota reading yet", "아직 할당량을 읽지 못함", "Noch kein Kontingent gelesen", "Aucun quota lu pour l’instant", "还没读到额度", "尚未讀到額度", "Квота ещё не прочитана", "クォータ未取得", "Henüz kota okunmadı", "Chưa đọc được hạn mức", "Cota ainda não lida"], + "acctTable.policy": ["Quota policy: scarce pools (Antigravity Claude & GPT, Anthropic and OpenAI subscriptions) go to the account that resets soonest when the pool strategy is reset-first. Gemini is effectively unlimited and is not rushed.", "할당량 정책: 풀 전략이 reset-first일 때 희소 풀(Antigravity Claude & GPT, Anthropic·OpenAI 구독)은 가장 먼저 초기화되는 계정부터 씁니다. Gemini는 사실상 무제한이라 서둘러 쓰지 않습니다.", "Kontingentregel: Knappe Pools (Antigravity Claude & GPT, Anthropic- und OpenAI-Abos) gehen bei der Strategie reset-first an das Konto, das zuerst zurückgesetzt wird. Gemini ist praktisch unbegrenzt und wird nicht vorgezogen.", "Règle de quota : avec la stratégie reset-first, les pools rares (Antigravity Claude & GPT, abonnements Anthropic et OpenAI) vont au compte qui se réinitialise le plus tôt. Gemini est pratiquement illimité et n’est pas pressé.", "额度策略:轮换策略为「最快重置优先」(reset-first)时,稀缺池(Antigravity 的 Claude & GPT、Anthropic 和 OpenAI 订阅)先用最快重置的账号;Gemini 基本不限量,不抢着用。", "額度策略:輪換策略為「最快重置優先」(reset-first)時,稀缺池(Antigravity 的 Claude & GPT、Anthropic 與 OpenAI 訂閱)先用最快重置的帳號;Gemini 基本不限量,不搶著用。", "Политика квот: при стратегии reset-first дефицитные пулы (Antigravity Claude & GPT, подписки Anthropic и OpenAI) отдаются аккаунту, который сбросится раньше всех. Gemini практически безлимитен, его не торопят.", "クォータ方針:プール戦略が reset-first のとき、希少プール(Antigravity の Claude & GPT、Anthropic と OpenAI のサブスク)は最も早くリセットされるアカウントから使います。Gemini は実質無制限なので急ぎません。", "Kota ilkesi: havuz stratejisi reset-first iken kıt havuzlar (Antigravity Claude & GPT, Anthropic ve OpenAI abonelikleri) ilk sıfırlanacak hesaba gider. Gemini pratikte sınırsızdır, aceleye getirilmez.", "Chính sách hạn mức: khi chiến lược là reset-first, các nhóm khan hiếm (Antigravity Claude & GPT, gói Anthropic và OpenAI) dùng tài khoản đặt lại sớm nhất trước. Gemini gần như không giới hạn nên không cần vội.", "Política de cota: com a estratégia reset-first, pools escassos (Antigravity Claude & GPT, assinaturas Anthropic e OpenAI) vão para a conta que reinicia primeiro. Gemini é praticamente ilimitado e não é apressado."], + "acctTable.flag.ok": ["Healthy", "정상", "In Ordnung", "Sain", "正常", "正常", "Работает", "正常", "Sağlıklı", "Bình thường", "Saudável"], + "acctTable.flag.paused": ["Paused", "일시 중지", "Pausiert", "En pause", "已暂停", "已暫停", "Приостановлен", "一時停止", "Duraklatıldı", "Đã tạm dừng", "Pausada"], + "acctTable.flag.reauth": ["Sign-in needed", "재로그인 필요", "Anmeldung nötig", "Connexion requise", "需重新登录", "需重新登入", "Нужен вход", "再ログインが必要", "Oturum açılmalı", "Cần đăng nhập lại", "Login necessário"], + "acctTable.flag.rateLimited": ["Rate limited", "요청 제한", "Ratenlimit", "Débit limité", "限流中", "限流中", "Ограничение частоты", "レート制限中", "Hız sınırında", "Bị giới hạn tốc độ", "Limite de taxa"], + "acctTable.flag.quotaLimited": ["Quota cooldown", "할당량 대기", "Kontingent-Pause", "Pause de quota", "额度冷却中", "額度冷卻中", "Квота на паузе", "クォータ待機中", "Kota beklemesi", "Đang chờ hạn mức", "Pausa de cota"], + "acctTable.flag.warning": ["Warning", "경고", "Warnung", "Alerte", "有警告", "有警告", "Предупреждение", "警告", "Uyarı", "Cảnh báo", "Aviso"], + "acctTable.flag.slow": ["Slow", "느림", "Langsam", "Lent", "响应慢", "回應慢", "Медленно", "遅い", "Yavaş", "Chậm", "Lenta"], + "acctTable.flag.stale": ["Quota not read", "할당량 미확인", "Kontingent nicht gelesen", "Quota non lu", "额度没读到", "額度沒讀到", "Квота не прочитана", "クォータ未取得", "Kota okunamadı", "Chưa đọc được hạn mức", "Cota não lida"], +} as const satisfies Record; + +export type AccountProbeCopyKey = keyof typeof rows; + +export function accountProbeCopy(locale: Locale): Record { + const index = locales.indexOf(locale); + return Object.fromEntries(Object.entries(rows).map(([key, values]) => [key, values[index]!])) as Record; +} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 234541ce8ca..180469b9916 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -134,6 +135,7 @@ export const de: Record = { "workflowBudget.saveFailed": "Workflow-Limits konnten nicht gespeichert werden.", "workflowBudget.saved": "Workflow-Limits gespeichert.", ...desktopCompatibilityCopy("de"), + ...accountProbeCopy("de"), ...shellV2Copy("de"), ...codexCliUpdateCopy("de"), ...remoteLinkDiagnosticsCopy("de"), diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 76381be2404..124dc915fd7 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -135,6 +136,7 @@ export const en = { "workflowBudget.saveFailed": "Could not save workflow limits.", "workflowBudget.saved": "Workflow limits saved.", ...desktopCompatibilityCopy("en"), + ...accountProbeCopy("en"), ...shellV2Copy("en"), ...codexCliUpdateCopy("en"), ...remoteLinkDiagnosticsCopy("en"), diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index f0314b0c16e..3a01fdd53e6 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -133,6 +134,7 @@ export const fr: Record = { "workflowBudget.saveFailed": "Impossible d'enregistrer les limites de workflow.", "workflowBudget.saved": "Limites de workflow enregistrées.", ...desktopCompatibilityCopy("fr"), + ...accountProbeCopy("fr"), ...shellV2Copy("fr"), ...codexCliUpdateCopy("fr"), ...remoteLinkDiagnosticsCopy("fr"), diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index b71b131dd49..c24fc34a0dd 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -133,6 +134,7 @@ export const ja: Record = { "workflowBudget.saveFailed": "ワークフロー上限を保存できませんでした。", "workflowBudget.saved": "ワークフロー上限を保存しました。", ...desktopCompatibilityCopy("ja"), + ...accountProbeCopy("ja"), ...shellV2Copy("ja"), ...codexCliUpdateCopy("ja"), ...remoteLinkDiagnosticsCopy("ja"), diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 399a227c363..260d5e6db53 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -133,6 +134,7 @@ export const ko: Record = { "workflowBudget.saveFailed": "워크플로 한도를 저장하지 못했습니다.", "workflowBudget.saved": "워크플로 한도를 저장했습니다.", ...desktopCompatibilityCopy("ko"), + ...accountProbeCopy("ko"), ...shellV2Copy("ko"), ...codexCliUpdateCopy("ko"), ...remoteLinkDiagnosticsCopy("ko"), diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 1b5c4960b76..e9dc848d368 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -135,6 +136,7 @@ export const pt: Record = { "workflowBudget.saveFailed": "Não foi possível salvar os limites de fluxo de trabalho.", "workflowBudget.saved": "Limites de fluxo de trabalho salvos.", ...desktopCompatibilityCopy("pt"), + ...accountProbeCopy("pt"), ...shellV2Copy("pt"), ...codexCliUpdateCopy("pt"), ...remoteLinkDiagnosticsCopy("pt"), diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 2771adadf00..21e215f2d26 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -133,6 +134,7 @@ export const ru: Record = { "workflowBudget.saveFailed": "Не удалось сохранить лимиты рабочих процессов.", "workflowBudget.saved": "Лимиты рабочих процессов сохранены.", ...desktopCompatibilityCopy("ru"), + ...accountProbeCopy("ru"), ...shellV2Copy("ru"), ...codexCliUpdateCopy("ru"), ...remoteLinkDiagnosticsCopy("ru"), diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index c27997fc8b4..ed605f4b6c1 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -134,6 +135,7 @@ export const tr: Record = { "workflowBudget.saveFailed": "İş akışı sınırları kaydedilemedi.", "workflowBudget.saved": "İş akışı sınırları kaydedildi.", ...desktopCompatibilityCopy("tr"), + ...accountProbeCopy("tr"), ...shellV2Copy("tr"), ...codexCliUpdateCopy("tr"), ...remoteLinkDiagnosticsCopy("tr"), diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 930028388dc..70f59d803b7 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -135,6 +136,7 @@ export const vi: Record = { "workflowBudget.saveFailed": "Không thể lưu giới hạn quy trình.", "workflowBudget.saved": "Đã lưu giới hạn quy trình.", ...desktopCompatibilityCopy("vi"), + ...accountProbeCopy("vi"), ...shellV2Copy("vi"), ...codexCliUpdateCopy("vi"), ...remoteLinkDiagnosticsCopy("vi"), diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 33da090ccc0..d6a3e34df3d 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -131,6 +132,7 @@ export const zhTW: Record = { "workflowBudget.saveFailed": "無法儲存工作流程限制。", "workflowBudget.saved": "工作流程限制已儲存。", ...desktopCompatibilityCopy("zh-TW"), + ...accountProbeCopy("zh-TW"), ...shellV2Copy("zh-TW"), ...codexCliUpdateCopy("zh-TW"), ...remoteLinkDiagnosticsCopy("zh-TW"), diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index fe8f2d4c4d9..cabf672308c 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -1,4 +1,5 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; @@ -133,6 +134,7 @@ export const zh: Record = { "workflowBudget.saveFailed": "无法保存工作流限制。", "workflowBudget.saved": "工作流限制已保存。", ...desktopCompatibilityCopy("zh"), + ...accountProbeCopy("zh"), ...shellV2Copy("zh"), ...codexCliUpdateCopy("zh"), ...remoteLinkDiagnosticsCopy("zh"), diff --git a/gui/src/provider-workspace/account-quota-table.ts b/gui/src/provider-workspace/account-quota-table.ts new file mode 100644 index 00000000000..92a760a33e0 --- /dev/null +++ b/gui/src/provider-workspace/account-quota-table.ts @@ -0,0 +1,189 @@ +/** + * One row per account, one column per quota pool: the at-a-glance account table on the + * Providers page. Pure data so the shape is testable without rendering. + * + * A pool is a registry entry, not a branch per provider: each entry names the window labels + * (or standard fields) that carry its 5-hour and weekly readings, and a provider shows the + * pools its accounts actually report. + */ + +export type PoolWindow = "fiveHour" | "weekly"; +export type PoolKey = "gemini" | "claudeGpt" | "argon" | "subscription"; + +interface QuotaWindowLike { label: string; percent: number; resetAt?: number } +export interface QuotaLike { + fiveHourPercent?: number; + fiveHourResetAt?: number; + weeklyPercent?: number; + weeklyResetAt?: number; + customWindows?: readonly QuotaWindowLike[]; +} + +type Reading = { percent: number; resetAt?: number }; +interface PoolSpec { + key: PoolKey; + /** Scarce pools are spent soonest-reset first; Gemini is effectively unlimited. */ + scarce: boolean; + read(quota: QuotaLike): Partial>; +} + +const byLabel = (fiveHour: string, weekly: string) => (quota: QuotaLike) => { + const find = (label: string) => quota.customWindows?.find(window => window.label === label); + const out: Partial> = {}; + const short = find(fiveHour); + const long = find(weekly); + if (short) out.fiveHour = short; + if (long) out.weekly = long; + return out; +}; + +export const QUOTA_POOLS: readonly PoolSpec[] = [ + { key: "gemini", scarce: false, read: byLabel("Gem", "Gem (Weekly)") }, + { key: "claudeGpt", scarce: true, read: byLabel("Cla", "Cla (Weekly)") }, + { key: "argon", scarce: false, read: byLabel("Argon", "Argon (Weekly)") }, + { + key: "subscription", + scarce: true, + read: quota => ({ + ...(typeof quota.fiveHourPercent === "number" ? { fiveHour: { percent: quota.fiveHourPercent, resetAt: quota.fiveHourResetAt } } : {}), + ...(typeof quota.weeklyPercent === "number" ? { weekly: { percent: quota.weeklyPercent, resetAt: quota.weeklyResetAt } } : {}), + }), + }, +]; + +/** Upstream tier ids seen in the wild, mapped to their product names. Anything else shows raw. */ +const PLAN_NAMES: Readonly> = { + "g1-pro-tier": "Pro", + "free-tier": "Free", + "standard-tier": "Standard", + free: "Free", + plus: "Plus", + pro: "Pro", + team: "Team", + business: "Business", + enterprise: "Enterprise", + edu: "Edu", +}; + +/** `null` means upstream did not say; the caller renders "unknown plan" rather than a guess. */ +export function planDisplayName(plan: string | null | undefined, planLabel?: string): string | null { + if (planLabel?.trim()) return planLabel.trim(); + if (!plan?.trim()) return null; + return PLAN_NAMES[plan.trim().toLowerCase()] ?? plan.trim(); +} + +export type AccountFlag = "ok" | "paused" | "reauth" | "rateLimited" | "quotaLimited" | "warning" | "probeFailed" | "slow" | "stale"; + +/** A probe slower than this is flagged; real Antigravity quota reads answer in about a second. */ +export const SLOW_PROBE_MS = 8_000; + +export interface QuotaTableAccount { + id: string; + label: string; + plan?: string | null; + planLabel?: string; + active: boolean; + paused: boolean; + needsReauth?: boolean; + health?: { status: string; reason?: string }; + quota?: QuotaLike | null; + quotaUnavailable?: boolean; + probe?: { status: string; latencyMs?: number }; +} + +export interface PoolCell { + /** Remaining share, 0–100. */ + remaining: number; + /** Epoch milliseconds. */ + resetAt?: number; +} + +export interface QuotaTableRow { + account: QuotaTableAccount; + plan: string | null; + flag: AccountFlag; + /** Probe status when the flag came from a probe, for its label. */ + probeStatus?: string; + cells: Partial>>>; + /** Scarce pools whose soonest reset among usable accounts belongs to this row. */ + next: PoolKey[]; +} + +export interface QuotaTable { + pools: PoolSpec[]; + rows: QuotaTableRow[]; +} + +/** Upstream resets arrive in seconds or milliseconds; QuotaBars reads them the same way. */ +function toMs(value: number | undefined): number | undefined { + if (typeof value !== "number" || !Number.isFinite(value)) return undefined; + return value > 10_000_000_000 ? value : value * 1000; +} + +function clampRemaining(usedPercent: number): number { + return Math.max(0, Math.min(100, 100 - usedPercent)); +} + +function accountFlag(account: QuotaTableAccount): { flag: AccountFlag; probeStatus?: string } { + if (account.paused) return { flag: "paused" }; + if (account.needsReauth || account.health?.status === "reauth_required") return { flag: "reauth" }; + if (account.health?.status === "cooldown") return { flag: account.health.reason === "rate_limit" ? "rateLimited" : "quotaLimited" }; + const probe = account.probe; + if (probe && probe.status !== "ok" && probe.status !== "paused") return { flag: "probeFailed", probeStatus: probe.status }; + if (account.health?.status === "warning") return { flag: "warning" }; + if (probe?.status === "ok" && typeof probe.latencyMs === "number" && probe.latencyMs > SLOW_PROBE_MS) return { flag: "slow" }; + if (account.quotaUnavailable) return { flag: "stale" }; + return { flag: "ok" }; +} + +const USABLE: ReadonlySet = new Set(["ok", "slow", "stale", "warning"]); + +export function buildQuotaTable(accounts: readonly QuotaTableAccount[], now = Date.now()): QuotaTable { + const rows: QuotaTableRow[] = accounts.map(account => { + const cells: QuotaTableRow["cells"] = {}; + if (account.quota) { + for (const pool of QUOTA_POOLS) { + const readings = pool.read(account.quota); + const cell: Partial> = {}; + for (const window of ["fiveHour", "weekly"] as const) { + const reading = readings[window]; + if (!reading || !Number.isFinite(reading.percent)) continue; + const resetAt = toMs(reading.resetAt); + cell[window] = { remaining: clampRemaining(reading.percent), ...(resetAt && resetAt > now ? { resetAt } : {}) }; + } + if (cell.fiveHour || cell.weekly) cells[pool.key] = cell; + } + } + return { account, plan: planDisplayName(account.plan, account.planLabel), ...accountFlag(account), cells, next: [] }; + }); + + const pools = QUOTA_POOLS.filter(pool => rows.some(row => row.cells[pool.key])); + // Mirror of reset-first: among accounts that can serve and still have headroom, the one whose + // allowance expires first is used first, so nothing lapses unspent. + for (const pool of pools.filter(spec => spec.scarce)) { + let best: { row: QuotaTableRow; resetAt: number } | undefined; + for (const row of rows) { + const cell = row.cells[pool.key]; + if (!cell || !USABLE.has(row.flag)) continue; + const windows = [cell.fiveHour, cell.weekly].filter((window): window is PoolCell => window !== undefined); + if (windows.some(window => window.remaining <= 0)) continue; + const resetAt = (cell.weekly ?? cell.fiveHour)?.resetAt; + if (resetAt === undefined) continue; + if (!best || resetAt < best.resetAt) best = { row, resetAt }; + } + best?.row.next.push(pool.key); + } + return { pools, rows }; +} + +/** "45m", "3h 12m", "2d 5h"; under a minute reads "<1m". */ +export function formatCountdown(resetAt: number, now = Date.now()): string { + const minutes = Math.floor((resetAt - now) / 60_000); + if (minutes < 1) return "<1m"; + const days = Math.floor(minutes / 1440); + const hours = Math.floor((minutes % 1440) / 60); + const mins = minutes % 60; + if (days > 0) return `${days}d ${hours}h`; + if (hours > 0) return `${hours}h ${mins}m`; + return `${mins}m`; +} diff --git a/gui/tests/fr-localization.test.ts b/gui/tests/fr-localization.test.ts index f58f8ecec7b..6d7c72bb4b7 100644 --- a/gui/tests/fr-localization.test.ts +++ b/gui/tests/fr-localization.test.ts @@ -28,6 +28,10 @@ const INTENTIONAL_ENGLISH = new Set([ "remoteLinkDiagnostics.colPort", // "Port" is the same word in French (a network port column). "usageV2.remoteLink", // Remote Link is the product name. "nav.claude", // Product name. + "acctTable.actions", // "Actions" is the same word in French (the table's action column). + "acctTable.pool.gemini", // Quota pool named after the product. + "acctTable.pool.claudeGpt", // Quota pool named after the products. + "acctTable.pool.argon", // Quota pool name used by the Antigravity quota API. "nav.codexSet", // Product name: the sidebar row reads "Codex" in every locale. "codexCliUpdate.tab", // Product name: the Codex CLI tab reads "Codex CLI" in every locale. "codexCliUpdate.provNpmGlobal", // "npm (global)": the tool name plus a word French spells the same. diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 05605249cbe..30858119d9f 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -2,7 +2,7 @@ "version": 1, "root": "tests", "explicitShards": ["layout-route-intent.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json"], - "explicit": { "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", + "explicit": { "kimi-monthly-quota.test.ts": "providers", "gui-account-quota-table.test.ts": "gui", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", "stop-restore-history-ownership.test.ts": "service", "cli-stop-refusal-transport.test.ts": "cli", "service-proxy-env.test.ts": "service", "openai-chat-standalone-bare-block.test.ts": "adapters/openai", @@ -146,6 +146,7 @@ "account-import.test.ts": "server", "account-import-project-fallback.test.ts": "server", "main-account-hard-lock-profile-dispatch.test.ts": "codex-integration", "account-pool-management-api.test.ts": "server", + "account-probe-routes.test.ts": "server", "link-listener-admission.test.ts": "server", "link-route-proof-admission.test.ts": "server", "link-route-edit.test.ts": "server", "link-confirm-pin.test.ts": "server", "link-management-relay.test.ts": "server", "quota-pool-relay.test.ts": "server", "quota-pool.test.ts": "usage", "fallback-policy.test.ts": "routing", "responses-combo-fallback-off.test.ts": "responses", "main-account-hard-lock-fallback-off.test.ts": "codex-integration", "subagent-model-fallback-off.test.ts": "routing", "routing-policy-fallback-off.test.ts": "routing", "fallback-routes.test.ts": "server", "client-home-unreachable.test.ts": "clients", "cli-fallback.test.ts": "cli", "link-listener-lifecycle.test.ts": "server", "link-listener-mutation.test.ts": "server", "link-traffic-status.test.ts": "server", diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 367504a2daf..4f03f388886 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -26,8 +26,8 @@ These answer in the CLI head and never reach the proxy, so they work with nothin | Chapter | Declared capabilities | |---|---| | [lifecycle](01_surface_lifecycle.md) | 14 | -| [providers-models](01_surface_providers-models.md) | 53 | -| [accounts](01_surface_accounts.md) | 43 | +| [providers-models](01_surface_providers-models.md) | 54 | +| [accounts](01_surface_accounts.md) | 44 | | [agents-routing](01_surface_agents-routing.md) | 71 | | [integrations](01_surface_integrations.md) | 41 | | [observe-system](01_surface_observe-system.md) | 105 | @@ -487,6 +487,10 @@ Original invocation order. These headings preserve links to the previous single- [Read-oriented task](01_surface_providers-models.md#ocx-models-new-arrivals) +### `ocx models discover` + +[State-changing task](01_surface_providers-models.md#ocx-models-discover) + ### `ocx models context status` [Read-oriented task](01_surface_providers-models.md#ocx-models-context-status) @@ -619,6 +623,10 @@ Original invocation order. These headings preserve links to the previous single- [State-changing task](01_surface_accounts.md#ocx-account-add-key) +### `ocx account probe` + +[Read-oriented task](01_surface_accounts.md#ocx-account-probe) + ### `ocx account import` [State-changing task](01_surface_accounts.md#ocx-account-import) @@ -1645,6 +1653,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 399 -- of those, state-changing: 250 +- declared capabilities: 401 +- of those, state-changing: 251 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_accounts.md b/skills/ocx/references/01_surface_accounts.md index e7f3f72e9b6..6422de9c7dd 100644 --- a/skills/ocx/references/01_surface_accounts.md +++ b/skills/ocx/references/01_surface_accounts.md @@ -8,7 +8,7 @@ Use these declarations to choose a task, then check its flags and authority before execution. Non-mutating probes may still contact providers, consume quota or refresh caches. -Declared capabilities: 43. +Declared capabilities: 44. ### `ocx account login` @@ -557,6 +557,25 @@ State-changing: yes. JSON mode: `envelope`. - API-key providers only. Requires non-TTY stdin and reads one secret line; never put plaintext keys in command arguments or agent transcripts. This imports an upstream credential, not an OpenCodex access-key creation workflow. +### `ocx account probe` + +Usage: `ocx account probe google-antigravity [] [--json]` + +Test stored accounts one by one with their own tokens, read-only. + +State-changing: no. JSON mode: `payload`. + +| Method | Route | +|---|---| +| GET | `/api/oauth/accounts` | +| POST | `/api/oauth/accounts/probe` | + +| Flag | Value | Meaning | +|---|---|---| +| `--json` | boolean | Emit per-account status, HTTP code, reason and quota windows. | + +- Statuses: ok, paused, token_expired, suspended, verification_required, rate_limited, permission_denied, error. Sends one retrieveUserQuotaSummary request per account with its stored token; paused accounts are skipped without a request, and expired tokens are reported, never refreshed. Only google-antigravity is supported. + ### `ocx account import` Usage: `ocx account import google-antigravity --format cockpit-tools (--file |--stdin) [--json]` diff --git a/skills/ocx/references/01_surface_providers-models.md b/skills/ocx/references/01_surface_providers-models.md index 60d05132b11..e040a2b72ac 100644 --- a/skills/ocx/references/01_surface_providers-models.md +++ b/skills/ocx/references/01_surface_providers-models.md @@ -8,7 +8,7 @@ Use these declarations to choose a task, then check its flags and authority before execution. Non-mutating probes may still contact providers, consume quota or refresh caches. -Declared capabilities: 53. +Declared capabilities: 54. ### `ocx models price` @@ -650,6 +650,24 @@ State-changing: no. JSON mode: `payload`. |---|---|---| | `--json` | boolean | Emit recentArrivals grouped by provider. | +### `ocx models discover` + +Usage: `ocx models discover [--json]` + +Re-fetch one provider's live model list now and report new arrivals. + +State-changing: yes. JSON mode: `payload`. + +| Method | Route | +|---|---| +| POST | `/api/model-discovery/refresh` | + +| Flag | Value | Meaning | +|---|---|---| +| `--json` | boolean | Emit discovery status, newArrivals and recentArrivals. | + +- Clears the provider's model cache and runs catalog convergence; new models follow the configured new-model policy. Providers with liveModels off report applicable:false. + ### `ocx models context status` Usage: `ocx models context status [--json]` diff --git a/src/cli/account-probe.ts b/src/cli/account-probe.ts new file mode 100644 index 00000000000..35d360c0796 --- /dev/null +++ b/src/cli/account-probe.ts @@ -0,0 +1,66 @@ +import { apiError, apiJson, proxyUnreachable, resolveBaseUrl, type AccountDeps } from "./account-api"; + +const PROBE_USAGE = "Usage: ocx account probe google-antigravity [] [--json]"; + +interface ProbeRow { + accountId: string; + maskedLabel?: string; + active?: boolean; + paused?: boolean; + status: string; + httpStatus: number | null; + reason: string | null; + message: string | null; + quota?: { customWindows?: Array<{ label: string; percent: number }> } | null; +} + +function resolveTarget(accounts: unknown, requested: string): { id: string } | { error: string } { + const rows = (Array.isArray(accounts) ? accounts : []).filter((row): row is { id: string; alias?: unknown } => + typeof row === "object" && row !== null && typeof (row as { id?: unknown }).id === "string"); + if (rows.some(row => row.id === requested)) return { id: requested }; + const matches = rows.filter(row => typeof row.alias === "string" && row.alias.toLowerCase() === requested.toLowerCase()); + if (matches.length === 1) return { id: matches[0]!.id }; + if (matches.length > 1) return { error: `alias "${requested}" names ${matches.length} accounts; use the account id` }; + return { error: `Account not found: no OAuth account has the id or alias "${requested}"` }; +} + +function rowLine(row: ProbeRow): string { + const flags = [row.active ? "active" : "", row.paused ? "paused" : ""].filter(Boolean).map(flag => `[${flag}]`).join(""); + const evidence = [row.httpStatus !== null ? `HTTP ${row.httpStatus}` : "", row.reason ?? "", row.message ?? ""].filter(Boolean).join(" · "); + const windows = (row.quota?.customWindows ?? []).map(window => `${window.label} ${Math.round(100 - window.percent)}% left`).join(", "); + return [`${row.accountId} ${row.maskedLabel ?? ""}${flags ? ` ${flags}` : ""}`.trim(), row.status, evidence, windows].filter(Boolean).join(" | "); +} + +/** Read-only per-account probe through `POST /api/oauth/accounts/probe`. */ +export async function cmdAccountProbe(args: string[], deps: AccountDeps): Promise { + const wantsJson = args.includes("--json"); + const positional = args.filter(arg => arg !== "--json"); + const provider = positional[0]?.trim().toLowerCase() ?? ""; + const requested = positional[1]; + if (!provider || positional.length > 2) { + console.error(PROBE_USAGE); + return 1; + } + const baseUrl = await resolveBaseUrl(deps); + if (!baseUrl) return proxyUnreachable(); + let accountId: string | undefined; + if (requested !== undefined) { + const list = await apiJson(deps, baseUrl, "GET", `/api/oauth/accounts?provider=${encodeURIComponent(provider)}`); + if (list.status === 0) return proxyUnreachable(list.transportError); + if (list.status !== 200) return apiError(list.json, `failed to list ${provider} OAuth accounts`, list.status); + const target = resolveTarget(list.json?.accounts, requested); + if ("error" in target) { + console.error(`Error: ${target.error}`); + return 1; + } + accountId = target.id; + } + const response = await apiJson(deps, baseUrl, "POST", "/api/oauth/accounts/probe", { provider, ...(accountId ? { accountId } : {}) }); + if (response.status === 0) return proxyUnreachable(response.transportError); + if (response.status !== 200) return apiError(response.json, `failed to probe ${provider} accounts`, response.status); + const results = Array.isArray(response.json?.results) ? response.json.results as ProbeRow[] : []; + if (wantsJson) console.log(JSON.stringify(response.json, null, 2)); + else if (results.length === 0) console.log(`${provider}: no stored accounts`); + else for (const row of results) console.log(rowLine(row)); + return 0; +} diff --git a/src/cli/account.ts b/src/cli/account.ts index b1a6e9004d3..e25b70f4a7d 100644 --- a/src/cli/account.ts +++ b/src/cli/account.ts @@ -65,6 +65,7 @@ const ACCOUNT_USAGE = `Usage: ocx account routes [--file |--clear] [--json] ocx account remove --yes [--json] ocx account clear-cooldown [--json] + ocx account probe google-antigravity [] [--json] ocx account add-key [--label