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