diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 305c2c87..ac93dbc3 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -33,9 +33,9 @@ paseo plugin ls paseo-omp Open the **OMP** sidebar to review the provider-profile contract, choose which composer pills appear, browse and edit native scalar settings, manage OMP-native plugins, verify runtime health, and generate a bounded support report under **Help**. The same tabs, including Accounts, MCPs, and Composer, are available in the workspace OMP panel, which adds a workspace-only Security tab. Then create an agent and select **OMP Plugin**; on a new install, [enable it](#plugin-provider-opt-in) and restart the daemon first. Its optional **MCP** composer control runs OMP-native management commands in the current session; setup questions and authorization stay in that chat timeline, where OAuth can open in a workspace-scoped Paseo Browser or on the current device. While OMP subagents run, a row under each `task` card in the conversation lets you steer or stop one of them; this needs OMP 18.4.9 or newer. Composer pill preferences are shared by clients connected to the same host; normal use requires no other plugin-specific settings. -Open the **Accounts** tab of the **OMP** sidebar to see the logins in OMP's own credential store with their usage and banked resets, add a login through OMP's own sign-in, sign one out, spend a banked reset, and steer OMP's balancing: prefer a login, keep part of its quota in reserve, and set what OMP does at a limit. Steering is written to OMP's own config. See [OMP accounts](docs/configuration.md#omp-accounts). +Open the **Accounts** tab of the **OMP** sidebar to see the logins in OMP's own credential store with their usage and banked resets, add a login through OMP's own sign-in, sign one out, spend a banked reset, and steer OMP's balancing: prefer a login, keep part of its quota in reserve, and set what OMP does at a limit. Each login shows plan and organization badges from its usage report, such as **Business**, **Pro Lite**, **Personal** or an organization name, and the label drops OMP's parenthesized organization once a badge shows it. Steering is written to OMP's own config. See [OMP accounts](docs/configuration.md#omp-accounts). -The quota popover groups recorded limits by provider and OMP account, showing an available recorded email or, when absent, the Copilot account ID (GitHub username) across that account's windows. Duplicate and unnamed accounts receive numbers in opaque account-key order, so changing usage does not swap their numbers; accounts are still displayed by highest usage. Duplicate-name suffixes stay visible when long emails truncate, and a lone unnamed account needs no heading. Copilot accounts also show **GitHub** or **GHE · host**, using the enterprise URL in OMP's recorded account key; unrecognized keys show neither. Only a server-side SHA-256 hash of the account key reaches the client. **CURRENT PROVIDER** identifies the session's provider, not its active account. Provider summary percentages show the highest recorded usage across that provider's accounts. +The quota popover groups recorded limits by provider and OMP account, showing an available recorded email or, when absent, the Copilot account ID (GitHub username) across that account's windows. Duplicate and unnamed accounts receive numbers in opaque account-key order, so changing usage does not swap their numbers; accounts are still displayed by highest usage, and a divider separates each account. Duplicate-name suffixes stay visible when long emails truncate, and a lone unnamed account needs no heading. Copilot accounts also show **GitHub** or **GHE · host**, using the enterprise URL in OMP's recorded account key; unrecognized keys show neither. Badges beside each account name show the plan (such as **Business** or **Pro Lite**) and organization name from OMP's cached usage report for that account; an Anthropic organization named after the account's email shows as **Personal**, and accounts without a cached plan or organization show no badge. Only a server-side SHA-256 hash of the account key reaches the client. The popover marks the login the session uses: a live OMP Plugin session answers through its OMP runtime (`get_logout_accounts`); any other OMP session, including Paseo's bundled **omp** provider, is matched through the session id Paseo stored for the agent to the pin OMP recorded (`session:sticky::`, kept 30 days past its last use). Both read the agent's own store: a named-profile agent never reads the daemon default store, and an agent Paseo cannot look up gets no account marks. That account leads the current provider marked **IN USE**, and every other login linked to recorded usage has an accent **Switch** button at the end of its name row, which sends `/session pin OAuth credential #` to the session, so the switch and OMP's reply appear in the chat timeline. A login that is the provider's only stored credential, API keys included, shows **ONLY LOGIN** in that spot instead of **Switch**; being the only stored login does not prove use, since an environment or explicit key can still serve the session, so it gets **IN USE** only when OMP reports or recorded it. A login without recorded usage has no row, so it cannot be switched to from the popover. A login links to recorded usage by OMP's identity rule: the organization must match, including being absent on both sides, then the email decides, else the account id. Only a provider whose single login and single usage account both lack any identity, organization included (Copilot), links without one. A session that has not yet sent a request to the provider has no recorded pin; its linked logins can still be switched to and **CURRENT PROVIDER** identifies only the provider. The composer pill shows the provider icon and the highest recorded usage of the account in use, such as **19%**; its tooltip names the provider and that account. When the account in use is unknown or has no recorded usage, the pill shows the highest usage across the provider's accounts and its tooltip says **all accounts**. Reset countdowns a day or more away show days and hours, such as **resets 14d 21h**. Open the **MCPs** tab of the **OMP** sidebar to list the MCP servers OMP connects to, add one by URL or command, test, enable, disable or remove it, and sign a remote server in through your browser, like **Accounts** does for logins. See [OMP MCP servers](docs/configuration.md#omp-mcp-servers). @@ -67,7 +67,7 @@ At startup the plugin discovers directory names under `~/.omp/profiles/` (or `PI Separate provider identities let the model picker request the correct profile catalog before an agent exists. Existing `omp-plugin` and bundled `omp` agents retain their provider; they are not migrated automatically. Profile names use OMP's lowercase grammar, including dotted names such as `team.prod`. -The OMP sidebar and memory panel expose an explicit store selector. Settings, plugins, quota, history, memory and diagnostics use that selection, and profile-agent popovers derive it from the provider ID. OMP-compatible XDG data and state roots are honored when a migrated profile uses them. Default-provider views are labelled **Daemon default store**; changing `providerOptions.command` on the default provider does not make those views profile-aware. Workspace configuration remains project-scoped, with the selected profile supplying inherited settings. Hub records are daemon-wide. The RPCs also accept an explicit absolute `store.agentDir` for custom stores; it is mutually exclusive with `store.profile`. +The OMP sidebar and memory panel expose an explicit store selector. Settings, plugins, quota, history, memory and diagnostics use that selection, and profile-agent popovers derive it from the provider ID. OMP-compatible XDG data and state roots are honored when a migrated profile uses them. Default-provider views are labelled **Daemon default store**, except the quota popover, which names only a profile or custom store; changing `providerOptions.command` on the default provider does not make those views profile-aware. Workspace configuration remains project-scoped, with the selected profile supplying inherited settings. Hub records are daemon-wide. The RPCs also accept an explicit absolute `store.agentDir` for custom stores; it is mutually exclusive with `store.profile`. Profile selection is request-local: concurrent clients cannot change each other's process environment or cached results. Settings edits affect the selected store immediately. diff --git a/paseo-omp/client/omp-accounts-section.tsx b/paseo-omp/client/omp-accounts-section.tsx index 3ee7e3ae..68a7ddae 100644 --- a/paseo-omp/client/omp-accounts-section.tsx +++ b/paseo-omp/client/omp-accounts-section.tsx @@ -10,7 +10,7 @@ import { useToast, } from "@getpaseo/plugin/client/ui"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { type ReactNode, useRef, useState } from "react"; +import { type ReactElement, type ReactNode, useRef, useState } from "react"; import { Pressable, Text, View } from "react-native"; import { cancelOmpAccountLogin, @@ -41,6 +41,7 @@ import { } from "./omp-accounts-state"; import type { OmpConfigStyles } from "./omp-config-styles"; import { ompStoreKey } from "./omp-store-state"; +import { providerIcon } from "./provider-brand"; import { quotaResetLabel, quotaSeverityFromFraction } from "./quota-state"; type Theme = PluginSurfaceProps["theme"]; @@ -189,11 +190,30 @@ function AccountCard({ const reserveShown = reserveOptions(account, defaultReservePct); const age = usageAgeLabel(account); return ( - + - - {account.label} - + + {/* Cards wrap into columns away from their provider heading, so each names its own. */} + + + {account.label} + + {account.tags.map((tag) => ( + + + {tag} + + + ))} + {account.resets ? ( {resetsLabel(account.resets)} @@ -260,6 +280,28 @@ function AccountCard({ ); } +/** Fixed account card width: wide enough for the label, badges and the reserve picker on one row. */ +const ACCOUNT_CARD_WIDTH = 440; +const ACCOUNT_GRID_GAP = 10; + +/** + * Fixed-width account cards that wrap, as many to a row as the page fits, instead of each card + * stretching across the page. Nothing is measured, so resizing never flips the column count back. + * A page narrower than one card shrinks the card to the page. + */ +function AccountGrid({ children }: { children: ReactElement[] }) { + return ( + + {children.map((child) => ( + // Each wrapper takes its card's key, so a removed login never shifts another card's state. + + {child} + + ))} + + ); +} + type SettingRow = { path: OmpAccountsSettingPath; label: string; @@ -821,7 +863,10 @@ export function OmpAccountsSection({ ) : null} {groups.map(({ provider, accounts: logins }) => ( - {provider.name} + + + {provider.name} + {view?.balance .filter((preview) => preview.provider === provider.id) .map((preview) => ( @@ -829,19 +874,21 @@ export function OmpAccountsSection({ {balanceLine(preview)} ))} - {logins.map((account) => ( - setPending({ kind: "remove", account })} - onRedeem={() => setPending({ kind: "reset", account })} - onSteer={(change) => steer.mutate({ kind: "account", account, ...change })} - /> - ))} + + {logins.map((account) => ( + setPending({ kind: "remove", account })} + onRedeem={() => setPending({ kind: "reset", account })} + onSteer={(change) => steer.mutate({ kind: "account", account, ...change })} + /> + ))} + ))} {view?.installed && view.fetchedAt !== null ? ( diff --git a/paseo-omp/client/provider-brand.ts b/paseo-omp/client/provider-brand.ts new file mode 100644 index 00000000..02c22209 --- /dev/null +++ b/paseo-omp/client/provider-brand.ts @@ -0,0 +1,31 @@ +import type { PluginIcon } from "@getpaseo/plugin/client"; +import antigravitySvg from "../shared/provider-icons/antigravity.svg"; +import claudeSvg from "../shared/provider-icons/claude.svg"; +import codexSvg from "../shared/provider-icons/codex.svg"; +import copilotSvg from "../shared/provider-icons/copilot.svg"; +import grokSvg from "../shared/provider-icons/grok.svg"; + +// Paseo's provider brand icons are host-internal: a host icon name such as "claude" fails button +// validation and draws nothing through `Icon`. The same marks ship here as inline SVG that paints +// with `currentColor`, so the host tints them like any icon; other providers use Lucide. +const BRAND_ICONS: Record = { + anthropic: { svg: claudeSvg }, + "antigravity-cli": { svg: antigravitySvg }, + "github-copilot": { svg: copilotSvg }, + "google-antigravity": { svg: antigravitySvg }, + openai: { svg: codexSvg }, + "openai-codex": { svg: codexSvg }, + xai: { svg: grokSvg }, + "xai-oauth": { svg: grokSvg }, +}; + +const LUCIDE_ICONS: Record = { + azure: "Cloud", + cursor: "MousePointer2", +}; + +/** The provider's brand mark when known, else the Lucide icon closest to it, else a gauge. */ +export function providerIcon(provider: string | null): PluginIcon { + if (!provider) return "Gauge"; + return BRAND_ICONS[provider] ?? LUCIDE_ICONS[provider] ?? "Gauge"; +} diff --git a/paseo-omp/client/provider-icon.tsx b/paseo-omp/client/provider-icon.tsx index 63b29c25..8bd67695 100644 --- a/paseo-omp/client/provider-icon.tsx +++ b/paseo-omp/client/provider-icon.tsx @@ -2,7 +2,8 @@ import type { PluginButtonIconProps } from "@getpaseo/plugin/client"; import { Icon } from "@getpaseo/plugin/client/ui"; import type { ComponentType } from "react"; import { View } from "react-native"; -import { type QuotaSeverity, quotaProviderIconName } from "./quota-state"; +import { providerIcon } from "./provider-brand"; +import type { QuotaSeverity } from "./quota-state"; export function quotaProviderIcon( provider: string | null, @@ -19,7 +20,7 @@ export function quotaProviderIcon( : color; return ( - + ); } diff --git a/paseo-omp/client/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index aa44582e..c2e24199 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -1,38 +1,73 @@ -import { type PluginButtonContentProps, useAgent, useRpc } from "@getpaseo/plugin/client"; +import { type PluginButtonContentProps, useAgent, usePaseo, useRpc } from "@getpaseo/plugin/client"; import { Icon } from "@getpaseo/plugin/client/ui"; -import { useQuery } from "@tanstack/react-query"; -import { useMemo } from "react"; -import { Text, View } from "react-native"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useMemo, useState } from "react"; +import { Pressable, Text, View } from "react-native"; import { storeForProvider, storeLabel } from "../shared/omp-store"; -import { listOmpQuotas } from "../shared/quota"; +import { listOmpQuotas, listOmpSessionAccounts, type OmpSessionAccount } from "../shared/quota"; import { ompStoreKey } from "./omp-store-state"; +import { providerIcon } from "./provider-brand"; import { type QuotaProviderGroup, + type QuotaSessionAccountGroup, + type QuotaSeverity, quotaDetailLabel, quotaProviderFromSession, quotaProviderGroups, - quotaProviderIconName, quotaProviderLabel, + quotaSessionAccounts, quotaSeverityFromFraction, + sessionPinCommand, } from "./quota-state"; const QUOTA_POLL_MS = 30_000; export function QuotaPopover(props: PluginButtonContentProps) { - const { theme, layout } = props; + const { theme, layout, close } = props; const agentId = props.context === "agent" ? props.agentId : ""; - const session = useAgent(agentId, (agent) => ({ model: agent.model, provider: agent.provider })); + const session = useAgent(agentId, (agent) => ({ + model: agent.model, + provider: agent.provider, + status: agent.status, + })); const currentProvider = quotaProviderFromSession(session?.provider ?? "", session?.model ?? null); const store = storeForProvider(session?.provider); + const paseo = usePaseo(); + const queryClient = useQueryClient(); const loadQuotas = useRpc(listOmpQuotas); + const loadSessionAccounts = useRpc(listOmpSessionAccounts); const quotas = useQuery({ queryKey: ["paseo-omp", "quotas", ompStoreKey(store)], queryFn: () => loadQuotas({ store }), enabled: session !== undefined && session !== null, refetchInterval: QUOTA_POLL_MS, }); + const sessionAccountsKey = ["paseo-omp", "session-accounts", agentId, currentProvider]; + const sessionAccounts = useQuery({ + queryKey: sessionAccountsKey, + queryFn: () => loadSessionAccounts({ agentId, provider: currentProvider ?? "" }), + enabled: Boolean(agentId && currentProvider), + refetchInterval: QUOTA_POLL_MS, + retry: false, + }); + const [switching, setSwitching] = useState(null); + const [switchError, setSwitchError] = useState(null); + + async function switchTo(login: OmpSessionAccount): Promise { + setSwitching(login.credentialId); + setSwitchError(null); + try { + await paseo.agents.ref(agentId).send(sessionPinCommand(login.credentialId)); + await queryClient.invalidateQueries({ queryKey: sessionAccountsKey }); + close(); + } catch (cause) { + setSwitchError(cause instanceof Error ? cause.message : "Could not switch the account."); + } finally { + setSwitching(null); + } + } - function severityColor(severity: ReturnType): string { + function severityColor(severity: QuotaSeverity): string { if (severity === "danger") return theme.colors.statusDanger; if (severity === "warning") return theme.colors.statusWarning; if (severity === "ok") return theme.colors.statusSuccess; @@ -84,15 +119,53 @@ export function QuotaPopover(props: PluginButtonContentProps) { overflow: "hidden" as const, }, detail: { color: theme.colors.foregroundMuted, fontSize: 11 }, - account: { gap: 6, paddingTop: 4 }, - accountHeading: { flexDirection: "row" as const, alignItems: "baseline" as const }, - accountLabel: { - color: theme.colors.foregroundMuted, + // Accounts after the first get a divider so each account's limits read as one block. + account: (first: boolean) => ({ + gap: 6, + paddingTop: first ? 4 : 10, + marginTop: first ? 0 : 4, + borderTopWidth: first ? 0 : 1, + borderTopColor: theme.colors.border, + }), + accountHeading: { flexDirection: "row" as const, alignItems: "center" as const }, + accountLabel: (inUse: boolean) => ({ + color: inUse ? theme.colors.foreground : theme.colors.foregroundMuted, fontSize: 11, + fontWeight: inUse ? ("700" as const) : ("400" as const), flexShrink: 1, minWidth: 0, - }, + }), accountSuffix: { color: theme.colors.foregroundMuted, fontSize: 11, flexShrink: 0 }, + tags: { flexDirection: "row" as const, gap: 4, flexShrink: 0 }, + headingTags: { flexDirection: "row" as const, gap: 4, flexShrink: 0, marginLeft: 6 }, + tag: { + color: theme.colors.foregroundMuted, + fontSize: 10, + fontWeight: "600" as const, + paddingHorizontal: 6, + paddingVertical: 1, + borderRadius: 999, + borderWidth: 1, + borderColor: theme.colors.border, + overflow: "hidden" as const, + }, + // Accent outline plus an icon so the switch reads as an action, not another badge. + switch: { + flexDirection: "row" as const, + alignItems: "center" as const, + gap: 4, + flexShrink: 0, + marginLeft: "auto" as const, + paddingHorizontal: 8, + paddingVertical: 3, + borderWidth: 1, + borderColor: theme.colors.accent, + borderRadius: 999, + }, + switchBelow: { alignSelf: "flex-start" as const, marginLeft: 0 }, + switchPressed: { backgroundColor: theme.colors.surface2 }, + switchDisabled: { opacity: 0.45 }, + switchText: { color: theme.colors.accent, fontSize: 11, fontWeight: "700" as const }, }), [layout.compact, theme], ); @@ -102,18 +175,143 @@ export function QuotaPopover(props: PluginButtonContentProps) { const groups = quotaProviderGroups(quotas.data?.quotas ?? [], currentProvider); const hasCurrent = groups.some((group) => group.provider === currentProvider); + const logins = sessionAccounts.data?.accounts ?? []; + const hasActive = logins.some((login) => login.active); + const currentAccounts = quotaSessionAccounts( + groups.find((group) => group.provider === currentProvider)?.accounts ?? [], + logins, + ); + + function renderTags(tags: readonly string[], style: object) { + return ( + + {tags.map((tag) => ( + + {tag} + + ))} + + ); + } - if (groups.length === 0) { - return No provider quota data available.; + function renderSwitch( + account: QuotaSessionAccountGroup, + login: OmpSessionAccount, + inHeading: boolean, + ) { + const busy = switching !== null; + return ( + void switchTo(login)} + style={({ pressed }) => [ + styles.switch, + inHeading ? null : styles.switchBelow, + pressed ? styles.switchPressed : null, + busy ? styles.switchDisabled : null, + ]} + > + + + {switching === login.credentialId ? "Switching…" : "Switch"} + + + ); + } + + function renderAccount(account: QuotaSessionAccountGroup, index: number) { + const login = account.login; + return ( + + {account.label ? ( + + + {account.label} + + {account.suffix ? ( + {` · ${account.suffix}`} + ) : null} + {account.tags.length > 0 ? renderTags(account.tags, styles.headingTags) : null} + {/* Right-aligned like the Switch button the other accounts have in this spot. */} + {account.inUse ? ( + IN USE + ) : login?.onlyLogin ? ( + // The provider's only stored credential: nothing to switch to, but its use unproven. + ONLY LOGIN + ) : null} + {login && !account.inUse && !login.onlyLogin + ? renderSwitch(account, login, true) + : null} + + ) : account.tags.length > 0 ? ( + renderTags(account.tags, styles.tags) + ) : null} + {account.accountService ? ( + + {account.accountService === "github" ? "GitHub" : `GHE · ${account.accountHost}`} + + ) : null} + {account.quotas.map((quota) => { + const severity = quotaSeverityFromFraction(quota.usedFraction); + const color = severityColor(severity); + const pct = + quota.usedFraction === null ? 0 : Math.min(100, Math.round(quota.usedFraction * 100)); + return ( + + + + {quota.label} + + + {quota.usedFraction === null ? "Unknown" : `${pct}%`} + + + + + + {quotaDetailLabel(quota)} + + ); + })} + {/* An unnamed account has no heading row, so its state sits below its limits. */} + {!account.label && account.inUse ? ( + IN USE + ) : !account.label && login?.onlyLogin ? ( + ONLY LOGIN + ) : login && !account.inUse && !account.label ? ( + renderSwitch(account, login, false) + ) : null} + + ); } return ( - {storeLabel(store)} - - Last recorded usage from the local agent database, not read live from the provider. - - {currentProvider ? ( + {sessionAccounts.error ? ( + // The host wraps handler errors in transport details; only a short notice belongs here. + Could not read which account this session uses. + ) : null} + {switchError ? {switchError} : null} + {/* The default store needs no label; a named profile's usage is worth telling apart. */} + {store ? {storeLabel(store)} : null} + {currentProvider && !hasActive ? ( CURRENT PROVIDER identifies the provider, not the account used by this session. @@ -123,72 +321,26 @@ export function QuotaPopover(props: PluginButtonContentProps) { {`No recorded quota yet for ${quotaProviderLabel(currentProvider)} (this session's provider).`} ) : null} + {groups.length === 0 ? ( + No provider quota data available. + ) : null} {groups.map((group: QuotaProviderGroup) => { const current = group.provider === currentProvider; + const accounts: QuotaSessionAccountGroup[] = current + ? currentAccounts + : group.accounts.map((account) => ({ ...account, login: null, inUse: false })); return ( {quotaProviderLabel(group.provider)} {current ? "CURRENT PROVIDER" : "RECORDED"} - {group.accounts.map((account) => ( - - {account.label ? ( - - - {account.label} - - {account.suffix ? ( - {` · ${account.suffix}`} - ) : null} - - ) : null} - {account.accountService ? ( - - {account.accountService === "github" - ? "GitHub" - : `GHE · ${account.accountHost}`} - - ) : null} - {account.quotas.map((quota) => { - const severity = quotaSeverityFromFraction(quota.usedFraction); - const color = severityColor(severity); - const pct = - quota.usedFraction === null - ? 0 - : Math.min(100, Math.round(quota.usedFraction * 100)); - return ( - - - - {quota.label} - - - {quota.usedFraction === null ? "Unknown" : `${pct}%`} - - - - - - {quotaDetailLabel(quota)} - - ); - })} - - ))} + {accounts.map(renderAccount)} ); })} diff --git a/paseo-omp/client/quota-state.ts b/paseo-omp/client/quota-state.ts index 9518a602..48b7f86e 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -1,4 +1,5 @@ -import type { OmpQuota } from "../shared/quota"; +import { accountTags } from "../shared/account-tags"; +import type { OmpQuota, OmpSessionAccount } from "../shared/quota"; import { isOmpProvider } from "./omp-store-state"; const PROVIDER_LABELS: Record = { @@ -8,23 +9,6 @@ const PROVIDER_LABELS: Record = { "openai-codex": "OpenAI", }; -// Paseo's own provider brand icons (@getpaseo/protocol names such as "claude" or "omp") are -// host-internal: passing one as a button `icon` string fails host validation, and rendering it -// through `Icon` draws nothing. Plugin icons resolve Lucide names only, so each provider maps -// to the Lucide vector closest to its mark. -const PROVIDER_ICON_NAMES: Record = { - anthropic: "Asterisk", - azure: "Cloud", - cursor: "MousePointer2", - "google-antigravity": "Gem", - openai: "Atom", - "openai-codex": "Atom", -}; - -export function quotaProviderIconName(provider: string | null): string { - return (provider ? PROVIDER_ICON_NAMES[provider] : undefined) ?? "Gauge"; -} - export type QuotaSeverity = "ok" | "warning" | "danger" | "unknown"; export function quotaSeverityFromFraction(fraction: number | null): QuotaSeverity { @@ -61,31 +45,58 @@ export function quotasForProvider( : []; } +/** + * The quotas the pill summarizes: the session's account in use when OMP named one and its usage is + * recorded, otherwise every account of the provider. + */ +export function quotasInUse( + quotas: readonly OmpQuota[], + provider: string | null, + includeAll: boolean, + inUse: OmpSessionAccount | null, +): OmpQuota[] { + const matching = quotasForProvider(quotas, provider, includeAll); + if (!provider || !inUse) return matching; + const own = matching.filter((quota) => inUse.quotaAccountKeys.includes(quota.accountKey)); + return own.length > 0 ? own : matching; +} + +/** + * The pill shows only the percentage beside the provider icon, so a long provider name never + * truncates the number; the title names the provider and the account it describes. + */ export function quotaSummaryForProvider( quotas: readonly OmpQuota[], provider: string | null, includeAll = false, -): { visible: boolean; label: string } { - const matching = quotasForProvider(quotas, provider, includeAll); - const label = provider ? quotaProviderLabel(provider) : "Quotas"; + inUse: OmpSessionAccount | null = null, +): { visible: boolean; label: string; title: string } { + const matching = quotasInUse(quotas, provider, includeAll, inUse); + const own = + provider !== null && + inUse !== null && + matching.some((quota) => inUse.quotaAccountKeys.includes(quota.accountKey)); const used = matching.flatMap((quota) => quota.usedFraction === null ? [] : [quota.usedFraction], ); - if (used.length === 0) { - return provider - ? { visible: true, label: `${quotaProviderLabel(provider)} · —` } - : { visible: includeAll, label: "Quotas · —" }; + const peak = used.length === 0 ? null : `${Math.round(Math.max(...used) * 100)}%`; + const scope = provider + ? [quotaProviderLabel(provider), own && inUse ? inUse.label : "all accounts"].join(" · ") + : "All providers"; + const title = `${scope} · ${peak ?? "no recorded usage"} (last recorded usage, not live)`; + if (!provider) { + return { visible: includeAll, label: `Quotas · ${peak ?? "—"}`, title }; } - const peak = Math.round(Math.max(...used) * 100); - return { visible: true, label: `${label} · ${peak}%` }; + return { visible: true, label: peak ?? "—", title }; } export function quotaSeverityForProvider( quotas: readonly OmpQuota[], provider: string | null, includeAll = false, + inUse: OmpSessionAccount | null = null, ): QuotaSeverity { - const used = quotasForProvider(quotas, provider, includeAll).flatMap((quota) => + const used = quotasInUse(quotas, provider, includeAll, inUse).flatMap((quota) => quota.usedFraction === null ? [] : [quota.usedFraction], ); return used.length === 0 ? "unknown" : quotaSeverityFromFraction(Math.max(...used)); @@ -97,6 +108,8 @@ export type QuotaAccountGroup = { accountService: OmpQuota["accountService"]; accountHost: string | null; label: string | null; + /** Plan and organization badges, e.g. "Business", "Personal" or an organization name. */ + tags: string[]; suffix: string | null; quotas: OmpQuota[]; peakFraction: number | null; @@ -143,6 +156,38 @@ export function quotaProviderGroups( return groups; } +export type QuotaSessionAccountGroup = QuotaAccountGroup & { + /** The OMP login this usage belongs to, when the session listed it. */ + login: OmpSessionAccount | null; + /** OMP routes this session's requests to this account. */ + inUse: boolean; +}; + +/** Links the current provider's accounts to the session's logins; the one in use sorts first. */ +export function quotaSessionAccounts( + accounts: readonly QuotaAccountGroup[], + logins: readonly OmpSessionAccount[], +): QuotaSessionAccountGroup[] { + const linked = accounts.map((account) => { + const login = logins.find((entry) => entry.quotaAccountKeys.includes(account.accountKey)); + return { ...account, login: login ?? null, inUse: login?.active === true }; + }); + return [...linked.filter((a) => a.inUse), ...linked.filter((a) => !a.inUse)]; +} + +/** OMP's `/session pin` accepts this exact form for any stored OAuth login. */ +export function sessionPinCommand(credentialId: number): string { + return `/session pin OAuth credential #${credentialId}`; +} + +function quotaAccountTags(quotas: readonly OmpQuota[], email: string | null): string[] { + return accountTags({ + plan: quotas.find((quota) => quota.plan)?.plan ?? null, + organization: quotas.find((quota) => quota.organization)?.organization ?? null, + email, + }); +} + function quotaAccountGroups(quotas: readonly OmpQuota[]): QuotaAccountGroup[] { const byAccount = new Map(); for (const quota of quotas) { @@ -165,6 +210,7 @@ function quotaAccountGroups(quotas: readonly OmpQuota[]): QuotaAccountGroup[] { email, accountService: service?.accountService ?? null, accountHost: service?.accountHost ?? null, + tags: quotaAccountTags(accountQuotas, email), label: email ?? accountId, suffix: null, quotas: [...accountQuotas].sort((a, b) => (b.usedFraction ?? -1) - (a.usedFraction ?? -1)), @@ -207,9 +253,10 @@ function quotaAccountGroups(quotas: readonly OmpQuota[]): QuotaAccountGroup[] { export function quotaResetLabel(resetsAtMs: number | null, nowMs: number = Date.now()): string { if (resetsAtMs === null) return ""; const remainingMs = Math.max(0, resetsAtMs - nowMs); - const hours = Math.floor(remainingMs / 3_600_000); + const totalHours = Math.floor(remainingMs / 3_600_000); const minutes = Math.floor((remainingMs % 3_600_000) / 60_000); - return hours > 0 ? `resets ${hours}h ${minutes}m` : `resets ${minutes}m`; + if (totalHours >= 24) return `resets ${Math.floor(totalHours / 24)}d ${totalHours % 24}h`; + return totalHours > 0 ? `resets ${totalHours}h ${minutes}m` : `resets ${minutes}m`; } export function quotaRecordedLabel(recordedAtMs: number, nowMs: number = Date.now()): string { diff --git a/paseo-omp/index.client.tsx b/paseo-omp/index.client.tsx index eabeeb15..0b9a461c 100644 --- a/paseo-omp/index.client.tsx +++ b/paseo-omp/index.client.tsx @@ -61,7 +61,7 @@ import { import { OMP_MCP_AUTH_TIMELINE_KIND, ompMcpAuthorizationTimelineSchema } from "./shared/mcp"; import { type OmpStore, storeForProvider } from "./shared/omp-store"; import { ompImageTimelineSchema, transformOmpImageToolItem } from "./shared/provider-image"; -import { listOmpQuotas } from "./shared/quota"; +import { listOmpQuotas, listOmpSessionAccounts, type OmpSessionAccount } from "./shared/quota"; import { OMP_RULE_NOTICE_KIND, ompRuleNoticeSchema } from "./shared/rule-notices"; import { OMP_SUBAGENT_STRIP_KIND, ompSubagentStripSchema } from "./shared/subagents"; @@ -496,18 +496,26 @@ export default function contribute(client: PluginClientContext) { try { const result = await loadStoreQuotas(targets[0].entry.store); if (disposed || !preferences?.quota) return; - for (const { agentId, entry, handle } of targets) { - const current = pills.get(agentId); - if (current !== entry || current.quota !== handle) continue; - const severity = quotaSeverityForProvider(result.quotas, entry.quotaProvider, true); - handle.update({ - ...quotaSummaryForProvider(result.quotas, entry.quotaProvider, true), - ...(severity === entry.quotaSeverity - ? {} - : { icon: quotaProviderIcon(entry.quotaProvider, severity) }), - }); - entry.quotaSeverity = severity; - } + await Promise.all( + targets.map(async ({ agentId, entry, handle }) => { + const inUse = await accountInUse(agentId, entry.quotaProvider); + const current = pills.get(agentId); + if (disposed || current !== entry || current.quota !== handle) return; + const severity = quotaSeverityForProvider( + result.quotas, + entry.quotaProvider, + true, + inUse, + ); + handle.update({ + ...quotaSummaryForProvider(result.quotas, entry.quotaProvider, true, inUse), + ...(severity === entry.quotaSeverity + ? {} + : { icon: quotaProviderIcon(entry.quotaProvider, severity) }), + }); + entry.quotaSeverity = severity; + }), + ); } catch { // Retain only this store's last result. Failure never falls back to another profile. } @@ -518,6 +526,20 @@ export default function contribute(client: PluginClientContext) { } } + /** The login OMP routes this agent's provider requests to, or null when it cannot say. */ + async function accountInUse( + agentId: string, + provider: string | null, + ): Promise { + if (!provider) return null; + try { + const { accounts } = await client.rpc(listOmpSessionAccounts, { agentId, provider }); + return accounts.find((account) => account.active) ?? null; + } catch { + return null; + } + } + async function refreshComposerPillSettings(): Promise { if (settingsReadRunning || disposed) return; settingsReadRunning = true; diff --git a/paseo-omp/index.server.ts b/paseo-omp/index.server.ts index cd5c27aa..5ab442f1 100644 --- a/paseo-omp/index.server.ts +++ b/paseo-omp/index.server.ts @@ -52,7 +52,11 @@ import { createOmpProvider } from "./server/provider/registration"; import { OmpPublicError } from "./server/provider/security"; import { OmpSessionLimit } from "./server/provider/session-limit"; import { resolveGetOmpProviderHealth } from "./server/provider-diagnostics"; -import { resolveListOmpQuotas } from "./server/quota"; +import { + resolveListOmpQuotas, + resolveListOmpSessionAccounts, + sessionAgentFromPaseo, +} from "./server/quota"; import { ompRuleNoticeRow } from "./server/rule-notices"; import { OmpSubagentControlRegistry, @@ -116,7 +120,7 @@ import { getOmpUpdateStatus, installOmpUpdate } from "./shared/omp-update"; import { getOmpProviderHealth } from "./shared/provider-diagnostics"; import { getOmpImage } from "./shared/provider-image"; import { providerLaunchSettings } from "./shared/provider-launch-settings"; -import { listOmpQuotas } from "./shared/quota"; +import { listOmpQuotas, listOmpSessionAccounts } from "./shared/quota"; import { cancelOmpSubagent, steerOmpSubagent } from "./shared/subagents"; import { getOmpSupportReport } from "./shared/support-diagnostics"; @@ -162,6 +166,9 @@ export default function contribute(server: PluginServerContext) { server.handle(listHubProcesses, resolveListHubProcesses); server.handle(tailHubLog, resolveTailHubLog); server.handle(listOmpQuotas, scoped(resolveListOmpQuotas)); + server.handle(listOmpSessionAccounts, (input, { paseo }) => + resolveListOmpSessionAccounts(input, subagentControlRegistry, sessionAgentFromPaseo(paseo)), + ); server.handle( listOmpAccounts, scoped(({ store, refresh }) => accounts.list(store, refresh ?? false)), diff --git a/paseo-omp/server/omp-accounts.ts b/paseo-omp/server/omp-accounts.ts index 8f95f994..476719ba 100644 --- a/paseo-omp/server/omp-accounts.ts +++ b/paseo-omp/server/omp-accounts.ts @@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto"; import { tmpdir } from "node:os"; import { createInterface } from "node:readline"; import { z } from "zod"; +import { accountTags } from "../shared/account-tags"; import { OMP_ACCOUNTS_SETTING_PATHS, type OmpAccount, @@ -118,7 +119,16 @@ const UsageReportSchema = z.object({ amount: z.object({ usedFraction: UsedFraction.nullish() }).nullish(), }), ).nullish(), - metadata: z.object({ accountId: z.string().nullish(), orgId: z.string().nullish() }).nullish(), + metadata: z + .object({ + accountId: z.string().nullish(), + orgId: z.string().nullish(), + email: z.string().nullish(), + plan: z.string().nullish(), + planType: z.string().nullish(), + orgName: z.string().nullish(), + }) + .nullish(), }); type UsageReport = z.infer; const UsageSchema = z.object({ reports: entries(UsageReportSchema).nullish() }); @@ -578,6 +588,7 @@ export function joinAccounts( credentialId: login.credentialId, oauth: false, label: login.label, + tags: [], limits: [], usageAt: null, usageIsRecorded: false, @@ -608,7 +619,7 @@ export function joinAccounts( provider: login.provider, credentialId: login.credentialId, oauth: true, - label: login.label, + ...labelWithTags(login.label, report), limits: recorded?.limits ?? live, usageAt: recorded?.at ?? report?.fetchedAt ?? null, usageIsRecorded: recorded !== null, @@ -621,6 +632,29 @@ export function joinAccounts( ); } +/** + * Plan and organization badges from the login's usage report. OMP appends the organization to the + * label in parentheses (`email (org)`); once a badge shows it, the suffix only repeats it. + */ +function labelWithTags( + label: string, + report: UsageReport | undefined, +): Pick { + const metadata = report?.metadata; + const orgName = metadata?.orgName?.trim() || null; + const tags = accountTags({ + plan: (metadata?.planType ?? metadata?.plan)?.trim() || null, + organization: orgName, + email: metadata?.email?.trim() || null, + }); + const suffix = orgName ? ` (${orgName})` : null; + return { + label: + tags.length > 0 && suffix && label.endsWith(suffix) ? label.slice(0, -suffix.length) : label, + tags, + }; +} + /** Where new sessions would go right now, by OMP's own balancer. */ async function previewBalance( command: OmpCommand, diff --git a/paseo-omp/server/provider/omp-rpc-protocol.ts b/paseo-omp/server/provider/omp-rpc-protocol.ts index 2d07fdef..77a80ce8 100644 --- a/paseo-omp/server/provider/omp-rpc-protocol.ts +++ b/paseo-omp/server/provider/omp-rpc-protocol.ts @@ -148,7 +148,7 @@ export const OMP_RPC_COMMAND_POLICIES = { cancel_subagent: "implemented", fork: "unsupported", get_btw_history: "unsupported", - get_logout_accounts: "unsupported", + get_logout_accounts: "implemented", goal: "unsupported", live_mute: "unsupported", live_connect: "unsupported", @@ -2003,6 +2003,21 @@ export const OmpSubagentsResultSchema = z.object({ .max(1_024), }); export const OmpCancelSubagentResultSchema = z.object({ cancelled: z.boolean() }); +/** Stored logins of one provider; `active` marks the ones this session may be using. */ +export const OmpLogoutAccountsResultSchema = z.object({ + accounts: z + .array( + z.object({ + credentialId: z.number().int().nonnegative(), + provider: IDENTIFIER, + label: TEXT, + type: z.enum(["api_key", "oauth"]), + active: z.boolean(), + }), + ) + .max(256), +}); +export type OmpLogoutAccount = z.infer["accounts"][number]; export const OmpSteerSubagentResultSchema = z.object({}).strict().optional(); export const OmpSubagentMessagesResultSchema = z.object({ sessionFile: boundedString(MAX_PATH_LENGTH), diff --git a/paseo-omp/server/provider/omp-rpc.ts b/paseo-omp/server/provider/omp-rpc.ts index 47df5b8f..84a49226 100644 --- a/paseo-omp/server/provider/omp-rpc.ts +++ b/paseo-omp/server/provider/omp-rpc.ts @@ -37,6 +37,8 @@ import { type OmpHostToolResult, type OmpHostToolUpdate, type OmpImage, + type OmpLogoutAccount, + OmpLogoutAccountsResultSchema, type OmpMessage, OmpMessageSchema, OmpMessagesPageResultSchema, @@ -121,6 +123,8 @@ export interface OmpRuntimeSession { /** Resolves `false` when OMP no longer lists the subagent as running for this session. */ cancelSubagent(subagentId: string): Promise; steerSubagent(subagentId: string, message: string): Promise; + /** The provider's stored logins; `active` marks the ones this session may be using. */ + getLogoutAccounts(providerId: string): Promise; prompt( message: string, images?: readonly OmpImage[], @@ -561,6 +565,13 @@ class OmpRpcSession implements OmpRuntimeSession { ).cancelled; } + async getLogoutAccounts(providerId: string): Promise { + const safeId = validateBoundedText(providerId, "provider identifier", MAX_ID_LENGTH); + return OmpLogoutAccountsResultSchema.parse( + await this.process.request({ type: "get_logout_accounts", providerId: safeId }), + ).accounts; + } + async steerSubagent(subagentId: string, message: string): Promise { const safeId = validateBoundedText(subagentId, "subagent identifier", MAX_ID_LENGTH); const safeMessage = validateBoundedText(message, "subagent steering message", MAX_TEXT_LENGTH); diff --git a/paseo-omp/server/provider/session.ts b/paseo-omp/server/provider/session.ts index 1c9dc8a9..e92ed081 100644 --- a/paseo-omp/server/provider/session.ts +++ b/paseo-omp/server/provider/session.ts @@ -40,6 +40,7 @@ import type { OmpAvailableCommand, OmpBranchResult, OmpCompactionResult, + OmpLogoutAccount, OmpMessage, OmpModel, OmpRpcEvent, @@ -482,6 +483,12 @@ export class OmpProviderSession implements OmpOpenedSession, OmpSubagentControls await target.runtime.steerSubagent(target.nativeId, message); } + /** The provider's stored logins as this session's runtime sees them; `active` marks its own. */ + async listProviderAccounts(provider: string): Promise { + if (this.closed || this.runtimeDead) throw new OmpPublicError("The OMP session is closed"); + return await this.runtime.getLogoutAccounts(provider); + } + /** * The native ID and runtime of a subagent this session's current runtime lists as running, or * `null`. OMP repeats the check; this scopes the request to this session and answers exactly. diff --git a/paseo-omp/server/quota.ts b/paseo-omp/server/quota.ts index 9d4665e3..d9375d5a 100644 --- a/paseo-omp/server/quota.ts +++ b/paseo-omp/server/quota.ts @@ -1,10 +1,16 @@ import { createHash } from "node:crypto"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; -import type { RpcInput } from "@getpaseo/plugin"; +import type { RpcInput, RpcOutput } from "@getpaseo/plugin"; +import type { PluginHandlerContext } from "@getpaseo/plugin/server"; import { z } from "zod"; -import type { listOmpQuotas, OmpQuota } from "../shared/quota"; -import { ompDataDir } from "./paths"; +import { storeForProvider } from "../shared/omp-store"; +import type { listOmpQuotas, listOmpSessionAccounts, OmpQuota } from "../shared/quota"; +import { ompDataDir, withOmpStore } from "./paths"; +import type { OmpLogoutAccount } from "./provider/omp-rpc-protocol"; +import { OmpRpcRequestRejectedError } from "./provider/omp-rpc-transport"; +import { isOmpPublicError, OmpPublicError } from "./provider/security"; +import type { OmpSubagentControlRegistry } from "./subagents"; const QuotaRowSchema = z.object({ provider: z.string(), @@ -46,6 +52,74 @@ function copilotAccount(accountKey: string): CopilotAccount { } } +const CachedReportSchema = z.object({ + value: z.object({ + provider: z.string(), + fetchedAt: z.number(), + metadata: z + .object({ + plan: z.string().nullish(), + planType: z.string().nullish(), + orgName: z.string().nullish(), + }) + .nullish(), + }), +}); + +type AccountTags = Pick; +type CachedReport = AccountTags & { key: string; provider: string; fetchedAt: number }; + +/** OMP's usage cache; missing on older OMP versions, so any failure yields no tags. */ +function readCachedReports(database: DatabaseSync): CachedReport[] { + let rows: Record[]; + try { + rows = database + .prepare("SELECT key, value FROM cache WHERE key LIKE 'usage_cache:report:%'") + .all(); + } catch { + return []; + } + return rows.flatMap(({ key, value }) => { + if (typeof key !== "string" || typeof value !== "string") return []; + let json: unknown; + try { + json = JSON.parse(value); + } catch { + return []; + } + const parsed = CachedReportSchema.safeParse(json); + if (!parsed.success) return []; + const { provider, fetchedAt, metadata } = parsed.data.value; + const plan = (metadata?.planType ?? metadata?.plan)?.trim() || null; + const organization = metadata?.orgName?.trim() || null; + return [ + { + key, + provider, + fetchedAt, + plan, + // Codex reports its plan as the organization name too; that is not an organization. + organization: organization?.toLowerCase() === plan?.toLowerCase() ? null : organization, + }, + ]; + }); +} + +/** OMP caches each report under a key that ends with the account_key usage_history records. */ +function accountTags( + reports: readonly CachedReport[], + provider: string, + accountKey: string, +): AccountTags { + const matches = reports + .filter((report) => report.provider === provider && report.key.endsWith(`:${accountKey}`)) + .sort((a, b) => b.fetchedAt - a.fetchedAt); + return { + plan: matches.find((report) => report.plan)?.plan ?? null, + organization: matches.find((report) => report.organization)?.organization ?? null, + }; +} + // Only live windows are returned: a series whose newest row already reset (or never resets and was // abandoned) would otherwise pin the pill at its last exhausted value and bloat the popover. export function listOmpQuotasFrom(path: string, now = Date.now()): OmpQuota[] { @@ -79,6 +153,7 @@ export function listOmpQuotasFrom(path: string, now = Date.now()): OmpQuota[] { ORDER BY COALESCE(usedFraction, -1) DESC, provider, label, accountKey, limitId`, ) .all(now, now - ABANDONED_AFTER_MS); + const reports = readCachedReports(database); return rows.flatMap((row) => { const parsed = QuotaRowSchema.safeParse(row); if (!parsed.success) return []; @@ -91,6 +166,7 @@ export function listOmpQuotasFrom(path: string, now = Date.now()): OmpQuota[] { // account_id is only known to be a username for Copilot; other providers keep it private. accountId: copilot ? quota.accountId : null, ...(copilot ? copilotAccount(quota.accountKey) : UNKNOWN_SERVICE), + ...accountTags(reports, quota.provider, quota.accountKey), }, ]; }); @@ -101,9 +177,266 @@ export function listOmpQuotasFrom(path: string, now = Date.now()): OmpQuota[] { return []; } } - export function resolveListOmpQuotas(_input: RpcInput): { quotas: OmpQuota[]; } { - return { quotas: listOmpQuotasFrom(join(ompDataDir(), "agent.db")) }; + return { quotas: listOmpQuotasFrom(defaultDatabasePath()) }; +} + +function defaultDatabasePath(): string { + return join(ompDataDir(), "agent.db"); +} + +function hashAccountKey(accountKey: string): string { + return createHash("sha256").update(accountKey).digest("hex"); +} + +type LoginIdentity = { email: string | null; accountId: string | null; orgId: string | null }; + +/** OMP's usage_history account_key is `oauth|account:|email:|org:`. */ +function usageKeyIdentity(accountKey: string): LoginIdentity { + const parts = new Map(); + for (const part of accountKey.split("|")) { + const colon = part.indexOf(":"); + if (colon > 0) parts.set(part.slice(0, colon), part.slice(colon + 1)); + } + return { + email: parts.get("email") || null, + accountId: parts.get("account") || null, + orgId: parts.get("org") || null, + }; +} + +/** + * OMP's own rule (`oauthMatchesActiveIdentity`): the organization gates the identity, so differing + * organizations, or one present on only one side, never match; an email on both sides then + * decides, else the account id. A record with no base identity matches on the organization alone. + */ +function sameLogin(login: LoginIdentity, usage: LoginIdentity): boolean { + if (login.orgId !== null || usage.orgId !== null) { + if (login.orgId !== usage.orgId) return false; + if (usage.email === null && usage.accountId === null) return true; + } + if (login.email && usage.email) return login.email.toLowerCase() === usage.email.toLowerCase(); + return login.accountId !== null && login.accountId === usage.accountId; +} + +/** Any field OMP's identity rule compares, the organization included. */ +function hasIdentity(identity: LoginIdentity): boolean { + return identity.email !== null || identity.accountId !== null || identity.orgId !== null; +} + +/** + * The usage accounts recorded for each login. Only identity fields leave the credential row. A login + * with an identity always has to match it. Only when neither the provider's single login nor its + * single usage account carries one (Copilot keys hold a credential fingerprint) are the two linked + * unchecked. + */ +export function quotaAccountKeysFor( + path: string, + provider: string, + credentialIds: readonly number[], +): Map { + const matched = new Map(credentialIds.map((id) => [id, []])); + if (credentialIds.length === 0) return matched; + try { + const database = new DatabaseSync(path, { readOnly: true, timeout: 500 }); + try { + const usageKeys = database + .prepare("SELECT DISTINCT account_key AS accountKey FROM usage_history WHERE provider = ?") + .all(provider) + .flatMap(({ accountKey }) => (typeof accountKey === "string" ? [accountKey] : [])); + const rows = database + .prepare( + `SELECT id, json_extract(data, '$.email') AS email, + json_extract(data, '$.accountId') AS accountId, + json_extract(data, '$.orgId') AS orgId + FROM auth_credentials WHERE id IN (${credentialIds.map(() => "?").join(", ")})`, + ) + .all(...credentialIds); + const text = (value: unknown) => (typeof value === "string" && value.trim()) || null; + for (const row of rows) { + if (typeof row.id !== "number") continue; + const login = { + email: text(row.email), + accountId: text(row.accountId), + orgId: text(row.orgId), + }; + if (hasIdentity(login)) { + matched.set( + row.id, + usageKeys.filter((key) => sameLogin(login, usageKeyIdentity(key))).map(hashAccountKey), + ); + } else if ( + credentialIds.length === 1 && + usageKeys.length === 1 && + !hasIdentity(usageKeyIdentity(usageKeys[0])) + ) { + matched.set(row.id, [hashAccountKey(usageKeys[0])]); + } + } + } finally { + database.close(); + } + } catch { + // An unreadable database only loses the link between logins and their recorded usage. + } + return matched; +} + +/** The agent's provider and, for an OMP session Paseo persisted, OMP's session id. */ +export type OmpSessionAgent = { provider: string; sessionId: string | null }; +export type OmpSessionAgentLookup = (agentId: string) => Promise; + +/** Paseo's bundled `omp` provider and this plugin's providers both persist OMP's session id. */ +export function sessionAgentFromPaseo(paseo: PluginHandlerContext["paseo"]): OmpSessionAgentLookup { + return async (agentId) => { + try { + const agent = (await paseo.agents.ref(agentId).refresh())?.agent; + if (!agent) return null; + const persistence = agent.persistence; + const omp = persistence && /^omp(-|$)/u.test(persistence.provider); + return { provider: agent.provider, sessionId: (omp && persistence.sessionId) || null }; + } catch { + return null; + } + }; +} + +const StickySchema = z.object({ type: z.string(), credentialId: z.number().int() }); + +/** + * The provider's stored OAuth logins with the one OMP pinned to `sessionId` marked active. OMP + * persists that pin as `session:sticky::` for 30 days past its last use; a + * session that never sent a request to the provider has none. Only identity fields are read. + */ +export function storedSessionLogins( + path: string, + provider: string, + sessionId: string, + nowSec = Math.floor(Date.now() / 1000), +): OmpLogoutAccount[] { + try { + const database = new DatabaseSync(path, { readOnly: true, timeout: 500 }); + try { + const sticky = database + .prepare("SELECT value FROM cache WHERE key = ? AND expires_at > ?") + .get(`session:sticky:${provider}:${sessionId}`, nowSec); + let active: number | null = null; + if (typeof sticky?.value === "string") { + try { + const parsed = StickySchema.safeParse(JSON.parse(sticky.value)); + if (parsed.success && parsed.data.type === "oauth") active = parsed.data.credentialId; + } catch { + // An unreadable pin only loses the active marker. + } + } + const text = (value: unknown) => (typeof value === "string" && value.trim()) || null; + // Every stored credential, API keys included, so "the only login" counts what OMP can use. + return database + .prepare( + `SELECT id, credential_type AS type, json_extract(data, '$.email') AS email, + json_extract(data, '$.accountId') AS accountId, + json_extract(data, '$.orgName') AS orgName + FROM auth_credentials + WHERE provider = ? AND disabled_cause IS NULL + ORDER BY id`, + ) + .all(provider) + .flatMap((row): OmpLogoutAccount[] => { + if (typeof row.id !== "number") return []; + if (row.type !== "oauth") { + return [ + { + credentialId: row.id, + provider, + label: `API key #${row.id}`, + type: "api_key", + active: false, + }, + ]; + } + // OMP's own label: the email or account id, then the organization in parentheses. + const base = text(row.email) ?? text(row.accountId) ?? `OAuth credential #${row.id}`; + const org = text(row.orgName); + return [ + { + credentialId: row.id, + provider, + label: org && org !== base ? `${base} (${org})` : base, + type: "oauth", + active: row.id === active, + }, + ]; + }); + } finally { + database.close(); + } + } catch { + return []; + } +} + +/** + * Logins and usage come from the agent's own store: a named-profile agent never reads the daemon + * default store, whose credential ids belong to other accounts. The store follows the provider + * Paseo reports for the agent, not anything the client sends. + */ +export async function resolveListOmpSessionAccounts( + input: RpcInput, + registry: OmpSubagentControlRegistry, + findAgent: OmpSessionAgentLookup, +): Promise> { + const agent = await findAgent(input.agentId); + // Without the agent its store is unknown; answering from the default store could name another + // store's login that happens to share a credential id. + if (!agent) return { accounts: [] }; + return await withOmpStore(storeForProvider(agent.provider), async () => { + const databasePath = defaultDatabasePath(); + const logins = await sessionLogins(input, registry, agent.sessionId, databasePath); + const oauth = logins.filter((login) => login.type === "oauth"); + const keys = quotaAccountKeysFor( + databasePath, + input.provider, + oauth.map((login) => login.credentialId), + ); + // One stored credential does not prove use (an environment or explicit key can serve the + // session), so OMP's own `active` stands and the sole login is only flagged as such. + const onlyLogin = logins.length === 1 && oauth.length === 1; + return { + accounts: oauth.map((login) => ({ + credentialId: login.credentialId, + label: login.label, + active: login.active, + onlyLogin, + quotaAccountKeys: keys.get(login.credentialId) ?? [], + })), + }; + }); +} + +/** + * A live OMP Plugin session answers itself. Any other OMP session (Paseo's bundled `omp` provider, + * or a plugin session not open in this daemon) falls back to the pin OMP recorded for it. + */ +async function sessionLogins( + input: RpcInput, + registry: OmpSubagentControlRegistry, + sessionId: string | null, + databasePath: string, +): Promise { + const controls = registry.get(input.agentId); + if (!controls) { + return sessionId ? storedSessionLogins(databasePath, input.provider, sessionId) : []; + } + try { + return await controls.listProviderAccounts(input.provider); + } catch (error) { + if (isOmpPublicError(error)) throw error; + if (error instanceof OmpRpcRequestRejectedError && error.code === "unsupported_command") { + throw new OmpPublicError("Update OMP to show which login this session uses"); + } + // Native OMP error text is never forwarded. + throw new OmpPublicError("OMP could not list this session's logins"); + } } diff --git a/paseo-omp/server/subagents.ts b/paseo-omp/server/subagents.ts index 5d15e1ad..ce427328 100644 --- a/paseo-omp/server/subagents.ts +++ b/paseo-omp/server/subagents.ts @@ -1,13 +1,16 @@ import type { RpcInput, RpcOutput } from "@getpaseo/plugin"; import type { cancelOmpSubagent, steerOmpSubagent } from "../shared/subagents"; +import type { OmpLogoutAccount } from "./provider/omp-rpc-protocol"; import { OmpRpcRequestRejectedError } from "./provider/omp-rpc-transport"; import { isOmpPublicError, OmpPublicError } from "./provider/security"; -/** Subagent controls of one live OMP session; history-only sessions never register. */ +/** Controls of one live OMP session; history-only sessions never register. */ export interface OmpSubagentControls { /** Resolves `false` when the subagent is no longer running. */ cancelSubagent(handle: string): Promise; steerSubagent(handle: string, message: string): Promise; + /** The provider's stored logins; `active` marks the ones this session may be using. */ + listProviderAccounts(provider: string): Promise; } export class OmpSubagentNotRunningError extends OmpPublicError { diff --git a/paseo-omp/shared/account-tags.ts b/paseo-omp/shared/account-tags.ts new file mode 100644 index 00000000..7c8efb8b --- /dev/null +++ b/paseo-omp/shared/account-tags.ts @@ -0,0 +1,38 @@ +const PLAN_LABELS: Record = { + free: "Free", + go: "Go", + plus: "Plus", + pro: "Pro", + prolite: "Pro Lite", + max: "Max", + team: "Team", + business: "Business", + self_serve_business_prolite: "Business", + self_serve_business_usage_based: "Business", + enterprise: "Enterprise", + enterprise_cbp_automation: "Enterprise", + enterprise_cbp_usage_based: "Enterprise", + edu: "Edu", +}; + +/** + * Plan and organization badges for one login, e.g. ["Business", "Example Team"] or ["Personal"]. + * `plan` is the raw plan OMP's usage report names (Codex `planType`, Copilot `plan`). + */ +export function accountTags(input: { + plan: string | null; + organization: string | null; + email: string | null; +}): string[] { + const { plan, organization, email } = input; + const tags: string[] = []; + if (plan) { + tags.push(PLAN_LABELS[plan.toLowerCase()] ?? plan.charAt(0).toUpperCase() + plan.slice(1)); + } + // Codex reports its plan as the organization name too; that is not an organization. + if (organization && organization.toLowerCase() !== plan?.toLowerCase()) { + // Anthropic names a personal account's default organization after its email. + tags.push(email && organization === `${email}'s Organization` ? "Personal" : organization); + } + return [...new Set(tags)]; +} diff --git a/paseo-omp/shared/omp-accounts.ts b/paseo-omp/shared/omp-accounts.ts index 208ec274..f0f3732c 100644 --- a/paseo-omp/shared/omp-accounts.ts +++ b/paseo-omp/shared/omp-accounts.ts @@ -46,6 +46,8 @@ export const OmpAccountSchema = z.object({ /** OAuth logins have usage and resets; API keys have neither. */ oauth: z.boolean(), label: z.string(), + /** Plan and organization badges from OMP's usage report, e.g. "Business" or "Personal". */ + tags: z.array(z.string()), limits: z.array(OmpAccountLimitSchema), /** When OMP read the limits shown (epoch ms); null when it has no reading for this login. */ usageAt: z.number().int().nullable(), diff --git a/paseo-omp/shared/provider-icons/antigravity.svg b/paseo-omp/shared/provider-icons/antigravity.svg new file mode 100644 index 00000000..9aa99c41 --- /dev/null +++ b/paseo-omp/shared/provider-icons/antigravity.svg @@ -0,0 +1 @@ +Antigravity diff --git a/paseo-omp/shared/provider-icons/claude.svg b/paseo-omp/shared/provider-icons/claude.svg new file mode 100644 index 00000000..6af48e81 --- /dev/null +++ b/paseo-omp/shared/provider-icons/claude.svg @@ -0,0 +1 @@ +Claude diff --git a/paseo-omp/shared/provider-icons/codex.svg b/paseo-omp/shared/provider-icons/codex.svg new file mode 100644 index 00000000..0da7c8ca --- /dev/null +++ b/paseo-omp/shared/provider-icons/codex.svg @@ -0,0 +1 @@ +OpenAI diff --git a/paseo-omp/shared/provider-icons/copilot.svg b/paseo-omp/shared/provider-icons/copilot.svg new file mode 100644 index 00000000..b103751f --- /dev/null +++ b/paseo-omp/shared/provider-icons/copilot.svg @@ -0,0 +1 @@ +GitHub Copilot diff --git a/paseo-omp/shared/provider-icons/grok.svg b/paseo-omp/shared/provider-icons/grok.svg new file mode 100644 index 00000000..dedbc3b1 --- /dev/null +++ b/paseo-omp/shared/provider-icons/grok.svg @@ -0,0 +1 @@ +Grok diff --git a/paseo-omp/shared/quota.ts b/paseo-omp/shared/quota.ts index be39817b..8c793a77 100644 --- a/paseo-omp/shared/quota.ts +++ b/paseo-omp/shared/quota.ts @@ -16,6 +16,10 @@ export const OmpQuotaSchema = z.object({ accountService: z.enum(["github", "ghe"]).nullable(), /** GHE hostname; null for public GitHub and every other provider. */ accountHost: z.string().nullable(), + /** Raw plan OMP's cached usage report names (Codex `planType`, Copilot `plan`). */ + plan: z.string().nullable().default(null), + /** Organization name from OMP's cached usage report, when it is not just the plan. */ + organization: z.string().nullable().default(null), label: z.string(), windowLabel: z.string().nullable(), usedFraction: z.number().min(0).nullable(), @@ -30,3 +34,32 @@ export const listOmpQuotas = defineRpc({ input: z.object({ store: OmpStoreSchema.optional() }), output: z.object({ quotas: z.array(OmpQuotaSchema) }), }); + +export const OmpSessionAccountSchema = z.object({ + /** OMP's credential id; `/session pin OAuth credential #` selects this login. */ + credentialId: z.number().int().nonnegative(), + label: z.string(), + /** OMP routes this session's requests to this login, as OMP itself reports or recorded it. */ + active: z.boolean(), + /** + * The provider's only stored credential of any kind. Not proof of use: an environment or explicit + * key can still serve the session, so it is shown apart from `active` and never offered a switch. + */ + onlyLogin: z.boolean(), + /** `OmpQuota.accountKey` values recorded for this login. */ + quotaAccountKeys: z.array(z.string()), +}); +export type OmpSessionAccount = z.infer; + +/** OAuth logins of the agent's current provider, as its live OMP session sees them. */ +export const listOmpSessionAccounts = defineRpc({ + name: "paseo-omp.list-session-accounts", + input: z.object({ + agentId: z.string().min(1).max(256), + provider: z + .string() + .regex(/^[a-z0-9][a-z0-9.-]*$/u) + .max(128), + }), + output: z.object({ accounts: z.array(OmpSessionAccountSchema) }), +}); diff --git a/paseo-omp/tests/helpers/provider-harness.ts b/paseo-omp/tests/helpers/provider-harness.ts index 26f2625d..50a22a6e 100644 --- a/paseo-omp/tests/helpers/provider-harness.ts +++ b/paseo-omp/tests/helpers/provider-harness.ts @@ -22,6 +22,7 @@ import type { OmpHostToolResult, OmpHostToolUpdate, OmpImage, + OmpLogoutAccount, OmpMessage, OmpModel, OmpPersistedSessionMessages, @@ -563,6 +564,12 @@ export class FakeOmpSession implements OmpRuntimeSession { if (this.subagentControlError) throw this.subagentControlError; } + logoutAccounts: OmpLogoutAccount[] = []; + + async getLogoutAccounts(_providerId: string) { + return this.logoutAccounts; + } + getSubagentMessages(selector: { subagentId?: string; sessionFile?: string }) { this.subagentMessageRequests.push(selector); const key = selector.subagentId ?? selector.sessionFile; diff --git a/paseo-omp/tests/omp-accounts-state.test.ts b/paseo-omp/tests/omp-accounts-state.test.ts index 889e4533..384a591d 100644 --- a/paseo-omp/tests/omp-accounts-state.test.ts +++ b/paseo-omp/tests/omp-accounts-state.test.ts @@ -15,6 +15,7 @@ function account(provider: string, credentialId: number): OmpAccount { credentialId, oauth: true, label: `${provider}-${credentialId}`, + tags: [], limits: [], usageAt: null, usageIsRecorded: false, diff --git a/paseo-omp/tests/omp-accounts.test.ts b/paseo-omp/tests/omp-accounts.test.ts index 54c266de..55faf660 100644 --- a/paseo-omp/tests/omp-accounts.test.ts +++ b/paseo-omp/tests/omp-accounts.test.ts @@ -335,6 +335,56 @@ describe.skipIf(ON_WINDOWS)("listing", () => { expect(usedBy(4)).toBe(0.9); }); + test("tags each login with its plan and organization instead of repeating it in the label", async () => { + const view = await ( + await install({ + usage: { + reports: [ + { + provider: "anthropic", + fetchedAt: NOW, + limits: [limit("anthropic:5h", 0.25)], + metadata: { + accountId: "acc-a", + email: "a@example.test", + orgName: "Org A", + }, + }, + { + provider: "anthropic", + fetchedAt: NOW, + limits: [limit("anthropic:5h", 0.9)], + metadata: { + accountId: "acc-b", + email: "b@example.test", + orgName: "b@example.test's Organization", + }, + }, + { + provider: "openai-codex", + fetchedAt: NOW, + limits: [limit("openai-codex:5h", 0.1)], + metadata: { + accountId: "acc-c", + planType: "self_serve_business_prolite", + orgName: "self_serve_business_prolite", + }, + }, + ], + }, + }) + ).list(undefined, false); + const shown = view.accounts.map(({ label, tags }) => ({ label, tags })); + + expect(shown).toEqual([ + { label: "a@example.test", tags: ["Org A"] }, + // OMP's label names Org B, but the report says this login is the personal organization. + { label: "b@example.test (Org B)", tags: ["Personal"] }, + { label: "c@example.test", tags: ["Business"] }, + { label: "key", tags: [] }, + ]); + }); + test("does not guess between same-provider logins it cannot tell apart", async () => { const accounts = await install({ resets: { accounts: [] }, diff --git a/paseo-omp/tests/omp-state.test.ts b/paseo-omp/tests/omp-state.test.ts index e010d3eb..75f256d1 100644 --- a/paseo-omp/tests/omp-state.test.ts +++ b/paseo-omp/tests/omp-state.test.ts @@ -68,6 +68,8 @@ describe("omp quota reader", () => { accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Claude 5 Hour", windowLabel: "5 Hour", usedFraction: 0.8, @@ -83,6 +85,8 @@ describe("omp quota reader", () => { accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Codex Weekly", windowLabel: "Weekly", usedFraction: 0.3, diff --git a/paseo-omp/tests/omp-store-client.test.ts b/paseo-omp/tests/omp-store-client.test.ts index ab0f847d..434d147a 100644 --- a/paseo-omp/tests/omp-store-client.test.ts +++ b/paseo-omp/tests/omp-store-client.test.ts @@ -16,6 +16,8 @@ const quota = (provider: string): OmpQuota => ({ accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: provider, windowLabel: null, usedFraction: 0.25, diff --git a/paseo-omp/tests/profile-pills.test.ts b/paseo-omp/tests/profile-pills.test.ts index 3ebec612..7f11cb2b 100644 --- a/paseo-omp/tests/profile-pills.test.ts +++ b/paseo-omp/tests/profile-pills.test.ts @@ -143,7 +143,7 @@ test("owned agent directory updates reconcile new agent pills and cached quota r expect.objectContaining({ visible: true, label: "Quotas · 20%" }), ); expect(quota("default").update).toHaveBeenLastCalledWith( - expect.objectContaining({ visible: true, label: "Anthropic · 50%" }), + expect.objectContaining({ visible: true, label: "50%" }), ); expect(quota("codex").update).not.toHaveBeenCalled(); expect( diff --git a/paseo-omp/tests/provider-subagent-control.test.ts b/paseo-omp/tests/provider-subagent-control.test.ts index a3189586..b5d0fd0b 100644 --- a/paseo-omp/tests/provider-subagent-control.test.ts +++ b/paseo-omp/tests/provider-subagent-control.test.ts @@ -456,6 +456,7 @@ describe("OMP subagent controls", () => { const controls = (): OmpSubagentControls => ({ cancelSubagent: async () => false, steerSubagent: async () => {}, + listProviderAccounts: async () => [], }); const older = controls(); const newer = controls(); diff --git a/paseo-omp/tests/quota-popover.test.tsx b/paseo-omp/tests/quota-popover.test.tsx index fbbad5ee..9d72105e 100644 --- a/paseo-omp/tests/quota-popover.test.tsx +++ b/paseo-omp/tests/quota-popover.test.tsx @@ -4,17 +4,38 @@ import { act, type ReactNode } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { QuotaPopover } from "../client/quota-popover"; -import type { OmpQuota } from "../shared/quota"; +import type { OmpQuota, OmpSessionAccount } from "../shared/quota"; -const recorded = vi.hoisted(() => ({ quotas: [] as OmpQuota[] })); +const recorded = vi.hoisted(() => ({ + quotas: [] as OmpQuota[], + logins: [] as OmpSessionAccount[], + sent: [] as Array<{ agentId: string; text: string }>, +})); vi.mock("@getpaseo/plugin/client", () => ({ - useAgent: () => ({ provider: "omp", model: "anthropic/example" }), + useAgent: () => ({ provider: "omp", model: "anthropic/example", status: "idle" }), useRpc: () => vi.fn(), + usePaseo: () => ({ + agents: { + ref: (agentId: string) => ({ + send: async (text: string) => { + recorded.sent.push({ agentId, text }); + }, + }), + }, + }), })); vi.mock("@getpaseo/plugin/client/ui", () => ({ Icon: () => null })); vi.mock("@tanstack/react-query", () => ({ - useQuery: () => ({ data: recorded, isLoading: false, error: null }), + useQuery: (options: { queryKey: readonly unknown[] }) => ({ + data: + options.queryKey[1] === "session-accounts" + ? { accounts: recorded.logins } + : { quotas: recorded.quotas }, + isLoading: false, + error: null, + }), + useQueryClient: () => ({ invalidateQueries: async () => {} }), })); vi.mock("react-native", () => ({ View: (props: { @@ -23,9 +44,23 @@ vi.mock("react-native", () => ({ accessibilityLabel?: string; style?: Record; }) => ( -
{props.children}
+
+ {props.children} +
), Text: (props: { children?: ReactNode }) => {props.children}, + Pressable: (props: { + children?: ReactNode; + accessibilityLabel?: string; + onPress?: () => void; + }) => ( + + ), })); const props: PluginButtonContentProps = { @@ -61,6 +96,8 @@ function quota(accountKey: string, limitId: string, usedFraction: number): OmpQu accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Usage", windowLabel: "Weekly", usedFraction, @@ -76,6 +113,8 @@ let root: Root; beforeEach(() => { vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); recorded.quotas = []; + recorded.logins = []; + recorded.sent = []; container = document.createElement("div"); document.body.append(container); root = createRoot(container); @@ -141,4 +180,96 @@ describe("quota popover reconciliation", () => { expect(secondLimit.isConnected).toBe(false); expect(container.textContent).not.toContain("80%"); }); + + test("shows plan and organization badges beside the account name", async () => { + await render([ + { + ...quota("a", "weekly", 0.4), + plan: "self_serve_business_prolite", + organization: "Example Team", + }, + ]); + const name = heading("same@example.invalid"); + expect(name.contains(text("Business"))).toBe(true); + expect(name.contains(text("Example Team"))).toBe(true); + expect(name.getAttribute("data-accessibility-label")).toBe( + "same@example.invalid · Business · Example Team", + ); + }); + + test("marks the account this session uses and switches to another from its heading", async () => { + recorded.logins = [ + { + credentialId: 3, + label: "same@example.invalid", + active: false, + onlyLogin: false, + quotaAccountKeys: ["a"], + }, + { credentialId: 5, label: "other", active: true, onlyLogin: false, quotaAccountKeys: ["b"] }, + ]; + await render([ + quota("a", "weekly", 0.9), + { ...quota("b", "weekly", 0.2), email: "b@x.invalid" }, + ]); + + const inUse = heading("b@x.invalid"); + expect(inUse.contains(text("IN USE"))).toBe(true); + // The account in use leads its provider even though the other one has more usage. + expect( + inUse.compareDocumentPosition(heading("same@example.invalid")) & + Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(container.querySelector('[aria-label="Use b@x.invalid for this session"]')).toBeNull(); + + const other = heading("same@example.invalid"); + const button = other.querySelector( + '[aria-label="Use same@example.invalid for this session"]', + ) as HTMLButtonElement; + expect(button.textContent).toBe("Switch"); + await act(async () => button.click()); + expect(recorded.sent).toEqual([ + { agentId: "synthetic-agent", text: "/session pin OAuth credential #3" }, + ]); + }); + + test("labels a provider's only login without a Switch button or an IN USE claim", async () => { + recorded.logins = [ + { + credentialId: 8, + label: "same@example.invalid", + active: false, + onlyLogin: true, + quotaAccountKeys: ["a"], + }, + ]; + await render([quota("a", "weekly", 0.3)]); + + const only = heading("same@example.invalid"); + expect(only.contains(text("ONLY LOGIN"))).toBe(true); + expect(container.textContent).not.toContain("IN USE"); + expect(container.querySelector('[aria-label$="for this session"]')).toBeNull(); + }); + + test("shows an unnamed account's state below its limits, where it has no heading", async () => { + const unnamed = { ...quota("a", "weekly", 0.3), email: null }; + const login = { + credentialId: 8, + label: "OAuth credential #8", + active: false, + onlyLogin: true, + quotaAccountKeys: ["a"], + }; + + recorded.logins = [login]; + await render([unnamed]); + expect(container.querySelector('[role="heading"]')).toBeNull(); + expect(text("ONLY LOGIN")).toBeTruthy(); + expect(container.querySelector('[aria-label$="for this session"]')).toBeNull(); + + recorded.logins = [{ ...login, active: true, onlyLogin: false }]; + await render([unnamed]); + expect(text("IN USE")).toBeTruthy(); + expect(container.textContent).not.toContain("ONLY LOGIN"); + }); }); diff --git a/paseo-omp/tests/quota-state.test.ts b/paseo-omp/tests/quota-state.test.ts index baa345f6..9cc2936c 100644 --- a/paseo-omp/tests/quota-state.test.ts +++ b/paseo-omp/tests/quota-state.test.ts @@ -1,20 +1,29 @@ -import { mkdtemp, rm } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; -import { afterEach, describe, expect, test } from "vitest"; +import { afterEach, describe, expect, test, vi } from "vitest"; +import { providerIcon } from "../client/provider-brand"; import { quotaDetailLabel, quotaProviderFromSession, quotaProviderGroups, - quotaProviderIconName, quotaRecordedLabel, quotaResetLabel, + quotaSessionAccounts, quotaSeverityForProvider, quotaSummaryForProvider, quotasForProvider, + sessionPinCommand, } from "../client/quota-state"; -import { listOmpQuotasFrom, resolveListOmpQuotas } from "../server/quota"; +import { OmpRpcRequestRejectedError } from "../server/provider/omp-rpc-transport"; +import { + listOmpQuotasFrom, + resolveListOmpQuotas, + resolveListOmpSessionAccounts, +} from "../server/quota"; +import { OmpSubagentControlRegistry, type OmpSubagentControls } from "../server/subagents"; import type { OmpQuota } from "../shared/quota"; const quotaRoots: string[] = []; @@ -32,6 +41,8 @@ const quotas: OmpQuota[] = [ accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Claude 5 Hour", windowLabel: "5 Hour", usedFraction: 0.25, @@ -47,6 +58,8 @@ const quotas: OmpQuota[] = [ accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Cursor Pro", windowLabel: null, usedFraction: 0.9, @@ -66,19 +79,57 @@ describe("session-specific quota selection", () => { expect(quotasForProvider(quotas, "anthropic")).toEqual([quotas[0]]); expect(quotaSummaryForProvider(quotas, "anthropic")).toEqual({ visible: true, - label: "Anthropic · 25%", + label: "25%", + title: "Anthropic · all accounts · 25% (last recorded usage, not live)", }); - expect(quotaSummaryForProvider(quotas, "azure")).toEqual({ + expect(quotaSummaryForProvider(quotas, "azure")).toMatchObject({ visible: true, label: "—" }); + }); + + test("summarizes the account in use, not the provider's busiest account", () => { + const rows: OmpQuota[] = [ + { ...quotas[0], accountKey: "spent", usedFraction: 1 }, + { ...quotas[0], accountKey: "working", usedFraction: 0.19 }, + ]; + const working = { + credentialId: 5, + label: "me@example.invalid (Team)", + active: true, + onlyLogin: false, + quotaAccountKeys: ["working"], + }; + + expect(quotaSummaryForProvider(rows, "anthropic", false, working)).toEqual({ visible: true, - label: "Azure · —", + label: "19%", + title: "Anthropic · me@example.invalid (Team) · 19% (last recorded usage, not live)", }); + expect(quotaSeverityForProvider(rows, "anthropic", false, working)).toBe("ok"); + // Without an account in use, or with no recorded usage for it, the provider's peak stands. + expect(quotaSummaryForProvider(rows, "anthropic").label).toBe("100%"); + expect( + quotaSummaryForProvider(rows, "anthropic", false, { ...working, quotaAccountKeys: [] }).label, + ).toBe("100%"); }); test("maps each provider to a distinct icon and severity bucket", () => { - expect(quotaProviderIconName("anthropic")).toBe("Asterisk"); - expect(quotaProviderIconName("cursor")).toBe("MousePointer2"); - expect(quotaProviderIconName("azure")).toBe("Cloud"); - expect(quotaProviderIconName("unknown-vendor")).toBe("Gauge"); + const brand = (provider: string) => providerIcon(provider) as { svg: string }; + // Brand marks for the providers Paseo itself draws; same company, same mark. + expect(brand("anthropic").svg).toEqual(expect.any(String)); + expect(brand("openai-codex")).toEqual(brand("openai")); + expect(brand("xai-oauth")).toEqual(brand("xai")); + expect(brand("antigravity-cli")).toEqual(brand("google-antigravity")); + expect( + new Set( + ["anthropic", "openai-codex", "github-copilot", "antigravity-cli", "xai-oauth"].map( + (provider) => brand(provider).svg, + ), + ).size, + ).toBe(5); + // Others keep the closest Lucide icon. + expect(providerIcon("cursor")).toBe("MousePointer2"); + expect(providerIcon("azure")).toBe("Cloud"); + expect(providerIcon("unknown-vendor")).toBe("Gauge"); + expect(providerIcon(null)).toBe("Gauge"); expect(quotaSeverityForProvider(quotas, "anthropic")).toBe("ok"); expect(quotaSeverityForProvider(quotas, "cursor")).toBe("danger"); expect(quotaSeverityForProvider(quotas, "azure")).toBe("unknown"); @@ -211,6 +262,8 @@ describe("quota timestamps", () => { accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, usedFraction: 0.25, windowLabel: "5 Hour", status: "ok", @@ -231,9 +284,128 @@ describe("quota reset countdown", () => { expect(quotaResetLabel(now - 1_000, now)).toBe("resets 0m"); expect(quotaResetLabel(null, now)).toBe(""); }); + + test("shows days and hours once a reset is a day or more away", () => { + const now = Date.UTC(2026, 0, 1, 0, 0, 0); + const at = (hours: number, minutes = 0) => now + hours * 3_600_000 + minutes * 60_000; + expect(quotaResetLabel(at(23, 59), now)).toBe("resets 23h 59m"); + expect(quotaResetLabel(at(24), now)).toBe("resets 1d 0h"); + expect(quotaResetLabel(at(357, 52), now)).toBe("resets 14d 21h"); + }); }); describe("OMP quota reader", () => { + test("tags accounts with the plan and organization from OMP's cached usage reports", async () => { + const root = await mkdtemp(join(tmpdir(), "paseo-omp-tags-")); + quotaRoots.push(root); + const path = join(root, "agent.db"); + const database = new DatabaseSync(path); + database.exec(`CREATE TABLE usage_history ( + id INTEGER PRIMARY KEY, provider TEXT, account_key TEXT, email TEXT, + limit_id TEXT, label TEXT, window_label TEXT, used_fraction REAL, status TEXT, + resets_at INTEGER, recorded_at INTEGER + ); + CREATE TABLE cache (key TEXT PRIMARY KEY, value TEXT, expires_at INTEGER)`); + const now = Date.now(); + const usage = database.prepare( + "INSERT INTO usage_history VALUES (?, ?, ?, ?, 'weekly', 'Weekly', NULL, 0.1, 'ok', NULL, ?)", + ); + usage.run( + 1, + "openai-codex", + "oauth|account:a|email:team@example.invalid", + "team@example.invalid", + now, + ); + usage.run( + 2, + "openai-codex", + "oauth|account:b|email:me@example.invalid", + "me@example.invalid", + now, + ); + usage.run( + 3, + "anthropic", + "oauth|account:c|email:me@example.invalid", + "me@example.invalid", + now, + ); + usage.run( + 4, + "anthropic", + "oauth|account:d|email:work@example.invalid", + "work@example.invalid", + now, + ); + usage.run(5, "xai-oauth", "oauth|account:e", null, now); + const cache = database.prepare("INSERT INTO cache VALUES (?, ?, NULL)"); + const report = (provider: string, fetchedAt: number, metadata: object) => + JSON.stringify({ expiresAt: 0, value: { provider, fetchedAt, limits: [], metadata } }); + cache.run( + "usage_cache:report:1:openai-codex:https://example.invalid/api:oauth|account:a|email:team@example.invalid", + report("openai-codex", 2, { + planType: "self_serve_business_prolite", + orgName: "self_serve_business_prolite", + }), + ); + cache.run( + "usage_cache:report:0:openai-codex:default:oauth|account:a|email:team@example.invalid", + report("openai-codex", 1, { planType: "plus" }), + ); + cache.run( + "usage_cache:report:1:openai-codex:default:oauth|account:b|email:me@example.invalid", + report("openai-codex", 1, { planType: "prolite", orgName: "prolite" }), + ); + cache.run( + "usage_cache:report:3:anthropic:default:oauth|account:c|email:me@example.invalid", + report("anthropic", 1, { orgName: "me@example.invalid's Organization" }), + ); + cache.run( + "usage_cache:report:3:anthropic:default:oauth|account:d|email:work@example.invalid", + report("anthropic", 1, { orgName: "Example Team" }), + ); + // Another provider's report under the same key suffix, and an unreadable one, are ignored. + cache.run( + "usage_cache:report:xai-oauth:default:oauth|account:c|email:me@example.invalid", + report("xai-oauth", 5, { plan: "business" }), + ); + cache.run("usage_cache:report:xai-oauth:default:oauth|account:e", "not json"); + database.close(); + + const recorded = listOmpQuotasFrom(path, now); + const tagsOf = (provider: string, email: string | null) => + quotaProviderGroups(recorded, null) + .find((group) => group.provider === provider) + ?.accounts.find((account) => account.email === email)?.tags; + expect(tagsOf("openai-codex", "team@example.invalid")).toEqual(["Business"]); + expect(tagsOf("openai-codex", "me@example.invalid")).toEqual(["Pro Lite"]); + expect(tagsOf("anthropic", "me@example.invalid")).toEqual(["Personal"]); + expect(tagsOf("anthropic", "work@example.invalid")).toEqual(["Example Team"]); + expect(tagsOf("xai-oauth", null)).toEqual([]); + }); + + test("reads quotas without tags when OMP has no usage cache table", async () => { + const root = await mkdtemp(join(tmpdir(), "paseo-omp-no-cache-")); + quotaRoots.push(root); + const path = join(root, "agent.db"); + const database = new DatabaseSync(path); + database.exec(`CREATE TABLE usage_history ( + id INTEGER PRIMARY KEY, provider TEXT, account_key TEXT, limit_id TEXT, label TEXT, + window_label TEXT, used_fraction REAL, status TEXT, resets_at INTEGER, recorded_at INTEGER + )`); + const now = Date.now(); + database + .prepare( + "INSERT INTO usage_history VALUES (1, 'anthropic', 'k', 'w', 'Weekly', NULL, 0.1, 'ok', NULL, ?)", + ) + .run(now); + database.close(); + expect(listOmpQuotasFrom(path, now)).toEqual([ + expect.objectContaining({ label: "Weekly", plan: null, organization: null }), + ]); + }); + test("shows Copilot usernames and distinguishes GitHub from the recorded GHE host", async () => { const root = await mkdtemp(join(tmpdir(), "paseo-omp-copilot-")); quotaRoots.push(root); @@ -618,6 +790,464 @@ describe("OMP quota reader", () => { }); }); +describe("session account", () => { + const sha = (value: string) => createHash("sha256").update(value).digest("hex"); + const teamA = "oauth|account:team|email:a@example.invalid|org:team"; + const teamB = "oauth|account:team|email:b@example.invalid|org:team"; + const personal = "oauth|account:me|email:a@example.invalid|org:mine"; + const LOCATION_ENV = [ + "PASEO_OMP_AGENT_DIR", + "OMP_AGENT_DIR", + "PI_CODING_AGENT_DIR", + "OMP_PROFILE", + "PI_PROFILE", + "PI_CONFIG_DIR", + "XDG_DATA_HOME", + ]; + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + /** A fresh HOME, so the daemon default store is `/.omp/agent` and profiles sit beside it. */ + async function home(): Promise { + const root = await mkdtemp(join(tmpdir(), "paseo-omp-session-accounts-")); + quotaRoots.push(root); + for (const name of LOCATION_ENV) vi.stubEnv(name, undefined); + vi.stubEnv("HOME", root); + return root; + } + + type Login = { + id: number; + email?: string; + accountId?: string; + orgId?: string; + orgName?: string; + disabled?: boolean; + /** A stored API key instead of an OAuth login. */ + apiKey?: boolean; + }; + + /** OMP's tables with only the columns this reads; tokens sit beside identity as in OMP. */ + async function store( + agentDir: string, + seed: { + provider: string; + usage: string[]; + logins: Login[]; + pins?: Array<[sessionId: string, credentialId: number, expiresAtSec: number]>; + }, + ): Promise { + await mkdir(agentDir, { recursive: true }); + const db = new DatabaseSync(join(agentDir, "agent.db")); + db.exec(`CREATE TABLE usage_history (provider TEXT, account_key TEXT); + CREATE TABLE auth_credentials (id INTEGER PRIMARY KEY, provider TEXT, + credential_type TEXT, data TEXT, disabled_cause TEXT); + CREATE TABLE cache (key TEXT PRIMARY KEY, value TEXT, expires_at INTEGER)`); + for (const key of seed.usage) { + db.prepare("INSERT INTO usage_history VALUES (?, ?)").run(seed.provider, key); + } + for (const { id, disabled, apiKey, ...identity } of seed.logins) { + db.prepare("INSERT INTO auth_credentials VALUES (?, ?, ?, ?, ?)").run( + id, + seed.provider, + apiKey ? "api_key" : "oauth", + JSON.stringify({ ...identity, access: "secret-token" }), + disabled ? "user" : null, + ); + } + for (const [sessionId, credentialId, expiresAt] of seed.pins ?? []) { + db.prepare("INSERT INTO cache VALUES (?, ?, ?)").run( + `session:sticky:${seed.provider}:${sessionId}`, + JSON.stringify({ type: "oauth", index: 0, credentialId, lastUsedAtMs: 1 }), + expiresAt, + ); + } + db.close(); + } + + const future = () => Math.floor(Date.now() / 1000) + 3_600; + + const codexTeam = (agentDir: string) => + store(agentDir, { + provider: "openai-codex", + usage: [teamA, teamB, personal], + logins: [ + { id: 1, email: "a@example.invalid", accountId: "team", orgId: "team", orgName: "Team" }, + { id: 2, email: "b@example.invalid", accountId: "team", orgId: "team", orgName: "Team" }, + { + id: 3, + email: "a@example.invalid", + accountId: "me", + orgId: "mine", + orgName: "a@example.invalid", + }, + { + id: 4, + email: "gone@example.invalid", + accountId: "x", + orgId: "x", + orgName: "X", + disabled: true, + }, + ], + pins: [ + ["bundled-session", 2, future()], + ["expired-session", 1, 1], + ], + }); + + const agentLookup = + (provider: string, sessionId: string | null = null) => + async () => ({ provider, sessionId }); + + function registryWith(controls: Partial): OmpSubagentControlRegistry { + const registry = new OmpSubagentControlRegistry(); + registry.register("agent-1", { + cancelSubagent: async () => false, + steerSubagent: async () => {}, + listProviderAccounts: async () => [], + ...controls, + }); + return registry; + } + + const runtimeLogin = (credentialId: number, active = false) => ({ + credentialId, + provider: "openai-codex", + label: `login ${credentialId}`, + type: "oauth" as const, + active, + }); + + test("links each login to its own usage when team seats share an account id and emails repeat across orgs", async () => { + await codexTeam(join(await home(), ".omp", "agent")); + const registry = registryWith({ + listProviderAccounts: async () => [ + runtimeLogin(2, true), + runtimeLogin(1), + runtimeLogin(3), + { ...runtimeLogin(9), type: "api_key" }, + ], + }); + + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "openai-codex" }, + registry, + agentLookup("omp-plugin"), + ); + + expect(result.accounts).toEqual([ + { + credentialId: 2, + label: "login 2", + active: true, + onlyLogin: false, + quotaAccountKeys: [sha(teamB)], + }, + { + credentialId: 1, + label: "login 1", + active: false, + onlyLogin: false, + quotaAccountKeys: [sha(teamA)], + }, + { + credentialId: 3, + label: "login 3", + active: false, + onlyLogin: false, + quotaAccountKeys: [sha(personal)], + }, + ]); + }); + + test("explains an OMP too old to list logins", async () => { + await codexTeam(join(await home(), ".omp", "agent")); + const outdated = registryWith({ + listProviderAccounts: async () => { + throw new OmpRpcRequestRejectedError(undefined, "unsupported_command"); + }, + }); + + await expect( + resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "openai-codex" }, + outdated, + agentLookup("omp-plugin"), + ), + ).rejects.toThrow("Update OMP to show which login this session uses"); + }); + + test("reads the pin OMP recorded for a session no OMP Plugin runtime owns, such as Paseo's bundled omp", async () => { + await codexTeam(join(await home(), ".omp", "agent")); + const list = (sessionId: string | null) => + resolveListOmpSessionAccounts( + { agentId: "bundled-agent", provider: "openai-codex" }, + new OmpSubagentControlRegistry(), + agentLookup("omp", sessionId), + ); + + expect((await list("bundled-session")).accounts).toEqual([ + { + credentialId: 1, + label: "a@example.invalid (Team)", + active: false, + onlyLogin: false, + quotaAccountKeys: [sha(teamA)], + }, + { + credentialId: 2, + label: "b@example.invalid (Team)", + active: true, + onlyLogin: false, + quotaAccountKeys: [sha(teamB)], + }, + { + credentialId: 3, + label: "a@example.invalid", + active: false, + onlyLogin: false, + quotaAccountKeys: [sha(personal)], + }, + ]); + // An expired pin marks nothing; the logins stay switchable. + expect((await list("expired-session")).accounts.some((login) => login.active)).toBe(false); + // No stored session at all is not an error: the popover simply cannot name the account. + expect((await list(null)).accounts).toEqual([]); + }); + + test("reads a profile agent's logins and usage from that profile, never the default store", async () => { + const root = await home(); + const profileUsage = "oauth|account:p|email:profile@example.invalid"; + const defaultUsage = "oauth|account:d|email:default@example.invalid"; + // The same credential id is a different account in each store. + await store(join(root, ".omp", "agent"), { + provider: "anthropic", + usage: [defaultUsage], + logins: [{ id: 1, email: "default@example.invalid", accountId: "d" }], + pins: [["session-1", 1, future()]], + }); + await store(join(root, ".omp", "profiles", "team-a", "agent"), { + provider: "anthropic", + usage: [profileUsage], + logins: [{ id: 1, email: "profile@example.invalid", accountId: "p" }], + pins: [["session-1", 1, future()]], + }); + const list = (provider: string) => + resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "anthropic" }, + new OmpSubagentControlRegistry(), + agentLookup(provider, "session-1"), + ); + + expect((await list("omp-plugin-team-a")).accounts).toEqual([ + { + credentialId: 1, + label: "profile@example.invalid", + active: true, + onlyLogin: true, + quotaAccountKeys: [sha(profileUsage)], + }, + ]); + expect((await list("omp")).accounts).toEqual([ + { + credentialId: 1, + label: "default@example.invalid", + active: true, + onlyLogin: true, + quotaAccountKeys: [sha(defaultUsage)], + }, + ]); + }); + + test("never hands a removed login's leftover usage to the login that replaced it", async () => { + const root = await home(); + await store(join(root, ".omp", "agent"), { + provider: "anthropic", + usage: ["oauth|account:old|email:old@example.invalid|org:o"], + logins: [{ id: 7, email: "new@example.invalid", accountId: "new", orgId: "o" }], + pins: [["session-1", 7, future()]], + }); + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "anthropic" }, + new OmpSubagentControlRegistry(), + agentLookup("omp", "session-1"), + ); + + expect(result.accounts).toEqual([ + expect.objectContaining({ credentialId: 7, quotaAccountKeys: [] }), + ]); + }); + + test("flags a provider's only login without claiming it is in use, and links its sole identity-less usage", async () => { + const root = await home(); + const copilot = "oauth|enterprise:ghe.example.invalid|secret:abc123"; + // No pin: the session has not sent a Copilot request yet, as for a freshly opened agent. + await store(join(root, ".omp", "agent"), { + provider: "github-copilot", + usage: [copilot], + logins: [{ id: 8 }], + }); + + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "github-copilot" }, + new OmpSubagentControlRegistry(), + agentLookup("omp", "session-1"), + ); + + expect(result.accounts).toEqual([ + { + credentialId: 8, + label: "OAuth credential #8", + active: false, + onlyLogin: true, + quotaAccountKeys: [sha(copilot)], + }, + ]); + }); + + test("keeps the runtime's not-in-use answer for a sole login, as when an environment key serves the session", async () => { + await home(); + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "openai-codex" }, + registryWith({ listProviderAccounts: async () => [runtimeLogin(2, false)] }), + agentLookup("omp-plugin"), + ); + + expect(result.accounts).toEqual([ + expect.objectContaining({ credentialId: 2, active: false, onlyLogin: true }), + ]); + }); + + test("does not call an OAuth login the only one when a stored API key sits beside it", async () => { + const root = await home(); + await store(join(root, ".omp", "agent"), { + provider: "anthropic", + usage: [], + logins: [ + { id: 1, email: "a@example.invalid", accountId: "a" }, + { id: 2, apiKey: true }, + ], + }); + + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "anthropic" }, + new OmpSubagentControlRegistry(), + agentLookup("omp", "session-1"), + ); + + expect(result.accounts).toEqual([ + expect.objectContaining({ credentialId: 1, active: false, onlyLogin: false }), + ]); + }); + + test("compares organizations even for a provider's only login and usage account", async () => { + const root = await home(); + const list = async (usage: string) => { + await rm(join(root, ".omp"), { recursive: true, force: true }); + await store(join(root, ".omp", "agent"), { + provider: "anthropic", + usage: [usage], + logins: [{ id: 5, orgId: "a" }], + }); + return resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "anthropic" }, + new OmpSubagentControlRegistry(), + agentLookup("omp", "session-1"), + ); + }; + + expect((await list("oauth|org:b")).accounts[0]?.quotaAccountKeys).toEqual([]); + expect((await list("oauth|org:a")).accounts[0]?.quotaAccountKeys).toEqual([sha("oauth|org:a")]); + }); + + test("answers nothing when Paseo cannot name the agent, even with its runtime still registered", async () => { + const root = await home(); + // A login in the default store shares the credential id the profile runtime reports. + await store(join(root, ".omp", "agent"), { + provider: "openai-codex", + usage: [teamA], + logins: [{ id: 2, email: "a@example.invalid", accountId: "team", orgId: "team" }], + }); + + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "openai-codex" }, + registryWith({ listProviderAccounts: async () => [runtimeLogin(2, true)] }), + async () => null, + ); + + expect(result).toEqual({ accounts: [] }); + }); + + test("keeps an organization-scoped login apart from the same email's org-less usage, as OMP does", async () => { + const root = await home(); + const orgless = "oauth|account:same|email:same@example.invalid"; + const scoped = "oauth|account:same|email:same@example.invalid|org:corp"; + await store(join(root, ".omp", "agent"), { + provider: "anthropic", + usage: [orgless, scoped], + logins: [ + { id: 1, email: "same@example.invalid", accountId: "same", orgId: "corp" }, + { id: 2, email: "same@example.invalid", accountId: "same" }, + ], + }); + + const result = await resolveListOmpSessionAccounts( + { agentId: "agent-1", provider: "anthropic" }, + registryWith({ + listProviderAccounts: async () => [ + { ...runtimeLogin(1), provider: "anthropic" }, + { ...runtimeLogin(2), provider: "anthropic" }, + ], + }), + agentLookup("omp-plugin"), + ); + + expect(result.accounts.map((login) => [login.credentialId, login.quotaAccountKeys])).toEqual([ + [1, [sha(scoped)]], + [2, [sha(orgless)]], + ]); + }); + + test("puts the account in use first and builds the pin command OMP accepts", () => { + const groups = quotaProviderGroups( + [ + { ...quotas[0], accountKey: "busy", usedFraction: 0.9 }, + { ...quotas[0], accountKey: "idle", usedFraction: 0.1 }, + { ...quotas[0], accountKey: "unlinked", usedFraction: 0.5 }, + ], + "anthropic", + ); + const linked = quotaSessionAccounts(groups[0].accounts, [ + { + credentialId: 4, + label: "busy", + active: false, + onlyLogin: false, + quotaAccountKeys: ["busy"], + }, + { + credentialId: 7, + label: "idle", + active: true, + onlyLogin: false, + quotaAccountKeys: ["idle"], + }, + ]); + + expect( + linked.map(({ accountKey, inUse, login }) => [accountKey, inUse, login?.credentialId]), + ).toEqual([ + ["idle", true, 7], + ["busy", false, 4], + ["unlinked", false, undefined], + ]); + expect(sessionPinCommand(4)).toBe("/session pin OAuth credential #4"); + }); +}); + describe("profile alias and opaque-model quotas", () => { test("recognizes native and profile plugin model providers without guessing opaque ids", () => { expect(quotaProviderFromSession("omp-plugin", "anthropic/claude-fable-5")).toBe("anthropic"); @@ -627,12 +1257,15 @@ describe("profile alias and opaque-model quotas", () => { expect(quotaProviderFromSession("omp-plugin-team-beta", "omp:model:opaque-hash")).toBeNull(); }); test("opaque OMP models retain an explicitly aggregate quota pill", () => { - expect(quotaSummaryForProvider(quotas, null, true)).toEqual({ + expect(quotaSummaryForProvider(quotas, null, true)).toMatchObject({ visible: true, label: "Quotas · 90%", }); expect(quotaSeverityForProvider(quotas, null, true)).toBe("danger"); - expect(quotaSummaryForProvider([], null, true)).toEqual({ visible: true, label: "Quotas · —" }); + expect(quotaSummaryForProvider([], null, true)).toMatchObject({ + visible: true, + label: "Quotas · —", + }); expect(quotaSummaryForProvider(quotas, null).visible).toBe(false); }); });