Skip to content

Commit a97b247

Browse files
committed
feat(muse): show Muse Code token usage and subscription limits
The Usage section only showed Codex. Muse Code had no token history reader and never reported subscription limits, so neither the Tokens view nor Limits mentioned it. Mark Muse's full two-window report explicitly. Complete reports replace stale windows and clear a failed-probe notice; partial live updates preserve upstream's notice behavior. Add a "muse" usage kind with a transcript reader over the native session logs: model completions and compaction summary metrics contribute counted-once input, output, and reasoning at their recorded time, with record-id deduplication across forked session files. Summary metrics omit the model, so retain their tokens as unknown and unpriced. Rescan existing Muse files from older usage caches while preserving deleted history. Read Muse's MSP usage/read during the existing read-only status probe and map usage/changed notifications from turn hosts to session and weekly limit windows, so Limits, /usage-limits, and the mobile widgets show Muse beside the other providers. A fresh probe host has observed nothing, so Limits first shows an honest not-reported notice and keeps the last observed windows after turns report. Scope the credential fingerprint to hostname, canonical home path, and filesystem identity so one login pools once without merging identical paths on other machines. Preserve fingerprints across window-only updates, advance stale checkedAt at most once a minute unless reset credits ride the snapshot, and reject record timestamps aggregation cannot bucket. Implemented by GPT-6-Astra at Max, reviewed by GPT-6.1-Sol at Extra High across three rounds, led and verified by muse-wonder-full-1.0 in Muse Code via T3 Code. Summary accounting validated with 102 focused tests, scoped typechecks, lint, and a read-only scan of 39 native summary records. Implemented by GPT-6-Astra through Codex; reviewed by GPT-6.1-Sol at Extra High.
1 parent e0027f3 commit a97b247

33 files changed

Lines changed: 1546 additions & 66 deletions

‎apps/mobile/src/features/usage/usageProviders.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export const PROVIDER_ORDER: readonly UsageProviderKind[] = [
99
"opencode",
1010
"antigravity",
1111
"pi",
12+
"muse",
1213
];
1314

1415
/** The usage series a provider driver reports under, or null for drivers without one. */
@@ -25,6 +26,7 @@ export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
2526
opencode: "OpenCode",
2627
antigravity: "Antigravity",
2728
pi: "Pi",
29+
muse: "Muse Code",
2830
};
2931

3032
export function useProviderColors(): Record<UsageProviderKind, string> {
@@ -37,6 +39,7 @@ export function useProviderColors(): Record<UsageProviderKind, string> {
3739
opencode: "#5b9bbd",
3840
antigravity: "#8c7bd1",
3941
pi: "#4d9f8a",
42+
muse: "#0082fb",
4043
};
4144
}
4245

