@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/layers.ts ADDED
@@ -0,0 +1,92 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Layer } from "effect";
3
+ import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
4
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
5
+ import * as NodePath from "@effect/platform-node/NodePath";
6
+ import { ActivityService } from "./activity.ts";
7
+ import { GitExecutionService } from "./commands/git-execution.ts";
8
+ import { GitStatusService } from "./commands/git-status.ts";
9
+ import { TuiConfigService } from "./config.ts";
10
+ import { SessionLifecycleService } from "./session-lifecycle.ts";
11
+ import { createInitialState, type FooterState } from "./state.ts";
12
+ import { TurnTelemetryService } from "./telemetry.ts";
13
+ import { RuntimeInfoService } from "./runtime-service.ts";
14
+ import { UsageTotalsService } from "./usage-totals-service.ts";
15
+ import { EditorTintService } from "./ui/editor-tint.ts";
16
+ import { PreviewService } from "./ui/preview.ts";
17
+
18
+ /**
19
+ * The one per-program composition point. `main` reads the live session state
20
+ * and context through this host; every stateful service is provided around
21
+ * `main` from the same layer graph, so two consumers of a tag share one
22
+ * instance.
23
+ */
24
+ export interface TuiSessionHost {
25
+ readonly state: FooterState;
26
+ ctx: ExtensionContext | undefined;
27
+ }
28
+
29
+ export const createTuiSessionHost = (): TuiSessionHost => ({
30
+ state: createInitialState(),
31
+ ctx: undefined,
32
+ });
33
+
34
+ /** Every service the tui extension provides. */
35
+ export type TuiServices =
36
+ | TuiConfigService
37
+ | EditorTintService
38
+ | PreviewService
39
+ | GitExecutionService
40
+ | GitStatusService
41
+ | SessionLifecycleService
42
+ | ActivityService
43
+ | TurnTelemetryService
44
+ | UsageTotalsService
45
+ | RuntimeInfoService;
46
+
47
+ /**
48
+ * The two platform primitives with no Effect service in 4.1, read once at the
49
+ * entry point (the `preview.ts` rule): the home directory for `~` expansion,
50
+ * and a live environment read (`ConfigProvider.fromEnv()` snapshots at
51
+ * construction, so it would not see a later change).
52
+ */
53
+ export interface TuiPlatform {
54
+ readonly homeDir: string;
55
+ readonly getEnv: (name: string) => string | undefined;
56
+ }
57
+
58
+ /** One lifecycle instance per build; every layer that yields it shares this value (D4). */
59
+ const sessionLayer = SessionLifecycleService.layer;
60
+
61
+ export const tuiServicesLayer = (
62
+ host: TuiSessionHost,
63
+ platform: TuiPlatform,
64
+ ): Layer.Layer<TuiServices> => {
65
+ const nodeLayer = NodeChildProcessSpawner.layer.pipe(
66
+ Layer.provide(Layer.mergeAll(NodePath.layer, NodeFileSystem.layer)),
67
+ );
68
+ const gitExecLayer = GitExecutionService.layer.pipe(Layer.provide(nodeLayer));
69
+ const gitLayer = Layer.provide(GitStatusService.layer, gitExecLayer);
70
+ const previewLayer = PreviewService.make(() => platform.homeDir).pipe(
71
+ Layer.provide(Layer.merge(NodePath.layer, NodeFileSystem.layer)),
72
+ );
73
+ const configLayer = TuiConfigService.layer.pipe(Layer.provide(NodeFileSystem.layer));
74
+
75
+ return Layer.mergeAll(
76
+ configLayer,
77
+ EditorTintService.layer,
78
+ previewLayer,
79
+ gitExecLayer,
80
+ gitLayer,
81
+ sessionLayer,
82
+ ActivityService.make(() => host.state),
83
+ TurnTelemetryService.layer,
84
+ UsageTotalsService.layer(() => host.ctx?.sessionManager.getEntries() ?? []).pipe(
85
+ Layer.provide(sessionLayer),
86
+ ),
87
+ RuntimeInfoService.layer(() => host.state, platform.getEnv).pipe(
88
+ Layer.provide(sessionLayer),
89
+ Layer.provide(Layer.mergeAll(nodeLayer, NodeFileSystem.layer, NodePath.layer)),
90
+ ),
91
+ );
92
+ };
@@ -0,0 +1,218 @@
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, it } from "@effect/vitest";
5
+ import { Deferred, Duration, Effect, Fiber, Option } from "effect";
6
+ import { createTuiSessionHost } from "./layers.ts";
7
+ import type { RuntimeEnv } from "./runtime.ts";
8
+ import { RuntimeInfoService } from "./runtime-service.ts";
9
+ import type { FooterState } from "./state.ts";
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // RuntimeInfoService — synchronous last-known read over an asynchronous,
13
+ // cached, generation-guarded probe. The env is a stub container of effectful
14
+ // closures (London school at the boundary this module owns).
15
+ // ---------------------------------------------------------------------------
16
+
17
+ const serviceOver = (env: RuntimeEnv, getState: () => FooterState, getGeneration: () => number) =>
18
+ Effect.service(RuntimeInfoService).pipe(
19
+ Effect.provide(RuntimeInfoService.layerTest(env, getState, getGeneration)),
20
+ );
21
+
22
+ it.live("current() is empty before the first refresh and never awaits", () =>
23
+ Effect.gen(function* () {
24
+ // Arrange: a probe that never answers.
25
+ const host = createTuiSessionHost();
26
+ const env: RuntimeEnv = {
27
+ matches: (_cwd, def) => Effect.succeed(def.name === "nodejs"),
28
+ fingerprint: () => Effect.succeed("fp"),
29
+ version: () => Effect.never,
30
+ };
31
+ const svc = yield* serviceOver(
32
+ env,
33
+ () => host.state,
34
+ () => 1,
35
+ );
36
+
37
+ // Act: the synchronous read, then a refresh that will be cut short.
38
+ const before = svc.current();
39
+ const timedOut = yield* Effect.timeoutOption(svc.refresh("/p"), Duration.millis(50));
40
+
41
+ // Assert: a synchronous read that awaited would hang the test itself.
42
+ assert.deepStrictEqual(before, []);
43
+ assert.ok(Option.isNone(timedOut));
44
+ assert.deepStrictEqual(svc.current(), []);
45
+ }),
46
+ );
47
+
48
+ it.effect("refresh publishes the probe result through the synchronous read", () =>
49
+ Effect.gen(function* () {
50
+ // Arrange
51
+ const host = createTuiSessionHost();
52
+ const env: RuntimeEnv = {
53
+ matches: (_cwd, def) => Effect.succeed(def.name === "nodejs"),
54
+ fingerprint: () => Effect.succeed("fp"),
55
+ version: () => Effect.succeed("20.11.0"),
56
+ };
57
+ const svc = yield* serviceOver(
58
+ env,
59
+ () => host.state,
60
+ () => 1,
61
+ );
62
+
63
+ // Act
64
+ yield* svc.refresh("/p");
65
+
66
+ // Assert: read synchronously, in the expression position a render uses.
67
+ assert.deepStrictEqual(svc.current(), [{ name: "nodejs", version: "20.11.0" }]);
68
+ }),
69
+ );
70
+
71
+ it.effect("a stale probe result is dropped (async probe ordering)", () =>
72
+ Effect.gen(function* () {
73
+ // Arrange: the first probe parks until the gate opens.
74
+ const host = createTuiSessionHost();
75
+ const gate = yield* Deferred.make<void>();
76
+ let target = "nodejs";
77
+ let generation = 1;
78
+ const env: RuntimeEnv = {
79
+ matches: (_cwd, def) => Effect.succeed(def.name === target),
80
+ fingerprint: () => Effect.succeed("fp"),
81
+ version: (def) =>
82
+ def.name === "nodejs"
83
+ ? Deferred.await(gate).pipe(Effect.as("20.11.0"))
84
+ : Effect.succeed("1.80.0"),
85
+ };
86
+ const svc = yield* serviceOver(
87
+ env,
88
+ () => host.state,
89
+ () => generation,
90
+ );
91
+
92
+ // Act: fork the first refresh, change the generation, run the second.
93
+ const first = yield* Effect.forkChild(svc.refresh("/p"));
94
+ generation = 2;
95
+ target = "rust";
96
+ yield* svc.refresh("/p");
97
+ yield* Deferred.succeed(gate, undefined);
98
+ yield* Fiber.join(first);
99
+
100
+ // Assert: only the current generation's probe is published.
101
+ assert.deepStrictEqual(svc.current(), [{ name: "rust", version: "1.80.0" }]);
102
+ }),
103
+ );
104
+
105
+ it.effect("the cache is keyed by cwd + fingerprint and bounded at 32", () =>
106
+ Effect.gen(function* () {
107
+ // Arrange: a counting env behind the service's own cache (D9).
108
+ const host = createTuiSessionHost();
109
+ let versionProbes = 0;
110
+ const env: RuntimeEnv = {
111
+ matches: (_cwd, def) => Effect.succeed(def.name === "nodejs"),
112
+ fingerprint: () => Effect.succeed("fp"),
113
+ version: () => {
114
+ versionProbes += 1;
115
+ return Effect.succeed("20.11.0");
116
+ },
117
+ };
118
+ const svc = yield* serviceOver(
119
+ env,
120
+ () => host.state,
121
+ () => 1,
122
+ );
123
+
124
+ // Act: three reads of one cwd with an unchanged fingerprint.
125
+ yield* svc.refresh("/a");
126
+ yield* svc.refresh("/a");
127
+ yield* svc.refresh("/a");
128
+
129
+ // Assert: one probe serves all three.
130
+ assert.strictEqual(versionProbes, 1);
131
+
132
+ // Act: 40 distinct cwds, then the first one again.
133
+ for (let i = 0; i < 40; i++) yield* svc.refresh(`/cwd-${i}`);
134
+ yield* svc.refresh("/a");
135
+
136
+ // Assert: the bound is observable through call counts: /a was evicted.
137
+ assert.strictEqual(versionProbes, 42);
138
+ }),
139
+ );
140
+
141
+ it.effect("a changed fingerprint re-probes the version", () =>
142
+ Effect.gen(function* () {
143
+ // Arrange: a fingerprint the test moves, the way a touched marker does.
144
+ const host = createTuiSessionHost();
145
+ let versionProbes = 0;
146
+ let fingerprint = "fp-1";
147
+ const env: RuntimeEnv = {
148
+ matches: (_cwd, def) => Effect.succeed(def.name === "nodejs"),
149
+ fingerprint: () => Effect.succeed(fingerprint),
150
+ version: () => {
151
+ versionProbes += 1;
152
+ return Effect.succeed("20.11.0");
153
+ },
154
+ };
155
+ const svc = yield* serviceOver(
156
+ env,
157
+ () => host.state,
158
+ () => 1,
159
+ );
160
+
161
+ // Act: two reads with an unchanged fingerprint, then one after a change.
162
+ yield* svc.refresh("/a");
163
+ yield* svc.refresh("/a");
164
+ const unchanged = versionProbes;
165
+ fingerprint = "fp-2";
166
+ yield* svc.refresh("/a");
167
+
168
+ // Assert: the cache hit served the second read; the change re-probed.
169
+ assert.strictEqual(unchanged, 1);
170
+ assert.strictEqual(versionProbes, 2);
171
+ }),
172
+ );
173
+
174
+ it.effect("the service publishes into the host snapshot both providers read", () =>
175
+ Effect.gen(function* () {
176
+ // Arrange
177
+ const host = createTuiSessionHost();
178
+ const env: RuntimeEnv = {
179
+ matches: (_cwd, def) => Effect.succeed(def.name === "nodejs"),
180
+ fingerprint: () => Effect.succeed("fp"),
181
+ version: () => Effect.succeed("20.11.0"),
182
+ };
183
+ const svc = yield* serviceOver(
184
+ env,
185
+ () => host.state,
186
+ () => 1,
187
+ );
188
+
189
+ // Act
190
+ yield* svc.refresh("/p");
191
+
192
+ // Assert
193
+ assert.deepStrictEqual(host.state.runtime, svc.current());
194
+ assert.deepStrictEqual(host.state.runtime, [{ name: "nodejs", version: "20.11.0" }]);
195
+ }),
196
+ );
197
+
198
+ it.effect("a version probe that answers nothing yields a runtime without a version", () =>
199
+ Effect.gen(function* () {
200
+ // Arrange
201
+ const host = createTuiSessionHost();
202
+ const env: RuntimeEnv = {
203
+ matches: (_cwd, def) => Effect.succeed(def.name === "nodejs"),
204
+ fingerprint: () => Effect.succeed("fp"),
205
+ version: () => Effect.undefined,
206
+ };
207
+ const svc = yield* serviceOver(
208
+ env,
209
+ () => host.state,
210
+ () => 1,
211
+ );
212
+
213
+ // Act/Assert: no version key, and no failure. (The failing *command* case
214
+ // lives in runtime.test.ts, where the production env reads the exit code.)
215
+ yield* svc.refresh("/p");
216
+ assert.deepStrictEqual(svc.current(), [{ name: "nodejs" }]);
217
+ }),
218
+ );
@@ -0,0 +1,103 @@
1
+ import { Context, Effect, Layer, Path } from "effect";
2
+ import * as FileSystem from "effect/FileSystem";
3
+ import * as CP from "effect/process";
4
+ import {
5
+ discoverRuntimes,
6
+ platformRuntimeEnv,
7
+ type RuntimeEnv,
8
+ type RuntimeInfo,
9
+ } from "./runtime.ts";
10
+ import { SessionLifecycleService } from "./session-lifecycle.ts";
11
+ import type { FooterState } from "./state.ts";
12
+
13
+ const CACHE_MAX = 32;
14
+
15
+ /** Wraps an env with the bounded fingerprint→version cache; one loop stays in discovery (D9). */
16
+ const withCache = (env: RuntimeEnv): RuntimeEnv => {
17
+ const cache = new Map<string, { fingerprint: string; version: string | undefined }>();
18
+ return {
19
+ matches: env.matches,
20
+ fingerprint: env.fingerprint,
21
+ version: Effect.fnUntraced(function* (def, cwd) {
22
+ const fingerprint = yield* env.fingerprint(cwd, def);
23
+ const key = `${cwd}\0${def.name}`;
24
+ const cached = cache.get(key);
25
+ if (cached !== undefined && cached.fingerprint === fingerprint) return cached.version;
26
+ const version = yield* env.version(def, cwd);
27
+ cache.set(key, { fingerprint, version });
28
+ while (cache.size > CACHE_MAX) {
29
+ const oldest = cache.keys().next().value;
30
+ if (oldest === undefined) break;
31
+ cache.delete(oldest);
32
+ }
33
+ return version;
34
+ }),
35
+ };
36
+ };
37
+
38
+ /** The service body, independent of how the env was supplied. */
39
+ const buildRuntimeInfoService = (
40
+ env: RuntimeEnv,
41
+ getState: () => FooterState,
42
+ getGeneration: () => number,
43
+ ): RuntimeInfoService["Service"] => {
44
+ const cachedEnv = withCache(env);
45
+ const refresh = Effect.fn("RuntimeInfoService.refresh")(function* (cwd: string) {
46
+ const generation = getGeneration();
47
+ const next = yield* discoverRuntimes(cwd, cachedEnv);
48
+ if (getGeneration() !== generation) return; // stale probe: drop it
49
+ getState().runtime = [...next];
50
+ });
51
+ return RuntimeInfoService.of({ current: () => getState().runtime, refresh });
52
+ };
53
+
54
+ /**
55
+ * Runtime detection as service state (Slice 5): a synchronous last-known read
56
+ * for the render path and an asynchronous refresh that publishes only while
57
+ * the session generation is unchanged.
58
+ */
59
+ export class RuntimeInfoService extends Context.Service<
60
+ RuntimeInfoService,
61
+ {
62
+ /** Synchronous last-known read for render paths. Never awaits. */
63
+ readonly current: () => readonly RuntimeInfo[];
64
+ /** Asynchronous probe; publishes only if the session generation is unchanged. */
65
+ readonly refresh: (cwd: string) => Effect.Effect<void>;
66
+ }
67
+ >()("@ftrdotdev/pi-tui/runtime-service/RuntimeInfoService") {
68
+ /** Real layer: platform services + the injected env read + the lifecycle generation. */
69
+ static layer(
70
+ getState: () => FooterState,
71
+ getEnv: (name: string) => string | undefined,
72
+ ): Layer.Layer<
73
+ RuntimeInfoService,
74
+ never,
75
+ | FileSystem.FileSystem
76
+ | Path.Path
77
+ | CP.ChildProcessSpawner.ChildProcessSpawner
78
+ | SessionLifecycleService
79
+ > {
80
+ return Layer.effect(
81
+ RuntimeInfoService,
82
+ Effect.gen(function* () {
83
+ const fs = yield* FileSystem.FileSystem;
84
+ const path = yield* Path.Path;
85
+ const spawner = yield* CP.ChildProcessSpawner.ChildProcessSpawner;
86
+ const lifecycle = yield* SessionLifecycleService;
87
+ return buildRuntimeInfoService(
88
+ platformRuntimeEnv(fs, spawner, path, getEnv),
89
+ getState,
90
+ () => lifecycle.currentGeneration(),
91
+ );
92
+ }),
93
+ );
94
+ }
95
+
96
+ /** Test layer: a scripted env, no platform requirement at all. */
97
+ static readonly layerTest = (
98
+ env: RuntimeEnv,
99
+ getState: () => FooterState,
100
+ getGeneration: () => number,
101
+ ): Layer.Layer<RuntimeInfoService> =>
102
+ Layer.sync(RuntimeInfoService, () => buildRuntimeInfoService(env, getState, getGeneration));
103
+ }
@@ -1,8 +1,20 @@
1
- import { afterEach, assert, it } from "@effect/vitest";
2
- import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
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, it, vi } from "@effect/vitest";
4
5
  import { join } from "node:path";
