@ftrdotdev/pi-tui 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -0
  3. package/package.json +80 -0
  4. package/src/autocomplete-contract.test.ts +126 -0
  5. package/src/autocomplete-contract.ts +91 -0
  6. package/src/commands/git-execution.test.ts +69 -0
  7. package/src/commands/git-execution.ts +198 -0
  8. package/src/commands/git-status.test.ts +379 -0
  9. package/src/commands/git-status.ts +320 -0
  10. package/src/components/bordered-box.test.ts +136 -0
  11. package/src/components/bordered-box.ts +106 -0
  12. package/src/components/define-component.ts +33 -0
  13. package/src/components/index.ts +35 -0
  14. package/src/config.test.ts +469 -0
  15. package/src/config.ts +307 -0
  16. package/src/frame/box-frame.test.ts +44 -0
  17. package/src/frame/box-frame.ts +160 -0
  18. package/src/icons.ts +203 -0
  19. package/src/index.ts +359 -0
  20. package/src/runtime.ts +256 -0
  21. package/src/session-lifecycle.ts +41 -0
  22. package/src/state.test.ts +7 -0
  23. package/src/state.ts +90 -0
  24. package/src/telemetry.ts +301 -0
  25. package/src/ui/editor-tint.test.ts +70 -0
  26. package/src/ui/editor-tint.ts +78 -0
  27. package/src/ui/editor.ts +403 -0
  28. package/src/ui/footer.test.ts +350 -0
  29. package/src/ui/footer.ts +225 -0
  30. package/src/ui/header.test.ts +260 -0
  31. package/src/ui/header.ts +165 -0
  32. package/src/ui/preview.test.ts +639 -0
  33. package/src/ui/preview.ts +374 -0
  34. package/src/ui/render-helpers.ts +275 -0
  35. package/src/ui/settings-command.test.ts +218 -0
  36. package/src/ui/settings-command.ts +390 -0
  37. package/src/utils.ts +448 -0
  38. package/src/vim/editor-close-autocomplete.ts +26 -0
  39. package/src/vim/editor-host.test.ts +340 -0
  40. package/src/vim/editor-state.test.ts +385 -0
  41. package/src/vim/editor-state.ts +314 -0
  42. package/src/vim/mode-indicator.test.ts +27 -0
  43. package/src/vim/mode-indicator.ts +44 -0
  44. package/src/vim/selection-render.test.ts +77 -0
  45. package/src/vim/selection-render.ts +85 -0
  46. package/src/vim/text-model.test.ts +85 -0
  47. package/src/vim/text-model.ts +75 -0
  48. package/src/vim/vim-router.test.ts +50 -0
  49. package/src/vim/vim-router.ts +55 -0
  50. package/src/vim/word-motion.ts +96 -0
