The best way to control Claude Code, Codex and more from any computer or phone
fix(usage): count shared Windows and WSL transcripts once (#24319)
Julius Marminge committed
Nov 13, 2026 at 18:35 UTC
525f5b2f6de6e13e53b704f5bffe4735fd2f5dcd
9 files changed
+543
-28
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+38
-1
@@ -683,6 +683,43 @@ describe("DesktopBackendConfiguration", () => {
683
),
684
);
685
686
+ it.effect("gives the Windows and WSL backends one host scope that survives a restart", () =>
687
+ Effect.gen(function* () {
688
+ const fileSystem = yield* FileSystem.FileSystem;
689
+ const baseDir = yield* fileSystem.makeTempDirectoryScoped({
690
+ prefix: "t3-desktop-backend-config-test-",
691
+ });
692
+ const launch = Effect.gen(function* () {
693
+ const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
694
+ const primary = yield* configuration.resolvePrimary;
695
+ const wsl = yield* configuration.resolveWsl({ port: 5050, distro: null });
696
+ assert.equal(wsl.env.T3CODE_DESKTOP_HOST_SCOPE, primary.env.T3CODE_DESKTOP_HOST_SCOPE);
697
+ assert.include((wsl.env.WSLENV ?? "").split(":"), "T3CODE_DESKTOP_HOST_SCOPE");
698
+ return primary.env.T3CODE_DESKTOP_HOST_SCOPE;
699
+ }).pipe(
700
+ Effect.provide(
701
+ layerBackendConfiguration().pipe(
702
+ Layer.provideMerge(layerServerExposure),
703
+ Layer.provideMerge(DesktopAppSettings.layerTest()),
704
+ Layer.provideMerge(DesktopWslServerTree.layerTest()),
705
+ Layer.provideMerge(
706
+ DesktopWslEnvironment.layerTest({
707
+ isAvailable: true,
708
+ windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
709
+ getDistroIp: () => Option.some("172.27.0.99"),
710
+ }),
711
+ ),
712
+ Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
713
+ ),
714
+ ),
715
+ );
716
+
717
+ const first = yield* launch;
718
+ assert.match(first ?? "", /^[0-9a-f]{32}$/);
719
+ assert.equal(yield* launch, first);
720
+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
721
+ );
722
+
723
it.effect("resolveWsl carries the kill switch and resource attributes into the distro", () =>
724
Effect.gen(function* () {
725
const fileSystem = yield* FileSystem.FileSystem;
@@ -748,7 +785,7 @@ describe("DesktopBackendConfiguration", () => {
785
assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf");
786
assert.equal(
787
config.env.WSLENV,
751
- "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
788
+ "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",
789
);
790
}).pipe(
791
Effect.provide(
apps/desktop/src/backend/DesktopBackendConfiguration.ts
+41
-2
@@ -243,8 +243,38 @@ interface SharedBootstrapInput {
243
readonly bootstrapToken: string;
244
readonly bootstrapSecret: string;
245
readonly observabilitySettings: BackendObservabilitySettings;
246
+ readonly hostScope: string;
247
}
248
249
+// Matches the server's DESKTOP_HOST_SCOPE_ENV.
250
+const DESKTOP_HOST_SCOPE_ENV = "T3CODE_DESKTOP_HOST_SCOPE";
251
+const HOST_SCOPE_FILE_NAME = "desktop-host-scope";
252
+const HOST_SCOPE_PATTERN = /^[0-9a-f]{32}$/;
253
+
254
+/**
255
+ * Not a credential: it only tells this install's Windows and WSL servers that
256
+ * they run on one machine, so usage both read from one Windows directory counts
257
+ * once. Persisted so summaries from earlier launches still match.
258
+ */
259
+const readOrCreateHostScope = Effect.gen(function* () {
260
+ const fileSystem = yield* FileSystem.FileSystem;
261
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
262
+ const random = yield* SecureRandom.SecureRandom;
263
+ const scopePath = environment.path.join(environment.stateDir, HOST_SCOPE_FILE_NAME);
264
+ const existing = (yield* fileSystem
265
+ .readFileString(scopePath)
266
+ .pipe(Effect.orElseSucceed(() => ""))).trim();
267
+ if (HOST_SCOPE_PATTERN.test(existing)) return existing;
268
+ const scope = Hex.encode(yield* random.randomBytes(16).pipe(Effect.orDie));
269
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }).pipe(
270
+ Effect.andThen(fileSystem.writeFileString(scopePath, scope)),
271
+ Effect.catch((cause) =>
272
+ Effect.logWarning("Could not persist the desktop host scope.", { cause }),
273
+ ),
274
+ );
275
+ return scope;
276
+});
277
+
278
type WslPreflightRuntime =
279
| {
280
readonly kind: "executable";
@@ -540,6 +570,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
570
ELECTRON_RUN_AS_NODE: "1",
571
T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1",
572
T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath),
573
+ [DESKTOP_HOST_SCOPE_ENV]: input.hostScope,
574
},
575
extendEnv: true,
576
bootstrap,
@@ -636,8 +667,8 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
667
const httpBaseUrl = new URL(`http://${rendererHost}:${input.port}`);
668
669
const distroArgs = distroForConfig ? ["-d", distroForConfig] : [];
639
- const forwardedEnv: Record<string, string> = {};
640
- const forwardedEnvNames: string[] = [];
670
+ const forwardedEnv: Record<string, string> = { [DESKTOP_HOST_SCOPE_ENV]: input.hostScope };
671
+ const forwardedEnvNames: string[] = [DESKTOP_HOST_SCOPE_ENV];
672
for (const name of WSL_FORWARDED_ENV_NAMES) {
673
const value = env[name];
674
if (value !== undefined && value.length > 0) {
@@ -735,6 +766,13 @@ export const make = Effect.gen(function* () {
766
const random = yield* SecureRandom.SecureRandom;
767
// Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets.
768
const secretRef = yield* SynchronizedRef.make(Option.none<string>());
769
+ const hostScope = yield* Effect.cached(
770
+ readOrCreateHostScope.pipe(
771
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
772
+ Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
773
+ Effect.provideService(SecureRandom.SecureRandom, random),
774
+ ),
775
+ );
776
const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) =>
777
Option.match(current, {
778
onSome: (secret) => Effect.succeed([secret, current] as const),
@@ -762,6 +800,7 @@ export const make = Effect.gen(function* () {
800
bootstrapToken,
801
bootstrapSecret,
802
observabilitySettings,
803
+ hostScope: yield* hostScope,
804
} satisfies SharedBootstrapInput;
805
});
806
apps/server/src/usage/UsageService.test.ts
+34
@@ -51,6 +51,7 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts";
51
import * as ProviderHostLive from "../provider/ProviderHostLive.ts";
52
import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
53
import * as UsageService from "./UsageService.ts";
54
+import { DESKTOP_HOST_SCOPE_ENV, physicalSourceIdOf } from "./usageTranscriptReader.ts";
55
import * as MuseSdk from "../../../../packages/provider-muse/src/server/sdk.ts";
56
import { MuseUsageHome } from "@t3tools/provider-muse/server";
57
import { makeScanCacheWriter, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts";
@@ -1440,6 +1441,39 @@ describe("UsageService", () => {
1441
}),
1442
);
1443
1444
+ it.effect("identifies a transcript directory created after the server first read usage", () =>
1445
+ Effect.gen(function* () {
1446
+ const { home, settings } = yield* setup;
1447
+ const scope = "0123456789abcdef0123456789abcdef";
1448
+ const dir = NodePath.join(home, "pi", "sessions");
1449
+ yield* Effect.gen(function* () {
1450
+ const service = yield* UsageService.make;
1451
+ const piFingerprint = (summary: UsageSummary) =>
1452
+ summary.sources.find((source) => source.fingerprint.provider === "pi")?.fingerprint;
1453
+ const missing = piFingerprint(yield* service.readSummary(WINDOW));
1454
+ assert.strictEqual(missing?.resolvedHomePath, dir);
1455
+ assert.isUndefined(missing?.physicalSourceId);
1456
+ yield* Effect.promise(() => NodeFSP.mkdir(dir, { recursive: true }));
1457
+ assert.strictEqual(
1458
+ piFingerprint(yield* service.readSummary(WINDOW))?.physicalSourceId,
1459
+ physicalSourceIdOf(scope, yield* Effect.promise(() => NodeFSP.realpath(dir))),
1460
+ );
1461
+ }).pipe(
1462
+ Effect.scoped,
1463
+ Effect.provide(
1464
+ layerService({
1465
+ prefix: "usage-physical-source-created",
1466
+ home,
1467
+ settings,
1468
+ // The native Windows server reads identity from realpath alone.
1469
+ platform: "win32",
1470
+ environment: { [DESKTOP_HOST_SCOPE_ENV]: scope },
1471
+ }),
1472
+ ),
1473
+ );
1474
+ }),
1475
+ );
1476
+
1477
it.effect(
1478
"reports missing Pi history and skips malformed records without losing valid usage",
1479
() =>
apps/server/src/usage/UsageService.ts
+60
-11
@@ -42,8 +42,10 @@ import type {
42
import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
43
import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
44
import {
45
+ DESKTOP_HOST_SCOPE_ENV,
46
listTranscriptFiles,
47
readDirectoryVolumeId,
48
+ readPhysicalSourceId,
49
readTranscriptRecords,
50
} from "./usageTranscriptReader.ts";
51
import {
@@ -92,6 +94,7 @@ interface TranscriptSource {
94
readonly format: TranscriptUsageFormat<unknown>;
95
readonly dir: string;
96
readonly volumeId: string;
97
+ readonly physicalSourceId?: string;
98
readonly fileName?: string;
99
}
100
@@ -158,6 +161,24 @@ export const make = Effect.gen(function* () {
161
const settingsService = yield* ServerSettings.ServerSettingsService;
162
const httpClient = yield* HttpClient.HttpClient;
163
const hostEnvironment = yield* HostProcess.Environment;
164
+ const hostPlatform = yield* HostProcess.Platform;
165
+ const hostScope = hostEnvironment[DESKTOP_HOST_SCOPE_ENV]?.trim();
166
+ // A mount or a directory's on-disk name does not change under a running server.
167
+ // A miss is not cached: the directory may not exist yet.
168
+ const physicalSourceIds = new Map<string, Promise<string | undefined>>();
169
+ const physicalSourceId = (dir: string) =>
170
+ Effect.promise(() => {
171
+ const cached = physicalSourceIds.get(dir);
172
+ if (cached !== undefined) return cached;
173
+ const id = readPhysicalSourceId(dir, hostScope, hostPlatform);
174
+ physicalSourceIds.set(dir, id);
175
+ void id.then((resolved) => {
176
+ if (resolved === undefined && physicalSourceIds.get(dir) === id) {
177
+ physicalSourceIds.delete(dir);
178
+ }
179
+ });
180
+ return id;
181
+ });
182
const hostname = yield* HostProcess.Hostname;
183
const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
184
@@ -385,11 +406,13 @@ export const make = Effect.gen(function* () {
406
const key = `${provider}\0${dir}`;
407
if (seen.has(key)) continue;
408
seen.add(key);
409
+ const sourceId = yield* physicalSourceId(dir);
410
dirs.push({
411
provider,
412
format,
413
dir,
414
volumeId,
415
+ ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
416
...(fileName === undefined ? {} : { fileName }),
417
});
418
}
@@ -629,6 +652,7 @@ export const make = Effect.gen(function* () {
652
readonly provider: UsageProviderKind;
653
readonly dir: string;
654
readonly volumeId: string;
655
+ readonly physicalSourceId?: string;
656
readonly hostId?: string;
657
readonly status?: UsageSource["status"];
658
readonly message?: string;
@@ -649,16 +673,22 @@ export const make = Effect.gen(function* () {
673
windowStartMs: number,
674
fromMemory: boolean,
675
) {
652
- const { provider, format, dir, volumeId, fileName } = source;
676
+ const { provider, format, dir, volumeId, physicalSourceId, fileName } = source;
677
+ const identity = {
678
+ provider,
679
+ dir,
680
+ volumeId,
681
+ ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
682
+ };
683
const exists = yield* fileSystem
684
.exists(dir)
685
.pipe(Effect.catchCause(() => Effect.succeed(false)));
686
if (!exists) {
687
cover(source, windowStartMs);
658
- return { provider, dir, volumeId, files: null } satisfies ScannedDir;
688
+ return { ...identity, files: null } satisfies ScannedDir;
689
}
690
// scanSummary aggregates the saved files, as it does for a deleted directory.
661
- if (fromMemory) return { provider, dir, volumeId, files: [] } satisfies ScannedDir;
691
+ if (fromMemory) return { ...identity, files: [] } satisfies ScannedDir;
692
const { files, walked, failedPaths } = yield* Effect.promise(() =>
693
listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
694
);
@@ -704,9 +734,7 @@ export const make = Effect.gen(function* () {
734
"usage.files_parsed": read.filter((file) => file.update !== undefined).length,
735
});
736
return {
707
- provider,
708
- dir,
709
- volumeId,
737
+ ...identity,
738
files: parsedFiles,
739
walked,
740
...(unread > 0
@@ -736,14 +764,19 @@ export const make = Effect.gen(function* () {
764
Effect.flatMap((sources) =>
765
Effect.forEach(sources, ({ volumeId, ...source }) =>
766
Effect.map(
767
+ // A reader's own volumeId names a remote account, not a local directory.
768
volumeId === undefined
740
- ? Effect.promise(() => readDirectoryVolumeId(source.dir))
741
- : Effect.succeed(volumeId),
742
- (resolved): ScannedDir => ({
769
+ ? Effect.all([
770
+ Effect.promise(() => readDirectoryVolumeId(source.dir)),
771
+ physicalSourceId(source.dir),
772
+ ])
773
+ : Effect.succeed<[string, string | undefined]>([volumeId, undefined]),
774
+ ([resolved, sourceId]): ScannedDir => ({
775
...source,
776
files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null,
777
provider: reader.provider,
778
volumeId: resolved,
779
+ ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
780
}),
781
),
782
),
@@ -972,7 +1005,17 @@ export const make = Effect.gen(function* () {
1005
1006
for (const [
1007
index,
975
- { provider, dir, volumeId, files, status, message, refreshing, hostId: sourceHostId },
1008
+ {
1009
+ provider,
1010
+ dir,
1011
+ volumeId,
1012
+ physicalSourceId,
1013
+ files,
1014
+ status,
1015
+ message,
1016
+ refreshing,
1017
+ hostId: sourceHostId,
1018
+ },
1019
] of scannedDirs.entries()) {
1020
let scannedFiles = 0;
1021
let skippedFiles = 0;
@@ -1019,7 +1062,13 @@ export const make = Effect.gen(function* () {
1062
const sourceMessage =
1063
message ?? (files === null ? "No transcript directory on this environment." : null);
1064
sources.push({
1022
- fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
1065
+ fingerprint: {
1066
+ hostId: sourceHostId ?? hostId,
1067
+ provider,
1068
+ resolvedHomePath: dir,
1069
+ volumeId,
1070
+ ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
1071
+ },
1072
status:
1073
files === null && scannedFiles === 0
1074
? "missing"
apps/server/src/usage/usageTranscriptReader.test.ts
+48
@@ -13,6 +13,8 @@ import * as Schema from "effect/Schema";
13
import { TEST_FORMATS } from "./usageTestFormats.ts";
14
import {
15
listTranscriptFiles,
16
+ physicalSourceIdOf,
17
+ readPhysicalSourceId,
18
readTranscriptRecords,
19
transcriptLineGate,
20
} from "./usageTranscriptReader.ts";
@@ -577,3 +579,49 @@ describe("transcriptLineGate", () => {
579
}
580
});
581
});
582
+
583
+describe("readPhysicalSourceId", () => {
584
+ const scope = "0123456789abcdef0123456789abcdef";
585
+ const windowsPath = "C:\\Users\\User\\.claude\\projects";
586
+
587
+ // One NTFS directory the Windows server reads natively and the WSL server
588
+ // through drvfs. The temp dir stands in for the drive's mount point.
589
+ async function drvfsFixture(extraMounts: (escapedMountPoint: string) => string = () => "") {
590
+ const mountPoint = NodePath.join(dir, "drive c");
591
+ await NodeFSP.mkdir(NodePath.join(mountPoint, "Users", "User", ".claude", "projects"), {
592
+ recursive: true,
593
+ });
594
+ const escaped = mountPoint.replaceAll(" ", "\\040");
595
+ const mountInfoPath = NodePath.join(dir, "mountinfo");
596
+ await NodeFSP.writeFile(
597
+ mountInfoPath,
598
+ [
599
+ "24 1 8:32 / / rw,relatime shared:1 - ext4 /dev/sdc rw,discard",
600
+ `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`,
601
+ extraMounts(escaped),
602
+ ].join("\n"),
603
+ );
604
+ return { mountPoint, mountInfoPath };
605
+ }
606
+
607
+ it("names a drvfs directory as the Windows server names it, whatever its typed case", async () => {
608
+ const { mountPoint, mountInfoPath } = await drvfsFixture();
609
+ const wslId = await readPhysicalSourceId(
610
+ `${mountPoint}/users/user/.claude/projects`,
611
+ scope,
612
+ "linux",
613
+ mountInfoPath,
614
+ );
615
+ assert.strictEqual(wslId, physicalSourceIdOf(scope, windowsPath));
616
+ });
617
+
618
+ it("gives no identity to native or shadowing Linux mounts, or without a desktop scope", async () => {
619
+ const { mountPoint, mountInfoPath } = await drvfsFixture(
620
+ (escaped) => `90 81 8:48 / ${escaped}/Users rw,relatime - ext4 /dev/sdd rw`,
621
+ );
622
+ const projects = `${mountPoint}/Users/User/.claude/projects`;
623
+ assert.isUndefined(await readPhysicalSourceId(projects, scope, "linux", mountInfoPath));
624
+ assert.isUndefined(await readPhysicalSourceId(dir, scope, "linux", mountInfoPath));
625
+ assert.isUndefined(await readPhysicalSourceId(projects, undefined, "linux", mountInfoPath));
626
+ });
627
+});
apps/server/src/usage/usageTranscriptReader.ts
+132
@@ -1,5 +1,6 @@
1
// @effect-diagnostics nodeBuiltinImport:off
2
// Cold windows span ~1.4 GB/1,500 files; node:fs buffer streaming is ~10x cheaper than materializing files.
3
+import * as NodeCrypto from "node:crypto";
4
import * as NodeFS from "node:fs";
5
import * as NodeFSP from "node:fs/promises";
6
import * as NodePath from "node:path";
@@ -150,6 +151,137 @@ export async function readDirectoryVolumeId(path: string): Promise<string> {
151
}
152
}
153
154
+/**
155
+ * Set by the desktop app, from a value it persists, on its Windows server and
156
+ * the WSL server it manages, so both can name one Windows directory alike
157
+ * without merging separate machines that share a hostname and path.
158
+ */
159
+export const DESKTOP_HOST_SCOPE_ENV = "T3CODE_DESKTOP_HOST_SCOPE";
160
+
161
+const MOUNT_FIELD_ESCAPE = /\\([0-7]{3})/g;
162
+const WINDOWS_ROOT = /^(?:[A-Za-z]:|\\\\[^\\]+\\[^\\]+)\\?$/;
163
+
164
+const unescapeMountField = (field: string) =>
165
+ field.replace(MOUNT_FIELD_ESCAPE, (_, octal: string) =>
166
+ String.fromCharCode(Number.parseInt(octal, 8)),
167
+ );
168
+
169
+const normalizeWindowsPath = (path: string) =>
170
+ (/^[a-z]:/.test(path) ? path[0]!.toUpperCase() + path.slice(1) : path).replace(/\\$/, "");
171
+
172
+/**
173
+ * The Windows directory behind the deepest mount holding `dir`, read from
174
+ * `/proc/self/mountinfo` so a custom automount root resolves and an ext4
175
+ * mount under `/mnt` never passes for a drive.
176
+ */
177
+function windowsMountFor(
178
+ mountInfo: string,
179
+ dir: string,
180
+): { readonly mountPoint: string; readonly windowsRoot: string } | undefined {
181
+ let deepest: { mountPoint: string; windowsRoot: string | undefined } | undefined;
182
+ for (const line of mountInfo.split("\n")) {
183
+ const fields = line.split(" ");
184
+ const separator = fields.indexOf("-", 6);
185
+ if (separator === -1) continue;
186
+ const mountPoint = unescapeMountField(fields[4] ?? "");
187
+ const contains =
188
+ mountPoint === "/" ||
189
+ dir === mountPoint ||
190
+ dir.startsWith(mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`);
191
+ if (!contains || (deepest !== undefined && deepest.mountPoint.length > mountPoint.length)) {
192
+ continue;
193
+ }
194
+ // WSL2 mounts drives over 9p with `aname=drvfs;path=C:\`; WSL1 as `drvfs`.
195
+ const options = (fields[separator + 3] ?? "").split(/[,;]/);
196
+ const source = options.includes("aname=drvfs")
197
+ ? options.find((option) => option.startsWith("path="))?.slice("path=".length)
198
+ : fields[separator + 1] === "drvfs"
199
+ ? unescapeMountField(fields[separator + 2] ?? "")
200
+ : undefined;
201
+ const root = unescapeMountField(fields[3] ?? "/")
202
+ .split("/")
203
+ .filter(Boolean);
204
+ deepest = {
205
+ mountPoint,
206
+ windowsRoot:
207
+ source !== undefined && WINDOWS_ROOT.test(source)
208
+ ? [normalizeWindowsPath(source), ...root].join("\\")
209
+ : undefined,
210
+ };
211
+ }
212
+ return deepest?.windowsRoot === undefined
213
+ ? undefined
214
+ : { mountPoint: deepest.mountPoint, windowsRoot: deepest.windowsRoot };
215
+}
216
+
217
+/**
218
+ * drvfs keeps the casing a path was typed with, while Windows reports the
219
+ * on-disk names. Read those names rather than folding case, which would join
220
+ * distinct entries of a case-sensitive directory.
221
+ */
222
+async function onDiskNames(
223
+ mountPoint: string,
224
+ parts: readonly string[],
225
+): Promise<string[] | undefined> {
226
+ const names: string[] = [];
227
+ let current = mountPoint;
228
+ for (const part of parts) {
229
+ let entries: string[];
230
+ try {
231
+ entries = await NodeFSP.readdir(current);
232
+ } catch {
233
+ return undefined;
234
+ }
235
+ const folded = part.toUpperCase();
236
+ const [name, ...others] = entries.includes(part)
237
+ ? [part]
238
+ : entries.filter((entry) => entry.toUpperCase() === folded);
239
+ if (name === undefined || others.length > 0) return undefined;
240
+ names.push(name);
241
+ current = NodePath.posix.join(current, name);
242
+ }
243
+ return names;
244
+}
245
+
246
+export function physicalSourceIdOf(scope: string, windowsPath: string): string {
247
+ return NodeCrypto.createHash("sha256")
248
+ .update(`${scope}\0${windowsPath}`)
249
+ .digest("hex")
250
+ .slice(0, 32);
251
+}
252
+
253
+/**
254
+ * Identifies a Windows directory the same way from the Windows server and from
255
+ * a WSL server reading it through drvfs. Directories that are not Windows
256
+ * backed, and servers the desktop app did not start, get none.
257
+ */
258
+export async function readPhysicalSourceId(
259
+ dir: string,
260
+ scope: string | undefined,
261
+ platform: NodeJS.Platform,
262
+ mountInfoPath = "/proc/self/mountinfo",
263
+): Promise<string | undefined> {
264
+ if (scope === undefined || scope.length === 0) return undefined;
265
+ try {
266
+ if (platform === "win32") {
267
+ // The native realpath reports on-disk casing; the JS one keeps the input's.
268
+ return physicalSourceIdOf(scope, normalizeWindowsPath(await NodeFSP.realpath(dir)));
269
+ }
270
+ if (platform !== "linux") return undefined;
271
+ const mount = windowsMountFor(await NodeFSP.readFile(mountInfoPath, "utf8"), dir);
272
+ if (mount === undefined) return undefined;
273
+ const names = await onDiskNames(
274
+ mount.mountPoint,
275
+ dir.slice(mount.mountPoint.length).split("/").filter(Boolean),
276
+ );
277
+ return names === undefined
278
+ ? undefined
279
+ : physicalSourceIdOf(scope, [mount.windowsRoot, ...names].join("\\"));
280
+ } catch {
281
+ return undefined;
282
+ }
283
+}
284
+
285
async function guardMatches(
286
handle: NodeFSP.FileHandle,
287
position: TranscriptParsePosition,
packages/contracts/src/usage.ts
+7
@@ -78,6 +78,13 @@ export const UsageSourceFingerprint = Schema.Struct({
78
resolvedHomePath: TrimmedNonEmptyString,
79
/** Transcript directory device:inode distinguishes machines sharing a hostname and home path. */
80
volumeId: Schema.String,
81
+ /**
82
+ * Opaque identity of a directory that the Windows server of a desktop install
83
+ * reads natively and its managed WSL server reads through a drvfs mount. Path
84
+ * and `volumeId` differ between the two sides, so clients treat sources with
85
+ * an equal value as one directory in addition to the fields above.
86
+ */
87
+ physicalSourceId: Schema.optionalKey(TrimmedNonEmptyString),
88
});
89
export type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;
90
packages/shared/src/usageMerge.test.ts
+138
@@ -43,6 +43,7 @@ function summary(
43
hostId: string;
44
homePath: string;
45
volumeId?: string;
46
+ physicalSourceId?: string;
47
distinctSessions?: number;
48
}[],
49
contractVersion: number = USAGE_CONTRACT_VERSION,
@@ -60,6 +61,9 @@ function summary(
61
provider: source.provider,
62
resolvedHomePath: source.homePath,
63
volumeId: source.volumeId ?? `vol-${source.hostId}`,
64
+ ...(source.physicalSourceId === undefined
65
+ ? {}
66
+ : { physicalSourceId: source.physicalSourceId }),
67
},
68
status: "ok" as const,
69
scannedFiles: 1,
@@ -544,6 +548,140 @@ describe("mergeUsage", () => {
548
expect(merged.duplicateSources).toHaveLength(0);
549
});
550
551
+ describe("one directory seen from both sides of a Windows and WSL boundary", () => {
552
+ // Fingerprints the reporter captured for one NTFS directory, read natively by
553
+ // Windows and through the drvfs mount by WSL. Path and dev:ino both differ.
554
+ const physicalSourceId = "physical-claude-projects";
555
+ const windows = {
556
+ provider: "claude" as const,
557
+ hostId: "MainPC",
558
+ homePath: "C:\\Users\\user\\.claude\\projects",
559
+ volumeId: "1280555009:3659174697951285",
560
+ physicalSourceId,
561
+ distinctSessions: 142,
562
+ };
563
+ const wsl = {
564
+ provider: "claude" as const,
565
+ hostId: "MainPC",
566
+ homePath: "/mnt/c/Users/user/.claude/projects",
567
+ volumeId: "112:3659174697951287",
568
+ physicalSourceId,
569
+ distinctSessions: 142,
570
+ };
571
+
572
+ it("counts it once, whichever scan is newer", () => {
573
+ const environments = [
574
+ environment(
575
+ "windows",
576
+ summary([bucket({ sourcePath: windows.homePath, records: 22433 })], [windows]),
577
+ ),
578
+ environment("wsl", {
579
+ ...summary([bucket({ sourcePath: wsl.homePath, records: 22432 })], [wsl]),
580
+ readAt: "2026-08-07T00:05:00.000Z",
581
+ }),
582
+ ];
583
+
584
+ for (const ordered of [environments, environments.toReversed()]) {
585
+ const merged = mergeUsage(ordered, USAGE_CONTRACT_VERSION);
586
+ expect(merged.sessions).toBe(142);
587
+ expect(merged.records).toBe(22432);
588
+ expect(merged.costUsd).toBe(10);
589
+ expect(merged.contributingEnvironments).toEqual(["wsl"]);
590
+ expect(merged.duplicateSources).toEqual([`windows: ${windows.homePath}`]);
591
+ }
592
+ });
593
+
594
+ it("keeps only new cells from a later partial scan through the other side", () => {
595
+ const complete = environment(
596
+ "windows",
597
+ summary([bucket({ sourcePath: windows.homePath })], [windows]),
598
+ );
599
+ const partialSummary = summary(
600
+ [
601
+ bucket({ sourcePath: wsl.homePath, costUsd: 4, records: 2 }),
602
+ bucket({ day: "2026-08-08" as UsageDay, sourcePath: wsl.homePath, costUsd: 3 }),
603
+ ],
604
+ [{ ...wsl, distinctSessions: 143 }],
605
+ );
606
+ const partial = environment("wsl", {
607
+ ...partialSummary,
608
+ readAt: "2026-08-08T01:00:00.000Z",
609
+ sources: partialSummary.sources.map((entry) => ({ ...entry, status: "partial" as const })),
610
+ });
611
+
612
+ const merged = mergeUsage([complete, partial], USAGE_CONTRACT_VERSION);
613
+ expect(merged.costUsd).toBe(13);
614
+ expect(merged.sessions).toBe(143);
615
+ expect(merged.daily.map(({ day, costUsd }) => [day, costUsd])).toEqual([
616
+ ["2026-08-07", 10],
617
+ ["2026-08-08", 3],
618
+ ]);
619
+ });
620
+
621
+ it("counts it once when one server reaches it through two mounts", () => {
622
+ const secondMount = { ...wsl, homePath: "/mnt/win/Users/user/.claude/projects" };
623
+ const merged = mergeUsage(
624
+ [
625
+ environment(
626
+ "wsl",
627
+ summary(
628
+ [
629
+ bucket({ sourcePath: wsl.homePath }),
630
+ bucket({
631
+ day: "2026-08-08" as UsageDay,
632
+ sourcePath: secondMount.homePath,
633
+ costUsd: 3,
634
+ }),
635
+ ],
636
+ [wsl, secondMount],
637
+ ),
638
+ ),
639
+ ],
640
+ USAGE_CONTRACT_VERSION,
641
+ );
642
+
643
+ expect(merged.costUsd).toBe(10);
644
+ expect(merged.sessions).toBe(142);
645
+ expect(merged.daily.map(({ day }) => day)).toEqual(["2026-08-07"]);
646
+ expect(merged.duplicateSources).toEqual([`wsl: ${secondMount.homePath}`]);
647
+ });
648
+
649
+ it("still counts a shared directory once when only one server reports physical identity", () => {
650
+ const { physicalSourceId: _omitted, ...legacy } = windows;
651
+ const merged = mergeUsage(
652
+ [
653
+ environment("desktop", summary([bucket({ sourcePath: windows.homePath })], [windows])),
654
+ environment("standalone", summary([bucket({ sourcePath: legacy.homePath })], [legacy])),
655
+ ],
656
+ USAGE_CONTRACT_VERSION,
657
+ );
658
+
659
+ expect(merged.costUsd).toBe(10);
660
+ expect(merged.sessions).toBe(142);
661
+ expect(merged.duplicateSources).toHaveLength(1);
662
+ });
663
+
664
+ it("counts it once when two desktop installs with different scopes read it", () => {
665
+ const merged = mergeUsage(
666
+ [
667
+ environment("packaged", summary([bucket({ sourcePath: windows.homePath })], [windows])),
668
+ environment(
669
+ "dev-build",
670
+ summary(
671
+ [bucket({ sourcePath: windows.homePath })],
672
+ [{ ...windows, physicalSourceId: "physical-other-scope" }],
673
+ ),
674
+ ),
675
+ ],
676
+ USAGE_CONTRACT_VERSION,
677
+ );
678
+
679
+ expect(merged.costUsd).toBe(10);
680
+ expect(merged.sessions).toBe(142);
681
+ expect(merged.duplicateSources).toHaveLength(1);
682
+ });
683
+ });
684
+
685
it("totals sessions from per-directory distinct counts, not per-bucket sums", () => {
686
const merged = mergeUsage(
687
[
packages/shared/src/usageMerge.ts
+45
-14
@@ -118,6 +118,31 @@ function fingerprintKey(fingerprint: UsageSourceFingerprint): string {
118
].join(" ");
119
}
120
121
+// Sources are one directory when either their legacy key or their physicalSourceId matches.
122
+// physicalSourceId joins a directory read natively by Windows and through a WSL mount (path
123
+// and dev:ino both differ); the legacy key still joins installs whose host scopes differ.
124
+function sourceIdentity(
125
+ environments: readonly EnvironmentUsage[],
126
+): (fingerprint: UsageSourceFingerprint) => string {
127
+ const parent = new Map<string, string>();
128
+ const find = (key: string): string => {
129
+ const next = parent.get(key);
130
+ if (next === undefined || next === key) return key;
131
+ const root = find(next);
132
+ parent.set(key, root);
133
+ return root;
134
+ };
135
+ for (const environment of environments) {
136
+ for (const { fingerprint } of environment.summary.sources) {
137
+ if (fingerprint.physicalSourceId === undefined) continue;
138
+ const legacy = find(fingerprintKey(fingerprint));
139
+ const physical = find(`\u0000${fingerprint.provider}\u0000${fingerprint.physicalSourceId}`);
140
+ if (legacy !== physical) parent.set(legacy, physical);
141
+ }
142
+ }
143
+ return (fingerprint) => find(fingerprintKey(fingerprint));
144
+}
145
+
146
function bucketsForSource(summary: UsageSummary, source: UsageSource): readonly UsageBucket[] {
147
const providerSources = summary.sources.filter(
148
(entry) => entry.fingerprint.provider === source.fingerprint.provider,
@@ -134,13 +159,15 @@ function bucketKey(bucket: UsageBucket): string {
159
return JSON.stringify([bucket.day, bucket.hourStart ?? null, bucket.provider, bucket.model]);
160
}
161
137
-function claimSources(environments: readonly EnvironmentUsage[]): {
138
- readonly ownerByFingerprint: ReadonlyMap<string, EnvironmentId>;
162
+function claimSources(
163
+ environments: readonly EnvironmentUsage[],
164
+ sourceKey: (fingerprint: UsageSourceFingerprint) => string,
165
+): {
166
+ readonly ownerScanByFingerprint: ReadonlyMap<string, { readonly source: UsageSource }>;
167
readonly supplementalBucketsByEnvironment: ReadonlyMap<EnvironmentId, ReadonlySet<UsageBucket>>;
168
readonly sessionsByFingerprint: ReadonlyMap<string, number>;
169
readonly duplicates: readonly string[];
170
} {
143
- const ownerByFingerprint = new Map<string, EnvironmentId>();
171
const ownerScanByFingerprint = new Map<
172
string,
173
{ environment: EnvironmentUsage; source: UsageSource }
@@ -160,12 +187,11 @@ function claimSources(environments: readonly EnvironmentUsage[]): {
187
for (const environment of ordered) {
188
for (const source of environment.summary.sources) {
189
if (source.status !== status) continue;
163
- const key = fingerprintKey(source.fingerprint);
164
- if (ownerByFingerprint.has(key)) {
190
+ const key = sourceKey(source.fingerprint);
191
+ if (ownerScanByFingerprint.has(key)) {
192
duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);
193
continue;
194
}
168
- ownerByFingerprint.set(key, environment.environmentId);
195
ownerScanByFingerprint.set(key, { environment, source });
196
sessionsByFingerprint.set(key, source.distinctSessions);
197
}
@@ -176,7 +202,7 @@ function claimSources(environments: readonly EnvironmentUsage[]): {
202
for (const environment of ordered) {
203
for (const source of environment.summary.sources) {
204
if (source.status !== "partial") continue;
179
- const key = fingerprintKey(source.fingerprint);
205
+ const key = sourceKey(source.fingerprint);
206
const owner = ownerScanByFingerprint.get(key);
207
// A scan under another model filter counts different records, so its cells are not missing ones.
208
if (
@@ -212,7 +238,7 @@ function claimSources(environments: readonly EnvironmentUsage[]): {
238
}
239
240
return {
215
- ownerByFingerprint,
241
+ ownerScanByFingerprint,
242
supplementalBucketsByEnvironment,
243
sessionsByFingerprint,
244
duplicates,
@@ -221,9 +247,10 @@ function claimSources(environments: readonly EnvironmentUsage[]): {
247
248
function ownedContribution(
249
environment: EnvironmentUsage,
224
- ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
250
+ ownerScanByFingerprint: ReadonlyMap<string, { readonly source: UsageSource }>,
251
supplementalBuckets: ReadonlySet<UsageBucket>,
252
sessionsByFingerprint: ReadonlyMap<string, number>,
253
+ sourceKey: (fingerprint: UsageSourceFingerprint) => string,
254
): {
255
readonly buckets: readonly UsageBucket[];
256
readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
@@ -233,8 +260,10 @@ function ownedContribution(
260
const sessionsByProvider = new Map<UsageProviderKind, number>();
261
for (const source of environment.summary.sources) {
262
if (source.status === "missing") continue;
236
- const key = fingerprintKey(source.fingerprint);
237
- if (ownerByFingerprint.get(key) === environment.environmentId) {
263
+ const key = sourceKey(source.fingerprint);
264
+ // By source, not environment: one server can reach a directory through two
265
+ // mounts, and only the winning reading may count.
266
+ if (ownerScanByFingerprint.get(key)?.source === source) {
267
const provider = source.fingerprint.provider;
268
ownedProviders.add(provider);
269
ownedSources.add(`${provider}\u0000${source.fingerprint.resolvedHomePath}`);
@@ -324,12 +353,13 @@ export function mergeUsage(
353
}
354
}
355
356
+ const sourceKey = sourceIdentity(current);
357
const {
328
- ownerByFingerprint,
358
+ ownerScanByFingerprint,
359
supplementalBucketsByEnvironment,
360
sessionsByFingerprint,
361
duplicates,
332
- } = claimSources(current);
362
+ } = claimSources(current, sourceKey);
363
364
let costUsd = 0;
365
let uncachedInputTokens = 0;
@@ -384,9 +414,10 @@ export function mergeUsage(
414
for (const environment of current) {
415
const { buckets, sessionsByProvider } = ownedContribution(
416
environment,
387
- ownerByFingerprint,
417
+ ownerScanByFingerprint,
418
supplementalBucketsByEnvironment.get(environment.environmentId) ?? new Set(),
419
sessionsByFingerprint,
420
+ sourceKey,
421
);
422
if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
423