The best way to control Claude Code, Codex and more from any computer or phone

main
ts 365 lines 14.1 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, expect, it } from "@effect/vitest";
4 import {
5 ProjectId,
6 TerminalNotRunningError,
7 type TerminalEvent,
8 type TerminalOpenInput,
9 type TerminalSessionSnapshot,
10 } from "@t3tools/contracts";
11 import * as HostProcess from "@t3tools/shared/HostProcess";
12 import * as Deferred from "effect/Deferred";
13 import * as Effect from "effect/Effect";
14 import * as Fiber from "effect/Fiber";
15 import * as Layer from "effect/Layer";
16 import * as Queue from "effect/Queue";
17 import * as Stream from "effect/Stream";
18 import { ChildProcess, ChildProcessSpawner } from "effect/process";
19 import { TestClock } from "effect/testing";
20
21 import * as ServerSettings from "../serverSettings.ts";
22 import * as TerminalManager from "../terminal/Manager.ts";
23 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
24 import * as ProjectService from "./ProjectService.ts";
25 import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts";
26
27 const threadId = "thread-1";
28 const terminalId = "setup-setup";
29 const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" };
30
31 const openSnapshot = (history: string): TerminalSessionSnapshot => ({
32 threadId,
33 terminalId,
34 cwd: "/repo/.t3/worktrees/feature",
35 worktreePath: null,
36 status: "running",
37 pid: 123,
38 history,
39 exitCode: null,
40 exitSignal: null,
41 label: "zsh",
42 updatedAt: "2026-01-01T00:00:00.000Z",
43 });
44
45 const makeHarness = Effect.fn(function* (options: {
46 readonly command?: string;
47 readonly history?: string;
48 readonly opening?: Deferred.Deferred<void>;
49 readonly shell?: string | null;
50 }) {
51 const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
52 const opens: TerminalOpenInput[] = [];
53 const writes = yield* Queue.unbounded<string>();
54 const outputLines = yield* Queue.unbounded<string>();
55 const terminals = Layer.mock(TerminalManager.TerminalManager)({
56 open: (input) =>
57 Effect.sync(() => opens.push(input)).pipe(
58 Effect.andThen(
59 options.opening
60 ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
61 : Effect.void,
62 ),
63 Effect.as(openSnapshot(options.history ?? "")),
64 ),
65 getShell: () =>
66 options.shell === null
67 ? Effect.fail(new TerminalNotRunningError({ threadId, terminalId }))
68 : Effect.succeed(options.shell ?? "/bin/zsh"),
69 subscribe: (listener) =>
70 Effect.sync(() => {
71 listeners.add(listener);
72 return () => listeners.delete(listener);
73 }),
74 write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid),
75 closeIdle: () => Effect.void,
76 closeOnSettle: () => Effect.void,
77 });
78 const runner = yield* ProjectSetupScriptRunner.make.pipe(
79 Effect.provide(
80 Layer.mergeAll(
81 terminals,
82 Layer.mock(ProjectService.ProjectService)({}),
83 Layer.mock(ProjectionStore.ProjectionStoreV2)({
84 getThreadShell: () => Effect.succeed(null),
85 }),
86 ServerSettings.layerTest(),
87 NodeCrypto.layer,
88 ),
89 ),
90 );
91 const start = runner.runForThread({
92 threadId,
93 worktreePath: "/repo/.t3/worktrees/feature",
94 observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) },
95 project: {
96 id: ProjectId.make("project-1"),
97 workspaceRoot: "/repo",
98 scripts: [
99 {
100 id: "setup",
101 name: "Setup",
102 command: options.command ?? "vp i",
103 icon: "configure",
104 runOnWorktreeCreate: true,
105 },
106 ],
107 },
108 });
109 const emit = (terminalEvent: TerminalEvent) =>
110 Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true });
111 return { start, listeners, writes, outputLines, emit, opens };
112 });
113
114 const setup = Effect.fn(function* (
115 options: {
116 readonly command?: string;
117 readonly history?: string;
118 readonly shell?: string | null;
119 } = {},
120 ) {
121 const harness = yield* makeHarness(options);
122 const result = yield* harness.start;
123 const completion = result.status === "started" ? result.completion : undefined;
124 if (!completion) return yield* Effect.die("setup did not start an observed run");
125 return { ...harness, result, completion };
126 });
127
128 describe("ProjectSetupScriptRunner", () => {
129 it.effect("keeps setup scripts independent of the interactive shell preference", () =>
130 Effect.gen(function* () {
131 const { opens } = yield* setup();
132 expect(opens[0]?.env?.T3CODE_TERMINAL_SHELL).toBe("");
133 }),
134 );
135
136 it.effect("writes immediately when the spawned fallback is PowerShell", () =>
137 Effect.gen(function* () {
138 const { writes } = yield* setup({
139 shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
140 });
141 expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE");
142 }),
143 );
144
145 it.effect("types an escaped Nushell wrapper once its line editor starts", () =>
146 Effect.gen(function* () {
147 const command =
148 'print "quoted"; print \'C:\\tools\'; print "$env.PATH"\nexit 7 # comment\r\n\t';
149 const escaped =
150 'print \\"quoted\\"; print \'C:\\\\tools\'; print \\"$env.PATH\\"\\u{a}exit 7 # comment\\u{d}\\u{a}\\u{9}';
151 const { writes, emit } = yield* setup({ shell: "/opt/homebrew/bin/nu", command });
152 yield* TestClock.adjust("1 second");
153 expect(yield* Queue.size(writes)).toBe(0);
154 yield* emit({ ...event, type: "output", data: "> \x1b[?2004h" });
155 const written = yield* Queue.take(writes);
156 const sentinel = written.match(/__T3_SETUP_DONE___[0-9a-f]{32}:/)?.[0];
157 expect(sentinel).toBeDefined();
158 expect(written).toBe(
159 ` ${[
160 "$env.LAST_EXIT_CODE = 0",
161 "let __t3f = try { mktemp --tmpdir-path $env.T3CODE_WORKTREE_PATH --suffix .nu .t3-setup-XXXXXXXX } catch {|e| print -e $e.msg; null }",
162 `if $__t3f == null { $env.LAST_EXIT_CODE = 1 } else { try { [$"rm --permanent ($__t3f | to nuon)" "${escaped}"] | str join (char newline) | save --force --raw $__t3f; ^$nu.current-exe --login --commands $"cd $env.T3CODE_WORKTREE_PATH; source ($__t3f | to nuon)" } catch {|e| if $e != null and $e.exit_code? == null { print -e $e.msg }; if $env.LAST_EXIT_CODE == 0 { $env.LAST_EXIT_CODE = 1 } } }`,
163 "let __t3c = $env.LAST_EXIT_CODE",
164 "try { if $__t3f != null and ($__t3f | path exists) { rm --permanent $__t3f } } catch {|e| print -e $e.msg }",
165 `print $"\\n${sentinel}($__t3c)"`,
166 ].join("; ")}\r`,
167 );
168 }),
169 );
170
171 it.effect("shows a startup prompt and types only once the line editor starts", () =>
172 Effect.gen(function* () {
173 const { result, writes, outputLines, emit } = yield* setup();
174 expect(result).toMatchObject({ status: "started", terminalId });
175
176 yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " });
177 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
178 yield* TestClock.adjust("1 minute");
179 expect(yield* Queue.size(writes)).toBe(0);
180 expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]);
181
182 yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" });
183 yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" });
184 expect(yield* Queue.take(writes)).toContain("vp i");
185 }),
186 );
187
188 it.effect("drops whole escape sequences from output lines", () =>
189 Effect.gen(function* () {
190 const { outputLines, emit } = yield* setup();
191 yield* emit({
192 ...event,
193 type: "output",
194 data: "\x1b7\x1b[24;0fProgress: [ 40%]\x1b8\r\n\x1b%G\x1b#8\x1b[4:3mdone\x1bM\r\n",
195 });
196 expect(yield* Queue.takeAll(outputLines)).toEqual(["Progress: [ 40%]", "done"]);
197 }),
198 );
199
200 it.effect("types into a quiet shell that has no line editor", () =>
201 Effect.gen(function* () {
202 const { writes } = yield* setup();
203 yield* TestClock.adjust("3 seconds");
204 expect(yield* Queue.take(writes)).toContain("vp i");
205 }),
206 );
207
208 it.effect("ignores line editor state restored from an earlier shell", () =>
209 Effect.gen(function* () {
210 const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" });
211 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
212 yield* TestClock.adjust("1 minute");
213 expect(yield* Queue.size(writes)).toBe(0);
214 }),
215 );
216
217 it.effect("forgets a busy startup child when the shell restarts", () =>
218 Effect.gen(function* () {
219 const { writes, emit } = yield* setup();
220 yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" });
221 yield* TestClock.adjust("1 minute");
222 expect(yield* Queue.size(writes)).toBe(0);
223 yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") });
224 // The restart lands inside a quiet window, so the next full window decides.
225 yield* TestClock.adjust("6 seconds");
226 expect(yield* Queue.take(writes)).toContain("vp i");
227 }),
228 );
229
230 it.effect("drops its terminal listeners when cancelled while the terminal opens", () =>
231 Effect.gen(function* () {
232 const opening = yield* Deferred.make<void>();
233 const { start, listeners } = yield* makeHarness({ opening });
234 const fiber = yield* Effect.forkChild(start);
235 yield* Deferred.await(opening);
236 expect(listeners.size).toBe(2);
237 yield* Fiber.interrupt(fiber);
238 expect(listeners.size).toBe(0);
239 }),
240 );
241
242 it.effect.each([false, true])(
243 "does not type into a shell that exits during startup (before shell lookup: %s)",
244 (beforeShellLookup) =>
245 Effect.gen(function* () {
246 const { completion, writes, emit, listeners } = yield* setup(
247 beforeShellLookup ? { shell: null } : {},
248 );
249 if (!beforeShellLookup) {
250 yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
251 }
252 expect(yield* completion).toMatchObject({ exitCode: null });
253 yield* TestClock.adjust("1 minute");
254 expect(yield* Queue.size(writes)).toBe(0);
255 expect(listeners.size).toBe(0);
256 }),
257 );
258 });
259
260 const runObservedSetup = Effect.fnUntraced(function* (command: string) {
261 const { writes, outputLines, emit, completion } = yield* setup({ command });
262 yield* emit({ ...event, type: "output", data: "\x1b[?2004h" });
263 const submitted = yield* Queue.take(writes);
264 const cwd = yield* HostProcess.WorkingDirectory;
265 const env = yield* HostProcess.Environment;
266
267 // Enter becomes a newline at the terminal boundary; transport assertions below
268 // cover line-editor submissions and canonical TTY limits that bash -c bypasses.
269 const child = yield* Effect.gen(function* () {
270 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
271 const handle = yield* spawner.spawn(
272 ChildProcess.make(
273 "/bin/bash",
274 ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")],
275 {
276 cwd,
277 env: { PATH: env.PATH },
278 },
279 ),
280 );
281 return yield* Effect.all(
282 {
283 stdout: handle.stdout.pipe(Stream.decodeText(), Stream.mkString),
284 stderr: handle.stderr.pipe(Stream.decodeText(), Stream.mkString),
285 exitCode: handle.exitCode,
286 },
287 { concurrency: "unbounded" },
288 );
289 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
290 yield* emit({ ...event, type: "output", data: submitted + "\n" });
291 yield* emit({ ...event, type: "output", data: child.stdout + child.stderr });
292 yield* emit({ ...event, type: "closed" });
293 return {
294 submitted,
295 lines: yield* Queue.clear(outputLines),
296 exitCode: (yield* completion).exitCode,
297 };
298 });
299
300 describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup completion", () => {
301 it.live("submits one line while preserving multiline shell syntax and literal text", () =>
302 Effect.gen(function* () {
303 const result = yield* runObservedSetup(
304 [
305 "printf '%s\\n' \"it's ready\" 'literal \\n $(printf wrong) `printf wrong` café'",
306 "cat <<'END'",
307 "$literal \\path 雪",
308 "END",
309 "printf '%s\\n' done # trailing comment",
310 ].join("\r\n"),
311 );
312 assert.equal(result.submitted.at(-1), "\r");
313 assert.notMatch(result.submitted.slice(0, -1), /[\r\n]/);
314 assert.deepEqual(result.lines, [
315 "it's ready",
316 "literal \\n $(printf wrong) `printf wrong` café",
317 "$literal \\path 雪",
318 "done",
319 ]);
320 assert.equal(result.exitCode, 0);
321 }),
322 );
323
324 it.live("completes long scripts without exceeding canonical terminal line limits", () =>
325 Effect.gen(function* () {
326 const expected = Array.from(
327 { length: 120 },
328 (_, index) => `line-${index}: café 雪 'quoted' \\path`,
329 );
330 const command = expected
331 .map((line) => `printf '%s\\n' "${line.replaceAll("\\", "\\\\")}"`)
332 .join("\n");
333 const utf8 = new TextEncoder();
334 assert.isAbove(utf8.encode(command).byteLength, 4_096);
335
336 const result = yield* runObservedSetup(command);
337 assert.deepEqual(result.lines, expected);
338 assert.equal(result.exitCode, 0);
339 assert.equal(result.submitted.at(-1), "\r");
340 assert.notInclude(result.submitted, "\n");
341 // The runner can write before the shell switches the terminal out of canonical mode.
342 for (const line of result.submitted.slice(0, -1).split("\r")) {
343 assert.isBelow(utf8.encode(line).byteLength, 1_024);
344 }
345 }),
346 );
347
348 it.live("preserves a trailing backslash-newline even when losing it would still exit zero", () =>
349 Effect.gen(function* () {
350 const result = yield* runObservedSetup("printf '%s\\n' direct\\\n");
351 assert.deepEqual(result.lines, ["direct"]);
352 assert.equal(result.exitCode, 0);
353 }),
354 );
355
356 it.live.each([
357 { name: "an explicit exit", command: "exit 7", exitCode: 7 },
358 { name: "a syntax error", command: "if then", exitCode: 2 },
359 ])("reports a nonzero completion for $name", ({ command, exitCode }) =>
360 Effect.gen(function* () {
361 const result = yield* runObservedSetup(command);
362 assert.equal(result.exitCode, exitCode);
363 }),
364 );
365 });