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 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 if (result.status !== "started" || result.commandWritten === undefined) {
206 return yield* Effect.die("the run reports no command write");
207 }
208 const written = yield* Effect.forkChild(result.commandWritten);
209
210 yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
211 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
212 yield* TestClock.adjust("1 minute");
213 expect(yield* Queue.size(writes)).toBe(0);
214 expect(written.pollUnsafe()).toBeUndefined();
215 expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
216
217 yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
218 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
219 const command = yield* Queue.take(writes);
220 expect(command).toContain("vp i");
221 expect(yield* Fiber.join(written)).toBe(true);
222 const sentinel = command.match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0];
223 expect(sentinel).toBeDefined();
224 yield* emit({ ...event, type: "output", data: `${sentinel}0\r\n% ` });
225 expect(yield* completion).toMatchObject({ exitCode: 0 });
226 }),
227 );
228
229 it.effect("closes a successful settle shell even while its prompt is still busy", () =>
230 Effect.gen(function* () {
231 const { result, completion, writes, emit, closed } = yield* setup({ trigger: "settle" });
232 if (result.status !== "started") return yield* Effect.die("settle did not start");
233 const settleEvent = { ...event, terminalId: result.terminalId };
234 yield* emit({ ...settleEvent, type: "output", data: "% \x1b[?2004h" });
235 const sentinel = (yield* Queue.take(writes)).match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0];
236 // No prompt follows: the prompt hook is still running when the wait for it ends.
237 yield* emit({ ...settleEvent, type: "output", data: `\r\n${sentinel}0\r\n` });
238 const done = yield* completion.pipe(Effect.forkChild({ startImmediately: true }));
239 yield* TestClock.adjust("1 second");
240 expect(yield* Fiber.join(done)).toMatchObject({ exitCode: 0 });
241 expect(closed).toEqual([result.terminalId]);
242 }),
243 );
244
245 it.effect("drops whole escape sequences from output lines", () =>
246 Effect.gen(function* () {
247 const { outputLines, emit } = yield* setup();
248 yield* emit({
249 ...event,
250 type: "output",
251 data: "\x1b7\x1b[24;0fProgress: [ 40%]\x1b8\r\n\x1b%G\x1b#8\x1b[4:3mdone\x1bM\r\n",
252 });
253 expect(yield* Queue.takeAll(outputLines)).toEqual(["Progress: [ 40%]", "done"]);
254 }),
255 );
256
257 it.effect("keeps emoji whole when capping a long output line or partial-line buffer", () =>
258 Effect.gen(function* () {
259 const { outputLines, emit } = yield* setup();
260 yield* emit({ ...event, type: "output", data: `x${"🙂".repeat(250)}\r\n` });
261 yield* emit({ ...event, type: "output", data: `${"🙂".repeat(2_100)}x` });
262 yield* emit({ ...event, type: "output", data: "\r\n" });
263 expect(yield* Queue.takeAll(outputLines)).toEqual([`x${"🙂".repeat(199)}`, "🙂".repeat(200)]);
264 }),
265 );
266
267 it.effect("types into a quiet shell that has no line editor and completes at its prompt", () =>
268 Effect.gen(function* () {
269 const { writes, emit, completion } = yield* setup({
270 command: "printf '%s\\n' 'setup-ready'\n".repeat(120),
271 });
272 yield* TestClock.adjust("3 seconds");
273 const submitted = yield* Queue.take(writes);
274 expect(submitted).toContain("setup-ready");
275 expect(submitted).not.toContain("\x1b[200~");
276
277 // A program the script ran left bracketed paste off; this shell's prompt never turns it on.
278 const sentinel = submitted.match(/__T3_SETUP_DONE___[a-f0-9]+:/)?.[0];
279 yield* emit({
280 ...event,
281 type: "output",
282 data: `\x1b[?2004h\x1b[?2004l\r\n${sentinel}0\r\n$ `,
283 });
284 const done = yield* completion.pipe(Effect.forkChild({ startImmediately: true }));
285 yield* TestClock.adjust("999 millis");
286 expect(done.pollUnsafe()).toBeDefined();
287 }),
288 );
289
290 it.effect("ignores line editor state restored from an earlier shell", () =>
291 Effect.gen(function* () {
292 const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
293 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
294 yield* TestClock.adjust("1 minute");
295 expect(yield* Queue.size(writes)).toBe(0);
296 }),
297 );
298
299 it.effect("forgets a busy startup child when the shell restarts", () =>
300 Effect.gen(function* () {
301 const { writes, emit } = yield* setup();
302 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
303 yield* TestClock.adjust("1 minute");
304 expect(yield* Queue.size(writes)).toBe(0);
305 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
306 // The restart lands inside a quiet window, so the next full window decides.
307 yield* TestClock.adjust("6 seconds");
308 expect(yield* Queue.take(writes)).toContain("vp i");
309 }),
310 );
311
312 it.effect.each(["opening", "completion"] as const)(
313 "stops pending setup when cancelled during %s",
314 (phase) =>
315 Effect.gen(function* () {
316 const opening = yield* Deferred.make<void>();
317 const { start, listeners, writes, emit } = yield* makeHarness(
318 phase === "opening" ? { opening } : {},
319 );
320 const pending =
321 phase === "opening"
322 ? start.pipe(Effect.asVoid)
323 : yield* start.pipe(
324 Effect.map((result) =>
325 result.status === "started" && result.completion
326 ? result.completion.pipe(Effect.asVoid)
327 : Effect.die("setup did not start"),
328 ),
329 );
330 const fiber = yield* pending.pipe(Effect.forkChild({ startImmediately: true }));
331 if (phase === "opening") yield* Deferred.await(opening);
332 expect(listeners.size).toBe(2);
333 yield* Fiber.interrupt(fiber);
334 expect(listeners.size).toBe(0);
335 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
336 expect(yield* Queue.size(writes)).toBe(0);
337 }),
338 );
339
340 it.effect.each([false, true])(
341 "does not type into a shell that exits during startup (before shell lookup: %s)",
342 (beforeShellLookup) =>
343 Effect.gen(function* () {
344 const { result, completion, writes, emit, listeners } = yield* setup(
345 beforeShellLookup ? { shell: null } : {},
346 );
347 if (!beforeShellLookup) {
348 yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
349 }
350 expect(yield* completion).toMatchObject({ exitCode: null });
351 expect(result.status === "started" && (yield* result.commandWritten!)).toBe(false);
352 yield* TestClock.adjust("1 minute");
353 expect(yield* Queue.size(writes)).toBe(0);
354 expect(listeners.size).toBe(0);
355 }),
356 );
357});
358
359const runObservedSetup = Effect.fnUntraced(function* (command: string) {
360 const { writes, outputLines, emit, completion } = yield* setup({ command });
361 yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
362 const submitted = yield* Queue.take(writes);
363 const shellInput = submitted.replace("\x1b[200~", "").replace("\x1b[201~", "");
364 const cwd = yield* HostProcess.WorkingDirectory;
365 const env = yield* HostProcess.Environment;
366
367 // Enter becomes a newline at the terminal boundary; transport assertions below
368 // cover line-editor submissions and canonical TTY limits that bash -c bypasses.
369 const child = yield* Effect.gen(function* () {
370 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
371 const handle = yield* spawner.spawn(
372 ChildProcess.make(
373 "/bin/bash",
374 ["--noprofile", "--norc", "-c", shellInput.replaceAll("\r", "\n")],
375 {
376 cwd,
377 env: { PATH: env.PATH },
378 },
379 ),
380 );
381 return yield* Effect.all(
382 {
383 stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
384 stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
385 exitCode: handle.exitCode,
386 },
387 { concurrency: "unbounded" },
388 );
389 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
390 yield* emit({ ...event, type: "output", data: submitted + "\n" });
391 yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
392 yield* emit({ ...event, type: "closed" });
393 return {
394 submitted,
395 shellInput,
396 lines: yield* Queue.clear(outputLines),
397 exitCode: (yield* completion).exitCode,
398 };
399});
400
401describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
402 it.live("submits one line while preserving multiline shell syntax and literal text", () =>
403 Effect.gen(function* () {
404 const result = yield* runObservedSetup(
405 [
406 "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
407 "cat <<'END'",
408 "$literal \\path 雪",
409 "END",
410 "printf '%s\\n' done # trailing comment",
411 ].join("\r\n"),
412 );
413 assert.equal(result.submitted.at(-1), "\r");
414 assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
415 assert.deepEqual(result.lines, [
416 "it's ready",
417 "literal \\n $(printf wrong) `printf wrong` café",
418 "$literal \\path 雪",
419 "done",
420 ]);
421 assert.equal(result.exitCode, 0);
422 }),
423 );
424
425 it.live("completes long scripts without exceeding canonical terminal line limits", () =>
426 Effect.gen(function* () {
427 const expected = Array.from(
428 { length: 120 },
429 (_, index) => `line-${index}: café 雪 'quoted' \\path`,
430 );
431 const command = expected
432 .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
433 .join("\n");
434 const utf8 = new TextEncoder();
435 assert.isAbove(utf8.encode(command).byteLength, 4_096);
436
437 const result = yield* runObservedSetup(command);
438 assert.deepEqual(result.lines, expected);
439 assert.equal(result.exitCode, 0);
440 assert.equal(result.submitted.at(-1), "\r");
441 assert.isTrue(result.submitted.startsWith(" \x1b[200~"));
442 assert.isTrue(result.submitted.endsWith("\x1b[201~\r"));
443 assert.notInclude(result.submitted.slice(0, -1), "\r");
444 for (const line of result.shellInput.slice(0, -1).split("\n")) {
445 assert.isBelow(utf8.encode(line).byteLength, 1_024);
446 }
447 }),
448 );
449
450 it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
451 Effect.gen(function* () {
452 const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
453 assert.deepEqual(result.lines, ["direct"]);
454 assert.equal(result.exitCode, 0);
455 }),
456 );
457
458 it.live.each([
459 { name: "an explicit exit", command: "exit 7", exitCode: 7 },
460 { name: "a syntax error", command: "if then", exitCode: 2 },
461 ])("reports a nonzero completion for $name", ({ command, exitCode }) =>
462 Effect.gen(function* () {
463 const result = yield* runObservedSetup(command);
464 assert.equal(result.exitCode, exitCode);
465 }),
466 );
467});