Skip to content

Commit 5988add

Browse files
fix(server): usage identity recovers once a transcript directory appears
A directory that did not exist on the first usage read kept no physical source id until restart, so Windows and WSL kept counting it twice. Only resolved ids are cached now. The desktop host scope is also persisted on first launch, when the state directory may not exist yet, so it stays stable across restarts. Also fixes the reader test's use of mountPoint before declaration, hoists its summary decoder, fixes the reader-scan tuple type, adds path compression to the merge's alias union-find, and covers the forwarded scope in the desktop configuration tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 31605ff commit 5988add

6 files changed

Lines changed: 101 additions & 18 deletions

File tree

‎apps/desktop/src/backend/DesktopBackendConfiguration.test.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,43 @@ describe("DesktopBackendConfiguration", () => {
678678
),
679679
);
680680

681+
it.effect("gives the Windows and WSL backends one host scope that survives a restart", () =>
682+
Effect.gen(function* () {
683+
const fileSystem = yield* FileSystem.FileSystem;
684+
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
685+
prefix: "t3-desktop-backend-config-test-",
686+
});
687+
const launch = Effect.gen(function* () {
688+
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
689+
const primary = yield* configuration.resolvePrimary;
690+
const wsl = yield* configuration.resolveWsl({ port: 5050, distro: null });
691+
assert.equal(wsl.env.T3CODE_DESKTOP_HOST_SCOPE, primary.env.T3CODE_DESKTOP_HOST_SCOPE);
692+
assert.include((wsl.env.WSLENV ?? "").split(":"), "T3CODE_DESKTOP_HOST_SCOPE");
693+
return primary.env.T3CODE_DESKTOP_HOST_SCOPE;
694+
}).pipe(
695+
Effect.provide(
696+
layerBackendConfiguration().pipe(
697+
Layer.provideMerge(layerServerExposure),
698+
Layer.provideMerge(DesktopAppSettings.layerTest()),
699+
Layer.provideMerge(DesktopWslServerTree.layerTest()),
700+
Layer.provideMerge(
701+
DesktopWslEnvironment.layerTest({
702+
isAvailable: true,
703+
windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
704+
getDistroIp: () => Option.some("172.27.0.99"),
705+
}),
706+
),
707+
Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
708+
),
709+
),
710+
);
711+
712+
const first = yield* launch;
713+
assert.match(first ?? "", /^[0-9a-f]{32}$/);
714+
assert.equal(yield* launch, first);
715+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
716+
);
717+
681718
it.effect("resolveWsl carries the kill switch into the distro", () =>
682719
Effect.gen(function* () {
683720
const fileSystem = yield* FileSystem.FileSystem;
@@ -763,7 +800,7 @@ describe("DesktopBackendConfiguration", () => {
763800
assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf");
764801
assert.equal(
765802
config.env.WSLENV,
766-
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
803+
"GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:T3CODE_DESKTOP_HOST_SCOPE:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
767804
);
768805
}).pipe(
769806
Effect.provide(

‎apps/desktop/src/backend/DesktopBackendConfiguration.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -267,13 +267,12 @@ const readOrCreateHostScope = Effect.gen(function* () {
267267
.pipe(Effect.orElseSucceed(() => ""))).trim();
268268
if (HOST_SCOPE_PATTERN.test(existing)) return existing;
269269
const scope = (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "");
270-
yield* fileSystem
271-
.writeFileString(scopePath, scope)
272-
.pipe(
273-
Effect.catch((cause) =>
274-
Effect.logWarning("Could not persist the desktop host scope.", { cause }),
275-
),
276-
);
270+
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }).pipe(
271+
Effect.andThen(fileSystem.writeFileString(scopePath, scope)),
272+
Effect.catch((cause) =>
273+
Effect.logWarning("Could not persist the desktop host scope.", { cause }),
274+
),
275+
);
277276
return scope;
278277
});
279278

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts";
4848
import * as ProviderHostLive from "../provider/ProviderHostLive.ts";
4949
import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
5050
import * as UsageService from "./UsageService.ts";
51+
import { DESKTOP_HOST_SCOPE_ENV, physicalSourceIdOf } from "./usageTranscriptReader.ts";
5152
import { encodeScanCache, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts";
5253

5354
vi.mock("node:fs/promises", { spy: true });
@@ -860,6 +861,39 @@ describe("UsageService", () => {
860861
}).pipe(Effect.scoped),
861862
);
862863

864+
it.live("identifies a transcript directory created after the server first read usage", () =>
865+
Effect.gen(function* () {
866+
const { home, settings } = yield* setup;
867+
const scope = "0123456789abcdef0123456789abcdef";
868+
const dir = NodePath.join(home, "pi", "sessions");
869+
yield* Effect.gen(function* () {
870+
const service = yield* UsageService.make;
871+
const piFingerprint = (summary: UsageSummary) =>
872+
summary.sources.find((source) => source.fingerprint.provider === "pi")?.fingerprint;
873+
const missing = piFingerprint(yield* service.readSummary(WINDOW));
874+
assert.strictEqual(missing?.resolvedHomePath, dir);
875+
assert.isUndefined(missing?.physicalSourceId);
876+
yield* Effect.promise(() => NodeFSP.mkdir(dir, { recursive: true }));
877+
assert.strictEqual(
878+
piFingerprint(yield* service.readSummary(WINDOW))?.physicalSourceId,
879+
physicalSourceIdOf(scope, yield* Effect.promise(() => NodeFSP.realpath(dir))),
880+
);
881+
}).pipe(
882+
Effect.scoped,
883+
Effect.provide(
884+
layerService({
885+
prefix: "usage-physical-source-created",
886+
home,
887+
settings,
888+
// The native Windows server reads identity from realpath alone.
889+
platform: "win32",
890+
environment: { [DESKTOP_HOST_SCOPE_ENV]: scope },
891+
}),
892+
),
893+
);
894+
}).pipe(Effect.scoped),
895+
);
896+
863897
it.live("discovers Pi history in its default home and directory overrides", () =>
864898
Effect.gen(function* () {
865899
const { home, settings } = yield* setup;

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,14 +198,19 @@ export const make = Effect.gen(function* () {
198198
const hostPlatform = yield* HostProcess.Platform;
199199
const hostScope = hostEnvironment[DESKTOP_HOST_SCOPE_ENV]?.trim();
200200
// A mount or a directory's on-disk name does not change under a running server.
201+
// A miss is not cached: the directory may not exist yet.
201202
const physicalSourceIds = new Map<string, Promise<string | undefined>>();
202203
const physicalSourceId = (dir: string) =>
203204
Effect.promise(() => {
204-
let id = physicalSourceIds.get(dir);
205-
if (id === undefined) {
206-
id = readPhysicalSourceId(dir, hostScope, hostPlatform);
207-
physicalSourceIds.set(dir, id);
208-
}
205+
const cached = physicalSourceIds.get(dir);
206+
if (cached !== undefined) return cached;
207+
const id = readPhysicalSourceId(dir, hostScope, hostPlatform);
208+
physicalSourceIds.set(dir, id);
209+
void id.then((resolved) => {
210+
if (resolved === undefined && physicalSourceIds.get(dir) === id) {
211+
physicalSourceIds.delete(dir);
212+
}
213+
});
209214
return id;
210215
});
211216
const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
@@ -678,7 +683,7 @@ export const make = Effect.gen(function* () {
678683
Effect.promise(() => readDirectoryVolumeId(source.dir)),
679684
physicalSourceId(source.dir),
680685
])
681-
: Effect.succeed([volumeId, undefined] as const),
686+
: Effect.succeed<[string, string | undefined]>([volumeId, undefined]),
682687
([resolved, sourceId]): ScannedDir => ({
683688
...source,
684689
files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null,

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import {
1919
transcriptLineGate,
2020
} from "./usageTranscriptReader.ts";
2121

22+
const decodeUsageSummary = Schema.decodeUnknownSync(UsageSummary);
23+
2224
let dir: string;
2325

2426
beforeEach(async () => {
@@ -331,7 +333,7 @@ describe("readPhysicalSourceId", () => {
331333

332334
// One NTFS directory the Windows server reads natively and the WSL server
333335
// through drvfs. The temp dir stands in for the drive's mount point.
334-
async function drvfsFixture(extraMounts = "") {
336+
async function drvfsFixture(extraMounts: (escapedMountPoint: string) => string = () => "") {
335337
const mountPoint = NodePath.join(dir, "drive c");
336338
await NodeFSP.mkdir(NodePath.join(mountPoint, "Users", "User", ".claude", "projects"), {
337339
recursive: true,
@@ -343,14 +345,14 @@ describe("readPhysicalSourceId", () => {
343345
[
344346
"24 1 8:32 / / rw,relatime shared:1 - ext4 /dev/sdc rw,discard",
345347
`81 24 0:61 / ${escaped} rw,noatime shared:2 - 9p C:\\134 rw,dirsync,aname=drvfs;path=C:\\;uid=1000;gid=1000;symlinkroot=/mnt/,mmap,access=client,msize=65536,trans=fd`,
346-
extraMounts,
348+
extraMounts(escaped),
347349
].join("\n"),
348350
);
349351
return { mountPoint, mountInfoPath };
350352
}
351353

352354
function summaryFor(resolvedHomePath: string, volumeId: string, physicalSourceId?: string) {
353-
return Schema.decodeUnknownSync(UsageSummary)({
355+
return decodeUsageSummary({
354356
contractVersion: USAGE_CONTRACT_VERSION,
355357
readAt: "2026-10-22T02:00:00.000Z",
356358
timeZone: "UTC",
@@ -417,7 +419,7 @@ describe("readPhysicalSourceId", () => {
417419

418420
it("gives no identity to native or shadowing Linux mounts, or without a desktop scope", async () => {
419421
const { mountPoint, mountInfoPath } = await drvfsFixture(
420-
`90 81 8:48 / ${mountPoint.replaceAll(" ", "\\040")}/Users rw,relatime - ext4 /dev/sdd rw`,
422+
(escaped) => `90 81 8:48 / ${escaped}/Users rw,relatime - ext4 /dev/sdd rw`,
421423
);
422424
const projects = `${mountPoint}/Users/User/.claude/projects`;
423425
assert.isUndefined(await readPhysicalSourceId(projects, scope, "linux", mountInfoPath));

‎packages/shared/src/usageMerge.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,12 @@ function sourceIdentity(
139139
const find = (key: string): string => {
140140
let root = key;
141141
for (let next = parent.get(root); next !== undefined; next = parent.get(root)) root = next;
142+
// Path compression keeps long alias chains from making lookups quadratic.
143+
for (let node = key; node !== root;) {
144+
const next = parent.get(node)!;
145+
parent.set(node, root);
146+
node = next;
147+
}
142148
return root;
143149
};
144150
for (const environment of environments) {

0 commit comments

Comments
 (0)