@ftrdotdev/pi-tui 0.5.2 → 0.6.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
+ adjustKeepContextThreshold,
14
+ adjustMaxCandidates,
15
+ KEEP_CONTEXT_THRESHOLD_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 · +/−: threshold · 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
+ smartCompactionKeepContextThreshold: "Keep-context confidence",
73
+ smartCompactionKeepContextMinConfidence: "Min confidence",
74
+ smartCompactionMaxCandidates: "Max candidates",
48
75
  },
49
76
  values: {
50
77
  on: "On",
@@ -93,6 +120,99 @@ 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: (
134
+ type: "classifier",
135
+ ) => Promise<readonly ClassifierDescriptor[]>;
136
+ readonly getModelsOfType: (type: "classifier") => readonly ClassifierDescriptor[];
137
+ }
138
+
139
+ /** The slice of `ExtensionAPI` the dialog needs to detect the tracker. */
140
+ export interface TrackerProbe {
141
+ readonly getAllTools: () => readonly { readonly name: string }[];
142
+ readonly getCommands: () => readonly { readonly name: string; readonly source: string }[];
143
+ }
144
+
145
+ /**
146
+ * Whether the tracker extension is loaded in this session. The tracker
147
+ * registers a tool and a command named `tracker`; either one proves presence,
148
+ * so the Compaction tab is hidden when it is not installed.
149
+ */
150
+ export const hasTrackerExtension = (probe: TrackerProbe): boolean =>
151
+ probe.getAllTools().some((tool) => tool.name === "tracker") ||
152
+ probe
153
+ .getCommands()
154
+ .some((command) => command.name === "tracker" && command.source === "extension");
155
+
156
+ export interface ClassifierChoice {
157
+ /** `"provider/modelId"`, or null for the preference order. */
158
+ readonly value: string | null;
159
+ readonly label: string;
160
+ }
161
+
162
+ const AUTOMATIC_CLASSIFIER_CHOICE: ClassifierChoice = {
163
+ value: null,
164
+ label: "Automatic (prefer Clef Flash, then Jev)",
165
+ };
166
+
167
+ /**
168
+ * Credential-available classifiers, else the whole catalog. `Automatic` is
169
+ * always first, so a chosen classifier is reversible.
170
+ */
171
+ export const loadClassifierChoices = async (
172
+ source: ClassifierSource,
173
+ ): Promise<ClassifierChoice[]> => {
174
+ let models: readonly ClassifierDescriptor[];
175
+ try {
176
+ const available = await source.getAvailableOfType("classifier");
177
+ models = available.length > 0 ? available : source.getModelsOfType("classifier");
178
+ } catch {
179
+ // Discovery failure must not empty the picker.
180
+ models = source.getModelsOfType("classifier");
181
+ }
182
+ const choices: ClassifierChoice[] = [AUTOMATIC_CLASSIFIER_CHOICE];
183
+ const seen = new Set<string>();
184
+ for (const model of models) {
185
+ const value = `${model.provider}/${model.id}`;
186
+ if (seen.has(value)) continue;
187
+ seen.add(value);
188
+ choices.push({ value, label: model.name ?? value });
189
+ }
190
+ return choices;
191
+ };
192
+
193
+ function classifierLabel(choices: readonly ClassifierChoice[], value: string | null): string {
194
+ if (value === null) return AUTOMATIC_CLASSIFIER_CHOICE.label;
195
+ return choices.find((choice) => choice.value === value)?.label ?? value;
196
+ }
197
+
198
+ function toggleSmartCompaction(config: TuiConfig): TuiConfig {
199
+ return {
200
+ ...config,
201
+ smartCompaction: { ...config.smartCompaction, enabled: !config.smartCompaction.enabled },
202
+ };
203
+ }
204
+
205
+ function cycleClassifier(config: TuiConfig, choices: readonly ClassifierChoice[]): TuiConfig {
206
+ const currentIndex = choices.findIndex(
207
+ (choice) => choice.value === config.smartCompaction.classifier,
208
+ );
209
+ const next = choices[(currentIndex + 1) % choices.length] ?? AUTOMATIC_CLASSIFIER_CHOICE;
210
+ return { ...config, smartCompaction: { ...config.smartCompaction, classifier: next.value } };
211
+ }
212
+
213
+ /** Two-decimal display for the keep-context threshold row. */
214
+ const formatKeepContextThreshold = (value: number): string => value.toFixed(2);
215
+
96
216
  function buildFeaturesItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
