From 67d1ddc34dd4b3cf3ae499f3df1955f1ab6e38db Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 10:23:32 +0900 Subject: [PATCH 1/9] feat(paseo-omp): tag quota accounts with plan and organization - Read each account's plan and organization from OMP's cached usage reports and show them as badges. - Show an Anthropic organization named after the account's email as Personal. - Show reset countdowns a day or more away as days and hours. --- paseo-omp/README.md | 2 +- paseo-omp/client/quota-popover.tsx | 21 ++++ paseo-omp/client/quota-state.ts | 39 ++++++- paseo-omp/server/quota.ts | 70 +++++++++++++ paseo-omp/shared/quota.ts | 4 + paseo-omp/tests/omp-state.test.ts | 4 + paseo-omp/tests/omp-store-client.test.ts | 2 + paseo-omp/tests/quota-popover.test.tsx | 15 +++ paseo-omp/tests/quota-state.test.ts | 125 +++++++++++++++++++++++ 9 files changed, 279 insertions(+), 3 deletions(-) diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 305c2c87..3760cbb0 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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). -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 under each account 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/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index aa44582e..dae2eccf 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -93,6 +93,18 @@ export function QuotaPopover(props: PluginButtonContentProps) { minWidth: 0, }, accountSuffix: { color: theme.colors.foregroundMuted, fontSize: 11, flexShrink: 0 }, + tags: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 4 }, + 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, + }, }), [layout.compact, theme], ); @@ -154,6 +166,15 @@ export function QuotaPopover(props: PluginButtonContentProps) { ) : null} ) : null} + {account.tags.length > 0 ? ( + + {account.tags.map((tag) => ( + + {tag} + + ))} + + ) : null} {account.accountService ? ( {account.accountService === "github" diff --git a/paseo-omp/client/quota-state.ts b/paseo-omp/client/quota-state.ts index 9518a602..3c17d8d2 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -97,6 +97,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 +145,37 @@ export function quotaProviderGroups( return groups; } +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", +}; + +function accountTags(quotas: readonly OmpQuota[], email: string | null): string[] { + const plan = quotas.find((quota) => quota.plan)?.plan ?? null; + const organization = quotas.find((quota) => quota.organization)?.organization ?? null; + const tags: string[] = []; + if (plan) { + tags.push(PLAN_LABELS[plan.toLowerCase()] ?? plan.charAt(0).toUpperCase() + plan.slice(1)); + } + // Anthropic names a personal account's default organization after its email. + if (organization) { + tags.push(email && organization === `${email}'s Organization` ? "Personal" : organization); + } + return [...new Set(tags)]; +} + function quotaAccountGroups(quotas: readonly OmpQuota[]): QuotaAccountGroup[] { const byAccount = new Map(); for (const quota of quotas) { @@ -165,6 +198,7 @@ function quotaAccountGroups(quotas: readonly OmpQuota[]): QuotaAccountGroup[] { email, accountService: service?.accountService ?? null, accountHost: service?.accountHost ?? null, + tags: accountTags(accountQuotas, email), label: email ?? accountId, suffix: null, quotas: [...accountQuotas].sort((a, b) => (b.usedFraction ?? -1) - (a.usedFraction ?? -1)), @@ -207,9 +241,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/quota.ts b/paseo-omp/server/quota.ts index 9d4665e3..8a5bfb83 100644 --- a/paseo-omp/server/quota.ts +++ b/paseo-omp/server/quota.ts @@ -46,6 +46,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 +147,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 +160,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/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-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..4f7a5015 100644 --- a/paseo-omp/tests/quota-popover.test.tsx +++ b/paseo-omp/tests/quota-popover.test.tsx @@ -61,6 +61,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 +143,17 @@ describe("quota popover reconciliation", () => { expect(secondLimit.isConnected).toBe(false); expect(container.textContent).not.toContain("80%"); }); + + test("shows plan and organization badges under the account heading", async () => { + await render([ + { + ...quota("a", "weekly", 0.4), + plan: "self_serve_business_prolite", + organization: "Example Team", + }, + ]); + const account = heading("same@example.invalid").parentElement; + expect(account?.contains(text("Business"))).toBe(true); + expect(account?.contains(text("Example Team"))).toBe(true); + }); }); diff --git a/paseo-omp/tests/quota-state.test.ts b/paseo-omp/tests/quota-state.test.ts index baa345f6..04d48b8e 100644 --- a/paseo-omp/tests/quota-state.test.ts +++ b/paseo-omp/tests/quota-state.test.ts @@ -32,6 +32,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 +49,8 @@ const quotas: OmpQuota[] = [ accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, label: "Cursor Pro", windowLabel: null, usedFraction: 0.9, @@ -211,6 +215,8 @@ describe("quota timestamps", () => { accountId: null, accountService: null, accountHost: null, + plan: null, + organization: null, usedFraction: 0.25, windowLabel: "5 Hour", status: "ok", @@ -231,9 +237,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); From 2213f3240328100d933697771055749be8fe0d6a Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 12:44:31 +0900 Subject: [PATCH 2/9] fix(paseo-omp): show account badges beside the account name - Move plan and organization badges into the account heading row and its accessibility label. --- paseo-omp/README.md | 2 +- paseo-omp/client/quota-popover.tsx | 23 ++++++++++++++++------- paseo-omp/tests/quota-popover.test.tsx | 9 +++++---- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 3760cbb0..2d1b2b1f 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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). -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 under each account 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**. +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/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index dae2eccf..df2c7915 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,7 +93,8 @@ export function QuotaPopover(props: PluginButtonContentProps) { minWidth: 0, }, accountSuffix: { color: theme.colors.foregroundMuted, fontSize: 11, flexShrink: 0 }, - tags: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 4 }, + 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, @@ -153,9 +154,9 @@ export function QuotaPopover(props: PluginButtonContentProps) { {account.label ? ( @@ -164,9 +165,17 @@ export function QuotaPopover(props: PluginButtonContentProps) { {account.suffix ? ( {` · ${account.suffix}`} ) : null} + {account.tags.length > 0 ? ( + + {account.tags.map((tag) => ( + + {tag} + + ))} + + ) : null} - ) : null} - {account.tags.length > 0 ? ( + ) : account.tags.length > 0 ? ( {account.tags.map((tag) => ( diff --git a/paseo-omp/tests/quota-popover.test.tsx b/paseo-omp/tests/quota-popover.test.tsx index 4f7a5015..e965bf1a 100644 --- a/paseo-omp/tests/quota-popover.test.tsx +++ b/paseo-omp/tests/quota-popover.test.tsx @@ -144,7 +144,7 @@ describe("quota popover reconciliation", () => { expect(container.textContent).not.toContain("80%"); }); - test("shows plan and organization badges under the account heading", async () => { + test("shows plan and organization badges beside the account name", async () => { await render([ { ...quota("a", "weekly", 0.4), @@ -152,8 +152,9 @@ describe("quota popover reconciliation", () => { organization: "Example Team", }, ]); - const account = heading("same@example.invalid").parentElement; - expect(account?.contains(text("Business"))).toBe(true); - expect(account?.contains(text("Example Team"))).toBe(true); + const name = heading("same@example.invalid"); + expect(name.contains(text("Business"))).toBe(true); + expect(name.contains(text("Example Team"))).toBe(true); + expect(name.getAttribute("aria-label")).toBe("same@example.invalid · Business · Example Team"); }); }); From 12f73a63653c661ece04746df5432efb79d7c996 Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 12:46:01 +0900 Subject: [PATCH 3/9] test(paseo-omp): expose accessibility labels from the react-native test double --- paseo-omp/tests/quota-popover.test.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/paseo-omp/tests/quota-popover.test.tsx b/paseo-omp/tests/quota-popover.test.tsx index e965bf1a..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}, })); @@ -155,6 +160,8 @@ describe("quota popover reconciliation", () => { const name = heading("same@example.invalid"); expect(name.contains(text("Business"))).toBe(true); expect(name.contains(text("Example Team"))).toBe(true); - expect(name.getAttribute("aria-label")).toBe("same@example.invalid · Business · Example Team"); + expect(name.getAttribute("data-accessibility-label")).toBe( + "same@example.invalid · Business · Example Team", + ); }); }); From 0a38773bc75ae3ef6fcd75186aacc9f858c6f705 Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 22:45:17 +0900 Subject: [PATCH 4/9] feat(paseo-omp): tag OMP account logins with plan and organization - Accounts cards show the plan and organization badges the quota popover shows, from OMP's cached usage report, and drop OMP's parenthesized organization from the label once a badge shows it. - One tag rule in shared/account-tags.ts serves both views; `tags` defaults to an empty list. --- paseo-omp/README.md | 2 +- paseo-omp/client/omp-accounts-section.tsx | 23 ++++++++-- paseo-omp/client/quota-state.ts | 38 ++++------------ paseo-omp/server/omp-accounts.ts | 38 +++++++++++++++- paseo-omp/shared/account-tags.ts | 38 ++++++++++++++++ paseo-omp/shared/omp-accounts.ts | 2 + paseo-omp/tests/omp-accounts-state.test.ts | 1 + paseo-omp/tests/omp-accounts.test.ts | 50 ++++++++++++++++++++++ 8 files changed, 156 insertions(+), 36 deletions(-) create mode 100644 paseo-omp/shared/account-tags.ts diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 2d1b2b1f..df704972 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -33,7 +33,7 @@ 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. 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**. 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-state.ts b/paseo-omp/client/quota-state.ts index 3c17d8d2..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"; @@ -145,35 +146,12 @@ export function quotaProviderGroups( return groups; } -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", -}; - -function accountTags(quotas: readonly OmpQuota[], email: string | null): string[] { - const plan = quotas.find((quota) => quota.plan)?.plan ?? null; - const organization = quotas.find((quota) => quota.organization)?.organization ?? null; - const tags: string[] = []; - if (plan) { - tags.push(PLAN_LABELS[plan.toLowerCase()] ?? plan.charAt(0).toUpperCase() + plan.slice(1)); - } - // Anthropic names a personal account's default organization after its email. - if (organization) { - tags.push(email && organization === `${email}'s Organization` ? "Personal" : organization); - } - return [...new Set(tags)]; +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[] { @@ -198,7 +176,7 @@ function quotaAccountGroups(quotas: readonly OmpQuota[]): QuotaAccountGroup[] { email, accountService: service?.accountService ?? null, accountHost: service?.accountHost ?? null, - tags: accountTags(accountQuotas, email), + tags: quotaAccountTags(accountQuotas, email), label: email ?? accountId, suffix: null, quotas: [...accountQuotas].sort((a, b) => (b.usedFraction ?? -1) - (a.usedFraction ?? -1)), 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/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..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/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: [] }, From 12c773a0e9d3a7e2e7f7a06ee50bda0b66d9c7d2 Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 23:04:52 +0900 Subject: [PATCH 5/9] fix(paseo-omp): name an OMP Plugin agent's quota provider from its live session - Paseo shows an OMP Plugin agent's model as an opaque id, so the quota pill and popover could not tell its provider and summarized every provider. - New RPC paseo-omp.session-model-provider asks the agent's live session, which maps the id back to OMP's model; a closed or unknown agent answers null and keeps the old summary. - The pill asks only for agents that are not closed and reuses the answer until the agent's model or status changes; the open popover asks again on the same changes. --- paseo-omp/README.md | 2 +- paseo-omp/client/quota-popover.tsx | 30 ++++- paseo-omp/client/quota-state.ts | 9 ++ paseo-omp/index.client.tsx | 39 +++++- paseo-omp/index.server.ts | 6 +- paseo-omp/server/provider/session.ts | 9 ++ paseo-omp/server/subagents.ts | 11 ++ paseo-omp/shared/quota.ts | 10 ++ paseo-omp/tests/profile-pills.test.ts | 94 ++++++++++++- .../tests/provider-subagent-control.test.ts | 16 +++ .../quota-popover-session-provider.test.tsx | 127 ++++++++++++++++++ 11 files changed, 342 insertions(+), 11 deletions(-) create mode 100644 paseo-omp/tests/quota-popover-session-provider.test.tsx diff --git a/paseo-omp/README.md b/paseo-omp/README.md index df704972..5a3652c4 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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. 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**. +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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index df2c7915..5f5e96d0 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -4,9 +4,10 @@ import { useQuery } from "@tanstack/react-query"; import { useMemo } from "react"; import { Text, View } from "react-native"; import { storeForProvider, storeLabel } from "../shared/omp-store"; -import { listOmpQuotas } from "../shared/quota"; +import { getOmpSessionModelProvider, listOmpQuotas } from "../shared/quota"; import { ompStoreKey } from "./omp-store-state"; import { + needsSessionModelProvider, type QuotaProviderGroup, quotaDetailLabel, quotaProviderFromSession, @@ -21,8 +22,31 @@ const QUOTA_POLL_MS = 30_000; export function QuotaPopover(props: PluginButtonContentProps) { const { theme, layout } = props; const agentId = props.context === "agent" ? props.agentId : ""; - const session = useAgent(agentId, (agent) => ({ model: agent.model, provider: agent.provider })); - const currentProvider = quotaProviderFromSession(session?.provider ?? "", session?.model ?? null); + const session = useAgent(agentId, (agent) => ({ + model: agent.model, + provider: agent.provider, + status: agent.status, + })); + const loadSessionModelProvider = useRpc(getOmpSessionModelProvider); + const sessionModelProvider = useQuery({ + // The answer comes from the live session, so a closed or resumed session asks again. + queryKey: [ + "paseo-omp", + "session-model-provider", + agentId, + session?.model ?? null, + session?.status ?? null, + ], + queryFn: () => loadSessionModelProvider({ agentId }), + enabled: Boolean( + agentId && session && needsSessionModelProvider(session.provider, session.model), + ), + retry: false, + }); + const currentProvider = + quotaProviderFromSession(session?.provider ?? "", session?.model ?? null) ?? + sessionModelProvider.data?.provider ?? + null; const store = storeForProvider(session?.provider); const loadQuotas = useRpc(listOmpQuotas); const quotas = useQuery({ diff --git a/paseo-omp/client/quota-state.ts b/paseo-omp/client/quota-state.ts index dc0b09e7..5d4115ca 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -44,6 +44,15 @@ export function quotaProviderFromSession( return model?.includes("/") ? model.split("/")[0] : null; } +/** An OMP Plugin agent's model reaches Paseo as an opaque id; its live session names the provider. */ +export function needsSessionModelProvider(provider: string, model: string | null): boolean { + return ( + isOmpProvider(provider.split("/")[0]) && + Boolean(model) && + quotaProviderFromSession(provider, model) === null + ); +} + export function quotaProviderLabel(provider: string | null): string { return provider ? (PROVIDER_LABELS[provider] ?? `${provider.slice(0, 1).toUpperCase()}${provider.slice(1)}`) diff --git a/paseo-omp/index.client.tsx b/paseo-omp/index.client.tsx index eabeeb15..2baab67d 100644 --- a/paseo-omp/index.client.tsx +++ b/paseo-omp/index.client.tsx @@ -28,6 +28,7 @@ import { quotaProviderIcon } from "./client/provider-icon"; import { OmpImageTimeline } from "./client/provider-image"; import { QuotaPopover } from "./client/quota-popover"; import { + needsSessionModelProvider, type QuotaSeverity, quotaProviderFromSession, quotaSeverityForProvider, @@ -61,7 +62,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 { getOmpSessionModelProvider, listOmpQuotas } from "./shared/quota"; import { OMP_RULE_NOTICE_KIND, ompRuleNoticeSchema } from "./shared/rule-notices"; import { OMP_SUBAGENT_STRIP_KIND, ompSubagentStripSchema } from "./shared/subagents"; @@ -382,15 +383,40 @@ export default function contribute(client: PluginClientContext) { } } + // Agent id to its session's provider, asked again only when the agent's model or status changes. + const sessionModelProviders = new Map(); + + async function sessionModelProvider(agent: AgentEntry["agent"]): Promise { + if (agent.status === "closed" || !needsSessionModelProvider(agent.provider, agent.model)) { + return null; + } + const key = `${agent.model}|${agent.status}`; + const cached = sessionModelProviders.get(agent.id); + if (cached?.key === key) return cached.provider; + try { + const { provider } = await client.rpc(getOmpSessionModelProvider, { agentId: agent.id }); + sessionModelProviders.set(agent.id, { key, provider }); + return provider; + } catch { + return null; + } + } + async function reconcileOnce(): Promise { if (!preferences) return; - const agents = await loadAgents(client.paseo); + const listed = (await loadAgents(client.paseo)).filter( + ({ agent }) => !agent.archivedAt && agent.workspaceId && agent.cwd, + ); + const sessionProviders = await Promise.all( + listed.map(({ agent }) => sessionModelProvider(agent)), + ); if (disposed || !preferences) return; const activeIds = new Set(); - for (const { agent } of agents) { - if (agent.archivedAt || !agent.workspaceId || !agent.cwd) continue; + for (const [index, { agent }] of listed.entries()) { + if (!agent.workspaceId || !agent.cwd) continue; activeIds.add(agent.id); - const quotaProvider = quotaProviderFromSession(agent.provider, agent.model); + const quotaProvider = + quotaProviderFromSession(agent.provider, agent.model) ?? sessionProviders[index]; const store = storeForProvider(agent.provider); let entry = pills.get(agent.id); if ( @@ -419,6 +445,9 @@ export default function contribute(client: PluginClientContext) { removePills(entry); pills.delete(agentId); } + for (const agentId of sessionModelProviders.keys()) { + if (!activeIds.has(agentId)) sessionModelProviders.delete(agentId); + } await Promise.all([refreshHubStatus(), refreshQuotaStatus()]); } diff --git a/paseo-omp/index.server.ts b/paseo-omp/index.server.ts index cd5c27aa..dd618f25 100644 --- a/paseo-omp/index.server.ts +++ b/paseo-omp/index.server.ts @@ -57,6 +57,7 @@ import { ompRuleNoticeRow } from "./server/rule-notices"; import { OmpSubagentControlRegistry, resolveCancelOmpSubagent, + resolveGetOmpSessionModelProvider, resolveSteerOmpSubagent, } from "./server/subagents"; import { resolveGetOmpSupportReport } from "./server/support-diagnostics"; @@ -116,7 +117,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 { getOmpSessionModelProvider, listOmpQuotas } from "./shared/quota"; import { cancelOmpSubagent, steerOmpSubagent } from "./shared/subagents"; import { getOmpSupportReport } from "./shared/support-diagnostics"; @@ -283,6 +284,9 @@ export default function contribute(server: PluginServerContext) { server.handle(steerOmpSubagent, (input) => resolveSteerOmpSubagent(input, subagentControlRegistry), ); + server.handle(getOmpSessionModelProvider, (input) => + resolveGetOmpSessionModelProvider(input, subagentControlRegistry), + ); const removeTurnRows = registerOmpTurnRows(server, [ompRuleNoticeRow, ompScreenshotRow]); const removeSessionOpenHook = server.before("agent.session_open", ({ request }) => { if (request.provider !== "omp-plugin" && !request.provider.startsWith("omp-plugin-")) return; diff --git a/paseo-omp/server/provider/session.ts b/paseo-omp/server/provider/session.ts index 1c9dc8a9..dad377d4 100644 --- a/paseo-omp/server/provider/session.ts +++ b/paseo-omp/server/provider/session.ts @@ -482,6 +482,15 @@ export class OmpProviderSession implements OmpOpenedSession, OmpSubagentControls await target.runtime.steerSubagent(target.nativeId, message); } + /** Paseo publishes the model as an opaque id; only the session can map it back to OMP's model. */ + modelProvider(): string | null { + if (this.closed || this.runtimeDead) return null; + const model = this.configState.model + ? this.nativeModelsByPublicId.get(this.configState.model) + : undefined; + return model?.provider ?? null; + } + /** * 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/subagents.ts b/paseo-omp/server/subagents.ts index 5d15e1ad..8499b6b7 100644 --- a/paseo-omp/server/subagents.ts +++ b/paseo-omp/server/subagents.ts @@ -1,4 +1,5 @@ import type { RpcInput, RpcOutput } from "@getpaseo/plugin"; +import type { getOmpSessionModelProvider } from "../shared/quota"; import type { cancelOmpSubagent, steerOmpSubagent } from "../shared/subagents"; import { OmpRpcRequestRejectedError } from "./provider/omp-rpc-transport"; import { isOmpPublicError, OmpPublicError } from "./provider/security"; @@ -8,6 +9,8 @@ export interface OmpSubagentControls { /** Resolves `false` when the subagent is no longer running. */ cancelSubagent(handle: string): Promise; steerSubagent(handle: string, message: string): Promise; + /** The OMP provider of the session's current model, or null once the session has ended. */ + modelProvider(): string | null; } export class OmpSubagentNotRunningError extends OmpPublicError { @@ -95,3 +98,11 @@ export async function resolveSteerOmpSubagent( await withPublicFailure("steer", () => controls.steerSubagent(input.subagentId, input.message)); return { accepted: true }; } + +/** No live session (closed, history-only or another daemon's) answers null rather than failing. */ +export function resolveGetOmpSessionModelProvider( + input: RpcInput, + registry: OmpSubagentControlRegistry, +): RpcOutput { + return { provider: registry.get(input.agentId)?.modelProvider() ?? null }; +} diff --git a/paseo-omp/shared/quota.ts b/paseo-omp/shared/quota.ts index 23f6f5e0..b772a8c7 100644 --- a/paseo-omp/shared/quota.ts +++ b/paseo-omp/shared/quota.ts @@ -34,3 +34,13 @@ export const listOmpQuotas = defineRpc({ input: z.object({ store: OmpStoreSchema.optional() }), output: z.object({ quotas: z.array(OmpQuotaSchema) }), }); + +/** + * The OMP provider (such as `anthropic`) of the model an OMP Plugin agent's live session uses. + * Paseo only sees that model as an opaque id, so the provider is null without a live session. + */ +export const getOmpSessionModelProvider = defineRpc({ + name: "paseo-omp.session-model-provider", + input: z.object({ agentId: z.string().min(1).max(256) }), + output: z.object({ provider: z.string().nullable() }), +}); diff --git a/paseo-omp/tests/profile-pills.test.ts b/paseo-omp/tests/profile-pills.test.ts index 3ebec612..323a57ce 100644 --- a/paseo-omp/tests/profile-pills.test.ts +++ b/paseo-omp/tests/profile-pills.test.ts @@ -22,7 +22,7 @@ vi.mock("../client/generated-image", () => ({ OmpGeneratedImagesRow: () => null vi.mock("../client/ast-edit", () => ({ OmpAstEditCard: () => null })); import contribute from "../index.client"; -import { listOmpQuotas } from "../shared/quota"; +import { getOmpSessionModelProvider, listOmpQuotas } from "../shared/quota"; afterEach(() => { vi.useRealTimers(); @@ -179,3 +179,95 @@ test("owned agent directory updates reconcile new agent pills and cached quota r dispose(); } }); + +test("summarizes an OMP Plugin agent's quota by the provider its live session names", async () => { + vi.useFakeTimers(); + const agents = [ + { id: "live", provider: "omp-plugin", model: "omp:model:opaque", status: "idle" }, + { id: "ended", provider: "omp-plugin", model: "omp:model:opaque", status: "closed" }, + ]; + let onDirectoryUpdate = () => {}; + const buttons: Array<{ id: string; agentId: string; update: ReturnType }> = []; + const rpc = vi.fn(async (definition, input) => { + if (definition.name === "settings.composer-pills.read") { + return { status: "ready", revision: "r", values: { quota: true } }; + } + if (definition === getOmpSessionModelProvider) { + return { provider: input.agentId === "live" ? "openai-codex" : null }; + } + if (definition !== listOmpQuotas) return { processes: [] }; + const row = { label: "Window", windowLabel: null, status: "ok", resetsAt: null, recordedAt: 1 }; + return { + quotas: [ + { ...row, provider: "anthropic", usedFraction: 0.9 }, + { ...row, provider: "openai-codex", usedFraction: 0.3 }, + ], + }; + }); + const registration = () => () => {}; + const list = async (options?: { subscribe?: object }) => { + const result = { + entries: agents.map((agent) => ({ + agent: { ...agent, cwd: "/workspace", workspaceId: "workspace", archivedAt: null }, + })), + pageInfo: { hasMore: false }, + }; + if (!options?.subscribe) return result; + return { + ...result, + subscription: { + ready: Promise.resolve(result), + subscribe: (observer: { update: () => void }) => { + onDirectoryUpdate = observer.update; + return () => {}; + }, + release: async () => {}, + }, + }; + }; + const client = { + paseo: { agents: { list } }, + rpc, + addWorkspacePanel: registration, + addCommandCenterItem: registration, + addScreen: registration, + addSidebarHeaderItem: registration, + openScreen: vi.fn(), + addTimelineRenderer: registration, + addTimelineTransformer: registration, + addComposerPill: (options: { id: string; agentId: string }) => { + const button = { ...options, update: vi.fn(), remove: vi.fn() }; + buttons.push(button); + return button; + }, + } as unknown as PluginClientContext; + const dispose = contribute(client); + const quota = (agentId: string) => + buttons.findLast((button) => button.id === "quota" && button.agentId === agentId)?.update; + const asked = () => + rpc.mock.calls + .filter(([definition]) => definition === getOmpSessionModelProvider) + .map(([, input]) => input.agentId); + try { + await vi.advanceTimersByTimeAsync(300); + expect(quota("live")).toHaveBeenLastCalledWith( + expect.objectContaining({ label: "OpenAI · 30%" }), + ); + // A closed agent has no session to ask and keeps the all-provider summary. + expect(quota("ended")).toHaveBeenLastCalledWith( + expect.objectContaining({ label: "Quotas · 90%" }), + ); + expect(asked()).toEqual(["live"]); + + // The same model and status reuse the answer; a new model asks again. + onDirectoryUpdate(); + await vi.advanceTimersByTimeAsync(250); + expect(asked()).toEqual(["live"]); + agents[0].model = "omp:model:other"; + onDirectoryUpdate(); + await vi.advanceTimersByTimeAsync(250); + expect(asked()).toEqual(["live", "live"]); + } finally { + dispose(); + } +}); diff --git a/paseo-omp/tests/provider-subagent-control.test.ts b/paseo-omp/tests/provider-subagent-control.test.ts index a3189586..0b688908 100644 --- a/paseo-omp/tests/provider-subagent-control.test.ts +++ b/paseo-omp/tests/provider-subagent-control.test.ts @@ -7,6 +7,7 @@ import { OmpSubagentControlRegistry, type OmpSubagentControls, resolveCancelOmpSubagent, + resolveGetOmpSessionModelProvider, resolveSteerOmpSubagent, } from "../server/subagents"; import { OMP_SUBAGENT_STRIP_KIND, ompSubagentStripSchema } from "../shared/subagents"; @@ -451,11 +452,26 @@ describe("OMP subagent controls", () => { await connection.close(); }); + test("names the OMP provider behind an agent's opaque model only while its session runs", async () => { + const { connection, events, runtime, registry } = await createControlledHarness(); + await openSession(connection, events, "open-a", "session-a", { PASEO_AGENT_ID: "agent-a" }); + const provider = (agentId: string) => + resolveGetOmpSessionModelProvider({ agentId }, registry).provider; + + expect(provider("agent-a")).toBe("anthropic"); + expect(provider("agent-unknown")).toBeNull(); + sessionAt(runtime, 0).emit({ type: "process_exit", error: "OMP exited between turns" }); + await Promise.resolve(); + expect(provider("agent-a")).toBeNull(); + await connection.close(); + }); + test("lets a newer session replace an agent's controls without the older cleanup removing it", () => { const registry = new OmpSubagentControlRegistry(); const controls = (): OmpSubagentControls => ({ cancelSubagent: async () => false, steerSubagent: async () => {}, + modelProvider: () => null, }); const older = controls(); const newer = controls(); diff --git a/paseo-omp/tests/quota-popover-session-provider.test.tsx b/paseo-omp/tests/quota-popover-session-provider.test.tsx new file mode 100644 index 00000000..ebeaefc8 --- /dev/null +++ b/paseo-omp/tests/quota-popover-session-provider.test.tsx @@ -0,0 +1,127 @@ +// @vitest-environment happy-dom +import type { PluginButtonContentProps } from "@getpaseo/plugin/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, type ReactNode } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, test, vi } from "vitest"; +import { QuotaPopover } from "../client/quota-popover"; +import { getOmpSessionModelProvider, type OmpQuota } from "../shared/quota"; + +// The agent as Paseo reports it, and the provider its live session names (null once it ends). +const agent = vi.hoisted(() => ({ + status: "idle", + sessionProvider: null as string | null, + asked: 0, +})); + +vi.mock("@getpaseo/plugin/client", () => ({ + useAgent: () => ({ provider: "omp-plugin", model: "omp:model:opaque", status: agent.status }), + usePaseo: () => ({}), + useRpc: (definition: unknown) => async () => { + if (definition === getOmpSessionModelProvider) { + agent.asked += 1; + return { provider: agent.sessionProvider }; + } + return { quotas: [quota("anthropic"), quota("openai-codex")], accounts: [] }; + }, +})); +vi.mock("@getpaseo/plugin/client/ui", () => ({ Icon: () => null })); +vi.mock("react-native", () => ({ + View: (props: { children?: ReactNode }) =>
{props.children}
, + Text: (props: { children?: ReactNode }) => {props.children}, + Pressable: (props: { children?: ReactNode }) => , +})); + +function quota(provider: string): OmpQuota { + return { + provider, + accountKey: provider, + limitId: "weekly", + email: null, + accountId: null, + accountService: null, + accountHost: null, + plan: null, + organization: null, + label: "Usage", + windowLabel: "Weekly", + usedFraction: 0.5, + status: "ok", + resetsAt: null, + recordedAt: 1, + }; +} + +const props: PluginButtonContentProps = { + context: "agent", + workspaceId: "synthetic-workspace", + agentId: "synthetic-agent", + host: { id: "synthetic-host", label: "Test host" }, + layout: { compact: false, platform: "web" }, + close() {}, + theme: { + colors: { + surface0: "#111111", + surface1: "#222222", + surface2: "#333333", + border: "#444444", + foreground: "#eeeeee", + foregroundMuted: "#aaaaaa", + accent: "#008800", + accentForeground: "#ffffff", + statusSuccess: "#008800", + statusWarning: "#aa8800", + statusDanger: "#aa0000", + }, + }, +}; + +let container: HTMLDivElement; +let root: Root; +let client: QueryClient; + +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); +}); + +afterEach(async () => { + await act(() => root.unmount()); + client.clear(); + container.remove(); + vi.unstubAllGlobals(); +}); + +/** Re-renders the open popover, as Paseo does when the agent's status changes. */ +async function show(status: string, sessionProvider: string | null) { + agent.status = status; + agent.sessionProvider = sessionProvider; + await act(async () => { + root.render( + + + , + ); + }); +} + +const currentProvider = () => container.textContent?.includes("CURRENT PROVIDER") ?? false; + +test("asks the session for its provider again when it ends or resumes while the popover is open", async () => { + // Opened before the session runs: nothing to name yet. + await show("closed", null); + await vi.waitFor(() => expect(agent.asked).toBe(1)); + expect(currentProvider()).toBe(false); + + // The same model resumes: the popover asks again and marks the provider. + await show("idle", "anthropic"); + await vi.waitFor(() => expect(currentProvider()).toBe(true)); + expect(agent.asked).toBe(2); + + // The session ends: the earlier answer is not kept. + await show("closed", null); + await vi.waitFor(() => expect(currentProvider()).toBe(false)); +}); From 4bee23f4ea79c3c9de2b6ecbcf2229a36e1fdc8b Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 22:46:37 +0900 Subject: [PATCH 6/9] feat(paseo-omp): show and switch the session's OMP account - The quota popover lists the session's OMP logins (get_logout_accounts, or the stored session pin for a bundled omp agent), marks the one in use IN USE, a provider's only stored credential ONLY LOGIN, and offers Switch, which sends `/session pin OAuth credential #`. - Logins link to recorded usage server-side by OMP's identity rule within the agent's own store. - The composer pill shows the in-use account's usage; dividers separate accounts and redundant notices are gone. --- paseo-omp/README.md | 4 +- paseo-omp/client/quota-popover.tsx | 299 +++++++--- paseo-omp/client/quota-state.ts | 73 ++- paseo-omp/index.client.tsx | 53 +- paseo-omp/index.server.ts | 11 +- paseo-omp/server/provider/omp-rpc-protocol.ts | 17 +- paseo-omp/server/provider/omp-rpc.ts | 11 + paseo-omp/server/provider/session.ts | 7 + paseo-omp/server/quota.ts | 273 +++++++++- paseo-omp/server/subagents.ts | 5 +- paseo-omp/shared/quota.ts | 29 + paseo-omp/tests/helpers/provider-harness.ts | 7 + paseo-omp/tests/profile-pills.test.ts | 4 +- .../tests/provider-subagent-control.test.ts | 1 + paseo-omp/tests/quota-popover.test.tsx | 116 +++- paseo-omp/tests/quota-state.test.ts | 511 +++++++++++++++++- 16 files changed, 1284 insertions(+), 137 deletions(-) diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 5a3652c4..79333eb3 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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. 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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**. +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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index 5f5e96d0..0c6f1ae1 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -1,26 +1,35 @@ -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 { getOmpSessionModelProvider, listOmpQuotas } from "../shared/quota"; +import { + getOmpSessionModelProvider, + listOmpQuotas, + listOmpSessionAccounts, + type OmpSessionAccount, +} from "../shared/quota"; import { ompStoreKey } from "./omp-store-state"; import { needsSessionModelProvider, 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, @@ -48,15 +57,42 @@ export function QuotaPopover(props: PluginButtonContentProps) { sessionModelProvider.data?.provider ?? 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); - function severityColor(severity: ReturnType): string { + 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: QuotaSeverity): string { if (severity === "danger") return theme.colors.statusDanger; if (severity === "warning") return theme.colors.statusWarning; if (severity === "ok") return theme.colors.statusSuccess; @@ -108,14 +144,22 @@ export function QuotaPopover(props: PluginButtonContentProps) { overflow: "hidden" as const, }, detail: { color: theme.colors.foregroundMuted, fontSize: 11 }, - account: { gap: 6, paddingTop: 4 }, + // 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: { - color: theme.colors.foregroundMuted, + 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 }, @@ -130,6 +174,23 @@ export function QuotaPopover(props: PluginButtonContentProps) { 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], ); @@ -139,18 +200,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} + + ))} + + ); + } + + 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"} + + + ); + } - if (groups.length === 0) { - return No provider quota data available.; + 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. @@ -160,8 +346,14 @@ 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 ( @@ -173,76 +365,7 @@ export function QuotaPopover(props: PluginButtonContentProps) { {quotaProviderLabel(group.provider)} {current ? "CURRENT PROVIDER" : "RECORDED"} - {group.accounts.map((account) => ( - - {account.label ? ( - - - {account.label} - - {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 ? ( - - {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 5d4115ca..aeb7afc4 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -1,5 +1,5 @@ import { accountTags } from "../shared/account-tags"; -import type { OmpQuota } from "../shared/quota"; +import type { OmpQuota, OmpSessionAccount } from "../shared/quota"; import { isOmpProvider } from "./omp-store-state"; const PROVIDER_LABELS: Record = { @@ -71,31 +71,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)); @@ -155,6 +182,30 @@ 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, diff --git a/paseo-omp/index.client.tsx b/paseo-omp/index.client.tsx index 2baab67d..c7e02f23 100644 --- a/paseo-omp/index.client.tsx +++ b/paseo-omp/index.client.tsx @@ -62,7 +62,12 @@ 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 { getOmpSessionModelProvider, listOmpQuotas } from "./shared/quota"; +import { + getOmpSessionModelProvider, + 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"; @@ -525,18 +530,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. } @@ -547,6 +560,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 dd618f25..4b776318 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, @@ -117,7 +121,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 { getOmpSessionModelProvider, listOmpQuotas } from "./shared/quota"; +import { getOmpSessionModelProvider, listOmpQuotas, listOmpSessionAccounts } from "./shared/quota"; import { cancelOmpSubagent, steerOmpSubagent } from "./shared/subagents"; import { getOmpSupportReport } from "./shared/support-diagnostics"; @@ -163,6 +167,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/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 dad377d4..3ee6ea8c 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, @@ -491,6 +492,12 @@ export class OmpProviderSession implements OmpOpenedSession, OmpSubagentControls return model?.provider ?? null; } + /** 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 8a5bfb83..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(), @@ -171,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 8499b6b7..51f2dacf 100644 --- a/paseo-omp/server/subagents.ts +++ b/paseo-omp/server/subagents.ts @@ -1,16 +1,19 @@ import type { RpcInput, RpcOutput } from "@getpaseo/plugin"; import type { getOmpSessionModelProvider } from "../shared/quota"; 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 OMP provider of the session's current model, or null once the session has ended. */ modelProvider(): string | null; + /** 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/quota.ts b/paseo-omp/shared/quota.ts index b772a8c7..68430074 100644 --- a/paseo-omp/shared/quota.ts +++ b/paseo-omp/shared/quota.ts @@ -44,3 +44,32 @@ export const getOmpSessionModelProvider = defineRpc({ input: z.object({ agentId: z.string().min(1).max(256) }), output: z.object({ provider: z.string().nullable() }), }); + +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/profile-pills.test.ts b/paseo-omp/tests/profile-pills.test.ts index 323a57ce..628f34f3 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( @@ -251,7 +251,7 @@ test("summarizes an OMP Plugin agent's quota by the provider its live session na try { await vi.advanceTimersByTimeAsync(300); expect(quota("live")).toHaveBeenLastCalledWith( - expect.objectContaining({ label: "OpenAI · 30%" }), + expect.objectContaining({ label: "30%", title: expect.stringMatching(/^OpenAI · /u) }), ); // A closed agent has no session to ask and keeps the all-provider summary. expect(quota("ended")).toHaveBeenLastCalledWith( diff --git a/paseo-omp/tests/provider-subagent-control.test.ts b/paseo-omp/tests/provider-subagent-control.test.ts index 0b688908..a9649ac6 100644 --- a/paseo-omp/tests/provider-subagent-control.test.ts +++ b/paseo-omp/tests/provider-subagent-control.test.ts @@ -472,6 +472,7 @@ describe("OMP subagent controls", () => { cancelSubagent: async () => false, steerSubagent: async () => {}, modelProvider: () => null, + 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 6a0efff2..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: { @@ -31,6 +52,15 @@ vi.mock("react-native", () => ({ ), Text: (props: { children?: ReactNode }) => {props.children}, + Pressable: (props: { + children?: ReactNode; + accessibilityLabel?: string; + onPress?: () => void; + }) => ( + + ), })); const props: PluginButtonContentProps = { @@ -83,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); @@ -164,4 +196,80 @@ describe("quota popover reconciliation", () => { "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 04d48b8e..f1efdb16 100644 --- a/paseo-omp/tests/quota-state.test.ts +++ b/paseo-omp/tests/quota-state.test.ts @@ -1,8 +1,9 @@ -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 { quotaDetailLabel, quotaProviderFromSession, @@ -10,11 +11,19 @@ import { 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[] = []; @@ -70,12 +79,36 @@ 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", () => { @@ -743,6 +776,465 @@ 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 () => [], + modelProvider: () => null, + ...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"); @@ -752,12 +1244,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); }); }); From a2c9427e2e64879bc2acfd11fdfc22dc710ef998 Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 22:50:45 +0900 Subject: [PATCH 7/9] fix(paseo-omp): keep Switch from interrupting a turn and tighten session account review gaps - Switch is disabled while the agent is running or initializing: Paseo interrupts a running turn on send, and OMP does not pin while it streams. Its accessible name uses the login label and its hit area grows by 8px. - Two logins sharing a usage account keep IN USE on the one in use. - The pill falls back to the provider peak when the account in use has no usage value, and its tooltip then says all accounts. - Tests cover Paseo's agent lookup through the registered RPC; a comment names the two parts of OMP's identity rules the matcher leaves out. - README lists what reaches the client and the limit of the Copilot single-login link. --- paseo-omp/README.md | 2 +- paseo-omp/client/quota-popover.tsx | 20 +++--- paseo-omp/client/quota-state.ts | 13 ++-- paseo-omp/server/quota.ts | 5 ++ paseo-omp/tests/quota-popover.test.tsx | 55 +++++++++++++++- paseo-omp/tests/quota-state.test.ts | 91 +++++++++++++++++++++++++- 6 files changed, 166 insertions(+), 20 deletions(-) diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 79333eb3..245143ab 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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, 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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**. +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. The raw account key stays on the server, and the client receives a SHA-256 hash of it. For the session's logins the client also receives OMP's credential id, OMP's login label (the email or, without one, the raw account id, plus the organization name), whether the login is in use or the provider's only stored credential, and the hashes of the usage accounts it links to. 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. **Switch** is disabled while the agent runs a turn, since sending then would interrupt it and OMP does not pin while it streams. 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, so after a Copilot login is replaced, the old login's remaining usage can show as the new login's until the new login records usage of its own. When two logins link to the same usage account, the one in use keeps **IN USE**. 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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 value, 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). diff --git a/paseo-omp/client/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index 0c6f1ae1..fa899b9e 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -219,17 +219,17 @@ export function QuotaPopover(props: PluginButtonContentProps) { ); } - function renderSwitch( - account: QuotaSessionAccountGroup, - login: OmpSessionAccount, - inHeading: boolean, - ) { - const busy = switching !== null; + function renderSwitch(login: OmpSessionAccount, inHeading: boolean) { + // Paseo interrupts a running turn on send, and OMP refuses to pin while it streams. + const turnActive = session?.status === "running" || session?.status === "initializing"; + const busy = switching !== null || turnActive; return ( void switchTo(login)} style={({ pressed }) => [ styles.switch, @@ -281,9 +281,7 @@ export function QuotaPopover(props: PluginButtonContentProps) { // 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} + {login && !account.inUse && !login.onlyLogin ? renderSwitch(login, true) : null} ) : account.tags.length > 0 ? ( renderTags(account.tags, styles.tags) @@ -321,7 +319,7 @@ export function QuotaPopover(props: PluginButtonContentProps) { ) : !account.label && login?.onlyLogin ? ( ONLY LOGIN ) : login && !account.inUse && !account.label ? ( - renderSwitch(account, login, false) + renderSwitch(login, false) ) : null}
); diff --git a/paseo-omp/client/quota-state.ts b/paseo-omp/client/quota-state.ts index aeb7afc4..5b7b380d 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -72,8 +72,8 @@ 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. + * The quotas the pill summarizes: the session's account in use when OMP named one and it has a + * recorded usage value, otherwise every account of the provider. */ export function quotasInUse( quotas: readonly OmpQuota[], @@ -84,7 +84,7 @@ export function quotasInUse( 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; + return own.some((quota) => quota.usedFraction !== null) ? own : matching; } /** @@ -101,7 +101,8 @@ export function quotaSummaryForProvider( const own = provider !== null && inUse !== null && - matching.some((quota) => inUse.quotaAccountKeys.includes(quota.accountKey)); + matching.length > 0 && + matching.every((quota) => inUse.quotaAccountKeys.includes(quota.accountKey)); const used = matching.flatMap((quota) => quota.usedFraction === null ? [] : [quota.usedFraction], ); @@ -195,7 +196,9 @@ export function quotaSessionAccounts( logins: readonly OmpSessionAccount[], ): QuotaSessionAccountGroup[] { const linked = accounts.map((account) => { - const login = logins.find((entry) => entry.quotaAccountKeys.includes(account.accountKey)); + const owns = (entry: OmpSessionAccount) => entry.quotaAccountKeys.includes(account.accountKey); + // Logins can share a usage account; the one in use keeps its mark. + const login = logins.find((entry) => entry.active && owns(entry)) ?? logins.find(owns); return { ...account, login: login ?? null, inUse: login?.active === true }; }); return [...linked.filter((a) => a.inUse), ...linked.filter((a) => !a.inUse)]; diff --git a/paseo-omp/server/quota.ts b/paseo-omp/server/quota.ts index d9375d5a..b135ea0f 100644 --- a/paseo-omp/server/quota.ts +++ b/paseo-omp/server/quota.ts @@ -211,6 +211,11 @@ function usageKeyIdentity(accountKey: string): LoginIdentity { * 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. + * + * Two parts of OMP's rules are left out. `projectId` is not compared: OMP's usage keys carry no + * project, and Antigravity logins share one project. An account id equal to the organization id + * (a ChatGPT workspace id every member shares, which `isSameOAuthAccount` skips) is not excluded: + * a usage key always carries the email where OMP recorded one, so the email decides first. */ function sameLogin(login: LoginIdentity, usage: LoginIdentity): boolean { if (login.orgId !== null || usage.orgId !== null) { diff --git a/paseo-omp/tests/quota-popover.test.tsx b/paseo-omp/tests/quota-popover.test.tsx index 9d72105e..863d9fe7 100644 --- a/paseo-omp/tests/quota-popover.test.tsx +++ b/paseo-omp/tests/quota-popover.test.tsx @@ -10,10 +10,11 @@ const recorded = vi.hoisted(() => ({ quotas: [] as OmpQuota[], logins: [] as OmpSessionAccount[], sent: [] as Array<{ agentId: string; text: string }>, + status: "idle" as string, })); vi.mock("@getpaseo/plugin/client", () => ({ - useAgent: () => ({ provider: "omp", model: "anthropic/example", status: "idle" }), + useAgent: () => ({ provider: "omp", model: "anthropic/example", status: recorded.status }), useRpc: () => vi.fn(), usePaseo: () => ({ agents: { @@ -55,9 +56,15 @@ vi.mock("react-native", () => ({ Pressable: (props: { children?: ReactNode; accessibilityLabel?: string; + disabled?: boolean; onPress?: () => void; }) => ( - ), @@ -115,6 +122,7 @@ beforeEach(() => { recorded.quotas = []; recorded.logins = []; recorded.sent = []; + recorded.status = "idle"; container = document.createElement("div"); document.body.append(container); root = createRoot(container); @@ -233,6 +241,49 @@ describe("quota popover reconciliation", () => { ]); }); + test("disables Switch while the agent runs a turn, so it cannot interrupt it", async () => { + recorded.logins = [ + { + credentialId: 3, + label: "a@x.invalid", + active: false, + onlyLogin: false, + quotaAccountKeys: ["a"], + }, + { + credentialId: 5, + label: "b@x.invalid", + active: true, + onlyLogin: false, + quotaAccountKeys: ["b"], + }, + ]; + const rows = [ + { ...quota("a", "weekly", 0.9), email: "a@x.invalid" }, + { ...quota("b", "weekly", 0.2), email: "b@x.invalid" }, + ]; + const button = () => + container.querySelector( + '[aria-label="Use a@x.invalid for this session"]', + ) as HTMLButtonElement; + + for (const status of ["running", "initializing"]) { + recorded.status = status; + await render(rows); + expect(button().disabled).toBe(true); + await act(async () => button().click()); + expect(recorded.sent).toEqual([]); + } + + recorded.status = "idle"; + await render(rows); + expect(button().disabled).toBe(false); + 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 = [ { diff --git a/paseo-omp/tests/quota-state.test.ts b/paseo-omp/tests/quota-state.test.ts index f1efdb16..2cd2ca60 100644 --- a/paseo-omp/tests/quota-state.test.ts +++ b/paseo-omp/tests/quota-state.test.ts @@ -3,6 +3,7 @@ import { mkdir, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; import { afterEach, describe, expect, test, vi } from "vitest"; import { quotaDetailLabel, @@ -17,6 +18,7 @@ import { quotasForProvider, sessionPinCommand, } from "../client/quota-state"; +import contribute from "../index.server"; import { OmpRpcRequestRejectedError } from "../server/provider/omp-rpc-transport"; import { listOmpQuotasFrom, @@ -24,7 +26,7 @@ import { resolveListOmpSessionAccounts, } from "../server/quota"; import { OmpSubagentControlRegistry, type OmpSubagentControls } from "../server/subagents"; -import type { OmpQuota } from "../shared/quota"; +import { listOmpSessionAccounts, type OmpQuota } from "../shared/quota"; const quotaRoots: string[] = []; @@ -109,6 +111,39 @@ describe("session-specific quota selection", () => { expect( quotaSummaryForProvider(rows, "anthropic", false, { ...working, quotaAccountKeys: [] }).label, ).toBe("100%"); + // A linked account whose rows hold no usage value does not hide the provider's peak. + const unread: OmpQuota[] = [ + ...rows, + { ...quotas[0], accountKey: "unread", usedFraction: null }, + ]; + expect( + quotaSummaryForProvider(unread, "anthropic", false, { + ...working, + quotaAccountKeys: ["unread"], + }), + ).toEqual({ + visible: true, + label: "100%", + title: "Anthropic · all accounts · 100% (last recorded usage, not live)", + }); + expect( + quotaSeverityForProvider(unread, "anthropic", false, { + ...working, + quotaAccountKeys: ["unread"], + }), + ).toBe("danger"); + }); + + test("keeps IN USE on the login in use when two logins share a usage account", () => { + const account = quotaProviderGroups([{ ...quotas[0], accountKey: "shared" }], "anthropic")[0] + .accounts; + const login = { label: "me@example.invalid", onlyLogin: false, quotaAccountKeys: ["shared"] }; + const [linked] = quotaSessionAccounts(account, [ + { ...login, credentialId: 3, active: false }, + { ...login, credentialId: 5, active: true }, + ]); + expect(linked.inUse).toBe(true); + expect(linked.login?.credentialId).toBe(5); }); test("maps each provider to a distinct icon and severity bucket", () => { @@ -1005,6 +1040,60 @@ describe("session account", () => { expect((await list(null)).accounts).toEqual([]); }); + test("serves the registered RPC from Paseo's own record of the agent", async () => { + await codexTeam(join(await home(), ".omp", "agent")); + const handlers = new Map unknown>(); + const cleanup = contribute({ + handle(contract: { name: string }, handler: (input: unknown, context: unknown) => unknown) { + handlers.set(contract.name, handler); + }, + on: () => () => {}, + before: () => () => {}, + registerSettings: () => ({ subscribe: () => () => {} }), + registerProvider: () => {}, + } as unknown as PluginServerContext); + const records: Record = { + bundled: { + agent: { provider: "omp", persistence: { provider: "omp", sessionId: "bundled-session" } }, + }, + // Another provider's session id is not an OMP session. + foreign: { + agent: { + provider: "omp", + persistence: { provider: "codex", sessionId: "bundled-session" }, + }, + }, + gone: null, + }; + const paseo = { + agents: { + ref: (agentId: string) => ({ + refresh: async () => { + if (agentId === "broken") throw new Error("offline"); + return records[agentId]; + }, + }), + }, + }; + const list = async (agentId: string) => + listOmpSessionAccounts.output.parse( + await handlers.get(listOmpSessionAccounts.name)?.( + { agentId, provider: "openai-codex" }, + { paseo }, + ), + ).accounts; + try { + expect((await list("bundled")).filter((login) => login.active)).toEqual([ + expect.objectContaining({ credentialId: 2 }), + ]); + for (const agentId of ["foreign", "gone", "broken"]) { + expect(await list(agentId)).toEqual([]); + } + } finally { + cleanup(); + } + }); + 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"; From 0060ea5dee113d9c50e4de07971aaff0fe5e6254 Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 23:16:59 +0900 Subject: [PATCH 8/9] fix(paseo-omp): link logins to usage only by identity and still name an unlinked login in use - Drop the rule that linked a provider's single identity-less login to its single usage account: one login and one usage key do not prove ownership, so a replaced Copilot login no longer inherits its predecessor's usage. - A login OMP names in use, or the provider's only one, that no usage row matches is named at the top of its provider with IN USE or ONLY LOGIN and no limits, for every provider alike. - Switch's hit slop brings its touch target to 44px; test fixtures drop token- and host-shaped values. --- paseo-omp/README.md | 2 +- paseo-omp/client/quota-popover.tsx | 36 ++++++++++++++++++++++++-- paseo-omp/client/quota-state.ts | 15 +++++++++++ paseo-omp/server/quota.ts | 22 +++++----------- paseo-omp/tests/quota-popover.test.tsx | 29 +++++++++++++++++++++ paseo-omp/tests/quota-state.test.ts | 10 ++++--- 6 files changed, 92 insertions(+), 22 deletions(-) diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 245143ab..19f96a71 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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, 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. The raw account key stays on the server, and the client receives a SHA-256 hash of it. For the session's logins the client also receives OMP's credential id, OMP's login label (the email or, without one, the raw account id, plus the organization name), whether the login is in use or the provider's only stored credential, and the hashes of the usage accounts it links to. 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. **Switch** is disabled while the agent runs a turn, since sending then would interrupt it and OMP does not pin while it streams. 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, so after a Copilot login is replaced, the old login's remaining usage can show as the new login's until the new login records usage of its own. When two logins link to the same usage account, the one in use keeps **IN USE**. 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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 value, 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**. +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. The raw account key stays on the server, and the client receives a SHA-256 hash of it. For the session's logins the client also receives OMP's credential id, OMP's login label (the email or, without one, the raw account id, plus the organization name), whether the login is in use or the provider's only stored credential, and the hashes of the usage accounts it links to. 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. **Switch** is disabled while the agent runs a turn, since sending then would interrupt it and OMP does not pin while it streams. 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 links to recorded usage only by OMP's identity rule: the organization must match, including being absent on both sides, then the email decides, else the account id. A login without any identity, such as a Copilot login, links to no usage, since one stored login and one usage account do not prove the usage is that login's. A login in use, or the provider's only one, that no usage row matches is still named at the top of its provider with **IN USE** or **ONLY LOGIN** and no limits; any other login without matching usage has no row, so it cannot be switched to from the popover. When two logins link to the same usage account, the one in use keeps **IN USE**. 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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 value, 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). diff --git a/paseo-omp/client/quota-popover.tsx b/paseo-omp/client/quota-popover.tsx index fa899b9e..06f3b855 100644 --- a/paseo-omp/client/quota-popover.tsx +++ b/paseo-omp/client/quota-popover.tsx @@ -24,6 +24,7 @@ import { quotaSessionAccounts, quotaSeverityFromFraction, sessionPinCommand, + unlinkedSessionLogins, } from "./quota-state"; const QUOTA_POLL_MS = 30_000; @@ -206,6 +207,32 @@ export function QuotaPopover(props: PluginButtonContentProps) { groups.find((group) => group.provider === currentProvider)?.accounts ?? [], logins, ); + const unlinked = unlinkedSessionLogins(currentAccounts, logins); + + // A login OMP names in use (or the only one) still shows when no usage row is its own. + function renderUnlinked(login: OmpSessionAccount, index: number) { + return ( + + + + {login.label} + + {login.active ? ( + IN USE + ) : ( + ONLY LOGIN + )} + + No recorded usage matches this login. + + ); + } function renderTags(tags: readonly string[], style: object) { return ( @@ -229,7 +256,8 @@ export function QuotaPopover(props: PluginButtonContentProps) { accessibilityLabel={`Use ${login.label} for this session`} accessibilityState={{ disabled: busy }} disabled={busy} - hitSlop={8} + // About 22px tall; the slop brings the touch target to 44px without growing the pill. + hitSlop={{ top: 11, bottom: 11, left: 8, right: 8 }} onPress={() => void switchTo(login)} style={({ pressed }) => [ styles.switch, @@ -344,6 +372,7 @@ export function QuotaPopover(props: PluginButtonContentProps) { {`No recorded quota yet for ${quotaProviderLabel(currentProvider)} (this session's provider).`}
) : null} + {currentProvider && !hasCurrent ? unlinked.map(renderUnlinked) : null} {groups.length === 0 ? ( No provider quota data available. ) : null} @@ -363,7 +392,10 @@ export function QuotaPopover(props: PluginButtonContentProps) { {quotaProviderLabel(group.provider)} {current ? "CURRENT PROVIDER" : "RECORDED"} - {accounts.map(renderAccount)} + {current ? unlinked.map(renderUnlinked) : null} + {accounts.map((account, index) => + renderAccount(account, index + (current ? unlinked.length : 0)), + )} ); })} diff --git a/paseo-omp/client/quota-state.ts b/paseo-omp/client/quota-state.ts index 5b7b380d..2d2c6326 100644 --- a/paseo-omp/client/quota-state.ts +++ b/paseo-omp/client/quota-state.ts @@ -204,6 +204,21 @@ export function quotaSessionAccounts( return [...linked.filter((a) => a.inUse), ...linked.filter((a) => !a.inUse)]; } +/** + * Logins OMP names in use, or the provider's only one, that head no usage account: their usage is + * unrecorded or carries no identity to match. They are still shown, without limits. + */ +export function unlinkedSessionLogins( + accounts: readonly QuotaSessionAccountGroup[], + logins: readonly OmpSessionAccount[], +): OmpSessionAccount[] { + return logins.filter( + (login) => + (login.active || login.onlyLogin) && + !accounts.some((account) => account.login?.credentialId === login.credentialId), + ); +} + /** 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}`; diff --git a/paseo-omp/server/quota.ts b/paseo-omp/server/quota.ts index b135ea0f..b5190524 100644 --- a/paseo-omp/server/quota.ts +++ b/paseo-omp/server/quota.ts @@ -233,9 +233,8 @@ function hasIdentity(identity: LoginIdentity): boolean { /** * 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. + * links only to usage whose identity matches its own, so a login without one (Copilot stores none) + * links to nothing: one stored login and one usage account do not prove the usage is that login's. */ export function quotaAccountKeysFor( path: string, @@ -267,18 +266,11 @@ export function quotaAccountKeysFor( 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])]); - } + if (!hasIdentity(login)) continue; + matched.set( + row.id, + usageKeys.filter((key) => sameLogin(login, usageKeyIdentity(key))).map(hashAccountKey), + ); } } finally { database.close(); diff --git a/paseo-omp/tests/quota-popover.test.tsx b/paseo-omp/tests/quota-popover.test.tsx index 863d9fe7..84bb5256 100644 --- a/paseo-omp/tests/quota-popover.test.tsx +++ b/paseo-omp/tests/quota-popover.test.tsx @@ -323,4 +323,33 @@ describe("quota popover reconciliation", () => { expect(text("IN USE")).toBeTruthy(); expect(container.textContent).not.toContain("ONLY LOGIN"); }); + + test("still names a login OMP uses when no recorded usage is its own", async () => { + const login = { + credentialId: 8, + label: "OAuth credential #8", + active: true, + onlyLogin: false, + quotaAccountKeys: [], + }; + recorded.logins = [login]; + await render([{ ...quota("a", "weekly", 0.3), email: "a@x.invalid" }]); + + const named = heading("OAuth credential #8"); + expect(named.contains(text("IN USE"))).toBe(true); + expect(text("No recorded usage matches this login.")).toBeTruthy(); + // The usage row it cannot claim stays unmarked, with nothing to switch to. + expect(heading("a@x.invalid").textContent).not.toContain("IN USE"); + expect(container.querySelector('[aria-label$="for this session"]')).toBeNull(); + + // The only stored login is named the same way, also when the provider has no usage at all. + recorded.logins = [{ ...login, active: false, onlyLogin: true }]; + await render([]); + expect(heading("OAuth credential #8").contains(text("ONLY LOGIN"))).toBe(true); + + // Another unlinked login is neither in use nor the only one, so it adds nothing. + recorded.logins = [{ ...login, active: false }]; + await render([]); + expect(container.textContent).not.toContain("OAuth credential #8"); + }); }); diff --git a/paseo-omp/tests/quota-state.test.ts b/paseo-omp/tests/quota-state.test.ts index 2cd2ca60..55899b82 100644 --- a/paseo-omp/tests/quota-state.test.ts +++ b/paseo-omp/tests/quota-state.test.ts @@ -874,7 +874,7 @@ describe("session account", () => { id, seed.provider, apiKey ? "api_key" : "oauth", - JSON.stringify({ ...identity, access: "secret-token" }), + JSON.stringify({ ...identity, access: "unread-placeholder" }), disabled ? "user" : null, ); } @@ -1157,9 +1157,10 @@ describe("session account", () => { ]); }); - test("flags a provider's only login without claiming it is in use, and links its sole identity-less usage", async () => { + test("flags a provider's only login without claiming it is in use, and links no usage it cannot prove is its own", async () => { const root = await home(); - const copilot = "oauth|enterprise:ghe.example.invalid|secret:abc123"; + // Copilot's shape: no identity on the login, only an enterprise host and fingerprint in the key. + const copilot = "oauth|enterprise:host-1|secret:fingerprint-1"; // 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", @@ -1179,7 +1180,8 @@ describe("session account", () => { label: "OAuth credential #8", active: false, onlyLogin: true, - quotaAccountKeys: [sha(copilot)], + // One login and one usage account do not prove the usage is this login's. + quotaAccountKeys: [], }, ]); }); From 837aa018a9d5c5a1f572df8920929abf5787440d Mon Sep 17 00:00:00 2001 From: JangMinSeok Date: Mon, 16 Nov 2026 23:19:18 +0900 Subject: [PATCH 9/9] docs(paseo-omp): note that a live session never marks an identity-less login in use - OMP's get_logout_accounts decides `active` by identity, so a pinned Copilot login reads as not in use in a live OMP Plugin session; the popover keeps OMP's answer. --- paseo-omp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/paseo-omp/README.md b/paseo-omp/README.md index 19f96a71..6c1cc908 100644 --- a/paseo-omp/README.md +++ b/paseo-omp/README.md @@ -35,7 +35,7 @@ Open the **OMP** sidebar to review the provider-profile contract, choose which c 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, 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. The raw account key stays on the server, and the client receives a SHA-256 hash of it. For the session's logins the client also receives OMP's credential id, OMP's login label (the email or, without one, the raw account id, plus the organization name), whether the login is in use or the provider's only stored credential, and the hashes of the usage accounts it links to. 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. **Switch** is disabled while the agent runs a turn, since sending then would interrupt it and OMP does not pin while it streams. 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 links to recorded usage only by OMP's identity rule: the organization must match, including being absent on both sides, then the email decides, else the account id. A login without any identity, such as a Copilot login, links to no usage, since one stored login and one usage account do not prove the usage is that login's. A login in use, or the provider's only one, that no usage row matches is still named at the top of its provider with **IN USE** or **ONLY LOGIN** and no limits; any other login without matching usage has no row, so it cannot be switched to from the popover. When two logins link to the same usage account, the one in use keeps **IN USE**. 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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 value, 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**. +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. The raw account key stays on the server, and the client receives a SHA-256 hash of it. For the session's logins the client also receives OMP's credential id, OMP's login label (the email or, without one, the raw account id, plus the organization name), whether the login is in use or the provider's only stored credential, and the hashes of the usage accounts it links to. 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). OMP's runtime answer marks a login in use only by its identity, so a login without one, such as a Copilot login, never shows **IN USE** in a live OMP Plugin session even when the session is pinned to it. 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. **Switch** is disabled while the agent runs a turn, since sending then would interrupt it and OMP does not pin while it streams. 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 links to recorded usage only by OMP's identity rule: the organization must match, including being absent on both sides, then the email decides, else the account id. A login without any identity, such as a Copilot login, links to no usage, since one stored login and one usage account do not prove the usage is that login's. A login in use, or the provider's only one, that no usage row matches is still named at the top of its provider with **IN USE** or **ONLY LOGIN** and no limits; any other login without matching usage has no row, so it cannot be switched to from the popover. When two logins link to the same usage account, the one in use keeps **IN USE**. 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. Paseo sees an OMP Plugin agent's model only as an opaque id, so the pill and popover ask the agent's live OMP session which provider that model belongs to; a closed OMP Plugin agent shows every provider until its session runs again. 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 value, 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).