Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as NetService from "@t3tools/shared/Net";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Result from "effect/Result";
13import * as Sink from "effect/Sink";
14import * as Stream from "effect/Stream";
15import { TestClock } from "effect/testing";
16import { HttpClient, HttpClientResponse } from "effect/unstable/http";
17import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
18
19import { SshPasswordPrompt } from "./auth.ts";
20import {
21 buildRemoteLaunchScript,
22 buildRemotePairingScript,
23 buildRemoteStopScript,
24 buildRemoteT3RunnerScript,
25 describeReadinessCause,
26 issueRemotePairingToken,
27 launchOrReuseRemoteServer,
28 REMOTE_PICK_PORT_SCRIPT,
29 SshEnvironmentManager,
30 waitForHttpReady,
31} from "./tunnel.ts";
32
33const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
34
35const makeSuccessfulProcess = (stdout: string) => {
36 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
37 return ChildProcessSpawner.makeHandle({
38 pid: ChildProcessSpawner.ProcessId(123),
39 stdout: stdoutStream,
40 stderr: Stream.empty,
41 all: stdoutStream,
42 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
43 isRunning: Effect.succeed(false),
44 kill: () => Effect.void,
45 stdin: Sink.drain,
46 getInputFd: () => Sink.drain,
47 getOutputFd: () => Stream.empty,
48 unref: Effect.succeed(Effect.void),
49 });
50};
51
52const makeRunningProcess = (onKill: () => void) => {
53 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
54 return ChildProcessSpawner.makeHandle({
55 pid: ChildProcessSpawner.ProcessId(123),
56 stdout: Stream.empty,
57 stderr: Stream.empty,
58 all: Stream.empty,
59 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
60 finish = (exitCode) => resume(Effect.succeed(exitCode));
61 return Effect.sync(() => {
62 finish = null;
63 });
64 }),
65 isRunning: Effect.succeed(true),
66 kill: () =>
67 Effect.sync(() => {
68 onKill();
69 finish?.(ChildProcessSpawner.ExitCode(143));
70 }),
71 stdin: Sink.drain,
72 getInputFd: () => Sink.drain,
73 getOutputFd: () => Stream.empty,
74 unref: Effect.succeed(Effect.void),
75 });
76};
77
78const testHttpClient = HttpClient.make((request) =>
79 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
80);
81
82const hangingHttpClient = HttpClient.make(() => Effect.never);
83
84const testNetService = NetService.NetService.of({
85 canListenOnHost: () => Effect.succeed(true),
86 isPortAvailableOnLoopback: () => Effect.succeed(true),
87 reserveLoopbackPort: () => Effect.succeed(41_773),
88 findAvailablePort: (preferred) => Effect.succeed(preferred),
89});
90
91function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
92 return command._tag === "StandardCommand" ? command.args : [];
93}
94
95describe("ssh tunnel scripts", () => {
96 it("builds the remote t3 runner with npx and npm fallbacks", () => {
97 const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
98
99 assert.include(script, "T3_NODE_SCRIPT_PATH=''");
100 assert.include(script, 'exec t3 "$@"');
101 assert.include(script, "exec npx --yes 't3@latest' \"$@\"");
102 assert.include(script, "exec npm exec --yes 't3@latest' -- \"$@\"");
103 assert.include(script, "could not install 't3@latest'");
104 assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
105 assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
106 assert.include(script, "remote_node_satisfies_engine()");
107 assert.include(script, "function satisfiesSemverRange");
108 assert.include(script, "satisfiesSemverRange(rawVersion, range)");
109 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
110 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
111 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
112 assert.include(script, 'eval "$(fnm env --shell bash)"');
113 assert.include(script, "fnm use --silent-if-unchanged");
114 assert.include(script, "fnm use default");
115 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
116 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
117 assert.include(script, "nvm use --silent default");
118 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
119 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
120 });
121
122 it("does not hard-code a remote node engine range", () => {
123 const script = buildRemoteT3RunnerScript();
124
125 assert.include(script, "T3_NODE_ENGINE_RANGE=''");
126 assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
127 });
128
129 it("shell-quotes package specs in the remote t3 runner", () => {
130 const script = buildRemoteT3RunnerScript({
131 packageSpec: "t3@nightly; touch /tmp/t3-owned",
132 });
133
134 assert.include(script, "exec npx --yes 't3@nightly; touch /tmp/t3-owned' \"$@\"");
135 assert.include(script, "exec npm exec --yes 't3@nightly; touch /tmp/t3-owned' -- \"$@\"");
136 assert.notInclude(script, "exec npx --yes t3@nightly; touch /tmp/t3-owned");
137 });
138
139 it("builds the remote t3 runner with a node script override", () => {
140 const script = buildRemoteT3RunnerScript({
141 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
142 });
143
144 assert.include(
145 script,
146 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
147 );
148 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
149 });
150
151 it("uses the remote t3 runner for launch and pairing scripts", () => {
152 const target = {
153 alias: "devbox",
154 hostname: "devbox.example.com",
155 username: "julius",
156 port: 2222,
157 } as const;
158
159 assert.include(
160 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
161 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
162 );
163 assert.include(buildRemoteLaunchScript(), "RUNNER_CHANGED=1");
164 assert.include(buildRemoteLaunchScript(), "ensure_remote_node_path()");
165 assert.include(buildRemoteLaunchScript(), "if ! ensure_remote_node_path; then");
166 assert.include(
167 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
168 `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`,
169 );
170 assert.include(
171 buildRemoteLaunchScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE }),
172 "does not satisfy required range ",
173 );
174 assert.include(buildRemoteLaunchScript(), 'kill "$REMOTE_PID" 2>/dev/null || true');
175 assert.include(buildRemoteLaunchScript(), "wait_ready");
176 assert.include(buildRemoteLaunchScript(), '"$RUNNER_FILE" serve --host 127.0.0.1');
177 assert.include(buildRemoteLaunchScript(), '--base-dir "$DEFAULT_SERVER_HOME"');
178 assert.notInclude(buildRemoteLaunchScript(), "server-home");
179 assert.include(buildRemoteLaunchScript(), "Remote T3 server did not become ready");
180 assert.include(buildRemoteLaunchScript({ packageSpec: "t3@nightly" }), "t3@nightly");
181 assert.include(
182 buildRemotePairingScript(target),
183 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
184 );
185 assert.include(buildRemotePairingScript(target), 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"');
186 assert.notInclude(buildRemotePairingScript(target), "server-home");
187 assert.include(buildRemotePairingScript(target, { packageSpec: "t3@nightly" }), "t3@nightly");
188 assert.include(
189 buildRemoteStopScript(target),
190 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
191 );
192 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
193 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
194 assert.include(
195 buildRemoteLaunchScript(),
196 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
197 );
198 assert.include(buildRemoteLaunchScript(), "resolve_default_runtime_port()");
199 assert.include(
200 buildRemoteLaunchScript(),
201 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port',
202 );
203 assert.include(
204 buildRemoteLaunchScript(),
205 "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))",
206 );
207 assert.include(buildRemoteLaunchScript(), '[ "$DEFAULT_RUNTIME_PID" = "$REMOTE_PID" ]');
208 assert.include(
209 buildRemoteLaunchScript(),
210 '[ "$PREVIOUS_REMOTE_PORT" != "$DEFAULT_REMOTE_PORT" ]',
211 );
212 assert.notInclude(buildRemoteLaunchScript(), "PID_TO_STOP");
213 assert.include(buildRemoteLaunchScript(), 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
214 assert.include(buildRemoteLaunchScript(), "DEFAULT_RUNTIME_IS_MANAGED=1");
215 assert.include(buildRemoteLaunchScript(), '[ "$DEFAULT_RUNTIME_IS_MANAGED" -eq 0 ]');
216 assert.include(buildRemoteLaunchScript(), 'rm -f "$PID_FILE"');
217 assert.include(buildRemoteLaunchScript(), "printf 'external\\n' >\"$MANAGED_FILE\"");
218 assert.include(buildRemoteLaunchScript(), 'if [ -z "$REMOTE_PORT" ]; then');
219 assert.include(buildRemoteLaunchScript(), "refusing to replace it with a managed SSH server");
220 assert.isBelow(
221 buildRemoteLaunchScript().indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
222 buildRemoteLaunchScript().indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
223 );
224 assert.isBelow(
225 buildRemoteLaunchScript().indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
226 buildRemoteLaunchScript().indexOf('elif [ -n "$REMOTE_PID" ]'),
227 );
228 });
229
230 it.effect("reuses its own managed runtime without replacing it", () =>
231 Effect.scoped(
232 Effect.gen(function* () {
233 if ((yield* HostProcessPlatform) === "win32") return;
234
235 const fileSystem = yield* FileSystem.FileSystem;
236 const path = yield* Path.Path;
237 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
238 const executablePath = yield* HostProcessExecutablePath;
239 const home = yield* fileSystem.makeTempDirectoryScoped({
240 prefix: "t3-ssh-launch-test-",
241 });
242 const stateKey = "managed-runtime";
243 const stateDir = path.join(home, ".t3", "ssh-launch", stateKey);
244 const runtimeDir = path.join(home, ".t3", "userdata");
245 const server = yield* spawner.spawn(
246 ChildProcess.make(
247 executablePath,
248 [
249 "-e",
250 `const http = require("node:http");
251const server = http.createServer((_request, response) => {
252 response.writeHead(200);
253 response.end("ok");
254});
255server.listen(0, "127.0.0.1", () => process.stdout.write(String(server.address().port) + "\\n"));`,
256 ],
257 { detached: false },
258 ),
259 );
260 yield* Effect.addFinalizer(() => server.kill().pipe(Effect.catchCause(() => Effect.void)));
261
262 const portLine = yield* server.stdout.pipe(
263 Stream.decodeText(),
264 Stream.splitLines,
265 Stream.runHead,
266 );
267 const port = Number.parseInt(Option.getOrThrow(portLine), 10);
268 assert.isTrue(Number.isInteger(port));
269
270 yield* fileSystem.makeDirectory(stateDir, { recursive: true });
271 yield* fileSystem.makeDirectory(runtimeDir, { recursive: true });
272 yield* fileSystem.writeFileString(path.join(stateDir, "managed"), "managed\n");
273 yield* fileSystem.writeFileString(path.join(stateDir, "pid"), `${server.pid}\n`);
274 yield* fileSystem.writeFileString(path.join(stateDir, "port"), `${port}\n`);
275 yield* fileSystem.writeFileString(
276 path.join(stateDir, "run-t3.sh"),
277 `${buildRemoteT3RunnerScript()}\n`,
278 );
279 yield* fileSystem.writeFileString(
280 path.join(runtimeDir, "server-runtime.json"),
281 `{"version":1,"pid":${server.pid},"port":${port},"origin":"http://127.0.0.1:${port}","startedAt":"2026-08-08T18:42:26.000Z"}\n`,
282 );
283
284 const shell = yield* spawner.spawn(
285 ChildProcess.make("sh", ["-s", "--", stateKey], {
286 detached: false,
287 env: { HOME: home },
288 extendEnv: true,
289 stdin: Stream.make(new TextEncoder().encode(buildRemoteLaunchScript())),
290 }),
291 );
292 const [stdout, stderr, exitCode] = yield* Effect.all(
293 [
294 Stream.mkString(Stream.decodeText(shell.stdout)),
295 Stream.mkString(Stream.decodeText(shell.stderr)),
296 shell.exitCode,
297 ],
298 { concurrency: "unbounded" },
299 );
300
301 assert.equal(exitCode, 0, stderr);
302 assert.include(stdout, `{"remotePort":${port},"serverKind":"managed"}`);
303 assert.isTrue(yield* server.isRunning);
304 assert.equal(yield* fileSystem.readFileString(path.join(stateDir, "managed")), "managed\n");
305 }).pipe(Effect.provide(NodeServices.layer)),
306 ),
307 );
308
309 it.effect("reuses an externally owned runtime even when the SSH runner changed", () =>
310 Effect.scoped(
311 Effect.gen(function* () {
312 if ((yield* HostProcessPlatform) === "win32") return;
313
314 const fileSystem = yield* FileSystem.FileSystem;
315 const path = yield* Path.Path;
316 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
317 const executablePath = yield* HostProcessExecutablePath;
318 const home = yield* fileSystem.makeTempDirectoryScoped({
319 prefix: "t3-ssh-external-runtime-test-",
320 });
321 const stateKey = "external-runtime";
322 const stateDir = path.join(home, ".t3", "ssh-launch", stateKey);
323 const runtimeDir = path.join(home, ".t3", "userdata");
324 const externalServer = yield* spawner.spawn(
325 ChildProcess.make(
326 executablePath,
327 [
328 "-e",
329 `const http = require("node:http");
330const server = http.createServer((_request, response) => {
331 response.writeHead(200);
332 response.end("ok");
333});
334server.listen(0, "127.0.0.1", () => process.stdout.write(String(server.address().port) + "\\n"));`,
335 ],
336 { detached: false },
337 ),
338 );
339 yield* Effect.addFinalizer(() =>
340 externalServer.kill().pipe(Effect.catchCause(() => Effect.void)),
341 );
342
343 const portLine = yield* externalServer.stdout.pipe(
344 Stream.decodeText(),
345 Stream.splitLines,
346 Stream.runHead,
347 );
348 const port = Number.parseInt(Option.getOrThrow(portLine), 10);
349 assert.isTrue(Number.isInteger(port));
350
351 yield* fileSystem.makeDirectory(stateDir, { recursive: true });
352 yield* fileSystem.makeDirectory(runtimeDir, { recursive: true });
353 yield* fileSystem.writeFileString(
354 path.join(stateDir, "run-t3.sh"),
355 "#!/bin/sh\n# deliberately stale runner\n",
356 );
357 yield* fileSystem.writeFileString(
358 path.join(runtimeDir, "server-runtime.json"),
359 `{"version":1,"pid":${externalServer.pid},"port":${port},"origin":"http://127.0.0.1:${port}","startedAt":"2026-08-09T05:10:06.000Z"}\n`,
360 );
361
362 const shell = yield* spawner.spawn(
363 ChildProcess.make("sh", ["-s", "--", stateKey], {
364 detached: false,
365 env: { HOME: home },
366 extendEnv: true,
367 stdin: Stream.make(new TextEncoder().encode(buildRemoteLaunchScript())),
368 }),
369 );
370 const [stdout, stderr, exitCode] = yield* Effect.all(
371 [
372 Stream.mkString(Stream.decodeText(shell.stdout)),
373 Stream.mkString(Stream.decodeText(shell.stderr)),
374 shell.exitCode,
375 ],
376 { concurrency: "unbounded" },
377 );
378
379 assert.equal(exitCode, 0, stderr);
380 assert.include(stdout, `{"remotePort":${port},"serverKind":"external"}`);
381 assert.isTrue(yield* externalServer.isRunning);
382 assert.equal(
383 yield* fileSystem.readFileString(path.join(stateDir, "managed")),
384 "external\n",
385 );
386 assert.equal(yield* fileSystem.readFileString(path.join(stateDir, "port")), `${port}\n`);
387 assert.isFalse(yield* fileSystem.exists(path.join(stateDir, "pid")));
388 }).pipe(Effect.provide(NodeServices.layer)),
389 ),
390 );
391
392 it.effect("converges a competing managed runtime onto the external owner", () =>
393 Effect.scoped(
394 Effect.gen(function* () {
395 if ((yield* HostProcessPlatform) === "win32") return;
396
397 const fileSystem = yield* FileSystem.FileSystem;
398 const path = yield* Path.Path;
399 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
400 const executablePath = yield* HostProcessExecutablePath;
401 const home = yield* fileSystem.makeTempDirectoryScoped({
402 prefix: "t3-ssh-owner-convergence-test-",
403 });
404 const stateKey = "owner-convergence";
405 const stateDir = path.join(home, ".t3", "ssh-launch", stateKey);
406 const runtimeDir = path.join(home, ".t3", "userdata");
407
408 const startServer = () =>
409 spawner.spawn(
410 ChildProcess.make(
411 executablePath,
412 [
413 "-e",
414 `const http = require("node:http");
415const server = http.createServer((_request, response) => {
416 response.writeHead(200);
417 response.end("ok");
418});
419server.listen(0, "127.0.0.1", () => process.stdout.write(String(server.address().port) + "\\n"));`,
420 ],
421 { detached: false },
422 ),
423 );
424 const managedServer = yield* startServer();
425 const externalServer = yield* startServer();
426 yield* Effect.addFinalizer(() =>
427 managedServer.kill().pipe(Effect.catchCause(() => Effect.void)),
428 );
429 yield* Effect.addFinalizer(() =>
430 externalServer.kill().pipe(Effect.catchCause(() => Effect.void)),
431 );
432
433 const managedPortLine = yield* managedServer.stdout.pipe(
434 Stream.decodeText(),
435 Stream.splitLines,
436 Stream.runHead,
437 );
438 const externalPortLine = yield* externalServer.stdout.pipe(
439 Stream.decodeText(),
440 Stream.splitLines,
441 Stream.runHead,
442 );
443 const managedPort = Number.parseInt(Option.getOrThrow(managedPortLine), 10);
444 const externalPort = Number.parseInt(Option.getOrThrow(externalPortLine), 10);
445 assert.isTrue(Number.isInteger(managedPort));
446 assert.isTrue(Number.isInteger(externalPort));
447 assert.notEqual(managedPort, externalPort);
448
449 yield* fileSystem.makeDirectory(stateDir, { recursive: true });
450 yield* fileSystem.makeDirectory(runtimeDir, { recursive: true });
451 yield* fileSystem.writeFileString(path.join(stateDir, "managed"), "managed\n");
452 yield* fileSystem.writeFileString(path.join(stateDir, "pid"), `${managedServer.pid}\n`);
453 yield* fileSystem.writeFileString(path.join(stateDir, "port"), `${managedPort}\n`);
454 yield* fileSystem.writeFileString(
455 path.join(stateDir, "run-t3.sh"),
456 `${buildRemoteT3RunnerScript()}\n`,
457 );
458 yield* fileSystem.writeFileString(
459 path.join(runtimeDir, "server-runtime.json"),
460 `{"version":1,"pid":${externalServer.pid},"port":${externalPort},"origin":"http://127.0.0.1:${externalPort}","startedAt":"2026-08-09T05:10:06.000Z"}\n`,
461 );
462
463 const shell = yield* spawner.spawn(
464 ChildProcess.make("sh", ["-s", "--", stateKey], {
465 detached: false,
466 env: { HOME: home },
467 extendEnv: true,
468 stdin: Stream.make(new TextEncoder().encode(buildRemoteLaunchScript())),
469 }),
470 );
471 const [stdout, stderr, exitCode] = yield* Effect.all(
472 [
473 Stream.mkString(Stream.decodeText(shell.stdout)),
474 Stream.mkString(Stream.decodeText(shell.stderr)),
475 shell.exitCode,
476 ],
477 { concurrency: "unbounded" },
478 );
479
480 assert.equal(exitCode, 0, stderr);
481 assert.include(stdout, `{"remotePort":${externalPort},"serverKind":"external"}`);
482 assert.isFalse(yield* managedServer.isRunning);
483 assert.isTrue(yield* externalServer.isRunning);
484 assert.equal(
485 yield* fileSystem.readFileString(path.join(stateDir, "managed")),
486 "external\n",
487 );
488 assert.equal(
489 yield* fileSystem.readFileString(path.join(stateDir, "port")),
490 `${externalPort}\n`,
491 );
492 assert.isFalse(yield* fileSystem.exists(path.join(stateDir, "pid")));
493 }).pipe(Effect.provide(NodeServices.layer)),
494 ),
495 );
496
497 it.effect("does not adopt or signal a reused managed PID on the external runtime port", () =>
498 Effect.scoped(
499 Effect.gen(function* () {
500 if ((yield* HostProcessPlatform) === "win32") return;
501
502 const fileSystem = yield* FileSystem.FileSystem;
503 const path = yield* Path.Path;
504 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
505 const executablePath = yield* HostProcessExecutablePath;
506 const home = yield* fileSystem.makeTempDirectoryScoped({
507 prefix: "t3-ssh-pid-reuse-test-",
508 });
509 const stateKey = "pid-reuse";
510 const stateDir = path.join(home, ".t3", "ssh-launch", stateKey);
511 const runtimeDir = path.join(home, ".t3", "userdata");
512
513 const externalServer = yield* spawner.spawn(
514 ChildProcess.make(
515 executablePath,
516 [
517 "-e",
518 `const http = require("node:http");
519const server = http.createServer((_request, response) => {
520 response.writeHead(200);
521 response.end("ok");
522});
523server.listen(0, "127.0.0.1", () => process.stdout.write(String(server.address().port) + "\\n"));`,
524 ],
525 { detached: false },
526 ),
527 );
528 const unrelatedProcess = yield* spawner.spawn(
529 ChildProcess.make(executablePath, ["-e", "setInterval(() => {}, 1_000)"], {
530 detached: false,
531 }),
532 );
533 yield* Effect.addFinalizer(() =>
534 externalServer.kill().pipe(Effect.catchCause(() => Effect.void)),
535 );
536 yield* Effect.addFinalizer(() =>
537 unrelatedProcess.kill().pipe(Effect.catchCause(() => Effect.void)),
538 );
539
540 const portLine = yield* externalServer.stdout.pipe(
541 Stream.decodeText(),
542 Stream.splitLines,
543 Stream.runHead,
544 );
545 const port = Number.parseInt(Option.getOrThrow(portLine), 10);
546 assert.isTrue(Number.isInteger(port));
547
548 yield* fileSystem.makeDirectory(stateDir, { recursive: true });
549 yield* fileSystem.makeDirectory(runtimeDir, { recursive: true });
550 yield* fileSystem.writeFileString(path.join(stateDir, "managed"), "managed\n");
551 yield* fileSystem.writeFileString(path.join(stateDir, "pid"), `${unrelatedProcess.pid}\n`);
552 yield* fileSystem.writeFileString(path.join(stateDir, "port"), `${port}\n`);
553 yield* fileSystem.writeFileString(
554 path.join(stateDir, "run-t3.sh"),
555 `${buildRemoteT3RunnerScript()}\n`,
556 );
557 yield* fileSystem.writeFileString(
558 path.join(runtimeDir, "server-runtime.json"),
559 `{"version":1,"pid":${externalServer.pid},"port":${port},"origin":"http://127.0.0.1:${port}","startedAt":"2026-08-09T05:10:06.000Z"}\n`,
560 );
561
562 const shell = yield* spawner.spawn(
563 ChildProcess.make("sh", ["-s", "--", stateKey], {
564 detached: false,
565 env: { HOME: home },
566 extendEnv: true,
567 stdin: Stream.make(new TextEncoder().encode(buildRemoteLaunchScript())),
568 }),
569 );
570 const [stdout, stderr, exitCode] = yield* Effect.all(
571 [
572 Stream.mkString(Stream.decodeText(shell.stdout)),
573 Stream.mkString(Stream.decodeText(shell.stderr)),
574 shell.exitCode,
575 ],
576 { concurrency: "unbounded" },
577 );
578
579 assert.equal(exitCode, 0, stderr);
580 assert.include(stdout, `{"remotePort":${port},"serverKind":"external"}`);
581 assert.isTrue(yield* externalServer.isRunning);
582 assert.isTrue(yield* unrelatedProcess.isRunning);
583 assert.equal(
584 yield* fileSystem.readFileString(path.join(stateDir, "managed")),
585 "external\n",
586 );
587 assert.isFalse(yield* fileSystem.exists(path.join(stateDir, "pid")));
588 }).pipe(Effect.provide(NodeServices.layer)),
589 ),
590 );
591
592 it.effect("accepts launch JSON after remote shell startup noise", () => {
593 const target = {
594 alias: "devbox",
595 hostname: "devbox.example.com",
596 username: "julius",
597 port: 2222,
598 } as const;
599 const spawner = ChildProcessSpawner.make(() =>
600 Effect.succeed(makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n')),
601 );
602 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
603 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
604
605 return Effect.gen(function* () {
606 const result = yield* launchOrReuseRemoteServer(target);
607 assert.equal(result.remotePort, 3774);
608 }).pipe(Effect.provide(processLayer));
609 });
610
611 it("allows the remote port picker to run without a state file path", () => {
612 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
613 });
614
615 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
616 Effect.gen(function* () {
617 const fiber = yield* Effect.forkChild(
618 Effect.result(
619 waitForHttpReady({
620 baseUrl: "http://127.0.0.1:41773/",
621 timeoutMs: 1_000,
622 intervalMs: 100,
623 probeTimeoutMs: 250,
624 }),
625 ),
626 );
627 yield* Effect.yieldNow;
628 yield* TestClock.adjust(Duration.millis(1_000));
629
630 const result = yield* Fiber.join(fiber);
631
632 assert.isTrue(Result.isFailure(result));
633 if (Result.isFailure(result)) {
634 assert.include(result.failure.message, "Timed out waiting 1000ms");
635 }
636 }).pipe(
637 Effect.provide(
638 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
639 ),
640 ),
641 );
642
643 it("preserves primitive readiness reason values in diagnostic output", () => {
644 assert.deepEqual(
645 describeReadinessCause({
646 _tag: "HttpClientError",
647 message: "Backend readiness probe failed.",
648 reason: "authentication failed",
649 cause: "upstream closed",
650 }),
651 {
652 _tag: "HttpClientError",
653 message: "Backend readiness probe failed.",
654 reason: "authentication failed",
655 cause: "upstream closed",
656 },
657 );
658 });
659
660 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
661 const target = {
662 alias: "devbox",
663 hostname: "devbox.example.com",
664 username: "julius",
665 port: 2222,
666 } as const;
667 const spawner = ChildProcessSpawner.make(() =>
668 Effect.succeed(
669 makeSuccessfulProcess(`{
670 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
671 "credential": "LCL4R2TPHDKQ",
672 "scopes": ["orchestration:read"],
673 "expiresAt": "2026-04-29T01:01:20.994Z"
674}
675
676`),
677 ),
678 );
679 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
680 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
681 return Effect.gen(function* () {
682 const result = yield* issueRemotePairingToken(target);
683 assert.equal(result.credential, "LCL4R2TPHDKQ");
684 }).pipe(Effect.provide(processLayer));
685 });
686
687 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
688 const target = {
689 alias: "devbox",
690 hostname: "devbox.example.com",
691 username: "julius",
692 port: 2222,
693 } as const;
694 const spawner = ChildProcessSpawner.make(() =>
695 Effect.succeed(
696 makeSuccessfulProcess(`loaded nvm default
697{
698 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
699 "credential": "LCL4R2TPHDKQ",
700 "scopes": ["orchestration:read"],
701 "expiresAt": "2026-04-29T01:01:20.994Z"
702}
703
704`),
705 ),
706 );
707 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
708 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
709 return Effect.gen(function* () {
710 const result = yield* issueRemotePairingToken(target);
711 assert.equal(result.credential, "LCL4R2TPHDKQ");
712 }).pipe(Effect.provide(processLayer));
713 });
714
715 it.effect("closes the tunnel scope and starts fresh after disconnect", () => {
716 const spawnedCommands: Array<ReadonlyArray<string>> = [];
717 let tunnelKillCount = 0;
718 let stopCommandCount = 0;
719 const spawner = ChildProcessSpawner.make((command) =>
720 Effect.sync(() => {
721 const args = commandArgs(command);
722 spawnedCommands.push(args);
723 if (args.includes("-N")) {
724 return makeRunningProcess(() => {
725 tunnelKillCount += 1;
726 });
727 }
728 if (args.includes("sh") && args.includes("--")) {
729 return makeSuccessfulProcess('{"remotePort":3773}\n');
730 }
731 if (args.includes("sh")) {
732 stopCommandCount += 1;
733 return makeSuccessfulProcess('{"stopped":true}\n');
734 }
735 return makeSuccessfulProcess("\n");
736 }),
737 );
738 const layer = Layer.mergeAll(
739 NodeServices.layer,
740 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
741 Layer.succeed(HttpClient.HttpClient, testHttpClient),
742 Layer.succeed(NetService.NetService, testNetService),
743 SshPasswordPrompt.disabledLayer,
744 SshEnvironmentManager.layer(),
745 );
746 const target = {
747 alias: "devbox",
748 hostname: "devbox.example.com",
749 username: "julius",
750 port: 2222,
751 } as const;
752
753 return Effect.gen(function* () {
754 const manager = yield* SshEnvironmentManager;
755
756 const first = yield* manager.ensureEnvironment(target);
757 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
758 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
759 assert.isDefined(firstTunnelArgs);
760 assert.include(firstTunnelArgs, "ControlMaster=no");
761 assert.include(firstTunnelArgs, "ControlPath=none");
762 assert.include(firstTunnelArgs, "ControlPersist=no");
763
764 yield* manager.disconnectEnvironment(target);
765 assert.equal(tunnelKillCount, 1);
766 assert.equal(stopCommandCount, 1);
767
768 yield* manager.ensureEnvironment(target);
769
770 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
771 assert.equal(tunnelKillCount, 1);
772 }).pipe(Effect.provide(layer), Effect.scoped);
773 });
774});