97
217
  return [
98
218
  {
@@ -113,6 +233,43 @@ function buildFeaturesItems(config: TuiConfig, copy: SettingsCopy): SettingItem[
113
233
  ];
114
234
  }
115
235
 
236
+ /** Integer display for the max-candidates row. */
237
+ const formatMaxCandidates = (value: number): string => String(value);
238
+
239
+ function buildCompactionItems(
240
+ config: TuiConfig,
241
+ copy: SettingsCopy,
242
+ choices: readonly ClassifierChoice[],
243
+ ): SettingItem[] {
244
+ return [
245
+ {
246
+ id: "smartCompactionEnabled",
247
+ label: copy.labels.smartCompactionEnabled,
248
+ currentValue: config.smartCompaction.enabled ? copy.values.on : copy.values.off,
249
+ },
250
+ {
251
+ id: "smartCompactionClassifier",
252
+ label: copy.labels.smartCompactionClassifier,
253
+ currentValue: classifierLabel(choices, config.smartCompaction.classifier),
254
+ },
255
+ {
256
+ id: "smartCompactionKeepContextThreshold",
257
+ label: copy.labels.smartCompactionKeepContextThreshold,
258
+ currentValue: formatKeepContextThreshold(config.smartCompaction.keepContextThreshold),
259
+ },
260
+ {
261
+ id: "smartCompactionKeepContextMinConfidence",
262
+ label: copy.labels.smartCompactionKeepContextMinConfidence,
263
+ currentValue: formatKeepContextThreshold(config.smartCompaction.keepContextMinConfidence),
264
+ },
265
+ {
266
+ id: "smartCompactionMaxCandidates",
267
+ label: copy.labels.smartCompactionMaxCandidates,
268
+ currentValue: formatMaxCandidates(config.smartCompaction.maxCandidates),
269
+ },
270
+ ];
271
+ }
272
+
116
273
  function buildIconsItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
117
274
  return [
118
275
  { id: "mode", label: copy.labels.iconMode, currentValue: copy.values.icons[config.icons.mode] },
@@ -153,11 +310,17 @@ function buildTelemetryItems(config: TuiConfig, copy: SettingsCopy): SettingItem
153
310
  ];
154
311
  }
155
312
 
