Skip to content

Commit 6fee75b

Browse files
author
Shaun Hawk
committed
fix(muse): keep refreshes nonblocking and isolate account labels
1 parent f4175fb commit 6fee75b

5 files changed

Lines changed: 249 additions & 32 deletions

File tree

‎packages/provider-core/src/server/managedProvider.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,68 @@ describe("makeManagedServerProvider", () => {
539539
).pipe(Effect.provide(layerAlwaysRunTest)),
540540
);
541541

542+
it.effect.each([
543+
{ name: "label to label", from: { label: "Team A" }, to: { label: "Team B" }, switched: true },
544+
{
545+
name: "label to email",
546+
from: { label: "Team A" },
547+
to: { email: "[email protected]" },
548+
switched: true,
549+
},
550+
{
551+
name: "email to label",
552+
from: { email: "[email protected]" },
553+
to: { label: "Team B" },
554+
switched: true,
555+
},
556+
{ name: "same label", from: { label: "Team A" }, to: { label: "Team A" }, switched: false },
557+
{
558+
name: "same email with different casing",
559+
from: { email: "[email protected]" },
560+
to: { email: "[email protected]" },
561+
switched: false,
562+
},
563+
])("keeps usage with its account on $name refreshes", ({ from, to, switched }) =>
564+
Effect.scoped(
565+
Effect.gen(function* () {
566+
const published = {
567+
checkedAt: "2026-04-10T00:05:00.000Z",
568+
windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 80 }],
569+
} as const;
570+
const probed = {
571+
checkedAt: "2026-04-10T00:01:00.000Z",
572+
windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 10 }],
573+
} as const;
574+
const provider = yield* makeManagedServerProvider<TestSettings>({
575+
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
576+
getSettings: Effect.succeed({ enabled: true }),
577+
streamSettings: Stream.empty,
578+
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
579+
initialSnapshot: () =>
580+
Effect.succeed({
581+
...refreshedSnapshot,
582+
auth: { status: "authenticated", type: "accountLogin", ...from },
583+
usageLimits: published,
584+
}),
585+
checkProvider: Effect.succeed({
586+
...refreshedSnapshot,
587+
auth: { status: "authenticated", type: "accountLogin", ...to },
588+
usageLimits: probed,
589+
}),
590+
refreshOnInterval: false,
591+
});
592+
assert.deepStrictEqual(
593+
(yield* provider.refresh).usageLimits,
594+
switched ? probed : published,
595+
);
596+
assert.deepStrictEqual(
597+
(yield* provider.refresh).usageLimits,
598+
switched ? probed : published,
599+
);
600+
}),
601+
).pipe(Effect.provide(layerProviderHost({ runBackgroundWork: false }))),
602+
);
603+
542604
it.effect("keeps sparse usage unavailable after probe failure until a full probe recovers", () =>
543605
Effect.scoped(
544606
Effect.gen(function* () {

‎packages/provider-core/src/server/managedProvider.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,11 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
158158
const previous = state.snapshot.auth;
159159
const differs = (a: string | undefined, b: string | undefined) =>
160160
a !== undefined && b !== undefined && a !== b;
161+
// Some account logins identify the account by display label instead of email.
162+
const identity = (auth: ServerProvider["auth"]) =>
163+
auth.email?.toLowerCase() ?? (auth.type === "accountLogin" ? auth.label : undefined);
161164
const switchedAccount =
162-
differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) ||
165+
differs(identity(probedSnapshot.auth), identity(previous)) ||
163166
(probedSnapshot.auth.workspaceId !== undefined &&
164167
probedSnapshot.auth.workspaceId !== previous.workspaceId);
165168
const usageLimits = switchedAccount

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

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,8 @@ export const MuseDriver: ProviderDriver<
120120
const latestUsage = yield* Ref.make<
121121
{ readonly usage: MuseSubscriptionUsage; readonly generation: number } | undefined
122122
>(undefined);
123-
// Reports and status checks take turns, so an older report cannot publish after a
124-
// newer one, and none publishes for a generation a check has just replaced.
123+
// Serialize state changes and publication; CLI reads run outside this permit
124+
// so slow refreshes cannot block the adapter's notification stream.
125125
const usagePermit = yield* Semaphore.make(1);
126126
const withUsageLimits = Effect.fn("MuseDriver.withUsageLimits")(function* (
127127
provider: ServerProviderDraft,
@@ -131,13 +131,10 @@ export const MuseDriver: ProviderDriver<
131131
environment: processEnvironment,
132132
cwd,
133133
provider,
134-
account: yield* Ref.get(usageAccount),
135-
latestUsage: yield* Ref.get(latestUsage),
134+
state: { account: usageAccount, latestUsage, permit: usagePermit },
136135
});
137-
yield* Ref.set(usageAccount, refreshed.account);
138-
yield* Ref.set(latestUsage, refreshed.latestUsage);
139136
return refreshed.provider;
140-
}, usagePermit.withPermits(1));
137+
});
141138
const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(
142139
resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, {
143140
binaryPath: effectiveConfig.binaryPath,

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

Lines changed: 121 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ import * as Schema from "effect/Schema";
1010
import * as TestClock from "effect/testing/TestClock";
1111
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1212
import { MuseSettings } from "../settings.ts";
13-
import { refreshMuseUsage } from "./usageProbe.ts";
13+
import { refreshMuseUsage as refreshState, type MuseUsageReport } from "./usageProbe.ts";
14+
import type { MuseUsageAccount } from "./usageLimits.ts";
15+
import * as Ref from "effect/Ref";
16+
import * as Semaphore from "effect/Semaphore";
1417

1518
const settings = Schema.decodeEffect(MuseSettings);
1619

@@ -72,6 +75,22 @@ const fixture = (source = `process.stdout.write(${JSON.stringify(JSON.stringify(
7275
};
7376
});
7477

78+
const refreshMuseUsage = Effect.fn("test.refreshMuseUsage")(function* (
79+
input: Omit<Parameters<typeof refreshState>[0], "state"> & {
80+
readonly account: MuseUsageAccount;
81+
readonly latestUsage: MuseUsageReport | undefined;
82+
},
83+
) {
84+
return yield* refreshState({
85+
...input,
86+
state: {
87+
account: yield* Ref.make(input.account),
88+
latestUsage: yield* Ref.make(input.latestUsage),
89+
permit: yield* Semaphore.make(1),
90+
},
91+
});
92+
});
93+
7594
it.layer(NodeServices.layer)("Muse CLI usage refresh", (it) => {
7695
it.effect("fills limits on the first status refresh without a model turn", () =>
7796
Effect.scoped(
@@ -212,6 +231,8 @@ it.layer(NodeServices.layer)("Muse CLI usage refresh", (it) => {
212231
{ ...provider, auth: { status: "unknown" } },
213232
{ ...provider, enabled: false },
214233
{ ...provider, status: "error" },
234+
{ ...provider, version: "1.4.12-R6909.1" },
235+
{ ...provider, version: null },
215236
];
216237
for (const candidate of cases) {
217238
const refreshed = yield* refreshMuseUsage({
@@ -230,6 +251,105 @@ it.layer(NodeServices.layer)("Muse CLI usage refresh", (it) => {
230251
),
231252
);
232253

254+
it.effect(
255+
"publishes a notification while the CLI read is stalled and retains the newer report",
256+
() =>
257+
Effect.scoped(
258+
Effect.gen(function* () {
259+
const input = yield* fixture();
260+
const state = {
261+
account: yield* Ref.make<MuseUsageAccount>(account),
262+
latestUsage: yield* Ref.make<MuseUsageReport | undefined>(report),
263+
permit: yield* Semaphore.make(1),
264+
};
265+
const started = yield* Deferred.make<void>();
266+
const release = yield* Deferred.make<void>();
267+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
268+
const pending = yield* refreshState({
269+
...input,
270+
provider: { ...provider, auth: { ...provider.auth, email: "[email protected]" } },
271+
state,
272+
}).pipe(
273+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, {
274+
...spawner,
275+
spawn: (command) =>
276+
Deferred.succeed(started, undefined).pipe(
277+
Effect.andThen(Deferred.await(release)),
278+
Effect.andThen(spawner.spawn(command)),
279+
),
280+
}),
281+
Effect.forkChild,
282+
);
283+
yield* Deferred.await(started);
284+
expect(yield* Ref.get(state.account)).toEqual({
285+
generation: 1,
286+
identity: "[email protected]",
287+
});
288+
const newer = {
289+
...report,
290+
generation: 1,
291+
usage: {
292+
...report.usage,
293+
observedAtMs: observedAtMs + 1,
294+
window: { ...report.usage.window, usedPercent: 10 },
295+
},
296+
};
297+
const published = yield* Deferred.make<void>();
298+
yield* state.permit.withPermits(1)(
299+
Ref.set(state.latestUsage, newer).pipe(
300+
Effect.andThen(Deferred.succeed(published, undefined)),
301+
),
302+
);
303+
yield* Deferred.await(published);
304+
expect(yield* Ref.get(state.latestUsage)).toBe(newer);
305+
yield* Deferred.succeed(release, undefined);
306+
const refreshed = yield* Fiber.join(pending);
307+
expect(refreshed.latestUsage).toBe(newer);
308+
expect(refreshed.provider.usageLimits?.windows[0]?.usedPercent).toBe(10);
309+
}),
310+
),
311+
);
312+
313+
it.effect("discards an in-flight read after the account generation changes", () =>
314+
Effect.scoped(
315+
Effect.gen(function* () {
316+
const input = yield* fixture();
317+
const state = {
318+
account: yield* Ref.make<MuseUsageAccount>(account),
319+
latestUsage: yield* Ref.make<MuseUsageReport | undefined>(report),
320+
permit: yield* Semaphore.make(1),
321+
};
322+
const started = yield* Deferred.make<void>();
323+
const release = yield* Deferred.make<void>();
324+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
325+
const pending = yield* refreshState({ ...input, state }).pipe(
326+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, {
327+
...spawner,
328+
spawn: (command) =>
329+
Deferred.succeed(started, undefined).pipe(
330+
Effect.andThen(Deferred.await(release)),
331+
Effect.andThen(spawner.spawn(command)),
332+
),
333+
}),
334+
Effect.forkChild,
335+
);
336+
yield* Deferred.await(started);
337+
const signedOut = { generation: 1, identity: null };
338+
yield* state.permit.withPermits(1)(
339+
Ref.set(state.account, signedOut).pipe(
340+
Effect.andThen(Ref.set(state.latestUsage, undefined)),
341+
),
342+
);
343+
yield* Deferred.succeed(release, undefined);
344+
const refreshed = yield* Fiber.join(pending);
345+
expect(refreshed.account).toBe(signedOut);
346+
expect(refreshed.latestUsage).toBeUndefined();
347+
expect(refreshed.provider.usageLimits).toBeUndefined();
348+
expect(yield* Ref.get(state.account)).toBe(signedOut);
349+
}),
350+
),
351+
);
352+
233353
it.effect("bounds a stalled CLI read and keeps the last observation", () =>
234354
Effect.scoped(
235355
Effect.gen(function* () {

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

Lines changed: 58 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell";
55
import * as DateTime from "effect/DateTime";
66
import * as Effect from "effect/Effect";
77
import * as Schema from "effect/Schema";
8+
import * as Ref from "effect/Ref";
9+
import * as Semaphore from "effect/Semaphore";
810
import * as ChildProcess from "effect/process/ChildProcess";
911
import { MuseSubscriptionUsage } from "./protocol.ts";
12+
import { compareMuseVersions } from "./maintenance.ts";
1013
import {
1114
museStatusUsageLimits,
1215
nextMuseUsageAccount,
@@ -65,38 +68,70 @@ export interface MuseUsageReport {
6568
readonly generation: number;
6669
}
6770

71+
export interface MuseUsageState {
72+
readonly account: Ref.Ref<MuseUsageAccount>;
73+
readonly latestUsage: Ref.Ref<MuseUsageReport | undefined>;
74+
readonly permit: Semaphore.Semaphore;
75+
}
76+
6877
export const refreshMuseUsage = Effect.fn("MuseUsageProbe.refresh")(function* (input: {
6978
readonly settings: MuseSettings;
7079
readonly environment: NodeJS.ProcessEnv;
7180
readonly cwd?: string;
7281
readonly provider: ServerProviderDraft;
73-
readonly account: MuseUsageAccount;
74-
readonly latestUsage: MuseUsageReport | undefined;
82+
readonly state: MuseUsageState;
7583
}) {
76-
const { provider } = input;
77-
const account = nextMuseUsageAccount(input.account, provider.auth);
78-
const dropped =
79-
input.latestUsage !== undefined && input.latestUsage.generation !== account.generation;
80-
let latestUsage = dropped ? undefined : input.latestUsage;
81-
if (
84+
const { provider, state } = input;
85+
const { account: initialAccount, dropped } = yield* state.permit.withPermits(1)(
86+
Effect.gen(function* () {
87+
const account = nextMuseUsageAccount(yield* Ref.get(state.account), provider.auth);
88+
const latest = yield* Ref.get(state.latestUsage);
89+
const dropped = latest !== undefined && latest.generation !== account.generation;
90+
yield* Ref.set(state.account, account);
91+
if (dropped) yield* Ref.set(state.latestUsage, undefined);
92+
return { account, dropped };
93+
}),
94+
);
95+
const canRead =
8296
provider.enabled &&
8397
provider.installed &&
8498
provider.status !== "error" &&
8599
provider.auth.status === "authenticated" &&
86100
provider.auth.type === "accountLogin" &&
87-
account.identity != null
88-
) {
89-
const usage = yield* readMuseUsage(input.settings, input.environment, input.cwd);
90-
if (usage && (!latestUsage || usage.observedAtMs > latestUsage.usage.observedAtMs)) {
91-
latestUsage = { usage, generation: account.generation };
92-
}
93-
}
94-
const usageLimits = museStatusUsageLimits({
95-
auth: provider.auth,
96-
enabled: provider.enabled,
97-
observation: latestUsage?.usage,
98-
dropped,
99-
nowMs: DateTime.toEpochMillis(yield* DateTime.now),
100-
});
101-
return { account, latestUsage, provider: { ...provider, usageLimits } };
101+
initialAccount.identity != null &&
102+
provider.version !== null &&
103+
compareMuseVersions(provider.version, "1.4.13") >= 0;
104+
// Network I/O must not hold the permit shared with inline usage notifications.
105+
const usage = canRead
106+
? yield* readMuseUsage(input.settings, input.environment, input.cwd)
107+
: undefined;
108+
return yield* state.permit.withPermits(1)(
109+
Effect.gen(function* () {
110+
const currentAccount = yield* Ref.get(state.account);
111+
const previous = yield* Ref.get(state.latestUsage);
112+
// Another refresh changed accounts while this CLI read was in flight.
113+
if (currentAccount !== initialAccount) {
114+
return {
115+
account: currentAccount,
116+
latestUsage: previous,
117+
provider: { ...provider, usageLimits: undefined },
118+
};
119+
}
120+
const account = currentAccount;
121+
let latestUsage = previous;
122+
if (usage && (!latestUsage || usage.observedAtMs > latestUsage.usage.observedAtMs)) {
123+
latestUsage = { usage, generation: account.generation };
124+
}
125+
const usageLimits = museStatusUsageLimits({
126+
auth: provider.auth,
127+
enabled: provider.enabled,
128+
observation: latestUsage?.usage,
129+
dropped,
130+
nowMs: DateTime.toEpochMillis(yield* DateTime.now),
131+
});
132+
yield* Ref.set(state.account, account);
133+
yield* Ref.set(state.latestUsage, latestUsage);
134+
return { account, latestUsage, provider: { ...provider, usageLimits } };
135+
}),
136+
);
102137
});

0 commit comments

Comments
 (0)