Skip to content

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

Rust

fix: resolve assistant Markdown file links against session cwd (#2108)

Florian Brandbf8894afa558
diff --git a/packages/coding-agent/.changes/session-relative-markdown-links.md b/packages/coding-agent/.changes/session-relative-markdown-links.md
new file mode 100644
index 0000000000..518dd3de40
--- /dev/null
+++ b/packages/coding-agent/.changes/session-relative-markdown-links.md
@@ -0,0 +1 @@
+- Fixed assistant Markdown file links to open relative to the session's working directory, including Windows drive paths ([#2108](https://github.com/PrimeIntellect-ai/prime-agent/issues/2108)).
diff --git a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts b/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
index a39279bfe5..0d90836547 100644
--- a/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
+++ b/packages/coding-agent/src/modes/interactive/components/assistant-message.ts
@@ -1,3 +1,5 @@
+import { resolve, sep } from "node:path";
+import { pathToFileURL } from "node:url";
import type { AssistantMessage } from "@earendil-works/pi-ai";
import {
type Component,
@@ -26,6 +28,7 @@ const OSC133_ZONE_FINAL = "\x1b]133;C\x07";
const LOGIN_RECOVERY_SUFFIX = `\n\n${LOGIN_RECOVERY_MESSAGE}`;
export interface AssistantMessageComponentOptions {
+ cwd?: string;
expanded?: boolean;
precededByToolActivity?: boolean;
/** Replaces Mermaid code blocks in assistant text (never thinking) with Unicode diagrams. */
@@ -127,6 +130,7 @@ export class AssistantMessageComponent extends Container {
private lastBlockTexts = new Map<number, string>();
private precededByToolActivity: boolean;
private mermaidTransform?: MermaidMarkdownTransform;
+ private baseUrl?: string;
private isStreaming = false;
constructor(
@@ -144,6 +148,7 @@ export class AssistantMessageComponent extends Container {
this.expanded = options.expanded ?? false;
this.precededByToolActivity = options.precededByToolActivity ?? false;
this.mermaidTransform = options.mermaidTransform;
+ this.baseUrl = options.cwd ? pathToFileURL(`${resolve(options.cwd)}${sep}`).href : undefined;
// Container for text/thinking content
this.contentContainer = new Container();
@@ -288,6 +293,7 @@ export class AssistantMessageComponent extends Container {
const mermaidTransform = this.mermaidTransform;
const isStreaming = this.isStreaming;
const markdown = new Markdown(content.text.trim(), 1, 0, this.markdownTheme, undefined, {
+ baseUrl: this.baseUrl,
transform:
mermaidTransform && ((md, availableWidth) => mermaidTransform(md, availableWidth, isStreaming)),
});
@@ -327,6 +333,7 @@ export class AssistantMessageComponent extends Container {
{
color: (text: string) => theme.fg("thinkingText", text),
},
+ { baseUrl: this.baseUrl },
);
this.blockMarkdowns.set(i, markdown);
this.lastBlockTexts.set(i, content.thinking.trim());
diff --git a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
index 8e06264658..26e7008825 100644
--- a/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
+++ b/packages/coding-agent/src/modes/interactive/components/conversation-components.ts
@@ -89,6 +89,7 @@ export function buildConversationComponents(
options.markdownTheme,
options.hiddenThinkingLabel ?? "Thinking...",
{
+ cwd: options.cwd,
expanded,
precededByToolActivity:
components.at(-1) instanceof ToolExecutionComponent ||
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index d031837b30..b8e64ad565 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -5834,6 +5834,7 @@ export class InteractiveMode {
this.chatContainer.children.at(-1) instanceof ToolExecutionComponent ||
this.chatContainer.children.at(-1) instanceof AgentMessageComponent,
mermaidTransform: this.mermaidMarkdownTransform,
+ cwd: this.getCurrentCwd(),
},
);
this.streamingMessage = message;
@@ -6482,6 +6483,7 @@ export class InteractiveMode {
this.chatContainer.children.at(-1) instanceof ToolExecutionComponent ||
this.chatContainer.children.at(-1) instanceof AgentMessageComponent,
mermaidTransform: this.mermaidMarkdownTransform,
+ cwd: this.getCurrentCwd(),
},
);
this.chatContainer.addChild(assistantComponent);
diff --git a/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts b/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts
new file mode 100644
index 0000000000..5dadaa46b4
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/2108-assistant-message-links.test.ts
@@ -0,0 +1,135 @@
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { type AssistantMessage, fauxAssistantMessage } from "@earendil-works/pi-ai";
+import { Container, getCapabilities, setCapabilities, TUI } from "@earendil-works/pi-tui";
+import stripAnsi from "strip-ansi";
+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
+import { AssistantMessageComponent } from "../../../src/modes/interactive/components/assistant-message.js";
+import { buildConversationComponents } from "../../../src/modes/interactive/components/conversation-components.js";
+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
+import { getMarkdownTheme, initTheme } from "../../../src/modes/interactive/theme/theme.js";
+
+import { createHarness } from "../harness.js";
+
+const cwd = resolve("/tmp/session #1 100%/project");
+const reportUrl = pathToFileURL(resolve(cwd, "audit-out/report.md")).href;
+let message: AssistantMessage;
+
+function linkTargets(lines: string[]): string[] {
+ return [...new Set([...lines.join("\n").matchAll(/\x1b\]8;;([^\x1b]+)\x1b\\/g)].map((match) => match[1]))];
+}
+
+describe("assistant Markdown file links", () => {
+ const capabilities = getCapabilities();
+ beforeAll(async () => {
+ const harness = await createHarness();
+ try {
+ harness.setResponses([fauxAssistantMessage("[Audit report](audit-out/report.md)")]);
+ await harness.session.prompt("Link the audit report.");
+ const response = harness.session.messages.find((entry) => entry.role === "assistant");
+ if (!response || response.role !== "assistant") throw new Error("Missing faux assistant response");
+ message = response;
+ } finally {
+ harness.cleanup();
+ }
+ });
+ beforeEach(() => {
+ initTheme("dark");
+ setCapabilities({ images: null, trueColor: true, hyperlinks: true });
+ });
+ afterEach(() => setCapabilities(capabilities));
+
+ test.each([
+ ["audit-out/report.md", reportUrl],
+ ["#overview", "#overview"],
+ ["./audit-out/report.md", reportUrl],
+ ["../report.md", pathToFileURL(resolve(cwd, "../report.md")).href],
+ ["/tmp/report.md", pathToFileURL("/tmp/report.md").href],
+ ["<audit-out/my report.md>", pathToFileURL(resolve(cwd, "audit-out/my report.md")).href],
+ ["audit-out/my%20report.md", pathToFileURL(resolve(cwd, "audit-out/my report.md")).href],
+ ["audit-out/report%23draft%25.md", pathToFileURL(resolve(cwd, "audit-out/report#draft%.md")).href],
+ ["audit-out/report.md#findings", `${reportUrl}#findings`],
+ ["file:///tmp/report.md", "file:///tmp/report.md"],
+ ["C:/repo/report.md", "file:///C:/repo/report.md"],
+ [String.raw`C:\repo\report.md`, "file:///C:/repo/report.md"],
+ ["<D:/repo/my report.md>", "file:///D:/repo/my%20report.md"],
+ ["D:/repo/report%23draft.md#findings", "file:///D:/repo/report%23draft.md#findings"],
+ ["https://example.com/report?q=1#findings", "https://example.com/report?q=1#findings"],
+ ["http://example.com/report", "http://example.com/report"],
+ ["mailto:[email protected]", "mailto:[email protected]"],
+ ["https://[invalid", "https://[invalid"],
+ ])("resolves %s without changing the label", (href, expected) => {
+ const component = new AssistantMessageComponent(
+ { ...message, content: [{ type: "text", text: `[Audit report](${href})` }] },
+ false,
+ undefined,
+ undefined,
+ { cwd },
+ );
+ const lines = component.render(80);
+ expect(linkTargets(lines)).toEqual([expected]);
+ expect(stripAnsi(lines.join("\n")).trim()).toBe("Audit report");
+ });
+
+ test.each(["addMessageToChat", "startAssistantStreamingMessage"] as const)(
+ "%s uses the attached session cwd and produces an openable target",
+ (method) => {
+ const chatContainer = new Container();
+ const mode = Object.assign(Object.create(InteractiveMode.prototype), {
+ chatContainer,
+ connectionState: { cwd },
+ uiServices: { getInitialCwd: () => resolve("/tmp/different-launch-directory") },
+ getMarkdownThemeWithSettings: getMarkdownTheme,
+ }) as {
+ addMessageToChat(message: AssistantMessage): void;
+ startAssistantStreamingMessage(message: AssistantMessage): void;
+ };
+ mode[method](message);
+ const targets = linkTargets(chatContainer.render(80));
+ expect(targets).toEqual([reportUrl]);
+ const onOpenUrl = vi.fn();
+ const ui = Object.assign(Object.create(TUI.prototype), { onOpenUrl }) as {
+ openHyperlink(url: string): void;
+ };
+ ui.openHyperlink(targets[0]);
+ expect(onOpenUrl).toHaveBeenCalledExactlyOnceWith(reportUrl);
+ },
+ );
+
+ test("conversation replay carries the session cwd", () => {
+ const components = buildConversationComponents([message], {
+ cwd,
+ ui: new TUI({} as TUI["terminal"]),
+ toolOptions: {},
+ getToolDefinition: () => undefined,
+ });
+ expect(linkTargets(components.flatMap((component) => component.render(80)))).toEqual([reportUrl]);
+ });
+
+ test("streamed reference links and thinking links retain their base after invalidation", () => {
+ const component = new AssistantMessageComponent(undefined, false, undefined, undefined, { cwd });
+ component.updateContent({ ...message, content: [{ type: "text", text: "[Audit report][report]" }] }, true);
+ expect(linkTargets(component.render(80))).toEqual([]);
+ component.updateContent(
+ {
+ ...message,
+ content: [
+ { type: "thinking", thinking: "[Audit report](audit-out/report.md)" },
+ { type: "text", text: "[Audit report][report]\n\n[report]: audit-out/report.md" },
+ ],
+ },
+ false,
+ );
+ expect(linkTargets(component.render(80))).toEqual([reportUrl]);
+ component.invalidate();
+ expect(linkTargets(component.render(8))).toEqual([reportUrl]);
+ });
+
+ test("keeps the visible path fallback when the terminal does not support hyperlinks", () => {
+ setCapabilities({ images: null, trueColor: true, hyperlinks: false });
+ const component = new AssistantMessageComponent(message, false, undefined, undefined, { cwd });
+ const lines = component.render(80);
+ expect(linkTargets(lines)).toEqual([]);
+ expect(stripAnsi(lines.join("\n")).trim()).toBe("Audit report (audit-out/report.md)");
+ });
+});
diff --git a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
index 2dd553165c..e16dc56287 100644
--- a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
@@ -386,6 +386,7 @@ describe("ENG-4531 agent message UI", () => {
const mode = {
chatContainer,
toolOutputExpanded: false,
+ getCurrentCwd: () => "/tmp",
getMarkdownThemeWithSettings: () => undefined,
};
Object.setPrototypeOf(mode, InteractiveMode.prototype);
diff --git a/packages/tui/.changes/session-relative-markdown-links.md b/packages/tui/.changes/session-relative-markdown-links.md
new file mode 100644
index 0000000000..c18b5d39d5
--- /dev/null
+++ b/packages/tui/.changes/session-relative-markdown-links.md
@@ -0,0 +1,2 @@
+- Added a base URL option for resolving relative Markdown links ([#2108](https://github.com/PrimeIntellect-ai/prime-agent/issues/2108)).
+- Fixed Windows drive paths in Markdown links to open as file URLs ([#2108](https://github.com/PrimeIntellect-ai/prime-agent/issues/2108)).
diff --git a/packages/tui/src/components/markdown.ts b/packages/tui/src/components/markdown.ts
index e14598d1a4..704ce10b6a 100644
--- a/packages/tui/src/components/markdown.ts
+++ b/packages/tui/src/components/markdown.ts
@@ -168,6 +168,8 @@ export interface MarkdownTheme {
export interface MarkdownOptions {
/** Transform source Markdown before parsing, with the exact width available for content. */
transform?: (markdown: string, availableWidth: number) => string;
+ /** Base URL for relative link targets. Directory URLs must end with a slash. */
+ baseUrl?: string;
}
interface InlineStyleContext {
@@ -611,9 +613,17 @@ export class Markdown implements Component {
const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
const styledLink = this.theme.link(this.theme.underline(linkText));
if (getCapabilities().hyperlinks) {
+ // A Windows drive letter is a file path, not a URL scheme.
+ const target = token.href.replace(/^([a-z]:[\\/])/i, "file:///$1");
+ const href =
+ !target.startsWith("#") &&
+ (this.options.baseUrl || target !== token.href) &&
+ URL.canParse(target, this.options.baseUrl)
+ ? new URL(target, this.options.baseUrl).href
+ : target;
// OSC 8: render as a clickable hyperlink. The URL is not printed inline,
// so we always show only the link text regardless of whether it matches href.
- result += hyperlink(styledLink, token.href) + stylePrefix;
+ result += hyperlink(styledLink, href) + stylePrefix;
} else {
// Compare raw token.text (not styled) against href for the equality check.
// For mailto: links strip the prefix (autolinked emails use text="[email protected]"