import * as path from "node:path"; import type { ExtensionContext, ReadonlyFooterDataProvider, Theme } from "@earendil-works/pi-coding-agent"; import { stripTerminalSequences, truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui"; import { CustomStyleConfig, resolveSeparator, styleSeparator } from "./presets"; import { BeautifierState, defaultBeautifierState, resolveActivePreset } from "./config"; import { Badge, formatBadge, formatFoldedBadges, type ThemeLike } from "./badge"; interface UsageSlice { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; cost?: { total?: number }; } interface FooterSessionStats { sessionId?: string; leafId?: string | null; entryCount: number; limitsModelId?: string; input: number; output: number; cacheRead: number; cacheWrite: number; cost: number; latestHitRate?: number; } export interface FooterRenderContext { cwd?: string; model?: { id?: string; name?: string; provider?: string; reasoning?: boolean; contextWindow?: number; }; routedModel?: { model?: { id?: string }; thinkingLevel?: string }; thinkingLevel?: string; sessionManager?: { getEntries?: () => unknown[]; getBranch?: () => unknown[]; getSessionId?: () => string; getLeafId?: () => string | null; getEntryCount?: () => number; getSessionName?: () => string | undefined; getCwd?: () => string; }; getContextUsage?: () => { tokens?: number | null; contextWindow?: number; percent: number | null } | undefined; modelRegistry?: { isUsingSubscription?: (provider: string) => boolean }; } export function formatCwdForFooter(cwd: string, home: string | undefined): string { if (!home) return cwd; const resolvedCwd = path.resolve(cwd); const resolvedHome = path.resolve(home); const rel = path.relative(resolvedHome, resolvedCwd); const insideHome = rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)); if (!insideHome) return cwd; return rel === "" ? "~" : `~${path.sep}${rel}`; } export function formatCount(n: number): string { if (n < 1000) return `${n}`; if (n < 10000) return `${(n / 1000).toFixed(1)}k`; if (n < 1000000) return `${Math.round(n / 1000)}k`; if (n < 10000000) return `${(n / 1000000).toFixed(1)}M`; return `${Math.round(n / 1000000)}M`; } function addUsage(acc: FooterSessionStats, u: UsageSlice | undefined): void { if (!u) return; acc.input += u.input || 0; acc.output += u.output || 0; acc.cacheRead += u.cacheRead || 0; acc.cacheWrite += u.cacheWrite || 0; acc.cost += u.cost?.total || 0; } function computeSessionStats(entries: unknown[]): Omit { const stats = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, latestHitRate: undefined as number | undefined, }; for (const raw of entries) { const entry = raw as { type?: string; usage?: UsageSlice; message?: { role?: string; usage?: UsageSlice }; }; if (!entry) continue; if (entry.type === "usage") { addUsage(stats as FooterSessionStats, entry.usage); } else if (entry.type === "message" && entry.message?.usage) { addUsage(stats as FooterSessionStats, entry.message.usage); if (entry.message.role === "assistant") { const u = entry.message.usage; const prompt = (u.input || 0) + (u.cacheRead || 0) + (u.cacheWrite || 0); stats.latestHitRate = prompt > 0 ? ((u.cacheRead || 0) / prompt) * 100 : undefined; } } else if (entry.type === "branch_summary" || entry.type === "compaction") { addUsage(stats as FooterSessionStats, entry.usage); } } return stats; } function buildMetricsSegments( stats: Omit, ctx: FooterRenderContext | undefined, preset: CustomStyleConfig, theme: ThemeLike | null | undefined ): { fullStyled: string; fullPlain: string; compactStyled: string; compactPlain: string; } { const hasFg = Boolean(theme && typeof theme.fg === "function"); const fullParts: string[] = []; const compactParts: string[] = []; const compactPlainParts: string[] = []; if (preset.showTokens !== false) { if (stats.input > 0) fullParts.push(`↑${formatCount(stats.input)}`); if (stats.output > 0) fullParts.push(`↓${formatCount(stats.output)}`); if (stats.cacheRead > 0) fullParts.push(`R${formatCount(stats.cacheRead)}`); if (stats.cacheWrite > 0) fullParts.push(`W${formatCount(stats.cacheWrite)}`); if ((stats.cacheRead > 0 || stats.cacheWrite > 0) && stats.latestHitRate !== undefined) { fullParts.push(`CH${stats.latestHitRate.toFixed(1)}%`); } } const provider = ctx?.model?.provider; const usingSubscription = provider ? provider === "kimi-coding" || Boolean(ctx?.modelRegistry?.isUsingSubscription?.(provider)) : false; if (preset.showCost !== false && (stats.cost > 0 || usingSubscription)) { const costStr = `$${stats.cost.toFixed(3)}${usingSubscription ? " (sub)" : ""}`; fullParts.push(costStr); compactParts.push(costStr); compactPlainParts.push(costStr); } const contextUsage = ctx?.getContextUsage?.(); const contextWindow = contextUsage?.contextWindow ?? ctx?.model?.contextWindow ?? 0; if (contextUsage || contextWindow > 0) { const pct = contextUsage?.percent; const winLabel = contextWindow > 0 ? `/${formatCount(contextWindow)}` : ""; const pctText = pct !== undefined && pct !== null ? `${pct.toFixed(1)}%` : "?"; const pctColor: "error" | "warning" | "dim" = pct !== undefined && pct !== null && pct > 90 ? "error" : pct !== undefined && pct !== null && pct > 70 ? "warning" : "dim"; const plainCtx = `${pctText}${winLabel}`; const styledCtx = hasFg && pctColor !== "dim" ? theme!.fg(pctColor, plainCtx) : plainCtx; fullParts.push(styledCtx); compactParts.push(styledCtx); compactPlainParts.push(plainCtx); } const compactPlain = compactPlainParts.join(" "); const dimWrap = (raw: string): string => (raw && hasFg ? theme!.fg("dim", raw) : raw); return { fullStyled: dimWrap(fullParts.join(" ")), fullPlain: stripTerminalSequences(fullParts.join(" ")), compactStyled: dimWrap(compactParts.join(" ")), compactPlain, }; } function formatRightModel( ctx: FooterRenderContext | undefined, availableProviderCount: number, maxAllowedWidth: number, theme: ThemeLike | null | undefined ): { styled: string; plain: string } { const modelId = ctx?.model?.id || ctx?.model?.name || ""; if (!modelId) return { styled: "", plain: "" }; const hasFg = Boolean(theme && typeof theme.fg === "function"); let base = modelId; if (ctx?.model?.reasoning !== false && ctx?.thinkingLevel) { base = ctx.thinkingLevel === "off" ? `${modelId} • thinking off` : `${modelId} • ${ctx.thinkingLevel}`; } if (ctx?.routedModel?.model?.id) { const rt = ctx.routedModel.thinkingLevel ? ` • ${ctx.routedModel.thinkingLevel}` : ""; base += ` → ${ctx.routedModel.model.id}${rt}`; } const withProvider = availableProviderCount > 1 && ctx?.model?.provider ? `(${ctx.model.provider}) ${base}` : base; const plain = visibleWidth(withProvider) <= maxAllowedWidth ? withProvider : base; return { plain, styled: hasFg ? theme!.fg("muted", plain) : plain, }; } export function renderFooterWithState( width: number, theme: ThemeLike | null | undefined, footerData: Partial | undefined, ctx: FooterRenderContext | undefined, style: string, customCfg?: CustomStyleConfig, cachedStats?: Omit, state: BeautifierState = defaultBeautifierState ): { lines: string[]; hasSpinner: boolean } { const { styleKey, preset } = resolveActivePreset(style, customCfg, state.runtime.custom, "claude"); const hasFg = Boolean(theme && typeof theme.fg === "function"); const sep = resolveSeparator(preset); const styledSep = styleSeparator(sep, theme); const sepVis = visibleWidth(sep); const cwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd(); let branchText = formatCwdForFooter(cwd, process.env.HOME || process.env.USERPROFILE); const branch = typeof footerData?.getGitBranch === "function" ? footerData.getGitBranch() : undefined; if (branch) branchText = `${branchText} (${branch})`; const sessionName = ctx?.sessionManager?.getSessionName?.(); if (sessionName) branchText = `${branchText} • ${sessionName}`; const entries = ctx?.sessionManager?.getEntries?.() || ctx?.sessionManager?.getBranch?.() || []; const stats = cachedStats ?? computeSessionStats(entries); const metrics = buildMetricsSegments(stats, ctx, preset, theme); const providerCount = typeof footerData?.getAvailableProviderCount === "function" ? footerData.getAvailableProviderCount() : 1; const modelBase = formatRightModel(ctx, providerCount, width, theme); const leftVis = visibleWidth(branchText); let line1 = ""; const tryRight = (metricsStyled: string, metricsPlain: string): boolean => { const rightPartsPlain = [metricsPlain, modelBase.plain].filter(Boolean); const rightPartsStyled = [metricsStyled, modelBase.styled].filter(Boolean); if (rightPartsPlain.length === 0) return false; const rightPlain = rightPartsPlain.join(sep); const rightVis = visibleWidth(rightPlain); if (leftVis + 1 + rightVis > width) return false; const styledLeft = hasFg ? theme!.fg("dim", branchText) : branchText; line1 = `${styledLeft}${" ".repeat(width - leftVis - rightVis)}${rightPartsStyled.join(styledSep)}`; return true; }; if ( !(metrics.fullPlain && tryRight(metrics.fullStyled, metrics.fullPlain)) && !(metrics.compactPlain && tryRight(metrics.compactStyled, metrics.compactPlain)) && !(modelBase.plain && tryRight("", modelBase.plain)) ) { if (modelBase.plain && width >= 12) { const avail = Math.max(0, width - 1); const rightBudget = Math.min(visibleWidth(modelBase.plain), avail, Math.max(6, Math.floor(avail / 2))); const leftBudget = Math.max(0, avail - rightBudget); const trimmedBranch = truncateToWidth(branchText, leftBudget, "…"); const trimmedModel = truncateToWidth(modelBase.plain, rightBudget, "…"); const gap = Math.max(1, width - visibleWidth(trimmedBranch) - visibleWidth(trimmedModel)); line1 = (hasFg ? theme!.fg("dim", trimmedBranch) : trimmedBranch) + " ".repeat(gap) + (hasFg ? theme!.fg("muted", trimmedModel) : trimmedModel); } else { const trimmed = truncateToWidth(branchText, width, "…"); line1 = (hasFg ? theme!.fg("dim", trimmed) : trimmed) + " ".repeat(Math.max(0, width - visibleWidth(trimmed))); } } const lines = [line1]; let hasSpinner = false; const statusEntries: Array<[string, string]> = []; if (footerData && typeof footerData.getExtensionStatuses === "function") { try { const map = footerData.getExtensionStatuses(); if (map && typeof map.entries === "function") { for (const [k, v] of map.entries()) { if (v) statusEntries.push([k, state.rawStatuses.get(k) ?? v]); } } } catch { // Ignore host accessor errors cleanly. } } if (statusEntries.length === 0) { for (const [k, v] of state.rawStatuses.entries()) { if (v) statusEntries.push([k, v]); } } if (statusEntries.length > 0 && width > 4) { statusEntries.sort(([a], [b]) => a.localeCompare(b)); const badges = statusEntries .map(([k, v]) => formatBadge(k, v, theme, styleKey, preset)) .filter((b): b is Badge => b !== null); hasSpinner = badges.some((b) => b.isSpinning); if (badges.length > 0) { void sepVis; lines.push(formatFoldedBadges(badges, Math.max(1, width - 2), theme)); } } return { lines, hasSpinner }; } export function renderBeautifiedFooter( width: number, _tui: TUI | null, theme: ThemeLike | null | undefined, footerData: Partial | undefined, ctx: FooterRenderContext | undefined, style: string, customCfg?: CustomStyleConfig, state: BeautifierState = defaultBeautifierState ): string[] { return renderFooterWithState(width, theme, footerData, ctx, style, customCfg, undefined, state).lines; } export function createFooterFactory(ctx: ExtensionContext, state: BeautifierState = defaultBeautifierState) { return (tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => { let spinnerTimer: ReturnType | undefined; let cached: FooterSessionStats | undefined; const stopSpinner = (): void => { if (spinnerTimer) { clearInterval(spinnerTimer); spinnerTimer = undefined; } }; const getCachedStats = (): Omit => { const sm = ctx.sessionManager; const entries = sm?.getEntries?.() || sm?.getBranch?.() || []; const sessionId = sm?.getSessionId?.(); const leafId = sm?.getLeafId?.(); const entryCount = entries.length; const limitsModelId = ctx.model?.id; if ( cached && cached.sessionId === sessionId && cached.leafId === leafId && cached.entryCount === entryCount && cached.limitsModelId === limitsModelId ) { return cached; } const computed = computeSessionStats(entries); cached = { sessionId, leafId, entryCount, limitsModelId, ...computed }; return cached; }; const unsub = typeof footerData?.onBranchChange === "function" ? footerData.onBranchChange(() => tui.requestRender()) : undefined; return { dispose(): void { stopSpinner(); unsub?.(); }, invalidate(): void { // Re-evaluate metrics lazily via cached signature on next render. }, render(width: number): string[] { if (state.runtime.style === "off" || !state.runtime.fullFooter) { stopSpinner(); return []; } const result = renderFooterWithState( width, theme, footerData, ctx as unknown as FooterRenderContext, state.runtime.style, state.runtime.custom, getCachedStats(), state ); if (result.hasSpinner && tui && typeof tui.requestRender === "function") { if (!spinnerTimer) { spinnerTimer = setInterval(() => tui.requestRender(), 300); spinnerTimer.unref?.(); } } else { stopSpinner(); } return result.lines; }, }; }; }