Files
paseo/plugins/muse-provider/server/usage.ts
T
Mohamed Boudra 52377f595a Enable sidebar usage summary by default and move source toggles to a dedicated Sources list (#10491)
* feat(usage): enable sidebar usage summary by default and add dedicated Sources list

Show the sidebar Usage summary by default instead of requiring opt-in in
Appearance settings, while honoring explicit off preferences and continuing
to hide the row when no enabled source has pinned windows.

Let usage sources declare optional provider hints (`providers` on the
registration and `provider` on discovered accounts) so the daemon can mark
reports `defaultEnabled: false` when their hinted providers are neither
enabled nor installed, keeping usage sources decoupled from agent providers
while avoiding clutter from leftover credentials.

Move per-source show/hide controls out of individual card headers into a
dedicated `Sources` submenu inside Usage Settings (with tri-state
`cardVisibility` preferences migrating legacy `cardsOff`) so disabled
sources stay out of the main card list.

* fix(usage): resolve provider hints per report, refresh on forceRefresh, and clarify inactive copy

Resolve each usage report's provider activity hint in parallel with its
fetch and enforce a real timeout deadline in `isProviderActiveForUsage` so
a slow provider probe never holds back unrelated reports or hangs past the
deadline on non-abortable plugin RPCs.

Give the availability hint a 5-minute freshness TTL and re-probe when
`forceRefresh` is requested, retaining the fresher probe result across
subsequent normal reads until a newer snapshot or TTL expiry supersedes it.

Rename the default-off Sources sublabel from "Provider not installed" to
"Provider inactive" across all locales so it accurately covers both
disabled and unavailable providers.

* fix(usage): share provider availability reading across snapshot publishes and usage probes

Record both `ready` and `unavailable` global snapshot publications into
`usageActivityCache` so `isProviderActiveForUsage` reads one timestamped
availability cache instead of relying on `fetchedAt` (which unavailable
snapshot entries do not carry).

* fix(app): add MenuCheckboxItem so Usage Sources toggles expose checked state to screen readers

Introduce `MenuCheckboxItem` / `DropdownMenuCheckboxItem` backed by
`accessibilityRole="checkbox"` so toggleable menu rows expose their checked
state in Chromium's accessibility tree and native screen readers while
leaving existing `MenuItem` roles unchanged.

* fix(app): keep compact menu sheet rows in Tab order and activate on Space

Use `tabIndex={0}` for `MenuRow` in `sheet` presentation (leaving
popover roving arrow-key navigation at `tabIndex={-1}`) and handle Space
in web sheet rows since React Native Web only activates Space for
`role="button"`, not `menuitem` or `checkbox`.

* test(usage): include provider hint in claude-usage-source keychain and stores assertions
2026-11-22 16:43:11 +07:00

132 lines
4.6 KiB
TypeScript

import { homedir } from "node:os";
import path from "node:path";
import { z } from "zod";
import type { UsageSourceRegistration } from "@getpaseo/plugin/server";
import type { ProviderLaunch } from "@getpaseo/plugin/server/provider";
import {
hashAccountKey,
unavailable,
windowFromUsedPct,
windowFromReportedDuration,
toneFromUsedPct,
} from "@getpaseo/plugin/server/usage";
import { MspConnection } from "./connection.js";
import { usageSchema } from "./wire.js";
const inputSchema = z.object({ account: z.string() }).strict();
type Observation = z.infer<typeof usageSchema>;
function accountKey(env: ProviderLaunch["env"]): string {
// MSP 1.4.1 has no stable account ID; swapping accounts in one config directory shares a report ID.
const configHome = env.XDG_CONFIG_HOME ?? path.join(env.HOME ?? homedir(), ".config");
return hashAccountKey(path.resolve(configHome, "muse"));
}
export class Usage {
private readonly launches = new Map<string, ProviderLaunch>();
private readonly sessions = new Map<
string,
{ account: string; read: () => Promise<Observation> }
>();
remember(launch: ProviderLaunch): { account: string } {
const key = accountKey(launch.env);
this.launches.set(key, launch);
return { account: key };
}
attach(id: string, launch: ProviderLaunch, read: () => Promise<Observation>): void {
this.sessions.set(id, { ...this.remember(launch), read });
}
detach(id: string): void {
this.sessions.delete(id);
}
private async read(account: string, launch: ProviderLaunch): Promise<Observation> {
const readers = [...this.sessions.values()].filter((session) => session.account === account);
if (readers.length > 0) {
const observations = await Promise.all(readers.map((session) => session.read()));
const usages = observations.flatMap((observation) =>
observation.usage ? [observation.usage] : [],
);
usages.sort((a, b) => b.observedAtMs - a.observedAtMs);
return usages.length > 0 ? { usage: usages[0] } : {};
}
const host = new MspConnection({ launch });
try {
await host.initialize();
return await host.request("usage/read", {}, usageSchema);
} finally {
await host.close();
}
}
registration(): UsageSourceRegistration {
return {
id: "muse",
label: "Muse Code",
icon: "icon.svg",
providers: ["muse"],
input: inputSchema,
discover: async (scope) => {
let accounts: string[];
if (scope.kind === "global") {
accounts = [...this.launches.keys()];
} else {
if (scope.provider !== "muse") return [];
const account = accountKey(scope.env);
accounts = this.launches.has(account) ? [account] : [];
}
return accounts.map((account) => ({
key: account,
label: "Muse Code",
input: { account },
}));
},
fetch: async (input) => {
const { account } = inputSchema.parse(input);
const launch = this.launches.get(account);
if (!launch) throw new Error("Muse login no longer exists");
try {
const { usage } = await this.read(account, launch);
if (!usage) return unavailable({ kind: "no_quota", detail: "No usage quota reported" });
const observedAt = new Date(usage.observedAtMs).toISOString();
return {
status: "available",
observedAt,
planLabel: usage.tier,
windows: [
windowFromReportedDuration({
durationSeconds: usage.window.windowDurationMins * 60,
unknown: { id: "window", label: "Current window", shortLabel: "" },
summary: true,
utilizationPct: usage.window.usedPercent,
resetsAt: new Date(usage.window.resetsAtMs).toISOString(),
tone: toneFromUsedPct(usage.window.usedPercent),
}),
windowFromUsedPct({
id: "weekly",
label: "Weekly",
shortLabel: "wk",
summary: true,
utilizationPct: usage.weekly.usedPercent,
resetsAt: new Date(usage.weekly.resetsAtMs).toISOString(),
tone: toneFromUsedPct(usage.weekly.usedPercent),
}),
],
details: [
{
id: "observed",
label: "Observed",
value: observedAt,
},
],
};
} catch (error) {
return {
status: "error",
error: error instanceof Error ? error.message : String(error),
};
}
},
};
}
}