Skip to content

Commit 721acc6

Browse files
feat(ssh): run preview builds on remotes from the release archive
When the desktop app is a preview build, the SSH launcher installs the matching release archive into ~/.t3/runtime/versions on the remote and runs its executable instead of npx. The port picker, readiness probe, and default-runtime lookup the launch script used to run as inline node snippets now live in a hidden __ssh-helper subcommand, so the remote needs neither Node nor npm. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent dcb1d0b commit 721acc6

5 files changed

Lines changed: 247 additions & 1 deletion

File tree

‎apps/desktop/src/main.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as Electron from "electron";
1616

1717
import * as NetService from "@t3tools/shared/Net";
1818
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
19+
import { isArchiveDistributedVersion } from "@t3tools/shared/cliRelease";
1920
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
2021
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
2122
import serverPackageJson from "../../server/package.json" with { type: "json" };
@@ -96,6 +97,11 @@ const resolveDesktopSshCliRunner = (
9697
nodeEngineRange: serverPackageJson.engines.node,
9798
};
9899
}
100+
// Preview builds ship as self-contained archives, so the remote runs the
101+
// same version this app is on without Node or npm.
102+
if (!environment.isDevelopment && isArchiveDistributedVersion(environment.appVersion)) {
103+
return { archiveVersion: environment.appVersion };
104+
}
99105
return {
100106
packageSpec: resolveRemoteT3CliPackageSpec({
101107
appVersion: environment.appVersion,

‎apps/server/src/bin.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
1919
import { serviceCommand } from "./cli/service.ts";
2020
import { serviceLauncherCommand } from "./cli/serviceLauncher.ts";
2121
import { servicePreflightCommand } from "./cli/servicePreflight.ts";
22+
import { sshHelperCommand } from "./cli/sshHelper.ts";
2223
import { themeCommand } from "./cli/theme.ts";
2324
import { triageCommand } from "./cli/triage.ts";
2425

@@ -62,6 +63,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
6263
serviceCommand,
6364
serviceLauncherCommand,
6465
servicePreflightCommand,
66+
sshHelperCommand,
6567
themeCommand,
6668
triageCommand,
6769
cloudEnabled ? connectCommand : connectUnavailableCommand,

‎apps/server/src/cli/sshHelper.ts‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
// @effect-diagnostics nodeBuiltinImport:off
2+
// @effect-diagnostics globalTimers:off
3+
// @effect-diagnostics globalDateInEffect:off
4+
// The helpers mirror the inline Node snippets the SSH launch script used to
5+
// run, byte for byte in behaviour, so they stay on plain Node APIs.
6+
import * as NodeFS from "node:fs";
7+
import * as NodeHttp from "node:http";
8+
import * as NodeNet from "node:net";
9+
10+
import * as Effect from "effect/Effect";
11+
import { Argument, Command } from "effect/unstable/cli";
12+
13+
/**
14+
* Small helpers the SSH launch script needs on the remote host. The script
15+
* used to run these as inline `node -` snippets; archive-distributed runtimes
16+
* have no Node on the remote, so the executable provides them instead. Output
17+
* and exit codes match the snippets exactly because the shell script parses
18+
* them.
19+
*/
20+
21+
const tryPort = (port: number) =>
22+
new Promise<number | false>((resolve) => {
23+
const server = NodeNet.createServer();
24+
server.unref();
25+
server.once("error", () => resolve(false));
26+
server.listen(port, "127.0.0.1", () => {
27+
server.close((error) => resolve(error ? false : port));
28+
});
29+
});
30+
31+
/** Prints the first free loopback port from the preferred one, scanning `window` ports. */
32+
const pickPort = Command.make("pick-port", {
33+
portFile: Argument.string("port-file"),
34+
defaultPort: Argument.integer("default-port"),
35+
scanWindow: Argument.integer("scan-window"),
36+
}).pipe(
37+
Command.withHandler(({ portFile, defaultPort, scanWindow }) =>
38+
Effect.promise(async () => {
39+
const raw = NodeFS.existsSync(portFile) ? NodeFS.readFileSync(portFile, "utf8").trim() : "";
40+
const preferred = Number.parseInt(raw, 10);
41+
const start = Number.isInteger(preferred) ? preferred : defaultPort;
42+
for (let port = start; port < start + scanWindow; port += 1) {
43+
if (await tryPort(port)) {
44+
process.stdout.write(String(port));
45+
return;
46+
}
47+
}
48+
process.exitCode = 1;
49+
}),
50+
),
51+
);
52+
53+
const probe = (port: number, probeTimeoutMs: number) =>
54+
new Promise<boolean>((resolve) => {
55+
const request = NodeHttp.get(
56+
{ hostname: "127.0.0.1", port, path: "/", timeout: probeTimeoutMs },
57+
(response) => {
58+
response.resume();
59+
response.once("end", () => {
60+
const status = response.statusCode ?? 0;
61+
resolve(status >= 200 && status < 300);
62+
});
63+
},
64+
);
65+
request.once("timeout", () => {
66+
request.destroy();
67+
resolve(false);
68+
});
69+
request.once("error", () => resolve(false));
70+
});
71+
72+
/** Exits 0 once the loopback server answers, 1 when the deadline passes first. */
73+
const waitReady = Command.make("wait-ready", {
74+
port: Argument.integer("port"),
75+
timeoutMs: Argument.integer("timeout-ms"),
76+
probeTimeoutMs: Argument.integer("probe-timeout-ms"),
77+
}).pipe(
78+
Command.withHandler(({ port, timeoutMs, probeTimeoutMs }) =>
79+
Effect.promise(async () => {
80+
const deadline = Date.now() + timeoutMs;
81+
while (Date.now() < deadline) {
82+
if (await probe(port, probeTimeoutMs)) return;
83+
await new Promise((resolve) => setTimeout(resolve, 100));
84+
}
85+
process.exitCode = 1;
86+
}),
87+
),
88+
);
89+
90+
/** Prints `<pid> <port>` for a live default-home server, or exits 1. */
91+
const runtimePort = Command.make("runtime-port", {
92+
runtimeFile: Argument.string("runtime-file"),
93+
}).pipe(
94+
Command.withHandler(({ runtimeFile }) =>
95+
Effect.sync(() => {
96+
try {
97+
// @effect-diagnostics-next-line preferSchemaOverJson:off - mirrors the shell snippet's loose parse.
98+
const runtime = JSON.parse(NodeFS.readFileSync(runtimeFile, "utf8")) as {
99+
pid?: unknown;
100+
port?: unknown;
101+
origin?: unknown;
102+
};
103+
const pid = Number(runtime.pid);
104+
const port = Number(runtime.port);
105+
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port)) {
106+
process.exitCode = 1;
107+
return;
108+
}
109+
const origin = new URL(String(runtime.origin ?? ""));
110+
if (origin.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(origin.hostname)) {
111+
process.exitCode = 1;
112+
return;
113+
}
114+
process.kill(pid, 0);
115+
process.stdout.write(`${pid} ${port}`);
116+
} catch {
117+
process.exitCode = 1;
118+
}
119+
}),
120+
),
121+
);
122+
123+
export const sshHelperCommand = Command.make("__ssh-helper").pipe(
124+
Command.unlisted,
125+
Command.withSubcommands([pickPort, waitReady, runtimePort]),
126+
);

‎packages/ssh/src/tunnel.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,36 @@ describe("ssh tunnel scripts", () => {
130130
assert.notInclude(script, "ensure $NVM_DIR/nvm.sh is available");
131131
});
132132

133+
it("installs and runs the release archive when an archive version is set", () => {
134+
const script = buildRemoteT3RunnerScript({ archiveVersion: "1.2.3-preview.20260911.4" });
135+
136+
assert.include(script, "T3_ARCHIVE_VERSION='1.2.3-preview.20260911.4'");
137+
assert.include(
138+
script,
139+
"T3_RELEASE_BASE_URL='https://github.com/pingdotgg/t3code/releases/download'",
140+
);
141+
assert.include(script, 'T3_RUNTIME_DIR="$HOME/.t3/runtime/versions/$T3_ARCHIVE_VERSION"');
142+
assert.include(script, 'T3_ARCHIVE="t3-$T3_ARCHIVE_VERSION-$T3_PLATFORM-$T3_ARCH.tar.gz"');
143+
assert.include(script, "SHA256SUMS");
144+
assert.include(script, 'exec "$T3_RUNTIME_DIR/t3" "$@"');
145+
// The archive branch execs before any of the Node discovery runs.
146+
assert.isBelow(
147+
script.indexOf('exec "$T3_RUNTIME_DIR/t3"'),
148+
script.indexOf("prepend_path_if_dir()"),
149+
);
150+
151+
const launch = buildRemoteLaunchScript({
152+
archiveVersion: "1.2.3-preview.20260911.4",
153+
releaseBaseUrl: "https://mirror.example/t3/",
154+
});
155+
assert.include(launch, "T3_ARCHIVE_MODE=1");
156+
assert.include(launch, "T3_RELEASE_BASE_URL='https://mirror.example/t3'");
157+
assert.include(launch, '"$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE"');
158+
assert.include(launch, '"$RUNNER_FILE" __ssh-helper wait-ready "$REMOTE_PORT"');
159+
assert.include(launch, '"$RUNNER_FILE" __ssh-helper runtime-port "$DEFAULT_RUNTIME_FILE"');
160+
assert.include(buildRemoteLaunchScript(), "T3_ARCHIVE_MODE=0");
161+
});
162+
133163
it("does not hard-code a remote node engine range", () => {
134164
const script = buildRemoteT3RunnerScript();
135165

‎packages/ssh/src/tunnel.ts‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
describeReadinessCause,
77
waitForHttpReady as waitForHttpReadyShared,
88
} from "@t3tools/shared/httpReadiness";
9+
import { CLI_RELEASE_REPOSITORY } from "@t3tools/shared/cliRelease";
910
import * as NetService from "@t3tools/shared/Net";
1011
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
1112
import { satisfiesSemverRange } from "@t3tools/shared/semver";
@@ -62,6 +63,12 @@ export interface RemoteT3RunnerOptions {
6263
readonly packageSpec?: string;
6364
readonly nodeScriptPath?: string | null;
6465
readonly nodeEngineRange?: string | null;
66+
/**
67+
* Exact version whose release archive the remote installs and runs. Takes
68+
* precedence over `packageSpec`; the remote then needs neither Node nor npm.
69+
*/
70+
readonly archiveVersion?: string | null;
71+
readonly releaseBaseUrl?: string | null;
6572
}
6673

6774
export interface SshEnvironmentManagerOptions {
@@ -108,6 +115,9 @@ function sshTargetLogFields(target: DesktopSshEnvironmentTarget) {
108115
}
109116

110117
function sshRunnerLogFields(runner: RemoteT3RunnerOptions | undefined) {
118+
if (runner?.archiveVersion?.trim()) {
119+
return { runner: "archive", archiveVersion: runner.archiveVersion.trim() };
120+
}
111121
if (runner?.nodeScriptPath?.trim()) {
112122
return { runner: "node-script", nodeScriptPath: runner.nodeScriptPath.trim() };
113123
}
@@ -404,6 +414,53 @@ ensure_remote_node_path() {
404414

405415
const REMOTE_RUNNER_SCRIPT = `#!/bin/sh
406416
set -eu
417+
T3_ARCHIVE_VERSION=@@T3_ARCHIVE_VERSION@@
418+
if [ -n "$T3_ARCHIVE_VERSION" ]; then
419+
# Self-contained release archive: no Node, npm, or compiler on the remote.
420+
# Unpacked into the pinned-runtime layout so \`t3 service install\` reuses it.
421+
T3_RELEASE_BASE_URL=@@T3_RELEASE_BASE_URL@@
422+
T3_RUNTIME_DIR="$HOME/.t3/runtime/versions/$T3_ARCHIVE_VERSION"
423+
if [ ! -x "$T3_RUNTIME_DIR/t3" ] || [ "$(cat "$T3_RUNTIME_DIR/.install-complete" 2>/dev/null)" != "$T3_ARCHIVE_VERSION" ]; then
424+
case "$(uname -s)" in
425+
Darwin) T3_PLATFORM="darwin" ;;
426+
Linux) T3_PLATFORM="linux" ;;
427+
*) printf 'Remote host %s has no t3 release archive.\\n' "$(uname -s)" >&2; exit 1 ;;
428+
esac
429+
case "$(uname -m)" in
430+
arm64 | aarch64) T3_ARCH="arm64" ;;
431+
x86_64 | amd64) T3_ARCH="x64" ;;
432+
*) printf 'Remote host %s has no t3 release archive.\\n' "$(uname -m)" >&2; exit 1 ;;
433+
esac
434+
T3_ARCHIVE="t3-$T3_ARCHIVE_VERSION-$T3_PLATFORM-$T3_ARCH.tar.gz"
435+
mkdir -p "$HOME/.t3/runtime/versions"
436+
T3_STAGING="$(mktemp -d "$HOME/.t3/runtime/versions/.staging-XXXXXX")"
437+
trap 'rm -rf "$T3_STAGING"' EXIT
438+
t3_fetch() {
439+
if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
440+
elif command -v wget >/dev/null 2>&1; then wget -q "$1" -O "$2"
441+
else printf 'Remote host needs curl or wget to download %s.\\n' "$T3_ARCHIVE" >&2; exit 1
442+
fi
443+
}
444+
t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/SHA256SUMS" "$T3_STAGING/SHA256SUMS"
445+
t3_fetch "$T3_RELEASE_BASE_URL/v$T3_ARCHIVE_VERSION/$T3_ARCHIVE" "$T3_STAGING/$T3_ARCHIVE"
446+
T3_EXPECTED="$(grep " \\*\\{0,1\\}$T3_ARCHIVE$" "$T3_STAGING/SHA256SUMS" | cut -d' ' -f1)"
447+
if command -v sha256sum >/dev/null 2>&1; then
448+
T3_ACTUAL="$(sha256sum "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)"
449+
else
450+
T3_ACTUAL="$(shasum -a 256 "$T3_STAGING/$T3_ARCHIVE" | cut -d' ' -f1)"
451+
fi
452+
if [ -z "$T3_EXPECTED" ] || [ "$T3_ACTUAL" != "$T3_EXPECTED" ]; then
453+
printf 'Checksum mismatch for %s.\\n' "$T3_ARCHIVE" >&2; exit 1
454+
fi
455+
tar -xzf "$T3_STAGING/$T3_ARCHIVE" -C "$T3_STAGING" --strip-components=1
456+
rm -f "$T3_STAGING/$T3_ARCHIVE" "$T3_STAGING/SHA256SUMS"
457+
printf '%s\\n' "$T3_ARCHIVE_VERSION" > "$T3_STAGING/.install-complete"
458+
rm -rf "$T3_RUNTIME_DIR"
459+
mv "$T3_STAGING" "$T3_RUNTIME_DIR"
460+
trap - EXIT
461+
fi
462+
exec "$T3_RUNTIME_DIR/t3" "$@"
463+
fi
407464
@@T3_NODE_ENV_SCRIPT@@
408465
ensure_remote_node_path || true
409466
T3_NODE_SCRIPT_PATH=@@T3_NODE_SCRIPT_PATH@@
@@ -473,16 +530,30 @@ if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then
473530
fi
474531
mv "$RUNNER_NEXT" "$RUNNER_FILE"
475532
chmod 700 "$RUNNER_FILE"
476-
if ! ensure_remote_node_path; then
533+
T3_ARCHIVE_MODE=@@T3_ARCHIVE_MODE@@
534+
if [ "$T3_ARCHIVE_MODE" = "1" ]; then
535+
# The archive ships the helpers below inside the executable; the remote
536+
# needs no Node at all. Resolving the runner once here also downloads the
537+
# archive before the port and readiness probes rely on it.
538+
"$RUNNER_FILE" --version >/dev/null
539+
elif ! ensure_remote_node_path; then
477540
printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
478541
exit 1
479542
fi
480543
pick_port() {
544+
if [ "$T3_ARCHIVE_MODE" = "1" ]; then
545+
"$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@"
546+
return
547+
fi
481548
node - "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" <<'NODE'
482549
@@T3_PICK_PORT_SCRIPT@@
483550
NODE
484551
}
485552
wait_ready() {
553+
if [ "$T3_ARCHIVE_MODE" = "1" ]; then
554+
"$RUNNER_FILE" __ssh-helper wait-ready "$REMOTE_PORT" "$1" "@@T3_READY_PROBE_TIMEOUT_MS@@"
555+
return
556+
fi
486557
node - "$REMOTE_PORT" "$1" "@@T3_READY_PROBE_TIMEOUT_MS@@" <<'NODE'
487558
@@T3_WAIT_READY_SCRIPT@@
488559
NODE
@@ -496,6 +567,10 @@ wait_for_pid_exit() {
496567
done
497568
}
498569
resolve_default_runtime_port() {
570+
if [ "$T3_ARCHIVE_MODE" = "1" ]; then
571+
"$RUNNER_FILE" __ssh-helper runtime-port "$DEFAULT_RUNTIME_FILE"
572+
return
573+
fi
499574
node - "$DEFAULT_RUNTIME_FILE" <<'NODE'
500575
const fs = require("node:fs");
501576
const runtimePath = process.argv[2] ?? "";
@@ -653,10 +728,16 @@ fi
653728
export function buildRemoteT3RunnerScript(input?: RemoteT3RunnerOptions): string {
654729
const packageSpec = shellSingleQuote(input?.packageSpec?.trim() || "t3@latest");
655730
const nodeScriptPath = input?.nodeScriptPath?.trim() || "";
731+
const archiveVersion = input?.archiveVersion?.trim() || "";
732+
const releaseBaseUrl =
733+
input?.releaseBaseUrl?.trim().replace(/\/+$/u, "") ||
734+
`https://github.com/${CLI_RELEASE_REPOSITORY}/releases/download`;
656735
return stripTrailingNewlines(
657736
applyScriptPlaceholders(REMOTE_RUNNER_SCRIPT, {
658737
T3_PACKAGE_SPEC: packageSpec,
659738
T3_NODE_SCRIPT_PATH: shellSingleQuote(nodeScriptPath),
739+
T3_ARCHIVE_VERSION: shellSingleQuote(archiveVersion),
740+
T3_RELEASE_BASE_URL: shellSingleQuote(releaseBaseUrl),
660741
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),
661742
}),
662743
);
@@ -673,6 +754,7 @@ export function buildRemoteNodeEnvScript(input?: RemoteT3RunnerOptions): string
673754

674755
export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
675756
return applyScriptPlaceholders(REMOTE_LAUNCH_SCRIPT, {
757+
T3_ARCHIVE_MODE: input?.archiveVersion?.trim() ? "1" : "0",
676758
T3_NODE_ENV_SCRIPT: buildRemoteNodeEnvScript(input),
677759
T3_RUNNER_SCRIPT: stripTrailingNewlines(buildRemoteT3RunnerScript(input)),
678760
T3_PICK_PORT_SCRIPT: stripTrailingNewlines(REMOTE_PICK_PORT_SCRIPT),

0 commit comments

Comments
 (0)