‎apps/mobile/src/widgets/SubscriptionUsage.tsx‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,11 @@ function SubscriptionUsage(
6262
const columns = providers.map((provider) => {
6363
const stale = provider.windows.length > 0 && now >= provider.expiresAt;
6464
const period =
65-
widgetEnvironment.configuration?.[
66-
provider.name === "Claude" ? "claudePeriod" : "codexPeriod"
67-
] ?? "auto";
65+
(provider.name === "Claude"
66+
? widgetEnvironment.configuration?.claudePeriod
67+
: provider.name === "Codex"
68+
? widgetEnvironment.configuration?.codexPeriod
69+
: undefined) ?? "auto";
6870
const windows = stale
6971
? []
7072
: provider.windows.filter((window) => period === "auto" || window.kind === period);
@@ -97,7 +99,17 @@ function SubscriptionUsage(
9799
const barModifiers = [
98100
progressViewStyle("linear"),
99101
frame({ height: 4 }),
100-
...(monochrome ? [] : [tint(provider.name === "Claude" ? "#d97757" : "#8e8e93")]),
102+
...(monochrome
103+
? []
104+
: [
105+
tint(
106+
provider.name === "Claude"
107+
? "#d97757"
108+
: provider.name === "Muse Code"
109+
? "#0082fb"
110+
: "#8e8e93",
111+
),
112+
]),
101113
];
102114
if (accessory) {
103115
return (

‎apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ describe("subscription widget snapshots", () => {
105105
it.each([
106106
{ name: "Codex", driver: "codex" },
107107
{ name: "Claude", driver: "claudeAgent" },
108+
{ name: "Muse Code", driver: "muse" },
108109
])("only shows $name when $name and OpenCode are configured", ({ name, driver }) => {
109110
const snapshot = buildSubscriptionUsageSnapshot(
110111
presentations([
@@ -140,6 +141,40 @@ describe("subscription widget snapshots", () => {
140141
{ name: "Codex", detail: "No limits available", windows: [], expiresAt: 0, totalWindows: 0 },
141142
]);
142143
});
144+
it("pools Muse instances sharing a home once and expires its observed windows", () => {
145+
const muse = provider({
146+
instanceId: ProviderInstanceId.make("muse-one"),
147+
driver: ProviderDriverKind.make("muse"),
148+
auth: { status: "unknown" },
149+
usageLimits: {
150+
checkedAt,
151+
credentialFingerprint: "shared-muse-home",
152+
windows: [
153+
{ ...window, id: "window", label: "Session" },
154+
{ ...window, id: "weekly", kind: "weekly", label: "Weekly", usedPercent: 20 },
155+
],
156+
},
157+
});
158+
const snapshot = buildSubscriptionUsageSnapshot(
159+
presentations([muse, { ...muse, instanceId: ProviderInstanceId.make("muse-two") }]),
160+
deepLink,
161+
);
162+
expect(snapshot.checkedAt).toBe(now);
163+
expect(snapshot.providers).toEqual([
164+
expect.objectContaining({
165+
name: "Muse Code",
166+
detail: "Subscription remaining",
167+
totalWindows: 2,
168+
windows: [
169+
expect.objectContaining({ label: "Session", remaining: 60 }),
170+
expect.objectContaining({ label: "Weekly", remaining: 80 }),
171+
],
172+
}),
173+
]);
174+
expect(
175+
subscriptionUsageTimeline(snapshot, now + 10 * 60_000)[0]?.props.providers[0]?.windows,
176+
).toEqual([]);
177+
});
143178
it("uses upstream deduplication for a native account also present in a proxy hub", () => {
144179
const input = new Map([
145180
[

‎apps/mobile/src/widgets/subscriptionUsageSnapshot.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,18 +53,21 @@ function subscriptionUsageProps(
5353
): SubscriptionUsageSnapshot {
5454
const pools = collectLimitPools(accounts, now);
5555
const checked = accounts
56-
.filter((account) => account.driver === "codex" || account.driver === "claudeAgent")
56+
.filter(
57+
(account) =>
58+
account.driver === "codex" || account.driver === "claudeAgent" || account.driver === "muse",
59+
)
5760
.map((account) => Date.parse(account.limits.checkedAt));
5861
return {
5962
checkedAt: checked.length > 0 && checked.every(Number.isFinite) ? Math.min(...checked) : 0,
60-
providers: (["codex", "claudeAgent"] as const)
63+
providers: (["codex", "claudeAgent", "muse"] as const)
6164
.filter(
6265
(driver) =>
6366
configuredDrivers.has(driver) || accounts.some((account) => account.driver === driver),
6467
)
6568
.map((driver) => {
6669
const pool = pools.find((candidate) => candidate.driver === driver);
67-
const name = driver === "codex" ? "Codex" : "Claude";
70+
const name = driver === "codex" ? "Codex" : driver === "muse" ? "Muse Code" : "Claude";
6871
if (!pool)
6972
return {
7073
name,

‎apps/server/src/orchestration-v2/Adapters/MuseAdapterV2.testkit.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ export async function connectMuseTransport(input: {
381381
return {
382382
connection,
383383
initializeResult: {
384+
museHome: typeof result.museHome === "string" ? result.museHome : "",
384385
grantedCapabilities: Array.isArray(granted)
385386
? granted.filter((capability) => typeof capability === "string")
386387
: [],

‎apps/server/src/provider/builtInDrivers.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ export type BuiltInUsageReadersEnv =
4545
| ProviderUsageReaderEnv<typeof OpenCodeDriver>
4646
| ProviderUsageReaderEnv<typeof AntigravityDriver>
4747
| ProviderUsageReaderEnv<typeof CursorDriver>
48-
| ProviderUsageReaderEnv<typeof PiDriver>;
48+
| ProviderUsageReaderEnv<typeof PiDriver>
49+
| ProviderUsageReaderEnv<typeof MuseDriver>;
4950

5051
/**
5152
* Aggregation keeps the first copy of a duplicate record, so the order is part
@@ -58,6 +59,7 @@ export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray<
5859
CodexDriver,
5960
GrokDriver,
6061
PiDriver,
62+
MuseDriver,
6163
OpenCodeDriver,
6264
AntigravityDriver,
6365
CursorDriver,

‎apps/server/src/usage/UsageService.test.ts‎

Lines changed: 158 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ const layerService = (input: {
175175
OPENCODE_DATA_DIR: NodePath.join(input.home, "opencode"),
176176
ANTIGRAVITY_DATA_DIR: NodePath.join(input.home, "antigravity"),
177177
XDG_CONFIG_HOME: NodePath.join(input.home, "config"),
178+
XDG_DATA_HOME: NodePath.join(input.home, "data"),
178179
APPDATA: NodePath.join(input.home, "config"),
179180
...input.environment,
180181
}),
@@ -457,6 +458,162 @@ describe("Codex usage history", () => {
457458
});
458459

459460
describe("UsageService", () => {
461+
it.live(
462+
"rescans unchanged Muse transcripts from v7 without losing deleted history or counting copies twice",
463+
() =>
464+
Effect.gen(function* () {
465+
const { home, settings } = yield* setup;
466+
const sessions = NodePath.join(home, "data", "muse", "sessions");
467+
const live = NodePath.join(sessions, "live", "session.jsonl");
468+
const deleted = NodePath.join(sessions, "deleted", "session.jsonl");
469+
const fork = NodePath.join(sessions, "fork", "session.jsonl");
470+
const line = (id: string, event: unknown) =>
471+
encodeUnknownJsonString({
472+
id,
473+
recorded_at: Date.parse("2026-08-01T10:00:00Z") * 1000,
474+
stream: { kind: "session", id: "parent" },
475+
payload: { event },
476+
}) + "\n";
477+
const ordinary = line("model-record", {
478+
kind: "model_completed",
479+
model: "muse-model",
480+
usage: { input_tokens: 10, output_tokens: 2 },
481+
});
482+
const summaryLine = line("summary-record", {
483+
kind: "context_compaction_candidate",
484+
diagnostics: [
485+
{
486+
reason: "summary_call_metrics",
487+
message: '{"input_tokens":100,"output_tokens":20,"reasoning_tokens":5}',
488+
},
489+
],
490+
});
491+
yield* Effect.promise(async () => {
492+
for (const [path, content] of [
493+
[live, ordinary + summaryLine + summaryLine],
494+
[fork, ordinary + summaryLine],
495+
[
496+
deleted,
497+
line("deleted-record", {
498+
kind: "model_completed",
499+
model: "muse-model",
500+
usage: { output_tokens: 3 },
501+
}),
502+
],
503+
] as const) {
504+
await NodeFSP.mkdir(NodePath.dirname(path), { recursive: true });
505+
await NodeFSP.writeFile(path, content);
506+
}
507+
});
508+
yield* Effect.gen(function* () {
509+
const { stateDir } = yield* ServerConfig.ServerConfig;
510+
const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME);
511+
const legacyPath = NodePath.join(stateDir, "usage-scan-cache-v7.json");
512+
const first = yield* UsageService.make;
513+
yield* first.readSummary(WINDOW);
514+
yield* first.awaitPersisted;
515+
const legacy = yield* Effect.promise(async () => {
516+
const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as {
517+
models: string[];
518+
files: Record<string, { r: unknown[][] }>;
519+
};
520+
for (const file of Object.values(document.files)) {
521+
file.r = file.r.filter((row) => row[1] !== document.models.indexOf("unknown"));
522+
}
523+
const text = encodeUnknownJsonString({ ...document, version: 7 });
524+
await NodeFSP.writeFile(legacyPath, text);
525+
await NodeFSP.rm(cachePath);
526+
await NodeFSP.rm(deleted);
527+
return text;
528+
});
529+
const upgraded = yield* UsageService.make;
530+
const summary = yield* upgraded.readSummary(WINDOW);
531+
assert.strictEqual(totalOutputTokens(summary), 25);
532+
const unknown = summary.buckets.find(
533+
(bucket) => bucket.provider === "muse" && bucket.model === "unknown",
534+
);
535+
assert.strictEqual(unknown?.records, 1);
536+
assert.strictEqual(unknown?.costSource, "unpriced");
537+
assert.deepStrictEqual(unknown?.totals, {
538+
uncachedInputTokens: 100,
539+
cachedInputTokens: 0,
540+
cacheCreationTokens: 0,
541+
outputTokens: 20,
542+
reasoningTokens: 5,
543+
});
544+
yield* upgraded.awaitPersisted;
545+
const restarted = yield* UsageService.make;
546+
assert.deepStrictEqual((yield* restarted.readSummary(WINDOW)).buckets, summary.buckets);
547+
assert.strictEqual(
548+
yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")),
549+
legacy,
550+
);
551+
}).pipe(Effect.provide(layerService({ prefix: "usage-muse-upgrade", home, settings })));
552+
}).pipe(Effect.scoped),
553+
);
554+
555+
it.live("reads Muse parent and subagent sessions once across copied records", () =>
556+
Effect.gen(function* () {
557+
const { home, settings } = yield* setup;
558+
const dir = NodePath.join(home, "data", "muse", "sessions", "2026", "08", "01");
559+
const line = (id: string, sessionId: string) =>
560+
encodeUnknownJsonString({
561+
id,
562+
recorded_at: Date.parse("2026-08-01T10:00:00Z") * 1000,
563+
stream: { kind: "session", id: sessionId },
564+
payload: {
565+
event: {
566+
kind: "model_completed",
567+
model: "muse-model",
568+
usage: {
569+
input_tokens: 100,
570+
cache_read_tokens: 40,
571+
cache_write_tokens: 10,
572+
output_tokens: 20,
573+
reasoning_tokens: 10,
574+
},
575+
},
576+
},
577+
}) + "\n";
578+
yield* Effect.promise(async () => {
579+
for (const [folder, content] of [
580+
["parent", line("parent-record", "parent")],
581+
["parent/subagent/child", line("child-record", "child")],
582+
["fork", line("parent-record", "parent")],
583+
]) {
584+
const path = NodePath.join(dir, folder!);
585+
await NodeFSP.mkdir(path, { recursive: true });
586+
await NodeFSP.writeFile(NodePath.join(path, "session.jsonl"), content!);
587+
}
588+
await NodeFSP.writeFile(NodePath.join(dir, "ignored.jsonl"), line("ignored", "ignored"));
589+
});
590+
yield* Effect.gen(function* () {
591+
const service = yield* UsageService.make;
592+
const summary = yield* service.readSummary(WINDOW);
593+
const muse = summary.buckets.filter((bucket) => bucket.provider === "muse");
594+
assert.strictEqual(muse.length, 1);
595+
assert.deepStrictEqual(muse[0]?.totals, {
596+
uncachedInputTokens: 100,
597+
cachedInputTokens: 80,
598+
cacheCreationTokens: 20,
599+
outputTokens: 40,
600+
reasoningTokens: 20,
601+
});
602+
assert.strictEqual(muse[0]?.records, 2);
603+
assert.strictEqual(muse[0]?.sessions, 2);
604+
assert.strictEqual(muse[0]?.costSource, "unpriced");
605+
assert.strictEqual(muse[0]?.unpricedRecords, 2);
606+
assert.strictEqual(
607+
summary.sources.find((source) => source.fingerprint.provider === "muse")?.scannedFiles,
608+
3,
609+
);
610+
}).pipe(
611+
Effect.scoped,
612+
Effect.provide(layerService({ prefix: "usage-muse", home, settings })),
613+
);
614+
}).pipe(Effect.scoped),
615+
);
616+
460617
it.live(
461618
"repairs initial Codex prices after unchanged-file retries, persists evidence and corrections, and honors later native tiers",
462619
() =>
@@ -2142,7 +2299,7 @@ describe("UsageService", () => {
21422299
60 + 20 * (version === 4 ? 1 : 2),
21432300
);
21442301
yield* upgraded.awaitPersisted;
2145-
assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v7.json");
2302+
assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v8.json");
21462303
assert.strictEqual(
21472304
yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")),
21482305
legacy,

‎apps/server/src/usage/usageScanCache.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,32 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][])
6161
}
6262

6363
describe("scan cache round trip", () => {
64+
it.each([4, 5, 6, 7, 8])(
65+
"retains v%s Muse history and rescans only pre-summary caches",
66+
(version) => {
67+
const original: CachedFile = {
68+
size: 256,
69+
mtimeMs: 100,
70+
provider: "muse",
71+
records: [record({ provider: "muse", model: "muse-model" })],
72+
tailRecords: [record({ provider: "muse", model: "unknown", dedupeKey: "summary" })],
73+
malformedRecords: 0,
74+
position: position(),
75+
};
76+
const encoded = encodeScanCache(new Map([["/muse/session.jsonl", original]]));
77+
const restored = decodeScanCache({ ...encoded, version }, TEST_FORMAT_MAP);
78+
expect(restored.get("/muse/session.jsonl")).toEqual(
79+
version === 8
80+
? original
81+
: {
82+
...original,
83+
size: -1,
84+
position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
85+
},
86+
);
87+
},
88+
);
89+
6490
it("restores cached history unchanged except for Claude local placeholders", () => {
6591
const original = cacheWith([
6692
[

0 commit comments

Comments
 (0)