Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(statusline): read an inherited CLAUDISH_TOKEN_FILE in the status line
Jack Rudenkoe6309f0df63b
diff --git a/packages/cli/src/claude-runner-token-file.test.ts b/packages/cli/src/claude-runner-token-file.test.tsnew file mode 100644index 00000000..f72daaad--- /dev/null+++ b/packages/cli/src/claude-runner-token-file.test.ts@@ -0,0 +1,79 @@+/**+ * F3: a parent that hands a child `CLAUDISH_TOKEN_FILE` (team, the channel, a pane)+ * names the file the child's proxy writes. `createTempSettingsFile` used to ignore it+ * and point the status line at `~/.claudish/tokens-<port>.json`, then publish THAT+ * path as `CLAUDISH_TOKEN_FILE` to Claude Code, so the status line read a file nobody+ * wrote. One resolver, `resolveTokenFilePath`, now serves the writer's override, the+ * status line and the end-of-session summary.+ */++import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createTempSettingsFile } from "./claude-runner.js";+import { resolveTokenFilePath } from "./session/session-stats.js";++let home: string;+const saved: Record<string, string | undefined> = {};+const KEYS = ["HOME", "CLAUDISH_TOKEN_FILE"] as const;++beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), "claudish-token-file-"));+});++afterAll(() => rmSync(home, { recursive: true, force: true }));++function withEnv<T>(values: Partial<Record<(typeof KEYS)[number], string>>, fn: () => T): T {+ for (const k of KEYS) {+ saved[k] = process.env[k];+ if (values[k] === undefined) delete process.env[k];+ else process.env[k] = values[k];+ }+ try {+ return fn();+ } finally {+ for (const k of KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+ }+}++const created: string[] = [];+afterEach(() => {+ for (const p of created.splice(0)) rmSync(p, { force: true });+});++describe("resolveTokenFilePath", () => {+ test("an inherited CLAUDISH_TOKEN_FILE wins", () => {+ expect(+ resolveTokenFilePath(4000, { CLAUDISH_TOKEN_FILE: "/run/stats/a.json", HOME: home })+ ).toBe("/run/stats/a.json");+ });++ test("otherwise the port-keyed file under $HOME/.claudish", () => {+ expect(resolveTokenFilePath(4000, { HOME: home })).toBe(+ join(home, ".claudish", "tokens-4000.json")+ );+ });+});++describe("createTempSettingsFile", () => {+ test("returns, and points the status line at, an inherited CLAUDISH_TOKEN_FILE", () => {+ const inherited = join(home, "team-run", "stats", "slot-1.json");+ const settings = withEnv({ HOME: home, CLAUDISH_TOKEN_FILE: inherited }, () =>+ createTempSettingsFile("m", "4321", false)+ );+ created.push(settings.path);+ expect(settings.tokenFilePath).toBe(inherited);+ expect(settings.statusLine.command).toContain(inherited);+ expect(settings.statusLine.command).not.toContain("tokens-4321.json");+ });++ test("without one, keeps the port-keyed file", () => {+ const settings = withEnv({ HOME: home }, () => createTempSettingsFile("m", "4322", false));+ created.push(settings.path);+ expect(settings.tokenFilePath).toBe(join(home, ".claudish", "tokens-4322.json"));+ });+});diff --git a/packages/cli/src/claude-runner.ts b/packages/cli/src/claude-runner.tsindex 9785d779..48176554 100644--- a/packages/cli/src/claude-runner.ts+++ b/packages/cli/src/claude-runner.ts@@ -28,6 +28,7 @@ import { getProviderByName } from "./providers/provider-definitions.js";import { route } from "./providers/routing-rules.js";import { installRecoveryUi, shutdownRecoveryUi } from "./recovery/magmux-ui.js";import { applyRetryWatchdog, recoverySurfaceAllowed } from "./recovery/settings.js";+import { resolveTokenFilePath } from "./session/session-stats.js";import { setClaudeCodeRunning } from "./telemetry.js";import { beginTerminalIsolation } from "./terminal-isolation.js";import { getThemeMode } from "./theme/theme-mode.js";@@ -808,15 +809,21 @@ export function createTempSettingsFile(const timestamp = Date.now();const tempPath = join(claudishDir, `settings-${timestamp}.json`);- // Token file path - also in .claudish directory- const tokenFilePath = join(claudishDir, `tokens-${port}.json`);+ // The file the proxy's TokenTracker writes: an inherited CLAUDISH_TOKEN_FILE+ // (a team slot's or channel session's own path), else `tokens-<port>.json` in+ // .claudish. Resolved by the same function as the summary's reader, so the+ // status line can never be pointed at a file the tracker does not write.+ const inheritedTokenFile = Boolean(process.env[ENV.CLAUDISH_TOKEN_FILE]);+ const tokenFilePath = resolveTokenFilePath(port);// Sweep the orphans FIRST (so this session's fresh file is never a candidate),// then blank the file for the port we are about to use. Without this the// status line can show a dead session's provider, cost and context — the file- // is keyed by port, and ports are recycled.+ // is keyed by port, and ports are recycled. An inherited file is the parent's,+ // unique to this child and read by the parent, so it is left for the tracker+ // to create: a blank record would read as "answered with zero tokens".cleanupStaleTokenFiles(claudishDir);- initializeTokenFile(tokenFilePath);+ if (!inheritedTokenFile) initializeTokenFile(tokenFilePath);let statusCommand: string;diff --git a/packages/cli/src/session/session-stats.ts b/packages/cli/src/session/session-stats.tsindex 3d37a6a7..c9f648f9 100644--- a/packages/cli/src/session/session-stats.ts+++ b/packages/cli/src/session/session-stats.ts@@ -9,8 +9,8 @@*/import { readFileSync } from "node:fs";-import { homedir } from "node:os";import { join } from "node:path";+import { userHomeFrom } from "../channel/home-dir.js";import { type Baseline, baselineCost, getBaselines } from "./baseline-pricing.js";/** One tool's share of the session. */@@ -74,9 +74,24 @@ export interface SessionStats {billedInputTokens: number;}-/** The path `TokenTracker.writeFile` wrote to, resolved the same way it resolves it. */-export function tokenFilePath(port: number): string {- return process.env.CLAUDISH_TOKEN_FILE || join(homedir(), ".claudish", `tokens-${port}.json`);+/**+ * 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`);}const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);@@ -93,7 +108,7 @@ export function readSessionStats(): SessionStats | null {let raw: unknown;try {- raw = JSON.parse(readFileSync(tokenFilePath(port), "utf-8"));+ raw = JSON.parse(readFileSync(resolveTokenFilePath(port), "utf-8"));} catch {return null;}