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