@ftrdotdev/pi-tui 0.5.2 → 0.7.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.
@@ -9,7 +9,15 @@ import {
9
9
  Text,
10
10
  } from "@earendil-works/pi-tui";
11
11
  import { makeBorderedBox } from "../components/bordered-box.ts";
12
- import type { IconMode, TuiConfig, SettingsLanguage } from "../config.ts";
12
+ import {
13
+ adjustSmartCompactionProbability,
14
+ adjustMaxCandidates,
15
+ SMART_COMPACTION_PROBABILITY_STEP,
16
+ MAX_CANDIDATES_STEP,
17
+ type IconMode,
18
+ type TuiConfig,
19
+ type SettingsLanguage,
20
+ } from "../config.ts";
13
21
  import { VimRouter } from "../vim/vim-router.ts";
14
22
 
15
23
  interface SettingItem {
@@ -18,15 +26,29 @@ interface SettingItem {
18
26
  currentValue: string;
19
27
  }
20
28
 
21
- type Tab = "features" | "icons" | "segments" | "telemetry";
29
+ type Tab = "features" | "compaction" | "icons" | "segments" | "telemetry";
22
30
 
23
- const TABS: Tab[] = ["features", "icons", "segments", "telemetry"];
31
+ const BASE_TABS: readonly Tab[] = ["features", "icons", "segments", "telemetry"];
32
+ const COMPACTION_TAB: Tab = "compaction";
33
+
34
+ /**
35
+ * The tab order. The Compaction tab exists only while the tracker extension is
36
+ * loaded, so a session without it never shows tracker-only settings.
37
+ */
38
+ const tabsFor = (hasTracker: boolean): readonly Tab[] =>
39
+ hasTracker ? ["features", COMPACTION_TAB, "icons", "segments", "telemetry"] : BASE_TABS;
24
40
 
25
41
  const COPY = {
26
42
  en: {
27
43
  title: "TUI Settings",
28
- tabs: { features: "General", icons: "Icons", segments: "Footer", telemetry: "Telemetry" },
29
- hint: "Tab/Shift+Tab/←/→/h/l: tabs · ↑/↓/j/k: move · Enter/Space: change · Esc/q: close",
44
+ tabs: {
45
+ features: "General",
46
+ compaction: "Compaction",
47
+ icons: "Icons",
48
+ segments: "Footer",
49
+ telemetry: "Telemetry",
50
+ },
51
+ hint: "Tab/Shift+Tab/←/→/h/l: tabs · ↑/↓/j/k: move · Enter/Space: change · +/−: step value · Esc/q: close",
30
52
  labels: {
31
53
  enabled: "Enabled",
32
54
  vim: "Vim mode",
@@ -45,6 +67,11 @@ const COPY = {
45
67
  tokenCounts: "Token counts",
46
68
  stallDetails: "Stall details",
47
69
  costRate: "Cost rate",
70
+ smartCompactionEnabled: "Smart compaction",
71
+ smartCompactionClassifier: "Compaction classifier",
72
+ smartCompactionNeedsContextProbability: "Needs-context probability",
73
+ smartCompactionMinAnswerConfidence: "Answer confidence floor",
74
+ smartCompactionMaxCandidates: "Max candidates",
48
75
  },
49
76
  values: {
50
77
  on: "On",
@@ -93,6 +120,97 @@ function toggleTelemetry(config: TuiConfig, key: keyof TuiConfig["telemetry"]):
93
120
  };
94
121
  }
95
122
 
123
+ /** A classifier the picker can offer. Structural, so a registry model fits. */
124
+ export interface ClassifierDescriptor {
125
+ readonly provider: string;
126
+ readonly id: string;
127
+ readonly name?: string | undefined;
128
+ }
129
+
130
+ /** The classifier fields this dialog needs from the model registry. Structural,
131
+ * so `ctx.modelRegistry` satisfies it and tests pass a plain object. */
132
+ export interface ClassifierSource {
133
+ readonly getAvailableOfType: (type: "classifier") => Promise<readonly ClassifierDescriptor[]>;
134
+ readonly getModelsOfType: (type: "classifier") => readonly ClassifierDescriptor[];
135
+ }
136
+
137
+ /** The slice of `ExtensionAPI` the dialog needs to detect the tracker. */
138
+ export interface TrackerProbe {
139
+ readonly getAllTools: () => readonly { readonly name: string }[];
140
+ readonly getCommands: () => readonly { readonly name: string; readonly source: string }[];
141
+ }
142
+
143
+ /**
144
+ * Whether the tracker extension is loaded in this session. The tracker
145
+ * registers a tool and a command named `tracker`; either one proves presence,
146
+ * so the Compaction tab is hidden when it is not installed.
147
+ */
148
+ export const hasTrackerExtension = (probe: TrackerProbe): boolean =>
149
+ probe.getAllTools().some((tool) => tool.name === "tracker") ||
150
+ probe
151
+ .getCommands()
152
+ .some((command) => command.name === "tracker" && command.source === "extension");
153
+
154
+ export interface ClassifierChoice {
155
+ /** `"provider/modelId"`, or null for the preference order. */
156
+ readonly value: string | null;
157
+ readonly label: string;
158
+ }
159
+
160
+ const AUTOMATIC_CLASSIFIER_CHOICE: ClassifierChoice = {
161
+ value: null,
162
+ label: "Automatic (prefer Clef Flash, then Jev)",
163
+ };
164
+
165
+ /**
166
+ * Credential-available classifiers, else the whole catalog. `Automatic` is
167
+ * always first, so a chosen classifier is reversible.
168
+ */
169
+ export const loadClassifierChoices = async (
170
+ source: ClassifierSource,
171
+ ): Promise<ClassifierChoice[]> => {
172
+ let models: readonly ClassifierDescriptor[];
173
+ try {
174
+ const available = await source.getAvailableOfType("classifier");
175
+ models = available.length > 0 ? available : source.getModelsOfType("classifier");
176
+ } catch {
177
+ // Discovery failure must not empty the picker.
178
+ models = source.getModelsOfType("classifier");
179
+ }
180
+ const choices: ClassifierChoice[] = [AUTOMATIC_CLASSIFIER_CHOICE];
181
+ const seen = new Set<string>();
182
+ for (const model of models) {
183
+ const value = `${model.provider}/${model.id}`;
184
+ if (seen.has(value)) continue;
185
+ seen.add(value);
186
+ choices.push({ value, label: model.name ?? value });
187
+ }
188
+ return choices;
189
+ };
190
+
191
+ function classifierLabel(choices: readonly ClassifierChoice[], value: string | null): string {
192
+ if (value === null) return AUTOMATIC_CLASSIFIER_CHOICE.label;
193
+ return choices.find((choice) => choice.value === value)?.label ?? value;
194
+ }
195
+
196
+ function toggleSmartCompaction(config: TuiConfig): TuiConfig {
197
+ return {
198
+ ...config,
199
+ smartCompaction: { ...config.smartCompaction, enabled: !config.smartCompaction.enabled },
200
+ };
201
+ }
202
+
203
+ function cycleClassifier(config: TuiConfig, choices: readonly ClassifierChoice[]): TuiConfig {
204
+ const currentIndex = choices.findIndex(
205
+ (choice) => choice.value === config.smartCompaction.classifier,
206
+ );
207
+ const next = choices[(currentIndex + 1) % choices.length] ?? AUTOMATIC_CLASSIFIER_CHOICE;
208
+ return { ...config, smartCompaction: { ...config.smartCompaction, classifier: next.value } };
209
+ }
210
+
211
+ /** Two-decimal display for the probability rows. */
212
+ const formatProbability = (value: number): string => value.toFixed(2);
213
+
96
214
  function buildFeaturesItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
97
215
  return [
98
216
  {
@@ -113,6 +231,43 @@ function buildFeaturesItems(config: TuiConfig, copy: SettingsCopy): SettingItem[
113
231
  ];
114
232
  }
115
233
 
234
+ /** Integer display for the max-candidates row. */
235
+ const formatMaxCandidates = (value: number): string => String(value);
236
+
237
+ function buildCompactionItems(
238
+ config: TuiConfig,
239
+ copy: SettingsCopy,
240
+ choices: readonly ClassifierChoice[],
241
+ ): SettingItem[] {
242
+ return [
243
+ {
244
+ id: "smartCompactionEnabled",
245
+ label: copy.labels.smartCompactionEnabled,
246
+ currentValue: config.smartCompaction.enabled ? copy.values.on : copy.values.off,
247
+ },
248
+ {
249
+ id: "smartCompactionClassifier",
250
+ label: copy.labels.smartCompactionClassifier,
251
+ currentValue: classifierLabel(choices, config.smartCompaction.classifier),
252
+ },
253
+ {
254
+ id: "smartCompactionNeedsContextProbability",
255
+ label: copy.labels.smartCompactionNeedsContextProbability,
256
+ currentValue: formatProbability(config.smartCompaction.needsContextProbabilityThreshold),
257
+ },
258
+ {
259
+ id: "smartCompactionMinAnswerConfidence",
260
+ label: copy.labels.smartCompactionMinAnswerConfidence,
261
+ currentValue: formatProbability(config.smartCompaction.minAnswerConfidence),
262
+ },
263
+ {
264
+ id: "smartCompactionMaxCandidates",
265
+ label: copy.labels.smartCompactionMaxCandidates,
266
+ currentValue: formatMaxCandidates(config.smartCompaction.maxCandidates),
267
+ },
268
+ ];
269
+ }
270
+
116
271
  function buildIconsItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
117
272
  return [
118
273
  { id: "mode", label: copy.labels.iconMode, currentValue: copy.values.icons[config.icons.mode] },
@@ -153,11 +308,17 @@ function buildTelemetryItems(config: TuiConfig, copy: SettingsCopy): SettingItem
153
308
  ];
154
309
  }
155
310
 
156
- function buildItems(tab: Tab, config: TuiConfig): SettingItem[] {
311
+ function buildItems(
312
+ tab: Tab,
313
+ config: TuiConfig,
314
+ choices: readonly ClassifierChoice[],
315
+ ): SettingItem[] {
157
316
  const copy = COPY[config.settingsLanguage];
158
317
  switch (tab) {
159
318
  case "features":
160
319
  return buildFeaturesItems(config, copy);
320
+ case "compaction":
321
+ return buildCompactionItems(config, copy, choices);
161
322
  case "icons":
162
323
  return buildIconsItems(config, copy);
163
324
  case "segments":
@@ -167,12 +328,21 @@ function buildItems(tab: Tab, config: TuiConfig): SettingItem[] {
167
328
  }
168
329
  }
169
330
 
170
- function handleSettingChange(tab: Tab, itemId: string, config: TuiConfig): TuiConfig {
331
+ function handleSettingChange(
332
+ tab: Tab,
333
+ itemId: string,
334
+ config: TuiConfig,
335
+ choices: readonly ClassifierChoice[],
336
+ ): TuiConfig {
171
337
  if (tab === "features") {
172
338
  if (itemId === "enabled") return toggleEnabled(config);
173
339
  if (itemId === "vim") return toggleVim(config);
174
340
  if (itemId === "settingsLanguage") return toggleLanguage(config);
175
341
  }
342
+ if (tab === "compaction") {
343
+ if (itemId === "smartCompactionEnabled") return toggleSmartCompaction(config);
344
+ if (itemId === "smartCompactionClassifier") return cycleClassifier(config, choices);
345
+ }
176
346
  if (tab === "icons" && itemId === "mode") return cycleIconMode(config);
177
347
  if (tab === "segments") {
178
348
  return toggleSetting(config, itemId as keyof TuiConfig["footerSegments"]);
@@ -200,10 +370,13 @@ export interface SettingsUiHandle {
200
370
  export const makeSettingsUi = (
201
371
  theme: Theme,
202
372
  config: TuiConfig,
373
+ classifierChoices: readonly ClassifierChoice[],
374
+ hasTracker: boolean,
203
375
  onChange: (config: TuiConfig) => void,
204
376
  onClose: () => void,
205
377
  router: VimRouter["Service"],
206
378
  ): SettingsUiHandle => {
379
+ const tabs = tabsFor(hasTracker);
207
380
  let tab: Tab = "features";
208
381
  let currentConfig = config;
209
382
  let selectList!: SelectList;
@@ -214,16 +387,72 @@ export const makeSettingsUi = (
214
387
  let cachedLines: string[] | undefined;
215
388
  let compact = false;
216
389
 
390
+ const adjustNeedsContextProbability = (delta: number): void => {
391
+ currentConfig = {
392
+ ...currentConfig,
393
+ smartCompaction: {
394
+ ...currentConfig.smartCompaction,
395
+ needsContextProbabilityThreshold: adjustSmartCompactionProbability(
396
+ currentConfig.smartCompaction.needsContextProbabilityThreshold,
397
+ delta,
398
+ ),
399
+ },
400
+ };
401
+ onChange(currentConfig);
402
+ rebuild("smartCompactionNeedsContextProbability");
403
+ };
404
+
405
+ const adjustMinAnswerConfidence = (delta: number): void => {
406
+ currentConfig = {
407
+ ...currentConfig,
408
+ smartCompaction: {
409
+ ...currentConfig.smartCompaction,
410
+ minAnswerConfidence: adjustSmartCompactionProbability(
411
+ currentConfig.smartCompaction.minAnswerConfidence,
412
+ delta,
413
+ ),
414
+ },
415
+ };
416
+ onChange(currentConfig);
417
+ rebuild("smartCompactionMinAnswerConfidence");
418
+ };
419
+
420
+ const adjustMaxCandidatesBy = (delta: number): void => {
421
+ currentConfig = {
422
+ ...currentConfig,
423
+ smartCompaction: {
424
+ ...currentConfig.smartCompaction,
425
+ maxCandidates: adjustMaxCandidates(currentConfig.smartCompaction.maxCandidates, delta),
426
+ },
427
+ };
428
+ onChange(currentConfig);
429
+ rebuild("smartCompactionMaxCandidates");
430
+ };
431
+
217
432
  const applySetting = (itemId: string): void => {
218
433
  selectedItemByTab[tab] = itemId;
219
- currentConfig = handleSettingChange(tab, itemId, currentConfig);
434
+ // The numeric rows have no enumerated value: Enter/Space steps them up, and
435
+ // the +/− keys step them either way.
436
+ if (itemId === "smartCompactionNeedsContextProbability") {
437
+ adjustNeedsContextProbability(SMART_COMPACTION_PROBABILITY_STEP);
438
+ return;
439
+ }
440
+ if (itemId === "smartCompactionMinAnswerConfidence") {
441
+ adjustMinAnswerConfidence(SMART_COMPACTION_PROBABILITY_STEP);
442
+ return;
443
+ }
444
+ if (itemId === "smartCompactionMaxCandidates") {
445
+ adjustMaxCandidatesBy(MAX_CANDIDATES_STEP);
446
+ return;
447
+ }
448
+ currentConfig = handleSettingChange(tab, itemId, currentConfig, classifierChoices);
220
449
  onChange(currentConfig);
221
450
  rebuild(itemId);
222
451
  };
223
452
 
224
453
  const switchTab = (offset: number): void => {
225
- const idx = TABS.indexOf(tab);
226
- tab = TABS[(idx + offset + TABS.length) % TABS.length]!;
454
+ const idx = tabs.indexOf(tab);
455
+ tab = tabs[(idx + offset + tabs.length) % tabs.length]!;
227
456
  rebuild();
228
457
  };
229
458
 
@@ -231,15 +460,17 @@ export const makeSettingsUi = (
231
460
  const copy = COPY[currentConfig.settingsLanguage];
232
461
  body.clear();
233
462
 
234
- const tabBar = TABS.map((tabName) => {
235
- const active = tabName === tab;
236
- const label = active ? `[${copy.tabs[tabName]}]` : ` ${copy.tabs[tabName]} `;
237
- return active ? theme.fg("accent", label) : theme.fg("dim", label);
238
- }).join(" ");
463
+ const tabBar = tabs
464
+ .map((tabName) => {
465
+ const active = tabName === tab;
466
+ const label = active ? `[${copy.tabs[tabName]}]` : ` ${copy.tabs[tabName]} `;
467
+ return active ? theme.fg("accent", label) : theme.fg("dim", label);
468
+ })
469
+ .join(" ");
239
470
  body.addChild(new Text(tabBar, 0, 0));
240
471
  body.addChild(new Text(theme.fg("dim", copy.hint), 0, 0));
241
472
 
242
- const items = buildItems(tab, currentConfig).map(
473
+ const items = buildItems(tab, currentConfig, classifierChoices).map(
243
474
  (item) =>
244
475
  ({
245
476
  value: item.id,
@@ -271,8 +502,8 @@ export const makeSettingsUi = (
271
502
  body.addChild(selectList);
272
503
 
273
504
  bordered = makeBorderedBox(body, theme, {
274
- label: theme.bold(theme.fg("accent", copy.title)),
275
- bg: (s: string) => theme.bg("customMessageBg", s),
505
+ label: theme.style(copy.title, { fg: "accent", bold: true }),
506
+ bg: "customMessageBg",
276
507
  });
277
508
  cachedWidth = undefined;
278
509
  cachedLines = undefined;
@@ -286,7 +517,7 @@ export const makeSettingsUi = (
286
517
  * (h/l drive switchTab) with or without the vim toggle.
287
518
  */
288
519
  const moveSelection = (offset: number): void => {
289
- const items = buildItems(tab, currentConfig);
520
+ const items = buildItems(tab, currentConfig, classifierChoices);
290
521
  if (items.length === 0) return;
291
522
  const currentIndex = items.findIndex((item) => item.id === selectList.getSelectedItem()?.value);
292
523
  const nextIndex = (currentIndex + offset + items.length) % items.length;
@@ -322,6 +553,18 @@ export const makeSettingsUi = (
322
553
  if (matchesKey(data, Key.space) || data === " ") {
323
554
  const selected = selectList.getSelectedItem();
324
555
  if (selected) applySetting(selected.value);
556
+ } else if (data === "+" || data === "=" || data === "-" || data === "_") {
557
+ const selected = selectList.getSelectedItem()?.value;
558
+ const sign = data === "+" || data === "=" ? 1 : -1;
559
+ if (selected === "smartCompactionNeedsContextProbability") {
560
+ adjustNeedsContextProbability(sign * SMART_COMPACTION_PROBABILITY_STEP);
561
+ } else if (selected === "smartCompactionMinAnswerConfidence") {
562
+ adjustMinAnswerConfidence(sign * SMART_COMPACTION_PROBABILITY_STEP);
563
+ } else if (selected === "smartCompactionMaxCandidates") {
564
+ adjustMaxCandidatesBy(sign * MAX_CANDIDATES_STEP);
565
+ } else {
566
+ selectList.handleInput?.(data);
567
+ }
325
568
  } else {
326
569
  selectList.handleInput?.(data);
327
570
  }
@@ -365,11 +608,15 @@ export function registerSettingsCommand(
365
608
  description: "Open the tui settings UI",
366
609
  handler: async (_args, ctx: ExtensionContext) => {
367
610
  if (!ctx.hasUI) return;
611
+ const choices = await loadClassifierChoices(ctx.modelRegistry);
612
+ const hasTracker = hasTrackerExtension(pi);
368
613
  await ctx.ui.custom<void>(
369
614
  (tui: TUI, theme, _kb, done) => {
370
615
  const ui = makeSettingsUi(
371
616
  theme,
372
617
  hooks.getConfig(),
618
+ choices,
619
+ hasTracker,
373
620
  (config) => hooks.onConfigChanged(config),
374
621
  () => done(undefined),
375
622
  router,
@@ -383,7 +630,16 @@ export function registerSettingsCommand(
383
630
  },
384
631
  };
385
632
  },
386
- { overlay: true },
633
+ {
634
+ overlay: true,
635
+ overlayOptions: {
636
+ width: "60%",
637
+ minWidth: 44,
638
+ maxHeight: "80%",
639
+ anchor: "center",
640
+ margin: 1,
641
+ },
642
+ },
387
643
  );
388
644
  },
389
645
  });
@@ -0,0 +1,39 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import type { Theme, ThemeToken } from "@earendil-works/pi-coding-agent";
3
+ import { type Color, mixColors, rgbColor } from "@earendil-works/pi-tui";
4
+ import { emphasize, isDark, mixThemeTokens, recede } from "./theme-color.ts";
5
+
6
+ // Stub theme: only the tokens the helpers read, plus the appearance branch.
7
+ const colors = {
8
+ accent: rgbColor(200, 60, 60),
9
+ text: rgbColor(230, 230, 230),
10
+ userMessageBg: rgbColor(30, 30, 30),
11
+ } as unknown as Readonly<Record<ThemeToken, Color>>;
12
+ const darkTheme = { colors, appearance: "dark" } as unknown as Theme;
13
+ const lightTheme = { colors, appearance: "light" } as unknown as Theme;
14
+
15
+ it("mixThemeTokens mixes the two tokens in OKLCH", () => {
16
+ assert.deepStrictEqual(
17
+ mixThemeTokens(darkTheme, "accent", "text", 0.25),
18
+ mixColors(colors.accent, colors.text, 0.25, "oklch"),
19
+ );
20
+ });
21
+
22
+ it("recede mixes toward the theme surface token", () => {
23
+ assert.deepStrictEqual(
24
+ recede(darkTheme, "accent", 0.5),
25
+ mixColors(colors.accent, colors.userMessageBg, 0.5, "oklch"),
26
+ );
27
+ });
28
+
29
+ it("emphasize mixes toward the theme text token", () => {
30
+ assert.deepStrictEqual(
31
+ emphasize(darkTheme, "accent", 0.5),
32
+ mixColors(colors.accent, colors.text, 0.5, "oklch"),
33
+ );
34
+ });
35
+
36
+ it("isDark reports the theme appearance", () => {
37
+ assert.strictEqual(isDark(darkTheme), true);
38
+ assert.strictEqual(isDark(lightTheme), false);
39
+ });
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Derived theme colors for the house UI.
3
+ *
4
+ * `theme.colors` exposes a concrete `Color` for every theme token, and
5
+ * pi-tui's `mixColors()` does the color math. Use these helpers when a
6
+ * component needs a shade that is not a theme token: a dimmed border, a
7
+ * hovered row, or a blended track. `theme.appearance` (`"dark"` or
8
+ * `"light"`) is available when a caller must choose a direction itself.
9
+ *
10
+ * Convert once and reuse: OKLCH mixes are more expensive than rendering a
11
+ * ready color, so callers should compute a shade outside the render path
12
+ * when it is stable.
13
+ */
14
+ import type { Theme, ThemeToken } from "@earendil-works/pi-coding-agent";
15
+ import { type Color, mixColors } from "@earendil-works/pi-tui";
16
+
17
+ /** Mix a theme token toward another theme token by `amount` (0..1) in OKLCH. */
18
+ export const mixThemeTokens = (
19
+ theme: Theme,
20
+ from: ThemeToken,
21
+ toward: ThemeToken,
22
+ amount: number,
23
+ ): Color => mixColors(theme.colors[from], theme.colors[toward], amount, "oklch");
24
+
25
+ /** A shade of `token` that recedes into the theme surface (`userMessageBg`). */
26
+ export const recede = (theme: Theme, token: ThemeToken, amount: number): Color =>
27
+ mixThemeTokens(theme, token, "userMessageBg", amount);
28
+
29
+ /** A shade of `token` with more contrast against the theme surface (`text`). */
30
+ export const emphasize = (theme: Theme, token: ThemeToken, amount: number): Color =>
31
+ mixThemeTokens(theme, token, "text", amount);
32
+
33
+ /**
34
+ * The theme's target appearance, for callers that must branch themselves.
35
+ * `recede()` and `emphasize()` already follow the palette, because the
36
+ * `userMessageBg` and `text` tokens are appearance-relative.
37
+ */
38
+ export const isDark = (theme: Theme): boolean => theme.appearance === "dark";
@@ -0,0 +1,152 @@
1
+ import { afterEach, assert, it } from "@effect/vitest";
2
+ import type { Theme } from "@earendil-works/pi-coding-agent";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join, sep } from "node:path";
6
+ import {
7
+ alignRight,
8
+ cacheHitColor,
9
+ center,
10
+ findBottomBorderIndex,
11
+ fitSegmentsByPriority,
12
+ fmtTokens,
13
+ formatCost,
14
+ formatCwd,
15
+ formatDuration,
16
+ formatModelLabel,
17
+ formatProviderLabel,
18
+ formatThinkingLabel,
19
+ isEditorBorderLine,
20
+ padRight,
21
+ providerColor,
22
+ sanitizeStatus,
23
+ stressColor,
24
+ stripAnsi,
25
+ truncatePath,
26
+ } from "./utils.ts";
27
+
28
+ // Identity theme: styling is a no-op so assertions read the plain text.
29
+ const theme = {
30
+ fg: (_color: string, text: string) => text,
31
+ bg: (_color: string, text: string) => text,
32
+ bold: (text: string) => text,
33
+ } as unknown as Theme;
34
+
35
+ const dirs: string[] = [];
36
+
37
+ afterEach(() => {
38
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
39
+ });
40
+
41
+ it("stripAnsi removes SGR and OSC sequences", () => {
42
+ assert.strictEqual(stripAnsi("\x1b[31mred\x1b[0m"), "red");
43
+ assert.strictEqual(stripAnsi("a\x1b]0;title\x07b"), "ab");
44
+ });
45
+
46
+ it("formatCwd collapses paths inside HOME and leaves others literal", () => {
47
+ const home = mkdtempSync(join(tmpdir(), "pi-tui-home-"));
48
+ dirs.push(home);
49
+ const previous = process.env.HOME;
50
+ process.env.HOME = home;
51
+ try {
52
+ assert.strictEqual(formatCwd(home), "~");
53
+ assert.strictEqual(formatCwd(join(home, "dev")), `~${sep}dev`);
54
+ assert.strictEqual(formatCwd("/etc"), "/etc");
55
+ } finally {
56
+ if (previous === undefined) delete process.env.HOME;
57
+ else process.env.HOME = previous;
58
+ }
59
+ });
60
+
61
+ it("truncatePath keeps the first and trailing segments", () => {
62
+ assert.strictEqual(truncatePath("~/dev", 20), "~/dev");
63
+ assert.strictEqual(truncatePath("~/dev/projects/pi-mono/packages/tui", 20), "~/.../packages/tui");
64
+ assert.strictEqual(truncatePath("abcdefgh", 3), "...");
65
+ });
66
+
67
+ it("fmtTokens uses plain digits below 1k and scales above", () => {
68
+ assert.strictEqual(fmtTokens(999), "999");
69
+ assert.strictEqual(fmtTokens(1500), "1.5k");
70
+ assert.strictEqual(fmtTokens(15_000), "15k");
71
+ assert.strictEqual(fmtTokens(2_000_000), "2.0M");
72
+ assert.strictEqual(fmtTokens(12_000_000), "12M");
73
+ });
74
+
75
+ it("formatCost appends the currency sign only when the glyph lacks it", () => {
76
+ assert.strictEqual(formatCost("$", 1.5), "$ 1.500");
77
+ assert.strictEqual(formatCost("n", 1.5, 2), "n $1.50");
78
+ });
79
+
80
+ it("formatDuration clamps negatives and scales through hours", () => {
81
+ assert.strictEqual(formatDuration(-5), "0s");
82
+ assert.strictEqual(formatDuration(0), "0s");
83
+ assert.strictEqual(formatDuration(1000), "1s");
84
+ assert.strictEqual(formatDuration(59_000), "59s");
85
+ assert.strictEqual(formatDuration(60_000), "1m 0s");
86
+ assert.strictEqual(formatDuration(3_600_000), "1h 0m 0s");
87
+ assert.strictEqual(formatDuration(3_723_000), "1h 2m 3s");
88
+ });
89
+
90
+ it("model, provider, and thinking labels", () => {
91
+ assert.strictEqual(formatModelLabel(undefined), "no-model");
92
+ assert.strictEqual(formatModelLabel({ id: "gpt" }), "gpt");
93
+ assert.strictEqual(formatModelLabel({ provider: "openai", id: "gpt" }), "openai/gpt");
94
+ assert.strictEqual(formatProviderLabel(undefined), "Unknown");
95
+ assert.strictEqual(formatProviderLabel("openai"), "Openai");
96
+ assert.strictEqual(formatThinkingLabel("off"), "thinking off");
97
+ assert.strictEqual(formatThinkingLabel("high"), "high effort");
98
+ });
99
+
100
+ it("threshold colors map to the expected tokens", () => {
101
+ assert.strictEqual(stressColor(50), "accent");
102
+ assert.strictEqual(stressColor(70), "warning");
103
+ assert.strictEqual(stressColor(95), "error");
104
+ assert.strictEqual(cacheHitColor(10), "error");
105
+ assert.strictEqual(cacheHitColor(50), "warning");
106
+ assert.strictEqual(cacheHitColor(80), "success");
107
+ assert.strictEqual(providerColor("anthropic"), "accent");
108
+ assert.strictEqual(providerColor("openai"), "success");
109
+ assert.strictEqual(providerColor("mystery"), "muted");
110
+ });
111
+
112
+ it("alignRight pads the gap and keeps the right block flush", () => {
113
+ assert.strictEqual(alignRight("a", "b", 5, theme), "a b");
114
+ assert.strictEqual(alignRight("a", "b", 2, theme), "b");
115
+ });
116
+
117
+ it("fitSegmentsByPriority drops the lowest priority first", () => {
118
+ const kept = fitSegmentsByPriority(
119
+ [
120
+ { text: "a", priority: 0 },
121
+ { text: "bb", priority: 1 },
122
+ ],
123
+ 5,
124
+ );
125
+ assert.deepStrictEqual(kept, ["a", "bb"]);
126
+
127
+ const dropped = fitSegmentsByPriority(
128
+ [
129
+ { text: "aaaa", priority: 0 },
130
+ { text: "bb", priority: 1 },
131
+ ],
132
+ 4,
133
+ );
134
+ assert.deepStrictEqual(dropped, ["bb"]);
135
+ });
136
+
137
+ it("padRight and center produce the expected columns", () => {
138
+ assert.strictEqual(padRight("ab", 5), "ab ");
139
+ assert.strictEqual(center("ab", 6), " ab");
140
+ });
141
+
142
+ it("sanitizeStatus strips ANSI, controls, and collapses whitespace", () => {
143
+ assert.strictEqual(sanitizeStatus("\x1b[31m a\n b \x1b[0m"), "a b");
144
+ });
145
+
146
+ it("editor border detection and bottom-border lookup", () => {
147
+ assert.strictEqual(isEditorBorderLine("────"), true);
148
+ assert.strictEqual(isEditorBorderLine("↓ 3 more"), true);
149
+ assert.strictEqual(isEditorBorderLine("hello"), false);
150
+ assert.strictEqual(findBottomBorderIndex(["a", "─", "b"]), 1);
151
+ assert.strictEqual(findBottomBorderIndex(["a", "b"]), 1);
152
+ });
@@ -8,9 +8,7 @@
8
8
  * degrade softly (no-op) if pi's internals change shape, instead of crashing
9
9
  * with a TypeError.
10
10
  */
11
- export function closeAutocomplete(editor: {
12
- readonly isShowingAutocomplete: () => boolean;
13
- }): void {
11
+ export function closeAutocomplete(editor: { readonly isShowingAutocomplete: () => boolean }): void {
14
12
  if (!editor.isShowingAutocomplete()) return;
15
13
  const internal = editor as unknown as {
16
14
  readonly cancelAutocomplete?: () => void;