TypeScript
fix(devices): explain Windows SSH host failures (#30941)
shivam8a65c000433b
diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.tsindex a551ffdf5a8..7e719806c17 100644--- a/apps/server/src/device/DeviceService.test.ts+++ b/apps/server/src/device/DeviceService.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "@effect/vitest";import {DEFAULT_SERVER_SETTINGS,DeviceBootError,+ DeviceError,DeviceId,DeviceOperationError,LOCAL_DEVICE_HOST_ID,@@ -13,6 +14,7 @@ import {import * as NodeCrypto from "@effect/platform-node/NodeCrypto";import * as NodeServices from "@effect/platform-node/NodeServices";import * as NetService from "@t3tools/shared/Net";+import { SshCommandError } from "@t3tools/ssh/errors";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as Deferred from "effect/Deferred";@@ -37,6 +39,7 @@ import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";import * as DeviceService from "./DeviceService.ts";+import * as SshDeviceHost from "./SshDeviceHost.ts";import { agentDeviceSession, releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));@@ -315,6 +318,7 @@ const fixture = Effect.fn("fixture")(function* (};return {service,+ host,starts,agentStarts,agentStops,@@ -361,6 +365,61 @@ describe("device setup consent", () => {}).pipe(Effect.scoped),);+ it.effect.each([+ {+ name: "a Windows host",+ exitCode: 1,+ stderr: "private diagnostics",+ expected:+ "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.",+ },+ {+ name: "a Windows host returning 9009",+ exitCode: 9009,+ stderr: "private diagnostics",+ expected:+ "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.",+ },+ {+ name: "missing Node on a Windows host with a POSIX shell",+ exitCode: 1,+ stderr: "private diagnostics\nNode is missing from the non-interactive SSH PATH",+ expected:+ "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.",+ },+ ])(+ "reports SSH probe failure on $name through readiness and host status",+ ({ exitCode, stderr, expected }) =>+ Effect.gen(function* () {+ const failure = new DeviceHost.DeviceHostError({+ hostId: LOCAL_DEVICE_HOST_ID,+ step: "probe",+ cause: new SshDeviceHost.SshWindowsHostError({+ cause: new SshCommandError({+ command: ["ssh", "private arguments"],+ exitCode,+ stderr,+ message: "private diagnostics",+ }),+ }),+ });+ const { service, settings } = yield* fixture(Effect.void, undefined, false, failure);+ yield* Ref.update(settings, (current) => ({+ ...current,+ enableDeviceSupport: true,+ enableAgentDeviceAccess: true,+ }));+ for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {+ const error = yield* readiness.pipe(Effect.flip);+ expect(error).toMatchObject({ reason: expected, cause: failure });+ expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({+ status: "failed",+ detail: expected,+ });+ }+ }).pipe(Effect.scoped),+ );+it.effect("listing and provider startup do not start helpers before consent", () =>Effect.gen(function* () {const { service, starts, requests } = yield* fixture();@@ -540,6 +599,80 @@ const layerSecretResolver = Layer.succeed(SecretResolver.SecretResolver, {invalidate: () => Effect.void,});+it.effect.each([1, 9009])(+ "Test connection preserves Windows exit %s guidance across the wire",+ (exitCode) =>+ Effect.gen(function* () {+ const { host } = yield* fixture();+ const service = yield* DeviceService.make.pipe(+ Effect.provideService(DeviceHost.DeviceHost, host),+ Effect.provideService(ProcessRunner.ProcessRunner, {+ run: () => Effect.die("Testing SSH does not install local tools"),+ }),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make(() => Effect.die("Testing SSH makes no hub requests")),+ ),+ Effect.provideService(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make((command) => {+ if (command._tag !== "StandardCommand") return Effect.die("Unexpected command");+ const config = command.args.includes("-G");+ const windows = command.args.includes("echo %OS% $env:OS");+ return Effect.succeed(+ ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(123),+ stdout: Stream.make(+ new TextEncoder().encode(+ config ? "hostname 192.0.2.1\nport 22\n" : windows ? "Windows_NT\r\n" : "",+ ),+ ),+ stderr: Stream.make(new TextEncoder().encode("private SSH diagnostics")),+ all: Stream.empty,+ exitCode: Effect.succeed(+ ChildProcessSpawner.ExitCode(config || windows ? 0 : exitCode),+ ),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ stdin: Sink.drain,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ unref: Effect.succeed(Effect.void),+ }),+ );+ }),+ ),+ );+ const error = yield* service+ .testHost({ kind: "ssh", id: "windows", label: "Windows test", target: "windows.test" })+ .pipe(Effect.flip);+ expect(error).toMatchObject({+ _tag: "DeviceHostUnavailableError",+ hostId: "windows",+ hostLabel: "Windows test",+ reason:+ "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.",+ });+ const codec = Schema.fromJsonString(DeviceError);+ const decoded = yield* Schema.decodeEffect(codec)(yield* Schema.encodeEffect(codec)(error));+ expect(decoded.message).toBe(+ "Windows test is unavailable: Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.",+ );+ expect(decoded.message).not.toContain("private SSH diagnostics");+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ ServerSettings.layerTest(),+ layerSecretResolver,+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-probe-" }),+ NodeCrypto.layer,+ NetService.layer,+ ).pipe(Layer.provideMerge(NodeServices.layer)),+ ),+ Effect.scoped,+ ),+);+it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>Effect.gen(function* () {const started = yield* Deferred.make<void>();diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex b18cf8a516a..663eaeaf726 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -82,12 +82,13 @@ import * as LocalDeviceHost from "./LocalDeviceHost.ts";export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {- const cause = error.cause;+ const windows = SshDeviceHost.isSshWindowsHostError(error.cause) ? error.cause : null;+ const cause = windows ? windows.cause : error.cause;if (!(cause instanceof SshCommandError) ||cause.exitCode === null ||cause.exitCode < 1 ||- cause.exitCode > 254+ (cause.exitCode > 254 && cause.exitCode !== 9009))return "Could not connect to this host over SSH.";@@ -99,6 +100,7 @@ const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {.some((line) => line.trim() === "Node is missing from the non-interactive SSH PATH"))return "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.";+ if (windows) return windows.message;return `Connected over SSH, but the device host check failed (exit code ${cause.exitCode}).`;};@@ -1354,13 +1356,19 @@ export const make = Effect.gen(function* () {}return yield* SshDeviceHost.probe(host).pipe(Effect.provide(probeContext));}).pipe(- Effect.mapError(- (error) =>- new DeviceOperationError({- operation: "probe host",- reason: "request_failed",- cause: error,- }),+ Effect.mapError((error) =>+ error._tag === "DeviceHostError" && SshDeviceHost.isSshWindowsHostError(error.cause)+ ? new DeviceHostUnavailableError({+ hostId: host.id,+ hostLabel: host.label,+ reason: sshProbeFailureMessage(error),+ cause: error,+ })+ : new DeviceOperationError({+ operation: "probe host",+ reason: "request_failed",+ cause: error,+ }),),),configureAgent,diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.tsindex 6600425331c..5bba5d084c5 100644--- a/apps/server/src/device/SshDeviceHost.test.ts+++ b/apps/server/src/device/SshDeviceHost.test.ts@@ -386,3 +386,119 @@ it.effect(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, TestClock.layer())),),);++it.effect.each([+ {+ name: "a Windows PowerShell login shell",+ exitCode: 1,+ stderr: "sh : The term 'sh' is not recognized as the name of a cmdlet\r\n",+ shellEcho: "%OS%\r\nWindows_NT\r\n",+ nodePlatform: null,+ windows: true,+ },+ {+ name: "a Windows cmd login shell",+ exitCode: 1,+ stderr: "'sh' is not recognized as an internal or external command,\r\n",+ shellEcho: "Windows_NT $env:OS\r\n",+ nodePlatform: null,+ windows: true,+ },+ {+ name: "a Windows cmd login shell returning 9009",+ exitCode: 9009,+ stderr: "'sh' is not recognized as an internal or external command,\r\n",+ shellEcho: "Windows_NT $env:OS\r\n",+ nodePlatform: null,+ windows: true,+ },+ {+ name: "a Windows Git Bash login shell without a spawnable npm",+ exitCode: 1,+ stderr: "npm is missing from the non-interactive SSH PATH\n",+ shellEcho: "%OS% :OS\n",+ nodePlatform: "win32",+ windows: true,+ },+ {+ name: "a Linux host without npm",+ exitCode: 1,+ stderr: "npm is missing from the non-interactive SSH PATH\n",+ shellEcho: "%OS% :OS\n",+ nodePlatform: "linux",+ windows: false,+ },+ {+ name: "a POSIX host without Node",+ exitCode: 1,+ stderr: "Node is missing from the non-interactive SSH PATH\n",+ shellEcho: "%OS% :OS\n",+ nodePlatform: null,+ windows: false,+ },+ {+ name: "a connection failure",+ exitCode: 255,+ stderr: "Connection refused\n",+ shellEcho: "Windows_NT\n",+ nodePlatform: "win32",+ windows: false,+ },+])(+ "probe failure on $name keeps the SSH cause",+ ({ exitCode, stderr, shellEcho, nodePlatform, windows }) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const home = yield* fs.makeTempDirectoryScoped();+ const shellChecks: string[] = [];+ const spawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ if (command._tag !== "StandardCommand") return yield* Effect.die("Unexpected command");+ const remote = command.args.slice(command.args.indexOf("test.example") + 1).join(" ");+ const shellCheck = remote === "echo %OS% $env:OS";+ const platformCheck = remote === "node -p process.platform";+ if (shellCheck || platformCheck) shellChecks.push(remote);+ return ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(123),+ stdout: Stream.make(+ new TextEncoder().encode(+ shellCheck ? shellEcho : platformCheck ? `${nodePlatform ?? ""}\n` : "",+ ),+ ),+ stderr: Stream.make(+ new TextEncoder().encode(shellCheck || platformCheck ? "" : stderr),+ ),+ all: Stream.empty,+ exitCode: Effect.succeed(+ ChildProcessSpawner.ExitCode(+ shellCheck ? 0 : platformCheck ? (nodePlatform === null ? 1 : 0) : exitCode,+ ),+ ),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ stdin: Sink.drain,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ unref: Effect.succeed(Effect.void),+ });+ }),+ );+ const failure = yield* SshDeviceHost.probe({+ kind: "ssh",+ id: "test",+ label: "Test",+ target: "test.example",+ }).pipe(+ Effect.provide(ServerConfig.layerTest(home, home)),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.flip,+ );+ expect(failure).toMatchObject({ _tag: "DeviceHostError", step: "probe" });+ const sshFailure = { _tag: "SshCommandError", exitCode, stderr };+ expect(failure.cause).toMatchObject(+ windows ? { _tag: "SshWindowsHostError", cause: sshFailure } : sshFailure,+ );+ // A transport failure has no remote shell to ask.+ if (exitCode === 255) expect(shellChecks).toEqual([]);+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),+);diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.tsindex ef051cb9075..8d17d4d3f3a 100644--- a/apps/server/src/device/SshDeviceHost.ts+++ b/apps/server/src/device/SshDeviceHost.ts@@ -6,6 +6,7 @@ import {type SshDeviceHostConfig,} from "@t3tools/contracts";import { runSshCommand, baseSshArgs, resolveSshCommand } from "@t3tools/ssh/command";+import { SshCommandError } from "@t3tools/ssh/errors";import * as NetService from "@t3tools/shared/Net";import { waitForHttpReady } from "@t3tools/shared/httpReadiness";import * as Digest from "effect/crypto/Digest";@@ -29,6 +30,17 @@ import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sconst UNHEALTHY_PROBE_LIMIT = 3;+/** The host bootstrap failed on a host identified as Windows. */+export class SshWindowsHostError extends Schema.TaggedError<SshWindowsHostError>()(+ "SshWindowsHostError",+ { cause: Schema.Defect() },+) {+ override get message(): string {+ return "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.";+ }+}+export const isSshWindowsHostError = Schema.is(SshWindowsHostError);+const Probe = Schema.Struct({nodePath: Schema.String,tools: Schema.optional(DeviceToolVersions),@@ -78,6 +90,47 @@ const bootstrap = (),);+// cmd expands only %OS% and PowerShell only $env:OS; POSIX shells expand neither to Windows_NT.+const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(function* (+ config: SshDeviceHostConfig,+ error: DeviceHost.DeviceHostError,+) {+ const cause = error.cause;+ // Windows ssh.exe preserves full remote exit statuses such as 9009.+ if (+ !(cause instanceof SshCommandError) ||+ cause.exitCode === null ||+ cause.exitCode < 1 ||+ (cause.exitCode > 254 && cause.exitCode !== 9009)+ )+ return yield* error;+ let windows = yield* runSshCommand(targetFor(config), {+ preHostArgs: identityArgs(config),+ remoteCommandArgs: ["echo %OS% $env:OS"],+ timeoutMs: 15_000,+ }).pipe(+ Effect.map(({ stdout }) => /(?:^|\s)Windows_NT(?:\s|$)/u.test(stdout)),+ Effect.orElseSucceed(() => false),+ );+ if (!windows) {+ // Git Bash does not expand Windows shell variables, but its Node still reports win32.+ windows = yield* runSshCommand(targetFor(config), {+ preHostArgs: identityArgs(config),+ remoteCommandArgs: ["node", "-p", "process.platform"],+ timeoutMs: 15_000,+ }).pipe(+ Effect.map(({ stdout }) => stdout.trim() === "win32"),+ Effect.orElseSucceed(() => false),+ );+ }+ if (!windows) return yield* error;+ return yield* new DeviceHost.DeviceHostError({+ hostId: config.id,+ step: error.step,+ cause: new SshWindowsHostError({ cause }),+ });+});+const ownerFor = Effect.fn("SshDeviceHost.ownerFor")(function* (hostId: string) {const fs = yield* FileSystem.FileSystem;const server = yield* ServerConfig.ServerConfig;@@ -98,7 +151,9 @@ export const probe = Effect.fn("SshDeviceHost.probe")(function* (config: SshDeviceHostConfig,owner?: string,) {- const result = yield* bootstrap(config, owner ?? (yield* ownerFor(config.id)), "probe");+ const result = yield* bootstrap(config, owner ?? (yield* ownerFor(config.id)), "probe").pipe(+ Effect.catchTags({ DeviceHostError: (error) => explainWindowsHost(config, error) }),+ );const value = yield* decodeProbe(result.stdout.trim()).pipe(Effect.mapError((cause) =>diff --git a/docs/user/devices.md b/docs/user/devices.mdindex 46a5a427cc8..ac053b36c08 100644--- a/docs/user/devices.md+++ b/docs/user/devices.md@@ -108,6 +108,8 @@ not supported.anything, with a result for each selected environment. Targets that resolve tothe environment’s own machine are skipped, since its devices are already local.The first device listing installs pinned device tools on the host.+SSH device hosts currently need macOS or Linux. To use devices on a Windows+machine, run T3 Code on that machine and connect to its environment.Node 22 or newer and npm must be available to non-interactive SSH commands.T3 checks common Homebrew and Android SDK locations; custom installations needthe appropriate PATH and ANDROID_HOME on the host. Android emulator video needs