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

ProjectSetupScriptRunner.test.ts

447 lines18.0 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 previousSession?: TerminalSessionSnapshot;
50 readonly shell?: string | null;
51 readonly trigger?: "setup" | "settle";
52}) {
53 const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
54 const opens: TerminalOpenInput[] = [];
55 const closed: Array<string | undefined> = [];
56 const openedSessions: TerminalSessionSnapshot[] = [];
57 let session = options.previousSession;
58 const writes = yield* Queue.unbounded<string>();
59 const outputLines = yield* Queue.unbounded<string>();
60 const terminals = Layer.mock(TerminalManager.TerminalManager)({
61 open: (input) =>
62 Effect.sync(() => opens.push(input)).pipe(
63 Effect.andThen(
64 options.opening
65 ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
66 : Effect.void,
67 ),
68 Effect.map(() => {
69 session ??= openSnapshot(options.history ?? "");
70 openedSessions.push(session);
71 return session;
72 }),
73 ),
74 getShell: () =>
75 options.shell === null
76 ? Effect.fail(new TerminalNotRunningError({ threadId, terminalId }))
77 : Effect.succeed(options.shell ?? "/bin/zsh"),
78 subscribe: (listener) =>
79 Effect.sync(() => {
80 listeners.add(listener);
81 return () => listeners.delete(listener);
82 }),
83 write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
84 close: (input) =>
85 Effect.sync(() => {
86 closed.push(input.terminalId);
87 session = undefined;
88 }).pipe(
89 Effect.andThen(
90 Effect.forEach([...listeners], (listener) => listener({ ...event, type: "closed" }), {
91 discard: true,
92 }),
93 ),
94 ),
95 // As if a prompt hook were still running: the idle check keeps the shell.
96 closeIdle: () => Effect.void,
97 closeOnSettle: () => Effect.void,
98 });
99 const runner = yield* ProjectSetupScriptRunner.make.pipe(
100 Effect.provide(
101 Layer.mergeAll(
102 terminals,
103 Layer.mock(ProjectService.ProjectService)({}),
104 Layer.mock(ProjectionStore.ProjectionStoreV2)({
105 getThreadShell: () => Effect.succeed(null),
106 }),
107 ServerSettings.layerTest(),
108 NodeCrypto.layer,
109 ),
110 ),
111 );
112 const start = runner.runForThread({
113 threadId,
114 worktreePath: "/repo/.t3/worktrees/feature",
115 ...(options.trigger ? { trigger: options.trigger } : {}),
116 observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
117 project: {
118 id: ProjectId.make("project-1"),
119 workspaceRoot: "/repo",
120 scripts: [
121 {
122 id: "setup",
123 name: "Setup",
124 command: options.command ?? "vp i",
125 icon: "configure",
126 runOnWorktreeCreate: true,
127 ...(options.trigger === "settle" ? { runOnSettle: true } : {}),
128 },
129 ],
130 },
131 });
132 const emit = (terminalEvent: TerminalEvent) =>
133 Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
134 return { start, listeners, writes, outputLines, emit, openedSessions, opens, closed };
135});
136​
137const setup = Effect.fn(function* (
138 options: {
139 readonly command?: string;
140 readonly history?: string;
141 readonly previousSession?: TerminalSessionSnapshot;
142 readonly shell?: string | null;
143 readonly trigger?: "setup" | "settle";
144 } = {},
145) {
146 const harness = yield* makeHarness(options);
147 const result = yield* harness.start;
148 const completion = result.status === "started" ? result.completion : undefined;
149 if (!completion) return yield* Effect.die("setup did not start an observed run");
150 return { ...harness, result, completion };
151});
152​
153describe("ProjectSetupScriptRunner", () => {
154 it.effect("keeps setup scripts independent of the interactive shell preference", () =>
155 Effect.gen(function* () {
156 const { opens } = yield* setup();
157 expect(opens[0]?.env?.T3CODE_TERMINAL_SHELL).toBe("");
158 }),
159 );
160​
161 it.effect("writes immediately when the spawned fallback is PowerShell", () =>
162 Effect.gen(function* () {
163 const { writes } = yield* setup({
164 shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
165 });
166 const submitted = yield* Queue.take(writes);
167 expect(submitted).toContain("$global:LASTEXITCODE");
168 expect(submitted).not.toContain("\x1b[200~");
169 }),
170 );
171​
172 it.effect("types an escaped Nushell wrapper once its line editor starts", () =>
173 Effect.gen(function* () {
174 const command =
175 'print "quoted"; print \'C:\\tools\'; print "$env.PATH"\nexit 7 # comment\r\n\t';
176 const escaped =
177 'print \\"quoted\\"; print \'C:\\\\tools\'; print \\"$env.PATH\\"\\u{a}exit 7 # comment\\u{d}\\u{a}\\u{9}';
178 const { writes, emit } = yield* setup({ shell: "/opt/homebrew/bin/nu", command });
179 yield* TestClock.adjust("1 second");
180 expect(yield* Queue.size(writes)).toBe(0);
181 yield* emit({ ...event, type: "output", data: "> \x1b[?2004h" });
182 const written = yield* Queue.take(writes);
183 const sentinel = written.match(/__T3_SETUP_DONE___[0-9a-f]{32}:/)?.[0];
184 expect(sentinel).toBeDefined();
185 expect(written).toBe(
186 ` ${[
187 "$env.LAST_EXIT_CODE = 0",
188 "let __t3f = try { mktemp --tmpdir-path $env.T3CODE_WORKTREE_PATH --suffix .nu .t3-setup-XXXXXXXX } catch {|e| print -e $e.msg; null }",
189 `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 } } }`,
190 "let __t3c = $env.LAST_EXIT_CODE",
191 "try { if $__t3f != null and ($__t3f | path exists) { rm --permanent $__t3f } } catch {|e| print -e $e.msg }",
192 `print $"\\n${sentinel}($__t3c)"`,
193 ].join("; ")}\r`,
194 );
195 }),
196 );
197​
198 it.effect("replaces a surviving setup shell and types only once the line editor starts", () =>
199 Effect.gen(function* () {
200 const { result, completion, openedSessions, writes, outputLines, emit } = yield* setup({
201 previousSession: openSnapshot("previous setup in the deleted checkout"),
202 });
203 expect(result).toMatchObject({ status: "started", terminalId });
204 expect(openedSessions).toEqual([openSnapshot("")]);
205​
206 yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
207 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
208 yield* TestClock.adjust("1 minute");
209 expect(yield* Queue.size(writes)).toBe(0);
210 expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
211​
212 yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
213 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
214 const command = yield* Queue.take(writes);
215 expect(command).toContain("vp i");
216 const sentinel = command.match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0];
217 expect(sentinel).toBeDefined();
218 yield* emit({ ...event, type: "output", data: `${sentinel}0\r\n% ` });
219 expect(yield* completion).toMatchObject({ exitCode: 0 });
220 }),
221 );
222​
223 it.effect("closes a successful settle shell even while its prompt is still busy", () =>
224 Effect.gen(function* () {
225 const { result, completion, writes, emit, closed } = yield* setup({ trigger: "settle" });
226 if (result.status !== "started") return yield* Effect.die("settle did not start");
227 const settleEvent = { ...event, terminalId: result.terminalId };
228 yield* emit({ ...settleEvent, type: "output", data: "% \x1b[?2004h" });
229 const sentinel = (yield* Queue.take(writes)).match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0];
230 // No prompt follows: the prompt hook is still running when the wait for it ends.
231 yield* emit({ ...settleEvent, type: "output", data: `\r\n${sentinel}0\r\n` });
232 const done = yield* completion.pipe(Effect.forkChild({ startImmediately: true }));
233 yield* TestClock.adjust("1 second");
234 expect(yield* Fiber.join(done)).toMatchObject({ exitCode: 0 });
235 expect(closed).toEqual([result.terminalId]);
236 }),
237 );
238​
239 it.effect("drops whole escape sequences from output lines", () =>
240 Effect.gen(function* () {
241 const { outputLines, emit } = yield* setup();
242 yield* emit({
243 ...event,
244 type: "output",
245 data: "\x1b7\x1b[24;0fProgress: [ 40%]\x1b8\r\n\x1b%G\x1b#8\x1b[4:3mdone\x1bM\r\n",
246 });
247 expect(yield* Queue.takeAll(outputLines)).toEqual(["Progress: [ 40%]", "done"]);
248 }),
249 );
250​
251 it.effect("keeps emoji whole when capping a long output line or partial-line buffer", () =>
252 Effect.gen(function* () {
253 const { outputLines, emit } = yield* setup();
254 yield* emit({ ...event, type: "output", data: `x${"🙂".repeat(250)}\r\n` });
255 yield* emit({ ...event, type: "output", data: `${"🙂".repeat(2_100)}x` });
256 yield* emit({ ...event, type: "output", data: "\r\n" });
257 expect(yield* Queue.takeAll(outputLines)).toEqual([`x${"🙂".repeat(199)}`, "🙂".repeat(200)]);
258 }),
259 );
260​
261 it.effect("types into a quiet shell that has no line editor", () =>
262 Effect.gen(function* () {
263 const { writes } = yield* setup({ command: "printf '%s\\n' 'setup-ready'\n".repeat(120) });
264 yield* TestClock.adjust("3 seconds");
265 const submitted = yield* Queue.take(writes);
266 expect(submitted).toContain("setup-ready");
267 expect(submitted).not.toContain("\x1b[200~");
268 }),
269 );
270​
271 it.effect("ignores line editor state restored from an earlier shell", () =>
272 Effect.gen(function* () {
273 const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
274 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
275 yield* TestClock.adjust("1 minute");
276 expect(yield* Queue.size(writes)).toBe(0);
277 }),
278 );
279​
280 it.effect("forgets a busy startup child when the shell restarts", () =>
281 Effect.gen(function* () {
282 const { writes, emit } = yield* setup();
283 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
284 yield* TestClock.adjust("1 minute");
285 expect(yield* Queue.size(writes)).toBe(0);
286 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
287 // The restart lands inside a quiet window, so the next full window decides.
288 yield* TestClock.adjust("6 seconds");
289 expect(yield* Queue.take(writes)).toContain("vp i");
290 }),
291 );
292​
293 it.effect.each(["opening", "completion"] as const)(
294 "stops pending setup when cancelled during %s",
295 (phase) =>
296 Effect.gen(function* () {
297 const opening = yield* Deferred.make<void>();
298 const { start, listeners, writes, emit } = yield* makeHarness(
299 phase === "opening" ? { opening } : {},
300 );
301 const pending =
302 phase === "opening"
303 ? start.pipe(Effect.asVoid)
304 : yield* start.pipe(
305 Effect.map((result) =>
306 result.status === "started" && result.completion
307 ? result.completion.pipe(Effect.asVoid)
308 : Effect.die("setup did not start"),
309 ),
310 );
311 const fiber = yield* pending.pipe(Effect.forkChild({ startImmediately: true }));
312 if (phase === "opening") yield* Deferred.await(opening);
313 expect(listeners.size).toBe(2);
314 yield* Fiber.interrupt(fiber);
315 expect(listeners.size).toBe(0);
316 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
317 expect(yield* Queue.size(writes)).toBe(0);
318 }),
319 );
320​
321 it.effect.each([false, true])(
322 "does not type into a shell that exits during startup (before shell lookup: %s)",
323 (beforeShellLookup) =>
324 Effect.gen(function* () {
325 const { completion, writes, emit, listeners } = yield* setup(
326 beforeShellLookup ? { shell: null } : {},
327 );
328 if (!beforeShellLookup) {
329 yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
330 }
331 expect(yield* completion).toMatchObject({ exitCode: null });
332 yield* TestClock.adjust("1 minute");
333 expect(yield* Queue.size(writes)).toBe(0);
334 expect(listeners.size).toBe(0);
335 }),
336 );
337});
338​
339const runObservedSetup = Effect.fnUntraced(function* (command: string) {
340 const { writes, outputLines, emit, completion } = yield* setup({ command });
341 yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
342 const submitted = yield* Queue.take(writes);
343 const shellInput = submitted.replace("\x1b[200~", "").replace("\x1b[201~", "");
344 const cwd = yield* HostProcess.WorkingDirectory;
345 const env = yield* HostProcess.Environment;
346​
347 // Enter becomes a newline at the terminal boundary; transport assertions below
348 // cover line-editor submissions and canonical TTY limits that bash -c bypasses.
349 const child = yield* Effect.gen(function* () {
350 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
351 const handle = yield* spawner.spawn(
352 ChildProcess.make(
353 "/bin/bash",
354 ["--noprofile", "--norc", "-c", shellInput.replaceAll("\r", "\n")],
355 {
356 cwd,
357 env: { PATH: env.PATH },
358 },
359 ),
360 );
361 return yield* Effect.all(
362 {
363 stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
364 stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
365 exitCode: handle.exitCode,
366 },
367 { concurrency: "unbounded" },
368 );
369 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
370 yield* emit({ ...event, type: "output", data: submitted + "\n" });
371 yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
372 yield* emit({ ...event, type: "closed" });
373 return {
374 submitted,
375 shellInput,
376 lines: yield* Queue.clear(outputLines),
377 exitCode: (yield* completion).exitCode,
378 };
379});
380​
381describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
382 it.live("submits one line while preserving multiline shell syntax and literal text", () =>
383 Effect.gen(function* () {
384 const result = yield* runObservedSetup(
385 [
386 "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
387 "cat <<'END'",
388 "$literal \\path 雪",
389 "END",
390 "printf '%s\\n' done # trailing comment",
391 ].join("\r\n"),
392 );
393 assert.equal(result.submitted.at(-1), "\r");
394 assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
395 assert.deepEqual(result.lines, [
396 "it's ready",
397 "literal \\n $(printf wrong) `printf wrong` café",
398 "$literal \\path 雪",
399 "done",
400 ]);
401 assert.equal(result.exitCode, 0);
402 }),
403 );
404​
405 it.live("completes long scripts without exceeding canonical terminal line limits", () =>
406 Effect.gen(function* () {
407 const expected = Array.from(
408 { length: 120 },
409 (_, index) => `line-${index}: café 雪 'quoted' \\path`,
410 );
411 const command = expected
412 .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
413 .join("\n");
414 const utf8 = new TextEncoder();
415 assert.isAbove(utf8.encode(command).byteLength, 4_096);
416​
417 const result = yield* runObservedSetup(command);
418 assert.deepEqual(result.lines, expected);
419 assert.equal(result.exitCode, 0);
420 assert.equal(result.submitted.at(-1), "\r");
421 assert.isTrue(result.submitted.startsWith(" \x1b[200~"));
422 assert.isTrue(result.submitted.endsWith("\x1b[201~\r"));
423 assert.notInclude(result.submitted.slice(0, -1), "\r");
424 for (const line of result.shellInput.slice(0, -1).split("\n")) {
425 assert.isBelow(utf8.encode(line).byteLength, 1_024);
426 }
427 }),
428 );
429​
430 it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
431 Effect.gen(function* () {
432 const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
433 assert.deepEqual(result.lines, ["direct"]);
434 assert.equal(result.exitCode, 0);
435 }),
436 );
437​
438 it.live.each([
439 { name: "an explicit exit", command: "exit 7", exitCode: 7 },
440 { name: "a syntax error", command: "if then", exitCode: 2 },
441 ])("reports a nonzero completion for $name", ({ command, exitCode }) =>
442 Effect.gen(function* () {
443 const result = yield* runObservedSetup(command);
444 assert.equal(result.exitCode, exitCode);
445 }),
446 );
447});