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

ProjectSetupScriptRunner.test.ts

201 lines7.4 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import { describe, expect, it } from "@effect/vitest";
3import {
4 ProjectId,
5 TerminalNotRunningError,
6 type TerminalEvent,
7 type TerminalSessionSnapshot,
8} from "@t3tools/contracts";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as Queue from "effect/Queue";
14import { TestClock } from "effect/testing";
15​
16import * as ServerSettings from "../serverSettings.ts";
17import * as TerminalManager from "../terminal/Manager.ts";
18import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
19import * as ProjectService from "./ProjectService.ts";
20import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
21​
22const threadId = "thread-1";
23const terminalId = "setup-setup";
24const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" };
25​
26const openSnapshot = (history: string): TerminalSessionSnapshot => ({
27 threadId,
28 terminalId,
29 cwd: "/repo/.t3/worktrees/feature",
30 worktreePath: null,
31 status: "running",
32 pid: 123,
33 history,
34 exitCode: null,
35 exitSignal: null,
36 label: "zsh",
37 updatedAt: "2026-01-01T00:00:00.000Z",
38});
39​
40const makeHarness = Effect.fn(function* (options: {
41 readonly history?: string;
42 readonly opening?: Deferred.Deferred<void>;
43 readonly shell?: string | null;
44}) {
45 const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
46 const writes = yield* Queue.unbounded<string>();
47 const outputLines = yield* Queue.unbounded<string>();
48 const terminals = Layer.mock(TerminalManager.TerminalManager)({
49 open: () =>
50 (options.opening
51 ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
52 : Effect.void
53 ).pipe(Effect.as(openSnapshot(options.history ?? ""))),
54 getShell: () =>
55 options.shell === null
56 ? Effect.fail(new TerminalNotRunningError({ threadId, terminalId }))
57 : Effect.succeed(options.shell ?? "/bin/zsh"),
58 subscribe: (listener) =>
59 Effect.sync(() => {
60 listeners.add(listener);
61 return () => listeners.delete(listener);
62 }),
63 write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
64 closeIdle: () => Effect.void,
65 closeOnSettle: () => Effect.void,
66 });
67 const runner = yield* ProjectSetupScriptRunner.make.pipe(
68 Effect.provide(
69 Layer.mergeAll(
70 terminals,
71 Layer.mock(ProjectService.ProjectService)({}),
72 Layer.mock(ProjectionStore.ProjectionStoreV2)({
73 getThreadShell: () => Effect.succeed(null),
74 }),
75 ServerSettings.layerTest(),
76 NodeCrypto.layer,
77 ),
78 ),
79 );
80 const start = runner.runForThread({
81 threadId,
82 worktreePath: "/repo/.t3/worktrees/feature",
83 observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
84 project: {
85 id: ProjectId.make("project-1"),
86 workspaceRoot: "/repo",
87 scripts: [
88 {
89 id: "setup",
90 name: "Setup",
91 command: "vp i",
92 icon: "configure",
93 runOnWorktreeCreate: true,
94 },
95 ],
96 },
97 });
98 const emit = (terminalEvent: TerminalEvent) =>
99 Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
100 return { start, listeners, writes, outputLines, emit };
101});
102​
103const setup = Effect.fn(function* (
104 options: {
105 readonly history?: string;
106 readonly shell?: string | null;
107 } = {},
108) {
109 const harness = yield* makeHarness(options);
110 const result = yield* harness.start;
111 const completion = result.status === "started" ? result.completion : undefined;
112 if (!completion) return yield* Effect.die("setup did not start an observed run");
113 return { ...harness, result, completion };
114});
115​
116describe("ProjectSetupScriptRunner", () => {
117 it.effect("writes immediately when the spawned fallback is PowerShell", () =>
118 Effect.gen(function* () {
119 const { writes } = yield* setup({
120 shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
121 });
122 expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE");
123 }),
124 );
125​
126 it.effect("shows a startup prompt and types only once the line editor starts", () =>
127 Effect.gen(function* () {
128 const { result, writes, outputLines, emit } = yield* setup();
129 expect(result).toMatchObject({ status: "started", terminalId });
130​
131 yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
132 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
133 yield* TestClock.adjust("1 minute");
134 expect(yield* Queue.size(writes)).toBe(0);
135 expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
136​
137 yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
138 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
139 expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
140 }),
141 );
142​
143 it.effect("types into a quiet shell that has no line editor", () =>
144 Effect.gen(function* () {
145 const { writes } = yield* setup();
146 yield* TestClock.adjust("3 seconds");
147 expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
148 }),
149 );
150​
151 it.effect("ignores line editor state restored from an earlier shell", () =>
152 Effect.gen(function* () {
153 const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
154 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
155 yield* TestClock.adjust("1 minute");
156 expect(yield* Queue.size(writes)).toBe(0);
157 }),
158 );
159​
160 it.effect("forgets a busy startup child when the shell restarts", () =>
161 Effect.gen(function* () {
162 const { writes, emit } = yield* setup();
163 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
164 yield* TestClock.adjust("1 minute");
165 expect(yield* Queue.size(writes)).toBe(0);
166 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
167 // The restart lands inside a quiet window, so the next full window decides.
168 yield* TestClock.adjust("6 seconds");
169 expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/);
170 }),
171 );
172​
173 it.effect("drops its terminal listeners when cancelled while the terminal opens", () =>
174 Effect.gen(function* () {
175 const opening = yield* Deferred.make<void>();
176 const { start, listeners } = yield* makeHarness({ opening });
177 const fiber = yield* Effect.forkChild(start);
178 yield* Deferred.await(opening);
179 expect(listeners.size).toBe(2);
180 yield* Fiber.interrupt(fiber);
181 expect(listeners.size).toBe(0);
182 }),
183 );
184​
185 it.effect.each([false, true])(
186 "does not type into a shell that exits during startup (before shell lookup: %s)",
187 (beforeShellLookup) =>
188 Effect.gen(function* () {
189 const { completion, writes, emit, listeners } = yield* setup(
190 beforeShellLookup ? { shell: null } : {},
191 );
192 if (!beforeShellLookup) {
193 yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
194 }
195 expect(yield* completion).toMatchObject({ exitCode: null });
196 yield* TestClock.adjust("1 minute");
197 expect(yield* Queue.size(writes)).toBe(0);
198 expect(listeners.size).toBe(0);
199 }),
200 );
201});