Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(ssh): fix reconnect issues and node binary path resolution #2504

Mergedjuliusmarmingemerged 7 commits intomain fromrefs/pull/2504/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

Fixes SSH launcher failure modes reported from remote Linux hosts:

  • bootstrap now recovers Node in non-interactive sh -s SSH sessions before running remote Node helper scripts or the T3 runner
  • Node discovery handles common install locations and version managers, including Volta, asdf, mise, fnm, nodenv, and nvm
  • the standalone SSH launcher accepts the required Node engine range as an option; the desktop app passes apps/server/package.json's engines.node range and the selected remote Node is validated before launch
  • reconnect after desktop app updates no longer reuses a launcher-managed remote server as if it were external; it stops stale managed processes and clears SSH state before relaunching
  • launch and pairing output parsing now tolerates shell startup noise before the final JSON payload
  • REMOTE.md now documents SSH launch troubleshooting, Node requirements, version-manager resolution, and reconnect cleanup behavior

Closes #2534

Root Cause

The remote bootstrap ran under non-interactive sh, so hosts with Node exposed only through shell setup from a version manager could fail with node: command not found during port picking/readiness. Even when a Node binary was found, the launcher did not check that it satisfied the server package's runtime engine range before starting helper scripts and the server. Separately, the shared remote runtime file could make a launcher-managed process look like an external server before runner-change restart logic ran, leaving users stuck after updates unless they manually killed remote t3code state.

Validation

  • bun fmt
  • bun lint (passes with existing warnings)
  • bun typecheck
  • bun run --filter @t3tools/ssh test

Note

Medium Risk Medium risk: changes the SSH bootstrap/launch scripts and remote server reuse logic, which can affect connectivity and remote process lifecycle across diverse host environments. Also replaces version-comparison utilities used for provider/CLI gating, which could alter upgrade/advisory behavior if edge cases differ.

Overview Hardens desktop-managed SSH launch/reconnect on remote hosts. The SSH bootstrap now tries to locate/activate a compatible remote node in non-interactive sh sessions (common paths + Volta/asdf/mise/fnm/nodenv/nvm), and can enforce a required Node engine range before running helper scripts or starting t3.

Launch/pairing output decoding is made resilient to shell startup noise by extracting the JSON object from stdout before decoding. Reconnect behavior is adjusted to avoid treating stale launcher-managed servers as “external” by stopping them and clearing/refreshing saved PID/port state.

Separately, a shared @t3tools/shared/semver module is introduced (with tests) and replaces the server’s custom cliVersion comparator; extractJsonObject is moved into @t3tools/shared/schemaJson and reused by text-generation and SSH parsing. REMOTE.md gains detailed SSH launch troubleshooting and Node requirements.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c4be90c49ffbdf32315f4fc035a511fb6fb0d5c5. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Fix SSH reconnect issues and Node binary path resolution for remote launch

  • Remote launch and runner scripts now bootstrap Node onto PATH for non-interactive shells by probing common install locations and initializing version managers (volta, asdf, mise, fnm, nodenv, nvm) via REMOTE_NODE_ENV_SCRIPT in tunnel.ts
  • Adds optional Node engine range enforcement: a self-contained satisfiesSemverRange implementation (valid plain JS for remote execution) is stringified and sent to the remote host to validate the Node version before proceeding
  • SSH launch and pairing token output parsing now tolerates shell startup noise by extracting JSON from mixed stdout via a new decodeRemoteJsonOutput helper
  • Consolidates semver utilities into a new @t3tools/shared/semver package, replacing local compareCliVersions in ClaudeProvider, OpenCodeProvider, and providerMaintenance
  • Moves extractJsonObject to @t3tools/shared/schemaJson, removing duplication from TextGenerationUtils
