Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge f42b2937fe fix: update Schema.Defect to function call and replace instanceof with Schema.is guard
After rebase on main, the SSH error schema definitions needed updating:
- Schema.Defect must be called as Schema.Defect() (function invocation)
- Added stdout field to SshCommandError schema to match main's error construction
- Replaced instanceof SshHttpBridgeError with Schema.is guard in desktop IPC

Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 19:18:52 +00:00
Cursor AgentandJulius Marminge 30199ae5e5 Use schema guard for SSH bridge error tests
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 19:10:38 +00:00
Cursor AgentandJulius Marminge 34ca6507db Make SSH Effect usage more idiomatic
Co-authored-by: Julius Marminge <[email protected]>
2026-06-05 19:10:38 +00:00
9 changed files with 179 additions and 77 deletions

No files matched your search

@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import {
@@ -33,6 +34,8 @@ function makeHttpClientLayer(
);
}
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
describe("SSH environment IPC", () => {
it.effect("fetches and decodes the remote environment descriptor", () => {
const requestUrls: string[] = [];
@@ -83,7 +86,7 @@ describe("SSH environment IPC", () => {
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
assert.equal(error.operation, "fetch-environment-descriptor");
assert.equal(error.cause instanceof SshHttpBridgeError, false);
assert.isFalse(isSshHttpBridgeError(error.cause));
}).pipe(Effect.provide(layer));
});
@@ -108,7 +111,7 @@ describe("SSH environment IPC", () => {
const error = failure.value;
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
assert.instanceOf(error.cause, SshHttpBridgeError);
assert.isTrue(isSshHttpBridgeError(error.cause));
assert.equal(requestCount, 0);
}).pipe(Effect.provide(layer));
});
@@ -50,12 +50,10 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
if (
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
cause instanceof SshHttpBridgeError
) {
if (cause instanceof RemoteEnvironmentAuthUndeclaredStatusError || isSshHttpBridgeError(cause)) {
return cause.status ?? null;
}
if (isEnvironmentRequestInvalidError(cause)) {
@@ -25,6 +25,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -79,11 +80,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
return discoverSshHosts(input ?? {});
}
const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
export function isDesktopSshPasswordPromptCancellation(
error: unknown,
): error is SshPasswordPromptError {
return (
error instanceof SshPasswordPromptError &&
isSshPasswordPromptError(error) &&
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
);
}
+1 -1
View File
@@ -219,7 +219,7 @@ describe("ssh command", () => {
username: "julius",
port: 2222,
},
{ timeoutMs: 1 },
{ timeout: Duration.millis(1) },
),
),
);
+14 -5
View File
@@ -14,7 +14,7 @@ import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
const DEFAULT_SSH_COMMAND_TIMEOUT = Duration.seconds(60);
const MAX_SSH_ERROR_OUTPUT_LENGTH = 4_000;
export const SSH_COMMAND = process.platform === "win32" ? "ssh.exe" : "ssh";
@@ -29,6 +29,8 @@ export interface RunSshCommandOptions extends SshAuthOptions {
readonly preHostArgs?: ReadonlyArray<string>;
readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string;
readonly timeout?: Duration.Input;
/** @deprecated Prefer `timeout` with an Effect Duration input. */
readonly timeoutMs?: number;
}
@@ -157,6 +159,10 @@ function stdinStream(input: string | undefined) {
return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
}
function resolveSshCommandTimeout(input: RunSshCommandOptions): Duration.Duration {
return Duration.fromInputUnsafe(input.timeout ?? input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT);
}
const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
target: DesktopSshEnvironmentTarget,
input: RunSshCommandOptions,
@@ -191,11 +197,12 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
...(input.remoteCommandArgs ?? []),
];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const timeout = resolveSshCommandTimeout(input);
yield* Effect.logDebug("ssh.command.start", {
...sshTargetLogFields(target),
command: [SSH_COMMAND, ...args],
hasStdin: input.stdin !== undefined,
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
timeoutMs: Duration.toMillis(timeout),
});
const child = yield* spawner
.spawn(
@@ -282,10 +289,12 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
const timeout = resolveSshCommandTimeout(input);
const timeoutMs = Duration.toMillis(timeout);
return yield* Effect.scopedWith((commandScope) =>
runSshCommandInScope(target, input, commandScope),
).pipe(
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
Effect.timeoutOption(timeout),
Effect.flatMap((result) =>
Option.match(result, {
onSome: Effect.succeed,
@@ -293,7 +302,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
Effect.gen(function* () {
yield* Effect.logWarning("ssh.command.timedOut", {
...sshTargetLogFields(target),
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
timeoutMs,
remoteCommandArgs: input.remoteCommandArgs ?? [],
preHostArgs: input.preHostArgs ?? [],
hasStdin: input.stdin !== undefined,
@@ -302,7 +311,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
command: ["ssh"],
exitCode: null,
stderr: "",
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
message: `SSH command timed out after ${timeoutMs}ms.`,
});
}),
}),
+27
View File
@@ -0,0 +1,27 @@
import { assert, describe, it } from "@effect/vitest";
import * as Schema from "effect/Schema";
import { SshCommandError, SshError } from "./errors.ts";
const encodeSshError = Schema.encodeSync(SshError);
const isSshError = Schema.is(SshError);
describe("ssh errors", () => {
it("encodes schema-backed SSH errors as tagged serializable data", () => {
const error = new SshCommandError({
message: "SSH command failed.",
command: ["ssh", "devbox"],
exitCode: 255,
stderr: "permission denied",
});
assert.isTrue(isSshError(error));
assert.deepEqual(encodeSshError(error), {
_tag: "SshCommandError",
message: "SSH command failed.",
command: ["ssh", "devbox"],
exitCode: 255,
stderr: "permission denied",
});
});
});
+73 -39
View File
@@ -1,47 +1,81 @@
import * as Data from "effect/Data";
import * as Schema from "effect/Schema";
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
readonly message: string;
readonly cause: unknown;
}> {}
const SshCommandArgs = Schema.Array(Schema.String);
export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
readonly message: string;
}> {}
export class SshHostDiscoveryError extends Schema.TaggedErrorClass<SshHostDiscoveryError>()(
"SshHostDiscoveryError",
{
message: Schema.String,
cause: Schema.Defect(),
},
) {}
export class SshCommandError extends Data.TaggedError("SshCommandError")<{
readonly message: string;
readonly command: readonly string[];
readonly exitCode: number | null;
readonly stderr: string;
readonly stdout?: string;
readonly cause?: unknown;
}> {}
export class SshInvalidTargetError extends Schema.TaggedErrorClass<SshInvalidTargetError>()(
"SshInvalidTargetError",
{
message: Schema.String,
},
) {}
export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
readonly message: string;
readonly stdout: string;
readonly cause?: unknown;
}> {}
export class SshCommandError extends Schema.TaggedErrorClass<SshCommandError>()("SshCommandError", {
message: Schema.String,
command: SshCommandArgs,
exitCode: Schema.NullOr(Schema.Number),
stderr: Schema.String,
stdout: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
}) {}
export class SshPairingError extends Data.TaggedError("SshPairingError")<{
readonly message: string;
readonly stdout: string;
readonly cause?: unknown;
}> {}
export class SshLaunchError extends Schema.TaggedErrorClass<SshLaunchError>()("SshLaunchError", {
message: Schema.String,
stdout: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
readonly message: string;
readonly status?: number;
readonly cause?: unknown;
}> {}
export class SshPairingError extends Schema.TaggedErrorClass<SshPairingError>()("SshPairingError", {
message: Schema.String,
stdout: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SshHttpBridgeError extends Schema.TaggedErrorClass<SshHttpBridgeError>()(
"SshHttpBridgeError",
{
message: Schema.String,
status: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {}
export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class SshReadinessError extends Schema.TaggedErrorClass<SshReadinessError>()(
"SshReadinessError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
export class SshPasswordPromptError extends Schema.TaggedErrorClass<SshPasswordPromptError>()(
"SshPasswordPromptError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
export const SshEnvironmentError = Schema.Union([
SshCommandError,
SshInvalidTargetError,
SshLaunchError,
SshPairingError,
SshReadinessError,
SshPasswordPromptError,
]);
export type SshEnvironmentError = typeof SshEnvironmentError.Type;
export const SshError = Schema.Union([
SshHostDiscoveryError,
SshHttpBridgeError,
SshEnvironmentError,
]);
export type SshError = typeof SshError.Type;
+3 -3
View File
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
Effect.result(
waitForHttpReady({
baseUrl: "http://127.0.0.1:41773/",
timeoutMs: 1_000,
intervalMs: 100,
probeTimeoutMs: 250,
timeout: Duration.seconds(1),
interval: Duration.millis(100),
probeTimeout: Duration.millis(250),
}),
),
);
+50 -22
View File
@@ -51,11 +51,14 @@ import {
export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT_MS = 20_000;
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
const REMOTE_READY_TIMEOUT_MS = 15_000;
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
const SSH_READY_TIMEOUT = Duration.seconds(20);
const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
const REMOTE_READY_TIMEOUT = Duration.seconds(15);
const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
const DEFAULT_HTTP_READY_TIMEOUT = Duration.seconds(30);
const DEFAULT_HTTP_READY_INTERVAL = Duration.millis(100);
const isSshReadinessError = Schema.is(SshReadinessError);
export interface RemoteT3RunnerOptions {
readonly packageSpec?: string;
@@ -233,7 +236,7 @@ function applyScriptPlaceholders(
}
export function describeReadinessCause(cause: unknown): unknown {
if (cause instanceof SshReadinessError) {
if (isSshReadinessError(cause)) {
return {
_tag: cause._tag,
message: cause.message,
@@ -682,9 +685,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
});
}
@@ -856,7 +859,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteLogTailScript(target),
timeoutMs: 10_000,
timeout: Duration.seconds(10),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
@@ -864,17 +867,42 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
return result.stdout.trim();
});
function resolveDurationInput(
duration: Duration.Input | undefined,
durationMs: number | undefined,
fallback: Duration.Duration,
): Duration.Duration {
return Duration.fromInputUnsafe(duration ?? durationMs ?? fallback);
}
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
readonly baseUrl: string;
readonly timeout?: Duration.Input;
readonly interval?: Duration.Input;
readonly probeTimeout?: Duration.Input;
/** @deprecated Prefer `timeout` with an Effect Duration input. */
readonly timeoutMs?: number;
/** @deprecated Prefer `interval` with an Effect Duration input. */
readonly intervalMs?: number;
/** @deprecated Prefer `probeTimeout` with an Effect Duration input. */
readonly probeTimeoutMs?: number;
readonly path?: string;
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
const timeoutMs = input.timeoutMs ?? 30_000;
const intervalMs = input.intervalMs ?? 100;
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
const timeout = resolveDurationInput(input.timeout, input.timeoutMs, DEFAULT_HTTP_READY_TIMEOUT);
const interval = resolveDurationInput(
input.interval,
input.intervalMs,
DEFAULT_HTTP_READY_INTERVAL,
);
const probeTimeout = resolveDurationInput(
input.probeTimeout,
input.probeTimeoutMs,
SSH_READY_PROBE_TIMEOUT,
);
const timeoutMs = Duration.toMillis(timeout);
const intervalMs = Duration.toMillis(interval);
const probeTimeoutMs = Duration.toMillis(probeTimeout);
const retryPolicy = Schedule.spaced(interval).pipe(
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
);
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
@@ -896,7 +924,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
Effect.gen(function* () {
attempt += 1;
const responseOption = yield* effect.pipe(
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
Effect.timeoutOption(probeTimeout),
Effect.mapError(
(cause) =>
new SshReadinessError({
@@ -921,7 +949,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
});
}).pipe(
Effect.mapError((cause) =>
cause instanceof SshReadinessError
isSshReadinessError(cause)
? cause
: new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
@@ -942,14 +970,14 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
Effect.mapError((cause) =>
cause instanceof SshReadinessError
isSshReadinessError(cause)
? cause
: new SshReadinessError({
message: `Backend readiness probe failed at ${requestUrl}.`,
cause,
}),
),
Effect.timeoutOption(Duration.millis(timeoutMs)),
Effect.timeoutOption(timeout),
);
return yield* Option.match(result, {
@@ -1166,7 +1194,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
yield* Effect.raceFirst(
waitForHttpReady({
baseUrl: input.httpBaseUrl,
timeoutMs: SSH_READY_TIMEOUT_MS,
timeout: SSH_READY_TIMEOUT,
}),
exitFailure,
).pipe(
@@ -1226,7 +1254,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
: child
.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
})
.pipe(Effect.ignore),
),
@@ -1470,7 +1498,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
[
tunnelEntry.process.kill({
killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
}),
stopRemoteServer(
tunnelEntry.target,
@@ -1524,7 +1552,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
remotePort: entry.remotePort,
});
const readinessExit = yield* Effect.exit(
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }),
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
);
if (Exit.isSuccess(readinessExit)) {
yield* Effect.logDebug("ssh.environment.tunnel.reused", {