5
- import { readRuntimeInfo } from "./runtime.ts";
6
+ import { Effect, Layer, Path, PlatformError } from "effect";
7
+ import * as FileSystem from "effect/FileSystem";
8
+ import * as CP from "effect/process";
9
+ import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
10
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
11
+ import * as NodePath from "@effect/platform-node/NodePath";
12
+ import {
13
+ discoverRuntimes,
14
+ platformRuntimeEnv,
15
+ type RuntimeEnv,
16
+ type RuntimeInfo,
17
+ } from "./runtime.ts";
6
18
 
7
19
  // Env-based runtimes (no marker file) would leak the host environment into
8
20
  // the "no marker matches" case, so that test clears them.
@@ -15,73 +27,160 @@ const ENV_KEYS = [
15
27
  "SPACK_ENV",
16
28
  ] as const;
17
29
 
18
- const dirs: string[] = [];
30
+ /** The environment the runner started with; a stub must not outlive its test. */
31
+ const ENV_AT_MODULE_LOAD = new Map(ENV_KEYS.map((key) => [key, process.env[key]] as const));
19
32
 
20
- function tempDir(): string {
21
- const dir = mkdtempSync(join(tmpdir(), "pi-tui-runtime-"));
22
- dirs.push(dir);
23
- return dir;
24
- }
33
+ type Platform = FileSystem.FileSystem | CP.ChildProcessSpawner.ChildProcessSpawner | Path.Path;
25
34
 
