Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectSetupScriptRunner.test.ts

375 lines14.6 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, describe, expect, it } from "@effect/vitest";
4import {
5 ProjectId,
6 TerminalNotRunningError,
7 type TerminalEvent,
8 type TerminalOpenInput,
9 type TerminalSessionSnapshot,
10} from "@t3tools/contracts";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Queue from "effect/Queue";
17import * as Stream from "effect/Stream";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19import { TestClock } from "effect/testing";
20​
21import * as ServerSettings from "../serverSettings.ts";
22import * as TerminalManager from "../terminal/Manager.ts";
23import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
24import * as ProjectService from "./ProjectService.ts";
25import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
26​
27const threadId = "thread-1";
28const terminalId = "setup-setup";
29const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" };
30​
31const openSnapshot = (history: string): TerminalSessionSnapshot => ({
32 threadId,
33 terminalId,
34 cwd: "/repo/.t3/worktrees/feature",
35 worktreePath: null,
36 status: "running",
37 pid: 123,
38 history,
39 exitCode: null,
40 exitSignal: null,
41 label: "zsh",
42 updatedAt: "2026-01-01T00:00:00.000Z",
43});
44​
45const makeHarness = Effect.fn(function* (options: {
46 readonly command?: string;
47 readonly history?: string;
48 readonly opening?: Deferred.Deferred<void>;
49 readonly shell?: string | null;
50}) {
51 const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
52 const opens: TerminalOpenInput[] = [];
53 const writes = yield* Queue.unbounded<string>();
54 const outputLines = yield* Queue.unbounded<string>();
55 const terminals = Layer.mock(TerminalManager.TerminalManager)({
56 open: (input) =>
57 Effect.sync(() => opens.push(input)).pipe(
58 Effect.andThen(
59 options.opening
60 ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
61 : Effect.void,
62 ),
63 Effect.as(openSnapshot(options.history ?? "")),
64 ),
65 getShell: () =>
66 options.shell === null
67 ? Effect.fail(new TerminalNotRunningError({ threadId, terminalId }))
68 : Effect.succeed(options.shell ?? "/bin/zsh"),
69 subscribe: (listener) =>
70 Effect.sync(() => {
71 listeners.add(listener);
72 return () => listeners.delete(listener);
73 }),
74 write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
75 closeIdle: () => Effect.void,
76 closeOnSettle: () => Effect.void,
77 });
78 const runner = yield* ProjectSetupScriptRunner.make.pipe(
79 Effect.provide(
80 Layer.mergeAll(
81 terminals,
82 Layer.mock(ProjectService.ProjectService)({}),
83 Layer.mock(ProjectionStore.ProjectionStoreV2)({
84 getThreadShell: () => Effect.succeed(null),
85 }),
86 ServerSettings.layerTest(),
87 NodeCrypto.layer,
88 ),
89 ),
90 );
91 const start = runner.runForThread({
92 threadId,
93 worktreePath: "/repo/.t3/worktrees/feature",
94 observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
95 project: {
96 id: ProjectId.make("project-1"),
97 workspaceRoot: "/repo",
98 scripts: [
99 {
100 id: "setup",
101 name: "Setup",
102 command: options.command ?? "vp i",
103 icon: "configure",
104 runOnWorktreeCreate: true,
105 },
106 ],
107 },
108 });
109 const emit = (terminalEvent: TerminalEvent) =>
110 Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
111 return { start, listeners, writes, outputLines, emit, opens };
112});
113​
114const setup = Effect.fn(function* (
115 options: {
116 readonly command?: string;
117 readonly history?: string;
118 readonly shell?: string | null;
119 } = {},
120) {
121 const harness = yield* makeHarness(options);
122 const result = yield* harness.start;
123 const completion = result.status === "started" ? result.completion : undefined;
124 if (!completion) return yield* Effect.die("setup did not start an observed run");
125 return { ...harness, result, completion };
126});
127​
128describe("ProjectSetupScriptRunner", () => {
129 it.effect("keeps setup scripts independent of the interactive shell preference", () =>
130 Effect.gen(function* () {
131 const { opens } = yield* setup();
132 expect(opens[0]?.env?.T3CODE_TERMINAL_SHELL).toBe("");
133 }),
134 );
135​
136 it.effect("writes immediately when the spawned fallback is PowerShell", () =>
137 Effect.gen(function* () {
138 const { writes } = yield* setup({
139 shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
140 });
141 expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE");
142 }),
143 );
144​
145 it.effect("types an escaped Nushell wrapper once its line editor starts", () =>
146 Effect.gen(function* () {
147 const command =
148 'print "quoted"; print \'C:\\tools\'; print "$env.PATH"\nexit 7 # comment\r\n\t';
149 const escaped =
150 'print \\"quoted\\"; print \'C:\\\\tools\'; print \\"$env.PATH\\"\\u{a}exit 7 # comment\\u{d}\\u{a}\\u{9}';
151 const { writes, emit } = yield* setup({ shell: "/opt/homebrew/bin/nu", command });
152 yield* TestClock.adjust("1 second");
153 expect(yield* Queue.size(writes)).toBe(0);
154 yield* emit({ ...event, type: "output", data: "> \x1b[?2004h" });
155 const written = yield* Queue.take(writes);
156 const sentinel = written.match(/__T3_SETUP_DONE___[0-9a-f]{32}:/)?.[0];
157 expect(sentinel).toBeDefined();
158 expect(written).toBe(
159 ` ${[
160 "$env.LAST_EXIT_CODE = 0",
161 "let __t3f = try { mktemp --tmpdir-path $env.T3CODE_WORKTREE_PATH --suffix .nu .t3-setup-XXXXXXXX } catch {|e| print -e $e.msg; null }",
162 `if $__t3f == null { $env.LAST_EXIT_CODE = 1 } else { try { [$"rm --permanent ($__t3f | to nuon)" "${escaped}"] | str join (char newline) | save --force --raw $__t3f; ^$nu.current-exe --login --commands $"cd $env.T3CODE_WORKTREE_PATH; source ($__t3f | to nuon)" } catch {|e| if $e != null and $e.exit_code? == null { print -e $e.msg }; if $env.LAST_EXIT_CODE == 0 { $env.LAST_EXIT_CODE = 1 } } }`,
163 "let __t3c = $env.LAST_EXIT_CODE",
164 "try { if $__t3f != null and ($__t3f | path exists) { rm --permanent $__t3f } } catch {|e| print -e $e.msg }",
165 `print $"\\n${sentinel}($__t3c)"`,
166 ].join("; ")}\r`,
167 );
168 }),
169 );
170​
171 it.effect("shows a startup prompt and types only once the line editor starts", () =>
172 Effect.gen(function* () {
173 const { result, writes, outputLines, emit } = yield* setup();
174 expect(result).toMatchObject({ status: "started", terminalId });
175​
176 yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
177 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
178 yield* TestClock.adjust("1 minute");
179 expect(yield* Queue.size(writes)).toBe(0);
180 expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
181​
182 yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
183 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
184 expect(yield* Queue.take(writes)).toContain("vp i");
185 }),
186 );
187​
188 it.effect("drops whole escape sequences from output lines", () =>
189 Effect.gen(function* () {
190 const { outputLines, emit } = yield* setup();
191 yield* emit({
192 ...event,
193 type: "output",
194 data: "\x1b7\x1b[24;0fProgress: [ 40%]\x1b8\r\n\x1b%G\x1b#8\x1b[4:3mdone\x1bM\r\n",
195 });
196 expect(yield* Queue.takeAll(outputLines)).toEqual(["Progress: [ 40%]", "done"]);
197 }),
198 );
199​
200 it.effect("keeps emoji whole when capping a long output line or partial-line buffer", () =>
201 Effect.gen(function* () {
202 const { outputLines, emit } = yield* setup();
203 yield* emit({ ...event, type: "output", data: `x${"🙂".repeat(250)}\r\n` });
204 yield* emit({ ...event, type: "output", data: `${"🙂".repeat(2_100)}x` });
205 yield* emit({ ...event, type: "output", data: "\r\n" });
206 expect(yield* Queue.takeAll(outputLines)).toEqual([`x${"🙂".repeat(199)}`, "🙂".repeat(200)]);
207 }),
208 );
209​
210 it.effect("types into a quiet shell that has no line editor", () =>
211 Effect.gen(function* () {
212 const { writes } = yield* setup();
213 yield* TestClock.adjust("3 seconds");
214 expect(yield* Queue.take(writes)).toContain("vp i");
215 }),
216 );
217​
218 it.effect("ignores line editor state restored from an earlier shell", () =>
219 Effect.gen(function* () {
220 const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
221 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
222 yield* TestClock.adjust("1 minute");
223 expect(yield* Queue.size(writes)).toBe(0);
224 }),
225 );
226​
227 it.effect("forgets a busy startup child when the shell restarts", () =>
228 Effect.gen(function* () {
229 const { writes, emit } = yield* setup();
230 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
231 yield* TestClock.adjust("1 minute");
232 expect(yield* Queue.size(writes)).toBe(0);
233 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
234 // The restart lands inside a quiet window, so the next full window decides.
235 yield* TestClock.adjust("6 seconds");
236 expect(yield* Queue.take(writes)).toContain("vp i");
237 }),
238 );
239​
240 it.effect("drops its terminal listeners when cancelled while the terminal opens", () =>
241 Effect.gen(function* () {
242 const opening = yield* Deferred.make<void>();
243 const { start, listeners } = yield* makeHarness({ opening });
244 const fiber = yield* Effect.forkChild(start);
245 yield* Deferred.await(opening);
246 expect(listeners.size).toBe(2);
247 yield* Fiber.interrupt(fiber);
248 expect(listeners.size).toBe(0);
249 }),
250 );
251​
252 it.effect.each([false, true])(
253 "does not type into a shell that exits during startup (before shell lookup: %s)",
254 (beforeShellLookup) =>
255 Effect.gen(function* () {
256 const { completion, writes, emit, listeners } = yield* setup(
257 beforeShellLookup ? { shell: null } : {},
258 );
259 if (!beforeShellLookup) {
260 yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
261 }
262 expect(yield* completion).toMatchObject({ exitCode: null });
263 yield* TestClock.adjust("1 minute");
264 expect(yield* Queue.size(writes)).toBe(0);
265 expect(listeners.size).toBe(0);
266 }),
267 );
268});
269​
270const runObservedSetup = Effect.fnUntraced(function* (command: string) {
271 const { writes, outputLines, emit, completion } = yield* setup({ command });
272 yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
273 const submitted = yield* Queue.take(writes);
274 const cwd = yield* HostProcess.WorkingDirectory;
275 const env = yield* HostProcess.Environment;
276​
277 // Enter becomes a newline at the terminal boundary; transport assertions below
278 // cover line-editor submissions and canonical TTY limits that bash -c bypasses.
279 const child = yield* Effect.gen(function* () {
280 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
281 const handle = yield* spawner.spawn(
282 ChildProcess.make(
283 "/bin/bash",
284 ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")],
285 {
286 cwd,
287 env: { PATH: env.PATH },
288 },
289 ),
290 );
291 return yield* Effect.all(
292 {
293 stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
294 stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
295 exitCode: handle.exitCode,
296 },
297 { concurrency: "unbounded" },
298 );
299 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
300 yield* emit({ ...event, type: "output", data: submitted + "\n" });
301 yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
302 yield* emit({ ...event, type: "closed" });
303 return {
304 submitted,
305 lines: yield* Queue.clear(outputLines),
306 exitCode: (yield* completion).exitCode,
307 };
308});
309​
310describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
311 it.live("submits one line while preserving multiline shell syntax and literal text", () =>
312 Effect.gen(function* () {
313 const result = yield* runObservedSetup(
314 [
315 "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
316 "cat <<'END'",
317 "$literal \\path 雪",
318 "END",
319 "printf '%s\\n' done # trailing comment",
320 ].join("\r\n"),
321 );
322 assert.equal(result.submitted.at(-1), "\r");
323 assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
324 assert.deepEqual(result.lines, [
325 "it's ready",
326 "literal \\n $(printf wrong) `printf wrong` café",
327 "$literal \\path 雪",
328 "done",
329 ]);
330 assert.equal(result.exitCode, 0);
331 }),
332 );
333​
334 it.live("completes long scripts without exceeding canonical terminal line limits", () =>
335 Effect.gen(function* () {
336 const expected = Array.from(
337 { length: 120 },
338 (_, index) => `line-${index}: café 雪 'quoted' \\path`,
339 );
340 const command = expected
341 .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
342 .join("\n");
343 const utf8 = new TextEncoder();
344 assert.isAbove(utf8.encode(command).byteLength, 4_096);
345​
346 const result = yield* runObservedSetup(command);
347 assert.deepEqual(result.lines, expected);
348 assert.equal(result.exitCode, 0);
349 assert.equal(result.submitted.at(-1), "\r");
350 assert.notInclude(result.submitted, "\n");
351 // The runner can write before the shell switches the terminal out of canonical mode.
352 for (const line of result.submitted.slice(0, -1).split("\r")) {
353 assert.isBelow(utf8.encode(line).byteLength, 1_024);
354 }
355 }),
356 );
357​
358 it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
359 Effect.gen(function* () {
360 const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
361 assert.deepEqual(result.lines, ["direct"]);
362 assert.equal(result.exitCode, 0);
363 }),
364 );
365​
366 it.live.each([
367 { name: "an explicit exit", command: "exit 7", exitCode: 7 },
368 { name: "a syntax error", command: "if then", exitCode: 2 },
369 ])("reports a nonzero completion for $name", ({ command, exitCode }) =>
370 Effect.gen(function* () {
371 const result = yield* runObservedSetup(command);
372 assert.equal(result.exitCode, exitCode);
373 }),
374 );
375});