fix(acp): strip multi-line command echoes in workDir-resolved output (#2072)
This commit is contained in:
@@ -85,24 +85,28 @@ func stripCommandEcho(command, workDir, stdout string, commitExactMatch bool) st
|
||||
// that resolve a relative file-path argument in the command to an absolute
|
||||
// (workDir-joined) one before actually invoking the real terminal, while the
|
||||
// tool call's reported "command" field - the same text the chat header
|
||||
// renders - keeps the original relative form. The captured echo line then no
|
||||
// longer matches literally. Retry against just the first echoed line with
|
||||
// the workDir prefix collapsed back out, so real output later in stdout
|
||||
// (which may legitimately contain workDir-prefixed paths of its own) is
|
||||
// never touched.
|
||||
// renders - keeps the original relative form. The captured echo then no
|
||||
// longer matches literally. Retry against exactly as many leading echoed
|
||||
// lines as the command itself spans - a command can carry an embedded
|
||||
// newline (e.g. a multi-line script or commit message passed as a single
|
||||
// tool-call argument), and a real terminal echoes that verbatim across
|
||||
// multiple lines, not just the first - with the workDir prefix collapsed
|
||||
// back out, so real output later in stdout (which may legitimately contain
|
||||
// workDir-prefixed paths of its own) is never touched.
|
||||
func stripCommandEchoWithWorkDir(command, workDir, stdout string, commitExactMatch bool) string {
|
||||
if workDir == "" {
|
||||
return stdout
|
||||
}
|
||||
echoLines := strings.Count(command, "\n") + 1
|
||||
chunk, remainder, hasMore := cutLines(stdout, echoLines)
|
||||
// workDir's trailing slashes are collapsed to exactly one first: a
|
||||
// provider can report cwd already "/"-terminated (e.g. "/repo/"), and
|
||||
// the root directory "/" is inherently "/"-terminated. Appending "/"
|
||||
// unconditionally would search for a doubled separator ("/repo//" or
|
||||
// "//") that the actually-joined path never contains, silently
|
||||
// declining to strip a real echo.
|
||||
firstLine, remainder, hasMore := cutFirstLine(stdout)
|
||||
workDirPrefix := strings.TrimRight(workDir, "/") + "/"
|
||||
if strings.ReplaceAll(firstLine, workDirPrefix, "") != "$ "+command {
|
||||
if strings.ReplaceAll(chunk, workDirPrefix, "") != "$ "+command {
|
||||
return stdout
|
||||
}
|
||||
if !hasMore {
|
||||
@@ -124,14 +128,24 @@ func finishCommandEchoStrip(rest, stdout string, commitExactMatch bool) string {
|
||||
return strings.TrimPrefix(rest, "\n")
|
||||
}
|
||||
|
||||
// cutFirstLine splits s at its first newline, reporting whether one was
|
||||
// found. The returned line excludes both the newline and any preceding "\r".
|
||||
func cutFirstLine(s string) (line, remainder string, hasMore bool) {
|
||||
idx := strings.IndexByte(s, '\n')
|
||||
if idx < 0 {
|
||||
return s, "", false
|
||||
// cutLines splits s at its Nth newline (n >= 1), reporting whether that many
|
||||
// newlines were found. The returned chunk joins the first n lines with "\n"
|
||||
// (matching how a multi-line command's literal newlines read back once
|
||||
// echoed), stripping any "\r" that precedes each newline within it. When s
|
||||
// contains fewer than n newlines, chunk is the whole of s and hasMore is
|
||||
// false - the echo (or its trailing lines) may still be in flight.
|
||||
func cutLines(s string, n int) (chunk, remainder string, hasMore bool) {
|
||||
rest := s
|
||||
for i := 0; i < n; i++ {
|
||||
idx := strings.IndexByte(rest, '\n')
|
||||
if idx < 0 {
|
||||
return s, "", false
|
||||
}
|
||||
rest = rest[idx+1:]
|
||||
}
|
||||
return strings.TrimSuffix(s[:idx], "\r"), s[idx+1:], true
|
||||
chunk = strings.TrimSuffix(s[:len(s)-len(rest)-1], "\r")
|
||||
chunk = strings.ReplaceAll(chunk, "\r\n", "\n")
|
||||
return chunk, rest, true
|
||||
}
|
||||
|
||||
// NormalizeShellToolUpdate merges live and final ACP shell result fields into
|
||||
|
||||
@@ -551,6 +551,33 @@ func TestNormalizeShellToolResultStripsLeadingCommandEchoWithRootWorkDir(t *test
|
||||
require.Equal(t, "hello\n", payload.ShellExec().Output.Stdout)
|
||||
}
|
||||
|
||||
// TestNormalizeShellToolResultStripsLeadingCommandEchoWithWorkDirResolvedPathMultilineCommand
|
||||
// is a regression for a report that PR #1975's workDir fallback still
|
||||
// leaves the echo in the output: the fallback only ever compared stdout's
|
||||
// FIRST line against "$ "+command (see cutLines). A command that itself
|
||||
// contains an embedded newline (e.g. a multi-line script or commit message
|
||||
// passed as a single tool-call argument) is echoed across as many lines as
|
||||
// it spans, not just one, so a single-line comparison can never match and
|
||||
// the entire multi-line echo (with the resolved absolute path) leaks into
|
||||
// the persisted Output.
|
||||
func TestNormalizeShellToolResultStripsLeadingCommandEchoWithWorkDirResolvedPathMultilineCommand(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
command := "echo start\ncat notes.txt"
|
||||
workDir := "/repo"
|
||||
resolvedCommand := "echo start\ncat /repo/notes.txt"
|
||||
|
||||
normalizer := NewNormalizer("")
|
||||
payload := normalizer.NormalizeToolCall("execute", map[string]any{
|
||||
"kind": "execute",
|
||||
"raw_input": map[string]any{"command": command, "cwd": workDir},
|
||||
})
|
||||
|
||||
normalizer.NormalizeToolResult(payload, "$ "+resolvedCommand+"\nstart\nhello\n")
|
||||
|
||||
require.Equal(t, "start\nhello\n", payload.ShellExec().Output.Stdout)
|
||||
}
|
||||
|
||||
func TestNormalizeShellToolUpdateStripsLeadingCommandEchoFromLiveOutput(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -117,4 +117,69 @@ test.describe("shell command output echo stripping", () => {
|
||||
await expect(outputRegion).not.toContainText(cwd);
|
||||
await expect(outputRegion).not.toContainText(resolvedCommand);
|
||||
});
|
||||
|
||||
test("does not repeat a multi-line workDir-resolved echo inside the expanded Output disclosure", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}, testInfo) => {
|
||||
// Regression for a report that the workDir-resolved-path fix above
|
||||
// still leaked the echo: a command that itself carries an embedded
|
||||
// newline (a multi-line script or commit message passed as a single
|
||||
// tool-call argument) is echoed by the real terminal across as many
|
||||
// lines as it spans, not just the first.
|
||||
const command = "echo start\ncat notes.txt";
|
||||
const cwd = "/workspace/example-repo";
|
||||
const resolvedCommand = `echo start\ncat ${cwd}/notes.txt`;
|
||||
const echoedOutput = `$ ${resolvedCommand}\nstart\nhello\n`;
|
||||
|
||||
const script = [
|
||||
`e2e:shell_result("${command.replace(/\n/g, "\\n")}", "${echoedOutput.replace(/\n/g, "\\n")}", "${cwd}")`,
|
||||
'e2e:message("done")',
|
||||
].join("\n");
|
||||
|
||||
const task = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
"Shell echo multiline workDir regression",
|
||||
seedData.agentProfileId,
|
||||
{
|
||||
description: script,
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
},
|
||||
);
|
||||
|
||||
await testPage.goto(`/t/${task.id}`);
|
||||
const session = new SessionPage(testPage);
|
||||
await session.waitForLoad();
|
||||
await session.waitForChatIdle({ timeout: 30_000 });
|
||||
|
||||
const chat = session.activeChat();
|
||||
const commandRow = chat.getByTestId("tool-execute-command").filter({ hasText: "echo start" });
|
||||
await expect(commandRow).toBeVisible();
|
||||
await expect(commandRow).toHaveText(command);
|
||||
|
||||
const disclosure = chat.getByRole("button", { name: "Show command output" });
|
||||
const responsePromise = testPage.waitForResponse(
|
||||
(response) => response.url().endsWith("/shell-output") && response.status() === 200,
|
||||
);
|
||||
await disclosure.click();
|
||||
await responsePromise;
|
||||
|
||||
const outputRegion = chat.getByTestId("tool-execute-output");
|
||||
await expect(outputRegion).toContainText("start");
|
||||
await expect(outputRegion).toContainText("hello");
|
||||
// Critical: neither the workDir-prefixed absolute path nor a repeat of
|
||||
// the resolved multi-line command may leak into the Output disclosure.
|
||||
await expect(outputRegion).not.toContainText(cwd);
|
||||
await expect(outputRegion).not.toContainText("cat /workspace");
|
||||
|
||||
// Visual evidence: the Output disclosure shows only "start\nhello",
|
||||
// never the "$ echo start" / "cat /workspace/..." echo lines.
|
||||
await testPage.screenshot({
|
||||
path: testInfo.outputPath("shell-output-multiline-workdir-echo-fixed.png"),
|
||||
fullPage: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user