26
- afterEach(() => {
27
- for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
28
- });
35
+ const platformLayer = Layer.mergeAll(
36
+ NodeFileSystem.layer,
37
+ NodePath.layer,
38
+ NodeChildProcessSpawner.layer.pipe(
39
+ Layer.provide(Layer.merge(NodePath.layer, NodeFileSystem.layer)),
40
+ ),
41
+ );
29
42
 
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
- });
43
+ /** The production env over real platform services; env reads stay live for `vi.stubEnv`. */
44
+ const platformEnv = (
45
+ fs: FileSystem.FileSystem,
46
+ spawner: CP.ChildProcessSpawner.ChildProcessSpawner["Service"],
47
+ ): Effect.Effect<RuntimeEnv, never, Path.Path> =>
48
+ Effect.gen(function* () {
49
+ const path = yield* Path.Path;
50
+ return platformRuntimeEnv(fs, spawner, path, (name) => process.env[name]);
51
+ });
39
52
 
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
+ /** Discovery over the production env (the only platform construction, D8). */
54
+ const discoverIn = (dir: string): Effect.Effect<readonly RuntimeInfo[], never, Platform> =>
55
+ Effect.gen(function* () {
56
+ const fs = yield* FileSystem.FileSystem;
57
+ const spawner = yield* CP.ChildProcessSpawner.ChildProcessSpawner;
58
+ const env = yield* platformEnv(fs, spawner);
59
+ return yield* discoverRuntimes(dir, env);
60
+ });
61
+
62
+ /** One real temp directory per test, removed when its scope closes. */
63
+ const withTempDir = <A, E>(
64
+ use: (fs: FileSystem.FileSystem, dir: string) => Effect.Effect<A, E, Platform>,
65
+ ): Effect.Effect<A, E | PlatformError.PlatformError> =>
66
+ Effect.scoped(
67
+ Effect.gen(function* () {
68
+ const fs = yield* FileSystem.FileSystem;
69
+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "pi-tui-runtime-" });
70
+ return yield* use(fs, dir);
71
+ }),
72
+ ).pipe(Effect.provide(platformLayer));
73
+
74
+ it.effect("returns every matching runtime in table order", () =>
75
+ withTempDir((fs, dir) =>
76
+ Effect.gen(function* () {
77
+ yield* fs.writeFileString(join(dir, "CMakeLists.txt"), "");
78
+ const runtimes = yield* discoverIn(dir);
79
+ assert.deepStrictEqual(
80
+ runtimes.map((r) => r.name),
81
+ ["cpp", "c", "cmake"],
82
+ );
83
+ }),
84
+ ),
85
+ );
86
+
87
+ it.effect("returns an empty list when no marker matches", () =>
88
+ withTempDir((_fs, dir) =>
89
+ Effect.gen(function* () {
90
+ for (const key of ENV_KEYS) vi.stubEnv(key, undefined);
91
+ const found = yield* discoverIn(dir);
92
+ assert.deepStrictEqual(found, []);
93
+ }),
94
+ ),
95
+ );
53
96
 
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
- }
97
+ it("the runtime keys are restored without a finally", () => {
98
+ for (const key of ENV_KEYS) assert.strictEqual(process.env[key], ENV_AT_MODULE_LOAD.get(key));
69
99
  });
