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