@ftrdotdev/pi-tui 0.5.1 → 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.
package/README.md CHANGED
@@ -60,4 +60,4 @@ no `this` and survive any hand-off.
60
60
  | `bun test` | Run the test suite (vitest + @effect/vitest) |
61
61
  | `bun test:watch` | Run the test suite in watch mode |
62
62
  | `bunx tsc --noEmit` | Type check |
63
- | `bun lint` | Lint with oxlint |
63
+ | `bun lint` | Lint with oxlint |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ftrdotdev/pi-tui",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "House TUI components and the pi interface extension: themed boxes, a pure box-frame model, and the header/footer/editor/settings/preview chrome",
5
5
  "keywords": [
6
6
  "components",
@@ -50,17 +50,17 @@
50
50
  "lint": "oxlint && oxlint --type-aware -A all -D typescript/unbound-method",
51
51
  "lint:fix": "oxlint --fix",
52
52
  "fmt": "oxfmt",
53
- "prepare": "bun effect-tsgo patch --typescript --oxlint",
54
53
  "typecheck": "tsc --noEmit"
55
54
  },
56
55
  "dependencies": {
57
- "@effect/platform-node": "4.0.0-rc.116",
58
- "@effect/platform-node-shared": "4.0.0-rc.116",
59
- "effect": "4.0.0-rc.116"
56
+ "@effect/platform-node": "4.0.0",
57
+ "@effect/platform-node-shared": "4.0.0",
58
+ "effect": "4.0.0"
60
59
  },
61
60
  "devDependencies": {
62
- "@effect/tsgo": "0.45.0",
63
- "@effect/vitest": "4.0.0-rc.116",
61
+ "@earendil-works/pi-tui": "1.0.2",
62
+ "@effect/tsgo": "0.47.2",
63
+ "@effect/vitest": "4.0.0",
64
64
  "@types/bun": "latest",
65
65
  "oxfmt": "^0.63.0",
66
66
  "oxlint": "1.82.0",
@@ -144,7 +144,10 @@ it("keeps inference plus tool plus wait at or below total active time at every i
144
144
  assert.deepStrictEqual(observed, expected);
145
145
  for (const b of observed) {
146
146
  assert.ok(b.inference + b.tool + b.wait <= b.total);
147
- assert.strictEqual(b.inference + b.tool + b.wait, b.total - (b.total - b.inference - b.tool - b.wait));
147
+ assert.strictEqual(
148
+ b.inference + b.tool + b.wait,
149
+ b.total - (b.total - b.inference - b.tool - b.wait),
150
+ );
148
151
  }
149
152
  });
150
153
 
@@ -235,20 +238,18 @@ it("parity: waitingMs reports the open wait span and 0 when no prompt is open",
235
238
 
236
239
  it("toTrackerEvent maps pi message roles and tool calls onto tracker descriptors", () => {
237
240
  // Assistant message_start opens an inference span.
238
- assert.deepStrictEqual(
239
- toTrackerEvent({ kind: "message_start", role: "assistant", now: 1000 }),
240
- { type: "message_start", role: "assistant", now: 1000 },
241
- );
241
+ assert.deepStrictEqual(toTrackerEvent({ kind: "message_start", role: "assistant", now: 1000 }), {
242
+ type: "message_start",
243
+ role: "assistant",
244
+ now: 1000,
245
+ });
242
246
  // toolResult message_end never maps to an assistant span.
243
247
  assert.strictEqual(
244
248
  toTrackerEvent({ kind: "message_end", role: "toolResult", now: 2000 }),
245
249
  undefined,
246
250
  );
247
251
  // User messages never map either.
248
- assert.strictEqual(
249
- toTrackerEvent({ kind: "message_start", role: "user", now: 2000 }),
250
- undefined,
251
- );
252
+ assert.strictEqual(toTrackerEvent({ kind: "message_start", role: "user", now: 2000 }), undefined);
252
253
  // Tool executions carry their call id through.
253
254
  assert.deepStrictEqual(
254
255
  toTrackerEvent({ kind: "tool_execution_start", toolCallId: "call_1", now: 3000 }),
@@ -278,4 +279,4 @@ it("toTrackerEvent feeds the tracker a live inference/tool script", () => {
278
279
  const breakdown = tracker.breakdown(6000);
279
280
  // tool 2000..4000 = 2s; inference 1000..2000 + 4000..5000 = 2s.
280
281
  assert.deepStrictEqual(breakdown, { inference: 2000, tool: 2000, wait: 0, total: 5000 });
281
- });
282
+ });
package/src/activity.ts CHANGED
@@ -271,4 +271,4 @@ export function toTrackerEvent(source: TrackerEventSource): ActivityEvent | unde
271
271
  callId: source.toolCallId,
272
272
  now: source.now,
273
273
  };
274
- }
274
+ }
@@ -1,5 +1,6 @@
1
+ // @effect-diagnostics unstableApiUsage:off
1
2
  import { Context, Duration, Effect, Layer, Schema, Stream, PlatformError } from "effect";
