diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts index b6b40ab8b60ac..3de2689cbe3d2 100644 --- a/apps/server/src/usage/UsageLimitSources.test.ts +++ b/apps/server/src/usage/UsageLimitSources.test.ts @@ -28,6 +28,14 @@ import * as UsageLimitSources from "./UsageLimitSources.ts"; const encodeConfigEvent = Schema.encodeSync(ServerConfigStreamEvent); +// Closura: a host with no gateway named in its configs still probes the fleet's loopback gateway +// links. These fixtures answer every request themselves, so the probe stays off unless a test asks. +const setFleetGatewayProbe = (value: "off" | undefined) => { + if (value === undefined) delete process.env.T3CODE_MAGPIE_FLEET_GATEWAYS; + else process.env.T3CODE_MAGPIE_FLEET_GATEWAYS = value; +}; +setFleetGatewayProbe("off"); + it.effect("keeps malformed source URLs encodable for config subscribers", () => Effect.gen(function* () { const sources = yield* UsageLimitSources.make; @@ -686,3 +694,54 @@ it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold t expect(yield* Fiber.join(stalled)).toBeNull(); }), ); + +it.effect("a host that names no gateway still shows the fleet's loopback Magpie gateway", () => { + setFleetGatewayProbe(undefined); + const urls: string[] = []; + const card = { + provider: "codex", + user: "first@example.com", + windows: [{ name: "5 hours", used: 40, resetsAt: "2027-01-01T00:00:00.000Z" }], + }; + return Effect.gen(function* () { + const sources = yield* UsageLimitSources.make; + yield* sources.refresh; + const snapshots = yield* sources.current; + // The ASUS-local port refuses the connection; the loopback link answers. + expect(snapshots.map(({ id, kind, origin }) => ({ id, kind, origin }))).toEqual([ + { id: "magpie:127.0.0.1:13425", kind: "magpie", origin: "http://127.0.0.1:13425" }, + ]); + expect(snapshots[0]?.accounts.map((account) => account.driver)).toEqual(["codex"]); + expect(urls.every((url) => url.endsWith("/v1/magpie/quotas"))).toBe(true); + // A manual refresh must not drop the row, and must not POST a live refresh to a gateway no route names. + yield* sources.refreshLive; + expect((yield* sources.current).map(({ id }) => id)).toEqual(["magpie:127.0.0.1:13425"]); + expect(urls.some((url) => url.includes("/refresh"))).toBe(false); + }).pipe( + Effect.provide([ + ServerSettings.layerTest({}), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunScopeWork: () => Effect.succeed(false), + }), + Layer.succeed(SecretResolver.SecretResolver, { + label: (provider) => Effect.succeed(provider), + read: (references) => Effect.succeed(references.map(() => undefined)), + invalidate: () => Effect.void, + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + urls.push(request.url); + return request.url.startsWith("http://127.0.0.1:13425/") + ? HttpClientResponse.fromWeb(request, Response.json({ data: [card] })) + : HttpClientResponse.fromWeb(request, new Response("no gateway", { status: 502 })); + }), + ), + ), + NodeCrypto.layer, + NodeServices.layer, + ]), + Effect.ensuring(Effect.sync(() => setFleetGatewayProbe("off"))), + ); +}); diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index 2d2f2656fc92f..3c27c2465cbfd 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -403,6 +403,25 @@ export const make = Effect.gen(function* () { ), { concurrency: 1 }, ); + // Closura: a gateway only the fleet's loopback links reach keeps its row through a manual + // refresh. It is read without the live POST: no route names it, so there is no driver to refresh. + const fleetOrigins = + settings === null + ? [] + : (yield* discoverGatewayOrigins(settings, process.env).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.orElseSucceed((): ReadonlyArray => []), + )).filter((origin) => !explicit.has(origin) && !discoveredOrigins.includes(origin)); + const fleetReads = yield* Effect.forEach( + fleetOrigins, + (origin) => + magpie.readAccounts({ url: origin, managementKey: "" }).pipe( + Effect.map((accounts) => ({ origin, accounts })), + Effect.option, + ), + { concurrency: 4 }, + ); const checkedAt = DateTime.formatIso(yield* DateTime.now); const seenAccounts = new Set([ ...snapshots.map((source) => accountSet(source.accounts)), @@ -414,7 +433,7 @@ export const make = Effect.gen(function* () { const origin = read.snapshot.origin; if (read.live && origin) liveByOrigin.set(origin, read.snapshot); } - for (const read of discoveredReads) { + for (const read of [...discoveredReads, ...fleetReads]) { if (read._tag === "None") continue; const key = accountSet(read.value.accounts); if (seenAccounts.has(key)) continue; diff --git a/apps/server/src/usage/magpieQuotas.test.ts b/apps/server/src/usage/magpieQuotas.test.ts index 5283aad36bc97..c885e30c767f6 100644 --- a/apps/server/src/usage/magpieQuotas.test.ts +++ b/apps/server/src/usage/magpieQuotas.test.ts @@ -11,6 +11,7 @@ import { codexPlanLabel } from "../provider/CodexProvider.ts"; import { codexBaseUrl, discoverGatewayOrigins, + FLEET_MAGPIE_LOOPBACK_ORIGINS, gatewayOrigin, isPrivateOrigin, magpieQuotasToAccounts, @@ -393,6 +394,47 @@ describe("gateway discovery", () => { expect(origins).toEqual(["http://127.0.0.1:13425", "http://127.0.0.1:3425"]); }), ); + + it.effect( + "still offers the fleet loopback gateways to a host whose instances name no gateway", + () => + Effect.gen(function* () { + const settings = { + providerInstances: { + [ProviderInstanceId.make("codex")]: { + driver: ProviderDriverKind.make("codex"), + enabled: true, + // A native sign-in: the config names no gateway. + config: { homePath: "/codex-home" }, + }, + }, + } as unknown as Pick; + const origins = yield* discoverGatewayOrigins(settings, { HOME: "/home/u" }).pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + readFileString: (path) => + Effect.succeed( + path === "/codex-home/config.toml" + ? 'model_provider = "m"\n[model_providers.m]\nbase_url = "http://192.168.0.27:3425/v1"\n' + : "", + ), + }), + ), + Effect.provide(NodeServices.layer), + ); + // A named gateway comes first; the fleet links follow without duplicates. + expect(origins).toEqual(["http://192.168.0.27:3425", ...FLEET_MAGPIE_LOOPBACK_ORIGINS]); + const bare = yield* discoverGatewayOrigins( + { providerInstances: {} } as unknown as Pick, + { HOME: "/home/u" }, + ).pipe( + Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})), + Effect.provide(NodeServices.layer), + ); + expect(bare).toEqual([...FLEET_MAGPIE_LOOPBACK_ORIGINS]); + }), + ); }); describe("makeMagpieApi", () => { diff --git a/apps/server/src/usage/magpieQuotas.ts b/apps/server/src/usage/magpieQuotas.ts index 5365288054783..28c8f41ca3d43 100644 --- a/apps/server/src/usage/magpieQuotas.ts +++ b/apps/server/src/usage/magpieQuotas.ts @@ -609,13 +609,34 @@ export const discoverMagpieRoutes = Effect.fn("discoverMagpieRoutes")(function* }); /** - * Distinct gateway origins the enabled provider instances send requests to. - * A file that is missing or unreadable contributes nothing. + * Closura: the fleet reads one quota source, the ASUS Magpie gateway, over each + * host's loopback link (13425) or the gateway's own port on ASUS (3425). A host + * whose provider instances sign in natively names no gateway in its configs, so + * discovery alone showed it a different Usage panel from its peers (CLO-1348). + * Loopback answers the quotas route without a key; a port with no gateway + * behind it refuses the connection and is dropped like any other non-answer. + * `T3CODE_MAGPIE_FLEET_GATEWAYS=off` leaves discovery to the instance configs. + */ +export const FLEET_MAGPIE_LOOPBACK_ORIGINS: ReadonlyArray = [ + "http://127.0.0.1:13425", + "http://127.0.0.1:3425", +]; + +/** + * Distinct gateway origins the enabled provider instances send requests to, + * then the fleet's loopback gateway links. A file that is missing or unreadable + * contributes nothing. */ export const discoverGatewayOrigins = Effect.fn("discoverGatewayOrigins")(function* ( settings: Pick, env: NodeJS.ProcessEnv, ) { const routes = yield* discoverMagpieRoutes(settings, env); - return [...new Set(routes.map((route) => route.origin))]; + const fleet = env.T3CODE_MAGPIE_FLEET_GATEWAYS?.trim().toLowerCase() === "off"; + return [ + ...new Set([ + ...routes.map((route) => route.origin), + ...(fleet ? [] : FLEET_MAGPIE_LOOPBACK_ORIGINS), + ]), + ]; });