Macroscope summarized c4be90c.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: d1656d40-cd49-4d1b-9d28-920181e5a609

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `t3code/11970999`

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. juliusmarminge changed the title

    4. juliusmarminge changed the title

    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/tunnel.ts:587

      When a default runtime server is ready and REMOTE_MANAGED="managed", the code clears all state variables and deletes the state files (lines 594-597), then falls through to launch a brand new managed server at line 635. The ready external server at DEFAULT_REMOTE_PORT is neither recorded nor reused. Contrast this with the non-managed branch (lines 599-602), which correctly persists the external server's port. This asymmetry means stopping a managed server to adopt an external server actually launches a duplicate managed server instead.

      ✅ Resolved in d43dad663ec14fdf342a07eede01cd908adf8266

    6. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR introduces substantial SSH launch behavior changes including node version manager detection and reconnect handling. Three unresolved review comments identify potential bugs: JSON extraction may fail with certain shell output, misleading error messages, and risk of killing external servers. These substantive issues warrant human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    7. @@ -167,2 +169,21 @@
      167169 const decodeRemoteHttpError = Schema.decodeEffect(Schema.fromJsonString(RemoteHttpError));
      168170
      171+const decodeRemoteJsonOutput = <A, E>(
      172+ stdout: string,
      173+ decode: (input: string) => Effect.Effect<A, E>,
      174+): Effect.Effect<A, E> =>
      175+ decode(stdout).pipe(
      176+ Effect.catch((error) =>
      177+ Effect.gen(function* () {
      178+ const jsonObject = extractJsonObject(stdout);
      179+ if (jsonObject === stdout.trim()) {
      180+ return yield* Effect.fail(error);
      181+ }
      182+ const exit = yield* Effect.exit(decode(jsonObject));
      183+ if (Exit.isSuccess(exit)) {
      184+ return exit.value;
      185+ }
      186+ return yield* Effect.fail(error);
      187+ }),
      188+ ),
      189+ );
      cursor[bot](GitHub profile, opens in a new tab)commented

      JSON extraction finds first brace, not last payload

      Medium Severity

      decodeRemoteJsonOutput falls back to extractJsonObject which finds the first { in stdout, not the last JSON payload. If shell startup noise from version managers contains any { character (e.g., nvm: {default} or asdf: update {notice}), the extraction grabs the wrong substring, decoding fails, and the valid JSON payload later in the output is never attempted — causing a spurious SSH launch or pairing failure.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 394dc2913e93245da3a1d8564aff2bdec046f595. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -343,3 +488,7 @@
      343488 fi
      344489 mv "$RUNNER_NEXT" "$RUNNER_FILE"
      345490 chmod 700 "$RUNNER_FILE"
      491+if ! ensure_remote_node_path; then
      492+ printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2
      493+ exit 1
      494+fi
      cursor[bot](GitHub profile, opens in a new tab)commented

      Misleading error when node version fails range check

      Low Severity

      When ensure_remote_node_path fails because the discovered node doesn't satisfy the engine range (not because node is missing), the launch script prints "Remote host is missing node on PATH" which contradicts the earlier stderr message from remote_node_satisfies_engine saying the node version doesn't satisfy the required range. Users troubleshooting SSH launch failures would see conflicting guidance.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 394dc2913e93245da3a1d8564aff2bdec046f595. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 3 total unresolved issues (including 2 from previous reviews).

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Caret operator incorrect for semver major version zero
        • Added special-case handling for the caret operator when major is zero: pins minor when major=0 and minor!=0, and pins patch when both major=0 and minor=0, matching the semver specification.

      Create PR

      Or push these changes by commenting:

      @cursor push 6d301562d5
      Preview (pingdotgg/t3code@6d301562d5)
      diff --git a/packages/shared/src/semver.ts b/packages/shared/src/semver.ts
      --- a/packages/shared/src/semver.ts
      +++ b/packages/shared/src/semver.ts
      @@ -188,7 +188,20 @@
               const operator = match[1] || "=";
               switch (operator) {
                 case "^":
      -            return version.major === target.major && compared >= 0;
      +            if (target.major !== 0) {
      +              return version.major === target.major && compared >= 0;
      +            }
      +            if (target.minor !== 0) {
      +              return (
      +                version.major === target.major && version.minor === target.minor && compared >= 0
      +              );
      +            }
      +            return (
      +              version.major === target.major &&
      +              version.minor === target.minor &&
      +              version.patch === target.patch &&
      +              compared >= 0
      +            );
                 case ">=":
                   return compared >= 0;
                 case ">":
      You can send follow-ups to the cloud agent here.
    9. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/d43dad663ec14fdf342a07eede01cd908adf8266/packages/ssh/src/tunnel.ts#L520

      The resolve_default_runtime_port node script validates pid using only Number.isInteger(), which accepts 0 as valid. When server-runtime.json contains null for pid, Number(null) produces 0, passes validation, and is output at line 529. This becomes DEFAULT_RUNTIME_PID="0" in the shell. At line 549, kill 0 sends SIGTERM to the entire current process group, terminating the SSH session and other processes. Consider adding pid > 0 to the validation check.

      ✅ Resolved in c4be90c49ffbdf32315f4fc035a511fb6fb0d5c5

    10. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      There are 3 total unresolved issues (including 2 from previous reviews).

      Fix All in Cursor

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Fallback PID may kill external server unintentionally
        • Removed the ${REMOTE_PID:-$DEFAULT_RUNTIME_PID} fallback so PID_TO_STOP is set to $REMOTE_PID directly, preventing an empty REMOTE_PID from resolving to the external server's PID.

      Create PR

      Or push these changes by commenting:

      @cursor push a2607dec13
      Preview (pingdotgg/t3code@a2607dec13)
      diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts
      --- a/packages/ssh/src/tunnel.ts
      +++ b/packages/ssh/src/tunnel.ts
      @@ -546,7 +546,7 @@
         REMOTE_PORT="$DEFAULT_REMOTE_PORT"
         if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
           if [ "$REMOTE_MANAGED" = "managed" ]; then
      -      PID_TO_STOP="\${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"
      +      PID_TO_STOP="$REMOTE_PID"
             if [ -n "$PID_TO_STOP" ] && kill -0 "$PID_TO_STOP" 2>/dev/null; then
               kill "$PID_TO_STOP" 2>/dev/null || true
               wait_for_pid_exit "$PID_TO_STOP"
      You can send follow-ups to the cloud agent here. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c4be90c49ffbdf32315f4fc035a511fb6fb0d5c5. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -386,10 +535,15 @@
      386535 REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)"
      387536 REMOTE_PORT="$(cat "$PORT_FILE" 2>/dev/null || true)"
      388537 REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)"
      389-DEFAULT_REMOTE_PORT="$(resolve_default_runtime_port 2>/dev/null || true)"
      538+DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port 2>/dev/null || true)"
      539+DEFAULT_RUNTIME_PID=""
      540+DEFAULT_REMOTE_PORT=""
      541+if [ -n "$DEFAULT_RUNTIME_INFO" ]; then
      542+ DEFAULT_RUNTIME_PID="\${DEFAULT_RUNTIME_INFO%% *}"
      543+ DEFAULT_REMOTE_PORT="\${DEFAULT_RUNTIME_INFO#* }"
      544+fi
      390545 if [ -n "$DEFAULT_REMOTE_PORT" ]; then
      391546 REMOTE_PORT="$DEFAULT_REMOTE_PORT"
      392547 if wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then
      393- if [ "$REMOTE_MANAGED" = "managed" ] && [ -n "$REMOTE_PID" ] && kill -0 "$REMOTE_PID" 2>/dev/null; then
      394- kill "$REMOTE_PID" 2>/dev/null || true
      395- wait_for_pid_exit "$REMOTE_PID"
      548+ if [ "$REMOTE_MANAGED" = "managed" ]; then
      549+ PID_TO_STOP="\${REMOTE_PID:-$DEFAULT_RUNTIME_PID}"

      Fallback PID may kill external server unintentionally

      Medium Severity

      When REMOTE_MANAGED is "managed" but REMOTE_PID is empty (e.g., PID file was deleted or corrupted), PID_TO_STOP falls back to DEFAULT_RUNTIME_PID via "${REMOTE_PID:-$DEFAULT_RUNTIME_PID}". DEFAULT_RUNTIME_PID comes from server-runtime.json and may represent an externally started server. Killing it defeats the purpose of adopting an external server, as the subsequent wait_ready on that port will fail, forcing an unnecessary full relaunch. The fallback should only kill the process we actually launched (i.e., only when REMOTE_PID is non-empty).

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c4be90c49ffbdf32315f4fc035a511fb6fb0d5c5. Configure [here](https://www.cursor.com/dashboard/bugbot).
    11. juliusmarminge merged this932df4e

    12. juliusmarminge closed this

Sign in to join this conversation.