2
- import * as CP from "effect/unstable/process";
3
+ import * as CP from "effect/process";
3
4
 
4
5
  /** Fixed per-invocation time cap applied to every git command (2 seconds). */
5
6
  export const GIT_EXECUTION_CAP: Duration.Duration = Duration.seconds(2);
@@ -14,6 +14,7 @@ const plainTheme = {
14
14
  fg: (_color: string, text: string) => text,
15
15
  bg: (_color: string, text: string) => text,
16
16
  bold: (text: string) => text,
17
+ style: (text: string) => text,
17
18
  } as unknown as Theme;
18
19
 
19
20
  // Marker theme for color and background assertions.
@@ -21,6 +22,12 @@ const markerTheme = {
21
22
  fg: (color: string, text: string) => `<${color}>${text}</${color}>`,
22
23
  bg: (color: string, text: string) => `[${color}]${text}[/${color}]`,
23
24
  bold: (text: string) => text,
25
+ style: (text: string, options: { fg?: string; bg?: string }) => {
26
+ let out = text;
27
+ if (options.fg) out = `<${options.fg}>${out}</${options.fg}>`;
28
+ if (options.bg) out = `[${options.bg}]${out}[/${options.bg}]`;
29
+ return out;
30
+ },
24
31
  } as unknown as Theme;
25
32
 
