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

ProjectSetupScriptRunner.test.ts

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