@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
@@ -0,0 +1,230 @@
1
+ // Each test is its own entry point: it builds a fresh layer for one scenario and
2
+ // runs its effects inside it, so providing there is the pattern the rule allows.
3
+ /* oxlint-disable effecttsgo/strict-effect-provide */
4
+ import { assert, beforeEach, it } from "@effect/vitest";
5
+ import { themeDouble } from "@ftrdotdev/pi-test-kit";
6
+ import { Effect } from "effect";
7
+ import { footerCtxDouble } from "../test-support/doubles.ts";
8
+ import type { SessionEntry, UsageTotals } from "./state.ts";
9
+ import { getUsageTotals, invalidateUsageCache } from "./state.ts";
10
+ import { UsageTotalsService } from "./usage-totals-service.ts";
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // UsageTotalsService — the usage cache as service state, keyed by the session
14
+ // generation. The plain adapter (getUsageTotals) stays as the parity oracle
15
+ // for plan 1's provider (D13).
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /** pi's session entries carry more fields than the fold reads; one documented cast. */
19
+ const entry = (value: unknown): SessionEntry => value as SessionEntry;
20
+
21
+ interface ScriptedUsage {
22
+ input: number;
23
+ output: number;
24
+ cacheRead: number;
25
+ cacheWrite: number;
26
+ cost: number;
27
+ }
28
+
29
+ const assistant = (id: string, usage: ScriptedUsage): SessionEntry =>
30
+ entry({
31
+ type: "message",
32
+ id,
33
+ parentId: null,
34
+ timestamp: `t-${id}`,
35
+ message: {
36
+ role: "assistant",
37
+ content: [],
38
+ usage: {
39
+ input: usage.input,
40
+ output: usage.output,
41
+ cacheRead: usage.cacheRead,
42
+ cacheWrite: usage.cacheWrite,
43
+ totalTokens: usage.input + usage.output + usage.cacheRead + usage.cacheWrite,
44
+ cost: { total: usage.cost },
45
+ },
46
+ },
47
+ });
48
+
49
+ const user = (id: string): SessionEntry =>
50
+ entry({
51
+ type: "message",
52
+ id,
53
+ parentId: null,
54
+ timestamp: `t-${id}`,
55
+ message: { role: "user", content: [] },
56
+ });
57
+
58
+ const EXPECTED: UsageTotals = {
59
+ input: 150,
60
+ output: 50,
61
+ cacheRead: 30,
62
+ cacheWrite: 20,
63
+ cost: 0.03,
64
+ latestCacheHitRate: 30,
65
+ };
66
+
67
+ const fixture = () => [
68
+ assistant("a1", { input: 100, output: 40, cacheRead: 0, cacheWrite: 0, cost: 0.01 }),
69
+ user("u1"),
70
+ assistant("a2", { input: 50, output: 10, cacheRead: 30, cacheWrite: 20, cost: 0.02 }),
71
+ ];
72
+
73
+ const serviceOver = (getEntries: () => readonly SessionEntry[], getGeneration: () => number) =>
74
+ Effect.service(UsageTotalsService).pipe(
75
+ Effect.provide(UsageTotalsService.layerTest(getEntries, getGeneration)),
76
+ );
77
+
78
+ const ctxOver = (entries: () => readonly SessionEntry[]) =>
79
+ footerCtxDouble({
80
+ model: {},
81
+ cwd: "/workspace/pi-mono",
82
+ getContextUsage: () => undefined,
83
+ sessionManager: { getEntries: entries },
84
+ ui: { theme: themeDouble() },
85
+ });
86
+
87
+ // The plain adapter's slot is module-level; every test starts empty.
88
+ beforeEach(() => invalidateUsageCache());
89
+
90
+ it.effect("totals fold assistant usage and ignore other roles", () =>
91
+ Effect.gen(function* () {
92
+ // Arrange
93
+ const entries = fixture();
94
+ const svc = yield* serviceOver(
95
+ () => entries,
96
+ () => 1,
97
+ );
98
+
99
+ // Act/Assert: the user entry contributes nothing.
100
+ assert.deepStrictEqual(svc.totals(), EXPECTED);
101
+ }),
102
+ );
103
+
104
+ it.effect("a repeated read with the same entries returns the same object", () =>
105
+ Effect.gen(function* () {
106
+ // Arrange
107
+ const entries = fixture();
108
+ const svc = yield* serviceOver(
109
+ () => entries,
110
+ () => 1,
111
+ );
112
+
113
+ // Act
114
+ const first = svc.totals();
115
+ const second = svc.totals();
116
+
117
+ // Assert
118
+ assert.strictEqual(second, first);
119
+ }),
120
+ );
121
+
122
+ it.effect("invalidation re-folds the same entries into a new object with equal values", () =>
123
+ Effect.gen(function* () {
124
+ // Arrange
125
+ const entries = fixture();
126
+ const svc = yield* serviceOver(
127
+ () => entries,
128
+ () => 1,
129
+ );
130
+ const before = svc.totals();
131
+
132
+ // Act
133
+ svc.invalidate();
134
+ const after = svc.totals();
135
+
136
+ // Assert
137
+ assert.notStrictEqual(after, before);
138
+ assert.deepStrictEqual(after, before);
139
+ }),
140
+ );
141
+
142
+ it.effect("a changed entries list is re-folded without an explicit invalidate", () =>
143
+ Effect.gen(function* () {
144
+ // Arrange: two entries, then one more assistant message.
145
+ const entries = fixture();
146
+ const svc = yield* serviceOver(
147
+ () => entries,
148
+ () => 1,
149
+ );
150
+ svc.totals();
151
+
152
+ // Act
153
+ entries.push(
154
+ assistant("a3", { input: 5, output: 5, cacheRead: 0, cacheWrite: 0, cost: 0.005 }),
155
+ );
156
+ const totals = svc.totals();
157
+
158
+ // Assert: the third entry is included.
159
+ assert.deepStrictEqual(totals, {
160
+ input: 155,
161
+ output: 55,
162
+ cacheRead: 30,
163
+ cacheWrite: 20,
164
+ cost: 0.034999999999999996,
165
+ latestCacheHitRate: 0,
166
+ });
167
+ }),
168
+ );
169
+
170
+ it.effect("a generation change alone drops the cached fold (D4)", () =>
171
+ Effect.gen(function* () {
172
+ // Arrange: identical entries, a generation the test advances.
173
+ const entries = fixture();
174
+ let generation = 1;
175
+ const svc = yield* serviceOver(
176
+ () => entries,
177
+ () => generation,
178
+ );
179
+ const before = svc.totals();
180
+
181
+ // Act: no reset call, only the session generation changes.
182
+ generation = 2;
183
+ const after = svc.totals();
184
+
185
+ // Assert
186
+ assert.notStrictEqual(after, before);
187
+ assert.deepStrictEqual(after, before);
188
+ }),
189
+ );
190
+
191
+ it.effect("reset drops the cached fold for an identical entries list", () =>
192
+ Effect.gen(function* () {
193
+ // Arrange
194
+ const entries = fixture();
195
+ const svc = yield* serviceOver(
196
+ () => entries,
197
+ () => 1,
198
+ );
199
+ const before = svc.totals();
200
+
201
+ // Act
202
+ svc.reset();
203
+ const after = svc.totals();
204
+
205
+ // Assert
206
+ assert.notStrictEqual(after, before);
207
+ assert.deepStrictEqual(after, before);
208
+ }),
209
+ );
210
+
211
+ it.effect("the plain adapter and the service instance are independent", () =>
212
+ Effect.gen(function* () {
213
+ // Arrange: the same entries behind both caches.
214
+ const entries = fixture();
215
+ const svc = yield* serviceOver(
216
+ () => entries,
217
+ () => 1,
218
+ );
219
+ const ctx = ctxOver(() => entries);
220
+ const serviceTotals = svc.totals();
221
+ const adapterTotals = getUsageTotals(ctx);
222
+
223
+ // Act: clearing the adapter's slot leaves the service's fold alone.
224
+ invalidateUsageCache();
225
+
226
+ // Assert: the service holds its object, and both folds agree in value.
227
+ assert.strictEqual(svc.totals(), serviceTotals);
228
+ assert.deepStrictEqual(svc.totals(), adapterTotals);
229
+ }),
230
+ );
@@ -0,0 +1,59 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import { SessionLifecycleService } from "./session-lifecycle.ts";
3
+ import { createUsageCache, type SessionEntry, type UsageTotals } from "./state.ts";
4
+
5
+ /** The service body, independent of how the generation was supplied. */
6
+ const makeService = (
7
+ getEntries: () => readonly SessionEntry[],
8
+ getGeneration: () => number,
9
+ ): UsageTotalsService["Service"] => {
10
+ const cache = createUsageCache();
11
+ return UsageTotalsService.of({
12
+ totals: () => {
13
+ const entries = getEntries();
14
+ const last = entries.at(-1);
15
+ return cache.totals(
16
+ `${getGeneration()}:${entries.length}:${last?.id ?? ""}:${last?.timestamp ?? ""}`,
17
+ entries,
18
+ );
19
+ },
20
+ invalidate: cache.invalidate,
21
+ reset: cache.invalidate,
22
+ });
23
+ };
24
+
25
+ /**
26
+ * The usage cache as service state, keyed by the session generation so a new
27
+ * session can never be served the previous session's totals (D4). Every
28
+ * member is synchronous: the footer render reads `totals()` per frame.
29
+ */
30
+ export class UsageTotalsService extends Context.Service<
31
+ UsageTotalsService,
32
+ {
33
+ readonly totals: () => UsageTotals;
34
+ /** The three in-session invalidation triggers (message_end, session_compact, session_tree). */
35
+ readonly invalidate: () => void;
36
+ /** Session boundary (session_start only, D5): drop the cached fold. */
37
+ readonly reset: () => void;
38
+ }
39
+ >()("@ftrdotdev/pi-tui/usage-totals-service/UsageTotalsService") {
40
+ /** Production layer: the generation is the lifecycle counter, resolved as a dependency (D4). */
41
+ static layer(
42
+ getEntries: () => readonly SessionEntry[],
43
+ ): Layer.Layer<UsageTotalsService, never, SessionLifecycleService> {
44
+ return Layer.effect(
45
+ UsageTotalsService,
46
+ Effect.gen(function* () {
47
+ const lifecycle = yield* SessionLifecycleService;
48
+ return makeService(getEntries, () => lifecycle.currentGeneration());
49
+ }),
50
+ );
51
+ }
52
+
53
+ /** Test layer: both getters injected, no lifecycle requirement. */
54
+ static readonly layerTest = (
55
+ getEntries: () => readonly SessionEntry[],
56
+ getGeneration: () => number,
57
+ ): Layer.Layer<UsageTotalsService> =>
58
+ Layer.sync(UsageTotalsService, () => makeService(getEntries, getGeneration));
59
+ }
package/src/utils.test.ts CHANGED
@@ -1,14 +1,13 @@
1
- import { afterEach, assert, it } from "@effect/vitest";
2
- import type { Theme } from "@earendil-works/pi-coding-agent";
1
+ import { afterEach, assert, it, vi } from "@effect/vitest";
2
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
3
3
  import { mkdtempSync, rmSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join, sep } from "node:path";
