Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NetService from "@t3tools/shared/Net";
4import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Result from "effect/Result";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { TestClock } from "effect/testing";
15import { HttpClient, HttpClientResponse } from "effect/unstable/http";
16import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
17
18import { SshPasswordPrompt } from "./auth.ts";
19import { SshCommandError } from "./errors.ts";
20import {
21 buildRemoteLaunchScript,
22 buildRemotePairingScript,
23 buildRemoteStopScript,
24 buildRemoteT3RunnerScript,
25 SshInvalidArchiveVersionError,
26 SshMissingRunnerError,
27 describeReadinessCause,
28 issueRemotePairingToken,
29 launchOrReuseRemoteServer,
30 REMOTE_PICK_PORT_SCRIPT,
31 SshEnvironmentManager,
32 waitForHttpReady,
33} from "./tunnel.ts";
34
35const TEST_NODE_ENGINE_RANGE = "^22.16 || ^23.11 || >=24.10";
36
37const makeSuccessfulProcess = (stdout: string) => {
38 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
39 return ChildProcessSpawner.makeHandle({
40 pid: ChildProcessSpawner.ProcessId(123),
41 stdout: stdoutStream,
42 stderr: Stream.empty,
43 all: stdoutStream,
44 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
45 isRunning: Effect.succeed(false),
46 kill: () => Effect.void,
47 stdin: Sink.drain,
48 getInputFd: () => Sink.drain,
49 getOutputFd: () => Stream.empty,
50 unref: Effect.succeed(Effect.void),
51 });
52};
53
54const makeDelayedSuccessfulProcess = (stdout: string, delayMs: number) => {
55 const process = makeSuccessfulProcess(stdout);
56 return {
57 ...process,
58 exitCode: Effect.sleep(Duration.millis(delayMs)).pipe(
59 Effect.as(ChildProcessSpawner.ExitCode(0)),
60 ),
61 };
62};
63
64const makeRunningProcess = (onKill: () => void) => {
65 let finish: ((exitCode: ChildProcessSpawner.ExitCode) => void) | null = null;
66 return ChildProcessSpawner.makeHandle({
67 pid: ChildProcessSpawner.ProcessId(123),
68 stdout: Stream.empty,
69 stderr: Stream.empty,
70 all: Stream.empty,
71 exitCode: Effect.callback<ChildProcessSpawner.ExitCode>((resume) => {
72 finish = (exitCode) => resume(Effect.succeed(exitCode));
73 return Effect.sync(() => {
74 finish = null;
75 });
76 }),
77 isRunning: Effect.succeed(true),
78 kill: () =>
79 Effect.sync(() => {
80 onKill();
81 finish?.(ChildProcessSpawner.ExitCode(143));
82 }),
83 stdin: Sink.drain,
84 getInputFd: () => Sink.drain,
85 getOutputFd: () => Stream.empty,
86 unref: Effect.succeed(Effect.void),
87 });
88};
89
90const testHttpClient = HttpClient.make((request) =>
91 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
92);
93
94const hangingHttpClient = HttpClient.make(() => Effect.never);
95
96const testNetService = NetService.NetService.of({
97 canListenOnHost: () => Effect.succeed(true),
98 isPortAvailableOnLoopback: () => Effect.succeed(true),
99 hasListenerOnHost: () => Effect.succeed(false),
100 reserveLoopbackPort: () => Effect.succeed(41_773),
101 findAvailablePort: (preferred) => Effect.succeed(preferred),
102});
103
104function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
105 return command._tag === "StandardCommand" ? command.args : [];
106}
107
108const ARCHIVE = { archiveVersion: "1.2.3-preview.20260911.4" } as const;
109const NODE_SCRIPT = {
110 nodeScriptPath: "/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs",
111} as const;
112
113describe("ssh tunnel scripts", () => {
114 it("installs and runs the release archive without Node, npm, or npx", () => {
115 const script = buildRemoteT3RunnerScript(ARCHIVE);
116
117 assert.include(script, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
118 assert.include(script, "T3_NODE_SCRIPT_PATH=''");
119 assert.include(
120 script,
121 "T3_RELEASE_BASE_URL='https://github.com/pingdotgg/t3code/releases/download'",
122 );
123 assert.include(script, 'T3_RUNTIME_DIR="$HOME/.t3/runtime/versions/$T3_ARCHIVE_VERSION"');
124 assert.include(script, 'T3_ARCHIVE="t3-$T3_ARCHIVE_VERSION-$T3_PLATFORM-$T3_ARCH.tar.gz"');
125 assert.include(script, "SHA256SUMS");
126 assert.include(script, 'exec "$T3_RUNTIME_DIR/t3" "$@"');
127 assert.notInclude(script, "npx");
128 assert.notInclude(script, "npm exec");
129 assert.notInclude(script, "t3@latest");
130 assert.notInclude(script, 'exec t3 "$@"');
131 // Concurrent launches serialize on a per-version mkdir lock and recheck
132 // the completion marker after acquiring it.
133 assert.include(
134 script,
135 'T3_LOCK="$HOME/.t3/runtime/versions/.$T3_ARCHIVE_VERSION.install.lock"',
136 );
137 // mkdir is the exclusive create; the pid follows atomically. A dead owner
138 // is reclaimed at once, a never-published owner after a short grace.
139 assert.include(script, 'while ! mkdir "$T3_LOCK" 2>/dev/null; do');
140 assert.include(script, 'mv "$T3_LOCK/pid.tmp" "$T3_LOCK/pid"');
141 assert.include(script, 'if ! kill -0 "$T3_LOCK_OWNER" 2>/dev/null; then');
142 assert.include(script, 'if [ "$T3_LOCK_UNOWNED" -ge 5 ]; then');
143 assert.include(script, 'if [ "$T3_LOCK_WAITED" -ge 360 ]; then');
144 assert.include(script, '"$T3_STAGING/SHA256SUMS" 30');
145 assert.include(script, '"$T3_STAGING/$T3_ARCHIVE" 240');
146 assert.notInclude(script, "T3_LOCK_CANDIDATE");
147 assert.notInclude(script, "-mmin");
148 assert.equal(script.split("if ! t3_runtime_ready; then").length - 1, 2);
149 assert.isBelow(
150 script.indexOf('"$T3_STAGING/t3" --version'),
151 script.indexOf('> "$T3_STAGING/.install-complete"'),
152 );
153 // Node discovery is defined for the dev path but only ever invoked inside
154 // the node-script branch, which the archive path skips entirely.
155 assert.equal(script.split("ensure_remote_node_path || true").length - 1, 1);
156 assert.isBelow(
157 script.indexOf("ensure_remote_node_path || true"),
158 script.indexOf('exec node "$T3_NODE_SCRIPT_PATH" "$@"'),
159 );
160 assert.isBelow(
161 script.indexOf('exec node "$T3_NODE_SCRIPT_PATH" "$@"'),
162 script.indexOf("T3_ARCHIVE_VERSION="),
163 );
164
165 const launch = buildRemoteLaunchScript({
166 ...ARCHIVE,
167 releaseBaseUrl: "https://mirror.example/t3/",
168 });
169 assert.include(launch, "T3_ARCHIVE_MODE=1");
170 assert.include(launch, "T3_RELEASE_BASE_URL='https://mirror.example/t3'");
171 assert.include(launch, '"$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE"');
172 assert.include(launch, '"$RUNNER_FILE" __ssh-helper wait-ready "$REMOTE_PORT"');
173 assert.include(launch, '"$RUNNER_FILE" __ssh-helper runtime-port "$DEFAULT_RUNTIME_FILE"');
174 assert.include(buildRemoteLaunchScript(NODE_SCRIPT), "T3_ARCHIVE_MODE=0");
175 });
176
177 it("rejects archive versions that are not a single exact version segment", () => {
178 for (const archiveVersion of [
179 "../other",
180 "1.2.3/evil",
181 "1.2.3\\evil",
182 "1.2.3-preview.1 x",
183 "1.2.3-preview.1\nrm -rf /",
184 "v1.2.3",
185 ]) {
186 assert.throws(
187 () => buildRemoteT3RunnerScript({ archiveVersion }),
188 SshInvalidArchiveVersionError,
189 undefined,
190 archiveVersion,
191 );
192 }
193 assert.include(
194 buildRemoteT3RunnerScript(ARCHIVE),
195 "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
196 );
197 });
198
199 it("refuses to build a runner with neither an archive version nor a node script", () => {
200 for (const input of [undefined, {}, { archiveVersion: " " }, { nodeScriptPath: null }]) {
201 assert.throws(() => buildRemoteT3RunnerScript(input), SshMissingRunnerError);
202 }
203 assert.throws(() => buildRemoteLaunchScript(), SshMissingRunnerError);
204 });
205
206 it("does not hard-code a remote node engine range", () => {
207 const script = buildRemoteT3RunnerScript(NODE_SCRIPT);
208
209 assert.include(script, "T3_NODE_ENGINE_RANGE=''");
210 assert.notInclude(script, TEST_NODE_ENGINE_RANGE);
211 });
212
213 it("builds the remote t3 runner with a node script override", () => {
214 const script = buildRemoteT3RunnerScript({
215 ...NODE_SCRIPT,
216 nodeEngineRange: TEST_NODE_ENGINE_RANGE,
217 });
218
219 assert.include(
220 script,
221 "T3_NODE_SCRIPT_PATH='/Users/julius/Development/Work/codething-mvp/apps/server/dist/bin.mjs'",
222 );
223 assert.include(script, 'exec node "$T3_NODE_SCRIPT_PATH" "$@"');
224 assert.include(script, "T3_ARCHIVE_VERSION=''");
225 assert.include(script, 'prepend_path_if_dir "$HOME/.local/bin"');
226 assert.include(script, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
227 assert.include(script, "remote_node_satisfies_engine()");
228 assert.include(script, "function satisfiesSemverRange");
229 assert.include(script, "satisfiesSemverRange(rawVersion, range)");
230 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
231 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
232 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
233 assert.include(script, 'eval "$(fnm env --shell bash)"');
234 assert.include(script, "fnm use --silent-if-unchanged");
235 assert.include(script, "fnm use default");
236 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
237 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
238 assert.include(script, "nvm use --silent default");
239 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
240 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
241 assert.notInclude(script, "npx");
242 });
243
244 it("uses the remote t3 runner for launch and pairing scripts", () => {
245 const target = {
246 alias: "devbox",
247 hostname: "devbox.example.com",
248 username: "julius",
249 port: 2222,
250 } as const;
251 const launch = buildRemoteLaunchScript(ARCHIVE);
252 const devLaunch = buildRemoteLaunchScript({
253 ...NODE_SCRIPT,
254 nodeEngineRange: TEST_NODE_ENGINE_RANGE,
255 });
256
257 assert.include(
258 launch,
259 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
260 );
261 assert.include(launch, "RUNNER_CHANGED=1");
262 assert.include(launch, "ensure_remote_node_path()");
263 assert.include(launch, "if ! ensure_remote_node_path; then");
264 assert.include(devLaunch, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
265 assert.include(devLaunch, "does not satisfy required range ");
266 assert.include(launch, 'kill "$REMOTE_PID" 2>/dev/null || true');
267 assert.include(launch, "wait_ready");
268 assert.include(launch, '"$RUNNER_FILE" serve --host 127.0.0.1');
269 assert.include(launch, '--base-dir "$DEFAULT_SERVER_HOME"');
270 assert.notInclude(launch, "server-home");
271 assert.include(launch, "Remote T3 server did not become ready");
272 assert.include(launch, 'wait_ready "60000"');
273 assert.include(launch, 'if [ -s "$LOG_FILE" ]; then');
274 assert.include(launch, "It wrote nothing to %s");
275 assert.include(launch, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
276 assert.include(
277 buildRemotePairingScript(target, ARCHIVE),
278 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
279 );
280 assert.include(
281 buildRemotePairingScript(target, ARCHIVE),
282 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"',
283 );
284 assert.notInclude(buildRemotePairingScript(target, ARCHIVE), "server-home");
285 assert.include(
286 buildRemotePairingScript(target, ARCHIVE),
287 "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
288 );
289 assert.include(
290 buildRemoteStopScript(target),
291 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
292 );
293 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
294 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
295 assert.include(
296 launch,
297 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
298 );
299 assert.include(launch, "resolve_default_runtime_port()");
300 assert.include(launch, 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port');
301 assert.include(launch, "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))");
302 assert.include(launch, 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
303 assert.include(launch, 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
304 assert.include(launch, 'rm -f "$PID_FILE"');
305 assert.include(launch, "printf 'external\\n' >\"$MANAGED_FILE\"");
306 assert.include(launch, 'if [ -z "$REMOTE_PORT" ]; then');
307 assert.isBelow(
308 launch.indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
309 launch.indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
310 );
311 assert.isBelow(
312 launch.indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
313 launch.indexOf('elif [ -n "$REMOTE_PID" ]'),
314 );
315 });
316
317 it.effect("accepts launch JSON after remote shell startup noise", () => {
318 const target = {
319 alias: "devbox",
320 hostname: "devbox.example.com",
321 username: "julius",
322 port: 2222,
323 } as const;
324 const spawnedCommands: Array<ReadonlyArray<string>> = [];
325 const spawner = ChildProcessSpawner.make((command) =>
326 Effect.sync(() => {
327 spawnedCommands.push(commandArgs(command));
328 return makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n');
329 }),
330 );
331 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
332 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
333
334 return Effect.gen(function* () {
335 const result = yield* launchOrReuseRemoteServer(target, undefined, ARCHIVE);
336 assert.equal(result.remotePort, 3774);
337 assert.deepEqual(spawnedCommands[0]?.slice(-5, -1), ["sh", "-l", "-s", "--"]);
338 }).pipe(Effect.provide(processLayer));
339 });
340
341 it.effect("allows cold remote launches to exceed the default SSH command timeout", () => {
342 const target = {
343 alias: "devbox",
344 hostname: "devbox.example.com",
345 username: "julius",
346 port: 2222,
347 } as const;
348 const spawner = ChildProcessSpawner.make(() =>
349 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 75_000)),
350 );
351 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
352 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
353
354 return Effect.gen(function* () {
355 const fiber = yield* Effect.forkChild(
356 launchOrReuseRemoteServer(target, undefined, NODE_SCRIPT),
357 );
358 yield* Effect.yieldNow;
359 yield* TestClock.adjust(Duration.seconds(75));
360
361 const result = yield* Fiber.join(fiber);
362 assert.equal(result.remotePort, 3774);
363 }).pipe(Effect.provide(processLayer));
364 });
365
366 it.effect("gives cold archive launches a larger budget than node-script launches", () => {
367 const target = {
368 alias: "devbox",
369 hostname: "devbox.example.com",
370 username: "julius",
371 port: 2222,
372 } as const;
373 const spawner = ChildProcessSpawner.make(() =>
374 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 800_000)),
375 );
376 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
377 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
378
379 return Effect.gen(function* () {
380 const fiber = yield* Effect.forkChild(launchOrReuseRemoteServer(target, undefined, ARCHIVE));
381 yield* Effect.yieldNow;
382 yield* TestClock.adjust(Duration.seconds(800));
383
384 const result = yield* Fiber.join(fiber);
385 assert.equal(result.remotePort, 3774);
386 }).pipe(Effect.provide(processLayer));
387 });
388
389 it("allows the remote port picker to run without a state file path", () => {
390 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
391 });
392
393 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
394 Effect.gen(function* () {
395 const fiber = yield* Effect.forkChild(
396 Effect.result(
397 waitForHttpReady({
398 baseUrl: "http://127.0.0.1:41773/",
399 timeoutMs: 1_000,
400 intervalMs: 100,
401 probeTimeoutMs: 250,
402 }),
403 ),
404 );
405 yield* Effect.yieldNow;
406 yield* TestClock.adjust(Duration.millis(1_000));
407
408 const result = yield* Fiber.join(fiber);
409
410 assert.isTrue(Result.isFailure(result));
411 if (Result.isFailure(result)) {
412 assert.include(result.failure.message, "Timed out waiting 1000ms");
413 }
414 }).pipe(
415 Effect.provide(
416 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
417 ),
418 ),
419 );
420
421 it("preserves primitive readiness reason values in diagnostic output", () => {
422 assert.deepEqual(
423 describeReadinessCause({
424 _tag: "HttpClientError",
425 message: "Backend readiness probe failed.",
426 reason: "authentication failed",
427 cause: "upstream closed",
428 }),
429 {
430 _tag: "HttpClientError",
431 message: "Backend readiness probe failed.",
432 reason: "authentication failed",
433 cause: "upstream closed",
434 },
435 );
436 });
437
438 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
439 const target = {
440 alias: "devbox",
441 hostname: "devbox.example.com",
442 username: "julius",
443 port: 2222,
444 } as const;
445 const spawner = ChildProcessSpawner.make(() =>
446 Effect.succeed(
447 makeSuccessfulProcess(`{
448 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
449 "credential": "LCL4R2TPHDKQ",
450 "scopes": ["orchestration:read"],
451 "expiresAt": "2026-04-29T01:01:20.994Z"
452}
453
454`),
455 ),
456 );
457 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
458 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
459 return Effect.gen(function* () {
460 const result = yield* issueRemotePairingToken(target, undefined, ARCHIVE);
461 assert.equal(result.credential, "LCL4R2TPHDKQ");
462 }).pipe(Effect.provide(processLayer));
463 });
464
465 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
466 const target = {
467 alias: "devbox",
468 hostname: "devbox.example.com",
469 username: "julius",
470 port: 2222,
471 } as const;
472 const spawner = ChildProcessSpawner.make(() =>
473 Effect.succeed(
474 makeSuccessfulProcess(`loaded nvm default
475{
476 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
477 "credential": "LCL4R2TPHDKQ",
478 "scopes": ["orchestration:read"],
479 "expiresAt": "2026-04-29T01:01:20.994Z"
480}
481
482`),
483 ),
484 );
485 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
486 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
487 return Effect.gen(function* () {
488 const result = yield* issueRemotePairingToken(target, undefined, ARCHIVE);
489 assert.equal(result.credential, "LCL4R2TPHDKQ");
490 }).pipe(Effect.provide(processLayer));
491 });
492
493 it.effect.each(["successful stop", "failed stop"] as const)(
494 "closes the tunnel scope and starts fresh after a %s",
495 (mode) => {
496 const spawnedCommands: Array<ReadonlyArray<string>> = [];
497 let tunnelKillCount = 0;
498 let stopCommandCount = 0;
499 const spawner = ChildProcessSpawner.make((command) =>
500 Effect.sync(() => {
501 const args = commandArgs(command);
502 spawnedCommands.push(args);
503 if (args.includes("-N")) {
504 return makeRunningProcess(() => {
505 tunnelKillCount += 1;
506 });
507 }
508 if (args.includes("sh") && args.includes("--")) {
509 return makeSuccessfulProcess('{"remotePort":3773}\n');
510 }
511 if (args.includes("sh")) {
512 stopCommandCount += 1;
513 if (mode === "failed stop" && stopCommandCount === 1) {
514 return {
515 ...makeSuccessfulProcess(""),
516 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
517 stderr: Stream.make(
518 new TextEncoder().encode("Remote T3 server did not stop within 2 seconds.\n"),
519 ),
520 };
521 }
522 return makeSuccessfulProcess('{"stopped":true}\n');
523 }
524 return makeSuccessfulProcess("\n");
525 }),
526 );
527 const layer = Layer.mergeAll(
528 NodeServices.layer,
529 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
530 Layer.succeed(HttpClient.HttpClient, testHttpClient),
531 Layer.succeed(NetService.NetService, testNetService),
532 SshPasswordPrompt.disabledLayer,
533 SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
534 );
535 const target = {
536 alias: "devbox",
537 hostname: "devbox.example.com",
538 username: "julius",
539 port: 2222,
540 } as const;
541
542 return Effect.gen(function* () {
543 const manager = yield* SshEnvironmentManager;
544
545 const first = yield* manager.ensureEnvironment(target);
546 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
547 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
548 assert.isDefined(firstTunnelArgs);
549 assert.include(firstTunnelArgs, "ControlMaster=no");
550 assert.include(firstTunnelArgs, "ControlPath=none");
551 assert.include(firstTunnelArgs, "ControlPersist=no");
552
553 const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
554 if (mode === "failed stop") {
555 assert.isTrue(Result.isFailure(disconnected));
556 if (Result.isFailure(disconnected)) {
557 assert.instanceOf(disconnected.failure, SshCommandError);
558 assert.equal(
559 disconnected.failure.message,
560 "Remote T3 server did not stop within 2 seconds.",
561 );
562 }
563 } else {
564 assert.isTrue(Result.isSuccess(disconnected));
565 }
566 assert.equal(tunnelKillCount, 1);
567 assert.equal(stopCommandCount, 1);
568
569 if (mode === "failed stop") {
570 yield* manager.disconnectEnvironment(target);
571 assert.equal(tunnelKillCount, 1);
572 assert.equal(stopCommandCount, 2);
573 }
574
575 yield* manager.ensureEnvironment(target);
576
577 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
578 assert.equal(tunnelKillCount, 1);
579 }).pipe(
580 Effect.provide(layer),
581 Effect.scoped,
582 Effect.andThen(
583 Effect.sync(() => {
584 assert.equal(tunnelKillCount, 2);
585 assert.equal(stopCommandCount, mode === "failed stop" ? 3 : 2);
586 }),
587 ),
588 );
589 },
590 );
591
592 it.effect.each(["local tunnel", "remote server"] as const)(
593 "waits for %s shutdown before reconnecting the same target",
594 (stalledStep) =>
595 Effect.gen(function* () {
596 const shutdownStarted = yield* Deferred.make<void>();
597 const finishShutdown = yield* Deferred.make<void>();
598 const reconnectsStarted = yield* Deferred.make<void>();
599 const pauseShutdown = Deferred.succeed(shutdownStarted, undefined).pipe(
600 Effect.andThen(Deferred.await(finishShutdown)),
601 );
602 let resolutions = 0;
603 let launches = 0;
604 let tunnels = 0;
605 let stops = 0;
606 let remoteRunning = false;
607 const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
608 const spawner = ChildProcessSpawner.make((command) =>
609 Effect.gen(function* () {
610 const args = commandArgs(command);
611 const isTarget = args.includes(target.alias);
612 if (args.includes("-G")) {
613 if (isTarget && ++resolutions === 4) {
614 yield* Deferred.succeed(reconnectsStarted, undefined);
615 }
616 return makeSuccessfulProcess("");
617 }
618 if (args.includes("-N")) {
619 const tunnel = makeRunningProcess(() => undefined);
620 if (isTarget && ++tunnels === 1 && stalledStep === "local tunnel") {
621 return {
622 ...tunnel,
623 kill: (options?: ChildProcess.KillOptions) =>
624 pauseShutdown.pipe(Effect.andThen(tunnel.kill(options))),
625 };
626 }
627 return tunnel;
628 }
629 if (args.includes("--")) {
630 if (isTarget) {
631 launches += 1;
632 remoteRunning = true;
633 }
634 return makeSuccessfulProcess('{"remotePort":3773}\n');
635 }
636 const stop = makeSuccessfulProcess('{"stopped":true}\n');
637 if (!isTarget) return stop;
638 const pause = ++stops === 1 && stalledStep === "remote server";
639 return {
640 ...stop,
641 exitCode: (pause ? pauseShutdown : Effect.void).pipe(
642 Effect.andThen(
643 Effect.sync(() => {
644 remoteRunning = false;
645 return ChildProcessSpawner.ExitCode(0);
646 }),
647 ),
648 ),
649 };
650 }),
651 );
652 const layer = Layer.mergeAll(
653 NodeServices.layer,
654 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
655 Layer.succeed(HttpClient.HttpClient, testHttpClient),
656 Layer.succeed(NetService.NetService, testNetService),
657 SshPasswordPrompt.disabledLayer,
658 SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
659 );
660 yield* Effect.gen(function* () {
661 const manager = yield* SshEnvironmentManager;
662 yield* manager.ensureEnvironment(target);
663 const disconnect = yield* Effect.forkChild(manager.disconnectEnvironment(target));
664 yield* Deferred.await(shutdownStarted);
665 const firstReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
666 const secondReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
667 yield* Deferred.await(reconnectsStarted);
668
669 yield* manager.ensureEnvironment({
670 alias: "other",
671 hostname: "other",
672 username: null,
673 port: null,
674 });
675 yield* TestClock.adjust(Duration.zero);
676 const launchesBeforeShutdown = launches;
677 yield* Deferred.succeed(finishShutdown, undefined);
678 yield* Fiber.join(disconnect);
679 const first = yield* Fiber.join(firstReconnect);
680 const second = yield* Fiber.join(secondReconnect);
681
682 assert.equal(launchesBeforeShutdown, 1);
683 assert.equal(launches, 2);
684 assert.equal(tunnels, 2);
685 assert.isTrue(remoteRunning);
686 assert.equal(first.httpBaseUrl, second.httpBaseUrl);
687 }).pipe(
688 Effect.ensuring(Deferred.succeed(finishShutdown, undefined)),
689 Effect.provide(layer),
690 Effect.scoped,
691 );
692 }),
693 );
694});
695
696// The archive runner is generated shell; string assertions cannot prove the
697// lock excludes concurrent installers. Run the real script against a tiny
698// fake archive served from a file:// mirror.
699describe("archive runner script", () => {
700 const hostPlatform = HostProcessPlatform.defaultValue();
701 const hostArch = HostProcessArchitecture.defaultValue();
702 const windowsHost = hostPlatform === "win32";
703 const archiveVersion = "1.2.3-preview.20260911.4";
704
705 const runRunner = (home: string, runner: string) =>
706 Effect.gen(function* () {
707 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
708 const child = yield* spawner.spawn(
709 ChildProcess.make("sh", [runner, "--version"], {
710 env: { PATH: process.env.PATH ?? "", HOME: home },
711 extendEnv: false,
712 }),
713 );
714 const [stdout, stderr, exitCode] = yield* Effect.all(
715 [
716 child.stdout.pipe(
717 Stream.decodeText(),
718 Stream.runFold(
719 () => "",
720 (acc, chunk) => acc + chunk,
721 ),
722 ),
723 child.stderr.pipe(
724 Stream.decodeText(),
725 Stream.runFold(
726 () => "",
727 (acc, chunk) => acc + chunk,
728 ),
729 ),
730 child.exitCode.pipe(Effect.map(Number)),
731 ],
732 { concurrency: "unbounded" },
733 );
734 return { stdout, stderr, exitCode };
735 });
736
737 // A fake "executable" that answers --version, packed the way the release
738 // workflow packs the real archive: one top-level directory named after the
739 // stem, checksummed in SHA256SUMS.
740 const makeMirror = Effect.fn("makeMirror")(function* (root: string) {
741 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
742 const platform = hostPlatform === "darwin" ? "darwin" : "linux";
743 const arch = hostArch === "arm64" ? "arm64" : "x64";
744 const stem = `t3-${archiveVersion}-${platform}-${arch}`;
745 const stage = `${root}/stage/${stem}`;
746 const release = `${root}/mirror/v${archiveVersion}`;
747 const script = [
748 "set -eu",
749 `mkdir -p '${stage}' '${release}'`,
750 `printf '#!/bin/sh\\necho t3 v${archiveVersion}\\n' > '${stage}/t3'`,
751 `chmod +x '${stage}/t3'`,
752 `tar -czf '${release}/${stem}.tar.gz' -C '${root}/stage' '${stem}'`,
753 `cd '${release}' && (sha256sum '${stem}.tar.gz' 2>/dev/null || shasum -a 256 '${stem}.tar.gz') > SHA256SUMS`,
754 ].join("\n");
755 const child = yield* spawner.spawn(ChildProcess.make("sh", ["-c", script]));
756 assert.equal(Number(yield* child.exitCode), 0);
757 return `file://${root}/mirror`;
758 });
759
760 it.effect.skipIf(windowsHost)(
761 "installs once when several launches race, and reclaims stale locks",
762 () =>
763 Effect.gen(function* () {
764 const fs = yield* FileSystem.FileSystem;
765 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-archive-runner-" });
766 const releaseBaseUrl = yield* makeMirror(root);
767 const runner = `${root}/run-t3.sh`;
768 yield* fs.writeFileString(
769 runner,
770 buildRemoteT3RunnerScript({ archiveVersion, releaseBaseUrl }),
771 );
772 const home = `${root}/home`;
773 yield* fs.makeDirectory(home, { recursive: true });
774
775 const results = yield* Effect.all(
776 [runRunner(home, runner), runRunner(home, runner), runRunner(home, runner)],
777 { concurrency: "unbounded" },
778 );
779 for (const result of results) {
780 assert.equal(result.exitCode, 0, result.stderr);
781 assert.include(result.stdout, `t3 v${archiveVersion}`);
782 }
783 const versionsDir = `${home}/.t3/runtime/versions`;
784 assert.deepEqual(yield* fs.readDirectory(versionsDir), [archiveVersion]);
785 assert.equal(
786 (yield* fs.readFileString(`${versionsDir}/${archiveVersion}/.install-complete`)).trim(),
787 archiveVersion,
788 );
789
790 // A lock left by a crashed installer (dead pid) must not block the
791 // next launch, and neither must one that never published a pid.
792 const lock = `${versionsDir}/.${archiveVersion}.install.lock`;
793 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
794 yield* fs.makeDirectory(lock);
795 yield* fs.writeFileString(`${lock}/pid`, "999999\n");
796 const afterDead = yield* runRunner(home, runner);
797 assert.equal(afterDead.exitCode, 0, afterDead.stderr);
798
799 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
800 yield* fs.makeDirectory(lock);
801 const afterUnowned = yield* runRunner(home, runner);
802 assert.equal(afterUnowned.exitCode, 0, afterUnowned.stderr);
803 assert.isFalse(yield* fs.exists(lock));
804 }).pipe(Effect.provide(NodeServices.layer)),
805 60_000,
806 );
807});