70
100
 
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");
101
+ it.effect("matches env-based runtimes without a marker file", () =>
102
+ withTempDir((_fs, dir) =>
103
+ Effect.gen(function* () {
104
+ vi.stubEnv("CONDA_DEFAULT_ENV", "pi-tui-test");
105
+ const runtimes = yield* discoverIn(dir);
106
+ assert.deepStrictEqual(
107
+ runtimes.map((r) => r.name),
108
+ ["conda"],
109
+ );
110
+ }),
111
+ ),
112
+ );
113
+
114
+ /** A one-command definition the production env can probe in a temp dir. */
115
+ const probeDef = (script: string) => ({
116
+ name: "probe",
117
+ files: [],
118
+ versionCommand: {
119
+ cmd: process.execPath,
120
+ args: ["-e", script],
121
+ pattern: /v(\d+\.\d+\.\d+)/,
122
+ },
87
123
  });
124
+
125
+ it.effect("the probe extracts a version through the platform env", () =>
126
+ withTempDir((fs, dir) =>
127
+ Effect.gen(function* () {
128
+ const spawner = yield* CP.ChildProcessSpawner.ChildProcessSpawner;
129
+ const version = yield* (yield* platformEnv(fs, spawner)).version(
130
+ probeDef("console.log('v20.11.0')"),
131
+ dir,
132
+ );
133
+ assert.strictEqual(version, "20.11.0");
134
+ }),
135
+ ),
136
+ );
137
+
138
+ it.effect("a version command that exits non-zero has no version", () =>
139
+ withTempDir((fs, dir) =>
140
+ Effect.gen(function* () {
141
+ // Arrange: the old `execFile` rejected on this exit, so the catch made it
142
+ // undefined; the platform string helper ignores the code, the probe must not.
143
+ const spawner = yield* CP.ChildProcessSpawner.ChildProcessSpawner;
144
+ const version = yield* (yield* platformEnv(fs, spawner)).version(
145
+ probeDef("console.log('v20.11.0'); process.exit(1)"),
146
+ dir,
147
+ );
148
+ assert.strictEqual(version, undefined);
149
+ }),
150
+ ),
151
+ );
152
+
153
+ it.effect("a large stdout and stderr keep the version and still drain", () =>
154
+ withTempDir((fs, dir) =>
155
+ Effect.gen(function* () {
156
+ // Arrange: the version first, then 2 MiB on each pipe. An unread stream
157
+ // blocks the child, which would hit the 2 500 ms timeout and lose it.
158
+ const spawner = yield* CP.ChildProcessSpawner.ChildProcessSpawner;
159
+ const version = yield* (yield* platformEnv(fs, spawner)).version(
160
+ probeDef(
161
+ [
162
+ "console.log('v20.11.0')",
163
+ "process.stdout.write('x'.repeat(2 * 1024 * 1024))",
164
+ "process.stderr.write('y'.repeat(2 * 1024 * 1024))",
165
+ ].join("; "),
166
+ ),
167
+ dir,
168
+ );
169
+ assert.strictEqual(version, "20.11.0");
170
+ }),
171
+ ),
172
+ );
173
+
174
+ it.effect("a version past the 64 KiB cap is not found", () =>
175
+ withTempDir((fs, dir) =>
176
+ Effect.gen(function* () {
177
+ // Arrange: the version sits behind 2 MiB of noise, so only the head is parsed.
178
+ const spawner = yield* CP.ChildProcessSpawner.ChildProcessSpawner;
179
+ const version = yield* (yield* platformEnv(fs, spawner)).version(
180
+ probeDef("process.stdout.write('x'.repeat(2 * 1024 * 1024)); console.log('v20.11.0')"),
181
+ dir,
182
+ );
183
+ assert.strictEqual(version, undefined);
184
+ }),
185
+ ),
186
+ );