@devries-cameron20 / t3code Mirror · read-only / commits / 9a455f02e2
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, 17:15 UTC

fix(ssh): a renamed SSH connection keeps managing its remote server (#36351)

Julius Marminge committed Nov 13, 2026 at 12:52 UTC 9a455f02e2ddf35cc78c21757a96d3ffc3491622
4 files changed +168 -9
apps/desktop/src/main.ts
+11
@@ -12,7 +12,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
12 // @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime.
13 import * as NodeFS from "node:fs";
14 import * as NodeOS from "node:os";
15 +import * as SecureRandom from "effect/crypto/SecureRandom";
16 import * as Effect from "effect/Effect";
17 +import * as FileSystem from "effect/FileSystem";
18 import * as Layer from "effect/Layer";
19 import * as Option from "effect/Option";
20
@@ -125,6 +127,15 @@ const layerDesktopSshEnvironment = Layer.unwrap(
127 const environment = yield* DesktopEnvironment.DesktopEnvironment;
128 return DesktopSshEnvironment.layer({
129 resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)),
130 + resolveLauncherId: yield* Effect.cached(
131 + DesktopSshEnvironment.readOrCreateLauncherId(
132 + environment.path.join(environment.stateDir, "ssh-launcher-id"),
133 + ).pipe(
134 + Effect.provide(
135 + yield* Effect.context<FileSystem.FileSystem | SecureRandom.SecureRandom>(),
136 + ),
137 + ),
138 + ),
139 });
140 }),
141 );
apps/desktop/src/ssh/DesktopSshEnvironment.ts
+30 -4
@@ -19,6 +19,7 @@ import {
19 import * as SshTunnel from "@t3tools/ssh/tunnel";
20 import * as Context from "effect/Context";
21 import type * as Digest from "effect/crypto/Digest";
22 +import * as SecureRandom from "effect/crypto/SecureRandom";
23 import * as Effect from "effect/Effect";
24 import * as FileSystem from "effect/FileSystem";
25 import * as Layer from "effect/Layer";
@@ -70,8 +71,30 @@ export class DesktopSshEnvironment extends Context.Service<
71
72 export interface DesktopSshEnvironmentLayerOptions {
73 readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>;
74 + readonly resolveLauncherId?: Effect.Effect<string | null>;
75 }
76
77 +// Remote servers record this ID as their owner, so it has to outlive restarts,
78 +// updates and edits to a saved connection. Without a stored one there is none.
79 +export const readOrCreateLauncherId = Effect.fn("desktop.ssh.readOrCreateLauncherId")(
80 + function* (filePath: string) {
81 + const fileSystem = yield* FileSystem.FileSystem;
82 + const random = yield* SecureRandom.SecureRandom;
83 + // Any other read failure may hide a stored ID, which a new one would overwrite.
84 + const stored = yield* fileSystem.readFileString(filePath).pipe(
85 + Effect.catchIf(
86 + (cause) => cause.reason._tag === "NotFound",
87 + () => Effect.succeed(""),
88 + ),
89 + );
90 + if (/^[0-9a-f]{32}$/u.test(stored.trim())) return stored.trim();
91 + const launcherId = (yield* random.uuidV4()).replace(/-/g, "");
92 + yield* fileSystem.writeFileString(filePath, `${launcherId}\n`);
93 + return launcherId;
94 + },
95 + Effect.orElseSucceed(() => null),
96 +);
97 +
98 function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
99 return discoverSshHosts(input ?? {});
100 }
@@ -164,10 +187,13 @@ export const make = Effect.gen(function* () {
187 export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
188 Layer.effect(DesktopSshEnvironment, make).pipe(
189 Layer.provide(
167 - SshTunnel.SshEnvironmentManager.layer(
168 - options.resolveCliRunner === undefined
190 + SshTunnel.SshEnvironmentManager.layer({
191 + ...(options.resolveCliRunner === undefined
192 ? {}
170 - : { resolveCliRunner: options.resolveCliRunner },
171 - ),
193 + : { resolveCliRunner: options.resolveCliRunner }),
194 + ...(options.resolveLauncherId === undefined
195 + ? {}
196 + : { resolveLauncherId: options.resolveLauncherId }),
197 + }),
198 ),
199 );
packages/ssh/src/tunnel.test.ts
+84 -2
@@ -137,7 +137,7 @@ serve(40);
137 // The launch's POSIX bootstrap without the account login shell around it, so the
138 // test machine's login profile cannot move HOME.
139 const launchStateKey = (command: ChildProcess.Command) =>
140 - /exec sh -s -- (\S+)"/u.exec(commandArgs(command).join(" "))?.[1];
140 + /exec sh -s -- ([^"]+)"/u.exec(commandArgs(command).join(" "))?.[1];
141
142 // Runs the remote half of an SSH launch as a local shell
143 // whose HOME is the given directory. Every launch after the first starts once
@@ -1157,7 +1157,7 @@ server.listen(Number(flag("--port") ?? 0), "127.0.0.1", () => {
1157 const remoteArgs =
1158 stateKey === undefined
1159 ? command.args.slice(command.args.indexOf("--") + 2)
1160 - : ["sh", "-s", "--", stateKey];
1160 + : ["sh", "-s", "--", ...stateKey.split(" ")];
1161 return realSpawner.spawn(
1162 ChildProcess.make("setsid", ["-w", ...remoteArgs], {
1163 ...command.options,
@@ -1236,6 +1236,88 @@ server.listen(Number(flag("--port") ?? 0), "127.0.0.1", () => {
1236 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1237 );
1238
1239 + it.live("an update replaces the managed server after its connection is renamed", () =>
1240 + Effect.gen(function* () {
1241 + const { fs, home, fakeServer, sshAsLocalShell, stateDir } =
1242 + yield* prepare("an unrelated process");
1243 + const updatedServer = `${home}/fake-t3-next.cjs`;
1244 + yield* fs.writeFileString(updatedServer, FAKE_SERVER);
1245 + const renamed = { ...target, alias: "devbox-renamed" };
1246 + const launch = (
1247 + launchTarget: typeof renamed,
1248 + nodeScriptPath: string,
1249 + launcherId: string | null = "a".repeat(32),
1250 + ) =>
1251 + SshTunnel.launchOrReuseRemoteServer(
1252 + launchTarget,
1253 + undefined,
1254 + { nodeScriptPath },
1255 + launcherId,
1256 + ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, sshAsLocalShell));
1257 + const runtimePid = fs
1258 + .readFileString(`${home}/.t3/userdata/server-runtime.json`)
1259 + .pipe(Effect.map((runtime) => Number(JSON.parse(runtime).pid)));
1260 + const launchedPids: Array<number> = [];
1261 + yield* Effect.addFinalizer(() =>
1262 + Effect.forEach(launchedPids, (pid) =>
1263 + Effect.sync(() => {
1264 + try {
1265 + process.kill(pid, "SIGKILL");
1266 + } catch {}
1267 + }),
1268 + ),
1269 + );
1270 +
1271 + assert.equal((yield* launch(target, fakeServer)).remoteServerKind, "managed");
1272 + const originalPid = yield* runtimePid;
1273 + launchedPids.push(originalPid);
1274 +
1275 + // Another desktop on another version shares the server; it must not take it over.
1276 + const otherDesktop = yield* launch(
1277 + { ...target, alias: "devbox-other" },
1278 + updatedServer,
1279 + "b".repeat(32),
1280 + );
1281 + assert.equal(otherDesktop.remoteServerKind, "external");
1282 + assert.isTrue(yield* isRunning(originalPid), "another desktop replaced the server");
1283 +
1284 + const afterRename = yield* launch(renamed, fakeServer);
1285 + assert.equal(yield* runtimePid, originalPid, "renaming alone restarted the server");
1286 + assert.equal(
1287 + yield* fs.readFileString(`${stateDir}/managed`),
1288 + "external\n",
1289 + "the old alias still owns the server, so its disconnect would stop it",
1290 + );
1291 + const afterUpdate = yield* launch(renamed, updatedServer);
1292 + launchedPids.push(yield* runtimePid);
1293 + assert.deepEqual(
1294 + [afterRename.remoteServerKind, afterUpdate.remoteServerKind],
1295 + ["managed", "managed"],
1296 + );
1297 + assert.isFalse(
1298 + yield* isRunning(originalPid),
1299 + "the update left the server launched under the old alias running",
1300 + );
1301 +
1302 + // A rename and an update in one reconnect still replace the server.
1303 + const updatedPid = yield* runtimePid;
1304 + const renamedAndUpdated = yield* launch({ ...target, alias: "devbox-again" }, fakeServer);
1305 + launchedPids.push(yield* runtimePid);
1306 + assert.equal(renamedAndUpdated.remoteServerKind, "managed");
1307 + assert.isFalse(yield* isRunning(updatedPid), "a rename with an update kept the old server");
1308 +
1309 + // A server that a launch without an ID started under a reused key is not this desktop's.
1310 + const again = { ...target, alias: "devbox-again" };
1311 + process.kill(yield* runtimePid, "SIGKILL");
1312 + assert.equal((yield* launch(again, fakeServer, null)).remoteServerKind, "managed");
1313 + const unownedPid = yield* runtimePid;
1314 + launchedPids.push(unownedPid);
1315 + const final = yield* launch({ ...target, alias: "devbox-final" }, updatedServer);
1316 + assert.equal(final.remoteServerKind, "external");
1317 + assert.isTrue(yield* isRunning(unownedPid), "a stale launcher ID claimed another's server");
1318 + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1319 + );
1320 +
1321 it.live.each(staleIds)("disconnecting does not signal %s named by the managed pid file", (kind) =>
1322 Effect.gen(function* () {
1323 const { fs, holder, sshAsLocalShell, staleId, stateDir } = yield* prepare(kind);
packages/ssh/src/tunnel.ts
+43 -3
@@ -106,6 +106,8 @@ export interface RemoteT3RunnerOptions {
106
107 export interface SshEnvironmentManagerOptions {
108 readonly resolveCliRunner?: Effect.Effect<RemoteT3RunnerOptions>;
109 + // Identifies this install to the remote across edits of a connection; null when unknown.
110 + readonly resolveLauncherId?: Effect.Effect<string | null>;
111 }
112
113 interface SshTunnelEntry {
@@ -580,6 +582,7 @@ const REMOTE_MANAGED_SERVER_RUNNING_SCRIPT = `managed_server_running() {
582 const REMOTE_LAUNCH_SCRIPT = `set -eu
583 @@T3_NODE_ENV_SCRIPT@@
584 STATE_KEY="$1"
585 +LAUNCHER_ID="\${2:-}"
586 STATE_DIR="$HOME/.t3/ssh-launch/$STATE_KEY"
587 DEFAULT_SERVER_HOME="$HOME/.t3"
588 DEFAULT_RUNTIME_FILE="$DEFAULT_SERVER_HOME/userdata/server-runtime.json"
@@ -667,6 +670,9 @@ if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then
670 RUNNER_CHANGED=1
671 fi
672 mv "$RUNNER_NEXT" "$RUNNER_FILE"
673 +if [ -n "$LAUNCHER_ID" ]; then
674 + printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher"
675 +fi
676 pick_port() {
677 if [ "$T3_ARCHIVE_MODE" = "1" ]; then
678 "$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@"
@@ -796,7 +802,29 @@ elif [ -n "$DEFAULT_REMOTE_PORT" ]; then
802 fi
803 return 1
804 }
799 -adopt_default_server || true
805 +# Editing a connection's alias, host, user or port changes its key, so the
806 +# adopted server may be one this desktop started under another key. Ownership
807 +# then moves here, leaving one managed record, so updates keep replacing it.
808 +# Another desktop's server stays external. Only this first adoption runs
809 +# before the replace decision, which the previous key's runner settles.
810 +if adopt_default_server && [ -n "$ADOPTED_PID" ] && [ -n "$LAUNCHER_ID" ]; then
811 + for SIBLING_DIR in "$DEFAULT_SERVER_HOME"/ssh-launch/*; do
812 + [ "$SIBLING_DIR" != "$STATE_DIR" ] && [ "$(cat "$SIBLING_DIR/managed" 2>/dev/null || true)" = "managed" ] || continue
813 + [ "$(cat "$SIBLING_DIR/pid" 2>/dev/null || true)" = "$ADOPTED_PID" ] && managed_server_running "$ADOPTED_PID" || continue
814 + [ "$(cat "$SIBLING_DIR/launcher" 2>/dev/null || true)" = "$LAUNCHER_ID" ] || break
815 + REMOTE_PID="$ADOPTED_PID"
816 + REMOTE_MANAGED="managed"
817 + printf '%s\\n' "$REMOTE_PID" >"$PID_FILE"
818 + printf 'managed\\n' >"$MANAGED_FILE"
819 + printf 'external\\n' >"$SIBLING_DIR/managed"
820 + rm -f "$SIBLING_DIR/pid"
821 + RUNNER_CHANGED=1
822 + if cmp -s "$RUNNER_FILE" "$SIBLING_DIR/run-t3.sh"; then
823 + RUNNER_CHANGED=0
824 + fi
825 + break
826 + done
827 +fi
828 if [ "$REMOTE_MANAGED" = "external" ]; then
829 # A server adopted above has just answered. While it is still alive, probing
830 # it again could catch a momentary stall and launch a second server beside it.
@@ -883,6 +911,10 @@ if [ -z "$REMOTE_PORT" ]; then
911 printf '%s\\n' "$REMOTE_PID" >"$PID_FILE"
912 printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE"
913 printf 'managed\\n' >"$MANAGED_FILE"
914 + # A stop keeps the launcher file; it must not name this server's owner.
915 + if [ -z "$LAUNCHER_ID" ]; then
916 + rm -f "$STATE_DIR/launcher"
917 + fi
918 if ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then
919 printf 'Remote T3 server did not become ready on 127.0.0.1:%s.\\n' "$REMOTE_PORT" >&2
920 if [ -s "$LOG_FILE" ]; then
@@ -1058,12 +1090,18 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
1090 target: DesktopSshEnvironmentTarget,
1091 input?: SshAuth.SshAuthOptions,
1092 runner?: RemoteT3RunnerOptions,
1093 + launcherId?: string | null,
1094 ): Effect.fn.Return<
1095 { readonly remotePort: number; readonly remoteServerKind: "external" | "managed" | null },
1096 SshCommandError | SshInvalidTargetError | SshLaunchError,
1097 ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path
1098 > {
1099 const stateKey = yield* remoteStateKey(target);
1100 + // The launcher ID is interpolated into the remote shell command, so only hex passes.
1101 + const launchArgs =
1102 + typeof launcherId === "string" && /^[0-9a-f]{32}$/u.test(launcherId)
1103 + ? `${stateKey} ${launcherId}`
1104 + : stateKey;
1105 yield* Effect.logInfo("ssh.remoteServer.launch.start", {
1106 ...sshTargetLogFields(target),
1107 ...sshRunnerLogFields(runner),
@@ -1076,7 +1114,7 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo
1114 "sh",
1115 "-c",
1116 shellSingleQuote(
1079 - `case "\${SHELL##*/}" in bash|zsh|ksh|fish|nu) exec "$SHELL" -l -c "exec sh -s -- ${stateKey}" ;; *) exec sh -l -s -- ${stateKey} ;; esac`,
1117 + `case "\${SHELL##*/}" in bash|zsh|ksh|fish|nu) exec "$SHELL" -l -c "exec sh -s -- ${launchArgs}" ;; *) exec sh -l -s -- ${launchArgs} ;; esac`,
1118 ),
1119 ],
1120 stdin: buildRemoteLaunchScript(runner),
@@ -1738,11 +1776,13 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
1776 ...sshRunnerLogFields(input.runner),
1777 key: input.key,
1778 });
1779 + const launcherId =
1780 + options.resolveLauncherId === undefined ? null : yield* options.resolveLauncherId;
1781 const remoteLaunch = yield* runWithSshAuth({
1782 key: input.key,
1783 target: input.resolvedTarget,
1784 operation: (authOptions) =>
1745 - launchOrReuseRemoteServer(input.resolvedTarget, authOptions, input.runner),
1785 + launchOrReuseRemoteServer(input.resolvedTarget, authOptions, input.runner, launcherId),
1786 });
1787 const remotePort = remoteLaunch.remotePort;
1788 yield* Effect.logDebug("ssh.environment.remotePort.ready", {