6
+ import { pathArbitrary } from "../test-support/generators.ts";
6
7
  import {
7
- alignRight,
8
- cacheHitColor,
9
8
  center,
9
+ effortColor,
10
10
  findBottomBorderIndex,
11
- fitSegmentsByPriority,
12
11
  fmtTokens,
13
12
  formatCost,
14
13
  formatCwd,
@@ -23,17 +22,14 @@ import {
23
22
  stressColor,
24
23
  stripAnsi,
25
24
  truncatePath,
25
+ visibleWidth,
26
26
  } from "./utils.ts";
27
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
28
  const dirs: string[] = [];
36
29
 
30
+ /** The home the runner started with; a stub inside a test must not outlive it. */
31
+ const HOME_AT_MODULE_LOAD = process.env.HOME;
32
+
37
33
  afterEach(() => {
38
34
  for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
39
35
  });
@@ -41,21 +37,21 @@ afterEach(() => {
41
37
  it("stripAnsi removes SGR and OSC sequences", () => {
42
38
  assert.strictEqual(stripAnsi("\x1b[31mred\x1b[0m"), "red");
43
39
  assert.strictEqual(stripAnsi("a\x1b]0;title\x07b"), "ab");
40
+ // A non-SGR CSI sequence (erase line) must go too; the old regex kept it.
41
+ assert.strictEqual(stripAnsi("a\x1b[2Kb"), "ab");
44
42
  });
45
43
 
46
44
  it("formatCwd collapses paths inside HOME and leaves others literal", () => {
47
45
  const home = mkdtempSync(join(tmpdir(), "pi-tui-home-"));
48
46
  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
- }
47
+ vi.stubEnv("HOME", home);
48
+ assert.strictEqual(formatCwd(home), "~");
49
+ assert.strictEqual(formatCwd(join(home, "dev")), `~${sep}dev`);
50
+ assert.strictEqual(formatCwd("/etc"), "/etc");
51
+ });
52
+
53
+ it("the home override does not outlive the test that made it", () => {
54
+ assert.strictEqual(process.env.HOME, HOME_AT_MODULE_LOAD);
59
55
  });
60
56
 
61
57
  it("truncatePath keeps the first and trailing segments", () => {
@@ -64,6 +60,12 @@ it("truncatePath keeps the first and trailing segments", () => {
64
60
  assert.strictEqual(truncatePath("abcdefgh", 3), "...");
65
61
  });
66
62
 
63
+ it("truncatePath measures wide characters in columns", () => {
64
+ const result = truncatePath("~/界/界界界/界界", 10);
65
+ assert.isAtMost(visibleWidth(result), 10);
66
+ assert.ok(result.includes("..."));
67
+ });
68
+
67
69
  it("fmtTokens uses plain digits below 1k and scales above", () => {
68
70
  assert.strictEqual(fmtTokens(999), "999");
69
71
  assert.strictEqual(fmtTokens(1500), "1.5k");
@@ -95,47 +97,21 @@ it("model, provider, and thinking labels", () => {
95
97
  assert.strictEqual(formatProviderLabel("openai"), "Openai");
96
98
  assert.strictEqual(formatThinkingLabel("off"), "thinking off");
97
99
  assert.strictEqual(formatThinkingLabel("high"), "high effort");
100
+ assert.strictEqual(effortColor("max"), "thinkingXhigh");
98
101
  });
99
102
 
100
103
  it("threshold colors map to the expected tokens", () => {
101
104
  assert.strictEqual(stressColor(50), "accent");
102
105
  assert.strictEqual(stressColor(70), "warning");
103
106
  assert.strictEqual(stressColor(95), "error");
104
- assert.strictEqual(cacheHitColor(10), "error");
105
- assert.strictEqual(cacheHitColor(50), "warning");
106
- assert.strictEqual(cacheHitColor(80), "success");
107
107
  assert.strictEqual(providerColor("anthropic"), "accent");
108
108
  assert.strictEqual(providerColor("openai"), "success");
109
109
  assert.strictEqual(providerColor("mystery"), "muted");
110
110
  });
111
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
112
  it("padRight and center produce the expected columns", () => {
138
113
  assert.strictEqual(padRight("ab", 5), "ab ");
114
+ assert.strictEqual(visibleWidth(padRight("界", 4)), 4);
139
115
  assert.strictEqual(center("ab", 6), " ab");
140
116
  });
141
117
 
@@ -150,3 +126,23 @@ it("editor border detection and bottom-border lookup", () => {
150
126
  assert.strictEqual(findBottomBorderIndex(["a", "─", "b"]), 1);
151
127
  assert.strictEqual(findBottomBorderIndex(["a", "b"]), 1);
152
128
  });
129
+
130
+ it.prop(
131
+ "truncatePath never exceeds the requested width",
132
+ { path: pathArbitrary },
133
+ ({ path }) => {
134
+ assert.isAtMost(visibleWidth(truncatePath(path.path, path.maxLen)), path.maxLen);
135
+ },
136
+ { arbitrary: { runs: PROPERTY_RUNS } },
137
+ );
138
+
139
+ it.prop(
140
+ "truncatePath invents no character",
141
+ { path: pathArbitrary },
142
+ ({ path }) => {
143
+ for (const character of truncatePath(path.path, path.maxLen)) {
144
+ assert(character === "." || path.path.includes(character));
145
+ }
146
+ },
147
+ { arbitrary: { runs: PROPERTY_RUNS } },
148
+ );