The best way to control Claude Code, Codex and more from any computer or phone
fix(ssh): keep draining tunnel diagnostics after readiness (#18832)
Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Alex Southwell committed
Oct 19, 2026 at 06:21 UTC
a331655b74676b69b1b6d7b645f2a5b219ab6df3
3 files changed
+252
-6
packages/ssh/src/command.ts
+1
-3
@@ -124,9 +124,7 @@ export function getLastNonEmptyOutputLine(stdout: string): string | null {
124
);
125
}
126
127
-export const collectProcessOutput = <E>(
128
- stream: Stream.Stream<Uint8Array, E>,
129
-): Effect.Effect<string, E> =>
127
+const collectProcessOutput = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
128
stream.pipe(
129
Stream.decodeText(),
130
Stream.runFold(
packages/ssh/src/tunnel.test.ts
+233
@@ -11,6 +11,8 @@ import * as Fiber from "effect/Fiber";
11
import * as FileSystem from "effect/FileSystem";
12
import * as Layer from "effect/Layer";
13
import * as Option from "effect/Option";
14
+import * as PlatformError from "effect/PlatformError";
15
+import * as Queue from "effect/Queue";
16
import * as Result from "effect/Result";
17
import * as Sink from "effect/Sink";
18
import * as Stream from "effect/Stream";
@@ -644,6 +646,237 @@ describe("ssh tunnel scripts", () => {
646
},
647
);
648
649
+ it.effect("keeps the stderr reader alive until disconnect", () =>
650
+ Effect.gen(function* () {
651
+ const readerStarted = yield* Deferred.make<void>();
652
+ let readers = 0;
653
+ let finalized = 0;
654
+ const stderr = Stream.fromEffect(
655
+ Effect.sync(() => {
656
+ readers += 1;
657
+ }).pipe(Effect.andThen(Deferred.succeed(readerStarted, undefined))),
658
+ ).pipe(
659
+ Stream.flatMap(() => Stream.fromEffect(Effect.never)),
660
+ Stream.ensuring(
661
+ Effect.sync(() => {
662
+ finalized += 1;
663
+ }),
664
+ ),
665
+ );
666
+ const spawner = ChildProcessSpawner.make((command) =>
667
+ Effect.succeed(
668
+ commandArgs(command).includes("-N")
669
+ ? { ...makeRunningProcess(() => undefined), stderr }
670
+ : makeSuccessfulProcess('{"remotePort":3773}\n'),
671
+ ),
672
+ );
673
+ const httpClient = HttpClient.make((request) =>
674
+ Deferred.await(readerStarted).pipe(
675
+ Effect.as(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
676
+ ),
677
+ );
678
+ const layer = Layer.mergeAll(
679
+ NodeServices.layer,
680
+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
681
+ Layer.succeed(HttpClient.HttpClient, httpClient),
682
+ Layer.succeed(NetService.NetService, testNetService),
683
+ SshAuth.SshPasswordPrompt.disabledLayer,
684
+ SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
685
+ );
686
+ yield* Effect.gen(function* () {
687
+ const manager = yield* SshTunnel.SshEnvironmentManager;
688
+ const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
689
+ yield* manager.ensureEnvironment(target);
690
+ assert.equal(readers, 1);
691
+ assert.equal(finalized, 0, "readiness must not release the stderr reader");
692
+ yield* manager.disconnectEnvironment(target);
693
+ assert.equal(finalized, 1, "disconnect must release the stderr reader");
694
+ }).pipe(Effect.provide(layer), Effect.scoped);
695
+ }),
696
+ );
697
+
698
+ it.effect("retains a bounded diagnostic tail when the tunnel exits before readiness", () =>
699
+ Effect.gen(function* () {
700
+ const diagnostic = "Connection refused: café";
701
+ const output = new TextEncoder().encode(
702
+ "old diagnostics\n" + "x".repeat(32_768) + "\n" + diagnostic,
703
+ );
704
+ const spawner = ChildProcessSpawner.make((command) =>
705
+ Effect.succeed(
706
+ commandArgs(command).includes("-N")
707
+ ? {
708
+ ...makeSuccessfulProcess(""),
709
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
710
+ stderr: Stream.make(output.subarray(0, output.length - 1), output.subarray(-1)),
711
+ }
712
+ : makeSuccessfulProcess('{"remotePort":3773}\n'),
713
+ ),
714
+ );
715
+ const layer = Layer.mergeAll(
716
+ NodeServices.layer,
717
+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
718
+ Layer.succeed(HttpClient.HttpClient, hangingHttpClient),
719
+ Layer.succeed(NetService.NetService, testNetService),
720
+ SshAuth.SshPasswordPrompt.disabledLayer,
721
+ SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
722
+ );
723
+ yield* Effect.gen(function* () {
724
+ const manager = yield* SshTunnel.SshEnvironmentManager;
725
+ const result = yield* Effect.result(
726
+ manager.ensureEnvironment({
727
+ alias: "devbox",
728
+ hostname: "devbox",
729
+ username: null,
730
+ port: null,
731
+ }),
732
+ );
733
+ assert.isTrue(Result.isFailure(result));
734
+ if (Result.isFailure(result)) {
735
+ assert.instanceOf(result.failure, SshCommandError);
736
+ if (result.failure instanceof SshCommandError) {
737
+ assert.equal(result.failure.exitCode, 1);
738
+ assert.equal(result.failure.stderr.length, 16_384);
739
+ assert.isTrue(result.failure.stderr.endsWith(diagnostic));
740
+ assert.equal(result.failure.message, result.failure.stderr.trim());
741
+ }
742
+ }
743
+ }).pipe(Effect.provide(layer), Effect.scoped);
744
+ }),
745
+ );
746
+
747
+ it.effect("reports the real exit when reading tunnel diagnostics fails", () =>
748
+ Effect.gen(function* () {
749
+ const diagnostic = "Permission denied (publickey)";
750
+ const spawner = ChildProcessSpawner.make((command) =>
751
+ Effect.succeed(
752
+ commandArgs(command).includes("-N")
753
+ ? {
754
+ ...makeSuccessfulProcess(""),
755
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(255)),
756
+ stderr: Stream.make(new TextEncoder().encode(diagnostic)).pipe(
757
+ Stream.concat(
758
+ Stream.fail(
759
+ PlatformError.systemError({
760
+ _tag: "Unknown",
761
+ module: "Stream",
762
+ method: "read",
763
+ description: "stderr read failed",
764
+ }),
765
+ ),
766
+ ),
767
+ ),
768
+ }
769
+ : makeSuccessfulProcess('{"remotePort":3773}\n'),
770
+ ),
771
+ );
772
+ const layer = Layer.mergeAll(
773
+ NodeServices.layer,
774
+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
775
+ Layer.succeed(HttpClient.HttpClient, hangingHttpClient),
776
+ Layer.succeed(NetService.NetService, testNetService),
777
+ SshAuth.SshPasswordPrompt.disabledLayer,
778
+ SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
779
+ );
780
+ yield* Effect.gen(function* () {
781
+ const manager = yield* SshTunnel.SshEnvironmentManager;
782
+ const result = yield* Effect.result(
783
+ manager.ensureEnvironment({
784
+ alias: "devbox",
785
+ hostname: "devbox",
786
+ username: null,
787
+ port: null,
788
+ }),
789
+ );
790
+ assert.isTrue(Result.isFailure(result));
791
+ if (Result.isFailure(result)) {
792
+ assert.instanceOf(result.failure, SshCommandError);
793
+ if (result.failure instanceof SshCommandError) {
794
+ assert.equal(result.failure.exitCode, 255);
795
+ assert.equal(result.failure.stderr, diagnostic);
796
+ }
797
+ }
798
+ }).pipe(Effect.provide(layer), Effect.scoped);
799
+ }),
800
+ );
801
+
802
+ it.live("drains diagnostics beyond pipe capacity after readiness", () =>
803
+ Effect.gen(function* () {
804
+ const nodeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
805
+ const executable = yield* HostProcess.ExecutablePath;
806
+ const input = yield* Queue.unbounded<Uint8Array>();
807
+ const readerStarted = yield* Deferred.make<void>();
808
+ const tunnelSpawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
809
+ let finalized = 0;
810
+ const spawner = ChildProcessSpawner.make((command) =>
811
+ Effect.gen(function* () {
812
+ if (!commandArgs(command).includes("-N")) {
813
+ return makeSuccessfulProcess('{"remotePort":3773}\n');
814
+ }
815
+ const child = yield* nodeSpawner.spawn(
816
+ ChildProcess.make(
817
+ executable,
818
+ [
819
+ "-e",
820
+ `process.stdin.once("data", () => {
821
+ process.stderr.write(Buffer.alloc(2 * 1024 * 1024, "x"), () => {
822
+ process.stdout.write("diagnostics complete\\n");
823
+ });
824
+ });`,
825
+ ],
826
+ { stdin: { stream: Stream.fromQueue(input) } },
827
+ ),
828
+ );
829
+ yield* Deferred.succeed(tunnelSpawned, child);
830
+ return {
831
+ ...child,
832
+ stderr: Stream.fromEffect(Deferred.succeed(readerStarted, undefined)).pipe(
833
+ Stream.flatMap(() => child.stderr),
834
+ Stream.ensuring(
835
+ Effect.sync(() => {
836
+ finalized += 1;
837
+ }),
838
+ ),
839
+ ),
840
+ };
841
+ }),
842
+ );
843
+ const httpClient = HttpClient.make((request) =>
844
+ Deferred.await(readerStarted).pipe(
845
+ Effect.as(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))),
846
+ ),
847
+ );
848
+ const layer = Layer.mergeAll(
849
+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
850
+ Layer.succeed(HttpClient.HttpClient, httpClient),
851
+ Layer.succeed(NetService.NetService, testNetService),
852
+ SshAuth.SshPasswordPrompt.disabledLayer,
853
+ SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }),
854
+ );
855
+ yield* Effect.gen(function* () {
856
+ const manager = yield* SshTunnel.SshEnvironmentManager;
857
+ const target = { alias: "devbox", hostname: "devbox", username: null, port: null };
858
+ yield* manager.ensureEnvironment(target);
859
+ const child = yield* Deferred.await(tunnelSpawned);
860
+ const progress = yield* child.stdout.pipe(
861
+ Stream.decodeText(),
862
+ Stream.splitLines,
863
+ Stream.take(1),
864
+ Stream.runCollect,
865
+ Effect.forkScoped,
866
+ );
867
+ yield* Queue.offer(input, new TextEncoder().encode("write diagnostics"));
868
+ // The deadline only bounds a blocked subprocess; success waits for its write callback.
869
+ assert.deepEqual(yield* Fiber.join(progress).pipe(Effect.timeout("5 seconds")), [
870
+ "diagnostics complete",
871
+ ]);
872
+ assert.isTrue(yield* child.isRunning);
873
+ yield* manager.disconnectEnvironment(target);
874
+ assert.equal(finalized, 1);
875
+ assert.isFalse(yield* child.isRunning);
876
+ }).pipe(Effect.provide(layer), Effect.scoped);
877
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
878
+ );
879
+
880
it.effect.each(["local tunnel", "remote server"] as const)(
881
"waits for %s shutdown before reconnecting the same target",
882
(stalledStep) =>
packages/ssh/src/tunnel.ts
+18
-3
@@ -15,6 +15,7 @@ import * as Context from "effect/Context";
15
import * as Crypto from "effect/Crypto";
16
import * as Effect from "effect/Effect";
17
import * as Exit from "effect/Exit";
18
+import * as Fiber from "effect/Fiber";
19
import * as FileSystem from "effect/FileSystem";
20
import * as Layer from "effect/Layer";
21
import * as Path from "effect/Path";
@@ -28,7 +29,6 @@ import * as SshAuth from "./auth.ts";
29
import {
30
baseSshArgs,
31
buildSshHostSpecEffect,
31
- collectProcessOutput,
32
getLastNonEmptyOutputLine,
33
remoteStateKey,
34
resolveSshCommand,
@@ -51,6 +51,7 @@ const REMOTE_PORT_SCAN_WINDOW = 200;
51
const SSH_READY_TIMEOUT_MS = 20_000;
52
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
53
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
54
+const TUNNEL_STDERR_TAIL_CHARS = 16_384;
55
const REMOTE_READY_TIMEOUT_MS = 60_000;
56
const REMOTE_LAUNCH_TIMEOUT_MS = 90_000;
57
// A cold archive launch also downloads and unpacks a ~70 MB release archive
@@ -1241,8 +1242,21 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
1242
process: child,
1243
scope,
1244
};
1245
+ // Readiness cancels the exit waiter, but diagnostics must drain until the tunnel closes.
1246
+ let stderrTail = "";
1247
+ const stderrDrain = yield* child.stderr.pipe(
1248
+ Stream.decodeText(),
1249
+ Stream.runForEach((chunk) =>
1250
+ Effect.sync(() => {
1251
+ stderrTail = (stderrTail + chunk).slice(-TUNNEL_STDERR_TAIL_CHARS);
1252
+ }),
1253
+ ),
1254
+ // Diagnostics are best-effort: a failed read must not hide the real exit.
1255
+ Effect.ignore,
1256
+ Effect.forkIn(scope),
1257
+ );
1258
const exitFailure = Effect.all(
1245
- [collectProcessOutput(child.stderr), child.exitCode.pipe(Effect.map(Number))],
1259
+ [Fiber.join(stderrDrain), child.exitCode.pipe(Effect.map(Number))],
1260
{ concurrency: "unbounded" },
1261
).pipe(
1262
Effect.mapError(
@@ -1258,7 +1272,8 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
1272
cause,
1273
}),
1274
),
1261
- Effect.flatMap(([stderr, exitCode]) => {
1275
+ Effect.flatMap(([, exitCode]) => {
1276
+ const stderr = stderrTail;
1277
const error = new SshCommandError({
1278
command: tunnelCommand,
1279
exitCode,