{"version":3,"file":"status-segments.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/status-segments.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;GAiBG;AAEH,eAAO,MAAM,uBAAuB,wEAAyE,CAAC;AAE9G,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,uBAAuB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE3E;;;GAGG;AACH,eAAO,MAAM,4BAA4B,EAAE,SAAS,mBAAmB,EAA4B,CAAC;AAIpG;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,OAAO,GAAG,mBAAmB,EAAE,CAWhF;AAED,oDAAoD;AACpD,MAAM,WAAW,kBAAkB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,6DAA6D;IAC7D,IAAI,EAAE,MAAM,CAAC;CACb;AAED,gEAAgE;AAChE,MAAM,WAAW,cAAc;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,kBAAkB,EAAE,SAAS,CAAC,EAAE,cAAc,GAAG,MAAM,CAUpG;AAED,mFAAmF;AACnF,MAAM,WAAW,mBAAmB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CACxB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,mBAAmB,EAAE,KAAK,CAAC,EAAE,cAAc,GAAG,MAAM,CAGhG;AAED,oDAAoD;AACpD,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKlD;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAEvE;AAED,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAGrF;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAwD7F;;;;;;;;;GASG;AACH,qBAAa,aAAa;IACzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAQ;IACtC,OAAO,CAAC,KAAK,CAAyC;IACtD,yGAAyG;IACzG,OAAO,CAAC,QAAQ,CAA6B;IAC7C,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,GAAG,CAAe;IAC1B,OAAO,CAAC,QAAQ,CAA2B;IAE3C,YACC,MAAM,GAAE,kBAA8C,EACtD,GAAG,GAAE,MAAM,MAAiB,EAC5B,QAAQ,CAAC,EAAE,MAAM,IAAI,EAKrB;IAED,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAgCvC;IAED,UAAU,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAQjC;CACD","sourcesContent":["import { spawn } from \"node:child_process\";\n\n/**\n * Configurable status line segments for the footer.\n *\n * The footer is assembled from an ordered list of segment ids. The default\n * list (DEFAULT_STATUS_LINE_SEGMENTS) reproduces the historical footer\n * composition plus the cost segment, so enabling this feature is purely\n * additive: nothing disappears unless the user removes a segment via the\n * \"statusLine.segments\" setting.\n *\n * Segment ids:\n * - \"cwd\": current working directory, home-shortened (first line)\n * - \"git\": git branch with dirty marker (appended to the cwd line)\n * - \"tokens\": cumulative input/output tokens (up/down arrows)\n * - \"cache\": cache read/write tokens and latest cache hit rate\n * - \"cost\": cumulative session cost in USD\n * - \"context\": context window usage percentage\n * - \"model\": active model id, right-aligned\n */\n\nexport const STATUS_LINE_SEGMENT_IDS = [\"cwd\", \"git\", \"tokens\", \"cache\", \"cost\", \"context\", \"model\"] as const;\n\nexport type StatusLineSegmentId = (typeof STATUS_LINE_SEGMENT_IDS)[number];\n\n/**\n * Default composition: the historical footer (cwd, git branch, token stats,\n * context usage, model) plus the cost segment. Purely additive.\n */\nexport const DEFAULT_STATUS_LINE_SEGMENTS: readonly StatusLineSegmentId[] = STATUS_LINE_SEGMENT_IDS;\n\nconst KNOWN_SEGMENTS: ReadonlySet<string> = new Set(STATUS_LINE_SEGMENT_IDS);\n\n/**\n * Resolve the configured segment list. Unknown ids are dropped so a typo in\n * settings.json degrades gracefully instead of blanking the footer. Returns\n * the default composition when the config is missing, not an array, empty,\n * or contains only unknown ids.\n */\nexport function resolveStatusLineSegments(config: unknown): StatusLineSegmentId[] {\n\tif (!Array.isArray(config)) return [...DEFAULT_STATUS_LINE_SEGMENTS];\n\tconst resolved: StatusLineSegmentId[] = [];\n\tfor (const entry of config) {\n\t\tif (typeof entry !== \"string\") continue;\n\t\tconst id = entry.trim();\n\t\tif (!KNOWN_SEGMENTS.has(id)) continue;\n\t\tconst segment = id as StatusLineSegmentId;\n\t\tif (!resolved.includes(segment)) resolved.push(segment);\n\t}\n\treturn resolved.length > 0 ? resolved : [...DEFAULT_STATUS_LINE_SEGMENTS];\n}\n\n/** Token usage accumulated over a whole session. */\nexport interface SessionTokenTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\t/** Cost in USD as reported by providers (0 when unknown). */\n\tcost: number;\n}\n\n/** Per-million-token pricing rates from the model catalogue. */\nexport interface ModelCostRates {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n}\n\n/**\n * Cumulative session cost in USD. Prefers the provider-reported cost; when\n * that is zero but tokens were consumed and the catalogue knows the model\n * rates, estimates cost as tokens x price per million.\n */\nexport function computeSessionCostUsd(totals: SessionTokenTotals, modelCost?: ModelCostRates): number {\n\tif (totals.cost > 0) return totals.cost;\n\tif (!modelCost) return 0;\n\tconst estimate =\n\t\t(totals.input * modelCost.input +\n\t\t\ttotals.output * modelCost.output +\n\t\t\ttotals.cacheRead * modelCost.cacheRead +\n\t\t\ttotals.cacheWrite * modelCost.cacheWrite) /\n\t\t1_000_000;\n\treturn estimate > 0 ? estimate : 0;\n}\n\n/** Token usage of a single message, with the provider-reported cost when known. */\nexport interface MessageUsageForCost {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: { total: number };\n}\n\n/**\n * Cost in USD of one message's usage. Prefers the provider-reported cost; otherwise estimates it\n * with `rates`, which must be the rates of the model that PRODUCED the message. Summing this per\n * message keeps multi-model sessions (/plan phases, /model switches) correct, whereas pricing the\n * whole session at the current model's rates did not.\n */\nexport function computeMessageCostUsd(usage: MessageUsageForCost, rates?: ModelCostRates): number {\n\tif (usage.cost.total > 0) return usage.cost.total;\n\treturn computeSessionCostUsd({ ...usage, cost: 0 }, rates);\n}\n\n/** Format a USD cost for compact footer display. */\nexport function formatCostUsd(cost: number): string {\n\tif (cost <= 0) return \"$0.000\";\n\tif (cost < 0.001) return \"$<0.001\";\n\tif (cost >= 100) return `$${cost.toFixed(0)}`;\n\treturn `$${cost.toFixed(3)}`;\n}\n\n/**\n * Parse `git status --porcelain` output. Returns true when the working tree\n * or index has any change (dirty), false for a clean tree.\n */\nexport function parseGitPorcelainDirty(porcelainOutput: string): boolean {\n\treturn porcelainOutput.trim().length > 0;\n}\n\n/** Render the git segment text: branch name plus a dirty marker. */\nexport function formatGitSegment(branch: string | null, dirty: boolean): string | null {\n\tif (!branch) return null;\n\treturn dirty ? `${branch}*` : branch;\n}\n\n/**\n * Runner for `git status --porcelain`; injectable for tests. May answer synchronously or\n * asynchronously; the default runner is asynchronous so the footer never blocks rendering.\n */\nexport type GitPorcelainRunner = (repoDir: string) => string | null | Promise<string | null>;\n\n/** Upper bound for one background `git status`, so a hung git cannot pin a child process. */\nconst GIT_STATUS_TIMEOUT_MS = 10_000;\n\n/**\n * Asynchronous `git status --porcelain`. Only emptiness matters, so the process is stopped as\n * soon as it prints a non-blank byte: on large repositories this avoids walking every change.\n * `--no-optional-locks` keeps the background call from taking index.lock.\n */\nfunction defaultGitPorcelainRunner(repoDir: string): Promise<string | null> {\n\treturn new Promise((resolvePromise) => {\n\t\tlet settled = false;\n\t\tlet output = \"\";\n\t\tconst finish = (value: string | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tresolvePromise(value);\n\t\t};\n\t\tlet child: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tchild = spawn(\"git\", [\"--no-optional-locks\", \"status\", \"--porcelain\"], {\n\t\t\t\tcwd: repoDir,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t} catch {\n\t\t\tresolvePromise(null);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.kill();\n\t\t\tfinish(null);\n\t\t}, GIT_STATUS_TIMEOUT_MS);\n\t\ttimer.unref?.();\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk: string) => {\n\t\t\toutput += chunk;\n\t\t\tif (output.trim().length > 0) {\n\t\t\t\tfinish(output);\n\t\t\t\tchild.kill();\n\t\t\t}\n\t\t});\n\t\t// \"error\" (git missing: ENOENT) must be consumed or Node raises an unhandled exception.\n\t\tchild.on(\"error\", () => finish(null));\n\t\tchild.on(\"close\", (code) => finish(code === 0 ? output : null));\n\t});\n}\n\ninterface GitDirtyCacheEntry {\n\t/** null when git failed or the path is not a repository. */\n\tdirty: boolean | null;\n\texpiresAt: number;\n}\n\n/**\n * Dirty-state lookup with a 2 second TTL cache, called from the footer render path.\n *\n * With an asynchronous runner (the default), isDirty() never blocks: it returns the last known\n * value (null before the first answer) and refreshes it in the background, at most one git\n * process per repository at a time; `onUpdate` fires when a refresh changes the answer so the\n * caller can re-render. The previous implementation ran a synchronous `git status` on the render\n * path every 2 seconds, freezing the TUI on large repositories and on Windows.\n * Returns null when git is unavailable or the path is not a repo.\n */\nexport class GitDirtyCache {\n\tprivate static readonly TTL_MS = 2000;\n\tprivate cache = new Map<string, GitDirtyCacheEntry>();\n\t/** Token of the refresh in flight per repository; invalidate() drops it so a stale answer is ignored. */\n\tprivate inFlight = new Map<string, number>();\n\tprivate nextRefreshToken = 0;\n\tprivate runner: GitPorcelainRunner;\n\tprivate now: () => number;\n\tprivate onUpdate: (() => void) | undefined;\n\n\tconstructor(\n\t\trunner: GitPorcelainRunner = defaultGitPorcelainRunner,\n\t\tnow: () => number = Date.now,\n\t\tonUpdate?: () => void,\n\t) {\n\t\tthis.runner = runner;\n\t\tthis.now = now;\n\t\tthis.onUpdate = onUpdate;\n\t}\n\n\tisDirty(repoDir: string): boolean | null {\n\t\tconst now = this.now();\n\t\tconst cached = this.cache.get(repoDir);\n\t\tif (cached && cached.expiresAt > now) {\n\t\t\treturn cached.dirty;\n\t\t}\n\t\tif (this.inFlight.has(repoDir)) {\n\t\t\treturn cached?.dirty ?? null;\n\t\t}\n\n\t\tconst output = this.runner(repoDir);\n\t\tif (!(output instanceof Promise)) {\n\t\t\tif (output === null) return null;\n\t\t\tconst dirty = parseGitPorcelainDirty(output);\n\t\t\tthis.cache.set(repoDir, { dirty, expiresAt: now + GitDirtyCache.TTL_MS });\n\t\t\treturn dirty;\n\t\t}\n\n\t\tconst token = ++this.nextRefreshToken;\n\t\tthis.inFlight.set(repoDir, token);\n\t\tvoid output\n\t\t\t.catch(() => null)\n\t\t\t.then((result) => {\n\t\t\t\tif (this.inFlight.get(repoDir) !== token) return;\n\t\t\t\tthis.inFlight.delete(repoDir);\n\t\t\t\tconst dirty = result === null ? null : parseGitPorcelainDirty(result);\n\t\t\t\tconst previous = this.cache.get(repoDir)?.dirty ?? null;\n\t\t\t\t// Failures are cached too, so a broken git is not respawned on every frame.\n\t\t\t\tthis.cache.set(repoDir, { dirty, expiresAt: this.now() + GitDirtyCache.TTL_MS });\n\t\t\t\tif (dirty !== previous) this.onUpdate?.();\n\t\t\t});\n\t\treturn cached?.dirty ?? null;\n\t}\n\n\tinvalidate(repoDir?: string): void {\n\t\tif (repoDir === undefined) {\n\t\t\tthis.cache.clear();\n\t\t\tthis.inFlight.clear();\n\t\t} else {\n\t\t\tthis.cache.delete(repoDir);\n\t\t\tthis.inFlight.delete(repoDir);\n\t\t}\n\t}\n}\n"]}