Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/desktop/src/acp/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import {
MOCK_VIZ,
mockLinkMeta,
} from "./mockSmartUi";
import { mockAntigravityPlan, mockUsage } from "./mockUsage";
import { mockAntigravityPlan, mockSharedPlans, mockUsage } from "./mockUsage";
import type { HarnessSnapshot } from "./types";

export {
Expand Down Expand Up @@ -1241,6 +1241,8 @@ export class MockEngine {
this.linkBook = book as JsonObject;
return { saved: true };
}
case "_rustcode/usage/shared":
return mockSharedPlans();
case "_rustcode/usage/plans": {
const at = (h: number) => Math.floor(Date.now() / 1000) + h * 3600;
const p = params as
Expand Down
23 changes: 23 additions & 0 deletions apps/desktop/src/acp/mockUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,3 +473,26 @@ export function mockAntigravityPlan(at: (hours: number) => number): JsonObject {
],
};
}

/** A paired machine's subscriptions (`_rustcode/usage/shared`), for Settings › Usage › On <machine>. */
export function mockSharedPlans(): JsonObject {
const at = (h: number) => Math.floor(Date.now() / 1000) + h * 3600;
return {
plans: [
{
id: "claude",
name: "Claude",
via: "Claude Code",
harness: "claude-code",
account: null,
status: "ok",
plan: "max",
windows: [
{ label: "5-hour", usedPercent: 62, windowMinutes: 300, resetsAt: at(2) },
{ label: "Weekly", usedPercent: 38, windowMinutes: 10_080, resetsAt: at(80) },
],
},
{ id: "codex", name: "ChatGPT", via: "Codex CLI", status: "signedOut", windows: [] },
],
};
}
1 change: 1 addition & 0 deletions apps/desktop/src/acp/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const Method = {
rewind: "_rustcode/rewind",
usageLimits: "_rustcode/usage/limits",
usagePlans: "_rustcode/usage/plans",
usageShared: "_rustcode/usage/shared",
/** The slash-command catalog, for a client with no session to advertise it on. */
commands: "_rustcode/commands",
dataUsage: "_rustcode/data/usage",
Expand Down
115 changes: 115 additions & 0 deletions apps/desktop/src/state/fleetUsage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Usage across paired machines (state/fleetUsage.ts): which stores a scope
// reads, how their reports add up, and which of a machine's plans are drawn.

import { describe, expect, test } from "bun:test";
import type { UsageReport, UsageRow } from "../acp/rustcode";
import { mergeUsageReports, scopeHosts, sharedPlans } from "./fleetUsage";
import { emptyTotals } from "./statistics";

const row = (over: Partial<UsageRow> = {}): UsageRow => ({
harness: "codex",
...emptyTotals(),
turns: 1,
...over,
});

const report = (groupBy: string, rows: UsageRow[], over: Partial<UsageReport> = {}): UsageReport => ({
groupBy,
rows,
totals: rows.reduce(
(sum, one) => ({
...sum,
turns: sum.turns + one.turns,
input: (sum.input ?? 0) + (one.input ?? 0),
}),
emptyTotals(),
),
truncated: false,
parentsReported: true,
...over,
});

describe("scopeHosts", () => {
test("all reads this computer first, then each connected machine", () => {
expect(scopeHosts("all", ["vps", "box"])).toEqual(["", "vps", "box"]);
});
test("one machine reads only it, and a gone one falls back to this computer", () => {
expect(scopeHosts("vps", ["vps"])).toEqual(["vps"]);
expect(scopeHosts("", ["vps"])).toEqual([""]);
expect(scopeHosts("gone", ["vps"])).toEqual([""]);
});
});

describe("mergeUsageReports", () => {
test("this computer alone is its own report", () => {
const one = report("model", [row({ model: "gpt-5.5" })]);
expect(mergeUsageReports([{ host: "", report: one }])).toBe(one);
});

test("the same model on two machines is one row with both counts", () => {
const merged = mergeUsageReports([
{ host: "", report: report("model", [row({ model: "gpt-5.5", input: 10, cost: 1 })]) },
{
host: "vps",
report: report("model", [
row({ model: "gpt-5.5", input: 5, turns: 2 }),
row({ model: "o4", input: 1 }),
]),
},
]);
expect(merged.rows).toHaveLength(2);
const shared = merged.rows.find((one) => one.model === "gpt-5.5");
expect(shared?.input).toBe(15);
expect(shared?.turns).toBe(3);
expect(shared?.cost).toBe(1);
expect(merged.totals.turns).toBe(4);
});

test("days add up across machines", () => {
const merged = mergeUsageReports([
{ host: "", report: report("day", [row({ day: "2026-11-18", turns: 2 })]) },
{
host: "vps",
report: report("day", [row({ day: "2026-11-18", turns: 3 }), row({ day: "2026-11-19" })]),
},
]);
expect(merged.rows.map((one) => [one.day, one.turns])).toEqual([
["2026-11-18", 5],
["2026-11-19", 1],
]);
});

test("a machine's threads keep their machine, parents included", () => {
const merged = mergeUsageReports([
{ host: "", report: report("thread", [row({ thread: "a" })]) },
{ host: "vps", report: report("thread", [row({ thread: "a" }), row({ thread: "b", parentId: "a" })]) },
]);
expect(merged.rows.map((one) => one.thread)).toEqual(["a", "vps/a", "vps/b"]);
expect(merged.rows[2]?.parentId).toBe("vps/a");
});

test("a capped machine marks the whole read capped", () => {
const merged = mergeUsageReports([
{ host: "", report: report("model", []) },
{ host: "vps", report: report("model", [], { truncated: true }) },
]);
expect(merged.truncated).toBe(true);
});
});

describe("sharedPlans", () => {
test("drops the rows the machine did not read", () => {
const plans = sharedPlans({
plans: [
{ id: "claude", name: "Claude", status: "notAsked", windows: [] },
{
id: "codex",
name: "ChatGPT",
status: "ok",
windows: [{ label: "5-hour", usedPercent: 40, windowMinutes: 300, resetsAt: 1 }],
},
],
});
expect(plans.map((plan) => plan.id)).toEqual(["codex"]);
});
});
86 changes: 86 additions & 0 deletions apps/desktop/src/state/fleetUsage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Usage across this computer and the machines it is paired with. A thread run
// on a server lands in that server's data store and reads that server's
// sign-ins, so this computer alone never sees it (issue: usage never syncs to
// the Mac that drives a VPS). Statistics reads every connected machine's
// `_rustcode/data/usage` and adds the reports up here; Settings › Usage reads
// each machine's `_rustcode/usage/shared` (numbers only, no sign-in leaves it).

import type { Json } from "../acp/jsonrpc";
import { parsePlans, type UsagePlan, type UsageReport, type UsageRow } from "../acp/rustcode";
import { addTotals, emptyTotals, totalsOf } from "./statistics";
import { LOCAL_HOST, threadKey } from "./threadKeys";

/** Which store Statistics reads: every connected machine, or one (`""` is this computer). */
export type MachineScope = "all" | string;

/** The hosts a scope reads: this computer first, then each connected machine. */
export function scopeHosts(scope: MachineScope, connected: readonly string[]): string[] {
if (scope === "all") return [LOCAL_HOST, ...connected];
return scope === LOCAL_HOST || connected.includes(scope) ? [scope] : [LOCAL_HOST];
}

/** A row named as it is on this computer: a thread on a machine by its key there. */
function onHost(row: UsageRow, host: string): UsageRow {
if (!host) return row;
return {
...row,
...(row.thread ? { thread: threadKey(host, row.thread) } : {}),
...(row.parentId ? { parentId: threadKey(host, row.parentId) } : {}),
};
}

/** What makes two rows of one grouping the same row. */
function rowKey(row: UsageRow, groupBy: string): string {
switch (groupBy) {
case "thread":
return `t\n${row.thread ?? ""}`;
case "day":
return `d\n${row.day ?? ""}`;
case "project":
return `p\n${row.project ?? ""}`;
case "model":
return `m\n${row.harness}\n${row.model ?? ""}`;
default:
return `h\n${row.harness}`;
}
}

/**
* The reports of several machines as one: rows of the same key (a model, a
* day) added, a thread kept apart by the machine it ran on. Counts a machine
* never reported stay absent unless another one reported them, as in one store.
*/
export function mergeUsageReports(parts: readonly { host: string; report: UsageReport }[]): UsageReport {
const [only] = parts;
if (parts.length === 1 && only && !only.host) return only.report;
const groupBy = parts.find((part) => part.report.groupBy)?.report.groupBy ?? "";
const rows = new Map<string, UsageRow>();
let totals = emptyTotals();
for (const { host, report } of parts) {
totals = addTotals(totals, report.totals);
for (const raw of report.rows) {
const row = onHost(raw, host);
const key = rowKey(row, groupBy);
const known = rows.get(key);
if (!known) {
rows.set(key, row);
continue;
}
// Two machines' rows of one model or day: the same pair only while both agree.
const modelHarness = known.modelHarness === row.modelHarness ? known.modelHarness : undefined;
rows.set(key, { ...known, ...addTotals(totalsOf(known), totalsOf(row)), modelHarness });
}
}
return {
groupBy,
rows: [...rows.values()],
totals,
truncated: parts.some((part) => part.report.truncated),
parentsReported: parts.some((part) => part.report.parentsReported),
};
}

/** One machine's plans as Settings › Usage draws them: only the rows it read. */
export function sharedPlans(result: Json | undefined): UsagePlan[] {
return parsePlans(result).filter((plan) => plan.status !== "notAsked");
}
61 changes: 48 additions & 13 deletions apps/desktop/src/ui/StatisticsPage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Settings › Statistics: what the local data store recorded of every turn, by
// harness and model and by thread (`_rustcode/data/usage`, docs/data-store.md).
// Settings › Statistics: what the data stores recorded of every turn, by
// harness and model and by thread (`_rustcode/data/usage`, docs/data-store.md):
// this computer's and, under "All machines", each connected machine's added up.
// A thread's total includes the threads it started, so a parent shows the work
// it delegated without the same tokens being counted twice. A count a harness
// never reported stays blank. A cost is the USD a harness reported or, where it
Expand All @@ -15,11 +16,18 @@
// breakdown's bar and table share the model rows.

import { Fragment, type ReactNode, useEffect, useMemo, useState } from "react";
import { parseUsageReport, type UsageRow, type UsageTotals, windowTitle } from "../acp/rustcode";
import {
parseUsageReport,
type UsageReport,
type UsageRow,
type UsageTotals,
windowTitle,
} from "../acp/rustcode";
import { type Harness, Method } from "../acp/types";
import { modelTitle } from "../lib/modelNames";
import { count } from "../lib/plural";
import { useClock } from "../lib/useNow";
import { type MachineScope, mergeUsageReports, scopeHosts } from "../state/fleetUsage";
import {
dailySeries,
previousRows,
Expand Down Expand Up @@ -90,6 +98,10 @@ function rankGroups(groups: HarnessTotal[], costs: Map<string, CostTotals>): Har
);
}

