Skip to content

Commit 1633ce1

Browse files
committed
feat(provider-muse): show Muse subscription limits in Usage limits
Muse forwards the Meta subscription windows with each reply as the MSP usage/changed notification, but the provider ignored it and never set usageLimits, so Muse was missing from Usage -> Limits while providers read natively or through a CLIProxyAPI hub showed theirs. The adapter now forwards each report to the driver, which publishes the Session and Weekly windows and re-derives them from the newest report on every status check; a window whose reset has passed starts over empty. Before the first reply after a server start, Limits shows that Muse reports subscription usage with its next reply. Mobile labels the new driver Muse Code. Worked with muse-wonder-1.0 in Muse Code; review by muse-spark-1.3-contributor.
1 parent 511d20c commit 1633ce1

8 files changed

Lines changed: 280 additions & 3 deletions

File tree

‎apps/mobile/src/features/threads/ComposerUsageLimits.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ import { SymbolView } from "../../components/AppSymbol";
55
import { AppText as Text } from "../../components/AppText";
66
import { AccountLimits, ResetCredits } from "../usage/UsageLimitsSection";
77

8-
const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
8+
const DRIVER_LABEL: Partial<Record<string, string>> = {
9+
codex: "Codex",
10+
claudeAgent: "Claude",
11+
muse: "Muse Code",
12+
};
913

