Files
paseo/packages/app/src/usage/model.test.ts
T
Mohamed Boudra 5eb4c8afad feat(usage): show each agent's own plan usage in its context window details (#5975)
* feat(usage): stream reports for live agent accounts

Resolve account scope from the running harness environment without invoking lifecycle hooks. Keep the client aggregate result while delivering report updates as each fetch settles; the app presentation follows separately.

* fix(usage): retain account scope for open agent sessions

Capture the launch environment once per session, independently of lazy child-process startup or exit. Use a session UUID for registry identity. Update remaining global discovery fixtures to the scoped SDK contract.

* test(usage): update browser fixtures for scoped report streams

* feat(usage): let a usage card show window rows without pins

UsageCard takes a required pinnable prop. When false, a window row is a
plain bar: no Pressable, hover highlight, or pin glyph. The settings
Usage list passes true.

* feat(usage): show the agent's usage in the context window popover

Reports stream into the query cache as each update arrives, for the
host list and for a new per-agent query keyed by agent. The context
window popover fetches its agent's reports while open and renders one
unpinnable card per report as it lands, a loading sentence before the
first, the request error as a sentence, and nothing on hosts without
usage reports.

* feat(usage): hide the Refresh button on popover usage cards

UsageCard takes a required refreshable prop. The popover passes false
because its content takes no pointer events, so the button could not
be pressed; the card then shows its freshness inline. The settings
Usage list keeps the button.

* feat(usage): make the sidebar Usage summary opt-in

The sidebar Usage item starts hidden on every layout, not only on
compact ones, so resolveSidebarNavItems drops its compact input. While
the summary is off, the Usage list renders window rows without pins;
saved pins stay in preferences and return when it is turned on. Specs
that read the summary now turn it on first.

* docs(glossary): describe the popover usage card and the opt-in sidebar summary

* fix(usage): show a popover request error without retrying

A daemon error for an agent's usage, such as an unknown agent, does not
heal on retry, and reopening the popover fetches again. Retrying held
the loading sentence for about seven seconds before the error.

* test(usage): cover agent usage in the context window popover

The usage fixture records agentId, streams reports held behind
promises, and can switch host support between reloads. The meter spec
walks loading, streaming, a report problem, a request error and a host
without usage reports, on desktop and compact in both themes.

* fix(usage): keep the plain context window tooltip on hosts without usage

The popover widened to fit usage cards on every host. Hosts that cannot
report usage now keep the tooltip's default padding and width, as
before, and mount no usage section.

* fix(usage): let a report's Refresh replace it in the agent's list too

Refresh wrote the refreshed report only into the host's list, so a card
rendered from an agent's list kept the old report. Both lists now sit
under one host key and Refresh replaces the report in each that holds it.

* feat(usage): open the context window details in a sheet on compact screens

Wide screens keep the tooltip. On compact screens pressing the meter opens
a content-sized bottom sheet titled Context window. Both render one
ContextWindowDetails body; only the sheet's usage cards have Refresh,
since the tooltip cannot be pressed. Pins stay off in both.

* test(usage): cover the compact context window sheet

On the compact viewport the meter opens the sheet; its cards have Refresh,
a Refresh replaces the card, and Close dismisses the sheet. The glossary
names the sheet.

* feat(ui): give tooltips and the context window sheet accessible roles

Tooltip content is role=tooltip, and the context window sheet is a dialog
named Context window, so assistive tech and tests find them by role. The
agent usage message drops its test ID; it is found by its text.

* test(usage): reshape the context window and Usage switch specs as journeys

The context window spec runs one tooltip journey and one sheet journey per
theme, with no layout branches. Its fixture script, meter actions and
report builders move to a context-window helper, and it finds the meter,
tooltip, sheet and Refresh buttons by role. The theme comes from the
system colour scheme. The Usage switch test uses named helpers for the
Usage icon and the Summary in sidebar switch.

* fix(usage): say an agent's usage request failed instead of showing older reports

A failed request keeps whatever reports the query held: those from an
earlier open, or those that streamed in before the failure. The context
window details showed them as if they were the agent's current usage.
The request error now wins over held reports.

* test(usage): let a fixture clean up the context window spec's agent

The tooltip and sheet tests no longer wrap their steps in try/finally;
a spec-local fixture seeds the agent and removes it after the test.

* fix(usage): keep a refreshed report when the list it is in finishes

Pressing Refresh on one card while another source was still streaming
put the pre-refresh report back: the finished list replaced the query's
data with the copies the request had fetched when it started. A report
now keeps whichever copy was fetched later, both when a streamed copy
arrives and when the finished list replaces the streamed one.

* fix(usage): show only the login a resumed agent runs under now

An agent resumed under another login keeps its ID, so its usage query
kept the previous login's reports: reopening the context window showed
them while the new login's reports loaded, then both side by side until
the request finished. The agent's usage is now dropped as soon as its
tooltip or sheet closes, so each open loads the login the agent runs
under at that moment.

* fix(usage): stop a closed agent usage request from writing reports

