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