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

ProjectSetupScriptRunner.test.ts

481 lines16.5 KB

1import { describe, expect, it, vi } from "@effect/vitest";
2import { type OrchestrationProject, ProjectId, type TerminalEvent } from "@t3tools/contracts";
3import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8​
9import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
10import * as ServerSettings from "../serverSettings.ts";
11import * as TerminalManager from "../terminal/Manager.ts";
12import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
13​
14const isProjectSetupScriptOperationError = Schema.is(
15 ProjectSetupScriptRunner.ProjectSetupScriptOperationError,
16);
17​
18const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationProject => ({
19 id: ProjectId.make("project-1"),
20 title: "Project",
21 workspaceRoot: "/repo/project",
22 defaultModelSelection: null,
23 scripts,
24 createdAt: "2026-01-01T00:00:00.000Z",
25 updatedAt: "2026-01-01T00:00:00.000Z",
26 deletedAt: null,
27});
28​
29const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
30 Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
31 getUserInputActivity: () => Effect.die("unused"),
32 getCommandReadModel: () => Effect.die("unused"),
33 getSnapshot: () => Effect.die("unused"),
34 getShellSnapshot: () => Effect.die("unused"),
35 getArchivedShellSnapshot: () => Effect.die("unused"),
36 getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
37 getCounts: () => Effect.die("unused"),
38 getEventReplayStats: () => Effect.die("unused"),
39 getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
40 Effect.succeed(
41 workspaceRoot === project.workspaceRoot ? Option.some(project) : Option.none(),
42 ),
43 getProjectShells: () => Effect.die("unused"),
44 getProjectShellById: (projectId) =>
45 Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
46 getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
47 getImportedAgentSessionSources: () => Effect.die("unused"),
48 getThreadCheckpointContext: () => Effect.die("unused"),
49 getFullThreadDiffContext: () => Effect.die("unused"),
50 getThreadRuntimeContext: () => Effect.die("unused"),
51 getTurnStartMessage: () => Effect.die("unused"),
52 getThreadShellById: () => Effect.die("unused"),
53 getThreadDetailById: () => Effect.die("unused"),
54 getThreadDetailSnapshot: () => Effect.die("unused"),
55 searchThreads: () => Effect.succeed({ matches: [] }),
56 });
57​
58type TerminalOverrides = Pick<TerminalManager.TerminalManager["Service"], "open" | "write"> &
59 Partial<Pick<TerminalManager.TerminalManager["Service"], "subscribe">>;
60​
61const makeTerminalManagerLayer = (overrides: TerminalOverrides) =>
62 Layer.succeed(TerminalManager.TerminalManager, {
63 attachStream: () => Effect.die(new Error("unused")),
64 resize: () => Effect.void,
65 clear: () => Effect.void,
66 restart: () => Effect.die(new Error("unused")),
67 close: () => Effect.void,
68 subscribe: () => Effect.succeed(() => undefined),
69 subscribeMetadata: () => Effect.succeed(() => undefined),
70 ...overrides,
71 });
72​
73const testLayer = (
74 project: OrchestrationProject,
75 terminal: TerminalOverrides,
76 settings = ServerSettings.layerTest(),
77) =>
78 ProjectSetupScriptRunner.layer.pipe(
79 Layer.provideMerge(makeProjectionSnapshotQueryLayer(project)),
80 Layer.provideMerge(makeTerminalManagerLayer(terminal)),
81 Layer.provide(settings),
82 );
83​
84describe("ProjectSetupScriptRunner", () => {
85 it.effect("runs the inherited machine setup action in the checkout's worktree", () => {
86 const open = vi.fn(() =>
87 Effect.succeed({
88 threadId: "thread-1",
89 terminalId: "setup-default-setup",
90 cwd: "/repo/worktrees/a",
91 worktreePath: "/repo/worktrees/a",
92 status: "running" as const,
93 pid: 123,
94 history: "",
95 exitCode: null,
96 exitSignal: null,
97 label: "setup-default-setup",
98 updatedAt: "2026-01-01T00:00:00.000Z",
99 }),
100 );
101 const write = vi.fn(() => Effect.void);
102 return Effect.gen(function* () {
103 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
104 const result = yield* runner.runForThread({
105 threadId: "thread-1",
106 projectId: "project-1",
107 worktreePath: "/repo/worktrees/a",
108 });
109 expect(result).toMatchObject({ status: "started", scriptId: "default-setup" });
110 expect(open).toHaveBeenCalledWith({
111 threadId: "thread-1",
112 terminalId: "setup-default-setup",
113 cwd: "/repo/worktrees/a",
114 worktreePath: "/repo/worktrees/a",
115 env: {
116 T3CODE_PROJECT_ROOT: "/repo/project",
117 T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
118 NO_COLOR: "1",
119 FORCE_COLOR: "0",
120 },
121 });
122 expect(write).toHaveBeenCalledWith({
123 threadId: "thread-1",
124 terminalId: "setup-default-setup",
125 data: "npm install\r",
126 });
127 }).pipe(
128 Effect.provide(
129 testLayer(
130 makeProject([]),
131 { open, write },
132 ServerSettings.layerTest({
133 defaultProjectScripts: [
134 {
135 id: "default-setup",
136 name: "Setup",
137 command: "npm install",
138 icon: "configure",
139 runOnWorktreeCreate: true,
140 },
141 ],
142 }),
143 ),
144 ),
145 );
146 });
147​
148 it.effect("returns no-script when no setup script exists", () => {
149 const open = vi.fn(() => Effect.die("unexpected open"));
150 const write = vi.fn(() => Effect.die("unexpected write"));
151 const project = makeProject([]);
152​
153 return Effect.gen(function* () {
154 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
155 const result = yield* runner.runForThread({
156 threadId: "thread-1",
157 projectId: "project-1",
158 worktreePath: "/repo/worktrees/a",
159 });
160​
161 expect(result).toEqual({ status: "no-script" });
162 expect(open).not.toHaveBeenCalled();
163 expect(write).not.toHaveBeenCalled();
164 }).pipe(Effect.provide(testLayer(project, { open, write })));
165 });
166​
167 it.effect(
168 "opens the deterministic setup terminal with worktree env and writes the command",
169 () => {
170 const open = vi.fn(() =>
171 Effect.succeed({
172 threadId: "thread-1",
173 terminalId: "setup-setup",
174 cwd: "/repo/worktrees/a",
175 worktreePath: "/repo/worktrees/a",
176 status: "running" as const,
177 pid: 123,
178 history: "",
179 exitCode: null,
180 exitSignal: null,
181 label: "setup-setup",
182 updatedAt: "2026-01-01T00:00:00.000Z",
183 }),
184 );
185 const write = vi.fn(() => Effect.void);
186 const project = makeProject([
187 {
188 id: "setup",
189 name: "Setup",
190 command: "bun install",
191 icon: "configure",
192 runOnWorktreeCreate: true,
193 },
194 ]);
195​
196 return Effect.gen(function* () {
197 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
198 const result = yield* runner.runForThread({
199 threadId: "thread-1",
200 projectCwd: "/repo/project",
201 worktreePath: "/repo/worktrees/a",
202 });
203​
204 expect(result).toEqual({
205 status: "started",
206 scriptId: "setup",
207 scriptName: "Setup",
208 scriptCommand: "bun install",
209 terminalId: "setup-setup",
210 cwd: "/repo/worktrees/a",
211 async: true,
212 });
213 expect(open).toHaveBeenCalledWith({
214 threadId: "thread-1",
215 terminalId: "setup-setup",
216 cwd: "/repo/worktrees/a",
217 worktreePath: "/repo/worktrees/a",
218 env: {
219 NO_COLOR: "1",
220 FORCE_COLOR: "0",
221 T3CODE_PROJECT_ROOT: "/repo/project",
222 T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
223 },
224 });
225 expect(write).toHaveBeenCalledWith({
226 threadId: "thread-1",
227 terminalId: "setup-setup",
228 data: "bun install\r",
229 });
230 }).pipe(Effect.provide(testLayer(project, { open, write })));
231 },
232 );
233​
234 it.effect(
235 "wraps the command with a completion sentinel and resolves the exit code from terminal output",
236 () => {
237 const open = vi.fn(() =>
238 Effect.succeed({
239 threadId: "thread-1",
240 terminalId: "setup-setup",
241 cwd: "/repo/worktrees/a",
242 worktreePath: "/repo/worktrees/a",
243 status: "running" as const,
244 pid: 123,
245 history: "",
246 exitCode: null,
247 exitSignal: null,
248 label: "setup-setup",
249 updatedAt: "2026-01-01T00:00:00.000Z",
250 }),
251 );
252 const writes: string[] = [];
253 const write = vi.fn((input: { data: string }) =>
254 Effect.sync(() => void writes.push(input.data)),
255 );
256 let listener: ((event: TerminalEvent) => Effect.Effect<void>) | null = null;
257 const subscribe = vi.fn((next: (event: TerminalEvent) => Effect.Effect<void>) => {
258 listener = next;
259 return Effect.succeed(() => {
260 listener = null;
261 });
262 });
263 const project = makeProject([
264 {
265 id: "setup",
266 name: "Setup",
267 command: "bun install",
268 icon: "configure",
269 runOnWorktreeCreate: true,
270 },
271 ]);
272 const emit = (data: string) =>
273 Effect.suspend(() =>
274 listener
275 ? listener({ threadId: "thread-1", terminalId: "setup-setup", type: "output", data })
276 : Effect.void,
277 );
278​
279 return Effect.gen(function* () {
280 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
281 const seen: string[] = [];
282 const result = yield* runner.runForThread({
283 threadId: "thread-1",
284 projectCwd: "/repo/project",
285 worktreePath: "/repo/worktrees/a",
286 observeCompletion: {
287 onOutputLine: (line) => Effect.sync(() => void seen.push(line)),
288 },
289 });
290 expect(result.status).toBe("started");
291 if (result.status !== "started") return;
292 expect(result.completion).toBeDefined();
293​
294 // The subscription is attached before the command is written.
295 expect(subscribe).toHaveBeenCalledTimes(1);
296 expect(writes).toHaveLength(1);
297 // The block closes on its own line so a trailing comment in the
298 // command cannot swallow the sentinel, and the sentinel carries a
299 // per-run token so script output cannot spoof it.
300 const written = writes[0] ?? "";
301 const sentinel = /__T3_SETUP_DONE___[0-9a-f]{32}:/.exec(written)?.[0];
302 expect(sentinel).toBeDefined();
303 expect(written).toBe(`( bun install\r); printf '\\n${sentinel}%s\\n' "$?"\r`);
304​
305 // Output arrives in chunks; partial lines are buffered until a newline,
306 // control sequences are stripped, and the echoed wrapper is hidden.
307 yield* emit(`( bun install\r\n> ); printf '\\n${sentinel}%s\\n' "$?"\r\n`);
308 yield* emit("\u001b[32mResolving");
309 yield* emit(" deps\u001b[0m\r\nDone in 2s\r\n");
310 // A spoofed sentinel from the script itself must not settle completion.
311 yield* emit("__T3_SETUP_DONE__:0\r\n");
312 yield* emit(`__T3_SETUP_DONE___${"0".repeat(32)}:0\r\n`);
313 yield* emit(`${sentinel}3\r\n`);
314​
315 const completion = yield* result.completion!;
316 expect(completion.exitCode).toBe(3);
317 expect(seen).toEqual([
318 "Resolving deps",
319 "Done in 2s",
320 "__T3_SETUP_DONE__:0",
321 `__T3_SETUP_DONE___${"0".repeat(32)}:0`,
322 ]);
323 // The subscription is torn down once the sentinel arrives.
324 expect(listener).toBeNull();
325 }).pipe(
326 Effect.provide(testLayer(project, { open, write, subscribe })),
327 Effect.provideService(HostProcessPlatform, "linux"),
328 Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
329 );
330 },
331 );
332​
333 it.effect("unsubscribes from terminal output when the command cannot be written", () => {
334 const open = vi.fn(() =>
335 Effect.succeed({
336 threadId: "thread-1",
337 terminalId: "setup-setup",
338 cwd: "/repo/worktrees/a",
339 worktreePath: "/repo/worktrees/a",
340 status: "running" as const,
341 pid: 123,
342 history: "",
343 exitCode: null,
344 exitSignal: null,
345 label: "setup-setup",
346 updatedAt: "2026-01-01T00:00:00.000Z",
347 }),
348 );
349 const write = vi.fn(() =>
350 Effect.fail(
351 new TerminalManager.TerminalCwdStatError({ cwd: "/repo/worktrees/a", cause: {} }),
352 ),
353 );
354 const unsubscribe = vi.fn();
355 const subscribe = vi.fn(() => Effect.succeed(unsubscribe));
356 const project = makeProject([
357 {
358 id: "setup",
359 name: "Setup",
360 command: "bun install",
361 icon: "configure",
362 runOnWorktreeCreate: true,
363 },
364 ]);
365​
366 return Effect.gen(function* () {
367 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
368 const result = yield* runner
369 .runForThread({
370 threadId: "thread-1",
371 projectCwd: "/repo/project",
372 worktreePath: "/repo/worktrees/a",
373 observeCompletion: {},
374 })
375 .pipe(Effect.result);
376 expect(result._tag).toBe("Failure");
377 expect(unsubscribe).toHaveBeenCalledTimes(1);
378 }).pipe(Effect.provide(testLayer(project, { open, write, subscribe })));
379 });
380​
381 it.effect.each([
382 {
383 shell: "/usr/bin/fish",
384 expected:
385 /^begin\rbun install\rend; printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' \$status\r$/,
386 },
387 {
388 shell: "/bin/bash",
389 expected: /^\( bun install\r\); printf '\\n__T3_SETUP_DONE___[0-9a-f]{32}:%s\\n' "\$\?"\r$/,
390 },
391 ])("wraps the command for the $shell syntax", ({ shell, expected }) => {
392 const open = vi.fn(() =>
393 Effect.succeed({
394 threadId: "thread-1",
395 terminalId: "setup-setup",
396 cwd: "/repo/worktrees/a",
397 worktreePath: "/repo/worktrees/a",
398 status: "running" as const,
399 pid: 123,
400 history: "",
401 exitCode: null,
402 exitSignal: null,
403 label: "setup-setup",
404 updatedAt: "2026-01-01T00:00:00.000Z",
405 }),
406 );
407 const writes: string[] = [];
408 const write = vi.fn((input: { data: string }) =>
409 Effect.sync(() => void writes.push(input.data)),
410 );
411 const project = makeProject([
412 {
413 id: "setup",
414 name: "Setup",
415 command: "bun install",
416 icon: "configure",
417 runOnWorktreeCreate: true,
418 },
419 ]);
420 return Effect.gen(function* () {
421 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
422 yield* runner.runForThread({
423 threadId: "thread-1",
424 projectCwd: "/repo/project",
425 worktreePath: "/repo/worktrees/a",
426 observeCompletion: {},
427 });
428 expect(writes).toHaveLength(1);
429 expect(writes[0]).toMatch(expected);
430 }).pipe(
431 Effect.provide(testLayer(project, { open, write })),
432 Effect.provideService(HostProcessPlatform, "linux"),
433 Effect.provideService(HostProcessEnvironment, { SHELL: shell }),
434 );
435 });
436​
437 it.effect("keeps terminal failures as the exact cause of a structured operation error", () => {
438 const rootCause = new Error("stat failed");
439 const terminalError = new TerminalManager.TerminalCwdStatError({
440 cwd: "/repo/worktrees/a",
441 cause: rootCause,
442 });
443 const project = makeProject([
444 {
445 id: "setup",
446 name: "Setup",
447 command: "bun install",
448 icon: "configure",
449 runOnWorktreeCreate: true,
450 },
451 ]);
452​
453 return Effect.gen(function* () {
454 const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
455 const error = yield* runner
456 .runForThread({
457 threadId: "thread-1",
458 projectId: "project-1",
459 worktreePath: "/repo/worktrees/a",
460 })
461 .pipe(Effect.flip);
462​
463 expect(isProjectSetupScriptOperationError(error)).toBe(true);
464 if (isProjectSetupScriptOperationError(error)) {
465 expect(error.operation).toBe("openTerminal");
466 expect(error.threadId).toBe("thread-1");
467 expect(error.projectId).toBe("project-1");
468 expect(error.worktreePath).toBe("/repo/worktrees/a");
469 expect(error.cause).toBe(terminalError);
470 expect(terminalError.cause).toBe(rootCause);
471 }
472 }).pipe(
473 Effect.provide(
474 testLayer(project, {
475 open: () => Effect.fail(terminalError),
476 write: () => Effect.die("unexpected write"),
477 }),
478 ),
479 );
480 });
481});