@@ -0,0 +1,374 @@
1
+ /**
2
+ * preview — display a file in the chat for the human only.
3
+ *
4
+ * Two entry points:
5
+ * - `preview` tool: the model calls it. The TUI renders the full file (with
6
+ * syntax highlighting) while the model only receives a one-line
7
+ * confirmation. Use when the user needs to review a file that the model
8
+ * does not need in its context.
9
+ * - `/preview <path>` command: the human invokes it. The content is stored as
10
+ * a custom entry that never participates in LLM context.
11
+ *
12
+ * The module has no direct Node dependencies: file reads go through the
13
+ * platform `FileSystem` service, path operations through the `Path` service,
14
+ * and byte slicing uses the standard `Uint8Array`/`TextEncoder` Web APIs. The
15
+ * only platform primitive without an Effect service — the home directory used
16
+ * for `~` expansion — is injected into {@link PreviewService.make} and bound
17
+ * at the entry point (src/index.ts). The registrations run the pipeline
18
+ * through the effect context captured there.
19
+ */
20
+
21
+ import { Context, Effect, Layer, Schema, Path, FileSystem, PlatformError } from "effect";
22
+ import type { Component } from "@earendil-works/pi-tui";
23
+ import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
24
+ import {
25
+ getLanguageFromPath,
26
+ getMarkdownTheme,
27
+ highlightCode,
28
+ } from "@earendil-works/pi-coding-agent";
29
+ import { Container, Markdown, Text } from "@earendil-works/pi-tui";
30
+ import { makeBorderedBox } from "../components/bordered-box.ts";
31
+ import { Type } from "typebox";
32
+
33
+ export const MAX_BYTES = 50 * 1024; // 50KB, matching the built-in read limits
34
+ export const MAX_LINES = 2000;
35
+ export const COLLAPSED_LINES = 40;
36
+
37
+ /** Slice a byte array without splitting a multi-byte UTF-8 character. */
38
+ export function sliceUtf8(buf: Uint8Array, maxBytes: number): Uint8Array {
39
+ if (buf.length <= maxBytes) return buf;
40
+ let end = maxBytes;
41
+ while (end > 0) {
42
+ const b = buf[end];
43
+ if (b === undefined || (b & 0xc0) !== 0x80) break;
44
+ end--;
45
+ }
46
+ return buf.subarray(0, end);
47
+ }
48
+
49
+ export function capContent(
50
+ raw: string,
51
+ maxBytes: number,
52
+ maxLines: number,
53
+ ): { content: string; truncated: boolean } {
54
+ const buf = new TextEncoder().encode(raw);
55
+ const truncatedBytes = buf.length > maxBytes;
56
+ let content = truncatedBytes ? new TextDecoder().decode(sliceUtf8(buf, maxBytes)) : raw;
57
+ const lines = content.split("\n");
58
+ const truncatedLines = lines.length > maxLines;
59
+ if (truncatedLines) content = lines.slice(0, maxLines).join("\n");
60
+ return { content, truncated: truncatedBytes || truncatedLines };
61
+ }
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Preview service
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /** The display record the preview tool, command, and entry renderer consume. */
68
+ export interface PreviewData {
69
+ path: string;
70
+ content: string;
71
+ lang?: string;
72
+ truncated: boolean;
73
+ }
74
+
75
+ /** The failure-details variant: the record plus the user-facing error message. */
76
+ export type PreviewDataError = PreviewData & { readonly error: string };
77
+
78
+ /** A file read failed; carries the path and the underlying platform message. */
79
+ export class PreviewReadError extends Schema.TaggedError<PreviewReadError>()("PreviewReadError", {
80
+ path: Schema.String,
81
+ message: Schema.String,
82
+ }) {}
83
+
84
+ /**
85
+ * Owns the whole preview pipeline: reference resolution (through the `Path`
86
+ * service and the injected home directory), the platform `FileSystem` read,
87
+ * byte/line capping, and the language hint. The only component in the module
88
+ * that can fail; every platform failure maps to a tagged error.
89
+ */
90
+ export class PreviewService extends Context.Service<
91
+ PreviewService,
92
+ {
93
+ readonly resolveFileRef: (
94
+ raw: string,
95
+ cwd: string,
96
+ ) => Effect.Effect<string, PlatformError.BadArgument>;
97
+ readonly read: (absPath: string) => Effect.Effect<PreviewData, PreviewReadError>;
98
+ }
99
+ >()("tui/preview/PreviewService") {
100
+ /**
101
+ * @param homedir - provider for the user's home directory (`~` expansion).
102
+ * Effect has no home-directory service, so the platform implementation is
103
+ * bound at the entry point.
104
+ */
105
+ static make(
106
+ homedir: () => string,
107
+ maxBytes: number = MAX_BYTES,
108
+ maxLines: number = MAX_LINES,
109
+ _collapsedLines: number = COLLAPSED_LINES,
110
+ ): Layer.Layer<PreviewService, never, FileSystem.FileSystem | Path.Path> {
111
+ return Layer.effect(
112
+ PreviewService,
113
+ Effect.gen(function* () {
114
+ const fs = yield* FileSystem.FileSystem;
115
+ const path = yield* Path.Path;
116
+
117
+ /**
118
+ * Resolve a file reference the same way pi's built-in tools do:
119
+ * - strips a leading `@` (the @-autocomplete inserts `@path` or `@"path with spaces"`)
120
+ * - expands `~` to the home directory
121
+ * - handles `file://` URLs
122
+ * - resolves relative paths against cwd
123
+ */
124
+ const resolveFileRef = Effect.fn("PreviewService.resolveFileRef")(function* (
125
+ raw: string,
126
+ cwd: string,
127
+ ): Effect.fn.Return<string, PlatformError.BadArgument> {
128
+ let ref = raw.trim();
129
+ if (ref.startsWith("@")) ref = ref.slice(1);
130
+ if (
131
+ ref.length >= 2 &&
132
+ ((ref.startsWith('"') && ref.endsWith('"')) ||
133
+ (ref.startsWith("'") && ref.endsWith("'")))
134
+ ) {
135
+ ref = ref.slice(1, -1);
136
+ }
137
+ if (ref === "~") return homedir();
138
+ if (ref.startsWith("~/")) return path.join(homedir(), ref.slice(2));
139
+ if (/^file:\/\//.test(ref)) {
140
+ const url = yield* Effect.try({
141
+ try: () => new URL(ref),
142
+ catch: () =>
143
+ new PlatformError.BadArgument({
144
+ module: "Path",
145
+ method: "fromFileUrl",
146
+ description: `invalid file URL: ${ref}`,
147
+ }),
148
+ });
149
+ return yield* path.fromFileUrl(url);
150
+ }
151
+ return path.isAbsolute(ref) ? ref : path.resolve(cwd, ref);
152
+ });
153
+
154
+ const read = Effect.fn("PreviewService.read")(function* (
155
+ absPath: string,
156
+ ): Effect.fn.Return<PreviewData, PreviewReadError> {
157
+ const raw = yield* fs
158
+ .readFileString(absPath)
159
+ .pipe(
160
+ Effect.catch(
161
+ (err: PlatformError.PlatformError) =>
162
+ new PreviewReadError({ path: absPath, message: err.message }),
163
+ ),
164
+ );
165
+ const { content, truncated } = capContent(raw, maxBytes, maxLines);
166
+ return { path: absPath, content, lang: getLanguageFromPath(absPath), truncated };
167
+ });
168
+
169
+ return PreviewService.of({ resolveFileRef, read });
170
+ }),
171
+ );
172
+ }
173
+
174
+ static readonly layerTest = (
175
+ fileSystem: Partial<FileSystem.FileSystem>,
176
+ homedir: () => string,
177
+ maxBytes: number = MAX_BYTES,
178
+ maxLines: number = MAX_LINES,
179
+ collapsedLines: number = COLLAPSED_LINES,
180
+ ): Layer.Layer<PreviewService> =>
181
+ PreviewService.make(homedir, maxBytes, maxLines, collapsedLines).pipe(
182
+ Layer.provide(FileSystem.layerNoop(fileSystem)),
183
+ Layer.provide(Path.layer),
184
+ );
185
+ }
186
+
187
+ /**
188
+ * Shared body renderer.
189
+ *
190
+ * Markdown files use pi's Markdown component (mdHeading/mdCode/mdLink colors,
191
+ * highlighted fenced code blocks). Everything else uses highlightCode(), whose
192
+ * hljs scope -> theme mapping covers code languages but not markdown's scopes
193
+ * (section, code, bullet, quote...), which would render uncolored.
194
+ */
195
+ export function renderBodyComponent(
196
+ data: PreviewData,
197
+ expanded: boolean,
198
+ theme: Theme,
199
+ collapsedLines: number = COLLAPSED_LINES,
200
+ ): Component {
201
+ const isMarkdown = data.lang === "markdown";
202
+ if (isMarkdown) {
203
+ const content = expanded
204
+ ? data.content
205
+ : data.content.split("\n").slice(0, collapsedLines).join("\n");
206
+ const lines = data.content.split("\n");
207
+ const note =
208
+ expanded && data.truncated
209
+ ? "\n... (truncated preview)"
210
+ : !expanded && lines.length > collapsedLines
211
+ ? `\n... (${lines.length - collapsedLines} more lines, expand to view all)`
212
+ : "";
213
+ return new Markdown(content + note, 0, 0, getMarkdownTheme());
214
+ }
215
+
216
+ const lines = data.lang ? highlightCode(data.content, data.lang) : data.content.split("\n");
217
+ const max = expanded ? lines.length : Math.min(collapsedLines, lines.length);
218
+ const out = lines.slice(0, max);
219
+ if (max < lines.length || data.truncated) {
220
+ out.push(theme.fg("muted", `... (${lines.length - max} lines shown, expand to view all)`));
221
+ }
222
+ return new Text(`\n${out.join("\n")}`, 0, 0);
223
+ }
224
+
225
+ /** Extract the user-facing message exactly like the legacy catch blocks. */
226
+ function errorMessage(err: unknown): string {
227
+ return err instanceof Error ? err.message : String(err);
228
+ }
229
+
230
+ /**
231
+ * Registers the `preview` tool, the `/preview` command, and the `preview`
232
+ * entry renderer. All three run the pipeline through the captured effect
233
+ * context at the async call sites.
234
+ */
235
+ export function registerPreview(
236
+ pi: ExtensionAPI,
237
+ effectContext: Context.Context<PreviewService>,
238
+ ): void {
239
+ // =========================================================================
240
+ // `preview` tool — agent-invokable, display-only
241
+ // =========================================================================
242
+ pi.registerTool({
243
+ name: "preview",
244
+ label: "Preview file for user",
245
+ description:
246
+ "Display a file's contents in the chat for the user to read. " +
247
+ "The full contents are rendered in the TUI only; the model receives just " +
248
+ "a confirmation and the path. Use only when the user needs to see the file " +
249
+ "and the model does not need its contents.",
250
+ promptGuidelines: [
251
+ "Use preview instead of read when ONLY the user needs to see the file contents. " +
252
+ "Example: asking the user to approve a file another agent wrote. " +
253
+ "Example: showing a file whose contents are not in the recent conversation history.",
254
+ "Do not use preview when the model needs the contents, such as to edit, summarize, " +
255
+ "or reason about the file. Use read instead.",
256
+ "The model never receives the file contents. Treat preview as display-only.",
257
+ ],
258
+ // The custom renderers draw their own framed box; skip pi's standard
259
+ // tool shell so the element is not double-framed.
260
+ renderShell: "self",
261
+ parameters: Type.Object({
262
+ path: Type.String({
263
+ description:
264
+ "File path to display. Accepts @-references (@src/main.ts), ~ expansion, relative or absolute paths.",
265
+ }),
266
+ }),
267
+
268
+ // What the MODEL sees — a stub, not the file.
269
+ async execute(_toolCallId, { path }, _signal, _onUpdate, ctx) {
270
+ return Effect.runPromiseWith(effectContext)(
271
+ Effect.gen(function* () {
272
+ const svc = yield* PreviewService;
273
+ const absPath = yield* svc.resolveFileRef(path, ctx.cwd);
274
+ return yield* svc.read(absPath);
275
+ }).pipe(
276
+ Effect.match({
277
+ onSuccess: (data) => ({
278
+ content: [{ type: "text", text: `[Preview shown to user: ${path}]` }],
279
+ details: data,
280
+ }),
281
+ onFailure: (err: unknown) => {
282
+ const message = errorMessage(err);
283
+ return {
284
+ content: [{ type: "text", text: `preview failed: ${message}` }],
285
+ details: {
286
+ path,
287
+ content: "",
288
+ lang: undefined,
289
+ truncated: false,
290
+ error: message,
291
+ } satisfies PreviewDataError,
292
+ };
293
+ },
294
+ }),
295
+ ),
296
+ );
297
+ },
298
+
299
+ renderCall(args, theme) {
300
+ return makeBorderedBox(new Text(args.path, 0, 0), theme, {
301
+ label: theme.fg("toolTitle", theme.bold("preview")),
302
+ bg: (s) => theme.bg("customMessageBg", s),
303
+ });
304
+ },
305
+
306
+ // What the TUI renders — the full highlighted file.
307
+ renderResult(result, options, theme, context) {
308
+ const data = result.details as (PreviewData & { error?: string }) | undefined;
309
+ if (!data) return context.lastComponent ?? new Text("", 0, 0);
310
+ if (data.error) {
311
+ return makeBorderedBox(new Text(`preview failed: ${data.error}`, 0, 0), theme, {
312
+ label: theme.fg("warning", theme.bold("preview")),
313
+ color: "warning",
314
+ bg: (s) => theme.bg("customMessageBg", s),
315
+ });
316
+ }
317
+ return makeBorderedBox(renderBodyComponent(data, options.expanded, theme), theme, {
318
+ label: theme.fg("accent", theme.bold("preview")),
319
+ bg: (s) => theme.bg("customMessageBg", s),
320
+ });
321
+ },
322
+ });
323
+
324
+ // =========================================================================
325
+ // `/preview <path>` command — human-invoked, strictly TUI-only
326
+ // =========================================================================
327
+ pi.registerEntryRenderer("preview", (entry, { expanded }, theme) => {
328
+ const data = entry.data as PreviewData | undefined;
329
+ const body = new Container();
330
+ if (!data) {
331
+ body.addChild(new Text(theme.fg("warning", "[preview] no data"), 0, 0));
332
+ return makeBorderedBox(body, theme, {
333
+ label: theme.fg("warning", theme.bold("preview")),
334
+ color: "warning",
335
+ bg: (s) => theme.bg("customMessageBg", s),
336
+ });
337
+ }
338
+ body.addChild(new Text(theme.fg("accent", data.path), 0, 0));
339
+ body.addChild(renderBodyComponent(data, expanded, theme));
340
+ return makeBorderedBox(body, theme, {
341
+ label: theme.fg("accent", theme.bold("preview")),
342
+ bg: (s) => theme.bg("customMessageBg", s),
343
+ });
344
+ });
345
+
346
+ pi.registerCommand("preview", {
347
+ description:
348
+ "Display a file in the chat for the user to read (TUI only, not sent to the model).",
349
+ handler: async (args, ctx) => {
350
+ const path = args.trim();
351
+ if (!path) {
352
+ ctx.ui.notify("usage: /preview <path>", "warning");
353
+ return;
354
+ }
355
+ const outcome = await Effect.runPromiseWith(effectContext)(
356
+ Effect.gen(function* () {
357
+ const svc = yield* PreviewService;
358
+ const absPath = yield* svc.resolveFileRef(path, ctx.cwd);
359
+ return yield* svc.read(absPath);
360
+ }).pipe(
361
+ Effect.match({
362
+ onSuccess: (data) => ({ ok: true as const, data }),
363
+ onFailure: (err: unknown) => ({ ok: false as const, message: errorMessage(err) }),
364
+ }),
365
+ ),
366
+ );
367
+ if (outcome.ok) {
368
+ pi.appendEntry("preview", outcome.data);
369
+ } else {
370
+ ctx.ui.notify(`preview failed: ${outcome.message}`, "error");
371
+ }
372
+ },
373
+ });
374
+ }
@@ -0,0 +1,275 @@
1
+ // Shared pure themed-string leaves for the widget render pipelines.
2
+ //
3
+ // Relocation, not redesign: the header leaves moved here verbatim from
4
+ // header.ts (Slice 1) and the footer leaves from footer.ts (Slice 3). Byte
5
+ // parity is gated by the frozen pixel tables in header.test.ts / footer.test.ts,
6
+ // so a moved-but-changed helper cannot ship.
7
+
8
+ import type { ExtensionContext, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
9
+ import { visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
10
+ import type { TuiConfig } from "../config.ts";
11
+ import type { IconGlyphs } from "../icons.ts";
12
+ import { resolveIconMode, runtimeSymbol } from "../icons.ts";
13
+ import type { GitStatus } from "../commands/git-status.ts";
14
+ import type { RuntimeInfo } from "../runtime.ts";
15
+ import {
16
+ cacheHitColor,
17
+ fmtTokens,
18
+ formatCost,
19
+ formatDuration,
20
+ padRight,
21
+ sanitizeStatus,
22
+ stressColor,
23
+ truncatePath,
24
+ } from "../utils.ts";
25
+ import type { FooterState, UsageTotals } from "../state.ts";
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Header leaves (relocated verbatim from header.ts, Slice 1)
29
+ // ---------------------------------------------------------------------------
30
+
31
+ const LOGO_CELL = "███";
32
+
33
+ /** Static house logo: painted cells as "row,col" (1-based), blank elsewhere. */
34
+ const LOGO_CELLS = new Set(["3,2", "3,3", "3,4", "4,2", "4,4", "5,2", "5,3", "5,5", "6,2", "6,5"]);
35
+
36
+ /**
37
+ * The house logo grid as painted lines: painted cells rendered with
38
+ * `paint(LOGO_CELL)` and blank cells padded to the same width, cropped to
39
+ * the logo's bounding box.
40
+ */
41
+ export function renderLogo(paint: (text: string) => string): string[] {
42
+ const grid: boolean[][] = [];
43
+ let minX = 7;
44
+ let maxX = 0;
45
+ for (let y = 1; y <= 7; y++) {
46
+ const row: boolean[] = [];
47
+ for (let x = 1; x <= 8; x++) {
48
+ const on = LOGO_CELLS.has(`${y},${x}`);
49
+ if (on) {
50
+ minX = Math.min(minX, x);
51
+ maxX = Math.max(maxX, x);
52
+ }
53
+ row.push(on);
54
+ }
55
+ grid.push(row);
56
+ }
57
+ return grid.map((row) =>
58
+ row
59
+ .slice(minX - 1, maxX)
60
+ .map((on) => (on ? paint(LOGO_CELL) : " ".repeat(LOGO_CELL.length)))
61
+ .join(""),
62
+ );
63
+ }
64
+
65
+ /**
66
+ * One header body row: left column padded to `leftWidth`, a painted
67
+ * column separator, and the right cell padded to `rightWidth` (with `…`
68
+ * when the right cell overflows).
69
+ */
70
+ export function twoColumn(
71
+ left: string,
72
+ right: string,
73
+ leftWidth: number,
74
+ rightWidth: number,
75
+ paint: (text: string) => string,
76
+ ): string {
77
+ return `${padRight(left, leftWidth)} ${paint("│")} ${padRight(right, rightWidth, "…")}`;
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Footer leaves (relocated verbatim from footer.ts, Slice 3)
82
+ // ---------------------------------------------------------------------------
83
+
84
+ /**
85
+ * A context-usage bar segment: `[####----]` (ascii) or `[████░░░░]`
86
+ * (nerd) with the filled fraction colored by `stressColor`, framed by
87
+ * dim brackets.
88
+ */
89
+ export function renderBar(theme: Theme, pct: number, barWidth: number, ascii: boolean): string {
90
+ const filled = Math.max(0, Math.min(barWidth, Math.round((pct / 100) * barWidth)));
91
+ const empty = barWidth - filled;
92
+ const color = stressColor(pct);
93
+ const filledCell = ascii ? "#" : "█";
94
+ const emptyCell = ascii ? "-" : "░";
95
+ return (
96
+ theme.fg("dim", "[") +
97
+ theme.fg(color, filledCell.repeat(filled)) +
98
+ theme.fg("dim", emptyCell.repeat(empty)) +
99
+ theme.fg("dim", "]")
100
+ );
101
+ }
102
+
103
+ /**
104
+ * The git footer segment: branch (or detached HEAD short hash + tag) and,
105
+ * when enabled, the bracketed status block (`[!3 A2 ?1 S1 ^v2/1]`). Each
106
+ * count is gated by its `footerSegments` flag; an empty result returns
107
+ * `""` so the caller drops the segment.
108
+ */
109
+ export function renderGitSegment(
110
+ theme: Theme,
111
+ git: GitStatus,
112
+ glyphs: IconGlyphs,
113
+ segments: TuiConfig["footerSegments"],
114
+ maxBranchLen = 20,
115
+ ): string {
116
+ const parts: string[] = [];
117
+ if (segments.gitBranch) {
118
+ if (git.branch) {
119
+ parts.push(theme.fg("mdLink", glyphs.git));
120
+ parts.push(theme.fg("mdLink", truncatePath(git.branch, maxBranchLen)));
121
+ } else if (git.commit?.detached) {
122
+ parts.push(theme.fg("warning", glyphs.git));
123
+ parts.push(theme.fg("warning", "HEAD"));
124
+ if (git.commit.oid) {
125
+ const shortHash = git.commit.oid.slice(0, 7);
126
+ const tag = git.commit.tag ? ` ${git.commit.tag}` : "";
127
+ parts.push(theme.fg("dim", `${shortHash}${tag}`));
128
+ }
129
+ }
130
+ }
131
+
132
+ if (segments.gitStatus) {
133
+ const statusIcons: string[] = [];
134
+ const addStatus = (count: number, glyph: string, color: ThemeColor) => {
135
+ if (count > 0) statusIcons.push(theme.fg(color, `${glyph}${count}`));
136
+ };
137
+ addStatus(git.conflicted, glyphs.conflicted, "error");
138
+ addStatus(git.deleted, glyphs.deleted, "error");
139
+ addStatus(git.modified, glyphs.modified, "warning");
140
+ addStatus(git.renamed, glyphs.renamed, "warning");
141
+ addStatus(git.staged, glyphs.staged, "success");
142
+ addStatus(git.untracked, glyphs.untracked, "muted");
143
+ addStatus(git.stashed, glyphs.stashed, "muted");
144
+
145
+ if (git.ahead > 0 && git.behind > 0) {
146
+ statusIcons.push(theme.fg("warning", `${glyphs.diverged}${git.ahead}/${git.behind}`));
147
+ } else if (git.ahead > 0) {
148
+ statusIcons.push(theme.fg("success", `${glyphs.ahead}${git.ahead}`));
149
+ statusIcons.push(theme.fg("warning", `${glyphs.behind}${git.behind}`));
150
+ }
151
+
152
+ const statusBlock = statusIcons.join(" ");
153
+ if (statusBlock) {
154
+ parts.push(`${theme.fg("dim", "[")}${statusBlock}${theme.fg("dim", "]")}`);
155
+ }
156
+ }
157
+
158
+ return parts.join(" ");
159
+ }
160
+
161
+ /**
162
+ * The runtime footer segment: a runtime symbol (ascii or nerd per the
163
+ * icon mode) plus its version when known. Returns `""` for no runtime.
164
+ */
165
+ export function renderRuntimeSegment(
166
+ theme: Theme,
167
+ runtime: RuntimeInfo | null,
168
+ iconMode: TuiConfig["icons"]["mode"],
169
+ ): string {
170
+ if (!runtime) return "";
171
+ const symbol = theme.fg("success", runtimeSymbol(runtime.name, iconMode));
172
+ const version = runtime.version ? theme.fg("muted", runtime.version) : "";
173
+ const label = [symbol, version].filter(Boolean).join(" ");
174
+ return label;
175
+ }
176
+
177
+ /**
178
+ * The working/done timer footer segment, or `""` when neither timer
179
+ * field is set. The working read calls `Date.now()` only while a timer
180
+ * is active.
181
+ */
182
+ export function renderTimerSegment(theme: Theme, state: FooterState, glyphs: IconGlyphs): string {
183
+ if (state.workingSince !== undefined) {
184
+ return `${theme.fg("accent", glyphs.working)} ${theme.fg("dim", "working")} ${theme.fg("accent", formatDuration(Date.now() - state.workingSince))}`;
185
+ }
186
+ if (state.lastDoneIn !== undefined) {
187
+ return `${theme.fg("success", glyphs.done)} ${theme.fg("success", "done")} ${theme.fg("text", formatDuration(state.lastDoneIn))}`;
188
+ }
189
+ return "";
190
+ }
191
+
192
+ /**
193
+ * The context-usage footer segment: icon, an ascii/nerd bar sized to
194
+ * the remaining width, the percentage, and `tokens/window`. Returns
195
+ * `""` when the window is unknown (empty session) so the caller drops it.
196
+ */
197
+ export function renderContextBar(
198
+ theme: Theme,
199
+ ctx: ExtensionContext,
200
+ width: number,
201
+ glyphs: IconGlyphs,
202
+ iconMode: TuiConfig["icons"]["mode"],
203
+ ): string {
204
+ const contextUsage = ctx.getContextUsage();
205
+ const contextWindow = contextUsage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
206
+ const contextTokens = contextUsage?.tokens ?? 0;
207
+ const contextPct = contextUsage?.percent ?? 0;
208
+
209
+ // populated instead of collapsing everything left in an empty session.
210
+ if (contextWindow <= 0) return "";
211
+
212
+ const pctText = theme.fg(stressColor(contextPct), `${contextPct.toFixed(1)}%`);
213
+ const ctxText = `${theme.fg("text", fmtTokens(contextTokens))}${theme.fg("dim", "/")}${theme.fg("text", fmtTokens(contextWindow))}`;
214
+ const contextIcon = theme.fg(stressColor(contextPct), glyphs.context);
215
+ const reserved =
216
+ visibleWidth(contextIcon) + visibleWidth(pctText) + visibleWidth(ctxText) + 5 + 2;
217
+ const barWidth = Math.max(4, Math.min(12, width - reserved));
218
+ return `${contextIcon} ${renderBar(theme, contextPct, barWidth, resolveIconMode(iconMode) === "ascii")} ${pctText} ${theme.fg("dim", "·")} ${ctxText}`;
219
+ }
220
+
221
+ /**
222
+ * Token/cache/cost stats from the usage totals, each gated by its
223
+ * `footerSegments` flag and joined with dim pipes. The cache-hit % is
224
+ * shown only when the provider reports cache tokens.
225
+ */
226
+ export function renderStatsBlock(
227
+ theme: Theme,
228
+ totals: UsageTotals,
229
+ glyphs: IconGlyphs,
230
+ segments: TuiConfig["footerSegments"],
231
+ ): string {
232
+ const stats: string[] = [];
233
+ if (segments.tokens) {
234
+ stats.push(theme.fg("accent", `${glyphs.input} ${fmtTokens(totals.input)}`));
235
+ stats.push(theme.fg("success", `${glyphs.output} ${fmtTokens(totals.output)}`));
236
+ // tokens — avoids a misleading "0%" on providers without prompt caching.
237
+ const hasCacheTokens = totals.cacheRead > 0 || totals.cacheWrite > 0;
238
+ if (hasCacheTokens && totals.latestCacheHitRate !== undefined) {
239
+ stats.push(
240
+ theme.fg(
241
+ cacheHitColor(totals.latestCacheHitRate),
242
+ `${glyphs.cacheHit} ${totals.latestCacheHitRate.toFixed(1)}%`,
243
+ ),
244
+ );
245
+ }
246
+ }
247
+ if (segments.cost) {
248
+ stats.push(theme.fg("warning", formatCost(glyphs.cost, totals.cost)));
249
+ }
250
+
251
+ return stats.join(` ${theme.fg("dim", "|")} `);
252
+ }
253
+
254
+ /**
255
+ * Extension status lines (sorted by key, sanitized, wrapped to `width`),
256
+ * prefixed with the extensions glyph. Returns `[]` when there are no
257
+ * non-empty statuses.
258
+ */
259
+ export function renderExtensionStatusLines(
260
+ theme: Theme,
261
+ extensionStatuses: ReadonlyMap<string, string>,
262
+ glyphs: IconGlyphs,
263
+ width: number,
264
+ ): string[] {
265
+ const statuses = Array.from(extensionStatuses.entries())
266
+ .sort(([a], [b]) => a.localeCompare(b))
267
+ .map(([, text]) => sanitizeStatus(text))
268
+ .filter((text) => text.length > 0);
269
+ if (statuses.length === 0) return [];
270
+
271
+ const separator = ` ${theme.fg("dim", "|")} `;
272
+ const statusText = statuses.map((status) => theme.fg("muted", status)).join(separator);
273
+ const line = `${theme.fg("mdLink", glyphs.extensions)} ${statusText}`;
274
+ return wrapTextWithAnsi(line, width);
275
+ }