diff --git a/AGENTS.md b/AGENTS.md index 5ec4b9461..f0ce6eed6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1773,6 +1773,7 @@ during the wait. ### Auth and model config - Auth flows go through `ompweb-omp` commands (`get_login_providers`, `login`, `get_logout_accounts`, `logout`) against the omp child process; credentials live in omp's `agent.db` (SQLite) which omp-web never touches directly. `/api/auth/accounts/[provider]` lists stored accounts and removes one by `credentialId`; omp without those commands reports `supported: false` and the UI falls back to the read-only `omp usage` account list. +- Provider Usage (`/api/provider-usage/accounts`, `lib/provider-usage.ts`) joins `omp usage --json` reports to the runner's `get_usage_accounts` by identity (`reportMatchesAccount`, mirroring `omp usage`; a provider's only report and only account match without one, as Copilot credentials carry no identity). A usage limit is omp's `auth.accountPolicies[].reservePct` (100 - limit) and "preferred" its `priority: 1`, both in config.yml; a selector must match exactly one stored account or omp rejects the provider's routing. Pause is omp's own tombstone (`credentials.disable` with cause `paused in omp-web`); omp cannot revive a tombstone, so `set_account_paused` resumes by clearing that cause in `agent.db` from the runner. Account names live in the `accountNames` web setting. - Linked hosts with `shareCredentials` read this machine's credentials through `lib/omp/auth-broker.ts`, the `omp auth-broker serve` child (the token comes from `omp auth-broker token` and stays in the server process; a refused token stops the child and the next request starts a new one). The broker reloads the store on every snapshot, so a login or logout in Settings reaches every omp process a sharing host starts afterwards; a running process picks it up the next time it is used (omp stops listening for updates after 20 seconds without activity and resumes on its next use) and keeps the access tokens and API keys it has already loaded until it ends. - The Models panel reads and writes `models.yml` in the omp agent directory (`~/.omp/agent/models.yml`, `.yaml` fallback). - API-key status endpoints must never return the raw key. diff --git a/CHANGELOG.md b/CHANGELOG.md index ec584eb19..253a7801e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,13 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Added + +- **Provider Usage shows one row per account with every limit window at once.** Splits such as Anthropic's Fable bucket or Antigravity's model quotas merge into their account; open a row for each split's reset time. The 5H/7D switch is gone. Each quota gets its own meter line; drag an account to reorder, double-click it to rename it. An open row sets the account's usage limit (omp's per-account reserve: above it omp uses the provider's other accounts first), marks it preferred (omp's account priority: used first while below its limit), pauses it without signing out, and opens it in API Keys & Providers. + ### Fixed +- **Provider Usage keeps accounts visible when their limits are unavailable.** Paused accounts can still be resumed, and a failed quota fetch no longer removes stored account names. Signing out drops the account instead of leaving its cached limits behind. - **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did. - **GitHub workflow watches no longer regress to stale run states.** Workflow updates retain GitHub's run timestamp and ignore older snapshots for the same or an earlier attempt, so a delayed `queued` response cannot follow a newer `in_progress` delivery. - **Keep sidebar transcript results aligned with expandable hits on every linked host.** Each daemon now searches its own active conversations, ignoring abandoned branches and pre-compaction messages. diff --git a/app/api/auth/accounts/[provider]/route.ts b/app/api/auth/accounts/[provider]/route.ts index ba9a21738..5181f015b 100644 --- a/app/api/auth/accounts/[provider]/route.ts +++ b/app/api/auth/accounts/[provider]/route.ts @@ -1,5 +1,6 @@ import { invalidateModelsCache } from "@/lib/models-cache"; import { runUtilityCommand } from "@/lib/omp/rpc-utility"; +import { invalidateUsageCache } from "@/lib/provider-usage"; /** Entry of omp's `get_logout_accounts` response. Labels never carry a raw key. */ interface OmpProviderAccount { @@ -47,6 +48,7 @@ export async function DELETE(req: Request, { params }: { params: Promise<{ provi try { await runUtilityCommand({ type: "logout", providerId: provider, credentialId }, 60_000); invalidateModelsCache(); + invalidateUsageCache(); return Response.json({ ok: true }); } catch (error) { return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); diff --git a/app/api/auth/login/[provider]/route.ts b/app/api/auth/login/[provider]/route.ts index 920ce2651..3a2201898 100644 --- a/app/api/auth/login/[provider]/route.ts +++ b/app/api/auth/login/[provider]/route.ts @@ -3,6 +3,7 @@ import { invalidateModelsCache } from "@/lib/models-cache"; import { enableProvider } from "@/lib/omp/model-roles"; import { RpcProcess, type RpcFrame } from "@/lib/omp/rpc-process"; import { disposeUtilityRpc } from "@/lib/omp/rpc-utility"; +import { invalidateUsageCache } from "@/lib/provider-usage"; /** * Interactive login over a dedicated headless runner. The runner drives the @@ -164,6 +165,7 @@ export async function GET( await child.sendCommand({ type: "login", providerId: provider }, LOGIN_TIMEOUT_MS); enableProvider(provider); invalidateModelsCache(); + invalidateUsageCache(); disposeUtilityRpc(); send({ type: "success" }); } catch (error) { diff --git a/app/api/provider-usage/accounts/route.ts b/app/api/provider-usage/accounts/route.ts new file mode 100644 index 000000000..52e33bbdd --- /dev/null +++ b/app/api/provider-usage/accounts/route.ts @@ -0,0 +1,68 @@ +import { invalidateModelsCache } from "@/lib/models-cache"; +import { getProviderUsageAccounts, renameProviderUsageAccount, updateProviderUsageAccount } from "@/lib/provider-usage"; +import { saveWebServerSettings } from "@/lib/web-settings"; +import { isRecord } from "@/lib/type-guards"; + +const PROVIDER_RE = /^[A-Za-z0-9._:/-]{1,200}$/; + +export async function GET(request: Request) { + try { + return Response.json(await getProviderUsageAccounts(new URL(request.url).searchParams.get("refresh") === "true")); + } catch { + return Response.json( + { error: "Provider usage is currently unavailable", code: "provider_usage_unavailable" }, + { status: 502 }, + ); + } +} + +/** + * Body `{ order }` saves the rows' order (`ProviderUsageAccount.key`s); `{ key, name }` names an account + * (`name: null` or blank clears it); `{ provider, credentialId, paused?, limitPercent?, priority? }` + * changes a stored one, `null` clearing a limit or priority. + */ +export async function PATCH(request: Request) { + const body: unknown = await request.json().catch(() => null); + if (!isRecord(body)) return Response.json({ error: "Body must be a JSON object" }, { status: 400 }); + if (body.order !== undefined) { + const { order } = body; + if (!Array.isArray(order) || order.length > 500 || order.some((key) => typeof key !== "string" || key.length > 300)) { + return Response.json({ error: "order must be an array of at most 500 account keys" }, { status: 400 }); + } + saveWebServerSettings({ accountOrder: order as string[] }); + return Response.json({ ok: true }); + } + if (body.key !== undefined) { + const { key, name } = body; + if (typeof key !== "string" || key.length > 300 || (name !== null && (typeof name !== "string" || name.length > 80))) { + return Response.json({ error: "key must be a string and name a string of at most 80 characters, or null" }, { status: 400 }); + } + renameProviderUsageAccount(key, name); + return Response.json({ ok: true }); + } + const { provider, credentialId, paused, limitPercent, priority } = body; + if (typeof provider !== "string" || !PROVIDER_RE.test(provider) || !Number.isSafeInteger(credentialId)) { + return Response.json({ error: "provider and an integer credentialId are required" }, { status: 400 }); + } + if (paused !== undefined && typeof paused !== "boolean") { + return Response.json({ error: "paused must be a boolean" }, { status: 400 }); + } + if (limitPercent !== undefined && limitPercent !== null + && (!Number.isInteger(limitPercent) || (limitPercent as number) < 1 || (limitPercent as number) > 100)) { + return Response.json({ error: "limitPercent must be an integer from 1 to 100, or null" }, { status: 400 }); + } + if (priority !== undefined && priority !== null && (!Number.isInteger(priority) || Math.abs(priority as number) > 1000)) { + return Response.json({ error: "priority must be an integer from -1000 to 1000, or null" }, { status: 400 }); + } + try { + await updateProviderUsageAccount(provider, credentialId as number, { + ...(paused !== undefined ? { paused } : {}), + ...(limitPercent !== undefined ? { limitPercent: limitPercent as number | null } : {}), + ...(priority !== undefined ? { priority: priority as number | null } : {}), + }); + if (paused !== undefined) invalidateModelsCache(); + return Response.json({ ok: true }); + } catch (error) { + return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 }); + } +} diff --git a/app/globals.css b/app/globals.css index 2b734e313..ea802835b 100644 --- a/app/globals.css +++ b/app/globals.css @@ -2662,6 +2662,54 @@ span.token.table { overflow: hidden; } +.provider-usage-card { + transition: background var(--dur-med) var(--ease-out-warm); +} + +.provider-usage-badges { + display: inline-flex; + align-items: center; + gap: 5px; + flex-shrink: 0; + overflow: hidden; + max-width: 140px; + opacity: 1; + transform: scale(1); + transform-origin: right center; + transition: max-width var(--dur-med) var(--ease-out-warm), + opacity var(--dur-fast) var(--ease-out-warm), + transform var(--dur-med) var(--ease-out-warm), + margin-left var(--dur-med) var(--ease-out-warm); +} + +.provider-usage-badges.is-hidden { + max-width: 0; + opacity: 0; + transform: scale(0.92); + margin-left: -6px; + pointer-events: none; +} + +.provider-usage-action-btn { + transition: background var(--dur-fast) var(--ease-out-warm), + color var(--dur-fast) var(--ease-out-warm), + border-color var(--dur-fast) var(--ease-out-warm), + opacity var(--dur-fast) var(--ease-out-warm); +} + +.provider-usage-action-btn:hover:not(:disabled) { + background: var(--bg-hover) !important; + border-color: var(--text-dim) !important; +} + +@media (prefers-reduced-motion: reduce) { + .accordion-flow, + .provider-usage-card, + .provider-usage-badges, + .provider-usage-action-btn { + transition: none !important; + } +} .chevron-smooth { transition: transform var(--dur-med) var(--ease-out-warm); } diff --git a/components/AppShell-provider-usage.test.mjs b/components/AppShell-provider-usage.test.mjs index b07c42474..eb5254a04 100644 --- a/components/AppShell-provider-usage.test.mjs +++ b/components/AppShell-provider-usage.test.mjs @@ -3,17 +3,8 @@ import assert from "node:assert/strict"; import test from "node:test"; const { act, cleanup, renderHook } = await import("@testing-library/react/pure.js"); -const { useProviderUsage, usageBucketLabel } = await import("./AppShell-provider-usage.ts"); +const { useProviderUsage } = await import("./AppShell-provider-usage.ts"); -test("usageBucketLabel distinguishes Anthropic tiers and Antigravity buckets (#284)", () => { - assert.equal(usageBucketLabel({ provider: "anthropic", tier: "fable" }), "Fable"); - assert.equal(usageBucketLabel({ provider: "anthropic" }), undefined); - assert.equal(usageBucketLabel({ provider: "google-antigravity", bucket: "Gemini" }), "Gemini"); - assert.equal(usageBucketLabel({ provider: "google-antigravity", bucket: "Claude & GPT (shared)" }), "Claude & GPT (shared)"); - assert.equal(usageBucketLabel({ provider: "google-antigravity", bucket: "Gemini", tier: "pro" }), "Gemini"); - // Other providers' tiers are quota tiers, not bucket names. - assert.equal(usageBucketLabel({ provider: "openai-codex", tier: "pro" }), undefined); -}); const snapshot = (percent) => ({ reports: [{ provider: "provider", fiveHour: { percent } }] }); test("manual refresh gets fresh limits on older browsers while automatic polling stays silent", async () => { @@ -25,14 +16,16 @@ test("manual refresh gets fresh limits on older browsers while automatic polling let finishPoll; let freshPercent = 10; let cachedPercent = 10; + let unavailable = false; try { delete URLSearchParams.prototype.size; window.setInterval = (callback) => { poll = callback; return 1; }; window.clearInterval = () => {}; globalThis.fetch = async (url) => { if (new URL(url, "http://localhost").searchParams.get("refresh") === "true") cachedPercent = freshPercent; + const response = unavailable ? new Response(null, { status: 502 }) : Response.json(snapshot(cachedPercent)); if (finishPoll) await new Promise((resolve) => { finishPoll.resolve = resolve; }); - return { ok: true, json: async () => snapshot(cachedPercent) }; + return response; }; const { result, unmount } = renderHook(() => useProviderUsage("", 300_000)); await act(async () => {}); @@ -61,6 +54,40 @@ test("manual refresh gets fresh limits on older browsers while automatic polling assert.equal(await queuedRefresh, true); }); assert.equal(result.current.snapshot.reports[0].fiveHour.percent, 95, "manual refresh during a background poll must still fetch fresh limits"); + // A reload() after a mutation must not settle on a pre-update GET that is still in flight. + cachedPercent = 40; + finishPoll = {}; + act(() => poll()); + cachedPercent = 65; + let reloaded; + act(() => { reloaded = result.current.reload(); }); + await act(async () => { + const resolve = finishPoll.resolve; + finishPoll = undefined; + resolve(); + assert.equal(await reloaded, true); + }); + assert.equal(result.current.snapshot.reports[0].fiveHour.percent, 65, "reload during an in-flight GET must issue a post-mutation non-forced GET"); + unavailable = true; + await act(async () => { assert.equal(await result.current.reload(), false); }); + assert.equal(result.current.error, true); + assert.equal(result.current.snapshot.reports[0].fiveHour.percent, 65, "a failed refresh retains the last visible snapshot"); + + unavailable = false; + finishPoll = {}; + act(() => poll()); + unavailable = true; + let afterLogout; + act(() => { afterLogout = result.current.reload({ invalidate: true }); }); + await act(async () => { + const finish = finishPoll.resolve; + finishPoll = undefined; + finish(); + assert.equal(await afterLogout, false); + }); + assert.equal(result.current.error, true); + assert.equal(result.current.snapshot, null, "a pre-logout poll cannot bring back invalidated rows"); + unavailable = false; finishPoll = {}; let cancelled; act(() => { cancelled = result.current.refresh(); }); diff --git a/components/AppShell-provider-usage.ts b/components/AppShell-provider-usage.ts index 232465015..64942ee8b 100644 --- a/components/AppShell-provider-usage.ts +++ b/components/AppShell-provider-usage.ts @@ -1,5 +1,8 @@ import { useState, useEffect, useRef, useCallback } from "react"; import type { ProviderUsageReport, ProviderUsageSnapshot } from "@/lib/provider-usage-types"; +import { isRecord } from "@/lib/type-guards"; + +export const PROVIDER_ACCOUNTS_CHANGED = "omp-provider-accounts-change"; export function formatUsageReset(value: number, unit: "minutes" | "hours"): string { if (unit === "minutes") { @@ -14,23 +17,6 @@ export function formatUsageReset(value: number, unit: "minutes" | "hours"): stri return hours > 0 ? `${days}d ${hours}h` : `${days}d`; } -/** - * Label that distinguishes one usage row from another row for the same - * provider and account, or undefined when the row needs none. - * Antigravity rows carry their bucket ("Gemini", "Claude & GPT (shared)"); - * Anthropic rows carry their tier, capitalised ("Fable", "Opus", "Sonnet") - * — the shared account-wide row has no tier and stays plain "Anthropic". - * Other providers' tiers are quota tiers, not bucket names, so they are - * not promoted to a label here. - */ -export function usageBucketLabel(report: ProviderUsageReport): string | undefined { - if (report.bucket) return report.bucket; - if (report.provider === "anthropic" && report.tier) { - return report.tier.charAt(0).toUpperCase() + report.tier.slice(1); - } - return undefined; -} - export function usageTone(percent: number): string { if (percent >= 80) return "var(--status-error)"; if (percent >= 50) return "var(--status-warning)"; @@ -62,16 +48,24 @@ export function formatProviderUsageReport(report: ProviderUsageReport, noLimitsL return parts.join(" · "); } -export type ProviderUsageState = { - snapshot: ProviderUsageSnapshot | null; +export type ProviderUsageState = { + snapshot: T | null; loading: boolean; error: boolean; }; -export function useProviderUsage(query: string | null, refreshMs?: number): ProviderUsageState & { refresh: () => Promise } { - const [state, setState] = useState({ snapshot: null, loading: false, error: false }); - const refreshRef = useRef<() => Promise>(async () => false); - const refresh = useCallback(() => refreshRef.current(), []); +type UsageLoad = "poll" | "reload" | "force" | "invalidate"; + +/** Polls `path` (`refresh()` asks omp for fresh limits, `reload()` only re-reads omp-web's view). */ +export function useProviderUsage( + query: string | null, + refreshMs?: number, + path = "/api/provider-usage", +): ProviderUsageState & { refresh: () => Promise; reload: (options?: { invalidate?: boolean }) => Promise } { + const [state, setState] = useState>({ snapshot: null, loading: false, error: false }); + const refreshRef = useRef<(mode: UsageLoad) => Promise>(async () => false); + const refresh = useCallback(() => refreshRef.current("force"), []); + const reload = useCallback((options?: { invalidate?: boolean }) => refreshRef.current(options?.invalidate ? "invalidate" : "reload"), []); useEffect(() => { if (query === null) { setState({ snapshot: null, loading: false, error: false }); @@ -81,26 +75,37 @@ export function useProviderUsage(query: string | null, refreshMs?: number): Prov setState({ snapshot: null, loading: true, error: false }); let inFlight: Promise | undefined; let inFlightForced = false; - const load = (force = false): Promise => { + let generation = 0; + const load = (mode: UsageLoad = "poll"): Promise => { if (controller.signal.aborted) return Promise.resolve(false); + if (mode === "invalidate") { + generation += 1; + setState({ snapshot: null, loading: true, error: false }); + } if (inFlight) { - return force && !inFlightForced ? inFlight.then(() => load(true)) : inFlight; + if (mode === "force" && !inFlightForced) return inFlight.then(() => load("force")); + if (mode === "reload" || mode === "invalidate") return inFlight.then(() => load("poll")); + return inFlight; } + const force = mode === "force"; if (force) setState((previous) => ({ ...previous, loading: true, error: false })); const params = new URLSearchParams(query); if (force) params.set("refresh", "true"); const queryString = params.toString(); inFlightForced = force; + const startedAt = generation; inFlight = (async () => { try { - const response = await fetch(`/api/provider-usage${queryString ? `?${queryString}` : ""}`, { signal: controller.signal }); + const response = await fetch(`${path}${queryString ? `?${queryString}` : ""}`, { signal: controller.signal }); if (!response.ok) throw new Error(`HTTP ${response.status}`); - const snapshot = await response.json() as ProviderUsageSnapshot; - if (controller.signal.aborted) return false; + const snapshot = await response.json() as T; + if (controller.signal.aborted || generation !== startedAt) return false; setState({ snapshot, loading: false, error: false }); - return true; + return !isRecord(snapshot) || snapshot.usageUnavailable !== true; } catch { - if (!controller.signal.aborted) setState({ snapshot: null, loading: false, error: true }); + if (!controller.signal.aborted && generation === startedAt) { + setState((previous) => ({ ...previous, loading: false, error: true })); + } return false; } finally { inFlight = undefined; @@ -108,7 +113,7 @@ export function useProviderUsage(query: string | null, refreshMs?: number): Prov })(); return inFlight; }; - refreshRef.current = () => load(true); + refreshRef.current = load; void load(); const interval = refreshMs ? window.setInterval(() => void load(), refreshMs) : undefined; return () => { @@ -116,6 +121,6 @@ export function useProviderUsage(query: string | null, refreshMs?: number): Prov controller.abort(); if (interval !== undefined) window.clearInterval(interval); }; - }, [query, refreshMs]); - return { ...state, refresh }; + }, [query, refreshMs, path]); + return { ...state, refresh, reload }; } diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 85795fb82..089d65a5a 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -168,6 +168,8 @@ export function AppShell({ appName }: { appName: string }) { const [explorerRefreshKey, setExplorerRefreshKey] = useState(0); const [explorerRefreshing, setExplorerRefreshing] = useState(false); const [settingsTab, setSettingsTab] = useState(null); + // A new object per request, so asking for the same provider again re-selects it. + const [settingsProvider, setSettingsProvider] = useState<{ id: string } | null>(null); const [archiveBrowserOpen, setArchiveBrowserOpen] = useState(false); const [modelsRefreshKey, setModelsRefreshKey] = useState(0); const [sidebarOpen, setSidebarOpen] = useState(true); @@ -2040,6 +2042,10 @@ export function AppShell({ appName }: { appName: string }) { usageVisible={providerUsageVisible} settingsOpen={Boolean(settingsTab)} onOpenSettings={() => setSettingsTab((prev) => prev ? null : "general")} + onOpenProviderSettings={(provider) => { + setSettingsProvider({ id: provider }); + setSettingsTab("providers"); + }} onOpenArchive={() => setArchiveBrowserOpen(true)} navigation={sidebarNavigation} updateAvailable={Boolean(appUpdate?.updateAvailable)} @@ -2247,6 +2253,7 @@ export function AppShell({ appName }: { appName: string }) { remoteHost={settingsHostId !== undefined} cluster={clusterSettings} sessionId={selectedSession?.id ?? null} + providerFocus={settingsProvider} onModelsSaved={() => setModelsRefreshKey((k) => k + 1)} onPluginsReloaded={() => setSessionKey((k) => k + 1)} appUpdate={appUpdate} diff --git a/components/ModelsConfig.test.mjs b/components/ModelsConfig.test.mjs index 23d0b1d95..cebad8117 100644 --- a/components/ModelsConfig.test.mjs +++ b/components/ModelsConfig.test.mjs @@ -3,9 +3,9 @@ import assert from "node:assert/strict"; import test, { afterEach } from "node:test"; import { createElement } from "react"; -const { cleanup, render, screen, waitFor } = await import("@testing-library/react/pure.js"); +const { act, cleanup, render, screen, waitFor } = await import("@testing-library/react/pure.js"); const { default: userEvent } = await import("@testing-library/user-event"); -const { providerInitials } = await import("./ModelsConfig.tsx"); +const { ModelsConfig, providerInitials } = await import("./ModelsConfig.tsx"); const { RetryFallbackDetail } = await import("./ModelsConfig-panels.tsx"); afterEach(cleanup); @@ -127,3 +127,31 @@ test("a failed fallback save restores the confirmed chain", async (t) => { assert.equal(screen.queryByText("openai-codex/gpt-5.6-sol:high"), null); assert.ok(screen.getByText("No explicit chain. OMP uses the default chain when available.")); }); + +test("focusProvider waits for OAuth list to settle before selecting apikey", async (t) => { + let resolveOauth; + t.mock.method(globalThis, "fetch", async (url) => { + if (url === "/api/auth/providers") { + return await new Promise((resolve) => { + resolveOauth = () => resolve(Response.json({ providers: [{ id: "anthropic", name: "Anthropic", loggedIn: false }] })); + }); + } + if (url === "/api/auth/all-providers") { + return Response.json({ providers: [{ id: "anthropic", name: "Anthropic", configured: true }] }); + } + if (url === "/api/models-config") return Response.json({ providers: {} }); + if (url === "/api/models") return Response.json({ modelList: [], connectedProviders: [] }); + return Response.json({}); + }); + + await act(async () => { + render(createElement(ModelsConfig, { onClose: () => {}, embedded: true, focusProvider: { id: "anthropic" } })); + await new Promise((r) => setTimeout(r, 30)); + }); + assert.equal(screen.queryByText("API Key"), null, "must not select apikey before oauth list settles"); + + await act(async () => { + resolveOauth(); + }); + await screen.findByText("Subscription"); +}); diff --git a/components/ModelsConfig.tsx b/components/ModelsConfig.tsx index dd82b9833..ef20a4aeb 100644 --- a/components/ModelsConfig.tsx +++ b/components/ModelsConfig.tsx @@ -25,6 +25,7 @@ import { toast } from "@/components/ui/toast"; import { SettingsTabs, type SettingsTab } from "./SettingsTabs"; import { ModelCatalogPicker } from "./ModelCatalogPicker"; import { ProviderAccounts } from "./ProviderAccounts"; +import { PROVIDER_ACCOUNTS_CHANGED } from "./AppShell-provider-usage"; import { API_OPTIONS, COMPOSER_MODELS_STORAGE_KEY, @@ -850,6 +851,7 @@ function OAuthDetail({ provider, onRefresh }: { provider: OAuthProvider; onRefre es.close(); setLoginState({ phase: "success" }); setAccountsVersion((v) => v + 1); + window.dispatchEvent(new Event(PROVIDER_ACCOUNTS_CHANGED)); onRefresh(); } else if (data.type === "error") { es.close(); @@ -1037,7 +1039,7 @@ function OAuthDetail({ provider, onRefresh }: { provider: OAuthProvider; onRefre // ── Main component ──────────────────────────────────────────────────────────── -export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false }: { onClose: () => void; onSelectTab?: (tab: SettingsTab) => void; onSaved?: () => void; embedded?: boolean }) { +export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false, focusProvider }: { onClose: () => void; onSelectTab?: (tab: SettingsTab) => void; onSaved?: () => void; embedded?: boolean; focusProvider?: { id: string } | null }) { const { t, tn } = useI18n(); const isMobile = useIsMobile(); const [config, setConfig] = useState({ providers: {} }); @@ -1049,6 +1051,7 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } const [systemTab, setSystemTab] = useState<"registry" | "picker" | "roles" | "fallbacks">("registry"); const [selection, setSelection] = useState(null); const [oauthProviders, setOauthProviders] = useState([]); + const [oauthLoaded, setOauthLoaded] = useState(false); const [apiKeyProviders, setApiKeyProviders] = useState([]); const [runtimeModels, setRuntimeModels] = useState([]); const [connectedProviders, setConnectedProviders] = useState([]); @@ -1065,12 +1068,14 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } const [parseError, setParseError] = useState<{ message: string; path?: string } | null>(null); const loadOAuthProviders = useCallback(() => { + setOauthLoaded(false); fetch("/api/auth/providers") .then((r) => r.json()) .then((d: { providers?: OAuthProvider[] }) => { if (Array.isArray(d.providers)) setOauthProviders(d.providers); }) - .catch(() => {}); + .catch(() => {}) + .finally(() => setOauthLoaded(true)); }, []); const loadApiKeyProviders = useCallback(() => { @@ -1125,6 +1130,19 @@ export function ModelsConfig({ onClose, onSelectTab, onSaved, embedded = false } loadRuntimeModels(); }, [loadConfig, loadOAuthProviders, loadApiKeyProviders, loadRuntimeModels]); + // Opened from a provider usage row: show that provider once the lists are in, once per request. + const focusedRef = useRef<{ id: string } | null>(null); + useEffect(() => { + if (!focusProvider || focusedRef.current === focusProvider) return; + const type = oauthProviders.some((p) => p.id === focusProvider.id) + ? "oauth" + : oauthLoaded && apiKeyProviders.some((p) => p.id === focusProvider.id) ? "apikey" : null; + if (!type) return; + focusedRef.current = focusProvider; + setSubTab("connected"); + setSelection({ type, providerId: focusProvider.id }); + }, [focusProvider, oauthProviders, oauthLoaded, apiKeyProviders]); + useEffect(() => { try { const stored = JSON.parse(localStorage.getItem(COMPOSER_MODELS_STORAGE_KEY) ?? "null"); diff --git a/components/ProviderAccounts.tsx b/components/ProviderAccounts.tsx index db82b9628..30cbbbb51 100644 --- a/components/ProviderAccounts.tsx +++ b/components/ProviderAccounts.tsx @@ -5,7 +5,7 @@ import { LogOut } from "lucide-react"; import { useI18n } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; import { planForStoredAccount, summarizeProviderAccounts } from "@/lib/provider-accounts"; -import { useProviderUsage } from "./AppShell-provider-usage"; +import { PROVIDER_ACCOUNTS_CHANGED, useProviderUsage } from "./AppShell-provider-usage"; import { ConfirmDialog } from "./ui/field"; interface StoredAccount { @@ -63,6 +63,7 @@ export function ProviderAccounts({ providerId, enabled, onChanged }: { providerI // Drop the row now; the refetch reconciles with omp's store. setStored((s) => s && { ...s, accounts: s.accounts.filter((a) => a.credentialId !== account.credentialId) }); setVersion((v) => v + 1); + window.dispatchEvent(new Event(PROVIDER_ACCOUNTS_CHANGED)); onChanged(); } catch (e) { setConfirm(null); diff --git a/components/ProviderUsageBar.test.mjs b/components/ProviderUsageBar.test.mjs index 68f3d48c9..bc0e79ec6 100644 --- a/components/ProviderUsageBar.test.mjs +++ b/components/ProviderUsageBar.test.mjs @@ -1,66 +1,208 @@ +import "../tests/setup-dom.mjs"; import assert from "node:assert/strict"; -import test from "node:test"; -import React from "react"; -import { renderToStaticMarkup } from "react-dom/server"; - -const { - ProviderUsageBar, - nextUsageDisplayWindow, - displayWindowForReport, - displaySummary, -} = await import("./ProviderUsageBar.tsx"); - -const report = (overrides) => ({ - provider: "anthropic", - accountLabel: "main", - accountIndex: 1, - ...overrides, +import test, { afterEach } from "node:test"; +import { createElement } from "react"; + +const { act, cleanup, fireEvent, render, screen, waitFor, within } = await import("@testing-library/react/pure.js"); +const { ProviderUsageBar } = await import("./ProviderUsageBar.tsx"); +const { PROVIDER_ACCOUNTS_CHANGED } = await import("./AppShell-provider-usage.ts"); + +afterEach(() => { + cleanup(); + window.localStorage.clear(); }); -test("usage display window cycles Auto -> 5H -> 7D -> Auto (#285)", () => { - assert.equal(nextUsageDisplayWindow("auto"), "5H"); - assert.equal(nextUsageDisplayWindow("5H"), "7D"); - assert.equal(nextUsageDisplayWindow("7D"), "auto"); +function makeSnapshot(overrides = {}) { + return { + generatedAt: 1_700_000_000_000, + defaultLimitPercent: 80, + accounts: [ + { + key: "anthropic:1", + provider: "anthropic", + accountLabel: "main@x.test", + name: "Main Claude", + credentialId: 1, + limitPercent: 60, + canLimit: true, + canPrioritize: true, + sevenDay: { percent: 70 }, + }, + { + key: "anthropic:2", + provider: "anthropic", + accountLabel: "second@x.test", + name: "Second Claude", + credentialId: 2, + priority: 1, + canLimit: true, + canPrioritize: true, + sevenDay: { percent: 70 }, + }, + { + key: "antigravity-acp:3", + provider: "antigravity-acp", + accountLabel: "google@x.test", + name: "Google Default", + credentialId: 3, + canLimit: true, + canPrioritize: true, + sevenDay: { percent: 70 }, + }, + { + key: "github-copilot:4", + provider: "github-copilot", + accountLabel: "gh@x.test", + name: "Paused Copilot", + credentialId: 4, + paused: true, + canPrioritize: true, + }, + ], + ...overrides, + }; +} + +test("collapsed rows show only non-default icons, turn into buttons when expanded, and apply default limit to meters", async (t) => { + window.localStorage.setItem("omp-web:provider-usage-collapsed", "false"); + const snapshot = makeSnapshot(); + t.mock.method(globalThis, "fetch", async () => Response.json(snapshot)); + + const opened = []; + render(createElement(ProviderUsageBar, { onOpenProvider: (provider) => opened.push(provider) })); + + const mainRow = (await screen.findByText("Main Claude")).closest("[role='button']"); + const secondRow = screen.getByText("Second Claude").closest("[role='button']"); + const googleRow = screen.getByText("Google Default").closest("[role='button']"); + const copilotRow = screen.getByText("Paused Copilot").closest("[role='button']"); + + // Non-default badges appear only on rows with non-default state when collapsed. + assert.ok(mainRow.textContent.includes("≤60%")); + assert.ok(secondRow.querySelector("[aria-label='Preferred']")); + assert.equal(googleRow.querySelector("[aria-label='Preferred']"), null); + assert.equal(googleRow.querySelector("[aria-label='Paused']"), null); + assert.ok(!googleRow.textContent.includes("≤80%")); + assert.ok(copilotRow.querySelector("[aria-label='Paused']")); + + // Default limit (80%) is applied to compact meters for accounts without an explicit override: + // at 70% usage, 70 / 80 = 87.5% (>= 80% -> error tone) and an 80% marker is rendered. + const googleCompactMarker = googleRow.querySelector("[aria-hidden='true'][style*='left: 80%']"); + assert.ok(googleCompactMarker, "compact meter should show the effective default limit marker (80%)"); + assert.ok(googleRow.innerHTML.includes("var(--status-error)"), "70% of an 80% default limit should render error tone"); + + // Expanding Main Claude hides its header badge (no duplicate) and exposes interactive buttons + settings on the right. + fireEvent.click(mainRow, { detail: 1 }); + await waitFor(() => assert.equal(mainRow.getAttribute("aria-expanded"), "true")); + + const mainCard = mainRow.parentElement; + const headerBadges = mainRow.querySelector(".provider-usage-badges"); + assert.equal(headerBadges.getAttribute("aria-hidden"), "true"); + + // Detail meter for Second Claude (no override) also uses defaultLimit (80%) while its selector keeps "default". + fireEvent.click(secondRow, { detail: 1 }); + await waitFor(() => assert.equal(secondRow.getAttribute("aria-expanded"), "true")); + const secondCard = secondRow.parentElement; + assert.ok(secondCard.querySelector(".accordion-flow.is-open [style*='left: 80%']"), "detail meter should show effective default limit marker"); + const limitTrigger = within(secondCard).getByRole("combobox", { name: "Usage limit for Second Claude" }); + assert.ok(limitTrigger.textContent.includes("≤80% (default)"), "limit selector stays on default"); + + const settingsBtn = [...secondCard.querySelectorAll("button")].find((btn) => btn.getAttribute("aria-label") === "Open in API Keys & Providers"); + assert.ok(settingsBtn, `settings button shows when expanded; found buttons: ${[...secondCard.querySelectorAll("button")].map((b) => b.getAttribute("aria-label")).join(", ")}`); + fireEvent.click(settingsBtn); + assert.deepEqual(opened, ["anthropic"]); + assert.ok(mainCard); }); -test("pinned 5H shows the 5-hour window even when it is not the worst (#285)", () => { - const r = report({ - fiveHour: { percent: 30, resetMinutes: 120 }, - sevenDay: { percent: 80, resetHours: 48 }, - monthly: { percent: 10, resetHours: 200 }, +test("Alt+ArrowUp/Down reorders accounts and serializes concurrent order saves", async (t) => { + window.localStorage.setItem("omp-web:provider-usage-collapsed", "false"); + let snapshot = makeSnapshot(); + const patchResolvers = []; + const postedOrders = []; + + t.mock.method(globalThis, "fetch", async (url, init) => { + if (url === "/api/provider-usage/accounts" && init?.method === "PATCH") { + const body = JSON.parse(init.body); + postedOrders.push(body.order); + return await new Promise((resolve) => { + patchResolvers.push(() => { + const map = new Map(snapshot.accounts.map((a) => [a.key, a])); + snapshot = { ...snapshot, accounts: body.order.map((k) => map.get(k)) }; + resolve(Response.json({ ok: true })); + }); + }); + } + return Response.json(snapshot); }); - assert.equal(displayWindowForReport(r, "auto")?.short, "7D"); - assert.equal(displayWindowForReport(r, "5H")?.window.percent, 30); - assert.equal(displayWindowForReport(r, "7D")?.window.percent, 80); -}); -test("a report without the pinned window falls back to its worst window (#285)", () => { - const r = report({ sevenDay: { percent: 55, resetHours: 24 } }); - assert.equal(displayWindowForReport(r, "5H")?.short, "7D"); - assert.equal(displayWindowForReport(r, "5H")?.window.percent, 55); -}); + render(createElement(ProviderUsageBar, {})); + const googleRow = (await screen.findByText("Google Default")).closest("[role='button']"); -test("header summary uses the pinned window across reports, skipping reports without it (#285)", () => { - const reports = [ - report({ fiveHour: { percent: 40 }, sevenDay: { percent: 90 } }), - report({ sevenDay: { percent: 70 } }), - report({ fiveHour: { percent: 65 }, sevenDay: { percent: 20 } }), - ]; - assert.deepEqual(displaySummary(reports, "auto"), { percent: 90, window: "7D" }); - assert.deepEqual(displaySummary(reports, "5H"), { percent: 65, window: "5H" }); - assert.deepEqual(displaySummary(reports, "7D"), { percent: 90, window: "7D" }); -}); + // Two rapid keyboard moves (index 2 -> 1 -> 0) before the first PATCH completes. + await act(async () => { + fireEvent.keyDown(googleRow, { key: "ArrowUp", altKey: true }); + }); + // Row moved up in localOrder; move it up again to the top. + const googleRowAfterFirst = screen.getByText("Google Default").closest("[role='button']"); + await act(async () => { + fireEvent.keyDown(googleRowAfterFirst, { key: "ArrowUp", altKey: true }); + }); + + // Only the first PATCH should be in flight while the second waits in the queue. + assert.equal(postedOrders.length, 1); + assert.deepEqual(postedOrders[0], ["anthropic:1", "antigravity-acp:3", "anthropic:2", "github-copilot:4"]); + + await act(async () => { + patchResolvers.shift()(); + await new Promise((r) => setTimeout(r, 10)); + }); + assert.equal(postedOrders.length, 2); + assert.deepEqual(postedOrders[1], ["antigravity-acp:3", "anthropic:1", "anthropic:2", "github-copilot:4"]); -test("header summary falls back to the worst window when no report has the pinned window (#285)", () => { - const reports = [report({ sevenDay: { percent: 55 } })]; - assert.deepEqual(displaySummary(reports, "5H"), { percent: 55, window: "7D" }); - assert.deepEqual(displaySummary([], "5H"), null); + await act(async () => { + patchResolvers.shift()(); + await new Promise((r) => setTimeout(r, 20)); + }); + + const renderedNames = [...document.querySelectorAll(".provider-usage-row")].map((el) => el.textContent); + assert.ok(renderedNames[0].includes("Google Default"), "final order should reflect the latest move"); }); -test("widget renders with a window toggle chip (#285)", () => { - const html = renderToStaticMarkup( - React.createElement(ProviderUsageBar, {}), - ); - assert.match(html, /Switch usage window \(currently Auto\)/); - assert.match(html, />Auto { + window.localStorage.setItem("omp-web:provider-usage-collapsed", "false"); + const paused = makeSnapshot().accounts.slice(0, 2).map((account) => ({ + ...account, sevenDay: undefined, paused: true, canLimit: false, + })); + let accounts = paused; + let rosterUnavailable = false; + const changes = []; + t.mock.method(globalThis, "fetch", async (_url, init) => { + if (init?.method === "PATCH") { + const change = JSON.parse(init.body); + changes.push(change); + accounts = accounts.map((account) => account.credentialId === change.credentialId ? { ...account, paused: change.paused } : account); + return Response.json({ ok: true }); + } + if (rosterUnavailable) return new Response(null, { status: 503 }); + return Response.json(makeSnapshot({ accounts, usageUnavailable: true, generatedAt: null })); + }); + + await act(async () => { render(createElement(ProviderUsageBar)); }); + const row = screen.getByText("Main Claude").closest("[role='button']"); + assert.ok(screen.getByText("Provider limits unavailable")); + assert.ok(screen.getByText("Second Claude")); + fireEvent.keyDown(row, { key: "Enter" }); + await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Resume Main Claude" })); }); + assert.ok(screen.getByRole("button", { name: "Pause Main Claude" })); + assert.deepEqual(changes, [{ provider: "anthropic", credentialId: 1, paused: false }]); + + rosterUnavailable = true; + await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Refresh" })); }); + assert.ok(screen.getByText("Main Claude")); + assert.ok(screen.getByText("Provider limits unavailable")); + rosterUnavailable = false; + + accounts = accounts.filter((account) => account.credentialId !== 1); + await act(async () => { window.dispatchEvent(new window.Event(PROVIDER_ACCOUNTS_CHANGED)); }); + assert.equal(screen.queryByText("Main Claude"), null); + assert.ok(screen.getByText("Second Claude")); }); diff --git a/components/ProviderUsageBar.tsx b/components/ProviderUsageBar.tsx index e6bb42845..28bd58dce 100644 --- a/components/ProviderUsageBar.tsx +++ b/components/ProviderUsageBar.tsx @@ -1,165 +1,289 @@ "use client"; -import { useEffect, useState } from "react"; -import { Check, ChevronRight, Gauge, RefreshCw } from "lucide-react"; +import { useEffect, useRef, useState, type ReactNode } from "react"; +import { Check, ChevronRight, Gauge, Pause, Play, RefreshCw, Settings2, Star } from "lucide-react"; import { useI18n } from "@/lib/i18n"; -import { formatUsageReset, usageBucketLabel, usageTone, useProviderUsage } from "./AppShell-provider-usage"; -import type { ProviderUsageReport, ProviderUsageWindow } from "@/lib/provider-usage-types"; +import { formatUsageReset, PROVIDER_ACCOUNTS_CHANGED, usageTone, useProviderUsage } from "./AppShell-provider-usage"; +import type { ProviderUsageAccount, ProviderUsageAccountsSnapshot, ProviderUsageBucket, ProviderUsageWindow } from "@/lib/provider-usage-types"; import { SidebarIconButton } from "./SessionSidebar-chrome"; -import { Tooltip } from "./ui/primitives"; +import { ThemedSelect, Tooltip } from "./ui/primitives"; +import { toast } from "./ui/toast"; -interface WindowDef { - short: string; - pick: (report: ProviderUsageReport) => ProviderUsageWindow | undefined; -} +const WINDOWS = [ + { short: "5H", key: "fiveHour" }, + { short: "7D", key: "sevenDay" }, + { short: "30D", key: "monthly" }, +] as const; -const WINDOWS: WindowDef[] = [ - { short: "5H", pick: (r) => r.fiveHour }, - { short: "7D", pick: (r) => r.sevenDay }, - { short: "30D", pick: (r) => r.monthly }, -]; +const LIMIT_CHOICES = [50, 60, 70, 80, 90, 95, 100]; const COLLAPSED_STORAGE_KEY = "omp-web:provider-usage-collapsed"; -const DISPLAY_WINDOW_STORAGE_KEY = "omp-web:provider-usage-window"; -function worstWindow(report: ProviderUsageReport): { short: string; window: ProviderUsageWindow } | null { - let best: { short: string; window: ProviderUsageWindow } | null = null; - for (const def of WINDOWS) { - const window = def.pick(report); - if (window && (best === null || window.percent > best.window.percent)) { - best = { short: def.short, window }; - } - } - return best; +type Translate = (key: string, vars?: Record) => string; + +/** Usage tone against the account's own limit: red from 80% of it, as from 80% of the provider's cap. */ +function limitTone(percent: number, limit: number | undefined): string { + return usageTone(limit ? (percent / limit) * 100 : percent); } -// Display window for the compact widget rows and header summary (#285). -// "auto" preserves the previous behavior (worst window per report); pinning -// to "5H" or "7D" shows that window instead, falling back to the worst -// window for a report that has no data for the pinned window. -export type UsageDisplayWindow = "auto" | "5H" | "7D"; +function Bar({ percent, limit, tone }: { percent: number; limit?: number; tone: string }) { + return ( + + + {limit !== undefined && limit < 100 && ( + + ); +} -export const USAGE_DISPLAY_WINDOWS: UsageDisplayWindow[] = ["auto", "5H", "7D"]; +type WindowKey = (typeof WINDOWS)[number]["key"]; -export function nextUsageDisplayWindow(current: UsageDisplayWindow): UsageDisplayWindow { - const index = USAGE_DISPLAY_WINDOWS.indexOf(current); - return USAGE_DISPLAY_WINDOWS[(index + 1) % USAGE_DISPLAY_WINDOWS.length]; +/** + * One bucket's windows side by side: "5H ▬ 12% 7D ▬ 54%". `slots` are the windows any bucket of the + * account has, so stacked lines keep their columns when a bucket lacks one. + */ +function WindowMeters({ windows, slots, limit }: { windows: Partial>; slots: readonly WindowKey[]; limit?: number }) { + return ( + + {WINDOWS.filter(({ key }) => slots.includes(key)).map(({ short, key }) => { + const window = windows[key]; + if (!window) return ; + const pct = Math.round(window.percent); + const tone = limitTone(pct, limit); + return ( + + {short} + + {pct}% + + ); + })} + + ); } -export function displayWindowForReport( - report: ProviderUsageReport, - display: UsageDisplayWindow, -): { short: string; window: ProviderUsageWindow } | null { - if (display === "auto") return worstWindow(report); - const def = WINDOWS.find((d) => d.short === display); - const window = def?.pick(report); - return window && def ? { short: def.short, window } : worstWindow(report); +/** One window per line with its reset, for the expanded account. */ +function DetailMeters({ windows, limit, t }: { windows: ProviderUsageBucket; limit?: number; t: Translate }) { + return WINDOWS.map(({ short, key }) => { + const window = windows[key]; + if (!window) return null; + const pct = Math.round(window.percent); + const tone = limitTone(pct, limit); + const rawReset = window.resetMinutes ?? window.resetHours; + const reset = rawReset !== undefined ? formatUsageReset(rawReset, window.resetMinutes !== undefined ? "minutes" : "hours") : null; + return ( + + {short} + + {pct}% + {reset && ( + {t("providerUsage.resets", { value: reset })} + )} + + ); + }); } -export function displaySummary( - reports: ProviderUsageReport[], - display: UsageDisplayWindow, -): { percent: number; window: string } | null { - let best: { percent: number; window: string } | null = null; - for (const report of reports) { - let picked: { short: string; window: ProviderUsageWindow } | null = null; - if (display === "auto") { - picked = worstWindow(report); - } else { - const def = WINDOWS.find((d) => d.short === display); - const window = def?.pick(report); - picked = window && def ? { short: def.short, window } : null; - } - if (picked && (best === null || picked.window.percent > best.percent)) { - best = { percent: Math.round(picked.window.percent), window: picked.short }; - } - } - if (best === null && display !== "auto") { - // No report has the pinned window: fall back to the worst window, as - // before, rather than showing "no data" for data that does exist. - for (const report of reports) { - const picked = worstWindow(report); - if (picked && (best === null || picked.window.percent > best.percent)) { - best = { percent: Math.round(picked.window.percent), window: picked.short }; - } - } - } - return best; +const chipStyle = { fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 10, border: "1px solid var(--border)", padding: "0 5px", borderRadius: 4, whiteSpace: "nowrap", flexShrink: 0, lineHeight: 1.7 } as const; + +const iconButtonStyle = { + display: "inline-flex", alignItems: "center", justifyContent: "center", width: 26, height: 26, padding: 0, flexShrink: 0, + background: "var(--bg)", border: "1px solid var(--border)", borderRadius: 5, color: "var(--text-muted)", cursor: "pointer", +} as const; + +type AccountChange = { paused?: boolean; limitPercent?: number | null; priority?: number | null; name?: string | null }; + +function IconAction({ label, busy, active, onClick, children }: { label: string; busy?: boolean; active?: boolean; onClick: () => void; children: ReactNode }) { + return ( + + + + ); } -function DetailMeter({ short, window, t }: { - short: string; - window: ProviderUsageWindow; - t: (key: string, vars?: Record) => string; +function AccountDetail({ account, label, defaultLimit, busy, onChange, onOpenProvider, t }: { + account: ProviderUsageAccount; + label: string; + defaultLimit: number; + busy: boolean; + onChange: (change: AccountChange) => void; + onOpenProvider?: (provider: string) => void; + t: Translate; }) { - const pct = Math.round(window.percent); - const tone = usageTone(pct); - const rawReset = window.resetMinutes ?? window.resetHours; - const reset = rawReset !== undefined - ? formatUsageReset(rawReset, window.resetMinutes !== undefined ? "minutes" : "hours") - : null; + const preferred = (account.priority ?? 0) > 0; + const limit = account.limitPercent; + const limitOptions = [ + { value: "default", label: t("providerUsage.limitDefault", { percent: defaultLimit }) }, + ...[...new Set([...LIMIT_CHOICES, ...(limit !== undefined ? [limit] : [])])].sort((a, b) => a - b).map((value) => ({ value: String(value), label: `≤${value}%` })), + ]; + const sections: ProviderUsageBucket[] = account.buckets ?? [account]; return ( - - {short} - - - - - {pct}% - - {reset && ( - - {t("providerUsage.resets", { value: reset })} +
+ {!account.paused && sections.map((bucket, index) => ( +
+ {account.buckets && ( + + {bucket.label ?? t("appShell.allModels")} + + )} + +
+ ))} + {account.paused || !WINDOWS.some(({ key }) => account[key]) ? ( + + {t(account.paused ? "providerUsage.pausedHint" : "appShell.providerUsageNoData")} - )} - + ) : null} +
+ {account.credentialId !== undefined && (account.canLimit || limit !== undefined) && ( + onChange({ limitPercent: value === "default" ? null : Number(value) })} + style={{ minHeight: 26, padding: "2px 7px", fontSize: 11, gap: 4 }} + /> + )} + {account.credentialId !== undefined && account.canPrioritize && ( + onChange({ priority: preferred ? null : 1 })} + > + + )} + {account.credentialId !== undefined && ( + onChange({ paused: !account.paused })} + > + {account.paused ? + )} + {onOpenProvider && ( + + onOpenProvider(account.provider)}> + + + )} +
+
); } -// Compact provider rate-limit block pinned above Settings in the sidebar: one -// slim row per account (worst window only), click to expand the full detail. -export function ProviderUsageBar() { +// Provider rate limits pinned above Settings in the sidebar: one row per stored account with every +// window it reports; click a row for its buckets, limit, pause and a way to its provider settings. +export function ProviderUsageBar({ onOpenProvider }: { onOpenProvider?: (provider: string) => void }) { const { t } = useI18n(); - const { snapshot, loading, error, refresh } = useProviderUsage("", 5 * 60_000); + const { snapshot, loading, error, refresh, reload } = useProviderUsage("", 5 * 60_000, "/api/provider-usage/accounts"); + const unavailable = error || snapshot?.usageUnavailable; + useEffect(() => { + const onAccountsChanged = () => void reload({ invalidate: true }); + window.addEventListener(PROVIDER_ACCOUNTS_CHANGED, onAccountsChanged); + return () => window.removeEventListener(PROVIDER_ACCOUNTS_CHANGED, onAccountsChanged); + }, [reload]); const [refreshDone, setRefreshDone] = useState(false); useEffect(() => { if (!refreshDone) return; const timer = window.setTimeout(() => setRefreshDone(false), 2000); return () => window.clearTimeout(timer); }, [refreshDone]); - const reports = snapshot?.reports ?? []; + // A dropped order shows at once and stays until the server's next snapshot carries it. + const [localOrder, setLocalOrder] = useState(null); + const orderQueueRef = useRef>(Promise.resolve()); + const orderVersionRef = useRef(0); + const orderPendingRef = useRef(0); + useEffect(() => { + if (orderPendingRef.current === 0) setLocalOrder(null); + }, [snapshot]); + const accounts = localOrder + ? [...(snapshot?.accounts ?? [])].sort((a, b) => localOrder.indexOf(a.key) - localOrder.indexOf(b.key)) + : snapshot?.accounts ?? []; + const defaultLimit = snapshot?.defaultLimitPercent ?? 90; + const [dragKey, setDragKey] = useState(null); + const [dropKey, setDropKey] = useState(null); + const moveAccount = (from: string, to: string) => { + const order = accounts.map((account) => account.key).filter((key) => key !== from); + const targetIndex = accounts.findIndex((account) => account.key === to); + if (targetIndex === -1) return; + order.splice(targetIndex, 0, from); + setLocalOrder(order); + const version = ++orderVersionRef.current; + orderPendingRef.current += 1; + orderQueueRef.current = orderQueueRef.current + .catch(() => {}) + .then(async () => { + const response = await fetch("/api/provider-usage/accounts", { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ order }), + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + if (version === orderVersionRef.current) await reload(); + }) + .catch((cause: unknown) => { + if (version === orderVersionRef.current) { + setLocalOrder(null); + toast.error(t("providerUsage.reorderFailed", { error: cause instanceof Error ? cause.message : String(cause) })); + } + }) + .finally(() => { + orderPendingRef.current = Math.max(0, orderPendingRef.current - 1); + if (orderPendingRef.current === 0 && version === orderVersionRef.current) setLocalOrder(null); + }); + }; const [expandedKey, setExpandedKey] = useState(null); + const [busyKey, setBusyKey] = useState(null); + const [editingKey, setEditingKey] = useState(null); + const clickTimer = useRef(undefined); // The first render must match the server, where localStorage is unavailable, // so start collapsed and apply the stored preference after mounting. const [collapsed, setCollapsed] = useState(true); - // Same pattern for the display window: start on "auto" (worst window, the - // previous behavior) and apply the stored pinned window after mounting. - const [displayWindow, setDisplayWindow] = useState("auto"); useEffect(() => { try { // No stored choice yet → stay hidden; an explicit expand persists. if (window.localStorage.getItem(COLLAPSED_STORAGE_KEY) === "false") setCollapsed(false); - const stored = window.localStorage.getItem(DISPLAY_WINDOW_STORAGE_KEY); - if (stored === "5H" || stored === "7D") setDisplayWindow(stored); } catch { // Storage unavailable: keep the collapsed default. } }, []); - const worst = displaySummary(reports, displayWindow); - - const cycleDisplayWindow = () => { - setDisplayWindow((prev) => { - const next = nextUsageDisplayWindow(prev); - try { - window.localStorage.setItem(DISPLAY_WINDOW_STORAGE_KEY, next); - } catch { - // The preference still applies for this page load. - } - return next; - }); + const update = async (account: ProviderUsageAccount, label: string, change: AccountChange) => { + setBusyKey(account.key); + try { + const response = await fetch("/api/provider-usage/accounts", { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify(change.name !== undefined + ? { key: account.key, name: change.name } + : { provider: account.provider, credentialId: account.credentialId, ...change }), + }); + const body = await response.json().catch(() => ({})) as { error?: string }; + if (!response.ok) throw new Error(body.error ?? `HTTP ${response.status}`); + await reload(); + } catch (cause) { + toast.error(t("providerUsage.updateFailed", { account: label, error: cause instanceof Error ? cause.message : String(cause) })); + } finally { + setBusyKey(null); + } }; - const displayLabel = displayWindow === "auto" ? "Auto" : displayWindow; return (
- - {refreshDone ? ( -
- {!collapsed && reports.length > 0 && ( -
- {reports.map((report, index) => { - const account = report.accountLabel ?? t("appShell.account", { number: report.accountIndex ?? index + 1 }); - const bucketLabel = usageBucketLabel(report); - const key = `${report.provider}:${account}:${report.modelId ?? "all"}:${report.tier ?? ""}:${report.bucket ?? ""}:${index}`; - const best = displayWindowForReport(report, displayWindow); - const expanded = expandedKey === key; - const pct = best ? Math.round(best.window.percent) : 0; - const tone = usageTone(pct); - return ( -
- - {!report.noLimits && ( -
-
-
- )} - {expanded && !report.noLimits && ( -
- {WINDOWS.map((def) => { - const window = def.pick(report); - return window ? : null; - })} -
- )} + {accounts.length > 0 && ( +
+
+
+ {accounts.map((account, index) => { + const defaultLabel = account.accountLabel ?? t("appShell.account", { number: account.accountIndex ?? index + 1 }); + const label = account.name ?? defaultLabel; + const { key } = account; + const expanded = expandedKey === key; + const editing = editingKey === key; + const preferred = (account.priority ?? 0) > 0; + const nonDefaultLimit = account.limitPercent !== undefined && account.limitPercent !== defaultLimit ? account.limitPercent : undefined; + const hasBadges = nonDefaultLimit !== undefined || preferred || !!account.paused; + const hasWindows = WINDOWS.some(({ key: windowKey }) => account[windowKey]); + const finishRename = (value: string | null) => { + setEditingKey(null); + if (value !== null && value.trim() !== (account.name ?? "")) void update(account, label, { name: value.trim() || null }); + }; + const rowStyle = { display: "flex", flexDirection: "column", width: "100%", boxSizing: "border-box", padding: "5px 6px", background: "none", border: "none", cursor: "pointer", textAlign: "left", minWidth: 0 } as const; + const content = ( + <> + + + {/* An open row lists the same quotas with names, resets and interactive buttons below. */} + {!account.paused && ( +
+
+ + {hasWindows ? ( + // Each bucket is its own quota (Gemini vs Argon, shared vs Fable): one unlabelled line each. + (account.buckets ?? [account]).map((bucket, bucketIndex) => ( + (account[windowKey] ? [windowKey] : []))} limit={account.limitPercent ?? defaultLimit} /> + )) + ) : ( + {t("appShell.providerUsageNoData")} + )} + +
+
+ )} + + ); + return ( +
{ event.dataTransfer.setData("text/plain", key); event.dataTransfer.effectAllowed = "move"; setDragKey(key); }} + onDragOver={(event) => { + if (!dragKey || dragKey === key) return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + setDropKey(key); + }} + onDragLeave={() => setDropKey((current) => (current === key ? null : current))} + onDrop={(event) => { + event.preventDefault(); + if (dragKey && dragKey !== key) moveAccount(dragKey, key); + setDragKey(null); + setDropKey(null); + }} + onDragEnd={() => { setDragKey(null); setDropKey(null); }} + style={{ + borderRadius: "var(--radius-control)", + background: expanded ? "var(--bg-subtle)" : "transparent", + opacity: dragKey === key ? 0.5 : 1, + ...(dropKey === key ? { outline: "1px solid var(--accent)", outlineOffset: -1 } : {}), + }} + > + {/* A div, not a button: the rename input sits inside the row. */} +
{ + // Expanding moves the row up (the panel grows from the bottom), so wait out a double-click. + window.clearTimeout(clickTimer.current); + if (!editing && event.detail <= 1) clickTimer.current = window.setTimeout(() => setExpandedKey((prev) => (prev === key ? null : key)), 220); + }} + onDoubleClick={() => { + window.clearTimeout(clickTimer.current); + setEditingKey(key); + }} + onKeyDown={(event) => { + if (event.target !== event.currentTarget) return; + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + setExpandedKey((prev) => (prev === key ? null : key)); + } else if (event.key === "F2") { + setEditingKey(key); + } else if (event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) { + event.preventDefault(); + const target = accounts[index + (event.key === "ArrowUp" ? -1 : 1)]; + if (target) moveAccount(key, target.key); + } + }} + aria-expanded={expanded} + title={[account.name && defaultLabel, account.plan, t("providerUsage.renameHint")].filter(Boolean).join(" · ")} + style={{ ...rowStyle, cursor: editing ? "default" : "pointer" }} + > + {content} +
+
+
+ void update(account, label, change)} + onOpenProvider={onOpenProvider} + t={t} + /> +
+
+
+ ); + })} +
- ); - })} -
+
)}
); diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index bdda72a1c..6d09fb2b6 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -97,6 +97,8 @@ interface Props { usageVisible?: boolean; /** Opens the app settings (pinned sidebar footer row). */ onOpenSettings?: () => void; + /** Opens Settings → API Keys & Providers on one provider (provider usage rows). */ + onOpenProviderSettings?: (provider: string) => void; /** True when an omp/ompweb update is available — shows a badge on the gear. */ updateAvailable?: boolean; /** Opens the archived sessions browser. */ @@ -143,7 +145,7 @@ function loadCollapsedHosts(): Set { } } -export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, optimisticSession, onSelectSession, onNewSession, initialSessionId, initialSessionHostId, skipInitialProjectSelection, onInitialRestoreDone, refreshKey, onSessionDeleted, selectedCwd: selectedCwdProp, selectedHostId: selectedHostIdProp, selectedLogicalProjectKey, onCwdChange, onWorkspaceOptionsChange, onWorktreeContextChange, addProjectOpen, addProjectHostId = LOCAL_HOST_ID, setAddProjectOpen, usageVisible = true, onOpenSettings, onOpenArchive, navigation, updateAvailable, settingsOpen = false, onClose, onSearchQueryChange, onOpenSearchMatch }: Props) { +export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, optimisticSession, onSelectSession, onNewSession, initialSessionId, initialSessionHostId, skipInitialProjectSelection, onInitialRestoreDone, refreshKey, onSessionDeleted, selectedCwd: selectedCwdProp, selectedHostId: selectedHostIdProp, selectedLogicalProjectKey, onCwdChange, onWorkspaceOptionsChange, onWorktreeContextChange, addProjectOpen, addProjectHostId = LOCAL_HOST_ID, setAddProjectOpen, usageVisible = true, onOpenSettings, onOpenProviderSettings, onOpenArchive, navigation, updateAvailable, settingsOpen = false, onClose, onSearchQueryChange, onOpenSearchMatch }: Props) { const { t } = useI18n(); @@ -1879,7 +1881,7 @@ export const SessionSidebar = memo(function SessionSidebar({ selectedSessionId, {/* Provider usage bar — pinned above Settings */} - {usageVisible && } + {usageVisible && } {/* Pinned footer: Settings */}
- + )} diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 76a40d343..074d17ee4 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -284,9 +284,21 @@ "appShell.providerUsageUnavailable": "Provider limits unavailable", "appShell.providerUsageNoData": "No provider limits reported", "appShell.account": "Account {number}", - "providerUsage.highest": "Highest {percent}% · {window}", - "providerUsage.toggleWindow": "Switch usage window (currently {window})", "providerUsage.resets": "resets {value}", + "providerUsage.limitFor": "Usage limit for {account}", + "providerUsage.limitDefault": "≤{percent}% (default)", + "providerUsage.nameFor": "Name for {account}", + "providerUsage.renameHint": "double-click the name to rename, drag or Alt+↑/↓ to reorder", + "providerUsage.paused": "Paused", + "providerUsage.pausedHint": "Still signed in. omp skips this account until you resume it.", + "providerUsage.preferred": "Preferred", + "providerUsage.preferAccount": "Prefer {account} while it is below its limit", + "providerUsage.unpreferAccount": "Stop preferring {account}", + "providerUsage.pauseAccount": "Pause {account}", + "providerUsage.resumeAccount": "Resume {account}", + "providerUsage.openProvider": "Open in API Keys & Providers", + "providerUsage.updateFailed": "Could not update {account}: {error}", + "providerUsage.reorderFailed": "Could not save the order: {error}", "appShell.providerUsageButton": "Provider usage limits", "composerContext.title": "Context", "composerContext.windowSize": "{tokens} window", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index e4467fc41..3a2c15454 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -273,8 +273,21 @@ "appShell.providerUsageUnavailable": "プロバイダー制限を取得できません", "appShell.providerUsageNoData": "プロバイダー制限の報告はありません", "appShell.account": "アカウント {number}", - "providerUsage.highest": "最大 {percent}% · {window}", "providerUsage.resets": "{value} でリセット", + "providerUsage.limitFor": "{account} の使用量の上限", + "providerUsage.limitDefault": "≤{percent}% (既定)", + "providerUsage.nameFor": "{account} の名前", + "providerUsage.renameHint": "名前をダブルクリックして変更、ドラッグまたは Alt+↑/↓ で並べ替え", + "providerUsage.paused": "一時停止中", + "providerUsage.pausedHint": "サインインしたままです。再開するまで omp はこのアカウントを使いません。", + "providerUsage.preferred": "優先", + "providerUsage.preferAccount": "上限に達するまで {account} を優先", + "providerUsage.unpreferAccount": "{account} の優先を解除", + "providerUsage.pauseAccount": "{account} を一時停止", + "providerUsage.resumeAccount": "{account} を再開", + "providerUsage.openProvider": "API Keys & Providers で開く", + "providerUsage.updateFailed": "{account} を更新できませんでした: {error}", + "providerUsage.reorderFailed": "並び順を保存できませんでした: {error}", "appShell.allModels": "すべてのモデル", "appShell.providerUsageButton": "プロバイダー使用量の制限", "appShell.showFilePanel": "ファイルパネルを表示", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index b98b9dddc..1b223cb9f 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -273,8 +273,21 @@ "appShell.providerUsageUnavailable": "提供商限额不可用", "appShell.providerUsageNoData": "没有提供商限额报告", "appShell.account": "账户 {number}", - "providerUsage.highest": "最高 {percent}% · {window}", "providerUsage.resets": "{value} 后重置", + "providerUsage.limitFor": "{account} 的用量上限", + "providerUsage.limitDefault": "≤{percent}%(默认)", + "providerUsage.nameFor": "{account} 的名称", + "providerUsage.renameHint": "双击名称即可重命名,拖动或按 Alt+↑/↓ 可调整顺序", + "providerUsage.paused": "已暂停", + "providerUsage.pausedHint": "仍保持登录。恢复之前 omp 不会使用此账户。", + "providerUsage.preferred": "优先", + "providerUsage.preferAccount": "在未达上限前优先使用 {account}", + "providerUsage.unpreferAccount": "取消优先使用 {account}", + "providerUsage.pauseAccount": "暂停 {account}", + "providerUsage.resumeAccount": "恢复 {account}", + "providerUsage.openProvider": "在 API 密钥与提供商中打开", + "providerUsage.updateFailed": "无法更新 {account}:{error}", + "providerUsage.reorderFailed": "无法保存顺序:{error}", "appShell.allModels": "所有模型", "appShell.providerUsageButton": "提供商用量限额", "appShell.showFilePanel": "显示文件面板", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index ca85ab4e1..95f7d031c 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -284,9 +284,21 @@ "appShell.providerUsageUnavailable": "無法取得供應商額度限制", "appShell.providerUsageNoData": "未回報供應商額度限制", "appShell.account": "帳戶 {number}", - "providerUsage.highest": "最高 {percent}% · {window}", - "providerUsage.toggleWindow": "切換用量區間(目前為 {window})", "providerUsage.resets": "{value} 重設", + "providerUsage.limitFor": "{account} 的用量上限", + "providerUsage.limitDefault": "≤{percent}%(預設)", + "providerUsage.nameFor": "{account} 的名稱", + "providerUsage.renameHint": "按兩下名稱即可重新命名,拖曳或按 Alt+↑/↓ 可調整順序", + "providerUsage.paused": "已暫停", + "providerUsage.pausedHint": "仍保持登入。恢復之前 omp 不會使用此帳戶。", + "providerUsage.preferred": "優先", + "providerUsage.preferAccount": "在未達上限前優先使用 {account}", + "providerUsage.unpreferAccount": "取消優先使用 {account}", + "providerUsage.pauseAccount": "暫停 {account}", + "providerUsage.resumeAccount": "恢復 {account}", + "providerUsage.openProvider": "在 API 金鑰與供應商中開啟", + "providerUsage.updateFailed": "無法更新 {account}:{error}", + "providerUsage.reorderFailed": "無法儲存順序:{error}", "appShell.providerUsageButton": "供應商用量限制", "composerContext.title": "上下文", "composerContext.windowSize": "{tokens} 視窗", diff --git a/lib/omp/settings-config.ts b/lib/omp/settings-config.ts index 2acbd20ee..214c2f858 100644 --- a/lib/omp/settings-config.ts +++ b/lib/omp/settings-config.ts @@ -80,6 +80,38 @@ export function readAnthropicSlowMode(): boolean { } } +/** omp's `auth.accountPolicies` (entries kept as written) and the global `retry.usageReservePct`. */ +export function readAccountPolicyConfig(): { policies: unknown[]; reservePct: number } { + const data = readDocument().doc.toJS(); + if (!isRecord(data)) return { policies: [], reservePct: 10 }; + const auth = isRecord(data.auth) ? data.auth : {}; + const retry = isRecord(data.retry) ? data.retry : {}; + // omp's migration also accepts top-level dotted keys, nested values winning. + const policies = auth.accountPolicies ?? data["auth.accountPolicies"]; + const reservePct = retry.usageReservePct ?? data["retry.usageReservePct"]; + return { + policies: Array.isArray(policies) ? policies : [], + reservePct: typeof reservePct === "number" && Number.isFinite(reservePct) ? Math.max(0, Math.min(100, reservePct)) : 10, + }; +} + +export function writeAccountPolicies(policies: unknown[]): void { + const { path, doc } = readDocument(); + if (doc.contents !== null && !isMap(doc.contents)) throw new Error(`${path} must contain a YAML mapping`); + if (policies.length > 0) doc.setIn(["auth", "accountPolicies"], policies); + else { + doc.deleteIn(["auth", "accountPolicies"]); + const auth = doc.get("auth"); + if (isMap(auth) && auth.items.length === 0) doc.delete("auth"); + } + // A dotted key would otherwise hand the old policies back once the nested one is gone. + doc.delete("auth.accountPolicies"); + mkdirSync(dirname(path), { recursive: true }); + const temp = `${path}.tmp-${process.pid}-${Date.now()}`; + writeFileSync(temp, doc.toString(), "utf8"); + renameSync(temp, path); +} + /** Returns the persisted native OMP values only; omitted keys keep OMP defaults. */ export function readNativeSettings(): { path: string; settings: NativeSettings } { const { path, doc } = readDocument(); diff --git a/lib/provider-accounts.test.mjs b/lib/provider-accounts.test.mjs index 073be1b0b..bb62d38a6 100644 --- a/lib/provider-accounts.test.mjs +++ b/lib/provider-accounts.test.mjs @@ -36,3 +36,40 @@ test("a usage plan is shown only for the one stored account its email identifies assert.equal(planForStoredAccount("a@x.test (Org A)", shared, usage), undefined); assert.equal(planForStoredAccount("a@x.test.evil", ["a@x.test.evil"], usage), undefined); }); + +const { withAccountPolicy } = await import("./provider-accounts.ts"); + +test("withAccountPolicy adds, updates and clears one field without touching other policies", () => { + const a = { email: "a@x.test", accountId: "acc-a", orgId: "org-a" }; + const b = { email: "b@x.test", accountId: "acc-b" }; + const other = { provider: "openai-codex", account: { email: "a@x.test" }, priority: 5 }; + + const added = withAccountPolicy([other], "anthropic", a, [a, b], "reservePct", 20); + assert.deepEqual(added, [other, { provider: "anthropic", account: { email: "a@x.test", orgId: "org-a" }, reservePct: 20 }]); + + const both = withAccountPolicy(added, "anthropic", a, [a, b], "priority", 1); + assert.deepEqual(both[1], { provider: "anthropic", account: { email: "a@x.test", orgId: "org-a" }, reservePct: 20, priority: 1 }, "one policy carries both fields"); + + assert.deepEqual(withAccountPolicy(both, "anthropic", a, [a, b], "reservePct", null)[1], { provider: "anthropic", account: { email: "a@x.test", orgId: "org-a" }, priority: 1 }); + assert.deepEqual(withAccountPolicy(added, "anthropic", a, [a, b], "reservePct", null), [other], "a policy left with only its selector goes"); +}); + +test("withAccountPolicy names an account apart from a sibling sharing its email and org", () => { + const seat1 = { email: "team@x.test", accountId: "seat-1", orgId: "org" }; + const seat2 = { email: "team@x.test", accountId: "seat-2", orgId: "org" }; + assert.deepEqual(withAccountPolicy([], "openai-codex", seat2, [seat1, seat2], "priority", 1)[0].account, { email: "team@x.test", accountId: "seat-2", orgId: "org" }); + assert.throws(() => withAccountPolicy([], "openai-codex", seat1, [seat1, { ...seat1 }], "priority", 1), /same identity/); +}); + +test("withAccountPolicy refuses a reserve at or above reclaimAbovePct, including on clear", () => { + const a = { email: "a@x.test" }; + const policies = [{ provider: "anthropic", account: { email: "a@x.test" }, reservePct: 5, reclaimAbovePct: 10 }]; + assert.throws(() => withAccountPolicy(policies, "anthropic", a, [a], "reservePct", 50), /reclaimAbovePct/); + assert.throws(() => withAccountPolicy(policies, "anthropic", a, [a], "reservePct", null, 10), /reclaimAbovePct/); + assert.throws(() => withAccountPolicy([{ provider: "anthropic", account: { email: "a@x.test" }, reservePct: 10, reclaimAbovePct: 20 }], "anthropic", a, [a], "reservePct", null, 20), /reclaimAbovePct/); + assert.deepEqual( + withAccountPolicy([{ provider: "anthropic", account: { email: "a@x.test" }, reservePct: 20, reclaimAbovePct: 30 }], "anthropic", a, [a], "reservePct", null, 10), + [{ provider: "anthropic", account: { email: "a@x.test" }, reclaimAbovePct: 30 }], + ); + assert.equal(withAccountPolicy([{ provider: "anthropic", account: { email: "a@x.test" }, reclaimAbovePct: 40 }], "anthropic", a, [a], "reservePct", 30)[0].reservePct, 30); +}); diff --git a/lib/provider-accounts.ts b/lib/provider-accounts.ts index 802e6f521..90a41f21c 100644 --- a/lib/provider-accounts.ts +++ b/lib/provider-accounts.ts @@ -1,3 +1,4 @@ +import { isRecord } from "./type-guards"; import type { ProviderUsageReport } from "./provider-usage-types"; export interface ProviderAccountSummary { @@ -44,3 +45,106 @@ export function planForStoredAccount(label: string, storedLabels: readonly strin const match = usage.find((u) => sameEmail(label, u.label)); return match && storedLabels.filter((stored) => sameEmail(stored, match.label)).length === 1 ? match.plan : undefined; } + +export interface AccountIdentity { + email?: string; + accountId?: string; + projectId?: string; + orgId?: string; +} + +/** A stored OAuth account as the runner's `get_usage_accounts` lists it. */ +export interface StoredUsageAccount extends AccountIdentity { + credentialId: number; + provider: string; + paused: boolean; +} + +const IDENTITY_FIELDS = ["email", "accountId", "projectId", "orgId"] as const; + +function sameId(a: string | undefined, b: string | undefined): boolean { + return !!a && !!b && a.toLowerCase() === b.toLowerCase(); +} + +/** + * Whether a usage report's identity names a stored account, as `omp usage` attributes them: differing orgs + * never match, an email on both sides decides, else a shared account or project id does. + */ +export function reportMatchesAccount(report: AccountIdentity, account: AccountIdentity): boolean { + if (report.orgId && account.orgId && !sameId(report.orgId, account.orgId)) return false; + if (report.email && account.email) return sameId(report.email, account.email); + return sameId(report.accountId, account.accountId) || sameId(report.projectId, account.projectId); +} + +/** omp's conjunctive `auth.accountPolicies[].account` match: every field the selector sets must be equal. */ +export function selectorMatches(selector: unknown, account: AccountIdentity): boolean { + if (!isRecord(selector)) return false; + return IDENTITY_FIELDS.every((field) => selector[field] === undefined || selector[field] === account[field]); +} + +function findPolicy(policies: readonly unknown[], provider: string, account: AccountIdentity): number { + return policies.findIndex((policy) => isRecord(policy) && policy.provider === provider && selectorMatches(policy.account, account)); +} + +type PolicyField = "reservePct" | "priority"; + +/** A numeric field of the account's own policy (`reservePct` = 100 - its limit), if it sets one. */ +export function accountPolicyValue(policies: readonly unknown[], provider: string, account: AccountIdentity, field: PolicyField): number | undefined { + const policy = policies[findPolicy(policies, provider, account)]; + return isRecord(policy) && typeof policy[field] === "number" ? policy[field] : undefined; +} + +/** Whether an account policy can name the account at all (omp requires an email, account or project id). */ +export function canNameAccount(account: AccountIdentity): boolean { + return !!(account.email || account.accountId || account.projectId); +} + +/** + * The selector for a new policy: the email (or account, or project id) plus the org, widened to every + * identity field when that still matches a sibling. omp rejects a selector matching two accounts. + */ +function policySelector(account: AccountIdentity, siblings: readonly AccountIdentity[]): AccountIdentity { + const pick = (fields: readonly (keyof AccountIdentity)[]) => + Object.fromEntries(fields.flatMap((field) => (account[field] ? [[field, account[field]]] : []))) as AccountIdentity; + const base = account.email ? "email" : account.accountId ? "accountId" : "projectId"; + for (const selector of [pick([base, "orgId"]), pick(IDENTITY_FIELDS)]) { + if (siblings.filter((sibling) => selectorMatches(selector, sibling)).length === 1) return selector; + } + throw new Error("Another stored account has the same identity; omp cannot tell them apart"); +} + +/** + * `auth.accountPolicies` with one field of the account's policy set, or cleared (null). Other policies + * and fields stay as they are; a policy left with nothing but its selector is dropped. + * `siblings` are the provider's stored accounts, the account included. + */ +export function withAccountPolicy( + policies: readonly unknown[], + provider: string, + account: AccountIdentity, + siblings: readonly AccountIdentity[], + field: PolicyField, + value: number | null, + defaultReservePct = 10, +): unknown[] { + const next = [...policies]; + const index = findPolicy(next, provider, account); + const existing = index === -1 ? undefined : next[index] as Record; + if (field === "reservePct" && typeof existing?.reclaimAbovePct === "number") { + const effectiveReserve = value ?? defaultReservePct; + if (existing.reclaimAbovePct <= effectiveReserve) { + throw new Error(`The account's reclaimAbovePct (${existing.reclaimAbovePct}%) must stay above its reserve (${effectiveReserve}%); use a higher limit`); + } + } + if (value === null) { + if (!existing) return next; + const rest = { ...existing }; + delete rest[field]; + if (Object.keys(rest).every((key) => key === "provider" || key === "account")) next.splice(index, 1); + else next[index] = rest; + return next; + } + if (existing) next[index] = { ...existing, [field]: value }; + else next.push({ provider, account: policySelector(account, siblings), [field]: value }); + return next; +} diff --git a/lib/provider-usage-types.ts b/lib/provider-usage-types.ts index f166cfc67..a76c96d1c 100644 --- a/lib/provider-usage-types.ts +++ b/lib/provider-usage-types.ts @@ -31,6 +31,50 @@ export interface ProviderUsageSnapshot { reports: ProviderUsageReport[]; } +export interface ProviderUsageBucket { + /** Tier, quota bucket or model ("Fable", "Gemini"); absent for the account-wide counter. */ + label?: string; + fiveHour?: ProviderUsageWindow; + sevenDay?: ProviderUsageWindow; + monthly?: ProviderUsageWindow; +} + +/** One stored account with every usage split merged in; windows hold the highest bucket. */ +export interface ProviderUsageAccount { + /** Stable id of the account in the overview: its credential, else its label or omp's position. */ + key: string; + /** The user's name for the account, shown instead of its email or "Account N". */ + name?: string; + provider: string; + accountLabel?: string; + accountIndex?: number; + plan?: string; + /** omp's credential row; absent when no stored account could be matched, so nothing can be changed. */ + credentialId?: number; + paused?: boolean; + /** Usage above which omp routes to the provider's other accounts first (100 - the account's reservePct). */ + limitPercent?: number; + /** omp's `priority` for the account: higher is picked first while it is below its limit. */ + priority?: number; + /** Whether an account policy can name this account (limit and priority need one). */ + canPrioritize?: boolean; + /** Whether a policy can name this account and omp can measure its usage. */ + canLimit?: boolean; + fiveHour?: ProviderUsageWindow; + sevenDay?: ProviderUsageWindow; + monthly?: ProviderUsageWindow; + /** Present when the account reports more than one bucket. */ + buckets?: ProviderUsageBucket[]; +} + +export interface ProviderUsageAccountsSnapshot { + generatedAt: number | null; + usageUnavailable?: boolean; + accounts: ProviderUsageAccount[]; + /** Limit omp applies to accounts without their own (100 - `retry.usageReservePct`). */ + defaultLimitPercent: number; +} + export interface ProviderUsageContext { provider: string; modelId: string; diff --git a/lib/provider-usage.test.mjs b/lib/provider-usage.test.mjs index 317bfd388..87387dd97 100644 --- a/lib/provider-usage.test.mjs +++ b/lib/provider-usage.test.mjs @@ -391,3 +391,256 @@ test("parseProviderUsageOutput reads Antigravity buckets from Usage (...) labels assert.equal(reports[1].bucket, "Anthropic"); assert.equal(reports[1].sevenDay.percent, 20); }); + +const { parseProviderUsageAccounts } = await import("./provider-usage.ts"); + +const limit = (windowId, usedFraction, scope = {}) => ({ scope: { windowId, ...scope }, amount: { usedFraction }, window: {} }); + +test("parseProviderUsageAccounts merges an account's buckets and keeps the highest per window", () => { + const output = JSON.stringify({ + reports: [ + { + provider: "anthropic", + metadata: { email: "a@x.test", orgId: "org-a" }, + limits: [limit("7d", 0.8, { shared: true }), limit("7d", 0.92, { tier: "fable" })], + }, + { + provider: "antigravity-acp", + metadata: {}, + limits: [ + limit("7d", 0.54, { tier: "Gemini Models", modelId: "gemini-4-hydrogen" }), + limit("7d", 0.54, { tier: "Gemini Models", modelId: "gemini-3.8-flash" }), + limit("5h", 0, { tier: "Claude and GPT models" }), + limit("7d", 1, { tier: "Gemini 4 Argon", modelId: "gemini-4-argon" }), + ], + }, + ], + }); + const { accounts } = parseProviderUsageAccounts(output, null, []); + assert.equal(accounts.length, 2); + assert.equal(accounts[0].sevenDay.percent, 92); + assert.deepEqual(accounts[0].buckets.map((bucket) => bucket.label), [undefined, "Fable"]); + assert.equal(accounts[0].credentialId, undefined, "nothing is changeable without the runner's account list"); + // The two Gemini models draw on one quota: listed once. + assert.deepEqual(accounts[1].buckets.map((bucket) => bucket.label), ["Gemini Models", "Claude and GPT models", "Gemini 4 Argon"]); + assert.equal(accounts[1].fiveHour.percent, 0); + assert.equal(accounts[1].sevenDay.percent, 100); +}); + +test("parseProviderUsageAccounts attaches stored accounts, limits and paused accounts", () => { + const output = JSON.stringify({ + reports: [ + { provider: "anthropic", metadata: { email: "a@x.test", orgId: "org-a" }, limits: [limit("7d", 0.5)] }, + { provider: "anthropic", metadata: { email: "a@x.test", orgId: "org-b" }, limits: [limit("7d", 0.6)] }, + // Fetched before b@x.test was paused. + { provider: "anthropic", metadata: { email: "b@x.test" }, limits: [limit("7d", 0.1)] }, + { provider: "github-copilot", metadata: { accountId: "gh-login" }, limits: [limit("monthly", 1.01)] }, + ], + }); + const stored = [ + { credentialId: 8, provider: "anthropic", email: "a@x.test", orgId: "org-b", paused: false }, + { credentialId: 7, provider: "anthropic", email: "a@x.test", orgId: "org-a", paused: false }, + { credentialId: 9, provider: "anthropic", email: "b@x.test", paused: true }, + // Copilot credentials carry no identity. + { credentialId: 4, provider: "github-copilot", paused: false }, + ]; + const policies = [ + { provider: "anthropic", account: { email: "a@x.test", orgId: "org-b" }, reservePct: 20, priority: 1 }, + { provider: "anthropic", account: { email: "b@x.test" }, reservePct: 40 }, + ]; + const { accounts } = parseProviderUsageAccounts(output, stored, policies); + assert.deepEqual( + accounts.map((account) => [account.provider, account.credentialId, account.limitPercent, account.paused ?? false, account.canLimit, account.priority]), + [ + ["anthropic", 7, undefined, false, true, undefined], + ["anthropic", 8, 80, false, true, 1], + ["github-copilot", 4, undefined, false, false, undefined], + ["anthropic", 9, 60, true, undefined, undefined], + ], + ); + assert.equal(accounts[3].accountLabel, "b@x.test"); +}); + +test("parseProviderUsageAccounts keys accounts by credential, else by label or omp's position", () => { + const output = JSON.stringify({ + reports: [ + { provider: "anthropic", metadata: { email: "a@x.test" }, limits: [limit("7d", 0.5)] }, + { provider: "antigravity-acp", metadata: {}, limits: [limit("7d", 0.5)] }, + { provider: "openai-codex", metadata: { email: "c@x.test" }, limits: [limit("7d", 0.5)] }, + ], + }); + const stored = [{ credentialId: 7, provider: "anthropic", email: "a@x.test", paused: false }]; + assert.deepEqual( + parseProviderUsageAccounts(output, stored, []).accounts.map((account) => account.key), + ["anthropic:7", "antigravity-acp:#2", "openai-codex:c@x.test"], + ); +}); + +test("parseProviderUsageAccounts does not pair a sole report with a conflicting stored identity", () => { + const diffEmail = JSON.stringify({ + reports: [{ provider: "anthropic", metadata: { email: "a@x.test", orgId: "org-a" }, limits: [limit("7d", 0.5)] }], + }); + const storedDiffEmail = [{ credentialId: 7, provider: "anthropic", email: "b@x.test", orgId: "org-a", paused: false }]; + assert.equal(parseProviderUsageAccounts(diffEmail, storedDiffEmail, []).accounts[0].credentialId, undefined); + + const diffOrg = JSON.stringify({ + reports: [{ provider: "anthropic", metadata: { email: "a@x.test", orgId: "org-a" }, limits: [limit("7d", 0.5)] }], + }); + const storedDiffOrg = [{ credentialId: 8, provider: "anthropic", email: "a@x.test", orgId: "org-b", paused: false }]; + assert.equal(parseProviderUsageAccounts(diffOrg, storedDiffOrg, []).accounts[0].credentialId, undefined); +}); + +const { invalidateUsageCache } = await import("./provider-usage.ts"); + +test("invalidateUsageCache fences an in-flight usage fetch from populating the cache later", { skip: process.platform === "win32" }, async () => { + const dir = await mkdtemp(join(tmpdir(), "ompweb-provider-usage-fence-")); + const bin = join(dir, "omp"); + const marker = join(dir, "slow-once"); + const started = join(dir, "slow-started"); + const previousBin = process.env.OMP_WEB_OMP_BIN; + try { + invalidateUsageCache(); + await writeFile(marker, ""); + await writeFile(bin, `#!/usr/bin/env node +const fs = require("node:fs"); +const marker = ${JSON.stringify(marker)}; +const started = ${JSON.stringify(started)}; +const report = (pct) => JSON.stringify({ reports: [{ provider: "p", limits: [{ scope: { windowId: "5h" }, amount: { usedFraction: pct }, window: {} }] }] }); +if (fs.existsSync(marker)) { + fs.rmSync(marker); + fs.writeFileSync(started, ""); + setTimeout(() => process.stdout.write(report(0.1)), 150); +} else { + process.stdout.write(report(0.8)); +} +`, { mode: 0o755 }); + process.env.OMP_WEB_OMP_BIN = bin; + const stale = getProviderUsage(); + const deadline = Date.now() + 2000; + const { existsSync } = await import("node:fs"); + while (!existsSync(started) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 5)); + assert.equal(existsSync(started), true, "slow fetch should have started"); + invalidateUsageCache(); + const fresh = await getProviderUsage(); + assert.equal(fresh.reports[0].fiveHour.percent, 80, "post-invalidation read must not join the pre-invalidation fetch"); + assert.equal((await stale).reports[0].fiveHour.percent, 10); + assert.equal((await getProviderUsage()).reports[0].fiveHour.percent, 80, "stale fetch completing late must not overwrite the cache"); + } finally { + invalidateUsageCache(); + if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; + else process.env.OMP_WEB_OMP_BIN = previousBin; + await rm(dir, { recursive: true, force: true }); + } +}); + +test("account route keeps credential identities and actions through quota failures and logout", { skip: process.platform === "win32" }, async (t) => { + const { GET, PATCH } = await import("../app/api/provider-usage/accounts/route.ts"); + const { DELETE } = await import("../app/api/auth/accounts/[provider]/route.ts"); + const { RpcCommandError } = await import("./omp/rpc-process.ts"); + const dir = await mkdtemp(join(tmpdir(), "ompweb-usage-accounts-")); + const bin = join(dir, "omp"); + const output = join(dir, "usage.json"); + const url = "http://localhost/api/provider-usage/accounts"; + const oldBin = process.env.OMP_WEB_OMP_BIN; + const oldAgentDir = process.env.PI_CODING_AGENT_DIR; + const oldUtility = globalThis.__ompUtilityRpcState; + let accounts = [ + { provider: "anthropic", credentialId: 1, email: "first@x.test", paused: false }, + { provider: "anthropic", credentialId: 2, email: "second@x.test", paused: false }, + { provider: "openai-codex", credentialId: 3, email: "codex@x.test", accountId: "codex-account", paused: false }, + { provider: "antigravity-acp", credentialId: 4, email: "antigravity@x.test", paused: false }, + ]; + let listError; + const utility = { + proc: { + isAlive: true, + sendCommand: async ({ type, credentialId, paused }) => { + if (type === "get_usage_accounts") { + if (listError) throw listError; + return { accounts }; + } + if (type === "set_account_paused") { + accounts = accounts.map((row) => row.credentialId === credentialId ? { ...row, paused } : row); + return {}; + } + if (type === "logout") { + accounts = accounts.filter((row) => row.credentialId !== credentialId); + return {}; + } + throw new Error(`Unexpected command: ${type}`); + }, + }, + idleTimer: null, + queue: Promise.resolve(), + }; + t.after(async () => { + invalidateUsageCache(); + clearTimeout(utility.idleTimer); + globalThis.__ompUtilityRpcState = oldUtility; + if (oldBin === undefined) delete process.env.OMP_WEB_OMP_BIN; + else process.env.OMP_WEB_OMP_BIN = oldBin; + if (oldAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = oldAgentDir; + await rm(dir, { recursive: true, force: true }); + }); + process.env.OMP_WEB_OMP_BIN = bin; + process.env.PI_CODING_AGENT_DIR = dir; + globalThis.__ompUtilityRpcState = utility; + invalidateUsageCache(); + await writeFile(join(dir, "omp-web-settings.json"), JSON.stringify({ accountNames: { "anthropic:1": "First Claude" } })); + await writeFile(bin, `#!/usr/bin/env node +if (process.argv[3] === "--json") process.stdout.write(require("node:fs").readFileSync(${JSON.stringify(output)})); +`, { mode: 0o755 }); + const first = { provider: "anthropic", metadata: { email: "first@x.test" }, limits: [limit("7d", 0.42)] }; + const codex = { provider: "openai-codex", limits: [limit("7d", 0.17, { accountId: "codex-account" })] }; + await writeFile(output, JSON.stringify({ reports: [first, codex] })); + + const get = async (suffix = "") => { + const response = await GET(new Request(url + suffix)); + assert.equal(response.status, 200); + const body = await response.json(); + return { ...body, byKey: new Map(body.accounts.map((row) => [row.key, row])) }; + }; + const pause = async (credentialId, paused) => { + const response = await PATCH(new Request(url, { method: "PATCH", body: JSON.stringify({ provider: "anthropic", credentialId, paused }) })); + assert.equal(response.status, 200); + }; + const initial = (await get()).byKey; + assert.equal(initial.size, 4); + assert.equal(initial.get("anthropic:1").name, "First Claude"); + assert.equal(initial.get("anthropic:1").sevenDay.percent, 42); + assert.equal(initial.get("anthropic:2").credentialId, 2, "a missing report does not remove a stored account"); + assert.equal(initial.get("openai-codex:3").accountLabel, "codex@x.test", "a report without an email uses the stored identity"); + assert.equal(initial.get("antigravity-acp:4").accountLabel, "antigravity@x.test"); + assert.equal(initial.get("antigravity-acp:4").sevenDay, undefined); + + await writeFile(output, "invalid usage output"); + await pause(1, true); + await pause(2, true); + const unavailable = await get("?refresh=true"); + assert.equal(unavailable.usageUnavailable, true); + assert.equal(unavailable.byKey.size, 4); + for (const id of [1, 2]) assert.equal(unavailable.byKey.get(`anthropic:${id}`).paused, true); + assert.equal(unavailable.byKey.get("anthropic:1").name, "First Claude"); + assert.equal(unavailable.byKey.get("anthropic:1").sevenDay, undefined); + await pause(1, false); + assert.equal((await get()).byKey.get("anthropic:1").paused, false); + + await writeFile(output, JSON.stringify({ reports: [first, codex] })); + assert.equal((await get()).byKey.get("anthropic:1").sevenDay.percent, 42, "failed payloads are not cached"); + accounts = accounts.filter((row) => row.credentialId !== 3); + await writeFile(output, JSON.stringify({ reports: [first] })); + assert.equal((await get()).accounts.some((row) => row.provider === "openai-codex"), false, "an external logout invalidates the cached report"); + const logout = await DELETE(new Request("http://localhost/api/auth/accounts/anthropic?credentialId=1", { method: "DELETE" }), { + params: Promise.resolve({ provider: "anthropic" }), + }); + assert.equal(logout.status, 200); + await writeFile(output, JSON.stringify({ reports: [] })); + assert.deepEqual((await get()).accounts.map((row) => row.key), ["anthropic:2", "antigravity-acp:4"]); + + listError = new Error("inventory temporarily unavailable"); + assert.equal((await GET(new Request(url))).status, 502, "transport failure is not a legacy runner"); + listError = new RpcCommandError("get_usage_accounts", "unknown command: get_usage_accounts"); + await writeFile(output, JSON.stringify({ reports: [codex] })); + assert.deepEqual((await get("?refresh=true")).accounts.map((row) => [row.provider, row.credentialId]), [["openai-codex", undefined]]); +}); diff --git a/lib/provider-usage.ts b/lib/provider-usage.ts index 9ab003758..696f466eb 100644 --- a/lib/provider-usage.ts +++ b/lib/provider-usage.ts @@ -1,9 +1,24 @@ import { execFile } from "child_process"; import { promisify } from "util"; import { OMP_NOT_FOUND, resolveOmpBin } from "./omp/omp-cli"; +import { RpcCommandError } from "./omp/rpc-process"; +import { runUtilityCommand } from "./omp/rpc-utility"; +import { readAccountPolicyConfig, writeAccountPolicies } from "./omp/settings-config"; import { createChildProcessEnvironment } from "./project-command-env"; +import { + accountPolicyValue, + canNameAccount, + reportMatchesAccount, + withAccountPolicy, + type AccountIdentity, + type StoredUsageAccount, +} from "./provider-accounts"; import { asNumber, isRecord } from "./type-guards"; +import { loadWebServerSettings, readWebServerSettingsFromDisk, saveWebServerSettings } from "./web-settings"; import type { + ProviderUsageAccount, + ProviderUsageAccountsSnapshot, + ProviderUsageBucket, ProviderUsageReport, ProviderUsageSnapshot, ProviderUsageWindowId, @@ -16,12 +31,20 @@ const USAGE_CACHE_TTL_MS = 5 * 60_000; type UsageQuery = { provider?: string; modelId?: string }; -type CachedUsage = { expiresAt: number; output: string }; +type UsagePayload = Record; +type CachedUsage = { expiresAt: number; payload: UsagePayload }; let usageCache: CachedUsage | undefined; -let usageInFlight: Promise | undefined; +let usageInFlight: Promise | undefined; let usageInFlightForced = false; +let usageGeneration = 0; +let usageAccountState: string | undefined; +export function invalidateUsageCache(): void { + usageGeneration += 1; + usageCache = undefined; + usageInFlight = undefined; +} function nonEmptyString(value: unknown): string | undefined { return typeof value === "string" && value.trim() ? value.trim() : undefined; } @@ -189,7 +212,7 @@ function normalizeReport( }); } -export function parseProviderUsageOutput(output: string, query: UsageQuery = {}, now = Date.now()): ProviderUsageSnapshot { +function parseUsagePayload(output: string): Record { let payload: unknown; try { payload = JSON.parse(output); @@ -197,21 +220,179 @@ export function parseProviderUsageOutput(output: string, query: UsageQuery = {}, throw new Error("omp usage returned invalid JSON"); } if (!isRecord(payload)) throw new Error("omp usage returned an invalid response"); - const rawReports = Array.isArray(payload.reports) ? payload.reports : []; - const reports = rawReports.flatMap((report, index) => isRecord(report) ? normalizeReport(report, query, now, index) : []); - const accountsWithoutUsage = Array.isArray(payload.accountsWithoutUsage) ? payload.accountsWithoutUsage : []; - for (const [index, account] of accountsWithoutUsage.entries()) { - if (!isRecord(account)) continue; - reports.push(...normalizeReport({ - provider: account.provider, - metadata: { email: account.email }, - }, query, now, rawReports.length + index)); + return payload; +} + +/** + * omp's raw reports, then its accounts that reported no usage as report-shaped records. Malformed + * entries stay as `undefined` so "Account N" keeps counting omp's own positions. + */ +function rawUsageReports(payload: Record): (Record | undefined)[] { + const reports = Array.isArray(payload.reports) ? payload.reports : []; + const withoutUsage = Array.isArray(payload.accountsWithoutUsage) ? payload.accountsWithoutUsage : []; + return [ + ...reports.map((report) => (isRecord(report) ? report : undefined)), + ...withoutUsage.map((account) => (isRecord(account) ? { provider: account.provider, metadata: account } : undefined)), + ]; +} + +export function parseProviderUsageOutput(output: string, query: UsageQuery = {}, now = Date.now()): ProviderUsageSnapshot { + return usageSnapshot(parseUsagePayload(output), query, now); +} + +function usageSnapshot(payload: UsagePayload, query: UsageQuery, now = Date.now()): ProviderUsageSnapshot { + const reports = rawUsageReports(payload).flatMap((report, index) => (report ? normalizeReport(report, query, now, index) : [])); + return { generatedAt: asNumber(payload.generatedAt) ?? null, reports }; +} + +/** Mirrors omp's `usageReportIdentity`: metadata first, then the first limit scope carrying the id. */ +function reportIdentity(rawReport: Record): AccountIdentity { + const metadata = isRecord(rawReport.metadata) ? rawReport.metadata : {}; + const limits = Array.isArray(rawReport.limits) ? rawReport.limits : []; + const scoped = (key: string) => limits + .map((limit) => (isRecord(limit) && isRecord(limit.scope) ? nonEmptyString(limit.scope[key]) : undefined)) + .find((value) => value !== undefined); + return { + email: nonEmptyString(metadata.email), + accountId: nonEmptyString(metadata.accountId) ?? scoped("accountId"), + projectId: nonEmptyString(metadata.projectId) ?? scoped("projectId"), + orgId: nonEmptyString(metadata.orgId) ?? scoped("orgId"), + }; +} + +function bucketLabel(report: ProviderUsageReport): string | undefined { + if (report.bucket) return report.bucket; + // Anthropic's tier is its model bucket ("fable"); other providers' tiers name quota groups as they are. + if (report.tier) return report.provider === "anthropic" ? report.tier.charAt(0).toUpperCase() + report.tier.slice(1) : report.tier; + return report.modelId; +} + +const WINDOW_KEYS = ["fiveHour", "sevenDay", "monthly"] as const; + +function mergeAccount(splits: ProviderUsageReport[], provider: string, index: number): Omit { + const first = splits[0]; + const account: Omit = { + provider, + ...(first?.accountLabel ? { accountLabel: first.accountLabel } : { accountIndex: index + 1 }), + ...(first?.plan ? { plan: first.plan } : {}), + }; + // omp repeats one quota per model drawing on it (Antigravity's Gemini models): one bucket per label. + const buckets = new Map(); + for (const split of splits) { + const label = bucketLabel(split); + const bucket = buckets.get(label) ?? { label }; + buckets.set(label, bucket); + for (const key of WINDOW_KEYS) { + const window = split[key]; + if (!window) continue; + if (!bucket[key] || window.percent > bucket[key].percent) bucket[key] = window; + if (!account[key] || window.percent > account[key].percent) account[key] = window; + } + } + if (buckets.size > 1) account.buckets = [...buckets.values()]; + return account; +} + +/** The account's limit (100 - reservePct) and priority from its `auth.accountPolicies` entry. */ +function policyFields(policies: readonly unknown[], provider: string, account: AccountIdentity): Pick { + const reservePct = accountPolicyValue(policies, provider, account, "reservePct"); + const priority = accountPolicyValue(policies, provider, account, "priority"); + return { ...(reservePct !== undefined ? { limitPercent: 100 - reservePct } : {}), ...(priority !== undefined ? { priority } : {}) }; +} + +export function parseProviderUsageAccounts( + output: string | null, + stored: readonly StoredUsageAccount[] | null, + policies: readonly unknown[], + now = Date.now(), +): { generatedAt: number | null; accounts: ProviderUsageAccount[] } { + return usageAccounts(output === null ? null : parseUsagePayload(output), stored, policies, now); +} + +function usageAccounts( + payload: UsagePayload | null, + stored: readonly StoredUsageAccount[] | null, + policies: readonly unknown[], + now = Date.now(), +): { generatedAt: number | null; accounts: ProviderUsageAccount[] } { + const rows = stored ?? []; + const entries = (payload ? rawUsageReports(payload) : []).flatMap((raw, index) => { + const provider = nonEmptyString(raw?.provider); + if (!raw || !provider) return []; + return [{ provider, index, identity: reportIdentity(raw), splits: normalizeReport(raw, {}, now, index) }]; + }); + const claimed = new Set(); + const accounts: Omit[] = []; + for (const entry of entries) { + const providerAccounts = rows.filter((account) => account.provider === entry.provider); + const matches = providerAccounts.filter((account) => reportMatchesAccount(entry.identity, account)); + const active = matches.filter((account) => !account.paused); + // A report fetched before its account was paused: the paused row below stands for it. + if (active.length === 0 && matches.length > 0) continue; + const sole = providerAccounts.length === 1 ? providerAccounts[0] : undefined; + const hasIdentity = (id: AccountIdentity) => !!(id.email || id.accountId || id.projectId || id.orgId); + const singleReport = entries.filter((other) => other.provider === entry.provider).length === 1; + const soleActive = sole?.paused === false ? sole : undefined; + // Copilot credentials carry no identity: fall back only when at least one side lacks identity, never on conflict. + const match = active.length === 1 + ? active[0] + : active.length === 0 && singleReport && soleActive && (!hasIdentity(entry.identity) || !hasIdentity(soleActive)) + ? soleActive + : undefined; + const account = mergeAccount(entry.splits, entry.provider, entry.index); + if (match && !claimed.has(match.credentialId)) { + claimed.add(match.credentialId); + account.credentialId = match.credentialId; + if (match.email) { + account.accountLabel = match.email; + delete account.accountIndex; + } + Object.assign(account, policyFields(policies, entry.provider, match)); + account.canPrioritize = canNameAccount(match); + account.canLimit = account.canPrioritize && WINDOW_KEYS.some((key) => account[key]); + } + accounts.push(account); } - const generatedAt = asNumber(payload.generatedAt) ?? null; - return { generatedAt, reports }; + for (const [index, storedAccount] of rows.entries()) { + if (claimed.has(storedAccount.credentialId)) continue; + accounts.push({ + provider: storedAccount.provider, + ...(storedAccount.email ? { accountLabel: storedAccount.email } : { accountIndex: index + 1 }), + credentialId: storedAccount.credentialId, + paused: storedAccount.paused, + canPrioritize: canNameAccount(storedAccount), + ...policyFields(policies, storedAccount.provider, storedAccount), + }); + } + return { + generatedAt: asNumber(payload?.generatedAt) ?? null, + // shortcut: an account without a stored credential is keyed by its label or omp's position, so a + // name for "Account 5" follows the position if omp reorders its reports; key it by identity when that bites. + accounts: accounts.map((account) => ({ + ...account, + key: `${account.provider}:${account.credentialId ?? account.accountLabel ?? `#${account.accountIndex}`}`, + })), + }; } -async function fetchProviderUsage(refresh = false): Promise { +async function listStoredUsageAccounts(): Promise { + const { accounts } = await runUtilityCommand<{ accounts?: unknown }>({ type: "get_usage_accounts" }, 30_000); + if (!Array.isArray(accounts)) throw new Error("get_usage_accounts returned no accounts"); + return accounts.flatMap((row) => { + if (!isRecord(row) || !Number.isInteger(row.credentialId) || typeof row.provider !== "string" || typeof row.paused !== "boolean") return []; + return [{ + credentialId: row.credentialId as number, + provider: row.provider, + paused: row.paused, + email: nonEmptyString(row.email), + accountId: nonEmptyString(row.accountId), + projectId: nonEmptyString(row.projectId), + orgId: nonEmptyString(row.orgId), + }]; + }); +} + +async function fetchProviderUsage(refresh = false): Promise { const bin = resolveOmpBin(); if (!bin) throw new Error(OMP_NOT_FOUND); if (refresh) { @@ -232,26 +413,96 @@ async function fetchProviderUsage(refresh = false): Promise { windowsHide: true, env: createChildProcessEnvironment(), }); - return stdout; + return parseUsagePayload(stdout); } -function getUsageOutput(refresh = false): Promise { - if (!refresh && usageCache && usageCache.expiresAt > Date.now()) return Promise.resolve(usageCache.output); +function getUsagePayload(refresh = false): Promise { + if (!refresh && usageCache && usageCache.expiresAt > Date.now()) return Promise.resolve(usageCache.payload); if (usageInFlight) { return refresh && !usageInFlightForced - ? usageInFlight.then(() => getUsageOutput(true), () => getUsageOutput(true)) + ? usageInFlight.then(() => getUsagePayload(true), () => getUsagePayload(true)) : usageInFlight; } + const generation = usageGeneration; usageInFlightForced = refresh; - usageInFlight = fetchProviderUsage(refresh) - .then((output) => { - usageCache = { output, expiresAt: Date.now() + USAGE_CACHE_TTL_MS }; - return output; + const pending = fetchProviderUsage(refresh) + .then((payload) => { + if (generation === usageGeneration) { + usageCache = { payload, expiresAt: Date.now() + USAGE_CACHE_TTL_MS }; + } + return payload; }) - .finally(() => { usageInFlight = undefined; }); - return usageInFlight; + .finally(() => { + if (usageInFlight === pending) usageInFlight = undefined; + }); + usageInFlight = pending; + return pending; } export async function getProviderUsage(query: UsageQuery = {}, refresh = false): Promise { - return parseProviderUsageOutput(await getUsageOutput(refresh), query); + return usageSnapshot(await getUsagePayload(refresh), query); +} + +export async function getProviderUsageAccounts(refresh = false): Promise { + const stored = await listStoredUsageAccounts().catch((error: unknown) => { + if (error instanceof RpcCommandError && error.message === "unknown command: get_usage_accounts") return null; + throw error; + }); + if (stored) { + // A cached report can outlive its credential, including when logout happened in the CLI. + const state = JSON.stringify([...stored].sort((a, b) => a.credentialId - b.credentialId)); + if (usageAccountState !== undefined && usageAccountState !== state) invalidateUsageCache(); + usageAccountState = state; + } + const payload = await getUsagePayload(refresh).catch((error: unknown) => { + if (!stored) throw error; + return null; + }); + const { policies, reservePct } = readAccountPolicyConfig(); + const { accountNames: names, accountOrder } = loadWebServerSettings(); + const { generatedAt, accounts } = usageAccounts(payload, stored, policies); + // Rows the user placed come first in their order; new ones follow in omp's order. + const rank = (key: string, index: number) => (accountOrder.includes(key) ? accountOrder.indexOf(key) : accountOrder.length + index); + const ordered = accounts.map((account, index) => ({ account, rank: rank(account.key, index) })).sort((a, b) => a.rank - b.rank); + return { + generatedAt, + ...(payload === null ? { usageUnavailable: true } : {}), + accounts: ordered.map(({ account }) => (names[account.key] ? { ...account, name: names[account.key] } : account)), + defaultLimitPercent: 100 - reservePct, + }; +} + +/** Names an account in the overview (`null` or blank: back to its email or "Account N"). */ +export function renameProviderUsageAccount(key: string, name: string | null): void { + const accountNames = { ...readWebServerSettingsFromDisk().accountNames }; + const trimmed = name?.trim(); + if (trimmed) accountNames[key] = trimmed; + else delete accountNames[key]; + saveWebServerSettings({ accountNames }); +} + +/** Pause or resume a stored account, or set (`null`: clear) its usage limit or priority. */ +export async function updateProviderUsageAccount( + provider: string, + credentialId: number, + change: { paused?: boolean; limitPercent?: number | null; priority?: number | null }, +): Promise { + if (change.limitPercent !== undefined || change.priority !== undefined) { + const siblings = (await listStoredUsageAccounts()).filter((account) => account.provider === provider); + const account = siblings.find((candidate) => candidate.credentialId === credentialId); + if (!account) throw new Error(`No stored ${provider} account ${credentialId}`); + if (!canNameAccount(account)) throw new Error("omp cannot name this account in a policy: it has no email, account or project id"); + const { policies: initialPolicies, reservePct } = readAccountPolicyConfig(); + let policies = initialPolicies; + if (change.limitPercent !== undefined) { + policies = withAccountPolicy(policies, provider, account, siblings, "reservePct", change.limitPercent === null ? null : 100 - change.limitPercent, reservePct); + } + if (change.priority !== undefined) policies = withAccountPolicy(policies, provider, account, siblings, "priority", change.priority); + writeAccountPolicies(policies); + } + if (change.paused !== undefined) { + await runUtilityCommand({ type: "set_account_paused", providerId: provider, credentialId, paused: change.paused }, 120_000); + } + // The cached report still lists a paused account as active and lacks a resumed one. + invalidateUsageCache(); } diff --git a/lib/web-settings.test.mjs b/lib/web-settings.test.mjs index 9826a2529..563547b6e 100644 --- a/lib/web-settings.test.mjs +++ b/lib/web-settings.test.mjs @@ -23,7 +23,7 @@ function withAgentDir(run) { test("defaults apply when no settings file exists yet", () => { withAgentDir(() => { - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30, accountNames: {}, accountOrder: [] }); }); }); @@ -39,7 +39,7 @@ test("agentEnv round-trips through the settings file", () => { delete globalThis.__ompWebSettingsCache; process.env.PI_CODING_AGENT_DIR = fresh; try { - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { OBSIDIAN_API_KEY: "secret" }, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { OBSIDIAN_API_KEY: "secret" }, browserTransport: "ws", uploadRetentionDays: 30, accountNames: {}, accountOrder: [] }); } finally { rmSync(fresh, { recursive: true, force: true }); } @@ -60,7 +60,7 @@ test("a patch leaves the other keys untouched", () => { withAgentDir(() => { saveWebServerSettings({ autoResumeSessions: true, agentEnv: { A: "1" } }); saveWebServerSettings({ agentEnv: { B: "2" } }); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: true, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { B: "2" }, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: true, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { B: "2" }, browserTransport: "ws", uploadRetentionDays: 30, accountNames: {}, accountOrder: [] }); }); }); @@ -107,7 +107,7 @@ test("settings GET reports peer permission changes and refuses unreadable values test("corrupt files fall back to defaults instead of throwing", () => { withAgentDir((dir) => { writeFileSync(join(dir, "omp-web-settings.json"), "{ not json", "utf8"); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30, accountNames: {}, accountOrder: [] }); }); }); @@ -227,7 +227,7 @@ test("a missing browserTransport reads as ws, sse and ws round-trip, and unknown for (const value of ["ws-client", "ws-client-split", "ws-session", "ws-pool", "websocket", true]) { withAgentDir((dir) => { writeFileSync(join(dir, "omp-web-settings.json"), JSON.stringify({ browserTransport: value, browserTransportPerSocket: 8, browserTransportMaxSockets: 3 }), "utf8"); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30 }, `${JSON.stringify(value)} reads as ws`); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: {}, browserTransport: "ws", uploadRetentionDays: 30, accountNames: {}, accountOrder: [] }, `${JSON.stringify(value)} reads as ws`); }); } }); @@ -239,7 +239,7 @@ test("only string-valued agentEnv entries are kept", () => { JSON.stringify({ autoResumeSessions: "yes", agentEnv: { GOOD: "1", BAD: 2, WORSE: null, NESTED: { a: 1 } } }), "utf8", ); - assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { GOOD: "1" }, browserTransport: "ws", uploadRetentionDays: 30 }); + assert.deepEqual(loadWebServerSettings(), { autoResumeSessions: false, agentToolsEnabled: false, githubWritesUnasked: false, githubActionsPermissions: { dispatch: "ask", cancel: "ask", rerun: "ask" }, agentEnv: { GOOD: "1" }, browserTransport: "ws", uploadRetentionDays: 30, accountNames: {}, accountOrder: [] }); }); }); diff --git a/lib/web-settings.ts b/lib/web-settings.ts index 59080a5f9..34eea6e39 100644 --- a/lib/web-settings.ts +++ b/lib/web-settings.ts @@ -36,6 +36,10 @@ export interface WebServerSettings { browserTransport: BrowserTransport; /** Days a sent upload stays in its session's `local://uploads/` on every host; `null` keeps them for ever (docs/specs/2026-11-02-file-uploads-design.md, U6). */ uploadRetentionDays: number | null; + /** Names for accounts in the sidebar's provider usage, keyed by `ProviderUsageAccount.key`. */ + accountNames: Record; + /** Order of the sidebar's provider usage rows (`ProviderUsageAccount.key`); unlisted rows follow in omp's order. */ + accountOrder: string[]; } const DEFAULTS: WebServerSettings = { @@ -46,6 +50,8 @@ const DEFAULTS: WebServerSettings = { agentEnv: {}, browserTransport: "ws", uploadRetentionDays: DEFAULT_UPLOAD_RETENTION_DAYS, + accountNames: {}, + accountOrder: [], }; /** What every hello and `transport` frame tells the browser. */ @@ -53,8 +59,8 @@ export function browserTransportState(settings = loadWebServerSettings()): Brows return { transport: settings.browserTransport }; } -/** String-valued entries only — the allow-list lives in lib/omp/agent-env.ts. */ -function readAgentEnvRecord(value: unknown): Record { +/** String-valued entries only — agentEnv's allow-list lives in lib/omp/agent-env.ts. */ +function readStringRecord(value: unknown): Record { if (!isRecord(value)) return {}; const entries: Array<[string, string]> = []; for (const [name, entry] of Object.entries(value)) { @@ -96,9 +102,11 @@ function normalizeSettings(raw: Record): WebServerSettings { agentToolsEnabled: raw.agentToolsEnabled === true, githubWritesUnasked: raw.githubWritesUnasked === true, githubActionsPermissions: readGithubActionsPermissions(raw.githubActionsPermissions), - agentEnv: readAgentEnvRecord(raw.agentEnv), + agentEnv: readStringRecord(raw.agentEnv), browserTransport: BROWSER_TRANSPORTS.find((transport) => transport === raw.browserTransport) ?? "ws", uploadRetentionDays: isUploadRetentionDays(raw.uploadRetentionDays) ? raw.uploadRetentionDays : DEFAULT_UPLOAD_RETENTION_DAYS, + accountNames: readStringRecord(raw.accountNames), + accountOrder: Array.isArray(raw.accountOrder) ? raw.accountOrder.filter((key): key is string => typeof key === "string") : [], }; } diff --git a/runner/src/commands/agents.ts b/runner/src/commands/agents.ts index 1e49bdd5e..39f1a1651 100644 --- a/runner/src/commands/agents.ts +++ b/runner/src/commands/agents.ts @@ -13,6 +13,7 @@ * Host frames: * host → omp {t:"login_input_response", id, value} value: string, or null/absent for cancelled */ +import { Database } from "bun:sqlite"; import * as fs from "node:fs/promises"; import { getOAuthProviders } from "@oh-my-pi/pi-ai/oauth"; import { AgentLifecycleManager } from "@oh-my-pi/pi-coding-agent/registry/agent-lifecycle"; @@ -32,10 +33,12 @@ import { TASK_SUBAGENT_PROGRESS_CHANNEL, } from "@oh-my-pi/pi-coding-agent/task"; import type { EventBus } from "@oh-my-pi/pi-coding-agent/utils/event-bus"; -import { isEnoent, logger } from "@oh-my-pi/pi-utils"; +import { getAgentDbPath, isEnoent, logger } from "@oh-my-pi/pi-utils"; import type { CommandContext, CommandTable, FrameTable } from "./types"; const LOGIN_INPUT_TIMEOUT_MS = 600_000; +/** The `disabled_cause` a paused account carries; only tombstones with it are resumed. */ +const PAUSED_CAUSE = "paused in omp-web"; /** Settled subagents whose transcript stays readable, and ids remembered from a previous session. */ const MAX_RETAINED_SUBAGENTS = 256; @@ -424,6 +427,82 @@ export const agentsCommands: CommandTable = { if (!removed) throw new Error(`logout: credential ${credentialId} is not stored for ${providerId}`); return { remainingSource }; }, + + /** Every stored OAuth account with the identity omp's account policies match, paused ones included. */ + get_usage_accounts: async ({ session }) => { + const { credentials } = session.modelRegistry.authStorage; + await credentials.reload(); + const accounts = credentials + .list() + .flatMap(({ id, provider, credential }) => + credential.type === "oauth" + ? [{ + credentialId: id, + provider, + email: credential.email, + accountId: credential.accountId, + projectId: credential.projectId, + orgId: credential.orgId, + paused: false, + }] + : [], + ); + for (const row of await credentials.listDisabled()) { + if (row.cause !== PAUSED_CAUSE) continue; + accounts.push({ + credentialId: row.id, + provider: row.provider, + email: row.email, + accountId: row.accountId, + projectId: undefined, + orgId: row.orgId, + paused: true, + }); + } + return { accounts }; + }, + + /** + * Pause keeps the credential as an omp tombstone, so no process picks it and nothing is signed out. + * omp has no call that revives a tombstone; resuming clears the cause in agent.db, which bumps omp's + * change revision so every process reloads. + */ + set_account_paused: async ({ session }, args) => { + const { providerId, credentialId, paused } = args; + if ( + typeof providerId !== "string" || + typeof credentialId !== "number" || + !Number.isInteger(credentialId) || + typeof paused !== "boolean" + ) { + throw new Error("set_account_paused: providerId must be a string, credentialId an integer and paused a boolean"); + } + const { modelRegistry } = session; + const { credentials } = modelRegistry.authStorage; + await credentials.reload(); + if (paused) { + const active = credentials.list(providerId).some(row => row.id === credentialId && row.credential.type === "oauth"); + if (!active || !(await credentials.disable(credentialId, PAUSED_CAUSE))) { + throw new Error(`set_account_paused: no active OAuth account ${credentialId} for ${providerId}`); + } + } else { + const db = new Database(getAgentDbPath()); + try { + db.run("PRAGMA busy_timeout = 5000"); + const { changes } = db.run( + "UPDATE auth_credentials SET disabled_cause = NULL, updated_at = CAST(strftime('%s','now') AS INTEGER) WHERE id = ? AND provider = ? AND disabled_cause = ?", + [credentialId, providerId, PAUSED_CAUSE], + ); + if (changes !== 1) throw new Error(`set_account_paused: account ${credentialId} for ${providerId} is not paused`); + } finally { + db.close(); + } + await credentials.reload(); + } + await modelRegistry.refreshProvider(providerId, "online"); + await session.refreshScopedModels(); + return {}; + }, }; export const agentsFrames: FrameTable = { diff --git a/server/routes.ts b/server/routes.ts index d6cfea353..e62d951fd 100644 --- a/server/routes.ts +++ b/server/routes.ts @@ -49,6 +49,7 @@ import * as ompVersion from "@/app/api/omp-version/route"; import * as plugins from "@/app/api/plugins/route"; import * as projectsClone from "@/app/api/projects/clone/route"; import * as projects from "@/app/api/projects/route"; +import * as providerUsageAccounts from "@/app/api/provider-usage/accounts/route"; import * as providerUsage from "@/app/api/provider-usage/route"; import * as providersEnable from "@/app/api/providers/enable/route"; import * as sessionsIdArchive from "@/app/api/sessions/[id]/archive/route"; @@ -152,6 +153,7 @@ export const ROUTE_MODULES: Record = { "plugins": plugins, "projects/clone": projectsClone, "projects": projects, + "provider-usage/accounts": providerUsageAccounts, "provider-usage": providerUsage, "providers/enable": providersEnable, "sessions/[id]/archive": sessionsIdArchive,