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..cabf4e2c54d --- /dev/null +++ b/devlog/_plan/261112_account_probe_and_model_discovery/010_design.md @@ -0,0 +1,86 @@ +# Per-account probe and manual model discovery + +Status: contributor design for PR #8740. + +## Problem + +1. `POST /api/providers/test` resolves only the active account's token, so an operator with a + pool of Google Antigravity accounts cannot tell which individual accounts still work. Accounts + that started returning `permission_denied` could only be checked with an out-of-tree script. +2. Model discovery runs implicitly (catalog convergence, `liveModels`). There is no per-provider + "discover now" action, and recent arrivals only show as small NEW badges on the Models page. + +## 1. Per-account probe + +`POST /api/oauth/accounts/probe` — body `{ "provider": "google-antigravity", "accountId"?: string }`. +Omitting `accountId` probes every stored account (concurrency 4). Response: + +```json +{ "provider": "google-antigravity", "probedAt": "", + "results": [{ "accountId": "…", "maskedLabel": "a***b@example.com", "active": true, "paused": false, + "status": "ok", "httpStatus": 200, "reason": null, "message": null, + "expiresAt": 0, "latencyMs": 412, "quota": { "customWindows": [] } }] } +``` + +`status` is one of: + +| status | meaning | rule | +| --- | --- | --- | +| `ok` | usable | HTTP 200 | +| `paused` | account is paused by the operator; not tested | `account.paused === true`; no request is sent | +| `token_expired` | stored access token expired, not refreshed | `credential.expires <= now`; no request is sent | +| `suspended` | upstream says the account is suspended/disabled | 403 whose reason/message names suspension, disablement or ToS | +| `verification_required` | upstream asks the user to verify the account | 403 with `details[].reason == VALIDATION_REQUIRED` or "verify your account" wording | +| `rate_limited` | throttled / quota exhausted | 429 or `RESOURCE_EXHAUSTED` | +| `permission_denied` | other 403 | 403 | +| `error` | anything else (401, 5xx, transport, missing project) | `httpStatus` and `reason` carry the detail | + +Read-only by construction: + +- Uses the account's stored access token exactly as read through `getAccountSet()`; never calls + `getValidAccessToken`, never refreshes, never writes the auth store, never changes pause, + active, cooldown or health state. Paused accounts are skipped with status `paused` and no + request: an operator who parked an account has said not to use it, and a probe is still a use. + To test one, resume it first. +- One request: `POST https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary` + with `{ "project": }` and `User-Agent: antigravityCliUserAgent()`. Unlike the quota + poller there is no 403 retry under the IDE UA and no `fetchAvailableModels` fallback: the + first answer is the evidence, and the CLI fingerprint is the one that reports the Gemini group. +- Goes through the pinned provider-outbound transport used by the quota poller. +- The response uses closed reason codes and recognized quota-window labels. + The management API serializes probe runs and allows up to four requests per batch. + +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, `expireModelCache(provider)`, then run the normal + catalog convergence (`convergeCodexCatalog`), which re-fetches the provider and records new + arrivals through the existing new-model policy. +3. Respond with `{ ok, provider, discovery, liveModelCount, newArrivals, recentArrivals, catalogRefresh }`, + where `newArrivals` are the arrivals recorded by this call and `discovery` is the provider's + discovery status (`ok` / `failed` + reason / http status). + +CLI: `ocx models discover [--json]`. + +GUI: provider settings, directly under the "Discover models from provider" toggle: a +**Discover now** button and a "Recently added" list (newest first, with date and whether the model +was auto-disabled by the new-model policy). + +## Not changed + +- `POST /api/providers/test` and the active-account path. +- Token refresh, re-login, pause/resume semantics. diff --git a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md index d004a53b886..3677b8ad5a1 100644 --- a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md @@ -548,6 +548,31 @@ Para el grupo Codex, use `ocx account refresh openai [--json]`. Se actualiza a l Para proveedores OAuth y de clave API, esto fuerza la actualización del punto final de informes de cuota del proveedor; no es un nuevo inicio de sesión de token ni una simple relectura de la lista de cuentas. `--json` devuelve `{ provider, report: ProviderQuotaReport | null }`. Un proveedor sin un informe de cuota compatible imprime `no quota report available for ` y sale con 0. Los proveedores desconocidos y los fallos de la API de gestión salen con 1; una sonda de cuota ascendente que falla o expira se degrada a un informe nulo o desactualizado (código de salida 0), lo que coincide con las barras de cuota del panel. +### `ocx account probe google-antigravity [id|alias] [--json]` + +Comprueba cada cuenta de Google Antigravity en modo de solo lectura. Cada cuenta recibe una +solicitud `retrieveUserQuotaSummary` con su propio token de acceso y la identidad de la CLI. +El resultado es `ok`, `rate_limited`, `verification_required`, `suspended`, `permission_denied` +o `error`, con el estado HTTP y un código de motivo reconocido. Los estados `paused` +(cuenta en pausa) y `token_expired` (token caducado) se determinan localmente, sin enviar +una solicitud. La comprobación conserva los tokens y el estado de la cuenta. Los botones +**Probar** y **Probar todas** de la tabla de cuotas de Antigravity llaman al mismo endpoint, +`POST /api/oauth/accounts/probe`. La tabla muestra el plan, las cuotas restantes por grupo, +los plazos de restablecimiento y las acciones de cada cuenta. Si falla una actualización, +la tabla conserva la cuota anterior e indica el error y las horas de lectura. Se ejecutan hasta cuatro +comprobaciones a la vez. Espera a que termine la comprobación actual antes de iniciar otra. + +### `ocx models discover [--json]` + +Ejecuta ahora la detección de modelos del proveedor e indica cuántos modelos encontró y +cuáles son nuevos. Es la misma acción que **Detectar ahora** en los ajustes del proveedor +(`POST /api/model-discovery/refresh`). Si ya hay una detección en curso para ese proveedor, la +acción devuelve HTTP 409 (`discovery_in_progress`) sin consultar al proveedor. Durante los 30 +segundos posteriores a un fallo, la acción muestra ese +fallo y conserva la última lista válida sin volver a consultar al proveedor. La sincronización del +catálogo de Codex puede incorporar después la lista actualizada. Los catálogos estáticos indican +que la detección en directo está desactivada. + ### `ocx account auto-switch > [--json]` Controla el umbral del grupo Codex `openai`, o almacena un umbral para un grupo OAuth genérico. `on` almacena el 80%, `off` almacena el 0% y `threshold ` acepta 0–100. Un umbral de grupo genérico dirige la selección solo mientras `pool.kernel` está activado con `strategy: "fill-first"`; con el indicador desactivado, guardar uno no habilita la conmutación basada en umbral. Nunca cambia la anulación de habilitación del proveedor ni desactiva la rotación reactiva 429. `status` y la salida de las mutaciones de grupos genéricos usan la respuesta confirmada del servidor. Para grupos genéricos, `poolEnabled` es la anulación almacenada del proveedor (`null` significa no especificado), no el estado efectivo heredado; `inert: true` significa que el umbral se almacena pero no se aplica, `inert: false` significa que el grupo lo está aplicando, y un `inert` ausente es una capacidad desconocida, que nunca informa `enabled: true`. Se rechazan los proveedores de clave API y los valores no válidos. diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index 936b2fc2d82..29d235684c2 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -455,6 +455,8 @@ Sin `format=desktop-config`, los contratos de catálogo ordinarios son: La combinación de este formato con `ids=cli` o cualquier `client_version` devuelve HTTP 400. Sin el selector de formato, los contratos ordinarios anteriores permanecen sin cambios. Cuando Claude está deshabilitado, la instantánea es `{ "version": 1, "models": [] }`; Connected Desktop apply trata esto como no disponible y no escribe un perfil de reemplazo. Los antiguos hubs que devuelven un catálogo ordinario en lugar de la versión 1 no son compatibles; el cliente no recurre a los ID generados localmente. +Si una operación de descubrimiento más reciente sustituye a la actual, el concentrador devuelve HTTP 503 con el código de error `desktop_snapshot_busy` y la cabecera `Retry-After: 1`. Al aplicar la configuración desde un cliente conectado, se conserva intacto el perfil de Claude Desktop existente. + La instantánea sigue siendo un contrato de lista de modelos de solo lectura; no es una rotación de claves ni una carga de perfil API. La migración, recuperación y desconexión de claves de escritorio conectadas funcionan a través del ciclo de vida del cliente existente. La rotación conserva las entradas y selecciones del modelo; CLI `rotation` distingue `committed` de `rolled_back`. Desconectar restaura la configuración propia o informa de una reserva estándar heredada conocida, preservando los campos de usuario y selecciones válidas posteriores. Los conflictos o la recuperación incompleta impiden una reclamación de finalización. Reinicie el escritorio para cargar los cambios de disco; la desconexión no revoca automáticamente la clave de concentrador. Véase [Claude Desktop ciclo de vida](/es/guides/claude-code/). La repetición de pensamiento y el trabajo de caché rápida permanecen separados en [#3719](https://github.com/lidge-jun/opencodex/issues/3719). diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index 87e3ca11777..53195e15417 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -100,6 +100,11 @@ Routing and catalog visibility are separate controls: Enabling an arrival manually keeps it enabled on later refreshes and exports. If the running provider configuration differs from disk, model lists still apply the policy using a temporary projection; they leave the running configuration and saved choices untouched. + If a newer discovery supersedes a successful response, the dashboard and ordinary model + listings can still show the older request's models under the visibility policy for that response. + When discovery is superseded or uses a temporary projection, the hub's Desktop configuration + endpoint returns a retryable HTTP 503 and connected apply keeps the current profile in place. + Anthropic listings using Desktop IDs show the visible aliases that already route to the same models. Use `ocx models new-policy off` globally, add `--provider ` for an override, and inspect `ocx models new-arrivals [--json]`. Failed/degraded fetches never change the baseline. Providers with a non-empty `selectedModels` (including preset mode) are already curated, so `on` and `off` 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 d6f2dce16e7..643f5cef352 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -1063,6 +1063,30 @@ 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 a recognized reason code). 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 the Antigravity account quota table call the same endpoint, `POST /api/oauth/accounts/probe`. +The table shows each account’s plan, remaining quota by pool, reset times, and account actions. +If a quota refresh fails, the table keeps the cached quota and shows the failure and read times. +A batch runs up to four checks at a time. Wait for the current check to finish before starting another. + +### `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`). If discovery is already running +for that provider, the action reports it is in progress (HTTP 409, `discovery_in_progress`) without +contacting the provider. For 30 seconds after a failed fetch, the action reports that failure +and keeps the last good list without contacting the provider again. The separate Codex catalog +sync can pick up the refreshed list. Providers without live discovery report that discovery is off. + ### `ocx account auto-switch > [--json]` Controls the `openai` Codex pool threshold, or stores a threshold for a generic OAuth pool. `on` stores 80%, `off` stores 0%, and `threshold ` accepts 0–100. A generic pool threshold steers selection only while `pool.kernel` is on with `strategy: "fill-first"`; with the flag off, saving one does not enable threshold-based switching. It never changes the provider enablement override or disables reactive 429 rotation. `status` and mutation output for generic pools use the confirmed server response. For generic pools, `poolEnabled` is the stored provider override (`null` means unspecified), not inherited effective state; `inert: true` means the threshold is stored but not applied, `inert: false` means the pool is applying it, and an absent `inert` is an unknown capability, which never reports `enabled: true`. API-key providers and invalid values are rejected. diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index d29396c268f..37253778e3d 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -815,6 +815,10 @@ the snapshot is `{ "version": 1, "models": [] }`; connected Desktop apply treats unavailable and does not write a replacement profile. Old hubs returning an ordinary catalog instead of version 1 are unsupported; the client does not fall back to locally generated IDs. +If a newer discovery supersedes the request, the hub returns HTTP 503 with the error code +`desktop_snapshot_busy` and `Retry-After: 1`. Connected apply leaves the existing Desktop +profile byte-for-byte intact. + The snapshot remains a read-only model-list contract; it is not a key-rotation or profile-upload API. Connected Desktop key migration, recovery and disconnect operate through the existing client lifecycle. Rotation preserves model entries and selections; CLI `rotation` distinguishes diff --git a/gui/src/components/provider-workspace/AccountProbe.tsx b/gui/src/components/provider-workspace/AccountProbe.tsx new file mode 100644 index 00000000000..a107cbbf719 --- /dev/null +++ b/gui/src/components/provider-workspace/AccountProbe.tsx @@ -0,0 +1,50 @@ +import { useT } from "../../i18n/shared"; +import type { AccountProbeController, AccountProbeEntry, AccountProbeStatus } from "../../hooks/useAccountProbe"; + +function statusBadgeClass(status: AccountProbeStatus): string { + if (status === "ok") return "badge badge-green"; + if (status === "token_expired" || status === "paused") return "badge badge-muted"; + return "badge badge-amber"; +} + +export function AccountProbeButton({ controller, accountId, label, disabled }: { + controller: AccountProbeController; accountId: string; label: string; disabled?: boolean; +}) { + const t = useT(); + const pending = controller.isPending(accountId); + return ( + + ); +} + +/** One line under the account row: verdict badge, then HTTP code, reason and upstream message. */ +export function AccountProbeResultLine({ entry }: { entry: AccountProbeEntry | undefined }) { + const t = useT(); + if (!entry) return null; + const time = new Date(entry.at).toLocaleTimeString(); + if ("failed" in entry) { + return
{`${t("acctProbe.failed")} · ${time}`}
; + } + const { result } = entry; + // A usable account needs no evidence; its quota is already in the bars below and the table. + const evidence = result.status === "ok" ? "" : [ + result.httpStatus !== null ? `HTTP ${result.httpStatus}` : null, + result.reason, + result.message, + ].filter((part): part is string => Boolean(part)).join(" · "); + return ( +
+ {t(`acctProbe.status.${result.status}`)} + {evidence && {evidence}} + {time} +
+ ); +} diff --git a/gui/src/components/provider-workspace/AccountQuotaTable.tsx b/gui/src/components/provider-workspace/AccountQuotaTable.tsx new file mode 100644 index 00000000000..45e60915e89 --- /dev/null +++ b/gui/src/components/provider-workspace/AccountQuotaTable.tsx @@ -0,0 +1,154 @@ +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 = { + banned: "danger", verify: "warn", 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} +
+ {t("acctTable.left", { percent: remaining })} + {countdown ? t("acctTable.resetsIn", { time: countdown }) : ""} +
+ ); +} + +/** One line in place of the quota cells: the account is refused upstream, so its numbers are moot. */ +function BannedNotice({ banned }: { banned: NonNullable }) { + const t = useT(); + const when = typeof banned.pausedAt === "number" && Number.isFinite(banned.pausedAt) ? new Date(banned.pausedAt).toLocaleString() : null; + return ( +
+ + {t("acctTable.bannedRow")} + {t("acctTable.bannedReason")} + +

{banned.message?.trim() || t("accountPause.reason.permissionDenied")}

+ {(when || banned.statusCode) && ( +

{[when, banned.statusCode ? `HTTP ${banned.statusCode}` : null].filter(Boolean).join(" · ")}

+ )} +
+ ); +} + +export interface AccountQuotaTableProps { + accounts: readonly QuotaTableAccount[]; + /** The pool's effective strategy; the `next` marker shows only under reset-first. */ + strategy?: string; + /** Supplies the account control, actions column, and full-width detail content for each row. */ + renderRowContent?: (row: QuotaTableRow) => { account: ReactNode; actions: ReactNode; details: ReactNode }; +} + +function hasContent(node: ReactNode): boolean { + if (node === null || node === undefined || node === false || node === "") return false; + return !Array.isArray(node) || node.some(hasContent); +} + +/** + * The one account list of a multi-account provider: plan, each quota pool's 5-hour and weekly + * remaining with a reset countdown, a status flag and, when the caller passes them, the row's + * controls and a detail line. Below a container width the rows stack instead of scrolling, so + * the controls never leave the screen. + */ +export function AccountQuotaTable({ accounts, strategy, renderRowContent }: AccountQuotaTableProps) { + const t = useT(); + const now = useMinuteClock(); + const table = buildQuotaTable(accounts, now, strategy); + if (table.rows.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); + const columns = 3 + table.pools.length + (renderRowContent ? 1 : 0); + return ( +
+
+ + + + + + {table.pools.map(pool => ( + + ))} + + {renderRowContent && } + + + {table.rows.map(row => { + const content = renderRowContent?.(row); + // No pool column to carry the notice (a refused account rarely has a quota reading), + // so it goes on the detail line instead of being lost behind the status flag. + const bannedLine = table.pools.length === 0 && row.account.banned ? : null; + const withDetails = bannedLine !== null || hasContent(content?.details); + return ( + + + + + {table.pools.length > 0 && (row.account.banned + ? + : Object.keys(row.cells).length === 0 + ? + : table.pools.map(pool => { + const cell = row.cells[pool.key]; + return ( + + ); + }))} + + {content && } + + {withDetails && ( + + + + )} + + ); + })} +
{t("acctTable.account")}{t("acctTable.plan")} + {poolLabel(pool.key)} + {pool.scarce && {t("acctTable.scarce")}} + {t("acctTable.status")}{t("acctTable.actions")}
+ {content ? content.account : <> + + {row.plan + ? {row.plan} + : {t("acctTable.unknownPlan")}} + {t("acctTable.noReading")} + {cell ? <> + {cell.fiveHour && } + {cell.weekly && } + {row.next.includes(pool.key) && {t("acctTable.next")}} + : —} + {flagText(row)}
{content.actions}
{bannedLine}{content?.details}
+
+
+ ); +} diff --git a/gui/src/components/provider-workspace/ProviderAccountQuota.tsx b/gui/src/components/provider-workspace/ProviderAccountQuota.tsx index 4b7504fd5b1..ed0af084995 100644 --- a/gui/src/components/provider-workspace/ProviderAccountQuota.tsx +++ b/gui/src/components/provider-workspace/ProviderAccountQuota.tsx @@ -6,9 +6,12 @@ import { ProviderCapacityQuota } from "./ProviderCapacityQuota"; import type { AccountQuotaReading } from "./types"; /** The same reading states and credit/window renderer for current and all-account views. */ -export default function ProviderAccountQuota({ quota: rawQuota, quotaMode, quotaUnavailable, quotaPending, quotaFailure, quotaReadAt }: AccountQuotaReading) { +export default function ProviderAccountQuota({ + quota: rawQuota, quotaMode, quotaUnavailable, quotaPending, quotaFailure, quotaReadAt, uncoveredQuota, +}: AccountQuotaReading & { uncoveredQuota?: AccountQuotaReading["quota"] }) { const t = useT(); const quota = accountQuotaFromReport({ quota: rawQuota }); + const displayedQuota = uncoveredQuota === undefined ? quota : uncoveredQuota; if (quotaMode === "unsupported") { return

{t("pws.quotaUnsupported")}

; } @@ -17,12 +20,12 @@ export default function ProviderAccountQuota({ quota: rawQuota, quotaMode, quota const state = quotaUnavailable ? "unavailable" : pending ? "pending" : quota ? "ready" : quotaMode === "passive" ? "unobserved" : "unknown"; return
{quotaUnavailable &&

{t(failure ? `pws.quotaFailure.${failure}` : "pws.accountQuotaUnavailable")}

} - {quota || pending ? ( + {displayedQuota || (pending && !quota) ? ( - ) : !quotaUnavailable && ( + ) : !quota && !quotaUnavailable && (

{t(quotaMode === "passive" ? "pws.quotaUnobserved" : "pws.quotaUnavailable")}

)} {quotaUnavailable && quota &&

diff --git a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx index 43d056afccc..418b7b0d117 100644 --- a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx +++ b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx @@ -14,12 +14,9 @@ import type { WorkspaceItem } from "../../provider-workspace/catalog"; import { oauthAccountDisplayLabel, providerAuthSurface } from "../../provider-workspace/auth"; import { oauthCredentialSlot } from "../../../../src/oauth/credential-siblings"; import { oauthLabel } from "../../pages/providers-shared"; -import { displayAccountId } from "../../lib/privacy"; import AccountAutoSwitchControl from "../AccountAutoSwitchControl"; import { - formatOAuthHealthLabel, formatOAuthHealthSummary, - oauthHealthBadgeClass, oauthHealthIsCooldown, oauthHealthShowsReauth, } from "../../oauth-health-display"; @@ -29,6 +26,11 @@ import ClaudeNativePassthroughSetting from "./ClaudeNativePassthroughSetting"; import { LoginHint as LoginHintView } from "../login-url-block"; import { OpenBrowserPrefToggle } from "../open-browser-pref-toggle"; import ProviderAccountQuota from "./ProviderAccountQuota"; +import { AccountProbeButton, AccountProbeResultLine } from "./AccountProbe"; +import { ACCOUNT_PROBE_PROVIDERS, useAccountProbe } from "../../hooks/useAccountProbe"; +import { AccountQuotaTable } from "./AccountQuotaTable"; +import { accountQuotaFromReport } from "../../provider-workspace/report"; +import { uncoveredWindows } from "../../provider-workspace/account-quota-table"; import { GrokCouponBadge, GrokResetCouponModal } from "./GrokResetCoupons"; import { AnthropicGrantBadge, AnthropicResetGrantModal } from "./AnthropicResetGrants"; import type { CodexAccountPoolController } from "../../hooks/useCodexAccountPool"; @@ -285,6 +287,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; @@ -305,6 +310,20 @@ 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, + }, + }))} + /> + )}

{isOauth ? t("pws.availableAccounts") : t("pws.apiKeys")}

- {((isOauth && loggedIn) || isKeyAuth) && canRefreshQuota && ( + {((((isOauth && loggedIn) || isKeyAuth) && canRefreshQuota) || probeEnabled) && (
+ {((isOauth && loggedIn) || isKeyAuth) && canRefreshQuota && <> {quotaRefreshResult && ( {quotaRefreshResult.text} @@ -467,6 +487,14 @@ export default function ProviderAuthPanel({ {" "} {refreshingQuota ? t("codexAuth.refreshingQuota") : t("codexAuth.refreshQuota")} + } + {probeEnabled && ( + + )}
)}
@@ -630,124 +658,134 @@ export default function ProviderAuthPanel({ {t("pws.sharedAccountsNote", { provider: oauthLabel(oauthCredentialSlot(item.name)) })}
)} - {accounts.length > 0 && ( -
    - {accounts.map(account => { - const label = oauthAccountDisplayLabel(accounts, account, t); - const planLabel = isAnthropicPool ? anthropicSubscriptionLabel(account.plan) : item.name === "google-antigravity" ? account.plan : undefined; - // One Claude account can hold a row per organization; the name tells those rows apart. + {accounts.length > 0 && (() => { + const byId = new Map(accounts.map(account => [account.id, account])); + const controlsLocked = Boolean(switchingAccountId) || Boolean(pausingAccountId); + return ( + { + 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), + verifyRequired: account.needsReauthReason === "verify_account", + ...(account.paused && account.pauseDetails?.reason === "account_permission_denied" ? { banned: { + message: account.pauseEvidence?.message, + pausedAt: account.pauseDetails.pausedAt, + statusCode: account.pauseEvidence?.statusCode, + } } : {}), + health: account.health, quota: accountQuotaFromReport({ quota: account.quota }), quotaUnavailable: account.quotaUnavailable, + ...(probe && "result" in probe ? { probe: { status: probe.result.status, latencyMs: probe.result.latencyMs } } : {}), + }; + })} + renderRowContent={row => { + const account = byId.get(row.account.id)!; const organizationName = isAnthropicPool ? account.organizationName : undefined; - const switching = switchingAccountId === account.id; - const pausing = pausingAccountId === account.id; - const healthStatus = account.health?.status; const showReauth = accountShowsReauth(account); - const inCooldown = oauthHealthIsCooldown(healthStatus); - const maskedId = displayAccountId(account.id); - const healthLabel = formatOAuthHealthLabel(t, account.health); - const healthSummary = isAnthropicPool ? null : formatOAuthHealthSummary(t, item.name, account.id, account.health); - const appealUrl = account.paused ? normalizeCloudCodeAppealUrl(account.pauseEvidence?.appealUrl) : undefined; - return ( -
  • -
    - - {typeof account.paused === "boolean" && authHandlers.onPauseAccount && ( - + ); + const actions = <> + {claudeGrantsEnabled && !showReauth && ( + setGrantAccount(account)} /> + )} + {grokCouponsEnabled && !showReauth && ( + setCouponAccount(account)} /> )} {showReauth && ( - )} - {grokCouponsEnabled && !showReauth && ( - setCouponAccount(account)} - /> + {typeof account.paused === "boolean" && authHandlers.onPauseAccount && ( + )} - {claudeGrantsEnabled && !showReauth && ( - setGrantAccount(account)} /> + {probeEnabled && ( + )} -
    -
    - {appealUrl && ( - - {normalizeCloudCodeAppealText(account.pauseEvidence?.appealText) ?? t("accountPause.submitAppeal")} - - )} - {isAnthropicPool && account.autoSwitchThresholdOverride !== undefined - && account.autoSwitchThreshold !== undefined && authHandlers.onAccountThreshold && ( - authHandlers.onAccountThreshold!(item.name, account, threshold)} - /> - )} - ; + const healthSummary = isAnthropicPool ? null : formatOAuthHealthSummary(t, item.name, account.id, account.health); + const covered = Object.keys(row.cells).length > 0; + // Windows the pool columns already show are not repeated; anything else (per-model + // rows, monthly, credits) still renders here so the list drops no reading. + const rest = covered && row.account.quota ? accountQuotaFromReport({ quota: { + ...row.account.quota, + customWindows: uncoveredWindows(row.account.quota.customWindows), + ...(row.cells.subscription ? { fiveHourPercent: undefined, fiveHourResetAt: undefined, weeklyPercent: undefined, weeklyResetAt: undefined } : {}), + } }) : null; + const appealUrl = account.paused ? normalizeCloudCodeAppealUrl(account.pauseEvidence?.appealUrl) : undefined; + const probeEntry = probeEnabled ? accountProbe.entries[account.id] : undefined; + const threshold = isAnthropicPool && account.autoSwitchThresholdOverride !== undefined + && account.autoSwitchThreshold !== undefined && authHandlers.onAccountThreshold; + const parts = [ + healthSummary &&

    {healthSummary}

    , + inCooldown &&

    {t("pws.healthCooldownHint")}

    , + account.paused && row.flag !== "banned" &&

    {t("pws.accountPausedHint")}

    , + appealUrl && ( + + {normalizeCloudCodeAppealText(account.pauseEvidence?.appealText) ?? t("accountPause.submitAppeal")} + + ), + probeEntry && , + threshold && ( + authHandlers.onAccountThreshold!(item.name, account, value)} + /> + ), + (!covered || rest || account.quotaUnavailable) && ( + -
    -
  • - ); - })} -
- )} + quotaReadAt={account.quotaReadAt} uncoveredQuota={covered ? rest : undefined} /> + ), + ].filter(Boolean); + return { account: accountCell, actions, details: parts }; + }} + /> + ); + })()} {couponAccount && ( +
+
+ {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 4fcdc8b2005..8a5bf563a1e 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 { @@ -685,6 +686,9 @@ function ProviderSettingsForm({ {t("pws.liveModelsDesc")} + {apiBase !== undefined && liveModelDiscoverySupported && item.liveModels !== false && ( + + )}

{t("pws.pacingTitle")}

{t("pws.pacingDesc")}

diff --git a/gui/src/components/provider-workspace/account-quota-table.css b/gui/src/components/provider-workspace/account-quota-table.css new file mode 100644 index 00000000000..c4c6a4da035 --- /dev/null +++ b/gui/src/components/provider-workspace/account-quota-table.css @@ -0,0 +1,285 @@ +/* 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); + container-type: inline-size; +} +.aqt-scroll { + overflow-x: auto; + border: 1px solid var(--border); + border-radius: var(--radius-sm); +} +.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; +} +.aqt-table thead th, +.aqt-group:not(:last-child) > tr:last-child > * { + border-bottom: 1px solid var(--border); +} +.aqt-table thead th { + font-weight: 500; + color: var(--muted); + white-space: nowrap; +} +.aqt-group--active { + background: color-mix(in oklab, var(--green) 6%, transparent); +} +.aqt-account { + font-weight: 500; + white-space: nowrap; +} +.aqt-account-main { + display: flex; + align-items: center; + gap: var(--space-2); + width: 100%; + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; +} +.aqt-account-main:disabled { + cursor: default; +} +.aqt-account-main .pwi-auth-dot { + margin-right: 0; +} +.aqt-account-copy { + display: grid; + min-width: 0; +} +.aqt-account-label { + overflow: hidden; + text-overflow: ellipsis; +} +.aqt-account-secondary { + font-weight: 400; + font-size: var(--text-caption); + overflow: hidden; + text-overflow: ellipsis; +} +.aqt-group--details > .aqt-row > * { + padding-bottom: var(--space-1); +} +.aqt-detail { + padding-top: 0; + font-weight: 400; + font-size: var(--text-caption); + color: var(--muted); +} +.aqt-detail > * + * { + margin-top: var(--space-1); +} +.aqt-detail p { + margin: 0; +} +/* Controls stay pinned to the right edge while the pool columns scroll under them. */ +.aqt-actions-cell { + position: sticky; + right: 0; + width: 1%; + background: var(--bg); +} +.aqt-group--active .aqt-actions-cell { + background: color-mix(in oklab, var(--green) 6%, var(--bg)); +} +.aqt-actions { + display: flex; + flex-wrap: nowrap; + align-items: center; + justify-content: flex-end; + gap: var(--space-1); +} +.aqt-account .pwi-auth-dot { + display: inline-block; + margin-right: var(--space-2); + vertical-align: middle; +} +.aqt-scarce { + margin-left: var(--space-1); +} +.aqt-pool { + min-width: 9rem; +} +.aqt-table .badge { + white-space: nowrap; +} +.aqt-bar { + display: grid; + grid-template-columns: 2.4rem minmax(2.5rem, 1fr) auto; + align-items: center; + column-gap: var(--space-2); +} +.aqt-bar + .aqt-bar { + margin-top: var(--space-1); +} +.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; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} +.aqt-next { + margin-top: var(--space-1); +} +.aqt-status { + white-space: nowrap; +} +.aqt-flag--ok { color: var(--green); } +.aqt-flag--warn { color: var(--amber); } +.aqt-flag--muted { color: var(--muted); } +.aqt-flag--danger { + color: var(--red); + font-weight: 500; +} +.aqt-banned { + padding: var(--space-1) var(--space-2); + border: 1px solid color-mix(in oklab, var(--red) 45%, transparent); + border-radius: var(--radius-sm); + background: var(--red-soft); +} +.aqt-banned summary { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: var(--space-1) var(--space-3); + cursor: pointer; + list-style: none; +} +.aqt-banned summary::-webkit-details-marker { + display: none; +} +.aqt-banned-text { + color: var(--red); +} +.aqt-banned-more { + color: var(--primary, var(--blue)); + text-decoration: underline; +} +.aqt-banned[open] .aqt-banned-more { + display: none; +} +.aqt-banned p { + margin: var(--space-1) 0 0; + font-size: var(--text-caption); + overflow-wrap: anywhere; +} + +/* Narrow: each account becomes a stacked block — account, plan and status on one line, then one + line per pool with its 5-hour and weekly bars side by side, then the controls — so nothing has + to scroll sideways to reach a button. */ +@container (max-width: 1100px) { + .aqt-table thead { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + } + .aqt-table, + .aqt-group, + .aqt-detail-row { + display: block; + } + .aqt-group:not(:last-child) > tr:last-child > * { + border-bottom: 0; + } + .aqt-group:not(:last-child) { + border-bottom: 1px solid var(--border); + } + .aqt-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto auto auto; + align-items: center; + gap: var(--space-2); + padding: var(--space-2); + } + .aqt-row > th, + .aqt-row > td { + display: block; + padding: 0; + } + .aqt-row > .aqt-account { + grid-area: 1 / 1; + white-space: normal; + } + .aqt-row > .aqt-plan { grid-area: 1 / 2; } + .aqt-row > .aqt-status { grid-area: 1 / 3; } + .aqt-row > .aqt-pool { + grid-column: 1 / -1; + } + .aqt-row > .aqt-actions-cell { grid-area: 1 / 4; } + .aqt-row > .aqt-pool { + display: grid; + grid-template-columns: 6.5rem repeat(2, minmax(0, 1fr)); + align-items: start; + column-gap: var(--space-3); + min-width: 0; + } + .aqt-row > .aqt-pool--empty, + .aqt-row > .aqt-pool--banned { + display: block; + } + .aqt-pool > .aqt-bar + .aqt-bar { + margin-top: 0; + } + .aqt-pool[data-label]::before { + content: attr(data-label); + grid-row: 1; + grid-column: 1; + color: var(--muted); + font-size: var(--text-caption); + } + .aqt-pool > .aqt-next { + grid-column: 1; + grid-row: 2; + justify-self: start; + } + .aqt-actions-cell { + position: static; + width: auto; + background: none; + } + .aqt-group--active .aqt-actions-cell { + background: none; + } + .aqt-actions { + flex-wrap: wrap; + justify-content: flex-start; + } + .aqt-detail-row > .aqt-detail { + display: block; + padding: 0 var(--space-2) var(--space-2); + } +} +@container (max-width: 560px) { + .aqt-row > .aqt-actions-cell { grid-area: auto; grid-column: 1 / -1; } + .aqt-row > .aqt-pool { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .aqt-pool[data-label]::before { grid-row: auto; grid-column: 1 / -1; margin-bottom: var(--space-1); } + .aqt-pool > .aqt-next { grid-row: auto; grid-column: 1 / -1; } +} +} diff --git a/gui/src/components/provider-workspace/types.ts b/gui/src/components/provider-workspace/types.ts index 627992c3a35..6c4ab30f3ec 100644 --- a/gui/src/components/provider-workspace/types.ts +++ b/gui/src/components/provider-workspace/types.ts @@ -70,6 +70,8 @@ export type OAuthAccountRow = AccountQuotaReading & { active: boolean; expiresAt?: number; needsReauth?: boolean; + /** `verify_account`: upstream asked to verify the account rather than refusing the refresh token. */ + needsReauthReason?: string; autoSelectable?: boolean; skipReason?: "needs_reauth" | "paused" | "suspended" | "cooldown" | "quota_exhausted"; paused?: boolean; diff --git a/gui/src/hooks/useAccountProbe.ts b/gui/src/hooks/useAccountProbe.ts new file mode 100644 index 00000000000..db3fc7e15d1 --- /dev/null +++ b/gui/src/hooks/useAccountProbe.ts @@ -0,0 +1,81 @@ +import { useCallback, useRef, useState } from "react"; + +/** Mirrors `AccountProbeStatus` in src/providers/quota/antigravity-account-probe.ts. */ +export const ACCOUNT_PROBE_STATUSES = [ + "ok", "paused", "token_expired", "suspended", "verification_required", "rate_limited", "permission_denied", "error", +] as const; +export type AccountProbeStatus = typeof ACCOUNT_PROBE_STATUSES[number]; + +export interface AccountProbeResultDto { + accountId: string; + status: AccountProbeStatus; + httpStatus: number | null; + reason: string | null; + message: string | null; + latencyMs?: number; + quota?: { customWindows?: Array<{ label: string; percent: number }> } | null; +} + +/** Providers whose management API implements `POST /api/oauth/accounts/probe`. */ +export const ACCOUNT_PROBE_PROVIDERS: ReadonlySet = new Set(["google-antigravity"]); + +export type AccountProbeEntry = { result: AccountProbeResultDto; at: number } | { failed: true; at: number }; + +function isProbeResult(value: unknown): value is AccountProbeResultDto { + if (!value || typeof value !== "object") return false; + const row = value as Partial; + return typeof row.accountId === "string" && typeof row.status === "string" + && (ACCOUNT_PROBE_STATUSES as readonly string[]).includes(row.status); +} + +/** Probe state for one provider's account list; results stay in memory for this view only. */ +export function useAccountProbe(apiBase: string, provider: string) { + const [entries, setEntries] = useState>({}); + const [pending, setPending] = useState>(new Set()); + const [allPending, setAllPending] = useState(false); + const running = useRef(false); + + const probe = useCallback(async (accountIds: readonly string[], all: boolean) => { + if (running.current || accountIds.length === 0) return; + running.current = true; + setPending(new Set(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 { + running.current = false; + setPending(new Set()); + if (all) setAllPending(false); + } + }, [apiBase, provider]); + + return { + entries, + busy: pending.size > 0, + 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/hooks/useProviderAccountPools.ts b/gui/src/hooks/useProviderAccountPools.ts index 22f9a1f8489..39cefaf23a1 100644 --- a/gui/src/hooks/useProviderAccountPools.ts +++ b/gui/src/hooks/useProviderAccountPools.ts @@ -35,6 +35,8 @@ export interface OAuthAccount extends AccountQuotaReading { maskedLabel?: string; active: boolean; needsReauth?: boolean; + /** `verify_account`: upstream asked to verify the account rather than refusing the refresh token. */ + needsReauthReason?: string; autoSelectable?: boolean; skipReason?: "needs_reauth" | "paused" | "suspended" | "cooldown" | "quota_exhausted"; paused?: boolean; diff --git a/gui/src/i18n/account-probe-copy.ts b/gui/src/i18n/account-probe-copy.ts new file mode 100644 index 00000000000..c08642757ee --- /dev/null +++ b/gui/src/i18n/account-probe-copy.ts @@ -0,0 +1,68 @@ +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; + +/** Per-account probe and manual model discovery copy, one row per key in `locales` order. */ +const rows = { + "acctProbe.test": ["Test", "테스트", "Testen", "Tester", "测试", "測試", "Проверить", "テスト", "Test et", "Kiểm tra", "Testar"], + "acctProbe.testing": ["Testing…", "테스트 중…", "Wird getestet…", "Test en cours…", "测试中…", "測試中…", "Проверка…", "テスト中…", "Test ediliyor…", "Đang kiểm tra…", "Testando…"], + "acctProbe.testAll": ["Test all", "모두 테스트", "Alle testen", "Tout tester", "全部测试", "全部測試", "Проверить все", "すべてテスト", "Tümünü test et", "Kiểm tra tất cả", "Testar todas"], + "acctProbe.hint": ["Read-only: sends one quota request with this account's stored token. Expired tokens are reported, never refreshed.", "읽기 전용: 이 계정에 저장된 토큰으로 할당량 요청을 한 번 보냅니다. 만료된 토큰은 갱신하지 않고 그대로 보고합니다.", "Nur lesend: sendet eine Kontingentanfrage mit dem gespeicherten Token dieses Kontos. Abgelaufene Tokens werden gemeldet, nie erneuert.", "Lecture seule : envoie une requête de quota avec le jeton enregistré de ce compte. Un jeton expiré est signalé, jamais renouvelé.", "只读:用该账号已存的 token 发一次额度查询。token 已过期时只报告,不刷新。", "唯讀:用該帳號已存的 Token 送出一次額度查詢。Token 已過期時只回報,不刷新。", "Только чтение: один запрос квоты с сохранённым токеном аккаунта. Истёкший токен только отмечается, не обновляется.", "読み取り専用:このアカウントの保存済みトークンでクォータ要求を 1 回送ります。期限切れトークンは報告のみで更新しません。", "Salt okunur: bu hesabın kayıtlı belirteciyle bir kota isteği gönderir. Süresi dolmuş belirteç yenilenmez, yalnızca bildirilir.", "Chỉ đọc: gửi một yêu cầu hạn mức bằng token đã lưu của tài khoản. Token hết hạn chỉ được báo, không làm mới.", "Somente leitura: envia uma consulta de cota com o token salvo desta conta. Tokens expirados são informados, nunca renovados."], + "acctProbe.failed": ["Test request failed", "테스트 요청 실패", "Testanfrage fehlgeschlagen", "La requête de test a échoué", "测试请求失败", "測試請求失敗", "Запрос проверки не выполнен", "テスト要求に失敗しました", "Test isteği başarısız", "Yêu cầu kiểm tra thất bại", "Falha na solicitação de teste"], + "acctProbe.status.ok": ["Usable", "사용 가능", "Nutzbar", "Utilisable", "可用", "可用", "Работает", "利用可能", "Kullanılabilir", "Dùng được", "Utilizável"], + "acctProbe.status.paused": ["Paused (not tested)", "일시 중지됨(테스트 안 함)", "Pausiert (nicht getestet)", "En pause (non testé)", "已暂停(未测试)", "已暫停(未測試)", "Приостановлен (не проверялся)", "一時停止中(未テスト)", "Duraklatıldı (test edilmedi)", "Đã tạm dừng (không kiểm tra)", "Pausada (não testada)"], + "acctProbe.status.token_expired": ["Token expired (not refreshed)", "토큰 만료(갱신 안 함)", "Token abgelaufen (nicht erneuert)", "Jeton expiré (non renouvelé)", "token 已过期(未刷新)", "Token 已過期(未刷新)", "Токен истёк (не обновлён)", "トークン期限切れ(未更新)", "Belirteç süresi doldu (yenilenmedi)", "Token hết hạn (chưa làm mới)", "Token expirado (não renovado)"], + "acctProbe.status.suspended": ["Suspended", "정지됨", "Gesperrt", "Suspendu", "已暂停", "已暫停", "Приостановлен", "停止中", "Askıya alındı", "Bị đình chỉ", "Suspensa"], + "acctProbe.status.verification_required": ["Verification required", "인증 필요", "Verifizierung erforderlich", "Vérification requise", "要求验证", "需要驗證", "Требуется подтверждение", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária"], + "acctProbe.status.rate_limited": ["Rate limited", "요청 제한", "Ratenlimit", "Limite de débit", "限流", "限流", "Ограничение частоты", "レート制限", "Hız sınırı", "Bị giới hạn tốc độ", "Limite de taxa"], + "acctProbe.status.permission_denied": ["Permission denied (403)", "권한 거부(403)", "Zugriff verweigert (403)", "Accès refusé (403)", "权限拒绝(403)", "權限遭拒(403)", "Доступ запрещён (403)", "権限拒否(403)", "İzin reddedildi (403)", "Bị từ chối quyền (403)", "Permissão negada (403)"], + "acctProbe.status.error": ["Other error", "기타 오류", "Anderer Fehler", "Autre erreur", "其他错误", "其他錯誤", "Другая ошибка", "その他のエラー", "Diğer hata", "Lỗi khác", "Outro erro"], + "modelDiscover.now": ["Discover now", "지금 검색", "Jetzt abrufen", "Découvrir maintenant", "立即发现", "立即探索", "Найти сейчас", "今すぐ検出", "Şimdi keşfet", "Khám phá ngay", "Descobrir agora"], + "modelDiscover.running": ["Discovering…", "검색 중…", "Wird abgerufen…", "Découverte…", "发现中…", "探索中…", "Поиск…", "検出中…", "Keşfediliyor…", "Đang khám phá…", "Descobrindo…"], + "modelDiscover.recent": ["Recently added models", "최근 추가된 모델", "Kürzlich hinzugekommene Modelle", "Modèles ajoutés récemment", "最近新增的模型", "最近新增的模型", "Недавно добавленные модели", "最近追加されたモデル", "Son eklenen modeller", "Mô hình mới thêm gần đây", "Modelos adicionados recentemente"], + "modelDiscover.none": ["No new models recorded yet.", "아직 기록된 새 모델이 없습니다.", "Noch keine neuen Modelle erfasst.", "Aucun nouveau modèle enregistré pour l’instant.", "还没有记录到新模型。", "尚未記錄到新模型。", "Новые модели пока не обнаружены.", "新しいモデルはまだ記録されていません。", "Henüz yeni model kaydedilmedi.", "Chưa ghi nhận mô hình mới nào.", "Nenhum modelo novo registrado ainda."], + "modelDiscover.result": ["{count} live models, {added} new", "실시간 모델 {count}개, 새 모델 {added}개", "{count} Live-Modelle, {added} neu", "{count} modèles en direct, {added} nouveaux", "共 {count} 个在线模型,新增 {added} 个", "共 {count} 個線上模型,新增 {added} 個", "Моделей: {count}, новых: {added}", "ライブモデル {count} 件、新規 {added} 件", "{count} canlı model, {added} yeni", "{count} mô hình trực tiếp, {added} mới", "{count} modelos ativos, {added} novos"], + "modelDiscover.failed": ["Discovery failed", "검색 실패", "Abruf fehlgeschlagen", "Échec de la découverte", "发现失败", "探索失敗", "Поиск не удался", "検出に失敗しました", "Keşif başarısız", "Khám phá thất bại", "Falha na descoberta"], + "modelDiscover.inProgress": ["Model discovery is already in progress. Try again shortly.", "이미 모델을 검색하고 있습니다. 잠시 후 다시 시도하세요.", "Modelle werden bereits abgerufen. Versuche es in Kürze erneut.", "La découverte de modèles est déjà en cours. Réessayez dans un instant.", "正在发现模型,请稍后重试。", "正在探索模型,請稍後重試。", "Поиск моделей уже идёт. Повторите попытку чуть позже.", "モデルを検出中です。しばらくしてからもう一度お試しください。", "Model keşfi zaten devam ediyor. Biraz sonra tekrar deneyin.", "Đang khám phá mô hình. Hãy thử lại sau giây lát.", "A descoberta de modelos já está em andamento. Tente novamente em instantes."], + "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.actions": ["Actions", "작업", "Aktionen", "Commandes", "操作", "操作", "Действия", "操作", "İşlemler", "Thao tác", "Ações"], + "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.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.left": ["{percent}% left", "{percent}% 남음", "{percent} % übrig", "{percent} % restant", "剩 {percent}%", "剩 {percent}%", "осталось {percent}%", "残り {percent}%", "%{percent} kaldı", "còn {percent}%", "{percent}% restante"], + "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.flag.ok": ["Healthy", "정상", "In Ordnung", "Sain", "正常", "正常", "Работает", "正常", "Sağlıklı", "Bình thường", "Saudável"], + "acctTable.flag.banned": ["Banned upstream", "업스트림 차단됨", "Upstream gesperrt", "Bloqué en amont", "已封禁", "已封禁", "Заблокирован", "上流で停止", "Upstream yasakladı", "Bị chặn phía upstream", "Bloqueada no upstream"], + "acctTable.flag.verify": ["Verification needed", "인증 필요", "Verifizierung nötig", "Vérification requise", "需验证", "需驗證", "Нужна проверка", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária"], + "acctTable.bannedRow": ["Upstream refused this account; automatic refresh is stopped", "업스트림이 이 계정을 거부해 자동 새로 고침을 멈췄습니다", "Upstream hat dieses Konto abgelehnt; automatische Aktualisierung gestoppt", "Le fournisseur a refusé ce compte ; actualisation automatique arrêtée", "账号已被上游封禁,已停止自动刷新", "帳號已被上游封禁,已停止自動重新整理", "Провайдер отклонил аккаунт; автообновление остановлено", "上流がこのアカウントを拒否したため自動更新を停止しました", "Upstream bu hesabı reddetti; otomatik yenileme durduruldu", "Upstream đã từ chối tài khoản này; đã dừng tự làm mới", "O upstream recusou esta conta; atualização automática parada"], + "acctTable.bannedReason": ["View reason", "사유 보기", "Grund anzeigen", "Voir le motif", "查看原因", "查看原因", "Причина", "理由を見る", "Nedeni gör", "Xem lý do", "Ver motivo"], + "acctTable.flag.paused": ["Paused", "일시 중지", "Pausiert", "En pause", "已暂停", "已暫停", "Приостановлен", "一時停止", "Duraklatıldı", "Đã tạm dừng", "Pausada"], + "acctTable.flag.reauth": ["Sign-in needed", "재로그인 필요", "Anmeldung nötig", "Connexion requise", "需重新登录", "需重新登入", "Нужен вход", "再ログインが必要", "Oturum açılmalı", "Cần đăng nhập lại", "Login necessário"], + "acctTable.flag.rateLimited": ["Rate limited", "요청 제한", "Ratenlimit", "Débit limité", "限流中", "限流中", "Ограничение частоты", "レート制限中", "Hız sınırında", "Bị giới hạn tốc độ", "Limite de taxa"], + "acctTable.flag.quotaLimited": ["Quota cooldown", "할당량 대기", "Kontingent-Pause", "Pause de quota", "额度冷却中", "額度冷卻中", "Квота на паузе", "クォータ待機中", "Kota beklemesi", "Đang chờ hạn mức", "Pausa de cota"], + "acctTable.flag.warning": ["Warning", "경고", "Warnung", "Alerte", "有警告", "有警告", "Предупреждение", "警告", "Uyarı", "Cảnh báo", "Aviso"], + "acctTable.flag.slow": ["Slow", "느림", "Langsam", "Lent", "响应慢", "回應慢", "Медленно", "遅い", "Yavaş", "Chậm", "Lenta"], + "acctTable.flag.stale": ["Quota not read", "할당량 미확인", "Kontingent nicht gelesen", "Quota non lu", "额度没读到", "額度沒讀到", "Квота не прочитана", "クォータ未取得", "Kota okunamadı", "Chưa đọc được hạn mức", "Cota não lida"], +} as const satisfies Record; + +export type AccountProbeCopyKey = keyof typeof rows; + +export function accountProbeCopy(locale: Locale): Record { + const index = locales.indexOf(locale); + return Object.fromEntries(Object.entries(rows).map(([key, values]) => [key, values[index]!])) as Record; +} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 9a223fa6ece..2ce81c28eda 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"; @@ -135,6 +136,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 fdfafafcf7a..0f8b69619c1 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"; @@ -136,6 +137,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 57b8c329a42..ea2b420fe18 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"; @@ -134,6 +135,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 91a8659de3d..adc77ac38b1 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"; @@ -134,6 +135,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 ce8c3727aff..cfe9ddc7c41 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"; @@ -134,6 +135,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 1650b843832..c92deaef38d 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"; @@ -136,6 +137,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 bd0f7d3b15b..739926ff620 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"; @@ -134,6 +135,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 30aade63dcf..ee73581b1bd 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"; @@ -135,6 +136,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 1bca40cbb0a..4fa3a0802b9 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"; @@ -136,6 +137,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 fb506e43e07..70b87e9660b 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"; @@ -132,6 +133,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 5e366410758..bd8ea445892 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"; @@ -134,6 +135,7 @@ export const zh: Record = { "workflowBudget.saveFailed": "无法保存工作流限制。", "workflowBudget.saved": "工作流限制已保存。", ...desktopCompatibilityCopy("zh"), + ...accountProbeCopy("zh"), ...shellV2Copy("zh"), ...codexCliUpdateCopy("zh"), ...remoteLinkDiagnosticsCopy("zh"), diff --git a/gui/src/provider-workspace/account-quota-table.ts b/gui/src/provider-workspace/account-quota-table.ts new file mode 100644 index 00000000000..55d461dd241 --- /dev/null +++ b/gui/src/provider-workspace/account-quota-table.ts @@ -0,0 +1,217 @@ +/** + * 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>; +} + +/** Window labels a pool column already shows; every other custom window stays in the row's detail line. */ +const POOL_LABELS = new Set(); + +const byLabel = (fiveHour: string, weekly: string) => { + POOL_LABELS.add(fiveHour); + POOL_LABELS.add(weekly); + return (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 } } : {}), + }), + }, +]; + +/** Custom windows no pool column shows (per-model rows, unknown labels), in their original order. */ +export function uncoveredWindows(windows: readonly W[] | undefined): W[] { + return (windows ?? []).filter(window => !POOL_LABELS.has(window.label)); +} + +/** 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(); + const label = plan?.trim(); + if (!label) return null; + const tier = label.toLowerCase(); + return Object.hasOwn(PLAN_NAMES, tier) ? PLAN_NAMES[tier]! : label; +} + +export type AccountFlag = "ok" | "banned" | "paused" | "verify" | "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; + /** Upstream asked for account verification (a 403), as opposed to a refused refresh token. */ + verifyRequired?: boolean; + /** + * Auto-paused because upstream refused the account itself (`account_permission_denied`). + * The row replaces its quota cells with one notice; resuming is the manual way back. + */ + banned?: { message?: string; pausedAt?: number; statusCode?: number }; + 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.banned) return { flag: "banned" }; + if (account.paused) return { flag: "paused" }; + if (account.verifyRequired) return { flag: "verify" }; + 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; + // An expired access token is routine (refreshed on the next request), not a failed probe. + if (probe && probe.status !== "ok" && probe.status !== "paused" && probe.status !== "token_expired") 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: account.quota ? "warning" : "stale" }; + return { flag: "ok" }; +} + +const USABLE: ReadonlySet = new Set(["ok", "slow", "stale", "warning"]); + +/** + * `strategy` is the pool's effective selection strategy. The `next` marker projects reset-first + * ordering only, so any other (or unknown) strategy gets no marker rather than a wrong guess. + */ +export function buildQuotaTable(accounts: readonly QuotaTableAccount[], now = Date.now(), strategy?: string): 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 strategy === "reset-first" ? pools.filter(spec => spec.scarce) : []) { + let best: { row: QuotaTableRow; resetAt: number } | undefined; + for (const row of rows) { + const cell = row.cells[pool.key]; + if (!cell || !USABLE.has(row.flag)) continue; + const windows = [cell.fiveHour, cell.weekly].filter((window): window is PoolCell => window !== undefined); + if (windows.some(window => window.remaining <= 0)) continue; + const resetAt = (cell.weekly ?? cell.fiveHour)?.resetAt; + if (resetAt === undefined) continue; + if (!best || resetAt < best.resetAt) best = { row, resetAt }; + } + best?.row.next.push(pool.key); + } + return { pools, rows }; +} + +/** "45m", "3h 12m", "2d 5h"; under a minute reads "<1m". */ +export function formatCountdown(resetAt: number, now = Date.now()): string { + const minutes = Math.floor((resetAt - now) / 60_000); + if (minutes < 1) return "<1m"; + const days = Math.floor(minutes / 1440); + const hours = Math.floor((minutes % 1440) / 60); + const mins = minutes % 60; + if (days > 0) return `${days}d ${hours}h`; + if (hours > 0) return `${hours}h ${mins}m`; + return `${mins}m`; +} diff --git a/gui/src/styles/provider-workspace-shell.css b/gui/src/styles/provider-workspace-shell.css index 57939257d80..d624942a0e5 100644 --- a/gui/src/styles/provider-workspace-shell.css +++ b/gui/src/styles/provider-workspace-shell.css @@ -5,6 +5,10 @@ max-width: 1440px; } +.main-inner:has(.pws-detail--oauth-accounts) { + max-width: 1600px; +} + .pws-shell-container { container-name: provider-workspace; container-type: inline-size; @@ -812,6 +816,10 @@ max-width: 960px; } +.pws-detail--oauth-accounts { + max-width: 1280px; +} + .pws-detail-icon { width: 32px; height: 32px; diff --git a/gui/tests/account-pause-display.test.tsx b/gui/tests/account-pause-display.test.tsx index aece27eeb23..3a8924ac6f3 100644 --- a/gui/tests/account-pause-display.test.tsx +++ b/gui/tests/account-pause-display.test.tsx @@ -5,6 +5,7 @@ import { Window } from "happy-dom"; import ProviderAuthPanel from "../src/components/provider-workspace/ProviderAuthPanel"; import { CodexAccountPoolCards } from "../src/components/codex-account-pool-cards"; import type { ProviderAuthHandlers } from "../src/components/provider-workspace/types"; +import type { OAuthAccount } from "../src/hooks/useProviderAccountPools"; import type { WorkspaceItem } from "../src/provider-workspace/catalog"; import { I18nContext, DICTS, interpolate, LOCALES, type Locale, type TFn } from "../src/i18n/shared"; import { formatAccountPauseTooltip } from "../src/account-pause-display"; @@ -45,7 +46,9 @@ test.each(["fr", "ko"] as const)("provider OAuth and key tooltips use the app lo accounts={[{ id: "account-fixture", alias: "Reserve account", active: false, paused: true, pauseDetails: details }]} keys={[{ id: "key-fixture", label: "Reserve key", masked: "****", active: false, disabled: true, pauseDetails: details }]} />, locale); try { - expect(win.document.querySelector(".badge-muted[title]")?.getAttribute("title")).toBe(expected); + // OAuth accounts render in the quota table (pause tooltip on the account button); key rows keep the badge. + const tooltipHost = authMode === "oauth" ? ".aqt-account-main[title]" : ".badge-muted[title]"; + expect(win.document.querySelector(tooltipHost)?.getAttribute("title")).toBe(expected); if (authMode === "key") { expect(win.document.querySelector(".pwi-auth-row-main")?.getAttribute("aria-label")) .toBe(`${t("pws.resumeAndActivateKey")} — Reserve key`); @@ -55,6 +58,43 @@ test.each(["fr", "ko"] as const)("provider OAuth and key tooltips use the app lo }); const appealHref = "https://forms.gle/appeal-fixture"; + +test("the banned quota row shows only the display fields from the OAuth pause response", () => { + const account = { + id: "banned-account-fixture", + alias: "Banned account fixture", + active: false, + paused: true, + pauseDetails: { ...details, reason: "account_permission_denied" }, + pauseEvidence: { + message: "This service has been disabled in this account for violation of Terms of Service.", + statusCode: 403, + appealUrl: appealHref, + appealText: "Request a review", + }, + } satisfies OAuthAccount; + const item = { name: "google-antigravity", authMode: "oauth", adapter: "google" } as WorkspaceItem; + const win = render(, "en"); + + try { + const row = win.document.querySelector('[data-testid="account-quota-table"] tbody')!; + const notice = row.querySelector("details")!; + notice.open = true; + expect(Array.from(notice.children, child => child.textContent)).toEqual([ + DICTS.en["acctTable.bannedRow"] + DICTS.en["acctTable.bannedReason"], + account.pauseEvidence.message, + new Date(account.pauseDetails.pausedAt).toLocaleString() + " · HTTP 403", + ]); + const link = row.querySelector("a"); + expect(link?.textContent).toBe(account.pauseEvidence.appealText); + expect(link?.getAttribute("href")).toBe(appealHref); + expect(row.textContent).not.toContain(account.id); + expect(row.textContent).not.toContain(account.pauseDetails.reason); + expect(row.textContent).not.toContain(appealHref); + } finally { void win.happyDOM.close(); } +}); + function renderAppeal(locale: Locale, appealText?: string, paused = true, appealUrl = appealHref) { const item = { name: "google-antigravity", authMode: "oauth", adapter: "google" } as WorkspaceItem; return render( { const win = renderAppeal(code, "Invalid vendor label"); try { - const link = win.document.querySelector(`.pwi-auth-acct a[href="${appealHref}"]`); + const link = win.document.querySelector(`.aqt-detail a[href="${appealHref}"]`); expect(link?.textContent).toBe(DICTS[code]["accountPause.submitAppeal"]); expect(link?.textContent?.trim()).toBeTruthy(); expect(link?.getAttribute("target")).toBe("_blank"); @@ -82,7 +122,7 @@ test("paused OAuth details use a plain vendor label and omit links on resumed ro ] as const) { const win = renderAppeal("en", "Request a review", paused, url); try { - expect(win.document.querySelector(".pwi-auth-acct a")?.textContent).toBe(expected); + expect(win.document.querySelector(".aqt-detail a")?.textContent).toBe(expected); } finally { void win.happyDOM.close(); } } }); diff --git a/gui/tests/anthropic-subscription-label.test.tsx b/gui/tests/anthropic-subscription-label.test.tsx index 17654d0c9a4..8cf9e03f21b 100644 --- a/gui/tests/anthropic-subscription-label.test.tsx +++ b/gui/tests/anthropic-subscription-label.test.tsx @@ -25,11 +25,15 @@ for (const provider of ["anthropic", "anthropic2"]) { expect(markup).toContain(`>${label}`); expect(markup).not.toContain("private@example.test"); expect(markup).not.toContain("synthetic-private-account"); - expect(markup).toContain("37% used"); + // The quota table shows remaining capacity: 37% used weekly -> 63% left, 18% used 5-hour -> 82% left. + expect(markup).toContain("63% left"); if (plan === "pro" || plan === "max_5x") { - expect(markup).toContain("5-hour limit"); - expect(markup).toContain("18% used"); - } else expect(markup).not.toContain("5-hour limit"); + expect(markup).toContain(`class="aqt-bar-label">${en["acctTable.fiveHour"]}`); + expect(markup).toContain("82% left"); + } else { + expect(markup).not.toContain(`class="aqt-bar-label">${en["acctTable.fiveHour"]}`); + expect(markup).not.toContain("82% left"); + } }); } } @@ -54,13 +58,13 @@ test("same-account rows show distinct organization names as literal text and omi win.document.body.innerHTML = renderToStaticMarkup( , ); - const rows = [...win.document.querySelectorAll(".pwi-auth-acct")]; - expect(rows.map(row => row.querySelector(".pwi-auth-row-label")?.textContent)).toEqual(accounts.map(() => shared.accountLabel)); - expect(rows.map(row => row.querySelector(".pwi-auth-row-secondary")?.textContent)).toEqual([ + const rows = [...win.document.querySelectorAll(".aqt-row")]; + expect(rows.map(row => row.querySelector(".aqt-account-label")?.textContent)).toEqual(accounts.map(() => shared.accountLabel)); + expect(rows.map(row => row.querySelector(".aqt-account-organization")?.textContent)).toEqual([ "Synthetic Team", "Research & Design", undefined, ]); expect(rows[1]?.querySelector("strong")).toBeNull(); - expect(rows[2]?.querySelector(".pwi-auth-row-secondary")).toBeNull(); + expect(rows[2]?.querySelector(".aqt-account-organization")).toBeNull(); } finally { await win.happyDOM.close(); } }); diff --git a/gui/tests/anthropic2-provider-surfaces.test.tsx b/gui/tests/anthropic2-provider-surfaces.test.tsx index 28617b4053b..ef1cd88b965 100644 --- a/gui/tests/anthropic2-provider-surfaces.test.tsx +++ b/gui/tests/anthropic2-provider-surfaces.test.tsx @@ -7,7 +7,7 @@ */ import { afterEach, beforeEach, expect, test } from "bun:test"; import { Window } from "happy-dom"; -import { act, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { act, createRef, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from "react"; import type { Root } from "react-dom/client"; import { en } from "../src/i18n/en"; import { LanguageProvider } from "../src/i18n/provider"; @@ -244,7 +244,7 @@ test("UX-05: every Pool 2 account, pool-settings and reset-grant mutation names expect(poolToggle()?.getAttribute("aria-pressed")).toBe("true"); await click(host.querySelectorAll('button[aria-label^="' + en["codexAuth.pause"] + ' — "]')[1]); await click(host.querySelectorAll("button.codex-account-auto-switch-toggle")[1]); - await click(host.querySelectorAll(".pwi-auth-row-main")[1]); + await click(host.querySelectorAll(".aqt-account-main")[1]); await click(buttonsByText(en["prov.editAlias"])[1]); await click(host.querySelectorAll(".pwi-auth-row-remove")[1]); await click(host.querySelector("[data-anthropic-grant-badge]")); @@ -469,7 +469,7 @@ test.each(["switch", "pause"] as const)("logout explains a pending %s and succee authHandlers={{ ...recordingHandlers([]), onSwitchAccount: pools.switchAccount, onPauseAccount: pools.pauseAccount, onLogout: oauth.logoutOAuth }} />; } await render(); - if (action === "switch") await click(host.querySelectorAll(".pwi-auth-row-main")[1]); + if (action === "switch") await click(host.querySelectorAll(".aqt-account-main")[1]); else await click(host.querySelectorAll('button[aria-label^="' + en["codexAuth.pause"] + ' — "]')[1]); await started; await click(buttonsByText(en["prov.logout"])[0]); @@ -496,7 +496,7 @@ test("unverified OAuth status never reports a stale roster as logged in or logge }); test.each(["delete", "logout"] as const)("%s with failed reads retains explicit logout without claiming authentication", async operation => { - let pools!: ReturnType; + const controls = createRef, "fetchAccountSets">>(); let failReads = false; const notices: string[] = []; respond = async request => { @@ -512,18 +512,19 @@ test.each(["delete", "logout"] as const)("%s with failed reads retains explicit const aliveRef = useRef(true); const [status, setOauthStatus] = useState>({ anthropic2: { loggedIn: true }, anthropic: { loggedIn: true } }); const loader = useProvidersFetch({ apiBase: "", t: key => key, setConfig: () => {}, setOauthProviders: () => {}, setOauthStatus, notify: () => {}, invalidateProviderQuotas: () => {} }); - pools = useProviderAccountPools({ apiBase: "", config: null, aliveRef, t: key => key, oauthStatus: status, notify: message => notices.push(message), + const pools = useProviderAccountPools({ apiBase: "", config: null, aliveRef, t: key => key, oauthStatus: status, notify: message => notices.push(message), fetchConfig: async () => {}, fetchOauth: loader.fetchOauth, fetchProviderQuotas: async () => {}, codexActiveNeedsReauth: false, invalidateOauthStatusReads: loader.invalidateOauthStatusReads, setOauthStatus }); const oauth = useProvidersOAuth({ apiBase: "", t: key => key, aliveRef, accountSets: pools.accountSets, setAccountSets: pools.setAccountSets, setBusy: () => {}, setStatus: () => {}, setLoginInfo: () => {}, setOauthStatus, invalidateOauthStatusReads: loader.invalidateOauthStatusReads, beginAccountLogout: pools.beginAccountLogout, notify: message => notices.push(message), fetchConfig: async () => {}, fetchOauth: loader.fetchOauth, fetchAccountSets: pools.fetchAccountSets, fetchProviderQuotas: async () => {}, bumpModelsRefresh: () => {} }); + useImperativeHandle(controls, () => ({ fetchAccountSets: pools.fetchAccountSets })); return <>{String(status.anthropic?.loggedIn)}; } await render(); - await act(async () => { await pools.fetchAccountSets(["anthropic2"]); }); + await act(async () => { await controls.current!.fetchAccountSets(["anthropic2"]); }); if (operation === "delete") { await click(host.querySelector(".pwi-auth-row-remove")); await click([...win.document.querySelectorAll("dialog button")].find(button => button.textContent === "common.remove")); @@ -555,8 +556,12 @@ test("pending login cancellation does not prevent logout or account removal", as const consent = spyOn(dialogs, "confirmAction").mockResolvedValue(true); const login = Promise.withResolvers(); const cancel = Promise.withResolvers(); - let oauth!: ReturnType; - let pools!: ReturnType; + const controls = createRef<{ + login: ReturnType["loginOAuth"]; + cancel: ReturnType["cancelLoginOAuth"]; + logout: ReturnType["logoutOAuth"]; + remove: ReturnType["removeAccount"]; + }>(); respond = async request => { if (request.path === "/api/oauth/login") return login.promise; if (request.path === "/api/oauth/login/cancel") return cancel.promise; @@ -565,23 +570,26 @@ test("pending login cancellation does not prevent logout or account removal", as function Harness() { const aliveRef = useRef(true); const [statuses, setOauthStatus] = useState>({}); - pools = useProviderAccountPools({ apiBase: "", config: null, aliveRef, t: key => key, oauthStatus: statuses, + const pools = useProviderAccountPools({ apiBase: "", config: null, aliveRef, t: key => key, oauthStatus: statuses, notify: () => {}, fetchConfig: async () => {}, fetchOauth: async () => {}, fetchProviderQuotas: async () => {}, codexActiveNeedsReauth: false }); - oauth = useProvidersOAuth({ apiBase: "", t: key => key, aliveRef, accountSets: pools.accountSets, + const oauth = useProvidersOAuth({ apiBase: "", t: key => key, aliveRef, accountSets: pools.accountSets, setAccountSets: pools.setAccountSets, setBusy: () => {}, setStatus: () => {}, setLoginInfo: () => {}, setOauthStatus, beginAccountLogout: pools.beginAccountLogout, notify: () => {}, fetchConfig: async () => {}, fetchOauth: async () => {}, fetchAccountSets: pools.fetchAccountSets, fetchProviderQuotas: async () => {}, bumpModelsRefresh: () => {} }); + useImperativeHandle(controls, () => ({ + login: oauth.loginOAuth, cancel: oauth.cancelLoginOAuth, logout: oauth.logoutOAuth, remove: pools.removeAccount, + })); return null; } try { await render(); - await act(async () => { void oauth.loginOAuth("anthropic2"); void oauth.cancelLoginOAuth("anthropic2"); }); + await act(async () => { void controls.current!.login("anthropic2"); void controls.current!.cancel("anthropic2"); }); expect(requests.filter(request => request.path === "/api/oauth/login")).toHaveLength(1); expect(requests.filter(request => request.path === "/api/oauth/login/cancel")).toHaveLength(1); - await act(async () => { await oauth.logoutOAuth("anthropic2"); }); - await act(async () => { await pools.removeAccount("anthropic2", accounts("anthropic2")[0]!); }); + await act(async () => { await controls.current!.logout("anthropic2"); }); + await act(async () => { await controls.current!.remove("anthropic2", accounts("anthropic2")[0]!); }); expect(requests.filter(request => request.path === "/api/oauth/logout")).toHaveLength(1); expect(requests.filter(request => request.method === "DELETE")).toHaveLength(1); } finally { diff --git a/gui/tests/auth-panel-refresh-render.test.tsx b/gui/tests/auth-panel-refresh-render.test.tsx index b444074f861..e3b5bf5153a 100644 --- a/gui/tests/auth-panel-refresh-render.test.tsx +++ b/gui/tests/auth-panel-refresh-render.test.tsx @@ -107,14 +107,14 @@ afterEach(async () => { await testWindow.happyDOM?.close?.(); }); -test("the refresh control renders above the account list", async () => { +test("the refresh control renders above the account quota table", async () => { const host = await mountPanel(async () => true); const button = headButton(host); - const list = host.querySelector(".pwi-auth-list") ?? host.querySelector(".pwi-auth-body"); - expect(list).not.toBeNull(); + const table = host.querySelector('table[aria-label="Account quotas"]'); + expect(table).not.toBeNull(); // The whole point of the move: it must precede the bars it refreshes in document // order, instead of sitting after every account's stacked windows. - const position = button.compareDocumentPosition(list!); + const position = button.compareDocumentPosition(table!); expect(position & 0x04 /* DOCUMENT_POSITION_FOLLOWING */).toBeTruthy(); }); diff --git a/gui/tests/fr-localization.test.ts b/gui/tests/fr-localization.test.ts index 869ecb7f75f..9fef8da4d41 100644 --- a/gui/tests/fr-localization.test.ts +++ b/gui/tests/fr-localization.test.ts @@ -28,6 +28,9 @@ 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.pool.gemini", // Quota pool named after the product. + "acctTable.pool.claudeGpt", // Quota pool named after the products. + "acctTable.pool.argon", // Quota pool name used by the Antigravity quota API. "nav.codexSet", // Product name: the sidebar row reads "Codex" in every locale. "codexCliUpdate.tab", // Product name: the Codex CLI tab reads "Codex CLI" in every locale. "codexCliUpdate.provNpmGlobal", // "npm (global)": the tool name plus a word French spells the same. diff --git a/gui/tests/provider-account-states-and-probe.test.tsx b/gui/tests/provider-account-states-and-probe.test.tsx new file mode 100644 index 00000000000..0e8e78e1e1f --- /dev/null +++ b/gui/tests/provider-account-states-and-probe.test.tsx @@ -0,0 +1,134 @@ +/** + * Account table states on the Antigravity Accounts panel: an upstream-banned row (with and without + * quota readings), the "Verification needed" flag, and the Test / Test all probe controls. + */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import ProviderAuthPanel from "../src/components/provider-workspace/ProviderAuthPanel"; +import { LanguageProvider } from "../src/i18n/provider"; +import type { WorkspaceItem } from "../src/provider-workspace/catalog"; +import type { ProviderAuthHandlers } from "../src/components/provider-workspace/types"; +import type { OAuthAccount } from "../src/hooks/useProviderAccountPools"; + +const globals = ["document", "window", "navigator", "localStorage", "sessionStorage", "fetch", "IS_REACT_ACT_ENVIRONMENT"] as const; +let previous: Record<(typeof globals)[number], unknown>; +let win: Window; +let host: HTMLElement; +let root: Root | null = null; +let probeBodies: unknown[]; +let holdProbe: Promise | undefined; + +const item = { name: "google-antigravity", adapter: "openai-responses", authMode: "oauth", hasApiKey: false } as unknown as WorkspaceItem; +const handlers: ProviderAuthHandlers = { + onLogin: () => {}, onLogout: () => {}, onReauth: () => {}, onSwitchAccount: () => {}, onRemoveAccount: () => {}, + onAddApiKey: async () => true, onSwitchApiKey: () => {}, onRemoveApiKey: () => {}, onEditAlias: () => {}, +}; +const PAUSED_AT = Date.parse("2026-11-13T12:00:00Z"); +const bannedDetails = { reason: "account_permission_denied", pausedAt: PAUSED_AT }; +const bannedEvidence = { message: "This account was disabled upstream.", statusCode: 403 }; + +beforeEach(() => { + previous = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previous; + win = new Window({ url: "http://localhost/" }); + Object.defineProperty(win.navigator, "language", { configurable: true, value: "en-US" }); + probeBodies = []; + holdProbe = undefined; + Object.defineProperties(globalThis, { + document: { configurable: true, value: win.document }, + window: { configurable: true, value: win }, + navigator: { configurable: true, value: win.navigator }, + localStorage: { configurable: true, value: win.localStorage }, + sessionStorage: { configurable: true, value: win.sessionStorage }, + fetch: { configurable: true, value: async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).endsWith("/api/oauth/accounts/probe")) { + const body = JSON.parse(String(init?.body)) as { accountId?: string }; + probeBodies.push(body); + await holdProbe; + const ids = body.accountId ? [body.accountId] : ["a", "b"]; + return Response.json({ results: ids.map(accountId => ({ accountId, status: "ok", httpStatus: 200, reason: null, message: null, latencyMs: 120 })) }); + } + return Response.json({}); + } }, + }); + (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + host = win.document.createElement("div") as unknown as HTMLElement; + win.document.body.appendChild(host as never); +}); + +afterEach(async () => { + if (root) { + const current = root; + await act(async () => { current.unmount(); }); + root = null; + } + for (const key of globals) Object.defineProperty(globalThis, key, { configurable: true, value: previous[key] }); +}); + +async function render(accounts: OAuthAccount[]) { + await act(async () => { + root ??= createRoot(host); + root.render(); + }); +} + +function button(label: string): HTMLButtonElement | undefined { + return (Array.from(host.querySelectorAll("button")) as unknown as HTMLButtonElement[]) + .find(candidate => (candidate.getAttribute("aria-label") ?? candidate.textContent ?? "").trim().startsWith(label)); +} + +const banned = (extra: Partial = {}): OAuthAccount => + ({ id: "a", active: false, paused: true, pauseDetails: bannedDetails, pauseEvidence: bannedEvidence, ...extra }); + +test("Test all stays disabled while an individual account check is running", async () => { + const gate = Promise.withResolvers(); + holdProbe = gate.promise; + await render([{ id: "a", active: true }, { id: "b", active: false }]); + await act(async () => { button("Test —")!.click(); }); + expect(button("Test all")?.disabled).toBe(true); + expect(host.querySelectorAll('button[aria-label^="Test —"]:disabled')).toHaveLength(2); + await act(async () => { gate.resolve(); }); + expect(button("Test all")?.disabled).toBe(false); + expect(probeBodies).toEqual([{ provider: "google-antigravity", accountId: "a" }]); +}); + +test("a banned account with no quota reading shows the ban notice and its reason once", async () => { + await render([banned()]); + expect(host.querySelector('[data-flag="banned"]')).not.toBeNull(); + expect(host.querySelectorAll(".aqt-banned").length).toBe(1); + expect(host.querySelector(".aqt-banned-text")?.textContent).toContain("Upstream refused this account"); + expect(host.textContent).toContain("This account was disabled upstream."); + expect(host.textContent).toContain("HTTP 403"); + // The generic paused hint would repeat the same fact, so a banned row leaves it out. + expect(host.textContent).not.toContain("Excluded from automatic selection"); + // Control: an ordinary pause still shows the hint, so the absence above is not vacuous. + await render([{ id: "a", active: false, paused: true }]); + expect(host.textContent).toContain("Excluded from automatic selection"); +}); + +test("a banned account that still has quota readings shows the notice in the pool cell, not twice", async () => { + const quota = { customWindows: [{ label: "Gem", percent: 10 }] }; + await render([banned({ quota })]); + expect(host.querySelectorAll(".aqt-banned").length).toBe(1); + expect(host.querySelector(".aqt-pool--banned .aqt-banned")).not.toBeNull(); + expect(host.querySelector(".aqt-detail .aqt-banned")).toBeNull(); + expect(host.textContent).toContain("HTTP 403"); +}); + +test("an account the upstream asked to verify reads Verification needed", async () => { + await render([{ id: "a", active: false, needsReauth: true, needsReauthReason: "verify_account" }]); + expect(host.querySelector('[data-flag="verify"]')).not.toBeNull(); + expect(host.querySelector(".aqt-flag")?.textContent).toBe("Verification needed"); +}); + +test("Test probes one account and Test all probes the provider; results land under the rows", async () => { + await render([{ id: "a", active: true }, { id: "b", active: false }]); + await act(async () => { button("Test —")!.click(); }); + expect(probeBodies).toEqual([{ provider: "google-antigravity", accountId: "a" }]); + expect(host.querySelector('[data-probe-status="ok"]')).not.toBeNull(); + + await act(async () => { button("Test all")!.click(); }); + expect(probeBodies.at(-1)).toEqual({ provider: "google-antigravity" }); + expect(host.querySelectorAll('[data-probe-status="ok"]').length).toBe(2); +}); diff --git a/gui/tests/provider-auth-target-capture.test.tsx b/gui/tests/provider-auth-target-capture.test.tsx index 145a41979f4..99523582a4b 100644 --- a/gui/tests/provider-auth-target-capture.test.tsx +++ b/gui/tests/provider-auth-target-capture.test.tsx @@ -5,7 +5,7 @@ import type { Root } from "react-dom/client"; import ProviderAuthPanel from "../src/components/provider-workspace/ProviderAuthPanel"; import { LanguageProvider } from "../src/i18n/provider"; import type { WorkspaceItem } from "../src/provider-workspace/catalog"; -import type { ProviderAuthHandlers } from "../src/components/provider-workspace/types"; +import type { OAuthAccountRow, ProviderAuthHandlers } from "../src/components/provider-workspace/types"; import { captureApiTarget, configureApiTargets } from "../src/api"; import { standaloneApiTargets } from "../src/api-targets"; @@ -39,6 +39,7 @@ function relayTargets(origin: string) { async function mountPanel(props: { item?: WorkspaceItem; + accounts?: OAuthAccountRow[]; loginCapture?: ReturnType; hint?: { provider: string; instructions?: string }; }) { @@ -51,7 +52,7 @@ async function mountPanel(props: { item={props.item ?? item()} apiBase="" busy - accounts={[]} + accounts={props.accounts ?? []} accountLoadState="ready" loginCapture={props.loginCapture} loginHint={props.hint ?? { provider: (props.item ?? item()).name, instructions: "Complete manual login" }} @@ -101,6 +102,30 @@ test("manual code uses the original login capture", async () => { expect(calls).toEqual(["/api/oauth/login/code"]); }); +test("cached Gemini quota keeps its timeout and distinct read timestamps in the table", async () => { + const now = Date.now(); + await mountPanel({ + item: item("google-antigravity"), + accounts: [{ + id: "acct1", active: true, quotaMode: "probe", quotaUnavailable: true, quotaFailure: "timeout", + quotaReadAt: now - 2 * 60_000, + quota: { updatedAt: now - 10 * 60_000, customWindows: [{ label: "Gem", percent: 20 }] }, + }], + }); + const table = host.querySelector('[data-testid="account-quota-table"]')!; + expect(table.textContent).toContain("80% left"); + expect(table.textContent).toContain("The quota request timed out."); + expect(table.textContent).toMatch(/Quota updated: 10m ago/); + expect(table.textContent).toMatch(/Last read: 2m ago/); + expect(table.textContent).not.toContain("Quota not read"); +}); + +test("an unrecognized upstream tier renders as text in the quota table", async () => { + await mountPanel({ item: item("google-antigravity"), accounts: [{ id: "acct1", active: true, plan: "__proto__" }] }); + const table = host.querySelector('[data-testid="account-quota-table"]')!; + expect(table.textContent).toContain("__proto__"); +}); + test("manual code without a login capture refuses instead of using the current target", async () => { let calls = 0; globalThis.fetch = (async () => { calls += 1; return Response.json({ ok: true }); }) as typeof fetch; diff --git a/gui/tests/provider-model-discovery-refresh.test.tsx b/gui/tests/provider-model-discovery-refresh.test.tsx new file mode 100644 index 00000000000..3b44d37d02f --- /dev/null +++ b/gui/tests/provider-model-discovery-refresh.test.tsx @@ -0,0 +1,109 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { LanguageProvider } from "../src/i18n/provider"; +import ProviderModelDiscovery from "../src/components/provider-workspace/ProviderModelDiscovery"; +import { buildConnectionProbeKey } from "../src/components/provider-workspace/use-provider-probe-state"; +import type { WorkspaceItem } from "../src/provider-workspace/catalog"; + +/** + * The manual "discover now" panel reads the recent arrivals once on mount and again from the + * refresh answer. A slow mount read that lands after the refresh must not put the pre-refresh + * list back, or the models the refresh just reported vanish under its own success line. + */ + +const DOM_GLOBALS = ["document", "window", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const; +const originalFetch = globalThis.fetch; +let previousLanguage: PropertyDescriptor | undefined; + +beforeEach(() => { + previousLanguage = Object.getOwnPropertyDescriptor(globalThis.navigator, "language"); + Object.defineProperty(globalThis.navigator, "language", { configurable: true, value: "en-US" }); +}); + +afterEach(() => { + globalThis.fetch = originalFetch; + if (previousLanguage) Object.defineProperty(globalThis.navigator, "language", previousLanguage); + else delete (globalThis.navigator as { language?: string }).language; +}); + +test.each(["success", "conflict"] as const)("manual discovery renders the %s response", async outcome => { + const previous = Object.fromEntries(DOM_GLOBALS.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); + const testWindow = new Window({ url: "http://localhost/" }); + const container = testWindow.document.createElement("div"); + testWindow.document.body.append(container); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + localStorage: { configurable: true, value: testWindow.localStorage }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + let releaseInitial!: (response: Response) => void; + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input); + if (url.endsWith("/api/model-discovery")) return new Promise(resolve => { releaseInitial = resolve; }); + if (url.endsWith("/api/model-discovery/refresh")) { + if (outcome === "conflict") { + return Response.json({ code: "discovery_in_progress", error: "server-provided text" }, { status: 409 }); + } + return Response.json({ + ok: true, discovery: { status: "ok" }, liveModelCount: 2, + newArrivals: [{ id: "fresh-model", at: "2026-11-12T00:00:00Z", state: "enabled" }], + recentArrivals: [ + { id: "old-model", at: "2026-11-01T00:00:00Z", state: "enabled" }, + { id: "fresh-model", at: "2026-11-12T00:00:00Z", state: "enabled" }, + ], + }); + } + return new Response(null, { status: 404 }); + }) as typeof fetch; + + let root: Root | undefined; + try { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(container); + root.render(); + }); + const button = container.querySelector("button") as unknown as HTMLButtonElement; + await act(async () => { button.click(); }); + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 0)); }); + if (outcome === "conflict") { + expect(container.querySelector('[role="status"]')?.textContent).toBe("Model discovery is already in progress. Try again shortly."); + expect(button.disabled).toBe(false); + await act(async () => { + releaseInitial(Response.json({ recentArrivals: { live: [{ id: "old-model", at: "2026-11-01T00:00:00Z" }] } })); + await new Promise(resolve => testWindow.setTimeout(resolve, 0)); + }); + expect(container.textContent).toContain("old-model"); + return; + } + expect(container.textContent).toContain("fresh-model"); + + // The mount read answers last, with the roster from before the refresh. + await act(async () => { + releaseInitial(Response.json({ recentArrivals: { live: [{ id: "old-model", at: "2026-11-01T00:00:00Z" }] } })); + await new Promise(resolve => testWindow.setTimeout(resolve, 0)); + }); + expect(container.textContent).toContain("fresh-model"); + expect(container.textContent).toContain("old-model"); + } finally { + if (root) await act(async () => root?.unmount()); + container.remove(); + testWindow.close(); + for (const key of DOM_GLOBALS) { + const descriptor = previous[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else delete (globalThis as Record)[key]; + } + } +}); + +test("a change in server-side Vertex verification discards a retained connection probe", () => { + const item = { name: "google-vertex", adapter: "google", baseUrl: "https://aiplatform.googleapis.com" } as WorkspaceItem; + const verified = buildConnectionProbeKey("http://localhost", { ...item, vertexCredentialVerified: true }); + const lapsed = buildConnectionProbeKey("http://localhost", { ...item, vertexCredentialVerified: false }); + expect(lapsed).not.toBe(verified); + expect(buildConnectionProbeKey("http://localhost", item)).toBe(lapsed); +}); diff --git a/gui/tests/provider-quota-refresh-controls.test.tsx b/gui/tests/provider-quota-refresh-controls.test.tsx index 73dab6a7ed8..352f34fa7fd 100644 --- a/gui/tests/provider-quota-refresh-controls.test.tsx +++ b/gui/tests/provider-quota-refresh-controls.test.tsx @@ -16,6 +16,7 @@ import ProviderAuthPanel from "../src/components/provider-workspace/ProviderAuth import { LanguageProvider } from "../src/i18n/provider"; import { en } from "../src/i18n/en"; import type { WorkspaceItem } from "../src/provider-workspace/catalog"; +import { planDisplayName } from "../src/provider-workspace/account-quota-table"; import type { ProviderAuthHandlers } from "../src/components/provider-workspace/types"; const globals = ["document", "window", "navigator", "localStorage", "sessionStorage", "IS_REACT_ACT_ENVIRONMENT"] as const; @@ -209,7 +210,8 @@ test.each(["google-antigravity", "anthropic"])("%s OAuth accounts expose pause a ]} authHandlers={handlers} />); const resume = findButton("Resume"); expect(resume).not.toBeNull(); - expect(resume!.getAttribute("title")).toBe(en["pws.accountPausedHint"]); + // The paused explanation now lives in the account's detail row of the quota table, not on the Resume button. + expect(host.querySelector(".aqt-detail")?.textContent).toContain(en["pws.accountPausedHint"]); expect(host.textContent).toContain(en["pws.accountPausedHint"]); expect(host.textContent).not.toContain(en["codexAuth.pausedHint"]); expect(en["pws.accountPausedHint"]).not.toBe(en["codexAuth.pausedHint"]); @@ -277,14 +279,18 @@ test("Antigravity badges expose canonical tier IDs across locales and preserve a const view = (plan?: string | null, paused = false, needsReauth = false, pausingAccountId: string | null = null) => ; - const main = () => host.querySelector(".pwi-auth-row-main") as HTMLButtonElement; - const badge = () => main().querySelector(".pwi-auth-row-heading .badge"); + const main = () => host.querySelector(".aqt-account-main") as HTMLButtonElement; + // A known plan renders as a green badge in the Plan column; an unknown plan renders a muted placeholder instead. + const badge = () => host.querySelector(".aqt-plan .badge-green"); const control = (text: string) => Array.from(host.querySelectorAll("button")).find(button => button.textContent?.trim() === text) as HTMLButtonElement; for (const plan of ["free-tier", "gemini-pro", "gemini-ultra", "standard-tier"]) { await render(view(plan)); - expect(badge()?.textContent).toBe(plan); - expect(main().getAttribute("aria-label")).toContain(` — ${plan} — `); + // The table shows the product name; the canonical upstream tier ID stays reachable in the badge tooltip. + const display = planDisplayName(plan)!; + expect(badge()?.textContent).toBe(display); + expect(badge()?.getAttribute("title")).toContain(plan); + expect(main().getAttribute("aria-label")).toContain(` — ${display} — `); expect(main().getAttribute("aria-current")).toBe("true"); expect(main().disabled).toBe(false); } @@ -292,7 +298,8 @@ test("Antigravity badges expose canonical tier IDs across locales and preserve a expect(calls).toEqual(["pause"]); await render(view("gemini-pro", true)); - expect(badge()?.textContent).toBe("gemini-pro"); + expect(badge()?.textContent).toBe(planDisplayName("gemini-pro")); + expect(badge()?.getAttribute("title")).toContain("gemini-pro"); expect(main().disabled).toBe(true); await act(async () => { control("恢复")!.click(); }); expect(calls).toEqual(["pause", "resume"]); diff --git a/gui/tests/provider-revalidation-policy.test.tsx b/gui/tests/provider-revalidation-policy.test.tsx index ad82aba3668..b6ca5bdbce7 100644 --- a/gui/tests/provider-revalidation-policy.test.tsx +++ b/gui/tests/provider-revalidation-policy.test.tsx @@ -312,7 +312,8 @@ for (const kind of ["oauth", "api-key"] as const) { .find(button => /Accounts|Keys/.test(button.textContent ?? "")); expect(accountsTab).toBeDefined(); await act(async () => { accountsTab!.click(); }); - expect(container.querySelector(".pwi-auth-acct--active")?.textContent).toContain("Choice A"); + const activeAccountSelector = kind === "oauth" ? 'button[aria-current="true"]' : ".pwi-auth-acct--active"; + expect(container.querySelector(activeAccountSelector)?.textContent).toContain("Choice A"); expect(subscriptions).toBe(1); const quotaReads = () => reads.filter(path => path.includes("quota=1") || path.startsWith("/api/provider-quotas")).length; const initialQuotas = quotaReads(); @@ -321,8 +322,8 @@ for (const kind of ["oauth", "api-key"] as const) { expect(reads.length).toBeGreaterThan(initialReads); selected = "b"; await act(async () => { send("account-selection", { provider: name, kind, revision: 1 }); }); - expect(container.querySelector(".pwi-auth-acct--active")?.textContent).toContain("Choice B"); - expect(container.querySelector(".pwi-auth-acct--active")?.textContent).not.toContain("Choice A"); + expect(container.querySelector(activeAccountSelector)?.textContent).toContain("Choice B"); + expect(container.querySelector(activeAccountSelector)?.textContent).not.toContain("Choice A"); expect(quotaReads()).toBe(initialQuotas); expect(subscriptions).toBe(1); expect(pollBucketCountForTests()).toBe(1); @@ -358,7 +359,7 @@ for (const kind of ["oauth", "api-key"] as const) { await retry(250); expect(subscriptions).toBe(2); await act(async () => { send("ready", { revision: 0 }); }); - expect(container.querySelector(".pwi-auth-acct--active")?.textContent).toContain("Choice A"); + expect(container.querySelector(activeAccountSelector)?.textContent).toContain("Choice A"); expect(quotaReads()).toBe(initialQuotas); await act(async () => { stream.error(new Error("connection interrupted")); }); @@ -372,7 +373,7 @@ for (const kind of ["oauth", "api-key"] as const) { expect(subscriptions).toBe(8); selected = "b"; await act(async () => { send("ready", { revision: 0 }); }); - expect(container.querySelector(".pwi-auth-acct--active")?.textContent).toContain("Choice B"); + expect(container.querySelector(activeAccountSelector)?.textContent).toContain("Choice B"); expect(quotaReads()).toBe(initialQuotas); // Cleanup cancels scheduled retries, and a callback already dequeued cannot orphan a loop. diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index a21cc111f3c..38be0f6b60a 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-release-signing.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", "layout-test-hygiene.json", "layout-codex-journal.json", "layout-upload-reduction.json"], - "explicit": { "web-search-local-deadline-provenance.test.ts": "web-search", "kimi-monthly-quota.test.ts": "providers", "vertex-adc-verified.test.ts": "adapters/google", "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": { "gui-account-quota-table.test.ts": "gui", "account-probe-routes.test.ts": "server", "web-search-local-deadline-provenance.test.ts": "web-search", "kimi-monthly-quota.test.ts": "providers", "vertex-adc-verified.test.ts": "adapters/google", "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/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 7f29171c848..7b6470b3737 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -26,8 +26,8 @@ These answer in the CLI head and never reach the proxy, so they work with nothin | Chapter | Declared capabilities | |---|---| | [lifecycle](01_surface_lifecycle.md) | 14 | -| [providers-models](01_surface_providers-models.md) | 53 | -| [accounts](01_surface_accounts.md) | 43 | +| [providers-models](01_surface_providers-models.md) | 54 | +| [accounts](01_surface_accounts.md) | 44 | | [agents-routing](01_surface_agents-routing.md) | 71 | | [integrations](01_surface_integrations.md) | 41 | | [observe-system](01_surface_observe-system.md) | 105 | @@ -487,6 +487,10 @@ Original invocation order. These headings preserve links to the previous single- [Read-oriented task](01_surface_providers-models.md#ocx-models-new-arrivals) +### `ocx models discover` + +[State-changing task](01_surface_providers-models.md#ocx-models-discover) + ### `ocx models context status` [Read-oriented task](01_surface_providers-models.md#ocx-models-context-status) @@ -619,6 +623,10 @@ Original invocation order. These headings preserve links to the previous single- [State-changing task](01_surface_accounts.md#ocx-account-add-key) +### `ocx account probe` + +[Read-oriented task](01_surface_accounts.md#ocx-account-probe) + ### `ocx account import` [State-changing task](01_surface_accounts.md#ocx-account-import) @@ -1661,6 +1669,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 403 -- of those, state-changing: 253 +- declared capabilities: 405 +- of those, state-changing: 254 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_accounts.md b/skills/ocx/references/01_surface_accounts.md index 3d7ef11e347..bc297dbd64d 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` @@ -559,6 +559,25 @@ State-changing: yes. JSON mode: `envelope`. - API-key providers only. Requires non-TTY stdin and reads one secret line; never put plaintext keys in command arguments or agent transcripts. This imports an upstream credential, not an OpenCodex access-key creation workflow. +### `ocx account probe` + +Usage: `ocx account probe google-antigravity [] [--json]` + +Test stored accounts one by one with their own tokens, read-only. + +State-changing: no. JSON mode: `payload`. + +| Method | Route | +|---|---| +| GET | `/api/oauth/accounts` | +| POST | `/api/oauth/accounts/probe` | + +| Flag | Value | Meaning | +|---|---|---| +| `--json` | boolean | Emit per-account status, HTTP code, reason and quota windows. | + +- Statuses: ok, paused, token_expired, suspended, verification_required, rate_limited, permission_denied, error. Sends one retrieveUserQuotaSummary request per account with its stored token; paused accounts are skipped without a request, and expired tokens are reported, never refreshed. Only google-antigravity is supported. + ### `ocx account import` Usage: `ocx account import google-antigravity --format cockpit-tools (--file |--stdin) [--accept-antigravity-risk] [--json]` diff --git a/skills/ocx/references/01_surface_providers-models.md b/skills/ocx/references/01_surface_providers-models.md index 60d05132b11..a92feafcb98 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. | + +- Refreshes one provider's model list. New models follow the configured new-model policy. If discovery is already running for that provider, the route returns HTTP 409 (`discovery_in_progress`). During cooldown it returns the recorded failure. Providers with liveModels off report applicable:false. + ### `ocx models context status` Usage: `ocx models context status [--json]` diff --git a/src/claude/desktop-3p.ts b/src/claude/desktop-3p.ts index 3b91d3b26c4..f5e612862c2 100644 --- a/src/claude/desktop-3p.ts +++ b/src/claude/desktop-3p.ts @@ -171,8 +171,9 @@ function collectDesktop3pModels( routedModels: Array, profile?: OcxClaudeDesktopProfile, nativeContextCap?: NativeContextLimitsInput, -): { models: Desktop3pModelEntry[]; routes: string[]; registry: Map; realAnthropicIds: Set } { +) { const registry = new Map(); + const aliasesByRoute = new Map(); const models: Desktop3pModelEntry[] = []; // routes[i] is the route models[i] serves; visibility filters by route, never by alias. const routes: string[] = []; @@ -198,7 +199,6 @@ function collectDesktop3pModels( } satisfies DesktopProfileModel)); const reconciled = reconcileDesktopProfile(profile, profileModels); const rendered = renderDesktopProfile(reconciled, profileModels); - const aliasesByRoute = new Map(); for (const model of rendered) { const realAnthropic = model.route.startsWith("anthropic/claude-"); if (!realAnthropic && realAnthropicIds.has(model.name)) { @@ -251,11 +251,9 @@ function collectDesktop3pModels( registry.set(legacy, model.route); } } - desktop3pAliasesByRoute = aliasesByRoute; - return { models, routes, registry, realAnthropicIds }; + return { models, routes, registry, aliasesByRoute, realAnthropicIds }; } - const aliasesByRoute = new Map(); const emittedNames = new Set(); for (const { provider, id, contextWindow } of candidates) { const route = `${provider}/${id}`; @@ -310,8 +308,13 @@ function collectDesktop3pModels( } if (models[0]) models[0].isFamilyDefault = true; + return { models, routes, registry, aliasesByRoute, realAnthropicIds }; +} + +function installDesktop3pRegistry({ registry, aliasesByRoute, realAnthropicIds }: ReturnType): void { + desktop3pRegistry = registry; desktop3pAliasesByRoute = aliasesByRoute; - return { models, routes, registry, realAnthropicIds }; + desktop3pRealAnthropicIds = realAnthropicIds; } /** Build and install the registry used to decode Desktop aliases. */ @@ -321,10 +324,9 @@ export function buildDesktop3pRegistry( profile?: OcxClaudeDesktopProfile, nativeContextCap?: NativeContextLimitsInput, ): Map { - const { registry, realAnthropicIds } = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap); - desktop3pRegistry = registry; - desktop3pRealAnthropicIds = realAnthropicIds; - return registry; + const collected = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap); + installDesktop3pRegistry(collected); + return collected.registry; } /** Generate Claude Desktop 3P model entries from the proxy's available models. */ @@ -348,9 +350,9 @@ export function generateDesktop3pModels( nativeContextCap?: NativeContextLimitsInput, options: Desktop3pModelOptions = {}, ): Desktop3pModelEntry[] { - const { models: all, routes, registry, realAnthropicIds } = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap); - desktop3pRegistry = registry; - desktop3pRealAnthropicIds = realAnthropicIds; + const collected = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap); + installDesktop3pRegistry(collected); + const { models: all, routes } = collected; let models = filterDesktopModelsByVisibility(all, routes, options.visibility); if (models.length === 0 && all.length > 0) { // An empty static list leaves Desktop with no usable picker. The dashboard refuses to save @@ -408,7 +410,9 @@ export function activeDesktop3pAlias(provider: string, modelId: string): string /** Discovery cannot offer a skipped alias or one owned by a different route. */ export function resolvableDesktop3pAlias(provider: string, modelId: string): string | undefined { - if (provider === "anthropic" && modelId.startsWith("claude-")) return modelId; + if (provider === "anthropic" && modelId.startsWith("claude-")) { + return desktop3pRealAnthropicIds.has(modelId) ? modelId : undefined; + } const alias = activeDesktop3pAlias(provider, modelId); return resolveDesktop3pAlias(alias) === `${provider}/${modelId}` ? alias : undefined; } diff --git a/src/cli/account-probe.ts b/src/cli/account-probe.ts new file mode 100644 index 00000000000..bdba7a39326 --- /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 !== "google-antigravity" || positional.length > 2 || requested?.startsWith("-")) { + 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 d8f3c5187c0..49a530afe76 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