Skip to content
TypeScript

fix(ssh): retain actionable errors from failed device commands (#19972)

Luís Miguel7a286c974427
diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.ts
index 57e7226e430..24c128c6543 100644
--- a/apps/server/src/device/SshDeviceHost.test.ts
+++ b/apps/server/src/device/SshDeviceHost.test.ts
@@ -33,6 +33,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ
(forwarding ? tunnelArgs : commandArgs).push([...command.args]);
if (forwarding) tunnelStdins.push(command.options.stdin);
let output = "";
+ let exitCode = 0;
if (forwarding) {
if (failForward) {
failForward = false;
@@ -77,13 +78,19 @@ it.effect("preserves installed status after probes and cleans failed agent activ
? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" }
: {}),
});
+ if (mode === "") {
+ output = `${"verbose-prefix ".repeat(400)}PANIC: emulator SDK is broken\n`;
+ exitCode = 1;
+ }
}
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(123),
stdout: Stream.make(new TextEncoder().encode(output)),
stderr: Stream.empty,
all: Stream.empty,
- exitCode: forwarding ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(0)),
+ exitCode: forwarding
+ ? Effect.never
+ : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(forwarding),
kill: () => Effect.void,
stdin: Sink.drain,
@@ -124,6 +131,15 @@ it.effect("preserves installed status after probes and cleans failed agent activ
expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
expect(forwards).toBe(1);
expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
+ const ready = yield* host.current;
+ expect(ready).not.toBeNull();
+ if (ready) {
+ const failed = yield* ready.run("emulator", ["-list-avds"]);
+ expect(failed.code).toBe(1);
+ expect(failed.stdout).toMatch(/^\[truncated\]/);
+ expect(failed.stderr).toBe(failed.stdout.trim());
+ expect(failed.stderr).toMatch(/PANIC: emulator SDK is broken$/);
+ }
yield* host.platformAvailability("ios");
expect((yield* host.summary).hubInstalled).toBe(true);
const failed = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.result);
diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts
index 2fc8c57e05d..1587fab9804 100644
--- a/apps/server/src/device/SshDeviceHost.ts
+++ b/apps/server/src/device/SshDeviceHost.ts
@@ -176,6 +176,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
remoteCommandArgs: commandArgs(
`cd "$HOME/.t3/device/hosts/${owner}" && exec ${[command, ...args].map(quoteRemoteArg).join(" ")}`,
),
+ keepErrorOutputTail: true,
...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
}),
diff --git a/packages/ssh/src/command.test.ts b/packages/ssh/src/command.test.ts
index 28efc3c9487..d47af297fe5 100644
--- a/packages/ssh/src/command.test.ts
+++ b/packages/ssh/src/command.test.ts
@@ -187,6 +187,54 @@ describe("ssh command", () => {
}).pipe(Effect.provide(layerProcess));
});
+ it.live.each([
+ { name: "default head", keepErrorOutputTail: undefined, exitCode: 1, stderr: "" },
+ {
+ name: "opt-in tail",
+ keepErrorOutputTail: true,
+ exitCode: 1,
+ stderr: "stderr failure ".repeat(400),
+ },
+ { name: "successful output", keepErrorOutputTail: true, exitCode: 0, stderr: "" },
+ ])("preserves process output: $name", ({ keepErrorOutputTail, exitCode, stderr }) =>
+ Effect.gen(function* () {
+ const prefix = `HEAD\n${"verbose-prefix ".repeat(400)}`;
+ const secret = "synthetic-secret".repeat(400);
+ const diagnostic = "\nPANIC: emulator SDK is broken\n";
+ const stdout = `${prefix}{"credential":"${secret}"}${diagnostic}`;
+ const nativeSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ // Replace only the SSH endpoint with a real, deterministic process.
+ const spawner = ChildProcessSpawner.make(() =>
+ nativeSpawner.spawn(
+ ChildProcess.make(process.execPath, [
+ "-e",
+ `process.stdout.write(${JSON.stringify(stdout)}); process.stderr.write(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`,
+ ]),
+ ),
+ );
+ const command = runSshCommand(
+ { alias: "synthetic-fixture", hostname: "synthetic-fixture", username: null, port: null },
+ keepErrorOutputTail === undefined ? {} : { keepErrorOutputTail },
+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
+ if (exitCode === 0) {
+ assert.deepEqual(yield* command, { stdout, stderr });
+ return;
+ }
+ const failure = yield* Effect.flip(command);
+ assert.instanceOf(failure, SshCommandError);
+ assert.equal(failure.exitCode, 1);
+ assert.equal(failure.stderr, stderr);
+ assert.equal(failure.message, stderr.trim() || failure.stdout?.trim());
+ const redacted = `${prefix}{"credential":"[redacted]"}${diagnostic}`;
+ assert.equal(
+ failure.stdout,
+ keepErrorOutputTail
+ ? `[truncated]\n${redacted.slice(-4_000)}`
+ : `${redacted.slice(0, 4_000)}\n[truncated]`,
+ );
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
it.effect("redacts credentials from stdout in non-zero command failures", () => {
const spawner = ChildProcessSpawner.make(() =>
Effect.succeed(makeFailedProcess({ stdout: '{"credential":"pairing-secret"}\n' })),
diff --git a/packages/ssh/src/command.ts b/packages/ssh/src/command.ts
index 3b62676ecec..1b295bf6854 100644
--- a/packages/ssh/src/command.ts
+++ b/packages/ssh/src/command.ts
@@ -39,6 +39,8 @@ export interface RunSshCommandOptions extends SshAuthOptions {
readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string;
readonly timeoutMs?: number;
+ /** Keep the end of long failed-command stdout, where the final cause usually is. */
+ readonly keepErrorOutputTail?: boolean;
}
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
@@ -133,14 +135,15 @@ const collectProcessOutput = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.E
),
);
-function redactSshErrorOutput(output: string): string {
+function redactSshErrorOutput(output: string, keepTail = false): string {
const redacted = output.replace(
/("(?:access_token|bearerToken|credential|pairingToken|token)"\s*:\s*")[^"]+(")/giu,
"$1[redacted]$2",
);
- return redacted.length > MAX_SSH_ERROR_OUTPUT_LENGTH
- ? `${redacted.slice(0, MAX_SSH_ERROR_OUTPUT_LENGTH)}\n[truncated]`
- : redacted;
+ if (redacted.length <= MAX_SSH_ERROR_OUTPUT_LENGTH) return redacted;
+ return keepTail
+ ? `[truncated]\n${redacted.slice(-MAX_SSH_ERROR_OUTPUT_LENGTH)}`
+ : `${redacted.slice(0, MAX_SSH_ERROR_OUTPUT_LENGTH)}\n[truncated]`;
}
function normalizeSshErrorMessage(input: {
@@ -262,7 +265,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
);
if (exitCode !== 0) {
- const diagnosticStdout = redactSshErrorOutput(stdout);
+ const diagnosticStdout = redactSshErrorOutput(stdout, input.keepErrorOutputTail);
yield* Effect.logWarning("ssh.command.failed", {
...sshTargetLogFields(target),
command: ["ssh", ...args],