1014
/**
1115
* The /usage-limits result, docked above the composer. It is the Usage → Limits

‎apps/mobile/src/features/usage/UsageLimitsPooled.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const DRIVER_LABEL: Partial<Record<string, string>> = {
3030
codex: "Codex",
3131
claudeAgent: "Claude",
3232
antigravity: "Antigravity",
33+
muse: "Muse Code",
3334
};
3435
const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const;
3536

‎packages/provider-muse/src/server/adapter.test.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ import * as Stream from "effect/Stream";
3333

3434
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
3535
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
36-
import type { MuseItem } from "./protocol.ts";
36+
import type { MuseItem, MuseSubscriptionUsage } from "./protocol.ts";
3737
import type { MuseSdkHost } from "./sdk.ts";
3838
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
3939
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -191,7 +191,11 @@ const makeHarness = Effect.fnUntraced(function* (
191191
policy = runtimePolicy,
192192
overrides: Pick<
193193
MuseAdapterV2Options,
194-
"createHost" | "nativeEventLogger" | "modelCatalog" | "continuationRequests"
194+
| "createHost"
195+
| "nativeEventLogger"
196+
| "modelCatalog"
197+
| "continuationRequests"
198+
| "onSubscriptionUsage"
195199
> = {},
196200
) {
197201
let hostCount = 0;
@@ -548,6 +552,39 @@ describe("MuseAdapterV2", () => {
548552
}).pipe(Effect.scoped, Effect.provide(testLayer)),
549553
);
550554

555+
it.effect("forwards subscription usage reports and skips unreadable ones", () =>
556+
Effect.gen(function* () {
557+
const fake = yield* makeFakeMuse();
558+
const reported = yield* Deferred.make<MuseSubscriptionUsage>();
559+
const harness = yield* makeHarness(
560+
fake,
561+
INSTANCE_ID,
562+
undefined,
563+
undefined,
564+
undefined,
565+
runtimePolicy,
566+
{
567+
onSubscriptionUsage: (usage) => Deferred.succeed(reported, usage).pipe(Effect.asVoid),
568+
},
569+
);
570+
const { nativeId } = yield* startConversation(harness, fake);
571+
yield* fake.emit("usage/changed", { tier: 1 });
572+
yield* fake.emit("usage/changed", {
573+
observedAtMs: 1_000,
574+
tier: "meta-subscription",
575+
window: { usedPercent: 3, resetsAtMs: 2_000, windowDurationMins: 300 },
576+
weekly: { usedPercent: 46, resetsAtMs: 3_000 },
577+
});
578+
const usage = yield* Deferred.await(reported);
579+
assert.strictEqual(usage.window.usedPercent, 3);
580+
assert.strictEqual(usage.weekly.usedPercent, 46);
581+
yield* fake.emit("turn/completed", { turnId: nativeId, terminal: "completed" });
582+
const terminal = yield* harness.takeEvent("turn.terminal");
583+
assert.strictEqual(terminal.status, "completed");
584+
assert.strictEqual(fake.closeCount(), 0);
585+
}).pipe(Effect.scoped, Effect.provide(testLayer)),
586+
);
587+
551588
it.effect("moves a resumed session on another model back to the catalog default", () =>
552589
Effect.gen(function* () {
553590
const fake = yield* makeFakeMuse();

‎packages/provider-muse/src/server/adapter.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
MuseDelta,
5151
MuseItemEvent,
5252
MuseSessionResult,
53+
MuseSubscriptionUsage,
5354
MuseTokenUsageEvent,
5455
MuseTodoList,
5556
MuseTurnRetryScheduled,
@@ -195,6 +196,8 @@ export interface MuseAdapterV2Options {
195196
readonly createHost?: typeof createMuseSdkHost;
196197
readonly requestTimeoutMs?: number;
197198
readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger;
199+
/** Each subscription-usage report Muse forwards (`usage/changed`); the driver publishes it. */
200+
readonly onSubscriptionUsage?: (usage: MuseSubscriptionUsage) => Effect.Effect<void>;
198201
/** Where a turn Muse starts on its own (a finished workflow's report) asks for its run. */
199202
readonly continuationRequests?: {
200203
readonly offer: (
@@ -261,6 +264,7 @@ const INFORMATIONAL_NOTIFICATIONS = new Set([
261264
"session/tokenUsage",
262265
"session/todoListChanged",
263266
"turn/retryScheduled",
267+
"usage/changed",
264268
]);
265269
// Tools whose results already show as their own rows: T3's todo list and question
266270
// rows, and the workflow item a `workflow` call launches.
@@ -1284,6 +1288,12 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
12841288
}
12851289
});
12861290
const handleNotification = Effect.fnUntraced(function* (method: string, data: unknown) {
1291+
// Subscription usage is connection-scoped: its payload names no session.
1292+
if (method === "usage/changed") {
1293+
const usage = yield* decode(MuseSubscriptionUsage, data);
1294+
if (options.onSubscriptionUsage) yield* options.onSubscriptionUsage(usage);
1295+
return;
1296+
}
12871297
const params = yield* decode(recordSchema, data);
12881298
if (params.sessionId !== nativeSessionId) return;
12891299
if (method === "view/gap")

‎packages/provider-muse/src/server/driver.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEve
2222
import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
2323
import { enrichMuseSnapshot, latestMuseVersion, museMaintenance } from "./maintenance.ts";
2424
import { makeMuseEnvironment } from "./sdk.ts";
25+
import type { MuseSubscriptionUsage } from "./protocol.ts";
26+
import { museSubscriptionUsageToLimits, museSubscriptionUsageToUpdate } from "./usageLimits.ts";
27+
import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
28+
import * as DateTime from "effect/DateTime";
29+
import * as Ref from "effect/Ref";
2530
import {
2631
defaultProviderContinuationIdentity,
2732
type ProviderDriver,
@@ -38,6 +43,7 @@ import {
3843
type ProviderSnapshotSettings,
3944
} from "@t3tools/provider-core/server/snapshotSettings";
4045
import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
46+
import type { ServerProviderDraft } from "@t3tools/provider-core/server/snapshotProbe";
4147

4248
const DRIVER_KIND = ProviderDriverKind.make("muse");
4349
const decodeMuseSettings = Schema.decodeSync(MuseSettings);
@@ -118,6 +124,28 @@ export const MuseDriver: ProviderDriver<MuseSettings, MuseDriverEnv> = {
118124
: undefined;
119125
return latestVersion !== undefined ? { ...capabilities, latestVersion } : capabilities;
120126
});
127+
// Meta reports subscription usage only with a reply, so the newest
128+
// `usage/changed` report is kept and re-derived on every status check.
129+
const retainedUsage = yield* Ref.make<MuseSubscriptionUsage | undefined>(undefined);
130+
const withUsageLimits = (snapshot: ServerProviderDraft) =>
131+
Effect.gen(function* () {
132+
if (!effectiveConfig.enabled || !snapshot.installed) return snapshot;
133+
const now = yield* DateTime.now;
134+
const checkedAt = DateTime.formatIso(now);
135+
const usage = yield* Ref.get(retainedUsage);
136+
const usageLimits = usage
137+
? museSubscriptionUsageToLimits({
138+
usage,
139+
checkedAt,
140+
nowMs: DateTime.toEpochMillis(now),
141+
})
142+
: makeUnavailableUsageLimits({
143+
checkedAt,
144+
reason: "probeFailed",
145+
message: "Muse reports subscription usage with its next reply.",
146+
});
147+
return { ...snapshot, usageLimits };
148+
});
121149
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<MuseSettings>>({
122150
resolveMaintenance,
123151
getSettings: snapshotSettings.getSettings,
@@ -126,6 +154,7 @@ export const MuseDriver: ProviderDriver<MuseSettings, MuseDriverEnv> = {
126154
initialSnapshot: (settings) =>
127155
makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)),
128156
checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe(
157+
Effect.flatMap(withUsageLimits),
129158
Effect.map(stampIdentity),
130159
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
131160
Effect.provideService(FileSystem.FileSystem, fileSystem),
@@ -163,6 +192,18 @@ export const MuseDriver: ProviderDriver<MuseSettings, MuseDriverEnv> = {
163192
environment: processEnvironment,
164193
modelCatalog,
165194
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
195+
onSubscriptionUsage: (usage) =>
196+
Effect.gen(function* () {
197+
yield* Ref.set(retainedUsage, usage);
198+
const now = yield* DateTime.now;
199+
yield* snapshot.applyUsageLimits({
200+
...museSubscriptionUsageToUpdate({
201+
usage,
202+
nowMs: DateTime.toEpochMillis(now),
203+
}),
204+
checkedAt: DateTime.formatIso(now),
205+
});
206+
}).pipe(Effect.ignoreCause({ log: true })),
166207
continuationRequests,
167208
});
168209
const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, {

‎packages/provider-muse/src/server/protocol.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,22 @@ export const MuseContextUsage = Schema.Struct({
148148
usedTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
149149
windowTokens: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
150150
});
151+
/** MSP `usage/changed` / `usage/read` payload: the Meta subscription windows last observed. */
152+
export const MuseSubscriptionUsage = Schema.Struct({
153+
observedAtMs: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
154+
tier: Schema.String,
155+
weekly: Schema.Struct({
156+
resetsAtMs: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
157+
usedPercent: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
158+
}),
159+
window: Schema.Struct({
160+
resetsAtMs: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
161+
usedPercent: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
162+
windowDurationMins: Schema.Finite.check(Schema.isGreaterThan(0)),
163+
}),
164+
});
165+
export type MuseSubscriptionUsage = typeof MuseSubscriptionUsage.Type;
166+
151167
export const MuseTodoList = Schema.Struct({
152168
items: Schema.Array(Schema.Struct({ text: Schema.String, status: Schema.String })),
153169
});
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
3+
import type { MuseSubscriptionUsage } from "./protocol.ts";
4+
import { museSubscriptionUsageToLimits, museSubscriptionUsageToUpdate } from "./usageLimits.ts";
5+
6+
const NOW_MS = Date.parse("2026-10-12T12:00:00.000Z");
7+
const CHECKED_AT = "2026-10-12T12:00:00.000Z";
8+
9+
const usage: MuseSubscriptionUsage = {
10+
observedAtMs: NOW_MS,
11+
tier: "meta-subscription",
12+
window: {
13+
usedPercent: 3,
14+
resetsAtMs: Date.parse("2026-10-12T14:19:00.000Z"),
15+
windowDurationMins: 300,
16+
},
17+
weekly: {
18+
usedPercent: 46,
19+
resetsAtMs: Date.parse("2026-10-19T00:00:00.000Z"),
20+
},
21+
};
22+
23+
describe("Muse subscription usage limits", () => {
24+
it("maps the session and weekly windows Muse reports", () => {
25+
expect(museSubscriptionUsageToLimits({ usage, checkedAt: CHECKED_AT, nowMs: NOW_MS })).toEqual({
26+
checkedAt: CHECKED_AT,
27+
windows: [
28+
{
29+
id: "session",
30+
kind: "session",
31+
label: "Session",
32+
usedPercent: 3,
33+
windowDurationMins: 300,
34+
resetsAt: "2026-10-12T14:19:00.000Z",
35+
},
36+
{
37+
id: "weekly",
38+
kind: "weekly",
39+
label: "Weekly",
40+
usedPercent: 46,
41+
windowDurationMins: 10080,
42+
resetsAt: "2026-10-19T00:00:00.000Z",
43+
},
44+
],
45+
});
46+
});
47+
48+
it("starts a window over empty once its reset has passed", () => {
49+
const limits = museSubscriptionUsageToLimits({
50+
usage: {
51+
...usage,
52+
window: { ...usage.window, usedPercent: 97, resetsAtMs: NOW_MS - 1 },
53+
},
54+
checkedAt: CHECKED_AT,
55+
nowMs: NOW_MS,
56+
});
57+
expect(limits.windows[0]).toEqual({
58+
id: "session",
59+
kind: "session",
60+
label: "Session",
61+
usedPercent: 0,
62+
windowDurationMins: 300,
63+
});
64+
expect(limits.windows[1]?.usedPercent).toBe(46);
65+
});
66+
67+
it("clamps over-quota percentages to the contract range and reuses the windows for live updates", () => {
68+
const update = museSubscriptionUsageToUpdate({
69+
usage: { ...usage, weekly: { ...usage.weekly, usedPercent: 130 } },
70+
nowMs: NOW_MS,
71+
});
72+
expect(update.windows.map((window) => window.usedPercent)).toEqual([3, 100]);
73+
});
74+
});
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/**
2+
* Muse subscription usage. Meta has no usage endpoint T3 can poll: Muse
3+
* reports the signed-in account's windows with each reply and forwards them
4+
* as the MSP `usage/changed` notification (the same payload `usage/read`
5+
* returns, except that a fresh host has observed nothing). The adapter hands
6+
* each report to the driver, which publishes it as the instance's
7+
* `usageLimits` and re-derives the windows from the newest report on every
8+
* status check. A window whose reset has passed starts over empty.
9+
*
10+
* @module server/usageLimits
11+
*/
12+
import type {
13+
ProviderUsageLimitsUpdate,
14+
ServerProviderUsageLimits,
15+
ServerProviderUsageWindow,
16+
} from "@t3tools/contracts";
17+
import * as DateTime from "effect/DateTime";
18+
import * as Option from "effect/Option";
19+
20+
import { clampPercent, makeUsageLimits } from "@t3tools/provider-core/server/usageLimits";
21+
import type { MuseSubscriptionUsage } from "./protocol.ts";
22+
23+
const WEEK_MINS = 7 * 24 * 60;
24+
25+
function isoFromEpochMs(value: number): string | undefined {
26+
const dt = DateTime.make(value);
27+
return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
28+
}
29+
30+
function window(input: {
31+
readonly id: string;
32+
readonly kind: ServerProviderUsageWindow["kind"];
33+
readonly label: string;
34+
readonly usedPercent: number;
35+
readonly resetsAtMs: number;
36+
readonly windowDurationMins: number;
37+
readonly nowMs: number;
38+
}): ServerProviderUsageWindow {
39+
const expired = input.resetsAtMs <= input.nowMs;
40+
const resetsAt = expired ? undefined : isoFromEpochMs(input.resetsAtMs);
41+
return {
42+
id: input.id,
43+
kind: input.kind,
44+
label: input.label,
45+
usedPercent: expired ? 0 : clampPercent(input.usedPercent),
46+
windowDurationMins: input.windowDurationMins,
47+
...(resetsAt ? { resetsAt } : {}),
48+
};
49+
}
50+
51+
/** The two subscription windows a Muse report names, as T3 limit windows. */
52+
export function museSubscriptionUsageWindows(
53+
usage: MuseSubscriptionUsage,
54+
nowMs: number,
55+
): ReadonlyArray<ServerProviderUsageWindow> {
56+
return [
57+
window({
58+
id: "session",
59+
kind: "session",
60+
label: "Session",
61+
usedPercent: usage.window.usedPercent,
62+
resetsAtMs: usage.window.resetsAtMs,
63+
windowDurationMins: usage.window.windowDurationMins,
64+
nowMs,
65+
}),
66+
window({
67+
id: "weekly",
68+
kind: "weekly",
69+
label: "Weekly",
70+
usedPercent: usage.weekly.usedPercent,
71+
resetsAtMs: usage.weekly.resetsAtMs,
72+
windowDurationMins: WEEK_MINS,
73+
nowMs,
74+
}),
75+
];
76+
}
77+
78+
export function museSubscriptionUsageToLimits(input: {
79+
readonly usage: MuseSubscriptionUsage;
80+
readonly checkedAt: string;
81+
readonly nowMs: number;
82+
}): ServerProviderUsageLimits {
83+
return makeUsageLimits({
84+
checkedAt: input.checkedAt,
85+
windows: museSubscriptionUsageWindows(input.usage, input.nowMs),
86+
});
87+
}
88+
89+
export function museSubscriptionUsageToUpdate(input: {
90+
readonly usage: MuseSubscriptionUsage;
91+
readonly nowMs: number;
92+
}): ProviderUsageLimitsUpdate {
93+
return { windows: [...museSubscriptionUsageWindows(input.usage, input.nowMs)] };
94+
}

0 commit comments

Comments
 (0)