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

ProjectSetupScriptRunner.test.ts

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