@devries-cameron20 / t3code Mirror · read-only / commits / c1f8459153
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 07:15 UTC

fix(ssh): an SSH host that already has the matching t3 runs it instead of the portable archive (#35268)

Co-authored-by: Felix Mrak <180021770+felixleopold@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Felix Mrak committed Nov 19, 2026 at 07:00 UTC c1f8459153490d78c0d674b2ce5d749f31aaa4cb
2 files changed +96 -17
packages/ssh/src/tunnel.test.ts
+65 -7
@@ -341,6 +341,48 @@ describe("ssh tunnel scripts", () => {
341 },
342 );
343
344 + it.each([
345 + { installed: ARCHIVE.archiveVersion, status: 0, reuses: true },
346 + { installed: ARCHIVE.archiveVersion, status: 1, reuses: false },
347 + { installed: "9.9.9", status: 0, reuses: false },
348 + ])(
349 + "reuses a host t3 only at exactly the requested version: installed $installed, status $status",
350 + ({ installed, status, reuses }) => {
351 + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-runner-"));
352 + try {
353 + const bin = NodePath.join(root, "bin");
354 + NodeFS.mkdirSync(bin);
355 + NodeFS.mkdirSync(NodePath.join(root, "home"));
356 + // A host the release archive cannot run on, so only reuse can succeed.
357 + NodeFS.writeFileSync(
358 + NodePath.join(bin, "uname"),
359 + `#!/bin/sh\ncase "$1" in -s) echo Darwin ;; -m) echo x86_64 ;; esac\n`,
360 + { mode: 0o755 },
361 + );
362 + NodeFS.writeFileSync(
363 + NodePath.join(bin, "t3"),
364 + `#!/bin/sh\ncase "$1" in --version) echo "t3 v${installed}"; exit ${status} ;; *) echo "host t3 $*" ;; esac\n`,
365 + { mode: 0o755 },
366 + );
367 + const runner = NodePath.join(root, "run-t3.sh");
368 + NodeFS.writeFileSync(runner, SshTunnel.buildRemoteT3RunnerScript(ARCHIVE));
369 + const result = NodeChildProcess.spawnSync("sh", [runner, "serve"], {
370 + encoding: "utf8",
371 + env: { HOME: NodePath.join(root, "home"), PATH: `${bin}:${process.env.PATH ?? ""}` },
372 + });
373 + if (reuses) {
374 + assert.equal(result.status, 0);
375 + assert.equal(result.stdout, "host t3 serve\n");
376 + } else {
377 + assert.notEqual(result.status, 0);
378 + assert.include(result.stderr, "has no t3 release archive.");
379 + }
380 + } finally {
381 + NodeFS.rmSync(root, { recursive: true, force: true });
382 + }
383 + },
384 + );
385 +
386 // sha256sum and shasum escape a newline in a file name they print, so the home path has one.
387 const checksumTools =
388 NodeChildProcess.spawnSync("sh", ["-c", 'command -v "$1"', "sh", "shasum"]).status === 0
@@ -445,17 +487,20 @@ describe("ssh tunnel scripts", () => {
487 "if shopt -q login_shell; then export T3_SSH_LOGIN_ENV=loaded; fi\n",
488 );
489 const target = { alias: "login-test", hostname: "login-test", username: null, port: null };
448 - let remoteCommand = "";
490 + const remoteCommands: string[] = [];
491 const capture = ChildProcessSpawner.make((command) =>
492 Effect.sync(() => {
493 const args = commandArgs(command);
452 - remoteCommand = args.slice(args.indexOf(target.alias) + 1).join(" ");
453 - return makeSuccessfulProcess('{"remotePort":3774}\n');
494 + remoteCommands.push(args.slice(args.indexOf(target.alias) + 1).join(" "));
495 + return makeSuccessfulProcess('{"remotePort":3774,"credential":"test"}\n');
496 }),
497 );
498 yield* SshTunnel.launchOrReuseRemoteServer(target, undefined, ARCHIVE).pipe(
499 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, capture),
500 );
501 + yield* SshTunnel.issueRemotePairingToken(target, undefined, ARCHIVE).pipe(
502 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, capture),
503 + );
504 yield* fs.writeFileString(
505 `${directory}/.zprofile`,
506 "if [[ -o login ]]; then export T3_SSH_LOGIN_ENV=loaded; fi\n",
@@ -483,7 +528,9 @@ describe("ssh tunnel scripts", () => {
528 break;
529 }
530 }
486 - for (const { shell, outerShell, expected } of cases) {
531 + for (const { shell, outerShell, expected, index, remoteCommand } of cases.flatMap((entry) =>
532 + remoteCommands.map((remoteCommand, index) => ({ ...entry, remoteCommand, index })),
533 + )) {
534 const child = yield* spawner.spawn(
535 ChildProcess.make(outerShell, ["-c", remoteCommand], {
536 env: {
@@ -526,7 +573,11 @@ describe("ssh tunnel scripts", () => {
573 assert.equal(Number(exitCode), 0, stderr);
574 // First-run shell messages can precede the bootstrap response.
575 const response = stdout.trim().split(/\r?\n/u).at(-1) ?? "";
529 - assert.match(response, new RegExp(`^${expected}:[a-f0-9]{16}$`), shell || "unset SHELL");
576 + assert.match(
577 + response,
578 + new RegExp(index === 0 ? `^${expected}:[a-f0-9]{16}$` : `^${expected}:$`),
579 + shell || "unset SHELL",
580 + );
581 }
582 }).pipe(Effect.provide(Layer.merge(NodeServices.layer, NodeCrypto.layer))),
583 );
@@ -1099,8 +1150,9 @@ describe("ssh tunnel scripts", () => {
1150
1151 it.live("concurrent launches on one remote home record the server that owns it", () =>
1152 // The second row's server never publishes server-runtime.json.
1102 - Effect.forEach([1_500, null], (publishDelayMs) =>
1153 + Effect.forEach([1_500, null, "wrapper"] as const, (variant) =>
1154 Effect.gen(function* () {
1155 + const publishDelayMs = variant === "wrapper" ? 0 : variant;
1156 const fs = yield* FileSystem.FileSystem;
1157 const path = yield* Path.Path;
1158 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-launch-" });
@@ -1119,6 +1171,12 @@ describe("ssh tunnel scripts", () => {
1171 );
1172 const serverScript = path.join(home, "fake-t3.cjs");
1173 yield* fs.writeFileString(serverScript, fakeT3Serve(publishDelayMs));
1174 + const wrapperScript = path.join(home, "wrapper.cjs");
1175 + yield* fs.writeFileString(
1176 + wrapperScript,
1177 + `const child = require("node:child_process").spawn(process.execPath, [${JSON.stringify(serverScript)}, ...process.argv.slice(2)], { stdio: "inherit" });
1178 +child.on("exit", (code) => process.exit(code ?? 1));`,
1179 + );
1180 // A launch that died holding the lock must not block or double-admit later ones.
1181 const launchLock = path.join(home, ".t3", "ssh-launch", ".launch.lock");
1182 yield* fs.makeDirectory(path.dirname(launchLock), { recursive: true });
@@ -1132,7 +1190,7 @@ describe("ssh tunnel scripts", () => {
1190 targets,
1191 (target) =>
1192 SshTunnel.launchOrReuseRemoteServer(target, undefined, {
1135 - nodeScriptPath: serverScript,
1193 + nodeScriptPath: variant === "wrapper" ? wrapperScript : serverScript,
1194 }),
1195 { concurrency: "unbounded" },
1196 ).pipe(Effect.provide(localRemoteShellLayer(home)));
packages/ssh/src/tunnel.ts
+31 -10
@@ -480,6 +480,12 @@ if [ -z "$T3_ARCHIVE_VERSION" ]; then
480 printf 'No t3 release version was provided for the remote runtime.\\n' >&2
481 exit 1
482 fi
483 +T3_SYSTEM_EXECUTABLE="$(command -v t3 2>/dev/null || true)"
484 +if [ -n "$T3_SYSTEM_EXECUTABLE" ] && T3_SYSTEM_VERSION="$("$T3_SYSTEM_EXECUTABLE" --version 2>/dev/null)" && [ "$T3_SYSTEM_VERSION" = "t3 v$T3_ARCHIVE_VERSION" ]; then
485 + # A matching host-provided runtime supports platforms such as musl Linux,
486 + # where the portable release archive cannot run.
487 + exec "$T3_SYSTEM_EXECUTABLE" "$@"
488 +fi
489 # Self-contained release archive: no Node, npm, or compiler on the remote.
490 # Unpacked into the pinned-runtime layout so \`t3 service install\` reuses it.
491 T3_RELEASE_BASE_URL=@@T3_RELEASE_BASE_URL@@
@@ -1001,6 +1007,19 @@ if [ -z "$REMOTE_PORT" ]; then
1007 while [ "$(date +%s)" -lt "$RECORD_DEADLINE" ]; do
1008 DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port 2>/dev/null || true)"
1009 [ "\${DEFAULT_RUNTIME_INFO%% *}" = "$REMOTE_PID" ] && break
1010 + # A host wrapper can spawn the server instead of replacing itself.
1011 + RUNTIME_PID="\${DEFAULT_RUNTIME_INFO%% *}"
1012 + if [ "\${DEFAULT_RUNTIME_INFO#* }" = "$REMOTE_PORT" ] && managed_server_running "$RUNTIME_PID"; then
1013 + RUNTIME_ANCESTOR="$RUNTIME_PID"
1014 + while [ -n "$RUNTIME_ANCESTOR" ] && [ "$RUNTIME_ANCESTOR" != "1" ] && [ "$RUNTIME_ANCESTOR" != "$REMOTE_PID" ]; do
1015 + RUNTIME_ANCESTOR="$(ps -o ppid= -p "$RUNTIME_ANCESTOR" 2>/dev/null | tr -d '[:space:]')"
1016 + done
1017 + if [ "$RUNTIME_ANCESTOR" = "$REMOTE_PID" ]; then
1018 + REMOTE_PID="$RUNTIME_PID"
1019 + printf '%s\\n' "$REMOTE_PID" >"$PID_FILE"
1020 + break
1021 + fi
1022 + fi
1023 sleep 0.1
1024 done
1025 fi
@@ -1154,6 +1173,16 @@ function buildRemoteLogTailScript(stateKey: string): string {
1173 });
1174 }
1175
1176 +// Shells known to take `-l -c` with a POSIX-style `exec` read their own login
1177 +// profiles first; any other shell (csh, pwsh, ...) keeps the plain `sh -l` launch.
1178 +const remoteLoginShellArgs = (args = "") => [
1179 + "sh",
1180 + "-c",
1181 + shellSingleQuote(
1182 + `case "\${SHELL##*/}" in bash|zsh|ksh|fish|nu) exec "$SHELL" -l -c "exec sh -s${args ? ` -- ${args}` : ""}" ;; *) exec sh -l -s${args ? ` -- ${args}` : ""} ;; esac`,
1183 + ),
1184 +];
1185 +
1186 export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemoteServer")(
1187 function* (
1188 target: DesktopSshEnvironmentTarget,
@@ -1177,15 +1206,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
1206 stateKey,
1207 });
1208 const result = yield* runSshCommand(target, {
1180 - // Shells known to take `-l -c` with a POSIX-style `exec` read their own login
1181 - // profiles first; any other shell (csh, pwsh, ...) keeps the plain `sh -l` launch.
1182 - remoteCommandArgs: [
1183 - "sh",
1184 - "-c",
1185 - shellSingleQuote(
1186 - `case "\${SHELL##*/}" in bash|zsh|ksh|fish|nu) exec "$SHELL" -l -c "exec sh -s -- ${launchArgs}" ;; *) exec sh -l -s -- ${launchArgs} ;; esac`,
1187 - ),
1188 - ],
1209 + remoteCommandArgs: remoteLoginShellArgs(launchArgs),
1210 stdin: buildRemoteLaunchScript(runner),
1211 timeoutMs: isNodeScriptRunner(runner)
1212 ? REMOTE_LAUNCH_TIMEOUT_MS
@@ -1246,7 +1267,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT
1267 stateKey,
1268 });
1269 const result = yield* runSshCommand(target, {
1249 - remoteCommandArgs: ["sh", "-s"],
1270 + remoteCommandArgs: remoteLoginShellArgs(),
1271 stdin: buildRemotePairingScript(stateKey, runner),
1272 ...(isNodeScriptRunner(runner) ? {} : { timeoutMs: REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS }),
1273 ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),