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("types into a quiet shell that has no line editor", () =>
176 Effect.gen(function* () {
177 const { writes } = yield* setup();
178 yield* TestClock.adjust("3 seconds");
179 expect(yield* Queue.take(writes)).toContain("vp i");
180 }),
181 );
182
183 it.effect("ignores line editor state restored from an earlier shell", () =>
184 Effect.gen(function* () {
185 const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
186 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
187 yield* TestClock.adjust("1 minute");
188 expect(yield* Queue.size(writes)).toBe(0);
189 }),
190 );
191
192 it.effect("forgets a busy startup child when the shell restarts", () =>
193 Effect.gen(function* () {
194 const { writes, emit } = yield* setup();
195 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
196 yield* TestClock.adjust("1 minute");
197 expect(yield* Queue.size(writes)).toBe(0);
198 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
199 // The restart lands inside a quiet window, so the next full window decides.
200 yield* TestClock.adjust("6 seconds");
201 expect(yield* Queue.take(writes)).toContain("vp i");
202 }),
203 );
204
205 it.effect("drops its terminal listeners when cancelled while the terminal opens", () =>
206 Effect.gen(function* () {
207 const opening = yield* Deferred.make<void>();
208 const { start, listeners } = yield* makeHarness({ opening });
209 const fiber = yield* Effect.forkChild(start);
210 yield* Deferred.await(opening);
211 expect(listeners.size).toBe(2);
212 yield* Fiber.interrupt(fiber);
213 expect(listeners.size).toBe(0);
214 }),
215 );
216
217 it.effect.each([false, true])(
218 "does not type into a shell that exits during startup (before shell lookup: %s)",
219 (beforeShellLookup) =>
220 Effect.gen(function* () {
221 const { completion, writes, emit, listeners } = yield* setup(
222 beforeShellLookup ? { shell: null } : {},
223 );
224 if (!beforeShellLookup) {
225 yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
226 }
227 expect(yield* completion).toMatchObject({ exitCode: null });
228 yield* TestClock.adjust("1 minute");
229 expect(yield* Queue.size(writes)).toBe(0);
230 expect(listeners.size).toBe(0);
231 }),
232 );
233});
234
235const runObservedSetup = Effect.fnUntraced(function* (command: string) {
236 const { writes, outputLines, emit, completion } = yield* setup({ command });
237 yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
238 const submitted = yield* Queue.take(writes);
239 const cwd = yield* HostProcess.WorkingDirectory;
240 const env = yield* HostProcess.Environment;
241
242 // Enter becomes a newline at the terminal boundary; transport assertions below
243 // cover line-editor submissions and canonical TTY limits that bash -c bypasses.
244 const child = yield* Effect.gen(function* () {
245 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
246 const handle = yield* spawner.spawn(
247 ChildProcess.make(
248 "/bin/bash",
249 ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")],
250 {
251 cwd,
252 env: { PATH: env.PATH },
253 },
254 ),
255 );
256 return yield* Effect.all(
257 {
258 stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
259 stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
260 exitCode: handle.exitCode,
261 },
262 { concurrency: "unbounded" },
263 );
264 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
265 yield* emit({ ...event, type: "output", data: submitted + "\n" });
266 yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
267 yield* emit({ ...event, type: "closed" });
268 return {
269 submitted,
270 lines: yield* Queue.clear(outputLines),
271 exitCode: (yield* completion).exitCode,
272 };
273});
274
275describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
276 it.live("submits one line while preserving multiline shell syntax and literal text", () =>
277 Effect.gen(function* () {
278 const result = yield* runObservedSetup(
279 [
280 "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
281 "cat <<'END'",
282 "$literal \\path 雪",
283 "END",
284 "printf '%s\\n' done # trailing comment",
285 ].join("\r\n"),
286 );
287 assert.equal(result.submitted.at(-1), "\r");
288 assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
289 assert.deepEqual(result.lines, [
290 "it's ready",
291 "literal \\n $(printf wrong) `printf wrong` café",
292 "$literal \\path 雪",
293 "done",
294 ]);
295 assert.equal(result.exitCode, 0);
296 }),
297 );
298
299 it.live("completes long scripts without exceeding canonical terminal line limits", () =>
300 Effect.gen(function* () {
301 const expected = Array.from(
302 { length: 120 },
303 (_, index) => `line-${index}: café 雪 'quoted' \\path`,
304 );
305 const command = expected
306 .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
307 .join("\n");
308 const utf8 = new TextEncoder();
309 assert.isAbove(utf8.encode(command).byteLength, 4_096);
310
311 const result = yield* runObservedSetup(command);
312 assert.deepEqual(result.lines, expected);
313 assert.equal(result.exitCode, 0);
314 assert.equal(result.submitted.at(-1), "\r");
315 assert.notInclude(result.submitted, "\n");
316 // The runner can write before the shell switches the terminal out of canonical mode.
317 for (const line of result.submitted.slice(0, -1).split("\r")) {
318 assert.isBelow(utf8.encode(line).byteLength, 1_024);
319 }
320 }),
321 );
322
323 it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
324 Effect.gen(function* () {
325 const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
326 assert.deepEqual(result.lines, ["direct"]);
327 assert.equal(result.exitCode, 0);
328 }),
329 );
330
331 it.live.each([
332 { name: "an explicit exit", command: "exit 7", exitCode: 7 },
333 { name: "a syntax error", command: "if then", exitCode: 2 },
334 ])("reports a nonzero completion for $name", ({ command, exitCode }) =>
335 Effect.gen(function* () {
336 const result = yield* runObservedSetup(command);
337 assert.equal(result.exitCode, exitCode);
338 }),
339 );
340});