Skip to content

Commit 1f6ab51

Browse files
steipetevincentkoc
andcommitted
refactor(process): consolidate command diagnostic tails
Reuse the canonical output normalizer and suffix fitter for mixed-stream command errors, preserving terminal sanitation, shared budgets, Unicode boundaries, termination reasons, and independent result-output limits. Follow up on #134428 without reintroducing the Git facade consolidation owned by #132180. Production shrinks by 42 lines, offsetting the original repair's 42-line increase. Add focused behavioral controls; the landed original already passes the 22-case formatter baseline. Co-authored-by: Vincent Koc <[email protected]>
1 parent f0e5968 commit 1f6ab51

2 files changed

Lines changed: 130 additions & 81 deletions

File tree

‎src/process/command-error.test.ts‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from "vitest";
2-
import { createCommandError } from "./command-error.js";
2+
import { createCommandError, formatCommandOutput, formatCommandResult } from "./command-error.js";
33
import type { SpawnResult } from "./exec-result.js";
44

55
const failure: SpawnResult = {
@@ -146,3 +146,94 @@ it.each([
146146
expect(detail).toBe(present);
147147
expect(error.message).toContain("exit code 23");
148148
});
149+
150+
// Buffered capture/launch failures carry an error termination, sometimes with an exit code.
151+
it.each([23, null])("keeps buffered error exit metadata %#", (code) => {
152+
const error = createCommandError(
153+
"setup",
154+
{
155+
...failure,
156+
code,
157+
killed: false,
158+
stdout: Buffer.alloc(0),
159+
stderr: Buffer.alloc(0),
160+
termination: "error",
161+
},
162+
{ timeoutMs: 3_000 },
163+
);
164+
expect(error.message).toBe(code === null ? "setup failed" : "setup failed (exit code 23)");
165+
});
166+
167+
it.each([0, 1])("keeps zero and tiny output caps surrogate-safe %#", (maxChars) => {
168+
expect(formatCommandOutput("🦞", maxChars)).toBe("…\n");
169+
});
170+
171+
it.each([
172+
{ stderr: " \tstale\r\tfinal\tfield\t \n", expected: "stderr: final\\tfield\nstdout: recovery" },
173+
{ stderr: "\u0007\u007f\u0085", expected: "recovery" },
174+
])("keeps trim and control-only normalization %#", ({ stderr, expected }) => {
175+
const error = createCommandError(
176+
"setup",
177+
{
178+
...failure,
179+
code: 23,
180+
killed: false,
181+
termination: "exit",
182+
stderr,
183+
stdout: "recovery",
184+
},
185+
{ timeoutMs: 3_000 },
186+
);
187+
expect(error.message).toBe(`setup failed (exit code 23):\n${expected}`);
188+
});
189+
190+
it("retains a short already-omitted tail alongside the other stream", () => {
191+
const error = createCommandError(
192+
"setup",
193+
{
194+
...failure,
195+
code: 23,
196+
killed: false,
197+
termination: "exit",
198+
stderr: Array.from({ length: 13 }, (_, index) => `note ${index}`).join("\n"),
199+
stdout: "recovery",
200+
},
201+
{ timeoutMs: 3_000 },
202+
);
203+
expect(error.message).toContain("stderr: …\nnote 1\n");
204+
expect(error.message).not.toContain("note 0\n");
205+
expect(error.message).toContain("note 12\nstdout: recovery");
206+
expect(error.message.match(/…/g)).toHaveLength(1);
207+
});
208+
209+
it.each(["stdout", "stderr"] as const)(
210+
"does not widen the result %s cap for a single stream",
211+
(stream) => {
212+
const result = formatCommandResult("command", {
213+
...failure,
214+
code: 23,
215+
killed: false,
216+
termination: "exit",
217+
stdout: "",
218+
stderr: "",
219+
[stream]: "x".repeat(1_600),
220+
});
221+
expect(result).toContain(`${stream}:`);
222+
expect(result).not.toContain("x".repeat(801));
223+
expect(result).toContain("…");
224+
},
225+
);
226+
227+
it("keeps timeout ahead of an output-limit flag", () => {
228+
const error = createCommandError(
229+
"setup",
230+
{
231+
...failure,
232+
code: null,
233+
termination: "timeout",
234+
outputLimitExceeded: true,
235+
},
236+
{ timeoutMs: 3_000 },
237+
);
238+
expect(error.message).toBe("setup failed (timed out after 3 seconds)");
239+
});

‎src/process/command-error.ts‎

Lines changed: 38 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -4,60 +4,18 @@ import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text
44
import type { SpawnResult } from "./exec-result.js";
55
import type { runCommandBuffered } from "./exec.js";
66

7-
function normalizeCommandOutput(output: string | Buffer): string {
8-
const visible = stripAnsi(output.toString())
7+
export function formatCommandOutput(output: string | Buffer, maxChars = 800): string {
8+
// CR redraws replace the current frame; trim before making edge tabs visible.
9+
const text = stripAnsi(output.toString())
910
.replace(/\r\n/g, "\n")
1011
.split("\n")
1112
.map((line) => line.replace(/\r+$/, "").split("\r").at(-1) ?? "")
1213
.join("\n")
13-
.trim();
14-
return visible
15-
.split("\n")
16-
.map((line) => sanitizeTerminalText(line))
17-
.join("\n");
18-
}
19-
20-
function renderCommandOutputTail(output: string, maxChars: number, markerChars = 0): string {
21-
const tail = output.split("\n").slice(-12).join("\n");
22-
if (tail.length === output.length && tail.length <= maxChars) {
23-
return tail;
24-
}
25-
const contentLimit = Math.max(0, Math.floor(maxChars)) - markerChars;
26-
return contentLimit < 0
27-
? ""
28-
: `…\n${contentLimit > 0 ? sliceUtf16Safe(tail, -contentLimit) : ""}`;
29-
}
30-
31-
function formatCommandErrorDetail(stderr: string | Buffer, stdout: string | Buffer): string {
32-
const streams = [normalizeCommandOutput(stderr), normalizeCommandOutput(stdout)];
33-
const visible = streams.filter(Boolean);
34-
if (visible.length < 2) {
35-
return visible[0] ? renderCommandOutputTail(visible[0], 2_000) : "";
36-
}
37-
38-
const bodyBudget = 2_000 - "stderr: \nstdout: ".length;
39-
const demands = streams.map((output) => {
40-
const tail = output.split("\n").slice(-12).join("\n");
41-
return tail.length + (tail.length < output.length ? 2 : 0);
42-
});
43-
let allocations = [...demands];
44-
if (demands[0]! + demands[1]! > bodyBudget) {
45-
allocations = demands.map((demand) => Math.min(demand, Math.floor(bodyBudget / 2)));
46-
const remaining = bodyBudget - allocations[0]! - allocations[1]!;
47-
const stderrUnmet = demands[0]! - allocations[0]!;
48-
const stdoutUnmet = demands[1]! - allocations[1]!;
49-
const index = stderrUnmet >= stdoutUnmet ? 0 : 1;
50-
allocations[index] = allocations[index]! + remaining;
51-
}
52-
return `stderr: ${renderCommandOutputTail(
53-
streams[0]!,
54-
Math.max(0, Math.floor(allocations[0]!)),
55-
2,
56-
)}\nstdout: ${renderCommandOutputTail(streams[1]!, Math.max(0, Math.floor(allocations[1]!)), 2)}`;
57-
}
58-
59-
export function formatCommandOutput(output: string | Buffer, maxChars = 800): string {
60-
return renderCommandOutputTail(normalizeCommandOutput(output), maxChars);
14+
.trim()
15+
.replace(/[^\n]+/g, sanitizeTerminalText);
16+
const tail = text.split("\n").slice(-12).join("\n");
17+
const omitted = tail.length < text.length || tail.length > maxChars;
18+
return `${omitted ? "…\n" : ""}${sliceUtf16Safe(tail, Math.max(0, tail.length - maxChars))}`;
6119
}
6220

6321
/** Use an operation label, never argv that may contain credentials. */
@@ -67,44 +25,44 @@ export function formatCommandResult(command: string, result: SpawnResult): strin
6725
const signal = result.signal ? `, signal=${result.signal}` : "";
6826
const killed = result.killed ? ", killed=true" : "";
6927
const status = result.code === 0 ? "exited" : "failed";
70-
const lines = [
28+
return [
7129
`${label} ${status} (code=${result.code}, termination=${termination}${signal}${killed})`,
72-
];
73-
for (const stream of ["stderr", "stdout"] as const) {
74-
const output = formatCommandOutput(result[stream]);
75-
if (output) {
76-
lines.push(`${stream}: ${output}`);
77-
}
78-
}
79-
return lines.join("\n");
30+
...(["stderr", "stdout"] as const).flatMap((stream) => {
31+
const output = formatCommandOutput(result[stream]);
32+
return output ? [`${stream}: ${output}`] : [];
33+
}),
34+
].join("\n");
8035
}
8136

8237
export function createCommandError(
8338
command: string,
8439
result: SpawnResult | Awaited<ReturnType<typeof runCommandBuffered>>,
8540
options: { timeoutMs: number },
8641
): Error {
87-
const detail = formatCommandErrorDetail(result.stderr, result.stdout);
88-
const reasons: string[] = [];
89-
if (result.termination === "timeout") {
90-
reasons.push(`timed out after ${options.timeoutMs / 1000} seconds`);
91-
} else if (result.termination === "no-output-timeout") {
92-
reasons.push("timed out waiting for output");
93-
} else if (
94-
result.termination === "output-limit" ||
95-
("outputLimitExceeded" in result && result.outputLimitExceeded)
96-
) {
97-
reasons.push("output limit exceeded");
98-
}
99-
if (result.signal) {
100-
reasons.push(`signal ${result.signal}`);
101-
} else if (result.termination === "signal" && reasons.length === 0) {
102-
reasons.push("terminated");
103-
}
104-
if (reasons.length === 0 && result.code !== null) {
105-
reasons.push(`exit code ${result.code}`);
42+
const stderr = formatCommandOutput(result.stderr, 2_000);
43+
const stdout = formatCommandOutput(result.stdout, 2_000);
44+
let detail = stderr || stdout;
45+
if (stderr && stdout) {
46+
const budget = 2_000 - "stderr: \nstdout: ".length;
47+
const first = Math.min(stderr.length, Math.max(Math.ceil(budget / 2), budget - stdout.length));
48+
// Pure suffix fitting replaces any earlier marker; normalization runs only once.
49+
const tail = (output: string, limit: number) =>
50+
output.length <= limit ? output : `…\n${sliceUtf16Safe(output, 2 - limit)}`;
51+
detail = `stderr: ${tail(stderr, first)}\nstdout: ${tail(stdout, budget - first)}`;
10652
}
53+
const signal = result.signal ? `signal ${result.signal}` : "";
54+
const limited =
55+
"outputLimitExceeded" in result && result.outputLimitExceeded ? "output limit exceeded" : "";
56+
const exitReason = limited || (!signal && result.code !== null ? `exit code ${result.code}` : "");
57+
const primary = {
58+
timeout: `timed out after ${options.timeoutMs / 1000} seconds`,
59+
"no-output-timeout": "timed out waiting for output",
60+
"output-limit": "output limit exceeded",
61+
exit: exitReason,
62+
error: exitReason,
63+
signal: limited || (!signal ? "terminated" : ""),
64+
}[result.termination];
65+
const reason = [primary, signal].filter(Boolean).join("; ");
10766
const label = truncateUtf16Safe(stripAnsi(command).replace(/[\r\n]+/g, " "), 256);
108-
const reason = reasons.length > 0 ? ` (${reasons.join("; ")})` : "";
109-
return new Error(`${label} failed${reason}${detail ? `:\n${detail}` : ""}`);
67+
return new Error(`${label} failed${reason ? ` (${reason})` : ""}${detail ? `:\n${detail}` : ""}`);
11068
}

0 commit comments

Comments
 (0)