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