Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/core/src/tests/tool-handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,51 @@ for (const lateEvent of ["close", "exit", "none"]) {
});
}

test("Bash strips the cwd marker when command output has no trailing newline", async () => {
const workspace = createTempWorkspace();
const result = await handleBashTool({ command: "printf 'x'" }, createContext("bash-no-trailing-newline", workspace));
assert.equal(result.ok, true);
assert.equal(result.output, "x");
assert.doesNotMatch(result.output ?? "", /__DEEPCODE_PWD__/);
assert.equal(fs.realpathSync.native(String(result.metadata?.cwd)), fs.realpathSync.native(workspace));

const multiline = await handleBashTool(
{ command: "printf 'a\\nb'" },
createContext("bash-no-newline-multi", workspace)
);
assert.equal(multiline.output, "a\nb");
});

test("Bash keeps trailing newline and cwd tracking for output that ends with a newline", async () => {
const workspace = createTempWorkspace();
const result = await handleBashTool({ command: "printf 'x\\n'" }, createContext("bash-trailing-newline", workspace));
assert.equal(result.ok, true);
assert.equal(result.output, "x\n");
assert.equal(fs.realpathSync.native(String(result.metadata?.cwd)), fs.realpathSync.native(workspace));
});

test(
"Bash does not expose the cwd marker in the command line of the shell",
{ skip: process.platform === "win32" },
async () => {
const workspace = createTempWorkspace();
const subdir = path.join(workspace, "sub");
fs.mkdirSync(subdir);
await handleBashTool({ command: "cd sub" }, createContext("bash-marker-argv", workspace));

// The command prints the shell's own command line and exits before the real marker is written.
const result = await handleBashTool(
{ command: "ps -o args= -p $$; exit 3" },
createContext("bash-marker-argv", workspace)
);
assert.equal(result.ok, false);
assert.match(result.output ?? "", /exit \$__DEEPCODE_STATUS__/);

const next = await handleBashTool({ command: "pwd" }, createContext("bash-marker-argv", workspace));
assert.equal(fs.realpathSync.native((next.output ?? "").trim()), fs.realpathSync.native(subdir));
}
);

for (const replacement of ["deleted", "file"]) {
test(`Bash falls back when cached cwd is ${replacement}`, async () => {
const workspace = createTempWorkspace();
Expand Down
30 changes: 23 additions & 7 deletions packages/core/src/tools/bash-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const MAX_OUTPUT_CHARS = 30000;
const MAX_CAPTURE_CHARS = 10 * 1024 * 1024;
const BACKGROUND_OUTPUT_DIR = path.join(os.tmpdir(), "deepcode-background");
const TRAILING_BACKGROUND_OPERATOR_PATTERN = /(^|[^\\&])\s*&\s*$/;
const MARKER_PREFIX = "__DEEPCODE_PWD__";
const MARKER_SUFFIX = "__";
const sessionWorkingDirs = new Map<string, string>();
// Process completion and output EOF are separate: descendants may retain pipes.
// Bound output draining after exit, and completion after a timeout kill attempt.
Expand Down Expand Up @@ -146,7 +148,7 @@ function buildShellCommand(command: string): {
marker: string;
} {
const shellPath = resolveShellPath();
const marker = buildMarker();
const { marker, token } = buildMarker();
const initCommand = buildShellInitCommand(shellPath);
const disableExtglobCommand = buildDisableExtglobCommand(shellPath);
const normalizedCommand = rewriteWindowsNullRedirect(command);
Expand All @@ -163,7 +165,8 @@ function buildShellCommand(command: string): {
wrappedParts.push(
normalizedCommand,
"__DEEPCODE_STATUS__=$?",
`printf '%s%s\\n' "${marker}" ${cwdExpression}`,
// The token is passed as a separate argument so the full marker never appears in the command text (argv, `set -x`).
`printf '${MARKER_PREFIX}%s${MARKER_SUFFIX}%s\\n' "${token}" ${cwdExpression}`,
"exit $__DEEPCODE_STATUS__"
);
const wrappedCommand = `{ ${wrappedParts.join("; ")}; } < /dev/null`;
Expand Down Expand Up @@ -504,9 +507,9 @@ function appendChunk(existing: string, chunk: string | Buffer): string {
return `${existing}${text.slice(0, remaining)}`;
}

function buildMarker(): string {
function buildMarker(): { marker: string; token: string } {
const token = Math.random().toString(36).slice(2);
return `__DEEPCODE_PWD__${token}__`;
return { marker: `${MARKER_PREFIX}${token}${MARKER_SUFFIX}`, token };
}

function buildToolCommandResult(
Expand Down Expand Up @@ -546,9 +549,13 @@ function stripMarker(stdout: string, marker: string): { output: string; cwd: str

const lines = stdout.split(/\r?\n/);
let markerIndex = -1;
let markerAt = -1;
for (let i = lines.length - 1; i >= 0; i -= 1) {
if (lines[i].startsWith(marker)) {
// The marker is not at the start of its line when the command output has no trailing newline.
const at = lines[i].lastIndexOf(marker);
if (at !== -1) {
markerIndex = i;
markerAt = at;
break;
}
}
Expand All @@ -558,9 +565,18 @@ function stripMarker(stdout: string, marker: string): { output: string; cwd: str
}

const markerLine = lines[markerIndex];
const shellCwd = markerLine.slice(marker.length).trim();
const shellCwd = markerLine.slice(markerAt + marker.length).trim();
const cwd = shellCwd ? toNativeCwd(shellCwd) : null;
lines.splice(markerIndex, 1);
const leadingText = markerLine.slice(0, markerAt);
if (leadingText) {
// Keep the unterminated output as the command printed it, without the marker's own line break.
lines[markerIndex] = leadingText;
if (markerIndex === lines.length - 2 && lines[lines.length - 1] === "") {
lines.pop();
}
} else {
lines.splice(markerIndex, 1);
}
return { output: lines.join("\n"), cwd };
}

Expand Down