Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(statusline): write the token file at the path its readers resolve

Jack Rudenko0295054afb4c
diff --git a/packages/cli/src/handlers/shared/token-tracker.test.ts b/packages/cli/src/handlers/shared/token-tracker.test.ts
index 3f5b4aee..a4b48b00 100644
--- a/packages/cli/src/handlers/shared/token-tracker.test.ts
+++ b/packages/cli/src/handlers/shared/token-tracker.test.ts
@@ -1,8 +1,10 @@
import { afterEach, describe, expect, test } from "bun:test";
-import { existsSync, readFileSync, unlinkSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, rmSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { readSessionStats } from "../../session/session-stats.js";
+import { resolveTokenFilePath } from "../../session/token-file.js";
import { TokenTracker, computeCacheReadDiscount } from "./token-tracker.js";
interface TokenFile {
@@ -53,6 +55,39 @@ afterEach(() => {
else process.env.CLAUDISH_TOKEN_FILE = originalTokenFile;
});
+describe("the token file path: one rule for the writer and its readers", () => {
+ test("with no override the tracker writes where resolveTokenFilePath says, $HOME first", () => {
+ const home = mkdtempSync(join(tmpdir(), "claudish-token-home-"));
+ const savedHome = process.env.HOME;
+ const port = nextPort++;
+ try {
+ process.env.HOME = home; // Bun's os.homedir() would ignore this
+ delete process.env.CLAUDISH_TOKEN_FILE;
+ const expected = join(home, ".claudish", `tokens-${port}.json`);
+ expect(resolveTokenFilePath(port)).toBe(expected);
+ const tracker = new TokenTracker(port, {
+ contextWindow: 400_000,
+ providerName: "openai",
+ modelName: "test-model",
+ });
+ tracker.updateWithDelta(1_000, 10);
+ expect(readTokenFile(expected).input_tokens).toBe(1_000);
+ // the end-of-session summary reads the same file
+ expect(readSessionStats(port)).not.toBeNull();
+ } finally {
+ if (savedHome === undefined) delete process.env.HOME;
+ else process.env.HOME = savedHome;
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test("source guard: token-tracker.ts never builds the path itself (no os.homedir)", () => {
+ const src = readFileSync(join(import.meta.dir, "token-tracker.ts"), "utf8");
+ expect(src).toContain("resolveTokenFilePath(this.port)");
+ expect(src).not.toMatch(/homedir\(/);
+ });
+});
+
describe("TokenTracker live input-token tracking", () => {
test("grow then compact writes the current context and recovers context-left percentage", () => {
const { tracker, tokenFile } = createTracker();
diff --git a/packages/cli/src/handlers/shared/token-tracker.ts b/packages/cli/src/handlers/shared/token-tracker.ts
index 54ab1e51..eaa69e91 100644
--- a/packages/cli/src/handlers/shared/token-tracker.ts
+++ b/packages/cli/src/handlers/shared/token-tracker.ts
@@ -11,11 +11,11 @@
*/
import { mkdirSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, join } from "node:path";
+import { dirname } from "node:path";
import { TOOL_NAME_SHAPE } from "../../adapters/tool-name-utils.js";
import { type PlanUsage, isPlanStale } from "../../auth/quota/types.js";
import { log } from "../../logger.js";
+import { resolveTokenFilePath } from "../../session/token-file.js";
import { type ModelPricing, getModelPricing } from "./remote-provider-types.js";
export interface TokenTrackerConfig {
@@ -554,8 +554,8 @@ export class TokenTracker {
// orchestrator spawning N children has no way to tell which file belongs
// to which model. Pointing each child at a known path is what makes
// per-model token/cost reporting possible.
- const override = process.env.CLAUDISH_TOKEN_FILE;
- const outPath = override || join(homedir(), ".claudish", `tokens-${this.port}.json`);
+ // The ONE rule the status line and the end-of-session summary read by.
+ const outPath = resolveTokenFilePath(this.port);
mkdirSync(dirname(outPath), { recursive: true });
writeFileSync(outPath, JSON.stringify(data), "utf-8");
} catch (e) {
diff --git a/packages/cli/src/session/session-stats.ts b/packages/cli/src/session/session-stats.ts
index c9f648f9..54a013b5 100644
--- a/packages/cli/src/session/session-stats.ts
+++ b/packages/cli/src/session/session-stats.ts
@@ -9,9 +9,8 @@
*/
import { readFileSync } from "node:fs";
-import { join } from "node:path";
-import { userHomeFrom } from "../channel/home-dir.js";
import { type Baseline, baselineCost, getBaselines } from "./baseline-pricing.js";
+import { resolveTokenFilePath } from "./token-file.js";
/** One tool's share of the session. */
export interface ToolCall {
@@ -74,25 +73,7 @@ export interface SessionStats {
billedInputTokens: number;
}
-/**
- * This session's token file: the path `TokenTracker.writeFile` writes to, the path the
- * status line reads, and the path the end-of-session summary reads. ONE resolver for
- * all three readers of the writer's rule.
- *
- * An inherited `CLAUDISH_TOKEN_FILE` wins: a parent (team, the MCP channel, a pane)
- * names the file the child's proxy writes, and the tracker honours it. Otherwise it is
- * `<home>/.claudish/tokens-<port>.json`, `<home>` by the `$HOME`-first rule.
- *
- * `createTempSettingsFile` used to build the default path itself and ignore the
- * override, so a child with an inherited `CLAUDISH_TOKEN_FILE` drew its status line
- * from a port-keyed file nobody wrote.
- */
-export function resolveTokenFilePath(
- port: number | string,
- env: Record<string, string | undefined> = process.env
-): string {
- return env.CLAUDISH_TOKEN_FILE || join(userHomeFrom(env), ".claudish", `tokens-${port}.json`);
-}
+export { resolveTokenFilePath };
const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
diff --git a/packages/cli/src/session/token-file.ts b/packages/cli/src/session/token-file.ts
new file mode 100644
index 00000000..e7922fa0
--- /dev/null
+++ b/packages/cli/src/session/token-file.ts
@@ -0,0 +1,26 @@
+/**
+ * This session's token file: the path `TokenTracker.writeFile` writes to, the path the
+ * status line reads, and the path the end-of-session summary reads. ONE resolver for
+ * the writer and all its readers — kept in its own module so the proxy's tracker can
+ * import it without the summary's pricing dependencies.
+ *
+ * An inherited `CLAUDISH_TOKEN_FILE` wins: a parent (team, the MCP channel, a pane)
+ * names the file the child's proxy writes, and the tracker honours it. Otherwise it is
+ * `<home>/.claudish/tokens-<port>.json`, `<home>` by the `$HOME`-first rule.
+ *
+ * `createTempSettingsFile` used to build the default path itself and ignore the
+ * override, so a child with an inherited `CLAUDISH_TOKEN_FILE` drew its status line
+ * from a port-keyed file nobody wrote; and the tracker built it with `os.homedir()`,
+ * which Bun resolves from the passwd entry and never from a runtime `$HOME`, so with a
+ * redirected HOME the summary read a file the tracker never wrote.
+ */
+
+import { join } from "node:path";
+import { userHomeFrom } from "../channel/home-dir.js";
+
+export function resolveTokenFilePath(
+ port: number | string,
+ env: Record<string, string | undefined> = process.env
+): string {
+ return env.CLAUDISH_TOKEN_FILE || join(userHomeFrom(env), ".claudish", `tokens-${port}.json`);
+}