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