/** Each machine's report as one, for "All machines" (`state/fleetUsage.ts`). */
const combineReports = (parts: { host: string; data: UsageReport }[]): UsageReport =>
mergeUsageReports(parts.map(({ host, data }) => ({ host, report: data })));

/** The period's models by harness, the cost of each harness, and its models ordered by cost. */
function useUsage(rows: UsageRow[] | undefined) {
return useMemo(() => {
Expand All @@ -110,27 +122,38 @@ export function StatisticsPage() {
const [all, setAll] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const range = useMemo(() => statsRange(period, new Date()), [period]);
// Every connected machine's store by default: a thread run on a server
// records its turns there, not here.
const [scope, setScope] = useState<MachineScope>("all");
const connected = useApp((s) => s.connectedHosts);
const machineNames = useApp((s) => s.machineNames);
const hosts = useMemo(() => scopeHosts(scope, connected), [scope, connected]);
const fleet = { hosts, combine: combineReports };

// The period, and the same-length period before it, each read on its own so
// their totals are the store's own sums rather than a page slicing.
const current = useEngineData(Method.dataUsage, parseUsageReport, {
groupBy: "model",
...(range.since ? { since: range.since } : {}),
});
const current = useEngineData(
Method.dataUsage,
parseUsageReport,
{ groupBy: "model", ...(range.since ? { since: range.since } : {}) },
fleet,
);
const before = useEngineData(
Method.dataUsage,
parseUsageReport,
{ groupBy: "model", ...(range.previousSince ? { since: range.previousSince } : {}) },
{ skip: period === "all" },
{ skip: period === "all", ...fleet },
);
// One day read covers both periods: the sparklines and the daily chart draw
// the current period's days, and the previous period's days count for its
// change. "All" asks for every day the store recorded.
const days = useEngineData(Method.dataUsage, parseUsageReport, {
groupBy: "day",
...(range.previousSince ? { since: range.previousSince } : {}),
});
const threads = useEngineData(Method.dataUsage, parseUsageReport, { groupBy: "thread" });
const days = useEngineData(
Method.dataUsage,
parseUsageReport,
{ groupBy: "day", ...(range.previousSince ? { since: range.previousSince } : {}) },
fleet,
);
const threads = useEngineData(Method.dataUsage, parseUsageReport, { groupBy: "thread" }, fleet);

const sessions = useApp((s) => s.sessions);
const sessionsCapped = useApp((s) => s.sessionsCapped);
Expand Down Expand Up @@ -209,6 +232,18 @@ export function StatisticsPage() {
title="Totals"
action={
<div className="flex flex-wrap items-center justify-end gap-2">
{connected.length > 0 && (
<Choice<MachineScope>
label="Machines"
value={connected.includes(scope) || scope === "" ? scope : "all"}
options={[
{ value: "all", label: "All machines" },
{ value: "", label: "This computer" },
...connected.map((host) => ({ value: host, label: machineNames[host] ?? host })),
]}
onChange={setScope}
/>
)}
<Choice<StatsPeriod>
label="Period"
value={period}
Expand Down
Loading
Loading