156
- function buildItems(tab: Tab, config: TuiConfig): SettingItem[] {
313
+ function buildItems(
314
+ tab: Tab,
315
+ config: TuiConfig,
316
+ choices: readonly ClassifierChoice[],
317
+ ): SettingItem[] {
157
318
  const copy = COPY[config.settingsLanguage];
158
319
  switch (tab) {
159
320
  case "features":
160
321
  return buildFeaturesItems(config, copy);
322
+ case "compaction":
323
+ return buildCompactionItems(config, copy, choices);
161
324
  case "icons":
162
325
  return buildIconsItems(config, copy);
163
326
  case "segments":
@@ -167,12 +330,21 @@ function buildItems(tab: Tab, config: TuiConfig): SettingItem[] {
167
330
  }
168
331
  }
169
332
 
170
- function handleSettingChange(tab: Tab, itemId: string, config: TuiConfig): TuiConfig {
333
+ function handleSettingChange(
334
+ tab: Tab,
335
+ itemId: string,
336
+ config: TuiConfig,
337
+ choices: readonly ClassifierChoice[],
338
+ ): TuiConfig {
171
339
  if (tab === "features") {
172
340
  if (itemId === "enabled") return toggleEnabled(config);
173
341
  if (itemId === "vim") return toggleVim(config);
174
342
  if (itemId === "settingsLanguage") return toggleLanguage(config);
175
343
  }
344
+ if (tab === "compaction") {
345
+ if (itemId === "smartCompactionEnabled") return toggleSmartCompaction(config);
346
+ if (itemId === "smartCompactionClassifier") return cycleClassifier(config, choices);
347
+ }
176
348
  if (tab === "icons" && itemId === "mode") return cycleIconMode(config);
177
349
  if (tab === "segments") {
178
350
  return toggleSetting(config, itemId as keyof TuiConfig["footerSegments"]);
@@ -200,10 +372,13 @@ export interface SettingsUiHandle {
200
372
  export const makeSettingsUi = (
201
373
  theme: Theme,
202
374
  config: TuiConfig,
375
+ classifierChoices: readonly ClassifierChoice[],
376
+ hasTracker: boolean,
203
377
  onChange: (config: TuiConfig) => void,
204
378
  onClose: () => void,
205
379
  router: VimRouter["Service"],
206
380
  ): SettingsUiHandle => {
381
+ const tabs = tabsFor(hasTracker);
207
382
  let tab: Tab = "features";
208
383
  let currentConfig = config;
209
384
  let selectList!: SelectList;
@@ -214,16 +389,72 @@ export const makeSettingsUi = (
214
389
  let cachedLines: string[] | undefined;
215
390
  let compact = false;
216
391
 
392
+ const adjustThreshold = (delta: number): void => {
393
+ currentConfig = {
394
+ ...currentConfig,
395
+ smartCompaction: {
396
+ ...currentConfig.smartCompaction,
397
+ keepContextThreshold: adjustKeepContextThreshold(
398
+ currentConfig.smartCompaction.keepContextThreshold,
399
+ delta,
400
+ ),
401
+ },
402
+ };
403
+ onChange(currentConfig);
404
+ rebuild("smartCompactionKeepContextThreshold");
405
+ };
406
+
407
+ const adjustMinConfidenceBy = (delta: number): void => {
408
+ currentConfig = {
409
+ ...currentConfig,
410
+ smartCompaction: {
411
+ ...currentConfig.smartCompaction,
412
+ keepContextMinConfidence: adjustKeepContextThreshold(
413
+ currentConfig.smartCompaction.keepContextMinConfidence,
414
+ delta,
415
+ ),
416
+ },
417
+ };
418
+ onChange(currentConfig);
419
+ rebuild("smartCompactionKeepContextMinConfidence");
420
+ };
421
+
422
+ const adjustMaxCandidatesBy = (delta: number): void => {
423
+ currentConfig = {
424
+ ...currentConfig,
425
+ smartCompaction: {
426
+ ...currentConfig.smartCompaction,
427
+ maxCandidates: adjustMaxCandidates(currentConfig.smartCompaction.maxCandidates, delta),
428
+ },
429
+ };
430
+ onChange(currentConfig);
431
+ rebuild("smartCompactionMaxCandidates");
432
+ };
433
+
217
434
  const applySetting = (itemId: string): void => {
218
435
  selectedItemByTab[tab] = itemId;
219
- currentConfig = handleSettingChange(tab, itemId, currentConfig);
436
+ // The numeric rows have no enumerated value: Enter/Space steps them up, and
437
+ // the +/− keys step them either way.
438
+ if (itemId === "smartCompactionKeepContextThreshold") {
439
+ adjustThreshold(KEEP_CONTEXT_THRESHOLD_STEP);
440
+ return;
441
+ }
442
+ if (itemId === "smartCompactionKeepContextMinConfidence") {
443
+ adjustMinConfidenceBy(KEEP_CONTEXT_THRESHOLD_STEP);
444
+ return;
445
+ }
446
+ if (itemId === "smartCompactionMaxCandidates") {
447
+ adjustMaxCandidatesBy(MAX_CANDIDATES_STEP);
448
+ return;
449
+ }
450
+ currentConfig = handleSettingChange(tab, itemId, currentConfig, classifierChoices);
220
451
  onChange(currentConfig);
221
452
  rebuild(itemId);
222
453
  };
223
454
 
224
455
  const switchTab = (offset: number): void => {
225
- const idx = TABS.indexOf(tab);
226
- tab = TABS[(idx + offset + TABS.length) % TABS.length]!;
456
+ const idx = tabs.indexOf(tab);
457
+ tab = tabs[(idx + offset + tabs.length) % tabs.length]!;
227
458
  rebuild();
228
459
  };
229
460
 
@@ -231,7 +462,7 @@ export const makeSettingsUi = (
231
462
  const copy = COPY[currentConfig.settingsLanguage];
232
463
  body.clear();
233
464
 
234
- const tabBar = TABS.map((tabName) => {
465
+ const tabBar = tabs.map((tabName) => {
235
466
  const active = tabName === tab;
236
467
  const label = active ? `[${copy.tabs[tabName]}]` : ` ${copy.tabs[tabName]} `;
237
468
  return active ? theme.fg("accent", label) : theme.fg("dim", label);
@@ -239,7 +470,7 @@ export const makeSettingsUi = (
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 === "smartCompactionKeepContextThreshold") {
560
+ adjustThreshold(sign * KEEP_CONTEXT_THRESHOLD_STEP);
561
+ } else if (selected === "smartCompactionKeepContextMinConfidence") {
562
+ adjustMinConfidenceBy(sign * KEEP_CONTEXT_THRESHOLD_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;