@devries-cameron20 / t3code Mirror · read-only / commits / 9e60e945d2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 13:15 UTC

fix(usage): keep host identity across container recreation (#25220)

Co-authored-by: maria <254055478+maria-rcks@users.noreply.github.com>

maria committed Oct 29, 2026 at 18:04 UTC 9e60e945d27a27f6505d0718122473454ce4afae
3 files changed +125 -3
apps/server/src/usage/UsageService.test.ts
+89
@@ -142,6 +142,7 @@ const layerService = (input: {
142 ) => Effect.Effect<Response, HttpClientError.HttpClientError>;
143 readonly environment?: NodeJS.ProcessEnv;
144 readonly platform?: NodeJS.Platform;
145 + readonly hostname?: string;
146 }) =>
147 layerCursorUsageAccounts(
148 CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)),
@@ -157,6 +158,7 @@ const layerService = (input: {
158 ),
159 Layer.provideMerge(NodeServices.layer),
160 Layer.provideMerge(Layer.succeed(HostProcess.Platform, input.platform ?? "linux")),
161 + Layer.provideMerge(Layer.succeed(HostProcess.Hostname, input.hostname ?? "usage-test-host")),
162 Layer.provideMerge(ServerSettings.layerTest(input.settings)),
163 Layer.provideMerge(
164 Layer.succeed(
@@ -465,6 +467,93 @@ describe("Codex usage history", () => {
467 });
468
469 describe("UsageService", () => {
470 + it.live("keeps the first host identity across recreation and explicit override removal", () =>
471 + Effect.gen(function* () {
472 + const { transcript, settings, home } = yield* setup;
473 + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
474 + for (const [hostname, override, expected] of [
475 + ["container-a", undefined, "container-a"],
476 + ["container-b", undefined, "container-a"],
477 + ["container-c", "physical-host", "physical-host"],
478 + ["container-d", undefined, "container-a"],
479 + ] as const) {
480 + const summary = yield* Effect.gen(function* () {
481 + const service = yield* UsageService.make;
482 + return yield* service.readSummary(WINDOW);
483 + }).pipe(
484 + Effect.scoped,
485 + Effect.provide(
486 + layerService({
487 + prefix: "usage-host-id",
488 + home,
489 + settings,
490 + hostname,
491 + environment: override === undefined ? {} : { T3CODE_HOST_ID: override },
492 + }),
493 + ),
494 + );
495 + const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
496 + assert.strictEqual(source?.fingerprint.hostId, expected);
497 + }
498 + }).pipe(Effect.scoped),
499 + );
500 +
501 + it.live("concurrent initialization keeps one host identity across service recreation", () =>
502 + Effect.gen(function* () {
503 + const { transcript, settings, home } = yield* setup;
504 + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
505 + const prefix = "usage-host-id-race";
506 + const hostIdPath = NodePath.join(home, prefix, "usage-host-id");
507 + const bothRead = yield* Deferred.make<void>();
508 + let reads = 0;
509 + const summaries = yield* Effect.forEach(
510 + ["container-a", "container-b"],
511 + (hostname) =>
512 + Effect.gen(function* () {
513 + const fileSystem = yield* FileSystem.FileSystem;
514 + let firstRead = true;
515 + const service = yield* UsageService.make.pipe(
516 + Effect.provideService(FileSystem.FileSystem, {
517 + ...fileSystem,
518 + readFileString: (path, encoding) =>
519 + Effect.gen(function* () {
520 + if (path !== hostIdPath || !firstRead) {
521 + return yield* fileSystem.readFileString(path, encoding);
522 + }
523 + firstRead = false;
524 + // Both instances observe the missing file before either can create it.
525 + const result = yield* Effect.exit(fileSystem.readFileString(path, encoding));
526 + reads += 1;
527 + if (reads === 2) yield* Deferred.succeed(bothRead, undefined);
528 + yield* Deferred.await(bothRead);
529 + return yield* result;
530 + }),
531 + }),
532 + );
533 + return yield* service.readSummary(WINDOW);
534 + }).pipe(
535 + Effect.scoped,
536 + Effect.provide(layerService({ prefix, home, settings, hostname })),
537 + ),
538 + { concurrency: "unbounded" },
539 + );
540 + const persisted = yield* Effect.promise(() => NodeFSP.readFile(hostIdPath, "utf8"));
541 + const hostId = persisted.trim();
542 + assert.include(["container-a", "container-b"], hostId);
543 + const restarted = yield* Effect.gen(function* () {
544 + const service = yield* UsageService.make;
545 + return yield* service.readSummary(WINDOW);
546 + }).pipe(
547 + Effect.scoped,
548 + Effect.provide(layerService({ prefix, home, settings, hostname: "container-c" })),
549 + );
550 + for (const summary of [...summaries, restarted]) {
551 + const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
552 + assert.strictEqual(source?.fingerprint.hostId, hostId);
553 + }
554 + }).pipe(Effect.scoped),
555 + );
556 +
557 it.live(
558 "repairs initial Codex prices after unchanged-file retries, persists evidence and corrections, and honors later native tiers",
559 () =>
apps/server/src/usage/UsageService.ts
+32 -3
@@ -1,5 +1,3 @@
1 -import * as NodeOS from "node:os";
2 -
1 import {
2 type ProviderInstanceConfig,
3 ProviderInstanceId,
@@ -155,6 +153,7 @@ export const make = Effect.gen(function* () {
153 const settingsService = yield* ServerSettings.ServerSettingsService;
154 const httpClient = yield* HttpClient.HttpClient;
155 const hostEnvironment = yield* HostProcess.Environment;
156 + const hostname = yield* HostProcess.Hostname;
157 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
158
159 const fileCache: ScanCache = new Map();
@@ -177,6 +176,37 @@ export const make = Effect.gen(function* () {
176 Effect.provideService(FileSystem.FileSystem, fileSystem),
177 Effect.provideService(Path.Path, path),
178 );
179 + const hostIdPath = path.join(config.baseDir, "usage-host-id");
180 + const explicitHostId = hostEnvironment["T3CODE_HOST_ID"]?.trim();
181 + const hostId =
182 + explicitHostId ||
183 + (yield* fileSystem.readFileString(hostIdPath).pipe(
184 + Effect.catchIf(
185 + (error) => error.reason._tag === "NotFound",
186 + () =>
187 + Effect.scoped(
188 + Effect.gen(function* () {
189 + yield* fileSystem.makeDirectory(config.baseDir, { recursive: true });
190 + const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
191 + directory: config.baseDir,
192 + prefix: "usage-host-id.",
193 + });
194 + const tempFile = path.join(tempDirectory, "identity");
195 + yield* fileSystem.writeFileString(tempFile, `${hostname}\n`);
196 + // Publish complete contents without replacing another initializer's identity.
197 + yield* fileSystem.link(tempFile, hostIdPath).pipe(
198 + Effect.catchIf(
199 + (error) => error.reason._tag === "AlreadyExists",
200 + () => Effect.void,
201 + ),
202 + );
203 + return yield* fileSystem.readFileString(hostIdPath);
204 + }),
205 + ),
206 + ),
207 + Effect.map((value) => value.trim() || hostname),
208 + Effect.orElseSucceed(() => hostname),
209 + ));
210 let rates: RateTable = new Map();
211 let ratesFetchedAtMs: number | null = null;
212 let ratesLastFailedAtMs: number | null = null;
@@ -664,7 +694,6 @@ export const make = Effect.gen(function* () {
694 const startedAtMs = yield* Clock.currentTimeMillis;
695 yield* ensureScanCacheLoaded;
696
667 - const hostId = NodeOS.hostname();
697 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
698 if (Option.isNone(windowStart)) {
699 return yield* new UsageReadError({
docs/user/usage.md
+4
@@ -43,6 +43,10 @@ Use absolute paths or `~/` paths in the account's environment settings; relative
43 depend on each project's working directory and cannot be reliably discovered by Usage. Accounts
44 sharing a history directory count once.
45
46 +The server saves its first hostname in `<T3 home>/usage-host-id`, so a recreated container keeps
47 +its usage identity when T3 home is persisted. Set `T3CODE_HOST_ID` to choose the identity
48 +explicitly.
49 +
50 When your app and server support different providers, usage totals may cover only the providers
51 your app understands. Update the app to include newly supported providers.
52