From e8e896345ae1f9fd0d20d9198c43974211eabd15 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Thu, 12 Nov 2026 13:54:40 -0500 Subject: [PATCH 1/7] feat(accounts): read-only per-account probe and manual model discovery - POST /api/oauth/accounts/probe: probe stored google-antigravity accounts one by one with their own stored access token (one retrieveUserQuotaSummary request under the CLI fingerprint; no refresh, no store write). Verdicts: ok, token_expired, suspended, verification_required, rate_limited, permission_denied, error, plus HTTP status, reason and sanitized message. - POST /api/model-discovery/refresh: clear one provider's model cache, run catalog convergence, report newArrivals recorded by this call. - CLI: ocx account probe, ocx models discover (capabilities registered, skill surface regenerated). - GUI: Test / Test all on Antigravity account rows; Discover now panel with recently added models under provider settings. Design: devlog/_plan/261112_account_probe_and_model_discovery/010_design.md --- .../010_design.md | 84 ++++++++ .../provider-workspace/AccountProbe.tsx | 53 +++++ .../provider-workspace/ProviderAuthPanel.tsx | 19 ++ .../ProviderModelDiscovery.tsx | 120 +++++++++++ .../provider-workspace/ProviderSettings.tsx | 4 + gui/src/hooks/useAccountProbe.ts | 81 +++++++ gui/src/i18n/account-probe-copy.ts | 35 +++ gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + .../ocx/references/01_management_surface.md | 16 +- skills/ocx/references/01_surface_accounts.md | 21 +- .../references/01_surface_providers-models.md | 20 +- src/cli/account-probe.ts | 66 ++++++ src/cli/account.ts | 5 + src/cli/capabilities-accounts.ts | 7 + src/cli/capabilities-provider-models.ts | 6 + src/cli/models-runtime-subcommands.ts | 1 + src/cli/models-runtime.ts | 30 +++ .../quota/antigravity-account-probe.ts | 163 ++++++++++++++ src/providers/quota/antigravity.ts | 35 +++ src/server/management/model-routes.ts | 30 +++ src/server/management/oauth-account-routes.ts | 17 ++ src/server/management/route-registry.ts | 2 + tests/server/account-probe-routes.test.ts | 203 ++++++++++++++++++ 33 files changed, 1034 insertions(+), 6 deletions(-) create mode 100644 devlog/_plan/261112_account_probe_and_model_discovery/010_design.md create mode 100644 gui/src/components/provider-workspace/AccountProbe.tsx create mode 100644 gui/src/components/provider-workspace/ProviderModelDiscovery.tsx create mode 100644 gui/src/hooks/useAccountProbe.ts create mode 100644 gui/src/i18n/account-probe-copy.ts create mode 100644 src/cli/account-probe.ts create mode 100644 src/providers/quota/antigravity-account-probe.ts create mode 100644 tests/server/account-probe-routes.test.ts 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..54c6caf4e58 --- /dev/null +++ b/devlog/_plan/261112_account_probe_and_model_discovery/010_design.md @@ -0,0 +1,84 @@ +# 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 | +| `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 probed too (that is the point), but stay + paused. +- 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/gui/src/components/provider-workspace/AccountProbe.tsx b/gui/src/components/provider-workspace/AccountProbe.tsx new file mode 100644 index 00000000000..7ffd6c3efc1 --- /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") 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/ProviderAuthPanel.tsx b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx index af2a579915b..24d0221f7ce 100644 --- a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx +++ b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx @@ -25,6 +25,8 @@ 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 { GrokCouponBadge, GrokResetCouponModal } from "./GrokResetCoupons"; import { AnthropicGrantBadge, AnthropicResetGrantModal } from "./AnthropicResetGrants"; import type { CodexAccountPoolController } from "../../hooks/useCodexAccountPool"; @@ -273,6 +275,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; @@ -451,6 +456,15 @@ export default function ProviderAuthPanel({ )} + {probeEnabled && ( +
+ +
+ )}
{item.name === "xai" && ( @@ -659,6 +673,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..6a73edb3be1 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/hooks/useAccountProbe.ts b/gui/src/hooks/useAccountProbe.ts new file mode 100644 index 00000000000..d41dfbacb00 --- /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", "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..82a1e1f8e6b --- /dev/null +++ b/gui/src/i18n/account-probe-copy.ts @@ -0,0 +1,35 @@ +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.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"], +} 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 af7d1dbe835..f2c1c0bb8da 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 ae02af00650..3f78ab5d028 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 a2b29c53044..2a097422877 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 f8f974cf65e..49aa3e7fd08 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 f7a76a6939c..d57c8d2873a 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 4df91cae699..3f54da18be8 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 44933de62e6..f8252fc91f3 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 9708140d4ee..b240af6fecc 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 ff94de877a2..6d5f6e9d0d7 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 6b80a68d516..6852b52afaf 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 91da96c8fe8..386820e1533 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/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 8efe1768ac8..fcb59c0dff9 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) | 68 | | [integrations](01_surface_integrations.md) | 41 | | [observe-system](01_surface_observe-system.md) | 105 | @@ -483,6 +483,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) @@ -615,6 +619,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) @@ -1629,6 +1637,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 395 -- of those, state-changing: 247 +- declared capabilities: 397 +- of those, state-changing: 248 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_accounts.md b/skills/ocx/references/01_surface_accounts.md index e7f3f72e9b6..bf18813d03d 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, token_expired, suspended, verification_required, rate_limited, permission_denied, error. Sends one retrieveUserQuotaSummary request per account with its stored token; expired tokens are reported, never refreshed, and paused accounts stay paused. 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 {apiBase !== undefined && liveModelDiscoverySupported && ( - + )}
From 401a5a2399f2b08f2188bd930b8d5bdc77c09072 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Thu, 12 Nov 2026 22:55:46 -0500 Subject: [PATCH 4/7] docs(cli): document ocx account probe and ocx models discover --- .../docs/reference/cli/providers-accounts.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) 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. From 80c731ae4df59c7859409ef4074dcea802f7a4af Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 17:24:17 -0500 Subject: [PATCH 5/7] feat(gui): per-account quota table on the Providers accounts tab With ten Antigravity accounts the accounts tab was a long stack of cards; comparing which account still had Claude & GPT left, and when each resets, meant scrolling through all of them. The tab now opens with one table, one row per account: - plan from the upstream tier field (g1-pro-tier shows as Pro; a missing tier shows "Unknown plan", never a guess; the raw tier is in the tooltip); - Gemini, Claude & GPT and Argon pools (or the 5-hour/weekly subscription windows for Codex and Anthropic), each as remaining % with a reset countdown; - one status flag: healthy, paused, sign-in needed, rate limited, quota cooldown, probe failure, slow probe (>8s) or quota not read; - pause/resume and the read-only account probe, both existing APIs; - a one-line quota policy and a "next" marker on the scarce pool's account that resets soonest, matching reset-first. The cards below are unchanged. The table renders from data the panel already loads; it adds no endpoint. --- .../provider-workspace/AccountQuotaTable.tsx | 124 ++++++++++++ .../provider-workspace/ProviderAuthPanel.tsx | 39 ++++ .../account-quota-table.css | 102 ++++++++++ gui/src/i18n/account-probe-copy.ts | 27 +++ .../provider-workspace/account-quota-table.ts | 189 ++++++++++++++++++ scripts/test-layout/layout.json | 2 +- structure/gui-and-management-api.md | 2 +- tests/fixtures/test-layout-expected.json | 2 +- tests/gui/account-quota-table.test.ts | 94 +++++++++ 9 files changed, 578 insertions(+), 3 deletions(-) create mode 100644 gui/src/components/provider-workspace/AccountQuotaTable.tsx create mode 100644 gui/src/components/provider-workspace/account-quota-table.css create mode 100644 gui/src/provider-workspace/account-quota-table.ts create mode 100644 tests/gui/account-quota-table.test.ts 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 24d0221f7ce..1d69fddbf56 100644 --- a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx +++ b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx @@ -27,6 +27,8 @@ 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"; @@ -298,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} + /> + )} )} + {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 => { 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/i18n/account-probe-copy.ts b/gui/src/i18n/account-probe-copy.ts index 805fe9aadac..8c649ffc70f 100644 --- a/gui/src/i18n/account-probe-copy.ts +++ b/gui/src/i18n/account-probe-copy.ts @@ -26,6 +26,33 @@ const rows = { "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; 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/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index d8ba7c33f9c..862341f9662 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", "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", diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index d5dc67e0b9d..c013edbacd9 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -277,7 +277,7 @@ per-request first-party callback reads that live object; a failed write leaves i | Updates | `GET /api/update/check`, `POST /api/update/run`, and `GET /api/update/status` own dashboard self-update state. A launched worker PID is persisted in `update-job.json`; dead PIDs recover immediately when a new run starts, and `GET /api/update/status` already reports such a record as `failed` without writing it (`readUpdateJobForStatus`), while legacy active records without a PID recover only after ten minutes. Live PIDs remain exclusive regardless of record age. `GET /api/update/check` and `POST /api/update/run` await one per-channel asynchronous registry lookup and write successful results through to the package cache; run passes that result to the job starter. `GET /api/update/badge` only reads the cache and reports unknown after 40 hours, on missing cache, or on channel mismatch. The badge links to the update surface rather than gating other actions. `GET /api/update/badge?surface=desktop&session=` projects only that process-local Tauri session; missing or expired state is unknown and never falls back to the package cache. `POST /api/update/desktop-snapshot` is a 1 KiB bounded display-state mutation with no install permission. It accepts the existing admin-token principal or a dedicated single-use, ten-second snapshot capability bound to nonce, method, path, PID, port and the SHA-256 digest of the exact body bytes; that capability cannot authorize another route. | | Providers | Create/update/delete ordinary provider configs and enrich registry metadata. A `POST /api/providers` overwrite of an existing name keeps the operator compatibility settings listed in `PROVIDER_COMPAT_CARRY_FIELDS` (`src/server/management/provider-overwrite-carry.ts`), including both hosted-tool denial lists, and the stored key pool only while the destination (adapter, normalized base URL, auth mode when named) is unchanged. It keeps omitted `hideRawReasoning` on every overwrite of the same name, including destination moves, because it is a display policy; a submitted boolean wins. An omitted `inferContextWindow` likewise keeps the latest live same-name state after asynchronous validation, including `false` or a concurrent clear; a submitted boolean wins. The provider-level `modelDiscovery` block (`PROVIDER_DISCOVERY_CARRY_FIELDS`, #7910) follows the same destination rule. An omitted `cacheAffinity` keeps the latest live same-name mode, including `off`, so unrelated dashboard saves cannot re-enable affinity; a submitted mode wins. It never merges the rest of the old row. `PATCH` is a field mask and keeps every field it does not name; `hideRawReasoning`, `preserveResponsesReasoningContent`, `promoteAdditionalTools` and `inferContextWindow` accept a boolean or `null` to clear them, rejecting other types; `modelDiscovery` accepts `{ skipInvalidRows?: boolean }` or `null`/`{}` to clear it, and every write path rejects any other shape through `providerManagementConfigError`. `GET /api/providers` exposes configured `inferContextWindow` as an optional boolean without substituting a default; its [custom-only, default-off inference policy](catalog-vendor-context.md) is unchanged. Custom Responses provider forms expose `preserveResponsesReasoningContent` as a default-off plaintext replay switch; unrelated settings saves preserve omission and curated/OpenAI destinations keep their existing defaults. The reserved `openai` card exposes Pool(default)/Direct account mode; `openai-apikey` remains the separate API route. | | Models | Fetch routed model lists, disabled model visibility, and catalog-facing ids. New non-OAuth registration holds exposure until authoritative discovery; 20 or more distinct switch rows start OFF without disabling the provider. Pending rows cannot accept visibility changes. Ordinary model reads also apply the [new-arrival catalog contract](catalog.md#shared-catalog) before returning models. With a matching persisted configuration, discovery records the baseline, NEW badges, and automatic disables together; HTTP listing does not wait for a separate Codex sync. Inventory already drifted from disk uses a detached policy projection: arrivals remain disabled in management rows without changing live config or disk. | -| OAuth | Login/status/logout for OAuth-backed providers, plus multiauth account management: `GET /api/oauth/accounts`, `PUT /api/oauth/accounts/active`, `PUT /api/oauth/accounts/alias`, `PUT /api/oauth/accounts/pause`, and `DELETE /api/oauth/accounts` list masked accounts per provider, switch the active one, edit its display-only alias, pause/resume a generic OAuth account, and remove one. Paused generic OAuth accounts are excluded from request selection, 429 failover, and proactive token refresh; pausing an active account selects the next usable account when available, and resuming an account restores an active selection if the current one remains paused. With no unpaused account, requests return 403 rather than a login error. Kiro account-list rows include the current automatic-selection projection and closed exclusion reason; an active singleton may still send. The login flow itself is `GET /api/oauth/providers`, `POST /api/oauth/login`, `POST /api/oauth/login/code`, `POST /api/oauth/login/cancel`, `POST /api/oauth/logout`, and `GET /api/oauth/status`; pool controls are `GET/PUT/PATCH /api/oauth/accounts/pool` and `POST /api/oauth/accounts/clear-cooldown`. Login accepts `addAccount: true` to force a fresh browser identity. Meta Muse login start and manual-code continuation require the server-resolved `gui-session` principal before credential acquisition or code submission (including reauth); see the [provider contract](providers-and-adapters.md). Device flows return a structured `deviceCode`; the GUI highlights and copies it before the user opens the verification page. Google Antigravity account rows in `gui/src/components/provider-workspace/ProviderAuthPanel.tsx` display the account-summary `plan` as a badge and include it in the account button’s accessible name. The value is the canonical upstream tier ID (for example `free-tier` or `gemini-pro`), preserved literally across locales rather than inferred as a product name. Absent plans render no badge; pause and reauthentication controls keep their existing behavior. | +| OAuth | Login/status/logout for OAuth-backed providers, plus multiauth account management: `GET /api/oauth/accounts`, `PUT /api/oauth/accounts/active`, `PUT /api/oauth/accounts/alias`, `PUT /api/oauth/accounts/pause`, and `DELETE /api/oauth/accounts` list masked accounts per provider, switch the active one, edit its display-only alias, pause/resume a generic OAuth account, and remove one. Paused generic OAuth accounts are excluded from request selection, 429 failover, and proactive token refresh; pausing an active account selects the next usable account when available, and resuming an account restores an active selection if the current one remains paused. With no unpaused account, requests return 403 rather than a login error. Kiro account-list rows include the current automatic-selection projection and closed exclusion reason; an active singleton may still send. The login flow itself is `GET /api/oauth/providers`, `POST /api/oauth/login`, `POST /api/oauth/login/code`, `POST /api/oauth/login/cancel`, `POST /api/oauth/logout`, and `GET /api/oauth/status`; pool controls are `GET/PUT/PATCH /api/oauth/accounts/pool` and `POST /api/oauth/accounts/clear-cooldown`. Login accepts `addAccount: true` to force a fresh browser identity. Meta Muse login start and manual-code continuation require the server-resolved `gui-session` principal before credential acquisition or code submission (including reauth); see the [provider contract](providers-and-adapters.md). Device flows return a structured `deviceCode`; the GUI highlights and copies it before the user opens the verification page. Google Antigravity account rows in `gui/src/components/provider-workspace/ProviderAuthPanel.tsx` display the account-summary `plan` as a badge and include it in the account button’s accessible name. The value is the canonical upstream tier ID (for example `free-tier` or `gemini-pro`), preserved literally across locales rather than inferred as a product name. Absent plans render no badge; pause and reauthentication controls keep their existing behavior. With two or more accounts (OAuth pools and the Codex pool) the panel also renders `AccountQuotaTable`: one row per account with the plan (a known tier id mapped to its product name, the raw id otherwise, "unknown plan" when upstream sent none), each quota pool's 5-hour and weekly remaining with a reset countdown, one status flag, and the existing pause and probe actions. Pools come from the registry in `gui/src/provider-workspace/account-quota-table.ts`; the `next` marker on a scarce pool mirrors reset-first ordering and is display only. | | Key providers | `GET /api/key-providers` exposes API-key provider presets for setup and dashboard flows, and `GET/POST/DELETE /api/keys` owns the proxy's own admission keys. Machine links live in `src/server/management/link-routes.ts`: dashboard sessions reach `GET /api/link/candidates`, `POST /api/link/probe`, `POST /api/link/confirm-host` and `POST /api/link/apply`, meaning a paired session or, on a standalone runtime, the current loopback-issued session on trusted loopback ingress; `POST /api/link/join` instead requires an operator-paired session because it durably redirects local client traffic, and also refuses a runtime that is not standalone (`409 standalone_required`) or not listening on its configured port (`409 join_port_mismatch`) before any SSH, then restarts this runtime as a client; `GET /api/link/status` reports `joinAvailable` and typed `joinDenied` causes only to GUI-session callers, distinguishing pairing, runtime-role and port refusals without changing the admin/CLI DTO, so the dashboard enables the Child role only when the join gates pass; `GET /api/link/status`, the read-only `GET /api/link/diagnostics` (this runtime's bounded diagnostics file, re-sanitized on read), `POST /api/link/{id}/reconnect` and `DELETE /api/link/{id}` also accept the admin token on a trusted loopback ingress, and reconnect restarts a Home-initiated link's tunnel now; `POST /api/link/issue` accepts only that admin token. Tailscale-identity sessions are refused on every link route. See [Remote Link](remote-link.md). Multi-key pool per key-auth provider: `GET /api/providers/keys`, `POST /api/providers/keys`, `PUT /api/providers/keys/active`, `PUT /api/providers/keys/alias`, `DELETE /api/providers/keys` masked list, add (upsert + activate), switch, rename, and remove keys. `provider.apiKey` always mirrors the active pool entry so routing stays single-key. | | OpenAI account mode | Report one OpenAI Codex card with Pool/Direct controls and one API-key card. Mode PATCH persists live without restart or catalog identity changes; Pool owns account/quota controls and Direct uses caller/main login only. Main-account DTOs report real credential presence and terminal `needsReauth` state instead of treating missing/invalid native auth as an unknown quota. Selection order has its own route: `PUT /api/codex-auth/accounts/priority` takes `{ id, priority }`, where `priority` is an integer -100..100 or `null` to restore the default, accepts `__main__`, 404s an unknown id, and echoes the stored value. Re-ordering never clears thread affinity, so the response carries no `appliesImmediately`, but it does release any pin — see [`openai-tiers.md`](providers/openai-tiers.md) for why. `PUT /api/codex-auth/active` with a null id releases one too, but that drops the operator's account selection along with it, so this route is the only operator-facing way to clear a pin while leaving the selected account in place. `GET /api/codex-auth/active` reports `pinned`, true only while the manually selected account is still the effective active one, plus `pinnedAccountId`, which names the pinned account whether or not it is the active one. Surfaces should render `pinnedAccountId`: under round-robin and fill-first the pin caps the tier ceiling at its own tier while the strategy cursor moves freely inside that tier, so `pinned` goes false on a sibling's turn even though the pin is still suppressing every higher tier — which is why the dashboard badges `pinnedAccountId` and the GUI controller tracks only the id. `pinned` answers the narrower question of whether routing is *currently* on the operator's choice; no surface in this repo asks it, and a new one almost certainly wants the id instead. | | Subagents | Read/write the featured `subagentModels` list capped at five ids. `GET/PUT /api/injection-model` manages the shared delegation model/effort selection, the independent OpenCodex guidance switch, and the default-off `syncCodexSubagentDefaults` opt-in for native Codex subagent defaults. When OpenCodex owns the active Codex routing, native `[agents]` defaults apply to newly created Codex tasks after sync/restart; external user-managed provider configs remain untouched. The defaults do not cause delegation and preserve existing user-owned defaults rather than overwriting them. PUT is partial-update: absent keys are unchanged, `null` clears, and non-object bodies are rejected with 400 before field validation. `syncCodexSubagentDefaults: true` requires a nonblank `model` and a supported Codex reasoning effort when effort is set; clearing `model` (null/empty) always clears effort and disables native-default sync even when the stored effort was invalid. | diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 157c3018a9d..76c0442f9bb 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1235,7 +1235,7 @@ "provider-quota-abliteration.test.ts": "providers", "provider-quota-ollama-cloud.test.ts": "providers", "provider-quota.test.ts": "providers", "provider-registry-parity.test.ts": "providers", "free-directory-runcrate.test.ts": "providers", "haiku-5-5-catalog.test.ts": "providers", "provider-send-path-import.test.ts": "server", "provider-static-model-discovery.test.ts": "providers", "provider-subscription-cli.test.ts": "gui", "provider-workspace-auth.test.ts": "gui", - "provider-workspace-data.test.ts": "gui", "provider-workspace-rail.test.ts": "gui", + "provider-workspace-data.test.ts": "gui", "account-quota-table.test.ts": "gui", "provider-workspace-rail.test.ts": "gui", "provider-workspace-state.test.ts": "gui", "proxy-env-macos.test.ts": "server", "proxy-env.test.ts": "server", "proxy-liveness-package-tree-fence.test.ts": "server", "proxy-liveness-recovery.test.ts": "server", diff --git a/tests/gui/account-quota-table.test.ts b/tests/gui/account-quota-table.test.ts new file mode 100644 index 00000000000..147a2a76a69 --- /dev/null +++ b/tests/gui/account-quota-table.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test } from "bun:test"; +import { + buildQuotaTable, formatCountdown, planDisplayName, SLOW_PROBE_MS, type QuotaTableAccount, +} from "../../gui/src/provider-workspace/account-quota-table"; + +const NOW = Date.parse("2026-11-13T12:00:00Z"); +const HOUR = 3_600_000; + +function antigravity(id: string, overrides: Partial = {}, windows: Array<[string, number, number?]> = []): QuotaTableAccount { + return { + id, label: id, plan: "g1-pro-tier", active: false, paused: false, + quota: { customWindows: windows.map(([label, percent, resetHours]) => ({ label, percent, ...(resetHours !== undefined ? { resetAt: NOW + resetHours * HOUR } : {}) })) }, + ...overrides, + }; +} + +describe("account quota table", () => { + test("Antigravity windows land in Gemini, Claude & GPT and Argon pools as remaining percent", () => { + const table = buildQuotaTable([ + antigravity("a", {}, [["Gem", 10, 2], ["Gem (Weekly)", 40, 50], ["Cla", 75, 3], ["Cla (Weekly)", 20, 100], ["Argon", 5, 1]]), + antigravity("b", {}, [["Gem", 0, 4], ["Cla", 30, 1]]), + ], NOW); + expect(table.pools.map(pool => pool.key)).toEqual(["gemini", "claudeGpt", "argon"]); + const a = table.rows[0]!; + expect(a.cells.gemini).toEqual({ fiveHour: { remaining: 90, resetAt: NOW + 2 * HOUR }, weekly: { remaining: 60, resetAt: NOW + 50 * HOUR } }); + expect(a.cells.claudeGpt?.fiveHour?.remaining).toBe(25); + expect(table.rows[1]!.cells.argon).toBeUndefined(); + }); + + test("model-attributed rows never become a pool", () => { + const table = buildQuotaTable([antigravity("a", {}, [["gemini-3-pro · free", 50, 1]])], NOW); + expect(table.pools).toEqual([]); + }); + + test("Codex and Anthropic five-hour and weekly fields form the scarce subscription pool", () => { + const table = buildQuotaTable([{ + id: "c", label: "c", plan: "plus", active: true, paused: false, + quota: { fiveHourPercent: 64, fiveHourResetAt: (NOW + HOUR) / 1000, weeklyPercent: 12, weeklyResetAt: NOW + 72 * HOUR }, + }], NOW); + expect(table.pools.map(pool => [pool.key, pool.scarce])).toEqual([["subscription", true]]); + expect(table.rows[0]!.cells.subscription).toEqual({ + fiveHour: { remaining: 36, resetAt: NOW + HOUR }, + weekly: { remaining: 88, resetAt: NOW + 72 * HOUR }, + }); + }); + + test("the scarce pool's next account resets soonest among usable accounts with headroom; Gemini gets no marker", () => { + const table = buildQuotaTable([ + antigravity("late", {}, [["Gem", 0, 1], ["Cla (Weekly)", 10, 90]]), + antigravity("soon", {}, [["Gem", 0, 1], ["Cla (Weekly)", 10, 20]]), + antigravity("empty", {}, [["Cla (Weekly)", 100, 5]]), + antigravity("paused", { paused: true }, [["Cla (Weekly)", 0, 2]]), + antigravity("limited", { health: { status: "cooldown", reason: "rate_limit" } }, [["Cla (Weekly)", 0, 3]]), + ], NOW); + expect(table.rows.filter(row => row.next.length > 0).map(row => [row.account.id, row.next])).toEqual([["soon", ["claudeGpt"]]]); + }); + + test("flags: paused, sign-in, cooldown, failed probe, slow probe, unread quota, healthy", () => { + const flags = buildQuotaTable([ + antigravity("p", { paused: true, needsReauth: true }), + antigravity("r", { needsReauth: true }), + antigravity("q", { health: { status: "cooldown", reason: "quota" } }), + antigravity("x", { probe: { status: "rate_limited", latencyMs: 300 } }), + antigravity("s", { probe: { status: "ok", latencyMs: SLOW_PROBE_MS + 1 } }), + antigravity("u", { quotaUnavailable: true }), + antigravity("h", { probe: { status: "ok", latencyMs: 900 } }), + ], NOW).rows.map(row => [row.account.id, row.flag, row.probeStatus]); + expect(flags).toEqual([ + ["p", "paused", undefined], ["r", "reauth", undefined], ["q", "quotaLimited", undefined], + ["x", "probeFailed", "rate_limited"], ["s", "slow", undefined], ["u", "stale", undefined], ["h", "ok", undefined], + ]); + }); + + test("plan names come from the upstream tier field; missing tier stays unknown", () => { + expect(planDisplayName("g1-pro-tier")).toBe("Pro"); + expect(planDisplayName("free-tier")).toBe("Free"); + expect(planDisplayName("g1-ultra-tier")).toBe("g1-ultra-tier"); + expect(planDisplayName("max_5x", "Max 5x")).toBe("Max 5x"); + expect(planDisplayName(null)).toBeNull(); + expect(planDisplayName(" ")).toBeNull(); + }); + + test("a reset already in the past shows no countdown", () => { + const table = buildQuotaTable([antigravity("a", {}, [["Cla", 10, -1]])], NOW); + expect(table.rows[0]!.cells.claudeGpt?.fiveHour).toEqual({ remaining: 90 }); + }); + + test("countdown text", () => { + expect(formatCountdown(NOW + 30_000, NOW)).toBe("<1m"); + expect(formatCountdown(NOW + 45 * 60_000, NOW)).toBe("45m"); + expect(formatCountdown(NOW + 3 * HOUR + 12 * 60_000, NOW)).toBe("3h 12m"); + expect(formatCountdown(NOW + 53 * HOUR, NOW)).toBe("2d 5h"); + }); +}); From d973f3c11e57272fa5eef18621ec85499abb54b2 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 17:33:42 -0500 Subject: [PATCH 6/7] test(layout): name the quota table test gui-account-quota-table so the gui seed places it The account- seed resolves to server, so the explicit gui entry tripped the membership oracle's seed check. A gui- name agrees with both. --- scripts/test-layout/layout.json | 2 +- tests/fixtures/test-layout-expected.json | 2 +- ...ount-quota-table.test.ts => gui-account-quota-table.test.ts} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename tests/gui/{account-quota-table.test.ts => gui-account-quota-table.test.ts} (100%) diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 862341f9662..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", "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", + "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", diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 76c0442f9bb..485da4fbdb8 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1235,7 +1235,7 @@ "provider-quota-abliteration.test.ts": "providers", "provider-quota-ollama-cloud.test.ts": "providers", "provider-quota.test.ts": "providers", "provider-registry-parity.test.ts": "providers", "free-directory-runcrate.test.ts": "providers", "haiku-5-5-catalog.test.ts": "providers", "provider-send-path-import.test.ts": "server", "provider-static-model-discovery.test.ts": "providers", "provider-subscription-cli.test.ts": "gui", "provider-workspace-auth.test.ts": "gui", - "provider-workspace-data.test.ts": "gui", "account-quota-table.test.ts": "gui", "provider-workspace-rail.test.ts": "gui", + "provider-workspace-data.test.ts": "gui", "gui-account-quota-table.test.ts": "gui", "provider-workspace-rail.test.ts": "gui", "provider-workspace-state.test.ts": "gui", "proxy-env-macos.test.ts": "server", "proxy-env.test.ts": "server", "proxy-liveness-package-tree-fence.test.ts": "server", "proxy-liveness-recovery.test.ts": "server", diff --git a/tests/gui/account-quota-table.test.ts b/tests/gui/gui-account-quota-table.test.ts similarity index 100% rename from tests/gui/account-quota-table.test.ts rename to tests/gui/gui-account-quota-table.test.ts From 0dbf408c7365129ab32d3b81b5d8bf82de2ed093 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:48:58 -0500 Subject: [PATCH 7/7] test(gui): register the quota table's French words that match English --- gui/tests/fr-localization.test.ts | 4 ++++ 1 file changed, 4 insertions(+) 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.