@ftrdotdev/pi-tui 0.8.0 → 0.9.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 (76) hide show
  1. package/CHANGELOG.md +225 -0
  2. package/README.md +5 -0
  3. package/package.json +18 -15
  4. package/src/activity-service.test.ts +97 -0
  5. package/src/activity.test.ts +1 -1
  6. package/src/activity.ts +38 -0
  7. package/src/chrome/budget.test.ts +345 -0
  8. package/src/chrome/budget.ts +220 -0
  9. package/src/chrome/declarations.ts +303 -0
  10. package/src/chrome/facts.test.ts +165 -0
  11. package/src/chrome/facts.ts +267 -0
  12. package/src/chrome/frame.ts +45 -0
  13. package/src/chrome/laws.test.ts +231 -0
  14. package/src/chrome/port.test.ts +164 -0
  15. package/src/chrome/port.ts +67 -0
  16. package/src/chrome/service-provider.test.ts +383 -0
  17. package/src/chrome/service-provider.ts +55 -0
  18. package/src/commands/git-execution.test.ts +5 -2
  19. package/src/commands/git-execution.ts +27 -15
  20. package/src/commands/git-status.test.ts +47 -15
  21. package/src/commands/git-status.ts +83 -31
  22. package/src/components/bordered-box.test.ts +12 -15
  23. package/src/components/bordered-box.ts +11 -7
  24. package/src/components/define-component.ts +1 -1
  25. package/src/components/index.ts +7 -0
  26. package/src/components/row-list.test.ts +310 -0
  27. package/src/components/row-list.ts +272 -0
  28. package/src/config.test.ts +118 -3
  29. package/src/config.ts +46 -40
  30. package/src/frame/box-frame.test.ts +53 -7
  31. package/src/harness-policy.test.ts +47 -0
  32. package/src/icons.test.ts +19 -0
  33. package/src/icons.ts +50 -31
  34. package/src/index.test.ts +135 -0
  35. package/src/index.ts +118 -119
  36. package/src/layers.test.ts +94 -0
  37. package/src/layers.ts +92 -0
  38. package/src/runtime-service.test.ts +218 -0
  39. package/src/runtime-service.ts +103 -0
  40. package/src/runtime.test.ts +165 -66
  41. package/src/runtime.ts +127 -93
  42. package/src/session-lifecycle-service.test.ts +95 -0
  43. package/src/session-lifecycle.test.ts +77 -0
  44. package/src/session-lifecycle.ts +21 -0
  45. package/src/state.test.ts +132 -3
  46. package/src/state.ts +43 -13
  47. package/src/telemetry-service.test.ts +250 -0
  48. package/src/telemetry.test.ts +322 -0
  49. package/src/telemetry.ts +130 -23
  50. package/src/ui/editor-tint.test.ts +58 -45
  51. package/src/ui/editor-tint.ts +1 -1
  52. package/src/ui/editor.ts +117 -53
  53. package/src/ui/footer.test.ts +349 -120
  54. package/src/ui/footer.ts +147 -124
  55. package/src/ui/header.test.ts +203 -223
  56. package/src/ui/header.ts +32 -96
  57. package/src/ui/preview.test.ts +73 -70
  58. package/src/ui/preview.ts +48 -33
  59. package/src/ui/render-helpers.test.ts +82 -13
  60. package/src/ui/render-helpers.ts +110 -122
  61. package/src/ui/settings-command.test.ts +70 -11
  62. package/src/ui/settings-command.ts +30 -45
  63. package/src/ui/theme-color.test.ts +4 -3
  64. package/src/usage-totals-service.test.ts +230 -0
  65. package/src/usage-totals-service.ts +59 -0
  66. package/src/utils.test.ts +46 -50
  67. package/src/utils.ts +41 -239
  68. package/src/vim/editor-host.test.ts +201 -75
  69. package/src/vim/editor-state.ts +2 -2
  70. package/src/vim/mode-indicator.test.ts +6 -5
  71. package/src/vim/mode-indicator.ts +13 -9
  72. package/src/vim/selection-render.ts +8 -4
  73. package/src/vim/text-model.test.ts +52 -14
  74. package/src/vim/text-model.ts +1 -1
  75. package/src/vim/vim-router.test.ts +3 -0
  76. package/src/vim/vim-router.ts +1 -1