26
33
  it("renders top and bottom borders with the content rail-wrapped between them", () => {
@@ -48,9 +55,8 @@ it("truncates long body lines to the content width", () => {
48
55
  assert.deepStrictEqual(out, ["╭──────╮", "│ abcd\x1b[0m │", "╰──────╯"]);
49
56
  });
50
57
 
51
- it("applies the background function to every rendered line", () => {
52
- const bg = (s: string) => `[customMessageBg]${s}[/customMessageBg]`;
53
- const out = makeBorderedBox(lines(["hi"]), markerTheme, { bg }).render(12);
58
+ it("applies the background token to every rendered line", () => {
59
+ const out = makeBorderedBox(lines(["hi"]), markerTheme, { bg: "customMessageBg" }).render(12);
54
60
  assert.strictEqual(out.length, 3);
55
61
  for (const line of out) {
56
62
  assert.strictEqual(line.startsWith("[customMessageBg]"), true);
@@ -1,5 +1,5 @@
1
- import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
2
- import type { Component } from "@earendil-works/pi-tui";
1
+ import type { Theme, ThemeBg, ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import type { Color, Component } from "@earendil-works/pi-tui";
3
3
  import { composeBorderLine, buildBoxFrame } from "../frame/box-frame.ts";
4
4
  import { padRight, visibleWidth } from "../utils.ts";
5
5
  import { defineComponent } from "./define-component.ts";
@@ -12,16 +12,19 @@ export interface BorderedBoxOptions {
12
12
  * follow theme changes. When the box is too narrow the label is omitted.
13
13
  */
14
14
  readonly label?: string | ((theme: Theme) => string);
15
- /** Border color token. Defaults to "accent". */
16
- readonly color?: ThemeColor;
15
+ /** Border color: a theme token, or a concrete derived `Color`. Defaults to "accent". */
16
+ readonly color?: ThemeColor | Color;
17
17
  /**
18
18
  * Decorative dash run after the label. Defaults to " ─────". Pass a
19
19
  * different tail (e.g. a single space for a scroll hint) when the label
20
20
  * should not trail with the full dash run.
21
21
  */
22
22
  readonly labelSuffix?: string;
23
- /** Background function applied to every rendered line. */
24
- readonly bg?: (s: string) => string;
23
+ /**
24
+ * Background token applied to every rendered line, including the embedded
25
+ * label. Painted through `theme.style()`, not a caller-supplied wrapper.
26
+ */
27
+ readonly bg?: ThemeBg;
25
28
  /** Horizontal padding between the rails and the content. Defaults to 1. */
26
29
  readonly paddingX?: number;
27
30
  /**
@@ -69,8 +72,15 @@ export const makeBorderedBox = (
69
72
  });
70
73
  if (!frame) return [];
71
74
 
72
- const paint = (s: string) => theme.fg(options.color ?? "accent", s);
73
- const bg = options.bg ?? ((s: string) => s);
75
+ // Border chrome carries the foreground token and the background in one
76
+ // `theme.style()` call. Body content styles itself, so it only needs the
77
+ // background wrapper; the wrapper also covers the embedded label, which
78
+ // `composeBorderLine` passes through raw (already pre-themed by callers).
79
+ const paint = (s: string) => theme.style(s, { fg: options.color ?? "accent", bg: options.bg });
80
+ const bg =
81
+ options.bg === undefined
82
+ ? (s: string) => s
83
+ : (s: string) => theme.style(s, { bg: options.bg });
74
84
  const pad = frame.padLeft;
75
85
 
76
86
  const top = bg(composeBorderLine(frame, "top", paint));
@@ -25,6 +25,9 @@ export {
25
25
  type BoxTopBorder,
26
26
  } from "../frame/box-frame.ts";
27
27
  export { VimRouter, type NavigationIntent } from "../vim/vim-router.ts";
28
+ // Derived theme colors: mix concrete token colors when a component needs a
29
+ // shade that is not a theme token.
30
+ export { emphasize, isDark, mixThemeTokens, recede } from "../ui/theme-color.ts";
28
31
  // Editor customization: a generic Effect service other extensions can import
29
32
  // and `.configure` to inject/override the editor's border tint.
30
33
  export {
@@ -1,13 +1,18 @@
1
1
  import { assert, it } from "@effect/vitest";
2
2
  import { Effect, PlatformError, Schema } from "effect";
3
3
  import * as FileSystem from "effect/FileSystem";
4
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
4
5
  import { join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
5
7
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
8
  import {
9
+ adjustKeepContextThreshold,
10
+ adjustMaxCandidates,
7
11
  applyDefaults,
8
12
  ConfigParseError,
9
13
  ConfigWriteError,
10
14
  DEFAULT_CONFIG,
15
+ decodeConfig,
11
16
  encodeConfig,
12
17
  getConfigPath,
13
18
  TuiConfig,
@@ -467,3 +472,129 @@ it("ConfigWriteError carries the expected tag", () => {
467
472
  assert.strictEqual(err._tag, "ConfigWriteError");
468
473
  assert.instanceOf(err, ConfigWriteError);
469
474
  });
475
+
476
+ // ---------------------------------------------------------------------------
477
+ // Smart compaction: shared with the tracker reader
478
+ // ---------------------------------------------------------------------------
479
+
480
+ const CONTRACT_FIXTURE = new URL(
481
+ "../../tracker/test-fixtures/tui-config.contract.json",
482
+ import.meta.url,
483
+ );
484
+
485
+ it.effect("the shared contract fixture decodes into the smart-compaction section", () =>
486
+ Effect.gen(function* () {
487
+ const fs = yield* FileSystem.FileSystem;
488
+ const raw = yield* fs.readFileString(fileURLToPath(CONTRACT_FIXTURE));
489
+ const config = applyDefaults(decodeConfig(raw));
490
+ assert.strictEqual(config.smartCompaction.enabled, true);
491
+ assert.strictEqual(config.smartCompaction.classifier, "typesafe/jev-latest");
492
+ assert.strictEqual(config.smartCompaction.keepContextThreshold, 0.5);
493
+ assert.strictEqual(config.smartCompaction.keepContextMinConfidence, 0.5);
494
+ assert.strictEqual(config.smartCompaction.maxCandidates, 8);
495
+ }).pipe(Effect.provide(NodeFileSystem.layer)),
496
+ );
497
+
498
+ it("a config file without the smart-compaction section applies the smart-compaction defaults", () => {
499
+ const config = applyDefaults({ enabled: false });
500
+ assert.deepStrictEqual(config.smartCompaction, {
501
+ enabled: true,
502
+ classifier: null,
503
+ keepContextThreshold: 0.5,
504
+ keepContextMinConfidence: 0.5,
505
+ maxCandidates: 8,
506
+ });
507
+ });
508
+
509
+ it("an encoded default config carries all smart-compaction keys", () => {
510
+ const encoded = JSON.parse(encodeConfig(DEFAULT_CONFIG)) as {
511
+ smartCompaction: unknown;
512
+ };
513
+ assert.deepStrictEqual(encoded.smartCompaction, {
514
+ enabled: true,
515
+ classifier: null,
516
+ keepContextThreshold: 0.5,
517
+ keepContextMinConfidence: 0.5,
518
+ maxCandidates: 8,
519
+ });
520
+ });
521
+
522
+ it("a config file keeps a valid keep-context threshold", () => {
523
+ const config = applyDefaults({ smartCompaction: { keepContextThreshold: 0.72 } });
524
+ assert.strictEqual(config.smartCompaction.keepContextThreshold, 0.72);
525
+ });
526
+
527
+ it("an out-of-range keep-context threshold falls back to the default", () => {
528
+ for (const invalid of [0, 1, -0.1, 1.5]) {
529
+ const config = applyDefaults({ smartCompaction: { keepContextThreshold: invalid } });
530
+ assert.strictEqual(config.smartCompaction.keepContextThreshold, 0.5);
531
+ }
532
+ });
533
+
534
+ it("a config file keeps a valid keep-context min confidence", () => {
535
+ const config = applyDefaults({ smartCompaction: { keepContextMinConfidence: 0.72 } });
536
+ assert.strictEqual(config.smartCompaction.keepContextMinConfidence, 0.72);
537
+ });
538
+
539
+ it("an out-of-range keep-context min confidence falls back to the default", () => {
540
+ for (const invalid of [0, 1, -0.1, 1.5]) {
541
+ const config = applyDefaults({ smartCompaction: { keepContextMinConfidence: invalid } });
542
+ assert.strictEqual(config.smartCompaction.keepContextMinConfidence, 0.5);
543
+ }
544
+ });
545
+
546
+ it("adjustKeepContextThreshold steps by 0.05 and clamps inside the open interval", () => {
547
+ assert.strictEqual(adjustKeepContextThreshold(0.5, 0.05), 0.55);
548
+ assert.strictEqual(adjustKeepContextThreshold(0.5, -0.05), 0.45);
549
+ assert.strictEqual(adjustKeepContextThreshold(0.95, 0.05), 0.95);
550
+ assert.strictEqual(adjustKeepContextThreshold(0.05, -0.05), 0.05);
551
+ });
552
+
553
+ it("a config file keeps a valid max-candidates cap", () => {
554
+ const config = applyDefaults({ smartCompaction: { maxCandidates: 3 } });
555
+ assert.strictEqual(config.smartCompaction.maxCandidates, 3);
556
+ });
557
+
558
+ it("a cap that is not an integer in range falls back to the default", () => {
559
+ for (const invalid of [0, 21, 5.5, -1]) {
560
+ const config = applyDefaults({ smartCompaction: { maxCandidates: invalid } });
561
+ assert.strictEqual(config.smartCompaction.maxCandidates, 8);
562
+ }
563
+ });
564
+
565
+ it("adjustMaxCandidates steps by one and clamps to the bounds", () => {
566
+ assert.strictEqual(adjustMaxCandidates(8, 1), 9);
567
+ assert.strictEqual(adjustMaxCandidates(8, -1), 7);
568
+ assert.strictEqual(adjustMaxCandidates(20, 1), 20);
569
+ assert.strictEqual(adjustMaxCandidates(1, -1), 1);
570
+ });
571
+
572
+ it.effect("save keeps a chosen classifier through a load round trip", () =>
573
+ Effect.gen(function* () {
574
+ const mem = makeMemFs();
575
+ const config = yield* runWithMem(
576
+ mem,
577
+ Effect.gen(function* () {
578
+ const svc = yield* TuiConfigService;
579
+ yield* svc.save({
580
+ ...DEFAULT_CONFIG,
581
+ smartCompaction: {
582
+ enabled: false,
583
+ classifier: "typesafe/jev-latest",
584
+ keepContextThreshold: 0.8,
585
+ keepContextMinConfidence: 0.8,
586
+ maxCandidates: 3,
587
+ },
588
+ });
589
+ return yield* svc.load;
590
+ }),
591
+ );
592
+ assert.deepStrictEqual(config.smartCompaction, {
593
+ enabled: false,
594
+ classifier: "typesafe/jev-latest",
595
+ keepContextThreshold: 0.8,
596
+ keepContextMinConfidence: 0.8,
597
+ maxCandidates: 3,
598
+ });
599
+ }),
600
+ );
package/src/config.ts CHANGED
@@ -37,6 +37,13 @@ export class TuiConfig extends Schema.Class<TuiConfig>("tui/config/TuiConfig")({
37
37
  stalls: Schema.Boolean,
38
38
  cost: Schema.Boolean,
39
39
  }),
40
+ smartCompaction: Schema.Struct({
41
+ enabled: Schema.Boolean,
42
+ classifier: Schema.NullOr(Schema.String),
43
+ keepContextThreshold: Schema.Number,
44
+ keepContextMinConfidence: Schema.Number,
45
+ maxCandidates: Schema.Number,
46
+ }),
40
47
  }) {}
41
48
 
42
49
  export type TelemetryConfig = TuiConfig["telemetry"];
@@ -66,8 +73,56 @@ export const DEFAULT_CONFIG: TuiConfig = {
66
73
  stalls: true,
67
74
  cost: true,
68
75
  },
76
+ smartCompaction: {
77
+ enabled: true,
78
+ classifier: null,
79
+ keepContextThreshold: 0.5,
80
+ keepContextMinConfidence: 0.5,
81
+ maxCandidates: 8,
82
+ },
83
+ };
84
+
85
+ /**
86
+ * Step and bounds for the settings dialog's threshold editor. The value must
87
+ * stay strictly inside (0, 1); the dialog clamps to this open interval so a
88
+ * user cannot write a value the tracker would reject.
89
+ */
90
+ export const KEEP_CONTEXT_THRESHOLD_STEP = 0.05;
91
+ export const KEEP_CONTEXT_THRESHOLD_MIN = 0.05;
92
+ export const KEEP_CONTEXT_THRESHOLD_MAX = 0.95;
93
+
94
+ /** True when `value` is a usable keep-context threshold: strictly inside (0, 1). */
95
+ export const isKeepContextThreshold = (value: number): boolean => value > 0 && value < 1;
96
+
97
+ /**
98
+ * True when `value` is a usable confidence floor: strictly inside (0, 1). The
99
+ * tracker applies the same open-interval rule to both knobs.
100
+ */
101
+ export const isKeepContextMinConfidence = isKeepContextThreshold;
102
+
103
+ /** Nudge a threshold by `delta`, rounded to two decimals and kept inside the bounds. */
104
+ export const adjustKeepContextThreshold = (value: number, delta: number): number => {
105
+ const next = Math.round((value + delta) * 100) / 100;
106
+ return Math.min(KEEP_CONTEXT_THRESHOLD_MAX, Math.max(KEEP_CONTEXT_THRESHOLD_MIN, next));
69
107
  };
70
108
 
109
+ /**
110
+ * Step and bounds for the settings dialog's max-candidates editor. The tracker
111
+ * accepts an integer in [1, 20]; the dialog clamps to this interval.
112
+ */
113
+ export const MAX_CANDIDATES_STEP = 1;
114
+ export const MAX_CANDIDATES_MIN = 1;
115
+ export const MAX_CANDIDATES_MAX = 20;
116
+ export const DEFAULT_MAX_CANDIDATES = 8;
117
+
118
+ /** True when `value` is a usable cap: an integer in [1, 20]. */
119
+ export const isMaxCandidates = (value: number): boolean =>
120
+ Number.isInteger(value) && value >= MAX_CANDIDATES_MIN && value <= MAX_CANDIDATES_MAX;
121
+
122
+ /** Nudge a cap by `delta`, clamped to the bounds. */
123
+ export const adjustMaxCandidates = (value: number, delta: number): number =>
124
+ Math.min(MAX_CANDIDATES_MAX, Math.max(MAX_CANDIDATES_MIN, Math.round(value + delta)));
125
+
71
126
  export function getConfigPath(): string {
72
127
  return join(getAgentDir(), CONFIG_FILE_NAME);
73
128
  }
@@ -109,6 +164,15 @@ const FileSchema = Schema.fromJsonString(
109
164
  cost: OptionalBoolean,
110
165
  }),
111
166
  ),
167
+ smartCompaction: Schema.optional(
168
+ Schema.Struct({
169
+ enabled: OptionalBoolean,
170
+ classifier: Schema.optional(Schema.NullOr(Schema.String)),
171
+ keepContextThreshold: Schema.optional(Schema.Finite),
172
+ keepContextMinConfidence: Schema.optional(Schema.Finite),
173
+ maxCandidates: Schema.optional(Schema.Int),
174
+ }),
175
+ ),
112
176
  }),
113
177
  { space: 2 },
114
178
  );
@@ -150,6 +214,25 @@ export function applyDefaults(partial: TuiConfigFile): TuiConfig {
150
214
  stalls: partial.telemetry?.stalls ?? DEFAULT_CONFIG.telemetry.stalls,
151
215
  cost: partial.telemetry?.cost ?? DEFAULT_CONFIG.telemetry.cost,
152
216
  },
217
+ smartCompaction: {
218
+ enabled: partial.smartCompaction?.enabled ?? DEFAULT_CONFIG.smartCompaction.enabled,
219
+ classifier: partial.smartCompaction?.classifier ?? DEFAULT_CONFIG.smartCompaction.classifier,
220
+ keepContextThreshold:
221
+ partial.smartCompaction?.keepContextThreshold !== undefined &&
222
+ isKeepContextThreshold(partial.smartCompaction.keepContextThreshold)
223
+ ? partial.smartCompaction.keepContextThreshold
224
+ : DEFAULT_CONFIG.smartCompaction.keepContextThreshold,
225
+ keepContextMinConfidence:
226
+ partial.smartCompaction?.keepContextMinConfidence !== undefined &&
227
+ isKeepContextMinConfidence(partial.smartCompaction.keepContextMinConfidence)
228
+ ? partial.smartCompaction.keepContextMinConfidence
229
+ : DEFAULT_CONFIG.smartCompaction.keepContextMinConfidence,
230
+ maxCandidates:
231
+ partial.smartCompaction?.maxCandidates !== undefined &&
232
+ isMaxCandidates(partial.smartCompaction.maxCandidates)
233
+ ? partial.smartCompaction.maxCandidates
234
+ : DEFAULT_CONFIG.smartCompaction.maxCandidates,
235
+ },
153
236
  };
154
237
  }
155
238
 
@@ -259,48 +342,3 @@ export class TuiConfigService extends Context.Service<
259
342
  ): Layer.Layer<TuiConfigService> =>
260
343
  TuiConfigService.make(path).pipe(Layer.provide(FileSystem.layerNoop(fileSystem)));
261
344
  }