Closing the context window details cancels the agent's usage request and
drops reports still on their way, so reopening after a resume under
another login sends a new request instead of joining the old one.
2026-10-03 23:12:57 +01:00

312 lines
10 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
displayPercent,
formatUsageFreshness,
resolveAgentUsageView,
replaceReport,
resolveUsageRefresh,
resolveUsageHostId,
resolveUsageScreenHostId,
resolveUsageView,
settleReports,
upsertReport,
usageWindowRowLabel,
type UsageHost,
type UsageQueryState,
} from "./model";
import type { UsageReportEntry, UsageWindow } from "./types";
function entry(input: {
windows?: UsageWindow[];
planLabel?: string;
icon?: string;
sourceId?: string;
}): UsageReportEntry {
return {
id: `${input.sourceId ?? "fixture"}:account-1`,
account: {},
fetchedAt: "2026-01-01T00:00:00.000Z",
sourceId: input.sourceId ?? "fixture",
sourceLabel: "Fixture source",
...(input.icon ? { icon: input.icon } : {}),
report: {
status: "available",
...(input.planLabel ? { planLabel: input.planLabel } : {}),
windows: input.windows ?? [],
},
};
}
function ready(data: UsageReportEntry[]): UsageQueryState {
return { data, error: null, isFetching: false };
}
describe("resolveUsageView", () => {
it("asks for a host update when the host lacks usage sources", () => {
expect(
resolveUsageView({
hostLabel: "Laptop",
isConnected: true,
supportsUsage: false,
query: ready([entry({})]),
}),
).toEqual({ kind: "unavailable", message: "Update Laptop to see usage" });
});
it("asks for a connection before anything else", () => {
expect(
resolveUsageView({
hostLabel: "Laptop",
isConnected: false,
supportsUsage: false,
query: undefined,
}),
).toEqual({ kind: "unavailable", message: "Connect to Laptop to see usage" });
});
it("moves from loading to ready to error", () => {
const base = { hostLabel: "Laptop", isConnected: true, supportsUsage: true };
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
expect(
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
expect(
resolveUsageView({
...base,
query: { data: undefined, error: new Error("boom"), isFetching: false },
}),
).toEqual({ kind: "error", message: "boom" });
});
});
const hosts: UsageHost[] = [
{ serverId: "offline", label: "Offline", isConnected: false, supportsUsage: true },
{ serverId: "old", label: "Old", isConnected: true, supportsUsage: false },
{ serverId: "a", label: "Alpha", isConnected: true, supportsUsage: true },
{ serverId: "b", label: "Beta", isConnected: true, supportsUsage: true },
];
describe("resolveUsageHostId", () => {
const choose = (pickedServerId: string | null, activeServerId: string | null) =>
resolveUsageHostId({ pickedServerId, activeServerId, hosts });
it("reads the picked host over the active workspace's host", () => {
expect(choose("a", "b")).toBe("a");
});
it("reads the active workspace's host when nothing usable is picked", () => {
expect(choose(null, "b")).toBe("b");
expect(choose("offline", "b")).toBe("b");
expect(choose("old", "b")).toBe("b");
});
it("falls back to the first connected host that reports usage", () => {
expect(choose(null, null)).toBe("a");
expect(choose(null, "offline")).toBe("a");
expect(choose(null, "old")).toBe("a");
});
it("has no host when none reports usage", () => {
expect(
resolveUsageHostId({
pickedServerId: "old",
activeServerId: "old",
hosts: hosts.slice(0, 2),
}),
).toBeNull();
});
});
describe("resolveUsageScreenHostId", () => {
it("shows the picked host while it stays connected, even one that cannot report usage", () => {
expect(resolveUsageScreenHostId({ pickedServerId: "old", activeServerId: "b", hosts })).toBe(
"old",
);
expect(
resolveUsageScreenHostId({ pickedServerId: "offline", activeServerId: "b", hosts }),
).toBe("b");
});
it("otherwise shows the host the sidebar row reads", () => {
for (const pickedServerId of [null, "a", "offline"]) {
for (const activeServerId of ["b", null, "old", "offline"]) {
const choice = { pickedServerId, activeServerId, hosts };
expect(resolveUsageScreenHostId(choice)).toBe(resolveUsageHostId(choice));
}
}
});
it("shows the first connected host when none reports usage, so the screen says to update it", () => {
expect(
resolveUsageScreenHostId({
pickedServerId: null,
activeServerId: null,
hosts: hosts.slice(0, 2),
}),
).toBe("old");
expect(
resolveUsageScreenHostId({ pickedServerId: null, activeServerId: null, hosts: [] }),
).toBeNull();
});
});
describe("usageWindowRowLabel", () => {
it("names the window, its percent and its reset after what pinning it pins", () => {
expect(
usageWindowRowLabel({
pinLabel: "Pin Claude Session",
value: "31%",
trailing: "resets in 2h",
}),
).toBe("Pin Claude Session, 31% · resets in 2h");
expect(usageWindowRowLabel({ pinLabel: "Pin Codex Weekly", value: "—", trailing: null })).toBe(
"Pin Codex Weekly, —",
);
});
});
describe("displayPercent", () => {
const window = (input: Partial<UsageWindow>): UsageWindow => ({
id: "weekly",
label: "Weekly",
...input,
});
it("reads the share used or the share left", () => {
expect(displayPercent(window({ usedPct: 31 }), "used")).toBe(31);
expect(displayPercent(window({ usedPct: 31 }), "remaining")).toBe(69);
expect(displayPercent(window({ remainingPct: 40 }), "used")).toBe(60);
expect(displayPercent(window({ usedPct: 50, remainingPct: 45 }), "remaining")).toBe(45);
});
it("has no percent when the window reports none", () => {
expect(displayPercent(window({}), "remaining")).toBeNull();
});
});
describe("formatUsageFreshness", () => {
it("says when the report was fetched", () => {
expect(formatUsageFreshness("now")).toBe("Updated just now");
expect(formatUsageFreshness("3m")).toBe("Updated 3m ago");
expect(formatUsageFreshness("Jan 15")).toBe("Updated Jan 15");
});
});
describe("resolveUsageRefresh", () => {
it("is pending while a refresh runs, even after an earlier failure", () => {
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
});
it("is failed after a refresh errors", () => {
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
});
it("is idle before and after a successful refresh", () => {
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
});
});
describe("replaceReport", () => {
const alpha = entry({ sourceId: "alpha", planLabel: "Old" });
const beta = entry({ sourceId: "beta" });
it("swaps only the refreshed report, in place", () => {
const refreshed = entry({ sourceId: "alpha", planLabel: "New" });
expect(replaceReport([alpha, beta], alpha.id, refreshed)).toEqual([refreshed, beta]);
});
it("drops a report the daemon no longer knows", () => {
expect(replaceReport([alpha, beta], alpha.id, null)).toEqual([beta]);
});
});
describe("upsertReport", () => {
const alpha = entry({ sourceId: "alpha", planLabel: "Old" });
const beta = entry({ sourceId: "beta" });
it("starts a list from the first streamed report", () => {
expect(upsertReport(undefined, alpha)).toEqual([alpha]);
});
it("appends a report the list does not have yet", () => {
expect(upsertReport([alpha], beta)).toEqual([alpha, beta]);
});
it("replaces a report the list already has, in place", () => {
const streamed = entry({ sourceId: "alpha", planLabel: "New" });
expect(upsertReport([alpha, beta], streamed)).toEqual([streamed, beta]);
});
it("keeps a copy fetched after the streamed one, such as a Refresh that landed first", () => {
const refreshed = { ...alpha, planLabel: "Refreshed", fetchedAt: "2026-01-01T00:05:00.000Z" };
expect(upsertReport([refreshed, beta], alpha)).toEqual([refreshed, beta]);
});
});
describe("settleReports", () => {
const alpha = entry({ sourceId: "alpha", planLabel: "Old" });
const beta = entry({ sourceId: "beta" });
it("takes the finished list, dropping reports the host no longer has", () => {
const streamed = entry({ sourceId: "alpha", planLabel: "New" });
expect(settleReports([alpha, beta], [streamed])).toEqual([streamed]);
});
it("keeps a report refreshed while the list streamed over its older copy in the list", () => {
const refreshed = { ...alpha, planLabel: "Refreshed", fetchedAt: "2026-01-01T00:05:00.000Z" };
expect(settleReports([refreshed, beta], [alpha, beta])).toEqual([refreshed, beta]);
});
it("takes the finished list as is when nothing was shown yet", () => {
expect(settleReports(undefined, [alpha, beta])).toEqual([alpha, beta]);
});
});
describe("resolveAgentUsageView", () => {
const report = entry({ sourceId: "claude" });
const idle: UsageQueryState = { data: undefined, error: null, isFetching: false };
it("shows nothing on a host that cannot report usage", () => {
expect(resolveAgentUsageView({ canReport: false, query: idle })).toEqual({ kind: "none" });
});
it("loads until the first report streams in", () => {
expect(
resolveAgentUsageView({ canReport: true, query: { ...idle, isFetching: true } }),
).toEqual({ kind: "loading" });
});
it("shows each report as it streams in, before the request finishes", () => {
expect(
resolveAgentUsageView({
canReport: true,
query: { data: [report], error: null, isFetching: true },
}),
).toEqual({ kind: "ready", reports: [report] });
});
it("shows nothing for an agent with no account to report", () => {
expect(resolveAgentUsageView({ canReport: true, query: { ...idle, data: [] } })).toEqual({
kind: "none",
});
});
it("says why a failed request has nothing to show", () => {
expect(
resolveAgentUsageView({
canReport: true,
query: { ...idle, error: new Error("Unknown agent") },
}),
).toEqual({ kind: "error", message: "Unable to load usage: Unknown agent" });
});
it("says the request failed instead of showing the reports from before it", () => {
expect(
resolveAgentUsageView({
canReport: true,
query: { data: [report], error: new Error("Unknown agent"), isFetching: false },
}),
).toEqual({ kind: "error", message: "Unable to load usage: Unknown agent" });
});
});