{"version":3,"file":"footer.d.ts","sourceRoot":"","sources":["../../../../src/modes/interactive/components/footer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,SAAS,EAAiC,MAAM,cAAc,CAAC;AAC7E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AAwBxF;;GAEG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAMlD;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAYhF;AAED;;;GAGG;AACH,qBAAa,eAAgB,YAAW,SAAS;IAChD,OAAO,CAAC,kBAAkB,CAAQ;IAClC,OAAO,CAAC,IAAI,CAAyB;IACrC,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,UAAU,CAA6B;IAC/C,OAAO,CAAC,WAAW,CAA2C;IAE9D,YACC,OAAO,EAAE,YAAY,EACrB,UAAU,EAAE,0BAA0B,EACtC,WAAW,CAAC,EAAE,MAAM,MAAM,EAAE,GAAG,SAAS,EAKxC;IAED,UAAU,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAEtC;IAED,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAE5C;IAED,kEAAkE;IAClE,OAAO,CAAC,IAAI,EAAE,KAAK,GAAG,MAAM,GAAG,IAAI,CAElC;IAED;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAS3B;;;OAGG;IACH,UAAU,IAAI,IAAI,CAEjB;IAED;;;OAGG;IACH,OAAO,IAAI,IAAI,CAEd;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAoN9B;CACD","sourcesContent":["import { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport { type Component, truncateToWidth, visibleWidth } from \"phi-code-tui\";\nimport type { AgentSession } from \"../../../core/agent-session.ts\";\nimport { areExperimentalFeaturesEnabled } from \"../../../core/experimental.ts\";\nimport type { ReadonlyFooterDataProvider } from \"../../../core/footer-data-provider.ts\";\nimport { addUsageToTotals, createUsageTotals } from \"../../../core/usage-totals.ts\";\nimport { theme } from \"../theme/theme.ts\";\nimport {\n\tcomputeMessageCostUsd,\n\tformatCostUsd,\n\tformatGitSegment,\n\ttype ModelCostRates,\n\tresolveStatusLineSegments,\n\ttype StatusLineSegmentId,\n} from \"./status-segments.ts\";\n\n/**\n * Sanitize text for display in a single-line status.\n * Removes newlines, tabs, carriage returns, and other control characters.\n */\nfunction sanitizeStatusText(text: string): string {\n\t// Replace newlines, tabs, carriage returns with space, then collapse multiple spaces\n\treturn text\n\t\t.replace(/[\\r\\n\\t]/g, \" \")\n\t\t.replace(/ +/g, \" \")\n\t\t.trim();\n}\n\n/**\n * Format token counts for compact footer display.\n */\nexport function formatTokens(count: number): string {\n\tif (count < 1000) return count.toString();\n\tif (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n\tif (count < 1000000) return `${Math.round(count / 1000)}k`;\n\tif (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n\treturn `${Math.round(count / 1000000)}M`;\n}\n\nexport function formatCwdForFooter(cwd: string, home: string | undefined): string {\n\tif (!home) return cwd;\n\n\tconst resolvedCwd = resolve(cwd);\n\tconst resolvedHome = resolve(home);\n\tconst relativeToHome = relative(resolvedHome, resolvedCwd);\n\tconst isInsideHome =\n\t\trelativeToHome === \"\" ||\n\t\t(relativeToHome !== \"..\" && !relativeToHome.startsWith(`..${sep}`) && !isAbsolute(relativeToHome));\n\n\tif (!isInsideHome) return cwd;\n\treturn relativeToHome === \"\" ? \"~\" : `~${sep}${relativeToHome}`;\n}\n\n/**\n * Footer component that shows pwd, token stats, and context usage.\n * Computes token/context stats from session, gets git branch and extension statuses from provider.\n */\nexport class FooterComponent implements Component {\n\tprivate autoCompactEnabled = true;\n\tprivate mode: \"act\" | \"plan\" = \"act\";\n\tprivate session: AgentSession;\n\tprivate footerData: ReadonlyFooterDataProvider;\n\tprivate getSegments: (() => string[] | undefined) | undefined;\n\n\tconstructor(\n\t\tsession: AgentSession,\n\t\tfooterData: ReadonlyFooterDataProvider,\n\t\tgetSegments?: () => string[] | undefined,\n\t) {\n\t\tthis.session = session;\n\t\tthis.footerData = footerData;\n\t\tthis.getSegments = getSegments;\n\t}\n\n\tsetSession(session: AgentSession): void {\n\t\tthis.session = session;\n\t}\n\n\tsetAutoCompactEnabled(enabled: boolean): void {\n\t\tthis.autoCompactEnabled = enabled;\n\t}\n\n\t/** Set the active input mode shown by the Act/Plan indicators. */\n\tsetMode(mode: \"act\" | \"plan\"): void {\n\t\tthis.mode = mode;\n\t}\n\n\t/**\n\t * Build the bottom-right Act/Plan mode indicator line.\n\t * The active mode is a filled, colored bullet; the inactive mode is a dim\n\t * hollow bullet. Right-aligned to the footer width.\n\t */\n\tprivate renderModeIndicator(width: number): string {\n\t\tconst actActive = this.mode === \"act\";\n\t\tconst act = actActive ? theme.fg(\"success\", \"● Act\") : theme.fg(\"dim\", \"○ Act\");\n\t\tconst plan = actActive ? theme.fg(\"dim\", \"○ Plan\") : theme.fg(\"accent\", \"● Plan\");\n\t\tconst indicator = `${act}   ${plan}`;\n\t\tconst pad = Math.max(0, width - visibleWidth(indicator));\n\t\treturn \" \".repeat(pad) + indicator;\n\t}\n\n\t/**\n\t * No-op: git branch caching now handled by provider.\n\t * Kept for compatibility with existing call sites in interactive-mode.\n\t */\n\tinvalidate(): void {\n\t\t// No-op: git branch is cached/invalidated by provider\n\t}\n\n\t/**\n\t * Clean up resources.\n\t * Git watcher cleanup now handled by provider.\n\t */\n\tdispose(): void {\n\t\t// Git watcher cleanup handled by provider\n\t}\n\n\trender(width: number): string[] {\n\t\tconst state = this.session.state;\n\t\tconst segments = resolveStatusLineSegments(this.getSegments?.());\n\t\tconst hasSegment = (id: StatusLineSegmentId) => segments.includes(id);\n\n\t\t// Calculate cumulative usage from ALL session entries (not just post-compaction messages)\n\t\tconst usageTotals = createUsageTotals();\n\t\tlet latestCacheHitRate: number | undefined;\n\t\t// Cost is accumulated per message: an unpriced response is estimated at the catalogue rates\n\t\t// of the model that produced it, not the current model (multi-model sessions, /plan phases).\n\t\t// Usage without a known producer (tool results, summaries) falls back to the current model.\n\t\tlet sessionCost = 0;\n\t\tconst currentRates = state.model?.cost;\n\t\tconst ratesByModel = new Map<string, ModelCostRates | undefined>();\n\t\tconst runtime = this.session.modelRuntime;\n\t\tconst ratesFor = (provider: string, modelId: string): ModelCostRates | undefined => {\n\t\t\tconst key = `${provider}/${modelId}`;\n\t\t\tif (!ratesByModel.has(key)) {\n\t\t\t\t// Optional lookup: the footer renders on every frame and must not fail on a partial runtime.\n\t\t\t\tconst model = typeof runtime?.getModel === \"function\" ? runtime.getModel(provider, modelId) : undefined;\n\t\t\t\tratesByModel.set(key, model?.cost);\n\t\t\t}\n\t\t\treturn ratesByModel.get(key);\n\t\t};\n\n\t\tfor (const entry of this.session.sessionManager.getEntries()) {\n\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\taddUsageToTotals(usageTotals, entry.message.usage);\n\t\t\t\tsessionCost += computeMessageCostUsd(\n\t\t\t\t\tentry.message.usage,\n\t\t\t\t\tratesFor(entry.message.provider, entry.message.model),\n\t\t\t\t);\n\n\t\t\t\tconst latestPromptTokens =\n\t\t\t\t\tentry.message.usage.input + entry.message.usage.cacheRead + entry.message.usage.cacheWrite;\n\t\t\t\tlatestCacheHitRate =\n\t\t\t\t\tlatestPromptTokens > 0 ? (entry.message.usage.cacheRead / latestPromptTokens) * 100 : undefined;\n\t\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\t\taddUsageToTotals(usageTotals, entry.message.usage);\n\t\t\t\tsessionCost += computeMessageCostUsd(entry.message.usage, currentRates);\n\t\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\t\taddUsageToTotals(usageTotals, entry.usage);\n\t\t\t\tsessionCost += computeMessageCostUsd(entry.usage, currentRates);\n\t\t\t}\n\t\t}\n\n\t\t// Calculate context usage from session (handles compaction correctly).\n\t\t// After compaction, tokens are unknown until the next LLM response.\n\t\tconst contextUsage = this.session.getContextUsage();\n\t\tconst contextWindow = contextUsage?.contextWindow ?? state.model?.contextWindow ?? 0;\n\t\tconst contextPercentValue = contextUsage?.percent ?? 0;\n\t\tconst contextPercent = contextUsage?.percent !== null ? contextPercentValue.toFixed(1) : \"?\";\n\n\t\t// Replace home directory with ~\n\t\tlet pwd = hasSegment(\"cwd\")\n\t\t\t? formatCwdForFooter(this.session.sessionManager.getCwd(), process.env.HOME || process.env.USERPROFILE)\n\t\t\t: \"\";\n\n\t\t// Add git branch if available (with dirty marker from `git status --porcelain`)\n\t\tif (hasSegment(\"git\")) {\n\t\t\tconst gitStatus = this.footerData.getGitStatus();\n\t\t\tconst gitSegment = formatGitSegment(gitStatus.branch, gitStatus.dirty);\n\t\t\tif (gitSegment) {\n\t\t\t\tpwd = pwd ? `${pwd} (${gitSegment})` : `(${gitSegment})`;\n\t\t\t}\n\t\t}\n\n\t\t// Add session name if set\n\t\tconst sessionName = this.session.sessionManager.getSessionName();\n\t\tif (sessionName) {\n\t\t\tpwd = pwd ? `${pwd} • ${sessionName}` : sessionName;\n\t\t}\n\n\t\t// Build stats line\n\t\tconst statsParts = [];\n\t\tif (hasSegment(\"tokens\")) {\n\t\t\tif (usageTotals.input) statsParts.push(`↑${formatTokens(usageTotals.input)}`);\n\t\t\tif (usageTotals.output) statsParts.push(`↓${formatTokens(usageTotals.output)}`);\n\t\t}\n\t\tif (hasSegment(\"cache\")) {\n\t\t\tif (usageTotals.cacheRead) statsParts.push(`R${formatTokens(usageTotals.cacheRead)}`);\n\t\t\tif (usageTotals.cacheWrite) statsParts.push(`W${formatTokens(usageTotals.cacheWrite)}`);\n\t\t\tif ((usageTotals.cacheRead > 0 || usageTotals.cacheWrite > 0) && latestCacheHitRate !== undefined) {\n\t\t\t\tstatsParts.push(`CH${latestCacheHitRate.toFixed(1)}%`);\n\t\t\t}\n\t\t}\n\n\t\t// Kimi Coding is subscription-backed despite using API-key authentication.\n\t\t// The runtime lookup is optional: the footer renders on every frame and must\n\t\t// never take the TUI down because a session was built without one.\n\t\tconst usingSubscription = state.model\n\t\t\t? state.model.provider === \"kimi-coding\" ||\n\t\t\t\t(this.session.modelRuntime?.isUsingSubscription(state.model.provider) ?? false)\n\t\t\t: false;\n\t\tif (hasSegment(\"cost\")) {\n\t\t\t// Provider-reported costs, plus tokens x catalogue price for unpriced messages so\n\t\t\t// subscription/flat-rate providers still show an estimate.\n\t\t\tif (sessionCost > 0 || usingSubscription) {\n\t\t\t\tconst costStr = `${formatCostUsd(sessionCost)}${usingSubscription ? \" (sub)\" : \"\"}`;\n\t\t\t\tstatsParts.push(costStr);\n\t\t\t}\n\t\t}\n\n\t\t// Colorize context percentage based on usage.\n\t\t// When the active model has no known context window (e.g. a provider that does\n\t\t// not report one), show \"?\" instead of a misleading \"0\" for both the percentage\n\t\t// and the window size. This keeps the footer correct across model switches and\n\t\t// during /plan orchestration, where each phase may run a different model.\n\t\tlet contextPercentStr: string;\n\t\tconst autoIndicator = this.autoCompactEnabled ? \" (auto)\" : \"\";\n\t\tconst windowKnown = contextWindow > 0;\n\t\tconst windowDisplay = windowKnown ? formatTokens(contextWindow) : \"?\";\n\t\tconst percentDisplay = windowKnown && contextPercent !== \"?\" ? `${contextPercent}%` : \"?\";\n\t\tconst contextPercentDisplay = `${percentDisplay}/${windowDisplay}${autoIndicator}`;\n\t\tif (contextPercentValue > 90) {\n\t\t\tcontextPercentStr = theme.fg(\"error\", contextPercentDisplay);\n\t\t} else if (contextPercentValue > 70) {\n\t\t\tcontextPercentStr = theme.fg(\"warning\", contextPercentDisplay);\n\t\t} else {\n\t\t\tcontextPercentStr = contextPercentDisplay;\n\t\t}\n\t\tif (hasSegment(\"context\")) {\n\t\t\tstatsParts.push(contextPercentStr);\n\t\t}\n\t\tif (areExperimentalFeaturesEnabled()) {\n\t\t\tstatsParts.push(`${theme.fg(\"dim\", \"•\")} ${theme.bold(theme.fg(\"warning\", \"xp\"))}`);\n\t\t}\n\n\t\tlet statsLeft = statsParts.join(\" \");\n\n\t\t// Add model name on the right side, plus thinking level if model supports it\n\t\tconst modelName = state.model?.id || \"no-model\";\n\n\t\tlet statsLeftWidth = visibleWidth(statsLeft);\n\n\t\t// If statsLeft is too wide, truncate it\n\t\tif (statsLeftWidth > width) {\n\t\t\tstatsLeft = truncateToWidth(statsLeft, width, \"...\");\n\t\t\tstatsLeftWidth = visibleWidth(statsLeft);\n\t\t}\n\n\t\t// Calculate available space for padding (minimum 2 spaces between stats and model)\n\t\tconst minPadding = 2;\n\n\t\t// Add thinking level indicator if model supports reasoning\n\t\tlet rightSideWithoutProvider = modelName;\n\t\tif (state.model?.reasoning) {\n\t\t\tconst thinkingLevel = state.thinkingLevel || \"off\";\n\t\t\trightSideWithoutProvider =\n\t\t\t\tthinkingLevel === \"off\" ? `${modelName} • thinking off` : `${modelName} • ${thinkingLevel}`;\n\t\t}\n\n\t\t// Prepend the provider in parentheses if there are multiple providers and there's enough room\n\t\tlet rightSide = rightSideWithoutProvider;\n\t\tif (this.footerData.getAvailableProviderCount() > 1 && state.model) {\n\t\t\trightSide = `(${state.model!.provider}) ${rightSideWithoutProvider}`;\n\t\t\tif (statsLeftWidth + minPadding + visibleWidth(rightSide) > width) {\n\t\t\t\t// Too wide, fall back\n\t\t\t\trightSide = rightSideWithoutProvider;\n\t\t\t}\n\t\t}\n\t\tif (!hasSegment(\"model\")) {\n\t\t\trightSide = \"\";\n\t\t}\n\n\t\tconst rightSideWidth = visibleWidth(rightSide);\n\t\tconst totalNeeded = statsLeftWidth + minPadding + rightSideWidth;\n\n\t\tlet statsLine: string;\n\t\tif (totalNeeded <= width) {\n\t\t\t// Both fit - add padding to right-align model\n\t\t\tconst padding = \" \".repeat(width - statsLeftWidth - rightSideWidth);\n\t\t\tstatsLine = statsLeft + padding + rightSide;\n\t\t} else {\n\t\t\t// Need to truncate right side\n\t\t\tconst availableForRight = width - statsLeftWidth - minPadding;\n\t\t\tif (availableForRight > 0) {\n\t\t\t\tconst truncatedRight = truncateToWidth(rightSide, availableForRight, \"\");\n\t\t\t\tconst truncatedRightWidth = visibleWidth(truncatedRight);\n\t\t\t\tconst padding = \" \".repeat(Math.max(0, width - statsLeftWidth - truncatedRightWidth));\n\t\t\t\tstatsLine = statsLeft + padding + truncatedRight;\n\t\t\t} else {\n\t\t\t\t// Not enough space for right side at all\n\t\t\t\tstatsLine = statsLeft;\n\t\t\t}\n\t\t}\n\n\t\t// Apply dim to each part separately. statsLeft may contain color codes (for context %)\n\t\t// that end with a reset, which would clear an outer dim wrapper. So we dim the parts\n\t\t// before and after the colored section independently.\n\t\tconst dimStatsLeft = theme.fg(\"dim\", statsLeft);\n\t\tconst remainder = statsLine.slice(statsLeft.length); // padding + rightSide\n\t\tconst dimRemainder = theme.fg(\"dim\", remainder);\n\n\t\tconst pwdLine = truncateToWidth(theme.fg(\"dim\", pwd), width, theme.fg(\"dim\", \"...\"));\n\t\tconst lines = pwd ? [pwdLine, dimStatsLeft + dimRemainder] : [dimStatsLeft + dimRemainder];\n\n\t\t// Add extension statuses on a single line, sorted by key alphabetically\n\t\tconst extensionStatuses = this.footerData.getExtensionStatuses();\n\t\tif (extensionStatuses.size > 0) {\n\t\t\tconst sortedStatuses = Array.from(extensionStatuses.entries())\n\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t.map(([, text]) => sanitizeStatusText(text));\n\t\t\tconst statusLine = sortedStatuses.join(\" \");\n\t\t\t// Truncate to terminal width with dim ellipsis for consistency with footer style\n\t\t\tlines.push(truncateToWidth(statusLine, width, theme.fg(\"dim\", \"...\")));\n\t\t}\n\n\t\t// Bottom-right Act/Plan mode indicator (dedicated line, always last).\n\t\tlines.push(this.renderModeIndicator(width));\n\n\t\treturn lines;\n\t}\n}\n"]}