262
-
263
- // // ------------------------------------------------------------------
264
- // // Temporary imperative wrappers for backwards compatibility.
265
- // // TODO: remove these once src/index.ts is wired to TuiConfigService.
266
- // // ------------------------------------------------------------------
267
- //
268
- // export function ensureConfigExists(): void {
269
- // const path = getConfigPath();
270
- // if (existsSync(path)) return;
271
- // try {
272
- // const agentDir = getAgentDir();
273
- // if (!existsSync(agentDir)) mkdirSync(agentDir, { recursive: true });
274
- // writeFileSync(path, JSON.stringify(DEFAULT_CONFIG, null, 2) + "\n", "utf8");
275
- // } catch {}
276
- // }
277
- //
278
- // export function loadConfig(notify?: (msg: string, level: "warning" | "info") => void): TuiConfig {
279
- // const path = getConfigPath();
280
- // if (!existsSync(path)) {
281
- // ensureConfigExists();
282
- // return applyDefaults({});
283
- // }
284
- //
285
- // try {
286
- // const raw = readFileSync(path, "utf8");
287
- // const parsed: unknown = JSON.parse(raw);
288
- // const partial = Schema.decodeUnknownSync(FileSchema, { onExcessProperty: "ignore" })(parsed);
289
- // return applyDefaults(partial);
290
- // } catch (err) {
291
- // notify?.(
292
- // `tui config parse error: ${err instanceof Error ? err.message : String(err)}`,
293
- // "warning",
294
- // );
295
- // return applyDefaults({});
296
- // }
297
- // }
298
- //
299
- // export function saveConfig(config: TuiConfig): void {
300
- // const path = getConfigPath();
301
- // try {
302
- // const agentDir = getAgentDir();
303
- // if (!existsSync(agentDir)) mkdirSync(agentDir, { recursive: true });
304
- // writeFileSync(path, JSON.stringify(config, null, 2) + "\n", "utf8");
305
- // } catch {}
306
- // }
package/src/index.ts CHANGED
@@ -27,32 +27,6 @@ import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcess
27
27
  import { VimRouter } from "./vim/vim-router.ts";
