diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 305c2c87..df704972 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. 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. **CURRENT PROVIDER** identifies the session's provider, not its active account. Provider summary percentages show the highest recorded usage across that provider's 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). diff --git a/paseo-omp/client/omp-accounts-section.tsx b/paseo-omp/client/omp-accounts-section.tsx index 3ee7e3ae..69cfae8c 100644 --- a/paseo-omp/client/omp-accounts-section.tsx +++ b/paseo-omp/client/omp-accounts-section.tsx @@ -191,9 +191,26 @@ function AccountCard({ return ( - - {account.label} - + + + {account.label} + + {account.tags.map((tag) => ( + + + {tag} + + + ))} + {account.resets ? ( {resetsLabel(account.resets)} diff --git a/paseo-omp/client/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index aa44582e..7bca6ae7 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -85,7 +85,7 @@ export function QuotaPopover(props: PluginButtonContentProps) { }, detail: { color: theme.colors.foregroundMuted, fontSize: 11 }, account: { gap: 6, paddingTop: 4 }, - accountHeading: { flexDirection: "row" as const, alignItems: "baseline" as const }, + accountHeading: { flexDirection: "row" as const, alignItems: "center" as const }, accountLabel: { color: theme.colors.foregroundMuted, fontSize: 11, @@ -93,6 +93,29 @@ export function QuotaPopover(props: PluginButtonContentProps) { minWidth: 0, }, accountSuffix: { color: theme.colors.foregroundMuted, fontSize: 11, flexShrink: 0 }, + // Badges may shrink (each ellipsized) so a long organization never pushes the name out. + tags: { flexDirection: "row" as const, gap: 4, flexShrink: 1, minWidth: 0 }, + headingTags: { + flexDirection: "row" as const, + gap: 4, + flexShrink: 1, + minWidth: 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, + flexShrink: 1, + minWidth: 0, + maxWidth: 160, + }, }), [layout.compact, theme], ); @@ -141,9 +164,9 @@ export function QuotaPopover(props: PluginButtonContentProps) { {account.label ? ( @@ -152,6 +175,23 @@ export function QuotaPopover(props: PluginButtonContentProps) { {account.suffix ? ( {` · ${account.suffix}`} ) : null} + {account.tags.length > 0 ? ( + + {account.tags.map((tag) => ( + + {tag} + + ))} + + ) : null} + + ) : account.tags.length > 0 ? ( + + {account.tags.map((tag) => ( + + {tag} + + ))} ) : null} {account.accountService ? ( diff --git a/paseo-omp/client/quota-state.ts b/paseo-omp/client/quota-state.ts index 9518a602..dc0b09e7 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -1,3 +1,4 @@ +import { accountTags } from "../shared/account-tags"; import type { OmpQuota } from "../shared/quota"; import { isOmpProvider } from "./omp-store-state"; @@ -97,6 +98,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 +146,14 @@ export function quotaProviderGroups( return groups; } +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 +176,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 +219,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/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/quota.ts b/paseo-omp/server/quota.ts index 9d4665e3..5c51fa97 100644 --- a/paseo-omp/server/quota.ts +++ b/paseo-omp/server/quota.ts @@ -46,6 +46,78 @@ 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 { + // A key range on the primary key (";" follows ":"), where LIKE would scan the whole cache. + rows = database + .prepare( + "SELECT key, value FROM cache WHERE key >= 'usage_cache:report:' AND key < '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. Both + * tags come from the newest report naming either, so two reports are never mixed into one badge row. + */ +function accountTags( + reports: readonly CachedReport[], + provider: string, + accountKey: string, +): AccountTags { + const best = reports + .filter((report) => report.provider === provider && report.key.endsWith(`:${accountKey}`)) + .sort((a, b) => b.fetchedAt - a.fetchedAt) + .find((report) => report.plan || report.organization); + return { plan: best?.plan ?? null, organization: best?.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 +151,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 +164,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), }, ]; }); diff --git a/paseo-omp/shared/account-tags.ts b/paseo-omp/shared/account-tags.ts new file mode 100644 index 00000000..6cd19e65 --- /dev/null +++ b/paseo-omp/shared/account-tags.ts @@ -0,0 +1,44 @@ +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) { + // An own-property lookup: a plan named like an Object member ("constructor") is still a plan. + const key = plan.toLowerCase(); + tags.push( + Object.hasOwn(PLAN_LABELS, key) + ? PLAN_LABELS[key] + : 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..0b66b701 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()).default([]), 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/quota.ts b/paseo-omp/shared/quota.ts index be39817b..23f6f5e0 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(), 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/quota-popover.test.tsx b/paseo-omp/tests/quota-popover.test.tsx index fbbad5ee..6a0efff2 100644 --- a/paseo-omp/tests/quota-popover.test.tsx +++ b/paseo-omp/tests/quota-popover.test.tsx @@ -23,7 +23,12 @@ vi.mock("react-native", () => ({ accessibilityLabel?: string; style?: Record; }) => ( -
{props.children}
+
+ {props.children} +
), Text: (props: { children?: ReactNode }) => {props.children}, })); @@ -61,6 +66,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, @@ -141,4 +148,20 @@ 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", + ); + }); }); diff --git a/paseo-omp/tests/quota-state.test.ts b/paseo-omp/tests/quota-state.test.ts index baa345f6..befa3363 100644 --- a/paseo-omp/tests/quota-state.test.ts +++ b/paseo-omp/tests/quota-state.test.ts @@ -15,6 +15,7 @@ import { quotasForProvider, } from "../client/quota-state"; import { listOmpQuotasFrom, resolveListOmpQuotas } from "../server/quota"; +import { accountTags } from "../shared/account-tags"; import type { OmpQuota } from "../shared/quota"; const quotaRoots: string[] = []; @@ -32,6 +33,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 +50,8 @@ const quotas: OmpQuota[] = [ accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Cursor Pro", windowLabel: null, usedFraction: 0.9, @@ -211,6 +216,8 @@ describe("quota timestamps", () => { accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, usedFraction: 0.25, windowLabel: "5 Hour", status: "ok", @@ -231,9 +238,154 @@ 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); + usage.run( + 6, + "openai-codex", + "oauth|account:g|email:mixed@example.invalid", + "mixed@example.invalid", + 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"); + cache.run("usage_cache:report:xai-oauth:other:oauth|account:e", null); + // A newer report names only a plan, an older one only an organization: never mixed. + cache.run( + "usage_cache:report:1:openai-codex:default:oauth|account:g|email:mixed@example.invalid", + report("openai-codex", 9, { planType: "plus" }), + ); + cache.run( + "usage_cache:report:0:openai-codex:default:oauth|account:g|email:mixed@example.invalid", + report("openai-codex", 3, { orgName: "Example Team" }), + ); + 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([]); + expect(tagsOf("openai-codex", "mixed@example.invalid")).toEqual(["Plus"]); + }); + + test("names a plan that matches an Object member as a plan", () => { + for (const plan of ["constructor", "__proto__", "toString"]) { + const tags = accountTags({ plan, organization: null, email: null }); + expect(tags).toEqual([plan.charAt(0).toUpperCase() + plan.slice(1)]); + expect(typeof tags[0]).toBe("string"); + } + }); + + 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);