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 "/home/linuxbrew/.linuxbrew/bin"');
231 assert.include(script, 'prepend_path_if_dir "$VOLTA_HOME/bin"');
232 assert.include(script, 'prepend_path_if_dir "$HOME/.asdf/shims"');
233 assert.include(script, 'prepend_path_if_dir "$HOME/.local/share/mise/shims"');
234 assert.include(script, 'eval "$(fnm env --shell bash)"');
235 assert.include(script, "fnm use --silent-if-unchanged");
236 assert.include(script, "fnm use default");
237 assert.include(script, 'prepend_path_if_dir "$HOME/.nodenv/shims"');
238 assert.include(script, 'NVM_DIR="$HOME/.nvm"');
239 assert.include(script, "nvm use --silent default");
240 assert.include(script, 'for T3_NODE_BIN in "$NVM_DIR"/versions/node/*/bin');
241 assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
242 assert.notInclude(script, "npx");
243 });
244
245 it("uses the remote t3 runner for launch and pairing scripts", () => {
246 const target = {
247 alias: "devbox",
248 hostname: "devbox.example.com",
249 username: "julius",
250 port: 2222,
251 } as const;
252 const launch = buildRemoteLaunchScript(ARCHIVE);
253 const devLaunch = buildRemoteLaunchScript({
254 ...NODE_SCRIPT,
255 nodeEngineRange: TEST_NODE_ENGINE_RANGE,
256 });
257
258 assert.include(
259 launch,
260 '[ -n "$REMOTE_PID" ] && [ -n "$REMOTE_PORT" ] && kill -0 "$REMOTE_PID" 2>/dev/null',
261 );
262 assert.include(launch, "RUNNER_CHANGED=1");
263 assert.include(launch, "ensure_remote_node_path()");
264 assert.include(launch, "if ! ensure_remote_node_path; then");
265 assert.include(devLaunch, `T3_NODE_ENGINE_RANGE='${TEST_NODE_ENGINE_RANGE}'`);
266 assert.include(devLaunch, "does not satisfy required range ");
267 assert.include(launch, 'kill "$REMOTE_PID" 2>/dev/null || true');
268 assert.include(launch, "wait_ready");
269 assert.include(launch, '"$RUNNER_FILE" serve --host 127.0.0.1');
270 assert.include(launch, '--base-dir "$DEFAULT_SERVER_HOME"');
271 assert.notInclude(launch, "server-home");
272 assert.include(launch, "Remote T3 server did not become ready");
273 assert.include(launch, 'wait_ready "60000"');
274 assert.include(launch, 'if [ -s "$LOG_FILE" ]; then');
275 assert.include(launch, "It wrote nothing to %s");
276 assert.include(launch, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
277 assert.include(
278 buildRemotePairingScript(target, ARCHIVE),
279 '"$RUNNER_FILE" auth pairing create --base-dir "$PAIRING_BASE_DIR" --json',
280 );
281 assert.include(
282 buildRemotePairingScript(target, ARCHIVE),
283 'PAIRING_BASE_DIR="$DEFAULT_SERVER_HOME"',
284 );
285 assert.notInclude(buildRemotePairingScript(target, ARCHIVE), "server-home");
286 assert.include(
287 buildRemotePairingScript(target, ARCHIVE),
288 "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'",
289 );
290 assert.include(
291 buildRemoteStopScript(target),
292 'if [ "$REMOTE_MANAGED" != "external" ] && [ -n "$REMOTE_PID" ]',
293 );
294 assert.include(buildRemoteStopScript(target), 'kill "$REMOTE_PID" 2>/dev/null || true');
295 assert.include(buildRemoteStopScript(target), 'rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE"');
296 assert.include(
297 launch,
298 'DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"',
299 );
300 assert.include(launch, "resolve_default_runtime_port()");
301 assert.include(launch, 'DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port');
302 assert.include(launch, "if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port))");
303 assert.include(launch, 'PID_TO_STOP="${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"');
304 assert.include(launch, 'REMOTE_PORT="$DEFAULT_REMOTE_PORT"');
305 assert.include(launch, 'rm -f "$PID_FILE"');
306 assert.include(launch, "printf 'external\\n' >\"$MANAGED_FILE\"");
307 assert.include(launch, 'if [ -z "$REMOTE_PORT" ]; then');
308 assert.isBelow(
309 launch.indexOf('if [ "$REMOTE_MANAGED" = "managed" ]'),
310 launch.indexOf("printf 'external\\n' >\"$MANAGED_FILE\""),
311 );
312 assert.isBelow(
313 launch.indexOf('DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port'),
314 launch.indexOf('elif [ -n "$REMOTE_PID" ]'),
315 );
316 });
317
318 it.effect("accepts launch JSON after remote shell startup noise", () => {
319 const target = {
320 alias: "devbox",
321 hostname: "devbox.example.com",
322 username: "julius",
323 port: 2222,
324 } as const;
325 const spawnedCommands: Array<ReadonlyArray<string>> = [];
326 const spawner = ChildProcessSpawner.make((command) =>
327 Effect.sync(() => {
328 spawnedCommands.push(commandArgs(command));
329 return makeSuccessfulProcess('loaded nvm default\n{"remotePort":3774}\n');
330 }),
331 );
332 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
333 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
334
335 return Effect.gen(function* () {
336 const result = yield* launchOrReuseRemoteServer(target, undefined, ARCHIVE);
337 assert.equal(result.remotePort, 3774);
338 assert.deepEqual(spawnedCommands[0]?.slice(-5, -1), ["sh", "-l", "-s", "--"]);
339 }).pipe(Effect.provide(processLayer));
340 });
341
342 it.effect("allows cold remote launches to exceed the default SSH command timeout", () => {
343 const target = {
344 alias: "devbox",
345 hostname: "devbox.example.com",
346 username: "julius",
347 port: 2222,
348 } as const;
349 const spawner = ChildProcessSpawner.make(() =>
350 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 75_000)),
351 );
352 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
353 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
354
355 return Effect.gen(function* () {
356 const fiber = yield* Effect.forkChild(
357 launchOrReuseRemoteServer(target, undefined, NODE_SCRIPT),
358 );
359 yield* Effect.yieldNow;
360 yield* TestClock.adjust(Duration.seconds(75));
361
362 const result = yield* Fiber.join(fiber);
363 assert.equal(result.remotePort, 3774);
364 }).pipe(Effect.provide(processLayer));
365 });
366
367 it.effect("gives cold archive launches a larger budget than node-script launches", () => {
368 const target = {
369 alias: "devbox",
370 hostname: "devbox.example.com",
371 username: "julius",
372 port: 2222,
373 } as const;
374 const spawner = ChildProcessSpawner.make(() =>
375 Effect.succeed(makeDelayedSuccessfulProcess('{"remotePort":3774}\n', 800_000)),
376 );
377 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
378 const processLayer = Layer.mergeAll(NodeServices.layer, spawnerLayer, TestClock.layer());
379
380 return Effect.gen(function* () {
381 const fiber = yield* Effect.forkChild(launchOrReuseRemoteServer(target, undefined, ARCHIVE));
382 yield* Effect.yieldNow;
383 yield* TestClock.adjust(Duration.seconds(800));
384
385 const result = yield* Fiber.join(fiber);
386 assert.equal(result.remotePort, 3774);
387 }).pipe(Effect.provide(processLayer));
388 });
389
390 it("allows the remote port picker to run without a state file path", () => {
391 assert.include(REMOTE_PICK_PORT_SCRIPT, 'const filePath = process.argv[2] ?? "";');
392 });
393
394 it.effect("bounds each HTTP readiness probe so retries cannot hang on one request", () =>
395 Effect.gen(function* () {
396 const fiber = yield* Effect.forkChild(
397 Effect.result(
398 waitForHttpReady({
399 baseUrl: "http://127.0.0.1:41773/",
400 timeoutMs: 1_000,
401 intervalMs: 100,
402 probeTimeoutMs: 250,
403 }),
404 ),
405 );
406 yield* Effect.yieldNow;
407 yield* TestClock.adjust(Duration.millis(1_000));
408
409 const result = yield* Fiber.join(fiber);
410
411 assert.isTrue(Result.isFailure(result));
412 if (Result.isFailure(result)) {
413 assert.include(result.failure.message, "Timed out waiting 1000ms");
414 }
415 }).pipe(
416 Effect.provide(
417 Layer.merge(TestClock.layer(), Layer.succeed(HttpClient.HttpClient, hangingHttpClient)),
418 ),
419 ),
420 );
421
422 it("preserves primitive readiness reason values in diagnostic output", () => {
423 assert.deepEqual(
424 describeReadinessCause({
425 _tag: "HttpClientError",
426 message: "Backend readiness probe failed.",
427 reason: "authentication failed",
428 cause: "upstream closed",
429 }),
430 {
431 _tag: "HttpClientError",
432 message: "Backend readiness probe failed.",
433 reason: "authentication failed",
434 cause: "upstream closed",
435 },
436 );
437 });
438
439 it.effect("accepts pretty-printed pairing JSON from the remote CLI", () => {
440 const target = {
441 alias: "devbox",
442 hostname: "devbox.example.com",
443 username: "julius",
444 port: 2222,
445 } as const;
446 const spawner = ChildProcessSpawner.make(() =>
447 Effect.succeed(
448 makeSuccessfulProcess(`{
449 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
450 "credential": "LCL4R2TPHDKQ",
451 "scopes": ["orchestration:read"],
452 "expiresAt": "2026-04-29T01:01:20.994Z"
453}
454
455`),
456 ),
457 );
458 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
459 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
460 return Effect.gen(function* () {
461 const result = yield* issueRemotePairingToken(target, undefined, ARCHIVE);
462 assert.equal(result.credential, "LCL4R2TPHDKQ");
463 }).pipe(Effect.provide(processLayer));
464 });
465
466 it.effect("accepts pretty-printed pairing JSON after remote shell startup noise", () => {
467 const target = {
468 alias: "devbox",
469 hostname: "devbox.example.com",
470 username: "julius",
471 port: 2222,
472 } as const;
473 const spawner = ChildProcessSpawner.make(() =>
474 Effect.succeed(
475 makeSuccessfulProcess(`loaded nvm default
476{
477 "id": "88941235-6ed5-4184-a2ff-5339e2075958",
478 "credential": "LCL4R2TPHDKQ",
479 "scopes": ["orchestration:read"],
480 "expiresAt": "2026-04-29T01:01:20.994Z"
481}
482
483`),
484 ),
485 );
486 const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner);
487 const processLayer = Layer.merge(NodeServices.layer, spawnerLayer);
488 return Effect.gen(function* () {
489 const result = yield* issueRemotePairingToken(target, undefined, ARCHIVE);
490 assert.equal(result.credential, "LCL4R2TPHDKQ");
491 }).pipe(Effect.provide(processLayer));
492 });
493
494 it.effect.each(["successful stop", "failed stop"] as const)(
495 "closes the tunnel scope and starts fresh after a %s",
496 (mode) => {
497 const spawnedCommands: Array<ReadonlyArray<string>> = [];
498 let tunnelKillCount = 0;
499 let stopCommandCount = 0;
500 const spawner = ChildProcessSpawner.make((command) =>
501 Effect.sync(() => {
502 const args = commandArgs(command);
503 spawnedCommands.push(args);
504 if (args.includes("-N")) {
505 return makeRunningProcess(() => {
506 tunnelKillCount += 1;
507 });
508 }
509 if (args.includes("sh") && args.includes("--")) {
510 return makeSuccessfulProcess('{"remotePort":3773}\n');
511 }
512 if (args.includes("sh")) {
513 stopCommandCount += 1;
514 if (mode === "failed stop" && stopCommandCount === 1) {
515 return {
516 ...makeSuccessfulProcess(""),
517 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
518 stderr: Stream.make(
519 new TextEncoder().encode("Remote T3 server did not stop within 2 seconds.\n"),
520 ),
521 };
522 }
523 return makeSuccessfulProcess('{"stopped":true}\n');
524 }
525 return makeSuccessfulProcess("\n");
526 }),
527 );
528 const layer = Layer.mergeAll(
529 NodeServices.layer,
530 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
531 Layer.succeed(HttpClient.HttpClient, testHttpClient),
532 Layer.succeed(NetService.NetService, testNetService),
533 SshPasswordPrompt.disabledLayer,
534 SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
535 );
536 const target = {
537 alias: "devbox",
538 hostname: "devbox.example.com",
539 username: "julius",
540 port: 2222,
541 } as const;
542
543 return Effect.gen(function* () {
544 const manager = yield* SshEnvironmentManager;
545
546 const first = yield* manager.ensureEnvironment(target);
547 assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
548 const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
549 assert.isDefined(firstTunnelArgs);
550 assert.include(firstTunnelArgs, "ControlMaster=no");
551 assert.include(firstTunnelArgs, "ControlPath=none");
552 assert.include(firstTunnelArgs, "ControlPersist=no");
553
554 const disconnected = yield* Effect.result(manager.disconnectEnvironment(target));
555 if (mode === "failed stop") {
556 assert.isTrue(Result.isFailure(disconnected));
557 if (Result.isFailure(disconnected)) {
558 assert.instanceOf(disconnected.failure, SshCommandError);
559 assert.equal(
560 disconnected.failure.message,
561 "Remote T3 server did not stop within 2 seconds.",
562 );
563 }
564 } else {
565 assert.isTrue(Result.isSuccess(disconnected));
566 }
567 assert.equal(tunnelKillCount, 1);
568 assert.equal(stopCommandCount, 1);
569
570 if (mode === "failed stop") {
571 yield* manager.disconnectEnvironment(target);
572 assert.equal(tunnelKillCount, 1);
573 assert.equal(stopCommandCount, 2);
574 }
575
576 yield* manager.ensureEnvironment(target);
577
578 assert.equal(spawnedCommands.filter((args) => args.includes("-N")).length, 2);
579 assert.equal(tunnelKillCount, 1);
580 }).pipe(
581 Effect.provide(layer),
582 Effect.scoped,
583 Effect.andThen(
584 Effect.sync(() => {
585 assert.equal(tunnelKillCount, 2);
586 assert.equal(stopCommandCount, mode === "failed stop" ? 3 : 2);
587 }),
588 ),
589 );
590 },
591 );
592
593 it.effect.each(["local tunnel", "remote server"] as const)(
594 "waits for %s shutdown before reconnecting the same target",
595 (stalledStep) =>
596 Effect.gen(function* () {
597 const shutdownStarted = yield* Deferred.make<void>();
598 const finishShutdown = yield* Deferred.make<void>();
599 const reconnectsStarted = yield* Deferred.make<void>();
600 const pauseShutdown = Deferred.succeed(shutdownStarted, undefined).pipe(
601 Effect.andThen(Deferred.await(finishShutdown)),
602 );
603 let resolutions = 0;
604 let launches = 0;
605 let tunnels = 0;
606 let stops = 0;
607 let remoteRunning = false;
608 const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
609 const spawner = ChildProcessSpawner.make((command) =>
610 Effect.gen(function* () {
611 const args = commandArgs(command);
612 const isTarget = args.includes(target.alias);
613 if (args.includes("-G")) {
614 if (isTarget && ++resolutions === 4) {
615 yield* Deferred.succeed(reconnectsStarted, undefined);
616 }
617 return makeSuccessfulProcess("");
618 }
619 if (args.includes("-N")) {
620 const tunnel = makeRunningProcess(() => undefined);
621 if (isTarget && ++tunnels === 1 && stalledStep === "local tunnel") {
622 return {
623 ...tunnel,
624 kill: (options?: ChildProcess.KillOptions) =>
625 pauseShutdown.pipe(Effect.andThen(tunnel.kill(options))),
626 };
627 }
628 return tunnel;
629 }
630 if (args.includes("--")) {
631 if (isTarget) {
632 launches += 1;
633 remoteRunning = true;
634 }
635 return makeSuccessfulProcess('{"remotePort":3773}\n');
636 }
637 const stop = makeSuccessfulProcess('{"stopped":true}\n');
638 if (!isTarget) return stop;
639 const pause = ++stops === 1 && stalledStep === "remote server";
640 return {
641 ...stop,
642 exitCode: (pause ? pauseShutdown : Effect.void).pipe(
643 Effect.andThen(
644 Effect.sync(() => {
645 remoteRunning = false;
646 return ChildProcessSpawner.ExitCode(0);
647 }),
648 ),
649 ),
650 };
651 }),
652 );
653 const layer = Layer.mergeAll(
654 NodeServices.layer,
655 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
656 Layer.succeed(HttpClient.HttpClient, testHttpClient),
657 Layer.succeed(NetService.NetService, testNetService),
658 SshPasswordPrompt.disabledLayer,
659 SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
660 );
661 yield* Effect.gen(function* () {
662 const manager = yield* SshEnvironmentManager;
663 yield* manager.ensureEnvironment(target);
664 const disconnect = yield* Effect.forkChild(manager.disconnectEnvironment(target));
665 yield* Deferred.await(shutdownStarted);
666 const firstReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
667 const secondReconnect = yield* Effect.forkChild(manager.ensureEnvironment(target));
668 yield* Deferred.await(reconnectsStarted);
669
670 yield* manager.ensureEnvironment({
671 alias: "other",
672 hostname: "other",
673 username: null,
674 port: null,
675 });
676 yield* TestClock.adjust(Duration.zero);
677 const launchesBeforeShutdown = launches;
678 yield* Deferred.succeed(finishShutdown, undefined);
679 yield* Fiber.join(disconnect);
680 const first = yield* Fiber.join(firstReconnect);
681 const second = yield* Fiber.join(secondReconnect);
682
683 assert.equal(launchesBeforeShutdown, 1);
684 assert.equal(launches, 2);
685 assert.equal(tunnels, 2);
686 assert.isTrue(remoteRunning);
687 assert.equal(first.httpBaseUrl, second.httpBaseUrl);
688 }).pipe(
689 Effect.ensuring(Deferred.succeed(finishShutdown, undefined)),
690 Effect.provide(layer),
691 Effect.scoped,
692 );
693 }),
694 );
695});
696
697// The archive runner is generated shell; string assertions cannot prove the
698// lock excludes concurrent installers. Run the real script against a tiny
699// fake archive served from a file:// mirror.
700describe("archive runner script", () => {
701 const hostPlatform = HostProcessPlatform.defaultValue();
702 const hostArch = HostProcessArchitecture.defaultValue();
703 const windowsHost = hostPlatform === "win32";
704 const archiveVersion = "1.2.3-preview.20260911.4";
705
706 const runRunner = (home: string, runner: string) =>
707 Effect.gen(function* () {
708 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
709 const child = yield* spawner.spawn(
710 ChildProcess.make("sh", [runner, "--version"], {
711 env: { PATH: process.env.PATH ?? "", HOME: home },
712 extendEnv: false,
713 }),
714 );
715 const [stdout, stderr, exitCode] = yield* Effect.all(
716 [
717 child.stdout.pipe(
718 Stream.decodeText(),
719 Stream.runFold(
720 () => "",
721 (acc, chunk) => acc + chunk,
722 ),
723 ),
724 child.stderr.pipe(
725 Stream.decodeText(),
726 Stream.runFold(
727 () => "",
728 (acc, chunk) => acc + chunk,
729 ),
730 ),
731 child.exitCode.pipe(Effect.map(Number)),
732 ],
733 { concurrency: "unbounded" },
734 );
735 return { stdout, stderr, exitCode };
736 });
737
738 // A fake "executable" that answers --version, packed the way the release
739 // workflow packs the real archive: one top-level directory named after the
740 // stem, checksummed in SHA256SUMS.
741 const makeMirror = Effect.fn("makeMirror")(function* (root: string) {
742 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
743 const platform = hostPlatform === "darwin" ? "darwin" : "linux";
744 const arch = hostArch === "arm64" ? "arm64" : "x64";
745 const stem = `t3-${archiveVersion}-${platform}-${arch}`;
746 const stage = `${root}/stage/${stem}`;
747 const release = `${root}/mirror/v${archiveVersion}`;
748 const script = [
749 "set -eu",
750 `mkdir -p '${stage}' '${release}'`,
751 `printf '#!/bin/sh\\necho t3 v${archiveVersion}\\n' > '${stage}/t3'`,
752 `chmod +x '${stage}/t3'`,
753 `tar -czf '${release}/${stem}.tar.gz' -C '${root}/stage' '${stem}'`,
754 `cd '${release}' && (sha256sum '${stem}.tar.gz' 2>/dev/null || shasum -a 256 '${stem}.tar.gz') > SHA256SUMS`,
755 ].join("\n");
756 const child = yield* spawner.spawn(ChildProcess.make("sh", ["-c", script]));
757 assert.equal(Number(yield* child.exitCode), 0);
758 return `file://${root}/mirror`;
759 });
760
761 it.effect.skipIf(windowsHost)(
762 "installs once when several launches race, and reclaims stale locks",
763 () =>
764 Effect.gen(function* () {
765 const fs = yield* FileSystem.FileSystem;
766 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-archive-runner-" });
767 const releaseBaseUrl = yield* makeMirror(root);
768 const runner = `${root}/run-t3.sh`;
769 yield* fs.writeFileString(
770 runner,
771 buildRemoteT3RunnerScript({ archiveVersion, releaseBaseUrl }),
772 );
773 const home = `${root}/home`;
774 yield* fs.makeDirectory(home, { recursive: true });
775
776 const results = yield* Effect.all(
777 [runRunner(home, runner), runRunner(home, runner), runRunner(home, runner)],
778 { concurrency: "unbounded" },
779 );
780 for (const result of results) {
781 assert.equal(result.exitCode, 0, result.stderr);
782 assert.include(result.stdout, `t3 v${archiveVersion}`);
783 }
784 const versionsDir = `${home}/.t3/runtime/versions`;
785 assert.deepEqual(yield* fs.readDirectory(versionsDir), [archiveVersion]);
786 assert.equal(
787 (yield* fs.readFileString(`${versionsDir}/${archiveVersion}/.install-complete`)).trim(),
788 archiveVersion,
789 );
790
791 // A lock left by a crashed installer (dead pid) must not block the
792 // next launch, and neither must one that never published a pid.
793 const lock = `${versionsDir}/.${archiveVersion}.install.lock`;
794 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
795 yield* fs.makeDirectory(lock);
796 yield* fs.writeFileString(`${lock}/pid`, "999999\n");
797 const afterDead = yield* runRunner(home, runner);
798 assert.equal(afterDead.exitCode, 0, afterDead.stderr);
799
800 yield* fs.remove(`${versionsDir}/${archiveVersion}`, { recursive: true });
801 yield* fs.makeDirectory(lock);
802 const afterUnowned = yield* runRunner(home, runner);
803 assert.equal(afterUnowned.exitCode, 0, afterUnowned.stderr);
804 assert.isFalse(yield* fs.exists(lock));
805 }).pipe(Effect.provide(NodeServices.layer)),
806 60_000,
807 );
808});