28
28
  import { EditorTintService } from "./ui/editor-tint.ts";
29
29
 
30
- function isInteractiveLaunch(): boolean {
31
- if (!process.stdout.isTTY) return false;
32
- const args = process.argv.slice(2);
33
- const nonInteractiveFlags = [
34
- "-p",
35
- "--print",
36
- "--help",
37
- "-h",
38
- "--version",
39
- "-v",
40
- "--list-models",
41
- "--export",
42
- ];
43
- for (const arg of args) {
44
- if (nonInteractiveFlags.includes(arg)) return false;
45
- if (arg.startsWith("--mode")) return false;
46
- }
47
- return true;
48
- }
49
-
50
- function clearVisibleScreen(): void {
51
- if (process.stdout.isTTY) {
52
- process.stdout.write("\x1b[2J\x1b[H");
53
- }
54
- }
55
-
56
30
  function isTuiContext(ctx: ExtensionContext): boolean {
57
31
  try {
58
32
  const mode = (ctx as ExtensionContext & { mode?: string }).mode;
@@ -79,7 +53,6 @@ const main = Effect.fn("tui/main")(function* (pi: ExtensionAPI) {
79
53
  let lastCtx: ExtensionContext | undefined;
80
54
  let requestFooterRender: (() => void) | undefined;
81
55
  let workingTimer: ReturnType<typeof setInterval> | undefined;
82
- // TODO: configure
83
56
  let cleanupHeader: (() => void) | undefined;
84
57
  let cleanupFooter: (() => void) | undefined;
85
58
  let cleanupEditor: (() => void) | undefined;
@@ -183,7 +156,10 @@ const main = Effect.fn("tui/main")(function* (pi: ExtensionAPI) {
183
156
  requestFooterRender?.();
184
157
  };
185
158
  tick();
186
- workingTimer = setInterval(tick, 250);
159
+ // The footer timer renders whole seconds (`formatDuration`), so a 1s
160
+ // cadence keeps the display exact and avoids 3 wasted full-layout
161
+ // re-renders per second.
162
+ workingTimer = setInterval(tick, 1000);
187
163
  workingTimer.unref?.();
188
164
  };
189
165
 
@@ -206,10 +182,6 @@ const main = Effect.fn("tui/main")(function* (pi: ExtensionAPI) {
206
182
 
207
183
  config = yield* conf.load.pipe(Effect.mapError((e) => ctx.ui.notify(e.message, "error")));
208
184
 
209
- if (isInteractiveLaunch() && config.enabled) {
210
- clearVisibleScreen();
211
- }
212
-
213
185
  applyUi(ctx);
214
186
 
215
187
  refreshInteractiveState(ctx, true);
@@ -0,0 +1,87 @@
1
+ import { afterEach, assert, it } from "@effect/vitest";
2
+ import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { readRuntimeInfo } from "./runtime.ts";
6
+
7
+ // Env-based runtimes (no marker file) would leak the host environment into
8
+ // the "no marker matches" case, so that test clears them.
9
+ const ENV_KEYS = [
10
+ "MESON_DEVENV",
11
+ "IN_NIX_SHELL",
12
+ "GUIX_ENVIRONMENT",
13
+ "CONDA_DEFAULT_ENV",
14
+ "PIXI_ENVIRONMENT_NAME",
15
+ "SPACK_ENV",
16
+ ] as const;
17
+
18
+ const dirs: string[] = [];
19
+
20
+ function tempDir(): string {
21
+ const dir = mkdtempSync(join(tmpdir(), "pi-tui-runtime-"));
22
+ dirs.push(dir);
23
+ return dir;
24
+ }
25
+
26
+ afterEach(() => {
27
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
28
+ });
29
+
30
+ it("returns every matching runtime in table order", async () => {
31
+ const dir = tempDir();
32
+ writeFileSync(join(dir, "CMakeLists.txt"), "");
33
+ const runtimes = await readRuntimeInfo(dir);
34
+ assert.deepStrictEqual(
35
+ runtimes.map((r) => r.name),
36
+ ["cpp", "c", "cmake"],
37
+ );
38
+ });
39
+
40
+ it("returns an empty list when no marker matches", async () => {
41
+ const dir = tempDir();
42
+ const saved = ENV_KEYS.map((key) => [key, process.env[key]] as const);
43
+ for (const key of ENV_KEYS) delete process.env[key];
44
+ try {
45
+ assert.deepStrictEqual(await readRuntimeInfo(dir), []);
46
+ } finally {
47
+ for (const [key, value] of saved) {
48
+ if (value === undefined) delete process.env[key];
49
+ else process.env[key] = value;
50
+ }
51
+ }
52
+ });
53
+
54
+ it("matches env-based runtimes without a marker file", async () => {
55
+ const dir = tempDir();
56
+ const key = "CONDA_DEFAULT_ENV";
57
+ const previous = process.env[key];
58
+ process.env[key] = "pi-tui-test";
59
+ try {
60
+ const runtimes = await readRuntimeInfo(dir);
61
+ assert.deepStrictEqual(
62
+ runtimes.map((r) => r.name),
63
+ ["conda"],
64
+ );
65
+ } finally {
66
+ if (previous === undefined) delete process.env[key];
67
+ else process.env[key] = previous;
68
+ }
69
+ });
70
+
71
+ it("reuses the cached entry until the marker fingerprint changes", async () => {
72
+ const dir = tempDir();
73
+ const marker = join(dir, "settings.gradle.kts");
74
+ writeFileSync(marker, "");
75
+ const first = await readRuntimeInfo(dir);
76
+ const second = await readRuntimeInfo(dir);
77
+ // A cache hit returns the same object, not a rebuilt one.
78
+ assert.strictEqual(first[0], second[0]);
79
+ assert.strictEqual(first[0]?.name, "kotlin");
80
+
81
+ // Touching the marker changes the fingerprint, so the next read rebuilds.
82
+ const future = new Date(Date.now() + 60_000);
83
+ utimesSync(marker, future, future);
84
+ const third = await readRuntimeInfo(dir);
85
+ assert.notStrictEqual(third[0], first[0]);
86
+ assert.strictEqual(third[0]?.name, "kotlin");
87
+ });