package/src/utils.ts CHANGED
@@ -1,21 +1,29 @@
1
1
  import { isAbsolute, relative, resolve, sep } from "node:path";
2
- import type { ThinkingLevel } from "@earendil-works/pi-ai";
3
- import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
4
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
- import { Effect, Random } from "effect";
2
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ replaceControlCharacters,
5
+ sliceByColumn,
6
+ stripTerminalSequences,
7
+ truncateToWidth,
8
+ visibleWidth,
9
+ } from "@earendil-works/pi-tui";
6
10
 
7
11
  export { truncateToWidth, visibleWidth };
8
12
 
9
13
  /**
10
- * Strip ANSI escape sequences (SGR color/style, OSC, and underscore-OSC
11
- * variants) from a themed string. Used for plain-text comparisons and for
12
- * measuring content without styling noise.
14
+ * True when a string carries text. Optional strings read from JSON, the
15
+ * environment, and pi context are `string | undefined`, and the empty string
16
+ * means the same thing: absent.
17
+ */
18
+ export const isNonEmptyString = (value: string | undefined): value is string =>
19
+ value !== undefined && value !== "";
20
+
21
+ /**
22
+ * Strip ANSI, OSC, and APC terminal sequences from a themed string. Used for
23
+ * plain-text comparisons and for measuring content without styling noise.
13
24
  */
14
25
  export function stripAnsi(text: string): string {
15
- return text
16
- .replace(/\x1b\[[0-9;]*m/g, "")
17
- .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "")
18
- .replace(/\x1b_[^\x07]*\x07/g, "");
26
+ return stripTerminalSequences(text);
19
27
  }
20
28
 
21
29
  /**
@@ -25,7 +33,7 @@ export function stripAnsi(text: string): string {
25
33
  */
