Skip to content

Commit 2ea15ee

Browse files
steipetevincentkoc
andauthored
fix(process): preserve safe mixed-stream command diagnostics (#134428)
* fix(process): retain both streams in command failure details A visible stderr warning hid actionable stdout in failed command errors. Normalize each stream once and retain independent recent tails within the existing error detail budget. Preserve termination reasons, single-stream result caps, progress redraw handling, and UTF-16 boundaries. Reuse the raw Git command owner for trimmed output to remove duplicated execution and failure handling. Keep worktree cleanup and command capture unchanged. * fix(process): preserve safe mixed-stream diagnostics --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent 92d8d63 commit 2ea15ee

3 files changed

Lines changed: 189 additions & 9 deletions

File tree

‎src/agents/worktrees/service.diagnostics.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,33 @@ describe("ManagedWorktreeService failure diagnostics", () => {
110110
return script;
111111
}
112112

113+
it("reports actual mixed setup output without losing diagnostics or cleanup", async () => {
114+
const script = await writeFailingSetup();
115+
await fs.writeFile(
116+
script,
117+
[
118+
"#!/bin/sh",
119+
'printf "%s\\n" "$OPENCLAW_WORKTREE_PATH" > "$OPENCLAW_SOURCE_TREE_PATH/setup-path.txt"',
120+
"printf '%s\\n' 'fatal: create local-fixture-input.txt and retry'",
121+
"printf '%s\\n' 'warning: optional fixture hint is unset' >&2",
122+
"exit 23",
123+
"",
124+
].join("\n"),
125+
);
126+
const message = await failureMessage(
127+
service.create({ repoRoot: repo, name: "actual-failed-setup", baseRef: "HEAD" }),
128+
);
129+
const allocated = (await fs.readFile(path.join(repo, "setup-path.txt"), "utf8")).trim();
130+
await expect(fs.stat(allocated)).rejects.toMatchObject({ code: "ENOENT" });
131+
expect(await git(repo, "worktree", "list", "--porcelain")).not.toContain("actual-failed-setup");
132+
expect(await git(repo, "branch", "--list", "openclaw/actual-failed-setup")).toBe("");
133+
expect(service.listRegistryRecords()).toEqual([]);
134+
expect(message).toContain("worktree setup failed (exit code 23)");
135+
expect(message).toContain("create local-fixture-input.txt and retry");
136+
expect(message).toContain("optional fixture hint is unset");
137+
expect(message.length).toBeLessThanOrEqual(2_300);
138+
});
139+
113140
it.each(terminationCases)("reports setup $name and removes its allocation", async (entry) => {
114141
const script = await writeFailingSetup();
115142
vi.spyOn(commandExec, "runCommandWithTimeout").mockImplementation(async (argv, options) => {

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

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,114 @@ describe("createCommandError", () => {
3535
expect(detail).toBe(`…\n${"y".repeat(1999)}`);
3636
});
3737
});
38+
39+
it.each([false, true])("retains both diagnostics when outputs are buffers: %s", (buffered) => {
40+
const text: SpawnResult = {
41+
...failure,
42+
code: 23,
43+
killed: false,
44+
termination: "exit",
45+
stdout: "Setup cannot continue: create local-fixture-input.txt and retry.\n",
46+
stderr: "Warning: optional fixture hint is unset.\n",
47+
};
48+
const result = buffered
49+
? {
50+
...text,
51+
termination: "exit" as const,
52+
stdout: Buffer.from(text.stdout),
53+
stderr: Buffer.from(text.stderr),
54+
}
55+
: text;
56+
const error = createCommandError("worktree setup", result, { timeoutMs: 120_000 });
57+
expect(error.message).toContain("exit code 23");
58+
expect(error.message).toContain("create local-fixture-input.txt and retry");
59+
expect(error.message).toContain("optional fixture hint is unset");
60+
expect(error.message).toContain("stderr:");
61+
expect(error.message).toContain("stdout:");
62+
expect(error.message).not.toContain("timed out");
63+
});
64+
65+
it("retains complete uneven streams when they fit within the shared budget", () => {
66+
const stdout = `recovery instruction: ${"x".repeat(1_200)}`;
67+
const error = createCommandError(
68+
"worktree setup",
69+
{
70+
...failure,
71+
code: 23,
72+
killed: false,
73+
termination: "exit",
74+
stdout,
75+
stderr: "warning",
76+
},
77+
{ timeoutMs: 120_000 },
78+
);
79+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
80+
expect(detail).toBe(`stderr: warning\nstdout: ${stdout}`);
81+
expect(detail).not.toContain("…");
82+
});
83+
84+
it("sanitizes terminal controls without flattening logical lines", () => {
85+
const error = createCommandError(
86+
"worktree setup",
87+
{
88+
...failure,
89+
code: 23,
90+
killed: false,
91+
termination: "exit",
92+
stdout: "recovery",
93+
stderr: "\u001b[31mstale\rfinal\tfield\u0007\u007f\u0085\nnext\u001b[0m",
94+
},
95+
{ timeoutMs: 120_000 },
96+
);
97+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
98+
expect(detail).toBe("stderr: final\\tfield\nnext\nstdout: recovery");
99+
});
100+
101+
it("keeps independent recent stream tails within the existing error budget", () => {
102+
const error = createCommandError(
103+
"worktree setup",
104+
{
105+
...failure,
106+
code: 23,
107+
killed: false,
108+
termination: "exit",
109+
stdout: `${"old output\n".repeat(30)}${"x".repeat(3000)}\nstdout recovery 🦞`,
110+
stderr: `${"old warning\n".repeat(30)}${"y".repeat(3000)}\nwarning detail 🦞`,
111+
},
112+
{ timeoutMs: 120_000 },
113+
);
114+
expect(error.message).toContain("stdout recovery 🦞");
115+
expect(error.message).toContain("warning detail 🦞");
116+
expect(error.message).not.toContain("old output");
117+
expect(error.message).not.toContain("old warning");
118+
expect(error.message).toContain(":\n");
119+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
120+
expect(detail).toMatch(/^stderr: …\n/u);
121+
expect(detail).toContain("\nstdout: …\n");
122+
expect(detail.length).toBeLessThanOrEqual(2_000);
123+
expect(detail).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/u);
124+
expect(detail).not.toMatch(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u);
125+
expect(error.message.length).toBeLessThan(2300);
126+
});
127+
128+
it.each([
129+
{ stdout: "stdout recovery", stderr: "", present: "stdout recovery" },
130+
{ stdout: "", stderr: "stderr recovery", present: "stderr recovery" },
131+
{ stdout: "stdout recovery", stderr: "\u001b[31m\u001b[0m\r\n", present: "stdout recovery" },
132+
])("keeps single visible output %#: $present", ({ stdout, stderr, present }) => {
133+
const error = createCommandError(
134+
"setup",
135+
{
136+
...failure,
137+
code: 23,
138+
killed: false,
139+
termination: "exit",
140+
stdout,
141+
stderr,
142+
},
143+
{ timeoutMs: 120_000 },
144+
);
145+
const detail = error.message.slice(error.message.indexOf(":\n") + 2);
146+
expect(detail).toBe(present);
147+
expect(error.message).toContain("exit code 23");
148+
});

‎src/process/command-error.ts‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,63 @@
11
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
22
import { sanitizeForLog, stripAnsi } from "../../packages/terminal-core/src/ansi.js";
3+
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
34
import type { SpawnResult } from "./exec-result.js";
45
import type { runCommandBuffered } from "./exec.js";
56

6-
export function formatCommandOutput(output: string | Buffer, maxChars = 800): string {
7-
// Progress redraws use CR, not LF. Keep the last frame, including an
8-
// unfinished redraw, before deciding whether this stream has visible text.
9-
const normalized = stripAnsi(output.toString())
7+
function normalizeCommandOutput(output: string | Buffer): string {
8+
const visible = stripAnsi(output.toString())
109
.replace(/\r\n/g, "\n")
1110
.split("\n")
1211
.map((line) => line.replace(/\r+$/, "").split("\r").at(-1) ?? "")
1312
.join("\n")
1413
.trim();
15-
const tail = normalized.split("\n").slice(-12).join("\n");
16-
const omitted = tail.length < normalized.length || tail.length > maxChars;
17-
return `${omitted ? "…\n" : ""}${sliceUtf16Safe(tail, -maxChars)}`;
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);
1861
}
1962

2063
/** Use an operation label, never argv that may contain credentials. */
@@ -41,8 +84,7 @@ export function createCommandError(
4184
result: SpawnResult | Awaited<ReturnType<typeof runCommandBuffered>>,
4285
options: { timeoutMs: number },
4386
): Error {
44-
const detail =
45-
formatCommandOutput(result.stderr, 2000) || formatCommandOutput(result.stdout, 2000);
87+
const detail = formatCommandErrorDetail(result.stderr, result.stdout);
4688
const reasons: string[] = [];
4789
if (result.termination === "timeout") {
4890
reasons.push(`timed out after ${options.timeoutMs / 1000} seconds`);

0 commit comments

Comments
 (0)