Skip to content

Commit 1bcd270

Browse files
omarshahineCopilot
authored andcommitted
fix(exec): preserve approved exec continuation output
Approved async exec continuations reused the compact background notification formatter, so the agent resumed from the last 400 characters of output with all whitespace collapsed and the head silently dropped. Both hosts now render the continuation through a shared whitespace-preserving formatter bounded at 16,000 UTF-16 units. Compact `notifyOnExit` notifications, poll/retained output, and the gateway diagnostics branch are unchanged. The truncation marker deliberately reports no exact omission count: output can already be capped at capture time without leaving a marker, so an exact number would describe only this cut while reading as though nothing else was lost. Closes #41152 Co-authored-by: Copilot App <[email protected]> Copilot-Session: 2d9762e2-f967-4cdd-9895-299512a20114
1 parent 0245765 commit 1bcd270

9 files changed

Lines changed: 303 additions & 25 deletions

‎src/agents/bash-tools.exec-approval-followup.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,9 @@ function buildExecApprovalFollowupPrompt(resultText: string): string {
9696
"Only ask the user for help if you are actually blocked.",
9797
"",
9898
"Exact completion details:",
99-
trimmed,
99+
// Raw, not trimmed: trailing newlines, tabs, and indentation are part of the command
100+
// output the agent has to work from.
101+
trimmed ? resultText : "",
100102
"",
101103
"Continue the task if needed, then reply to the user in a helpful way.",
102104
"If it succeeded, share the relevant output.",
@@ -331,11 +333,14 @@ export async function sendExecApprovalFollowup(
331333
params: ExecApprovalFollowupParams,
332334
): Promise<boolean> {
333335
const sessionKey = params.sessionKey?.trim();
334-
const resultText = params.resultText.trim();
335-
if (!resultText) {
336+
// Trimmed text only classifies empty/denied results; the raw text is what reaches the
337+
// agent so command whitespace survives the follow-up.
338+
const trimmedResultText = params.resultText.trim();
339+
if (!trimmedResultText) {
336340
return false;
337341
}
338-
const isDenied = isExecDeniedResultText(resultText);
342+
const resultText = params.resultText;
343+
const isDenied = isExecDeniedResultText(trimmedResultText);
339344

340345
const deliveryTarget = resolveExternalBestEffortDeliveryTarget({
341346
channel: params.turnSourceChannel,
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { describe, expect, it } from "vitest";
2+
import { formatExecApprovalContinuationOutput } from "./bash-tools.exec-approval-output.js";
3+
4+
// Pinned so a budget change is a deliberate edit rather than a silent drift.
5+
const MAX_UTF16_UNITS = 16_000;
6+
const MARKER =
7+
"[... truncated to fit the continuation budget; more output may have been dropped when it was captured ...]";
8+
9+
describe("formatExecApprovalContinuationOutput", () => {
10+
it("returns empty output when no stream carries content", () => {
11+
expect(formatExecApprovalContinuationOutput([])).toBe("");
12+
expect(
13+
formatExecApprovalContinuationOutput([
14+
{ label: "stdout", value: "" },
15+
{ label: "stderr", value: undefined },
16+
{ label: "error", value: null },
17+
]),
18+
).toBe("");
19+
});
20+
21+
it("leaves a single stream verbatim and unlabelled", () => {
22+
const value = "line one\nline two\n";
23+
expect(
24+
formatExecApprovalContinuationOutput([
25+
{ label: "stdout", value },
26+
{ label: "stderr", value: "" },
27+
]),
28+
).toBe(value);
29+
});
30+
31+
it("preserves LF, CRLF, tabs, indentation, blank lines and trailing whitespace", () => {
32+
const value = "first\r\n\tindented\n\n spaced \ttrailing\t\n ";
33+
expect(formatExecApprovalContinuationOutput([{ label: "stdout", value }])).toBe(value);
34+
});
35+
36+
it("does not collapse whitespace the way the compact notify formatter does", () => {
37+
const value = "a\n\n\nb c";
38+
const formatted = formatExecApprovalContinuationOutput([{ label: "stdout", value }]);
39+
expect(formatted).toBe(value);
40+
expect(formatted).not.toBe(value.replace(/\s+/g, " ").trim());
41+
});
42+
43+
it("labels streams in deterministic order when several carry content", () => {
44+
expect(
45+
formatExecApprovalContinuationOutput([
46+
{ label: "stdout", value: "out\n" },
47+
{ label: "stderr", value: "err\n" },
48+
{ label: "error", value: "boom" },
49+
]),
50+
).toBe("[stdout]\nout\n\n[stderr]\nerr\n\n[error]\nboom");
51+
});
52+
53+
it("keeps error-only output unlabelled", () => {
54+
expect(
55+
formatExecApprovalContinuationOutput([
56+
{ label: "stdout", value: "" },
57+
{ label: "stderr", value: "" },
58+
{ label: "error", value: "spawn failed" },
59+
]),
60+
).toBe("spawn failed");
61+
});
62+
63+
it("is byte-identical at and below the cap", () => {
64+
const exact = "x".repeat(MAX_UTF16_UNITS);
65+
expect(formatExecApprovalContinuationOutput([{ label: "stdout", value: exact }])).toBe(exact);
66+
const under = "y".repeat(MAX_UTF16_UNITS - 1);
67+
expect(formatExecApprovalContinuationOutput([{ label: "stdout", value: under }])).toBe(under);
68+
});
69+
70+
it("keeps head and tail within the cap and marks the cut once", () => {
71+
const value = `${"a".repeat(30_000)}\n${"b".repeat(30_000)}`;
72+
const formatted = formatExecApprovalContinuationOutput([{ label: "stdout", value }]);
73+
expect(formatted.length).toBeLessThanOrEqual(MAX_UTF16_UNITS);
74+
expect(formatted.split(MARKER)).toHaveLength(2);
75+
expect(formatted.startsWith("a")).toBe(true);
76+
expect(formatted.endsWith("b")).toBe(true);
77+
});
78+
79+
it("does not claim an exact omission count", () => {
80+
const formatted = formatExecApprovalContinuationOutput([
81+
{ label: "stdout", value: "z".repeat(50_000) },
82+
]);
83+
// Source-side capture can already have dropped output without a marker, so the
84+
// continuation must not imply this cut is the whole story.
85+
expect(formatted).toContain("may have been dropped when it was captured");
86+
expect(formatted).not.toMatch(/\d+\s+(characters|units|chars)\s+omitted/);
87+
});
88+
89+
it("never splits a surrogate pair at either cut", () => {
90+
const value = "😀".repeat(20_000);
91+
const formatted = formatExecApprovalContinuationOutput([{ label: "stdout", value }]);
92+
expect(formatted.length).toBeLessThanOrEqual(MAX_UTF16_UNITS);
93+
for (const part of formatted.split(MARKER)) {
94+
expect(part).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/);
95+
expect(part).not.toMatch(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/);
96+
}
97+
});
98+
99+
it("never emits a partial generated stream header", () => {
100+
// Sized so both the head cut and the tail cut land inside the "[stderr]" header.
101+
const headBudget = Math.floor((MAX_UTF16_UNITS - MARKER.length - 2) * 0.75);
102+
const formatted = formatExecApprovalContinuationOutput([
103+
{ label: "stdout", value: "s".repeat(headBudget - 3) },
104+
{ label: "stderr", value: "e".repeat(MAX_UTF16_UNITS) },
105+
]);
106+
expect(formatted.length).toBeLessThanOrEqual(MAX_UTF16_UNITS);
107+
for (const partial of ["[st\n", "[std\n", "[stde", "[stder", "[stderr\n"]) {
108+
expect(formatted).not.toContain(partial);
109+
}
110+
});
111+
112+
it("keeps a source-side truncation marker visible when it fits", () => {
113+
const value = "head output\n... (truncated)\ntail output";
114+
expect(formatExecApprovalContinuationOutput([{ label: "stdout", value }])).toContain(
115+
"... (truncated)",
116+
);
117+
});
118+
});
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Formats command output for the model continuation sent after an approved async exec
2+
// completes. This is deliberately separate from the compact background `notifyOnExit`
3+
// notification path: a notification is a glance, a continuation is what the agent must
4+
// work from, so it keeps whitespace and stays large enough to be useful.
5+
6+
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
7+
8+
// The continuation re-enters the run as a user follow-up, so it bypasses the live
9+
// tool-result guard in attempt-context-guards. Bound it here at the same order of
10+
// magnitude as DEFAULT_MAX_LIVE_TOOL_RESULT_CHARS so one long-running command cannot
11+
// flood the resumed context.
12+
const MAX_UTF16_UNITS = 16_000;
13+
14+
// Command output usually opens with context and closes with the result or error, so keep
15+
// both ends rather than a single window.
16+
const HEAD_SHARE = 0.75;
17+
18+
// Intentionally reports no omission count. Output can already be capped at capture time
19+
// (bash-process-registry `trimWithCap` drops the head at DEFAULT_MAX_OUTPUT and leaves no
20+
// marker), so an exact number here would describe only this cut while reading as though
21+
// nothing else was lost. "may" is the strongest honest claim available at this boundary.
22+
const TRUNCATION_MARKER =
23+
"[... truncated to fit the continuation budget; more output may have been dropped when it was captured ...]";
24+
25+
/** Backs a cut off to a line break so a generated stream header is never split. */
26+
function alignHeadToLineBreak(text: string): string {
27+
const lastBreak = text.lastIndexOf("\n");
28+
return lastBreak > text.length / 2 ? text.slice(0, lastBreak) : text;
29+
}
30+
31+
/** Advances a cut past a line break so a generated stream header is never split. */
32+
function alignTailToLineBreak(text: string): string {
33+
const firstBreak = text.indexOf("\n");
34+
return firstBreak >= 0 && firstBreak < text.length / 2 ? text.slice(firstBreak + 1) : text;
35+
}
36+
37+
function capContinuationOutput(text: string): string {
38+
if (text.length <= MAX_UTF16_UNITS) {
39+
return text;
40+
}
41+
// The marker and its two surrounding newlines are spent from the same budget so the
42+
// rendered result never exceeds the cap.
43+
const cutBudget = MAX_UTF16_UNITS - TRUNCATION_MARKER.length - 2;
44+
const headBudget = Math.floor(cutBudget * HEAD_SHARE);
45+
const head = alignHeadToLineBreak(truncateUtf16Safe(text, headBudget));
46+
const tail = alignTailToLineBreak(sliceUtf16Safe(text, text.length - (cutBudget - headBudget)));
47+
return `${head}\n${TRUNCATION_MARKER}\n${tail}`;
48+
}
49+
50+
/**
51+
* Renders approved exec output for the agent continuation, preserving whitespace exactly.
52+
*
53+
* Streams are emitted in the given order and labelled only when more than one carries
54+
* content, so the common single-stream case stays byte-identical to the command output.
55+
* The node payload supplies separate fields, so this order is not a claim about
56+
* chronological stdout/stderr interleaving.
57+
*/
58+
export function formatExecApprovalContinuationOutput(
59+
streams: readonly { label: string; value?: string | null }[],
60+
): string {
61+
const present = streams.filter((stream) => (stream.value ?? "") !== "");
62+
const [only] = present;
63+
if (!only) {
64+
return "";
65+
}
66+
const rendered =
67+
present.length === 1
68+
? (only.value ?? "")
69+
: present.map((stream) => `[${stream.label}]\n${stream.value ?? ""}`).join("\n");
70+
return capContinuationOutput(rendered);
71+
}

‎src/agents/bash-tools.exec-host-gateway.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,6 @@ vi.mock("./bash-tools.exec-host-shared.js", () => ({
239239
}));
240240

241241
vi.mock("./bash-tools.exec-runtime.js", () => ({
242-
DEFAULT_NOTIFY_TAIL_CHARS: 1000,
243242
createApprovalSlug: vi.fn(() => "slug"),
244243
normalizeNotifyOutput: vi.fn((value) => value),
245244
runExecProcess: runExecProcessMock,
@@ -2080,6 +2079,49 @@ EOF`,
20802079
expect(requireSentFollowupText(0)).toContain("done");
20812080
});
20822081

2082+
it("keeps multiline gateway approval follow-up output intact", async () => {
2083+
buildExecApprovalFollowupTargetMock.mockImplementation((value) => value);
2084+
resolveExecHostApprovalContextMock.mockReturnValue({
2085+
approvals: { allowlist: [], file: { version: 1, agents: {} } },
2086+
hostSecurity: "allowlist",
2087+
hostAsk: "always",
2088+
askFallback: "deny",
2089+
});
2090+
resolveApprovalDecisionOrUndefinedMock.mockResolvedValue("allow-once");
2091+
createExecApprovalDecisionStateMock.mockReturnValue({
2092+
baseDecision: { timedOut: false },
2093+
approvedByAsk: true,
2094+
deniedReason: null,
2095+
});
2096+
const aggregated = "first line\r\n\tindented\n\nlast line \t\n";
2097+
runExecProcessMock.mockResolvedValue({
2098+
session: { id: "sess-1" },
2099+
promise: Promise.resolve({
2100+
status: "completed",
2101+
exitCode: 0,
2102+
timedOut: false,
2103+
aggregated,
2104+
}),
2105+
});
2106+
2107+
const result = await runGatewayAllowlist({
2108+
command: "openclaw sessions export-trajectory --json",
2109+
approvalFollowupMode: "agent",
2110+
sessionId: "approval-session",
2111+
sessionStore: "/tmp/openclaw-sessions.json",
2112+
turnSourceChannel: "webchat",
2113+
});
2114+
2115+
expect(result.pendingResult?.details.status).toBe("approval-pending");
2116+
await vi.waitFor(() => {
2117+
expect(sendExecApprovalFollowupResultMock).toHaveBeenCalledTimes(1);
2118+
});
2119+
const text = requireSentFollowupText(0);
2120+
expect(text).toContain(aggregated);
2121+
// The compact notify formatter would have collapsed every run of whitespace.
2122+
expect(text).not.toContain("first line indented last line");
2123+
});
2124+
20832125
it("fails closed when detached approval metadata cannot be persisted", async () => {
20842126
resolveApprovalDecisionOrUndefinedMock.mockResolvedValue("allow-once");
20852127
createExecApprovalDecisionStateMock.mockReturnValue({

‎src/agents/bash-tools.exec-host-gateway.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import {
4848
} from "../process/gateway-work-admission.js";
4949
import { isNativeApprovalChannel, normalizeMessageChannel } from "../utils/message-channel.js";
5050
import { markBackgrounded, tail } from "./bash-process-registry.js";
51+
import { formatExecApprovalContinuationOutput } from "./bash-tools.exec-approval-output.js";
5152
import {
5253
buildExecApprovalRequesterContext,
5354
buildExecApprovalTurnSourceContext,
@@ -69,7 +70,6 @@ import {
6970
} from "./bash-tools.exec-host-shared.js";
7071
import { appendExecTimeoutRetryGuidance } from "./bash-tools.exec-output.js";
7172
import {
72-
DEFAULT_NOTIFY_TAIL_CHARS,
7373
createApprovalSlug,
7474
normalizeNotifyOutput,
7575
runExecProcess,
@@ -404,9 +404,9 @@ function buildGatewayExecApprovalFollowupSummary(params: {
404404
const body = [diagnosticsText, followupText].filter(Boolean).join("\n\n");
405405
summary = `Exec finished (gateway id=${params.approvalId}, session=${params.sessionId}, ${exitLabel})\n${body}`;
406406
} else {
407-
const output = normalizeNotifyOutput(
408-
tail(params.outcome.aggregated || "", DEFAULT_NOTIFY_TAIL_CHARS),
409-
);
407+
const output = formatExecApprovalContinuationOutput([
408+
{ label: "output", value: params.outcome.aggregated },
409+
]);
410410
summary = output
411411
? `Exec finished (gateway id=${params.approvalId}, session=${params.sessionId}, ${exitLabel})\n${output}`
412412
: `Exec finished (gateway id=${params.approvalId}, session=${params.sessionId}, ${exitLabel})`;

‎src/agents/bash-tools.exec-host-node.cancellation.test.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,7 @@ vi.mock("./bash-tools.exec-host-shared.js", () => ({
8888
vi.mock("./bash-process-registry.js", () => ({ tail: vi.fn((text: string) => text) }));
8989

9090
vi.mock("./bash-tools.exec-runtime.js", () => ({
91-
DEFAULT_NOTIFY_TAIL_CHARS: 1_000,
9291
createApprovalSlug: vi.fn(() => "approval"),
93-
normalizeNotifyOutput: vi.fn((text: string) => text),
9492
}));
9593

9694
vi.mock("./embedded-agent-runner/run/abortable.js", () => ({

‎src/agents/bash-tools.exec-host-node.test.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,7 @@ vi.mock("./bash-tools.exec-host-shared.js", () => ({
291291
}));
292292

293293
vi.mock("./bash-tools.exec-runtime.js", () => ({
294-
DEFAULT_NOTIFY_TAIL_CHARS: 1000,
295294
createApprovalSlug: vi.fn(() => "slug"),
296-
normalizeNotifyOutput: vi.fn((value: string) => value),
297295
}));
298296

299297
vi.mock("./tools/gateway.js", () => ({
@@ -1495,7 +1493,56 @@ describe("executeNodeHostCommand", () => {
14951493
const loneSurrogate = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;
14961494
expect(message).not.toMatch(loneSurrogate);
14971495
expect(message).not.toContain("�");
1498-
expect(message).toContain(`Exec finished (node=node-1 id=approval-1, code 0)\n${tailHead}`);
1496+
// Under the continuation budget the payload survives whole, so the leading `prefix`
1497+
// is no longer dropped by the old compact tail.
1498+
expect(message).toContain(`Exec finished (node=node-1 id=approval-1, code 0)\n${stdout}`);
1499+
expect(message).toContain(prefix);
1500+
expect(message).toContain(tailHead);
1501+
});
1502+
1503+
it("keeps multiline async node approval follow-up output intact", async () => {
1504+
resolveExecHostApprovalContextMock.mockReturnValue({
1505+
approvals: { allowlist: [], file: { version: 1, agents: {} } },
1506+
hostSecurity: "full",
1507+
hostAsk: "always",
1508+
askFallback: "deny",
1509+
});
1510+
const stdout = "first line\r\n\tindented\n\nlast line \t\n";
1511+
const stderr = "warning: something\n";
1512+
callGatewayToolMock.mockImplementation(
1513+
async (method: string, _options: unknown, params: MockNodeInvokeParams | undefined) => {
1514+
if (method === "exec.approvals.node.get") {
1515+
return { file: { version: 1, agents: {} } };
1516+
}
1517+
if (method !== "node.invoke") {
1518+
throw new Error(`unexpected gateway method: ${method}`);
1519+
}
1520+
if (params?.command === "system.run.prepare") {
1521+
return { payload: { plan: preparedPlan } };
1522+
}
1523+
if (params?.command === "system.run") {
1524+
return {
1525+
payload: { success: true, stdout, stderr, exitCode: 0, timedOut: false },
1526+
};
1527+
}
1528+
throw new Error(`unexpected node invoke command: ${String(params?.command)}`);
1529+
},
1530+
);
1531+
1532+
const result = await executeNodeHostCommand(createNodeHostRequest({}));
1533+
1534+
expect(result.details?.status).toBe("approval-pending");
1535+
await vi.waitFor(() => {
1536+
expect(sendExecApprovalFollowupResultMock).toHaveBeenCalled();
1537+
});
1538+
const message = sendExecApprovalFollowupResultMock.mock.calls[0]?.[1];
1539+
if (typeof message !== "string") {
1540+
throw new Error("expected follow-up message");
1541+
}
1542+
expect(message).toContain(`[stdout]\n${stdout}`);
1543+
expect(message).toContain(`[stderr]\n${stderr}`);
1544+
// The compact notify formatter would have collapsed every run of whitespace.
1545+
expect(message).not.toContain("first line indented last line");
14991546
});
15001547

15011548
it("does not build a human approval prompt for node auto-review allows", async () => {

0 commit comments

Comments
 (0)