26
34
  export function formatCwd(cwd: string): string {
27
35
  const home = process.env.HOME || process.env.USERPROFILE;
28
- if (!home) return cwd;
36
+ if (!isNonEmptyString(home)) return cwd;
29
37
  const resolvedCwd = resolve(cwd);
30
38
  const resolvedHome = resolve(home);
31
39
  const rel = relative(resolvedHome, resolvedCwd);
@@ -41,23 +49,27 @@ export function formatCwd(cwd: string): string {
41
49
  * `...` — e.g. `~/dev/.../packages/tui`.
42
50
  */
43
51
  export function truncatePath(path: string, maxLen: number): string {
44
- if (path.length <= maxLen) return path;
45
- if (maxLen <= 3) return "...".slice(0, maxLen);
52
+ if (visibleWidth(path) <= maxLen) return path;
53
+ const ellipsis = "...";
54
+ if (maxLen <= 3) return sliceByColumn(ellipsis, 0, maxLen, true);
46
55
  const sepChar = path.includes("/") ? "/" : "\\";
47
56
  const parts = path.split(/[\\/]/);
48
- if (parts.length <= 2) return path.slice(0, maxLen - 3) + "...";
57
+ if (parts.length <= 2) return sliceByColumn(path, 0, maxLen - 3, true) + ellipsis;
49
58
  // Keep first segment (e.g. ~) and as many trailing segments as fit.
50
59
  const tail: string[] = [];
51
60
  let tailLen = 0;
52
61
  for (let i = parts.length - 1; i >= 1; i--) {
53
62
  const seg = parts[i]!;
54
- if (tailLen + seg.length + 4 > maxLen) break;
63
+ const segWidth = visibleWidth(seg);
64
+ if (tailLen + segWidth + 4 > maxLen) break;
55
65
  tail.unshift(seg);
56
- tailLen += seg.length + 1;
66
+ tailLen += segWidth + 1;
57
67
  }
58
68
  const head = parts[0]!;
59
- const result = `${head}${sepChar}...${sepChar}${tail.join(sepChar)}`;
60
- return result.length > maxLen ? result.slice(0, maxLen - 3) + "..." : result;
69
+ const result = `${head}${sepChar}${ellipsis}${sepChar}${tail.join(sepChar)}`;
70
+ return visibleWidth(result) > maxLen
71
+ ? sliceByColumn(result, 0, maxLen - 3, true) + ellipsis
72
+ : result;
61
73
  }
62
74
 
63
75
  /**
@@ -103,93 +115,18 @@ export function formatDuration(ms: number): string {
103
115
  export function formatModelLabel(
104
116
  model: { provider?: string; id?: string } | null | undefined,
105
117
  ): string {
106
- if (!model?.id) return "no-model";
107
- return model.provider ? `${model.provider}/${model.id}` : model.id;
118
+ if (!isNonEmptyString(model?.id)) return "no-model";
119
+ return isNonEmptyString(model.provider) ? `${model.provider}/${model.id}` : model.id;
108
120
  }
109
121
 
110
122
  /**
111
123
  * Capitalized provider display label; `Unknown` when absent.
112
124
  */
113
125
  export function formatProviderLabel(provider: string | undefined): string {
114
- if (!provider) return "Unknown";
126
+ if (!isNonEmptyString(provider)) return "Unknown";
115
127
  return provider.charAt(0).toUpperCase() + provider.slice(1);
116
128
  }
117
129
 
118
- /**
119
- * Compose a single line from a left block and a right block: the right
120
- * block is right-aligned (truncated with ellipsis when it alone exceeds
121
- * `width`), and the left block fills the remainder — truncated if it
122
- * does not fit — separated by one space.
123
- */
124
- export function alignRight(left: string, right: string, width: number, theme: Theme): string {
125
- const rightW = visibleWidth(right);
126
- if (rightW > width) {
127
- right = truncateToWidth(right, width, theme.fg("dim", "..."));
128
- }
129
- const leftW = visibleWidth(left);
130
- const rightW2 = visibleWidth(right);
131
- const pad = width - leftW - rightW2;
132
- if (pad >= 1) {
133
- return left + " ".repeat(pad) + right;
134
- }
135
- const availableForLeft = Math.max(0, width - rightW2 - 1);
136
- const truncatedLeft =
137
- availableForLeft > 0 ? truncateToWidth(left, availableForLeft, theme.fg("dim", "...")) : "";
138
- return truncatedLeft ? truncatedLeft + " " + right : right;
139
- }
140
-
141
- /** A text segment with a survival priority; higher survives longer. */
142
- export type PrioritizedSegment = {
143
- text: string;
144
- priority: number;
145
- };
146
-
147
- /**
148
- * Pack segments into maxWidth, shrinking/dropping lowest-priority segments first.
149
- * Higher priority = survives longer. Returns the surviving segment texts in
150
- * original order, space-joined. Each segment is either kept whole, truncated
151
- * with ellipsis, or dropped entirely.
152
- */
153
- export function fitSegmentsByPriority(
154
- segs: readonly PrioritizedSegment[],
155
- maxW: number,
156
- ellipsis = "...",
157
- ): string[] {
158
- const items = segs.map((s) => ({ text: s.text, priority: s.priority, w: visibleWidth(s.text) }));
159
- const totalW = () => {
160
- const active = items.filter((it) => it.text !== "");
161
- return active.reduce((a, it) => a + it.w, 0) + Math.max(0, active.length - 1);
162
- };
163
- while (totalW() > maxW) {
164
- let target = -1;
165
- for (let i = 0; i < items.length; i++) {
166
- if (
167
- items[i]?.text !== "" &&
168
- (target === -1 || (items[i]?.priority ?? -1) < (items[target]?.priority ?? -1))
169
- ) {
170
- target = i;
171
- }
172
- }
173
- if (target === -1) break;
174
- const item = items[target];
175
- if (!item) break;
176
-
177
- const others = items.filter((_, i) => i !== target && items[i]?.text !== "");
178
- const otherW = others.reduce((a, it) => a + it.w, 0) + Math.max(0, others.length - 1);
179
- const avail = maxW - otherW - (others.length > 0 ? 1 : 0);
180
- if (avail <= visibleWidth(ellipsis)) {
181
- item.text = "";
182
- item.w = 0;
183
- } else if (avail < item.w) {
184
- item.text = truncateToWidth(item.text, avail, ellipsis);
185
- item.w = visibleWidth(item.text);
186
- } else {
187
- break;
188
- }
189
- }
190
- return items.filter((it) => it.text !== "").map((it) => it.text);
191
- }
192
-
193
130
  /**
194
131
  * Color token for a utilization percentage (accent under `warn`, warning
195
132
  * up to `danger`, error from there).
@@ -200,16 +137,6 @@ export function stressColor(value: number, warn = 70, danger = 90): ThemeColor {
200
137
  return "accent";
201
138
  }
202
139
 
203
- /**
204
- * Color token for a cache-hit rate: error below 30%, warning below 70%,
205
- * success from there.
206
- */
207
- export function cacheHitColor(value: number): ThemeColor {
208
- if (value < 30) return "error";
209
- if (value < 70) return "warning";
210
- return "success";
211
- }
212
-
213
140
  /**
214
141
  * Color token for a provider name (identity styling); `muted` for
215
142
  * unlisted providers.
@@ -242,10 +169,10 @@ export function providerColor(provider: string): ThemeColor {
242
169
  }
243
170
 
244
171
  /**
245
- * Color token for a thinking-effort label; unknown levels fall back to
246
- * `thinkingMedium`.
172
+ * Color token for a thinking-effort label. The level is a plain string because
173
+ * config may carry any value; unknown levels fall back to `thinkingMedium`.
247
174
  */
248
- export function effortColor(level: ThinkingLevel | string | undefined): ThemeColor {
175
+ export function effortColor(level: string | undefined): ThemeColor {
249
176
  switch (level) {
250
177
  case "minimal":
251
178
  return "thinkingMinimal";
@@ -257,6 +184,8 @@ export function effortColor(level: ThinkingLevel | string | undefined): ThemeCol
257
184
  return "thinkingHigh";
258
185
  case "xhigh":
259
186
  return "thinkingXhigh";
187
+ case "max":
188
+ return "thinkingXhigh";
260
189
  default:
261
190
  return "thinkingMedium";
262
191
  }
@@ -289,8 +218,7 @@ export function findBottomBorderIndex(lines: string[]): number {
289
218
  * overflows. The returned string is exactly `width` terminal columns wide.
290
219
  */
291
220
  export function padRight(text: string, width: number, ellipsis = ""): string {
292
- const clipped = truncateToWidth(text, width, ellipsis);
293
- return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
221
+ return truncateToWidth(text, width, ellipsis, true);
294
222
  }
295
223
 
296
224
  /**
@@ -309,10 +237,7 @@ export function center(text: string, width: number): string {
309
237
  * control characters, collapse whitespace runs, trim.
310
238
  */
311
239
  export function sanitizeStatus(text: string): string {
312
- return stripAnsi(text)
313
- .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
314
- .replace(/ +/g, " ")
315
- .trim();
240
+ return replaceControlCharacters(stripTerminalSequences(text)).replace(/ +/g, " ").trim();
316
241
  }
317
242
 
318
243
  /**
@@ -323,126 +248,3 @@ export function formatThinkingLabel(level: string): string {
323
248
  if (level === "off") return "thinking off";
324
249
  return `${level} effort`;
325
250
  }
326
-
327
- /**
328
- * Slash-command names pi ships built-in (without a leading `/`). Merged
329
- * with the session-command names to form the header tips pool.
330
- */
331
- export const PI_BUILTIN_SLASH_COMMAND_NAMES = [
332
- "settings",
333
- "model",
334
- "scoped-models",
335
- "export",
336
- "import",
337
- "share",
338
- "copy",
339
- "name",
340
- "session",
341
- "changelog",
342
- "hotkeys",
343
- "fork",
344
- "clone",
345
- "tree",
346
- "trust",
347
- "login",
348
- "logout",
349
- "new",
350
- "compact",
351
- "resume",
352
- "reload",
353
- "quit",
354
- ] as const;
355
-
356
- /**
357
- * The full slash-command name pool: pi's builtin names plus any session
358
- * commands (deduplicated, no leading `/`).
359
- */
360
- export function collectPiCommandNames(sessionCommands: readonly { name: string }[]): string[] {
361
- const names = new Set<string>(PI_BUILTIN_SLASH_COMMAND_NAMES);
362
- for (const command of sessionCommands) {
363
- if (command.name) names.add(command.name);
364
- }
365
- return [...names];
366
- }
367
-
368
- /**
369
- * Select the header's slash-command tips: the fixed commands (always
370
- * first) followed by `count` commands shuffled from the remaining pool
371
- * (Fisher–Yates) using Effect's Random service. The shuffle draws from
372
- * the ambient seed, so runners must wrap the program in
373
- * `Random.withSeed(seed)` for deterministic output.
374
- */
375
- export const pickSlashCommandTips = Effect.fn("tui/utils/pickSlashCommandTips")(function* (
376
- availableNames: readonly string[],
377
- options: {
378
- fixed?: readonly string[];
379
- count?: number;
380
- exclude?: readonly string[];
381
- } = {},
382
- ) {
383
- const fixed = [...(options.fixed ?? [])];
384
- const count = options.count ?? 3;
385
- const exclude = new Set<string>([...(options.exclude ?? []), ...fixed]);
386
-
387
- const pool = [...new Set(availableNames.map((n) => n.trim()).filter(Boolean))].filter(
388
- (name) => !exclude.has(name),
389
- );
390
-
391
- for (let i = pool.length - 1; i > 0; i--) {
392
- const j = yield* Random.nextIntBetween(0, i);
393
- const [pi, pj] = [String(pool[i]), String(pool[j])];
394
- pool[j] = pi;
395
- pool[i] = pj;
396
- }
397
-
398
- const picked = pool.slice(0, Math.max(0, count));
399
- return [...fixed, ...picked].map((name) => (name.startsWith("/") ? name : `/${name}`));
400
- });
401
-
402
- /** Minimum left-column width for the two-column header body. */
403
- export const MIN_LEFT_WIDTH = 28;
404
- /** Minimum tips-column width before the tips are dropped. */
405
- export const MIN_TIPS_WIDTH = 16;
406
- /** Maximum tips-column width; excess goes to the left column. */
407
- export const MAX_TIPS_WIDTH = 28;
408
- const COLUMN_GAP = 3;
409
-
410
- /**
411
- * Split an inner (rail-to-rail) width into left/tips columns for the
412
- * header body. Returns `useTips: false` with a single full-width left
413
- * column when the width cannot hold both columns at their minimums.
414
- */
415
- export function headerColumnWidths(
416
- innerWidth: number,
417
- minTipsWidth = MIN_TIPS_WIDTH,
418
- maxTipsWidth = MAX_TIPS_WIDTH,
419
- minLeftWidth = MIN_LEFT_WIDTH,
420
- ): { leftWidth: number; rightWidth: number; useTips: boolean } {
421
- if (innerWidth <= 0) {
422
- return { leftWidth: 0, rightWidth: 0, useTips: false };
423
- }
424
-
425
- const gap = COLUMN_GAP;
426
- if (innerWidth < minLeftWidth + gap + minTipsWidth) {
427
- return { leftWidth: innerWidth, rightWidth: 0, useTips: false };
428
- }
429
-
430
- let rightWidth = Math.min(maxTipsWidth, Math.max(minTipsWidth, Math.round(innerWidth * 0.28)));
431
- let leftWidth = innerWidth - gap - rightWidth;
432
-
433
- if (leftWidth < minLeftWidth) {
434
- leftWidth = minLeftWidth;
435
- rightWidth = innerWidth - gap - leftWidth;
436
- }
437
-
438
- if (leftWidth <= rightWidth) {
439
- leftWidth = Math.ceil((innerWidth - gap) * 0.65);
440
- rightWidth = innerWidth - gap - leftWidth;
441
- }
442
-
443
- if (rightWidth < minTipsWidth || leftWidth < minLeftWidth) {
444
- return { leftWidth: innerWidth, rightWidth: 0, useTips: false };
445
- }
446
-
447
- return { leftWidth, rightWidth, useTips: true };
448
- }