Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

fix bash cell labels and restore splash spacing (#373)

kt43c20e68cc97
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 053a0cabef..bd5a6fa56f 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -8,8 +8,10 @@
- Changed the new-chat splash to show only version, model, and cwd metadata and rotate among five example prompts.
- Fixed self-updates losing restored daemon sessions to a socket cleanup race and leaving open session or agents-view windows disconnected.
- Changed daemon connection errors to report the failed operation, session identity, recovery steps, socket, and diagnostic log instead of raw protocol reasons.
+- Changed the Agents View and new-chat splashes to keep one blank row above the butterfly.
- Fixed Agents View retrying after an intentional daemon shutdown instead of stopping with restart guidance.
- Fixed stale heartbeat jobs reopening archived, deleted, or concurrently terminated sessions ([ENG-4519](https://linear.app/primeintellect/issue/ENG-4519/heartbeats-rebirth-sessions-that-were-previously-killed)).
+- Fixed IPython Bash cells with leading blank lines being labeled and previewed as Python ([ENG-4529](https://linear.app/primeintellect/issue/ENG-4529/leading-newline-before-percentpercentbash-names-tool-call-as-python)).
## [0.2.8] - 2026-07-09
diff --git a/packages/coding-agent/src/core/tools/code-preview.ts b/packages/coding-agent/src/core/tools/code-preview.ts
index 6865b1b13f..a28ae0ec8b 100644
--- a/packages/coding-agent/src/core/tools/code-preview.ts
+++ b/packages/coding-agent/src/core/tools/code-preview.ts
@@ -1,6 +1,7 @@
+import { parseIpythonBashCell } from "./ipython-cell-code.js";
+
const DESCRIPTOR_MAX_WIDTH = 64;
-const CELL_MAGIC_PATTERN = /^\s*%%bash\b/;
const MAGIC_LINE_PATTERN = /^\s*!/;
const COMMENT_LINE_PATTERN = /^\s*#/;
const CD_PREFIX_PATTERN = /^\s*cd\s+([^&;|]+)(?:&&|;)\s*/;
@@ -434,9 +435,9 @@ export function previewPythonCode(code: string): CodePreview {
export function previewIpythonCode(code: string): CodePreview {
const trimmedCode = code.trimEnd();
- const lines = trimmedCode.split("\n");
- if (CELL_MAGIC_PATTERN.test(lines[0] ?? "")) {
- return previewBashCommand(lines.slice(1).join("\n"));
+ const bashCell = parseIpythonBashCell(trimmedCode);
+ if (bashCell) {
+ return previewBashCommand(bashCell.body);
}
return previewPythonCode(trimmedCode);
}
diff --git a/packages/coding-agent/src/core/tools/ipython-cell-code.ts b/packages/coding-agent/src/core/tools/ipython-cell-code.ts
new file mode 100644
index 0000000000..9dfbfd552d
--- /dev/null
+++ b/packages/coding-agent/src/core/tools/ipython-cell-code.ts
@@ -0,0 +1,23 @@
+const BASH_CELL_MAGIC_PATTERN = /^((?:[ \t]*\r?\n)*)([ \t]*)%%bash\b([^\r\n]*)(\r?\n|$)/;
+
+export interface ParsedIpythonBashCell {
+ leadingWhitespace: string;
+ indent: string;
+ magicArguments: string;
+ lineBreak: string;
+ body: string;
+}
+
+export function parseIpythonBashCell(code: string): ParsedIpythonBashCell | undefined {
+ const match = BASH_CELL_MAGIC_PATTERN.exec(code);
+ if (!match) {
+ return undefined;
+ }
+ return {
+ leadingWhitespace: match[1] ?? "",
+ indent: match[2] ?? "",
+ magicArguments: match[3] ?? "",
+ lineBreak: match[4] ?? "",
+ body: code.slice(match[0].length),
+ };
+}
diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.ts
index de3382c24b..78a0ae6b19 100644
--- a/packages/coding-agent/src/core/tools/ipython.ts
+++ b/packages/coding-agent/src/core/tools/ipython.ts
@@ -17,6 +17,7 @@ import {
} from "../kernel/index.js";
import { manifestPathIn, type RestoreResult, snapshotPathIn } from "../kernel/state-snapshot.js";
import type { PythonSkillRuntimeInfo } from "../skills.js";
+import { parseIpythonBashCell } from "./ipython-cell-code.js";
import { wrapToolDefinition } from "./tool-definition-wrapper.js";
const RLM_BOOTSTRAP_BASE_CODE = `
@@ -287,17 +288,15 @@ function applyShellSettingsToBashMagicCell(
const shellPath = options?.shellPath?.trim();
if (!commandPrefix && !shellPath) return code;
- const match = /^([ \t]*)%%bash\b([^\r\n]*)(\r?\n|$)/.exec(code);
- if (!match) return code;
+ const bashCell = parseIpythonBashCell(code);
+ if (!bashCell) return code;
- const [, indent, rest, lineBreak] = match;
- const body = code.slice(match[0].length);
const firstLine =
- shellPath && rest.trim().length === 0
- ? `${indent}%%script ${quoteScriptMagicArgument(shellPath)}`
- : `${indent}%%bash${rest}`;
- const nextBody = commandPrefix ? `${commandPrefix}${body ? `\n${body}` : ""}` : body;
- return `${firstLine}${lineBreak || "\n"}${nextBody}`;
+ shellPath && bashCell.magicArguments.trim().length === 0
+ ? `${bashCell.indent}%%script ${quoteScriptMagicArgument(shellPath)}`
+ : `${bashCell.indent}%%bash${bashCell.magicArguments}`;
+ const nextBody = commandPrefix ? `${commandPrefix}${bashCell.body ? `\n${bashCell.body}` : ""}` : bashCell.body;
+ return `${bashCell.leadingWhitespace}${firstLine}${bashCell.lineBreak || "\n"}${nextBody}`;
}
/**
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
index 14fe28e6e7..44a3fd6bfa 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts
@@ -477,6 +477,7 @@ class AgentsViewMode implements Component, Focusable {
() => this.getSplashCwd(),
undefined,
{
+ topPadding: true,
getExtraMetadata: () => [{ label: "agents", value: this.getAgentCountsText() }],
},
);
diff --git a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
index fad1eb4b79..98aeebb00f 100644
--- a/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
+++ b/packages/coding-agent/src/modes/interactive/components/ipython-cell.ts
@@ -8,6 +8,7 @@ import {
} from "@earendil-works/pi-tui";
import { previewIpythonCode } from "../../../core/tools/code-preview.js";
import { generateDiffString } from "../../../core/tools/edit-diff.js";
+import { parseIpythonBashCell } from "../../../core/tools/ipython-cell-code.js";
import { shortenPath } from "../../../core/tools/render-utils.js";
import { getLanguageFromPath, highlightCode, theme } from "../theme/theme.js";
import { getWorkingPulseFrame, WORKING_ICON_FRAMES, workingIconFrame } from "../theme/working-icon.js";
@@ -67,7 +68,6 @@ interface TracebackParts {
}
const MAGIC_LINE_PATTERN = /^\s*!/;
-const CELL_MAGIC_PATTERN = /^\s*%%bash\b/;
// Two columns, matching the code body's "› "/" " gutter so output aligns under it.
const OUTPUT_INDENT = " ";
@@ -322,7 +322,7 @@ export class IPythonCellComponent implements Component {
private collapsedLine(details: IpythonDetails): string {
const code = this.state.code.trimEnd();
- const isBashCell = CELL_MAGIC_PATTERN.test(code.split("\n")[0] ?? "");
+ const isBashCell = parseIpythonBashCell(code) !== undefined;
const preview = previewIpythonCode(code);
const languageLabel = isBashCell && preview.language !== "bash" ? `bash · ${preview.language}` : preview.language;
const parts = [`${this.marker(details)} ${theme.fg("muted", languageLabel)}`];
@@ -371,9 +371,8 @@ export class IPythonCellComponent implements Component {
// `↑in ↓out lines` — the "lines" unit disambiguates from the token counts on
// the activity line. Output is omitted for edits (the diff shows on expand).
private lineCounts(details: IpythonDetails): string | undefined {
- const codeLines = this.state.code.split("\n");
- const isBashCell = CELL_MAGIC_PATTERN.test(codeLines[0] ?? "");
- const body = isBashCell ? codeLines.slice(1) : codeLines;
+ const bashCell = parseIpythonBashCell(this.state.code);
+ const body = (bashCell?.body ?? this.state.code).split(/\r?\n/);
const input = body.filter((line) => line.trim().length > 0).length;
const hasDiffs = (details.diffs?.length ?? 0) > 0;
@@ -437,7 +436,7 @@ export class IPythonCellComponent implements Component {
}
this.addBlank(lines, width);
- const isBashCell = CELL_MAGIC_PATTERN.test(code.split("\n")[0] ?? "");
+ const isBashCell = parseIpythonBashCell(code) !== undefined;
const rawLines = code.split("\n");
for (const [index, rawLine] of rawLines.entries()) {
const prefix = index === 0 ? theme.fg("dim", "› ") : theme.fg("dim", " ");
@@ -449,7 +448,7 @@ export class IPythonCellComponent implements Component {
}
private highlightInputLine(line: string, isBashCell: boolean): string {
- if (isBashCell || MAGIC_LINE_PATTERN.test(line) || CELL_MAGIC_PATTERN.test(line)) {
+ if (isBashCell || MAGIC_LINE_PATTERN.test(line) || parseIpythonBashCell(line) !== undefined) {
return theme.fg("bashMode", line);
}
const highlighted = highlightCode(line, "python");
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 6ea55273ad..1ca660dc81 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -318,6 +318,7 @@ export interface BrandSplashMetadataLine {
export interface BrandSplashHeaderOptions {
logo?: string;
+ topPadding?: boolean;
getExtraMetadata?: () => readonly BrandSplashMetadataLine[];
getHideStartHint?: () => boolean;
getStartHint?: () => string;
@@ -369,15 +370,20 @@ export class BrandSplashHeader implements Component {
]
: [];
const metaStart = Math.max(0, Math.floor((this.logoRaw.length - metaLines.length) / 2));
- const lines = this.logoRaw.map((line, index) => {
- const colored = theme.fg("text", line);
- const meta = index >= metaStart && index < metaStart + metaLines.length ? metaLines[index - metaStart] : "";
- const padding = showMeta
- ? " ".repeat(Math.max(0, this.logoCanvasWidth - visibleWidth(line) + this.gutter))
- : "";
- const content = truncateToWidth(colored + padding + meta, contentWidth, "");
- return " ".repeat(paddingX) + content + " ".repeat(Math.max(0, safeWidth - paddingX - visibleWidth(content)));
- });
+ const lines = this.options.topPadding ? [""] : [];
+ lines.push(
+ ...this.logoRaw.map((line, index) => {
+ const colored = theme.fg("text", line);
+ const meta = index >= metaStart && index < metaStart + metaLines.length ? metaLines[index - metaStart] : "";
+ const padding = showMeta
+ ? " ".repeat(Math.max(0, this.logoCanvasWidth - visibleWidth(line) + this.gutter))
+ : "";
+ const content = truncateToWidth(colored + padding + meta, contentWidth, "");
+ return (
+ " ".repeat(paddingX) + content + " ".repeat(Math.max(0, safeWidth - paddingX - visibleWidth(content)))
+ );
+ }),
+ );
if (this.verboseInstructions) {
lines.push(" ".repeat(safeWidth));
@@ -1101,6 +1107,7 @@ export class InteractiveMode {
() => this.getCurrentCwd(),
verboseInstructions,
{
+ topPadding: true,
getHideStartHint: () => this.childAgentPanelMode !== undefined || !this.isNewChat(),
getStartHint: () => this.startHint,
},
diff --git a/packages/coding-agent/test/interactive-mode-startup.test.ts b/packages/coding-agent/test/interactive-mode-startup.test.ts
index 473ca1c38e..6952665350 100644
--- a/packages/coding-agent/test/interactive-mode-startup.test.ts
+++ b/packages/coding-agent/test/interactive-mode-startup.test.ts
@@ -34,19 +34,22 @@ describe("InteractiveMode startup hints", () => {
return mode;
}
- it("keeps the splash metadata to version, model, and cwd", () => {
+ it("keeps a blank row above the shared splash and limits its metadata", () => {
const header = new BrandSplashHeader(
"0.0.0",
() => "test-model",
() => "/tmp/project",
undefined,
{
+ topPadding: true,
getStartHint: () => 'Try "refactor @<filepath>"',
},
);
- const output = stripAnsi(header.render(120).join("\n"));
+ const lines = header.render(120);
+ const output = stripAnsi(lines.join("\n"));
+ expect(lines[0]).toBe("");
expect(output).toContain("version v0.0.0");
expect(output).toContain("model test-model");
expect(output).toContain("cwd /tmp/project");
@@ -54,6 +57,13 @@ describe("InteractiveMode startup hints", () => {
expect(output).not.toContain("input");
expect(output).not.toContain("files");
expect(output).not.toContain("help");
+
+ const unpadded = new BrandSplashHeader(
+ "0.0.0",
+ () => "test-model",
+ () => "/tmp/project",
+ );
+ expect(unpadded.render(120)[0]).not.toBe("");
});
it("randomly selects from five concise filepath prompts", () => {
diff --git a/packages/coding-agent/test/ipython-provisioner.test.ts b/packages/coding-agent/test/ipython-provisioner.test.ts
index 4370e5356b..176487335f 100644
--- a/packages/coding-agent/test/ipython-provisioner.test.ts
+++ b/packages/coding-agent/test/ipython-provisioner.test.ts
@@ -237,6 +237,32 @@ describe("IpythonKernelProvisioner", () => {
expect(internals.startupListeners.has(onProgress)).toBe(false);
});
+ it("applies shell settings to bash cells after leading blank lines", async () => {
+ const execute = vi.fn<KernelManager["execute"]>().mockResolvedValueOnce(okExecuteResult());
+ const manager = { execute } as unknown as KernelManager;
+ const ensure = vi.fn(async () => manager);
+ const kill = vi.fn(async () => {});
+ const provisioner = { ensure, kill } as unknown as IpythonKernelProvisioner;
+ const tool = createIpythonToolDefinition(tempDir, {
+ provisioner,
+ commandPrefix: "export TEST_PREFIX=1",
+ shellPath: "/custom/bash",
+ });
+
+ await tool.execute(
+ "tool-call",
+ { code: "\n \r\n\t%%bash\r\necho body" },
+ undefined,
+ undefined,
+ {} as ExtensionContext,
+ );
+
+ expect(execute).toHaveBeenCalledWith(
+ "\n \r\n\t%%script /custom/bash\r\nexport TEST_PREFIX=1\necho body",
+ expect.objectContaining({ signal: undefined, onStream: expect.any(Function) }),
+ );
+ });
+
it("lets the user wait when an interrupted kernel is still busy", async () => {
const execute = vi
.fn<KernelManager["execute"]>()
diff --git a/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.ts b/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.ts
new file mode 100644
index 0000000000..529ab7925b
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4529-leading-newline-bash-cell.test.ts
@@ -0,0 +1,79 @@
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";
+import type { TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { Type } from "typebox";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { parseIpythonBashCell } from "../../../src/core/tools/ipython-cell-code.js";
+import { ToolExecutionComponent } from "../../../src/modes/interactive/components/tool-execution.js";
+import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
+import { createHarness, type Harness } from "../harness.js";
+
+const ipythonTool: AgentTool = {
+ name: "ipython",
+ label: "ipython",
+ description: "Execute a test IPython cell",
+ parameters: Type.Object({ code: Type.String() }),
+ execute: async () => ({
+ content: [{ type: "text", text: "" }],
+ details: { status: "ok" },
+ }),
+};
+
+describe("ENG-4529 leading newline before %%bash", () => {
+ let harness: Harness | undefined;
+
+ beforeAll(() => {
+ initTheme("dark");
+ });
+
+ afterEach(() => {
+ harness?.cleanup();
+ harness = undefined;
+ });
+
+ it("parses blank lines, indentation, arguments, and CRLF before the bash body", () => {
+ expect(parseIpythonBashCell(" \r\n\t\r\n %%bash --noprofile\r\necho ok")).toEqual({
+ leadingWhitespace: " \r\n\t\r\n",
+ indent: " ",
+ magicArguments: " --noprofile",
+ lineBreak: "\r\n",
+ body: "echo ok",
+ });
+ expect(parseIpythonBashCell("\nprint('python')")).toBeUndefined();
+ });
+
+ it("renders a generated bash cell with a leading newline as bash", async () => {
+ const code = "\n%%bash\ncd /tmp";
+ harness = await createHarness({ tools: [ipythonTool] });
+ harness.setResponses([
+ fauxAssistantMessage(fauxToolCall("ipython", { code }), { stopReason: "toolUse" }),
+ fauxAssistantMessage("done"),
+ ]);
+
+ await harness.session.prompt("run the command");
+
+ const start = harness.eventsOfType("tool_execution_start")[0];
+ expect(start).toMatchObject({ toolName: "ipython", args: { code } });
+ if (!start) {
+ throw new Error("Expected an IPython tool call");
+ }
+
+ const component = new ToolExecutionComponent(
+ start.toolName,
+ start.toolCallId,
+ start.args,
+ { allowInlineImages: false },
+ undefined,
+ { requestRender: vi.fn() } as unknown as TUI,
+ harness.tempDir,
+ );
+ component.markExecutionStarted();
+ component.setArgsComplete();
+ component.updateResult({ content: [], details: { status: "ok" }, isError: false });
+
+ const rendered = stripAnsi(component.render(100).join("\n"));
+ expect(rendered).toContain("✓ bash · cd /tmp · ↑ 1 lines");
+ expect(rendered).not.toContain("✓ python");
+ });
+});