Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(statusline): keep a nested claudish off its parent session's token file
Jack Rudenkoca64ba8505cf
diff --git a/packages/cli/src/claude-runner-token-file.test.ts b/packages/cli/src/claude-runner-token-file.test.tsindex f72daaad..def6b71f 100644--- a/packages/cli/src/claude-runner-token-file.test.ts+++ b/packages/cli/src/claude-runner-token-file.test.ts@@ -8,15 +8,15 @@*/import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";-import { mkdtempSync, rmSync } from "node:fs";+import { mkdtempSync, readFileSync, 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";+import { assignedTokenFile, resolveTokenFilePath } from "./session/token-file.js";let home: string;const saved: Record<string, string | undefined> = {};-const KEYS = ["HOME", "CLAUDISH_TOKEN_FILE"] as const;+const KEYS = ["HOME", "CLAUDISH_TOKEN_FILE", "CLAUDISH_PUBLISHED_TOKEN_FILE"] as const;beforeAll(() => {home = mkdtempSync(join(tmpdir(), "claudish-token-file-"));@@ -57,6 +57,17 @@ describe("resolveTokenFilePath", () => {join(home, ".claudish", "tokens-4000.json"));});++ test("an enclosing session's PUBLISHED file is not an assignment: a nested claudish keeps its own", () => {+ const parent = join(home, ".claudish", "tokens-3999.json");+ const env = { HOME: home, CLAUDISH_TOKEN_FILE: parent, CLAUDISH_PUBLISHED_TOKEN_FILE: parent };+ expect(assignedTokenFile(env)).toBeNull();+ expect(resolveTokenFilePath(4000, env)).toBe(join(home, ".claudish", "tokens-4000.json"));+ // a team slot / channel session sets a path of its own, which still wins+ expect(+ resolveTokenFilePath(4000, { ...env, CLAUDISH_TOKEN_FILE: "/run/stats/slot.json" })+ ).toBe("/run/stats/slot.json");+ });});describe("createTempSettingsFile", () => {@@ -71,6 +82,23 @@ describe("createTempSettingsFile", () => {expect(settings.statusLine.command).not.toContain("tokens-4321.json");});+ test("a nested claudish (Bash tool of a claudish session) never points at the parent's file", () => {+ const parent = join(home, ".claudish", "tokens-3998.json");+ const settings = withEnv(+ { HOME: home, CLAUDISH_TOKEN_FILE: parent, CLAUDISH_PUBLISHED_TOKEN_FILE: parent },+ () => createTempSettingsFile("m", "4323", false)+ );+ created.push(settings.path);+ expect(settings.tokenFilePath).toBe(join(home, ".claudish", "tokens-4323.json"));+ expect(settings.statusLine.command).not.toContain(parent);+ });++ test("claude-runner publishes the session's file under both names (source guard)", () => {+ const src = readFileSync(join(import.meta.dir, "claude-runner.ts"), "utf8");+ expect(src).toContain("[ENV.CLAUDISH_TOKEN_FILE]: tokenFilePath,");+ expect(src).toContain("[ENV.CLAUDISH_PUBLISHED_TOKEN_FILE]: tokenFilePath,");+ });+test("without one, keeps the port-keyed file", () => {const settings = withEnv({ HOME: home }, () => createTempSettingsFile("m", "4322", false));created.push(settings.path);diff --git a/packages/cli/src/claude-runner.ts b/packages/cli/src/claude-runner.tsindex 1d32f0eb..4ea8429e 100644--- a/packages/cli/src/claude-runner.ts+++ b/packages/cli/src/claude-runner.ts@@ -33,7 +33,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 { assignedTokenFile, resolveTokenFilePath } from "./session/token-file.js";import { setClaudeCodeRunning } from "./telemetry.js";import { beginTerminalIsolation } from "./terminal-isolation.js";import { getThemeMode } from "./theme/theme-mode.js";@@ -814,21 +814,23 @@ export function createTempSettingsFile(const timestamp = Date.now();const tempPath = join(claudishDir, `settings-${timestamp}.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]);+ // The file the proxy's TokenTracker writes: one a parent ASSIGNED (a team slot's or+ // channel session's own CLAUDISH_TOKEN_FILE), else `tokens-<port>.json` in .claudish.+ // An enclosing claudish session's PUBLISHED file (inherited by a claudish run from its+ // Bash tool) is not an assignment — see assignedTokenFile. Resolved by the same+ // function as the tracker and the summary, so the status line can never be pointed at+ // a file the tracker does not write.+ const assignedFile = assignedTokenFile(process.env) !== null;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. 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".+ // is keyed by port, and ports are recycled. An assigned file is the parent's to+ // read, unique to this child, so it is left for the tracker to create: a blank+ // record would read as "answered with zero tokens".cleanupStaleTokenFiles(claudishDir);- if (!inheritedTokenFile) initializeTokenFile(tokenFilePath);+ if (!assignedFile) initializeTokenFile(tokenFilePath);let statusCommand: string;@@ -1685,6 +1687,9 @@ export async function runClaudeWithProxy(// of guessing a path, and can tell that the session is proxied (and therefore// that Anthropic plan/rate-limit numbers describe the wrong account).[ENV.CLAUDISH_TOKEN_FILE]: tokenFilePath,+ // ...and marked as published, so a claudish started from this session's Bash tool+ // keeps a file of its own instead of writing into ours (assignedTokenFile).+ [ENV.CLAUDISH_PUBLISHED_TOKEN_FILE]: tokenFilePath,// Turn on Claude Code's experimental advisor tool under --advisor. The value// is `"1"` and nothing else (see resolveAdvisorToolEnv), and this spread is// empty when the parent environment already carries one — the `...process.env`diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex 17394dab..a986868b 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -14,6 +14,10 @@ export const ENV = {// CLAUDISH_TOKEN_FILE is running against a proxied, non-Anthropic account and// must not render Anthropic plan/rate-limit data.CLAUDISH_TOKEN_FILE: "CLAUDISH_TOKEN_FILE", // Absolute path to ~/.claudish/tokens-<port>.json for this session+ // The same path again, set ONLY by claude-runner when it publishes the session's own+ // file to Claude Code. A claudish started from that session's Bash tool inherits both;+ // equal values mean "a parent session's status-line file", never "your file".+ CLAUDISH_PUBLISHED_TOKEN_FILE: "CLAUDISH_PUBLISHED_TOKEN_FILE",CLAUDISH_PROVIDER_NAME: "CLAUDISH_PROVIDER_NAME", // Provider display name (e.g. "Alibaba Token Plan"); UNSET when not known at spawn timeANTHROPIC_MODEL: "ANTHROPIC_MODEL", // Claude Code standard env var for model selectionANTHROPIC_SMALL_FAST_MODEL: "ANTHROPIC_SMALL_FAST_MODEL", // Claude Code standard env var for fast modeldiff --git a/packages/cli/src/session/token-file.ts b/packages/cli/src/session/token-file.tsindex e7922fa0..1fceea21 100644--- a/packages/cli/src/session/token-file.ts+++ b/packages/cli/src/session/token-file.ts@@ -18,9 +18,24 @@import { join } from "node:path";import { userHomeFrom } from "../channel/home-dir.js";+/**+ * The token file a PARENT assigned to this process: `CLAUDISH_TOKEN_FILE`, unless it is+ * only the path an enclosing claudish session published for its status line+ * (`CLAUDISH_PUBLISHED_TOKEN_FILE` carries the same value). A claudish launched from a+ * claudish session's Bash tool inherits that published path; honouring it made the+ * nested session's tracker overwrite the parent's file, and both status lines (and the+ * parent's summary) showed each other's model, cost and context. Team slots and channel+ * sessions set `CLAUDISH_TOKEN_FILE` to a path of their own, which never equals it.+ */+export function assignedTokenFile(env: Record<string, string | undefined>): string | null {+ const f = env.CLAUDISH_TOKEN_FILE;+ if (!f || f === env.CLAUDISH_PUBLISHED_TOKEN_FILE) return null;+ return f;+}+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`);+ return assignedTokenFile(env) ?? join(userHomeFrom(env), ".claudish", `tokens-${port}.json`);}