Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web,desktop): a reply's link to a Workspace file opens it in the Files panel, and the desktop never opens a second app window (#780)

Yaowei Zhengd59484f1bc24
diff --git a/changelog/unreleased/2026-09-17-chat-file-links-open-in-files.md b/changelog/unreleased/2026-09-17-chat-file-links-open-in-files.md
new file mode 100644
index 00000000..c792518e
--- /dev/null
+++ b/changelog/unreleased/2026-09-17-chat-file-links-open-in-files.md
@@ -0,0 +1,39 @@
+# A reply's link to a Workspace file opens it in the Files panel, and the desktop app stops opening another window for it
+
+- **Date:** 2026-09-17
+- **Type:** fix
+- **Scope:** `web`, `desktop`
+- **PR:** [#780](https://github.com/Prism-Shadow/penguin-harness/pull/780)
+
+[中文版](2026-09-17-chat-file-links-open-in-files.zh.md)
+
+Clicking a link in an assistant reply that named a file the Agent wrote —
+`[pelican-bike.html](pelican-bike.html)` — opened a new browser tab on a Web App route that does not
+exist, and in the desktop app opened one more full PenguinHarness window per click. Links in a
+conversation are now sorted before they render, and the desktop shell opens a window of its own
+only for the addresses that need one.
+
+## Web App
+
+- Inside a conversation — the message stream and the subagent conversations in the agents panel,
+ reasoning and compaction summaries included — a relative link, or an absolute path inside the
+ Session's Workspace, opens that file in the Files panel the way a file card's row does. The href
+ is percent-decoded, a leading `./` is dropped, a query or fragment is ignored, and a `..` that
+ leaves the Workspace is refused. A file that does not exist still opens the panel on its path,
+ and the panel reports it missing.
+- In a conversation, an `#anchor` link (a footnote reference or back-reference) scrolls to its
+ target within the page instead of opening a new tab, and a link that names nothing the App can
+ open — a path outside the Workspace, a `file:` URL — no longer opens anything.
+- External `http(s)` and `mailto` links still open in a new tab, and so does every link outside a
+ conversation (Memory, the company handbook, tickets).
+
+## Desktop
+
+- A request for a new window, from the main window or from any window it opened, follows one rule:
+ the Workspace HTML preview's "Open in a new tab" route, pages on the preview host and a detached
+ terminal get a window of the app; `http(s)` and `mailto` links to anywhere else go to the system
+ browser; every other address of the app is refused and logged instead of opening a second copy
+ of the App.
+- Windows opened from a preview window carry the same rules; they previously carried none.
+- A link or navigation with a scheme other than `http`, `https` or `mailto` is no longer handed to
+ the operating system.
diff --git a/changelog/unreleased/2026-09-17-chat-file-links-open-in-files.zh.md b/changelog/unreleased/2026-09-17-chat-file-links-open-in-files.zh.md
new file mode 100644
index 00000000..eb4c45fe
--- /dev/null
+++ b/changelog/unreleased/2026-09-17-chat-file-links-open-in-files.zh.md
@@ -0,0 +1,31 @@
+# 回复中指向 Workspace 文件的链接改在文件面板中打开,桌面端不再因此多开窗口
+
+- **Date:** 2026-09-17
+- **Type:** fix
+- **Scope:** `web`, `desktop`
+- **PR:** [#780](https://github.com/Prism-Shadow/penguin-harness/pull/780)
+
+[English](2026-09-17-chat-file-links-open-in-files.md)
+
+助手回复里指向 Agent 所写文件的链接——如 `[pelican-bike.html](pelican-bike.html)`——点击后会在浏览器
+新标签页打开一个并不存在的 Web App 路由,在桌面端则每点一次就多开一个完整的 PenguinHarness 窗口。现在对话中
+的链接在渲染前先分类,桌面壳也只为确实需要应用内窗口的地址开窗。
+
+## Web App
+
+- 在对话内——消息流与智能体面板中的子会话对话,含思考过程与压缩摘要——相对链接,或位于该 Session
+ Workspace 之内的绝对路径,会像文件卡片的行一样在文件面板中打开该文件:href 先做百分号解码、去掉开头的
+ `./`、忽略查询串与片段,越出 Workspace 的 `..` 一律拒绝。文件不存在时照样在该路径上打开面板,由面板
+ 自己提示文件不存在。
+- 在对话内,`#锚点` 链接(脚注引用与回跳)改为在页面内滚动到目标,不再打开新标签页;指向 App 打不开
+ 之物的链接——Workspace 之外的路径、`file:` URL——点击后不再打开任何东西。
+- 外部 `http(s)` 与 `mailto` 链接仍在新标签页打开,对话之外的所有链接(记忆、公司手册、工单)也照旧在
+ 新标签页打开。
+
+## 桌面端
+
+- 新窗口请求——无论来自主窗口还是它打开的任何窗口——遵循同一条规则:Workspace HTML 预览的「新标签页
+ 打开」路由、预览主机上的页面与拆出的终端获得应用内窗口;指向其他任何地方的 `http(s)` 与 `mailto` 链接
+ 交给系统浏览器;应用的其余地址一律拒绝并记日志,而不是再开一份 App。
+- 从预览窗口打开的窗口同样受这套规则约束;此前它们不受任何约束。
+- 协议不是 `http`、`https` 或 `mailto` 的链接与导航,不再交给操作系统处理。
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index 77f88163..a7ec57a6 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -37,6 +37,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, shell } from "electron";
+import type { WindowOpenHandlerResponse } from "electron";
import { resolveRoot } from "@prismshadow/penguin-core";
import { liveServerLock } from "@prismshadow/penguin-server/lock";
import { appIdentity, desktopDataRoot } from "./app-identity.js";
@@ -61,13 +62,16 @@ import {
import { getUpdaterStatus, handleUpdaterCommand, initUpdater, onUpdaterStatus } from "./updater.js";
import { parseUpdaterCommand, updaterStatusMessage } from "./updater-status.js";
import {
+ classifyWindowOpen,
desktopLoginUrl,
hidesOnClose,
isAppUrl,
isAuthorizationBridgeUrl,
+ isExternalScheme,
isLocalSurfaceUrl,
MAX_SERVER_RESTARTS,
restartDelayMs,
+ urlForLog,
} from "./util.js";
// Identity first: the name decides the userData directory, which also keys the
@@ -143,24 +147,51 @@ function createWindow(url: string): void {
win.on("closed", () => {
win = null;
});
- // "Open in a new tab" (Workspace HTML previews) is an app-origin link that mints a
- // token and 302s to the preview origin — it needs the session cookie, so it must open
- // in a window of this app; handing it to the system browser would land on a 401.
- // Denying it outright (as this did at first) made the entry silently do nothing.
- // Genuinely external links still go to the system browser.
+ // New windows, from this window and from every window it opens, go through one rule
+ // (classifyWindowOpen): only the Workspace preview hand-off, a preview page and a detached
+ // terminal get a window of this app; other sites go to the system browser; anything else
+ // on this instance is refused, since every other app path boots a second copy of the App.
win.webContents.setWindowOpenHandler(({ url: target }) => {
+ // The one addition, and this window's alone: Penguin Go's authorization bridge. The Web
+ // App opens it from the Authorize click, then points it at the platform or closes it when
+ // `/start` fails. It is an implementation detail, not a second app window, so it stays
+ // hidden. It is decided here and not in openWindowFor, which every opened window shares, so
+ // HTML in a preview window cannot open hidden windows. An HTML preview in this window's own
+ // Files panel still can: its iframe allows popups, and this handler is not told which frame
+ // asked.
if (isAuthorizationBridgeUrl(target)) {
return {
action: "allow",
- // The bridge is an implementation detail, not a second app window. The Web App
- // either navigates it to the platform URL or closes it when `/start` fails.
overrideBrowserWindowOptions: {
show: false,
webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },
},
};
}
- if (isLocalSurfaceUrl(target, appOrigin)) {
+ return openWindowFor(target, iconPath);
+ });
+ win.webContents.on("did-create-window", (child, details) =>
+ guardOpenedWindow(child, iconPath, isAuthorizationBridgeUrl(details.url)),
+ );
+ win.webContents.on("will-navigate", (event, target) => {
+ if (!isAppUrl(target, appOrigin)) {
+ event.preventDefault();
+ openInSystem(target);
+ }
+ });
+ win.webContents.on("render-process-gone", () => win?.webContents.reload());
+ armSmokeProbe(win);
+ void win.loadURL(url);
+}
+
+/**
+ * Answers a window-open request from any window of this app (see classifyWindowOpen in
+ * util.ts). A refusal is logged, by origin and path only: the user clicked something, and
+ * this line is the one trace of why nothing opened.
+ */
+function openWindowFor(target: string, iconPath: string | null): WindowOpenHandlerResponse {
+ switch (classifyWindowOpen(target, appOrigin)) {
+ case "window":
return {
action: "allow",
overrideBrowserWindowOptions: {
@@ -168,44 +199,52 @@ function createWindow(url: string): void {
height: 800,
autoHideMenuBar: true,
...(iconPath !== null ? { icon: iconPath } : {}),
- // Same hardening as the main window: the preview is Agent-written, untrusted
- // HTML and must never get Node.
+ // Same hardening as the main window: a preview is Agent-written, untrusted HTML
+ // and must never get Node.
webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },
},
};
- }
- void shell.openExternal(target);
- return { action: "deny" };
- });
- // The child lands on the preview origin after the redirect, so its policy is "stay
- // within this instance's loopback surface, everything else to the system browser" —
- // the main window's stricter app-origin-only rule would bounce the preview itself out.
- win.webContents.on("did-create-window", (child, details) => {
- const authorizationBridge = isAuthorizationBridgeUrl(details.url);
- child.webContents.setWindowOpenHandler(({ url: target }) => {
- if (isLocalSurfaceUrl(target, appOrigin)) return { action: "allow" };
+ case "external":
void shell.openExternal(target);
return { action: "deny" };
- });
- child.webContents.on("will-navigate", (event, target) => {
- if (!isLocalSurfaceUrl(target, appOrigin)) {
- event.preventDefault();
- void shell.openExternal(target);
- // A preview window stays open when one of its links opens externally. The hidden
- // authorization bridge has completed its only job and must not linger.
- if (authorizationBridge) child.close();
- }
- });
- });
- win.webContents.on("will-navigate", (event, target) => {
- if (!isAppUrl(target, appOrigin)) {
+ case "deny":
+ process.stdout.write(`[shell] refused to open a window for ${urlForLog(target)}\n`);
+ return { action: "deny" };
+ }
+}
+
+/**
+ * The rules a window opened by this app lives under — and, in turn, every window that one
+ * opens: a window-open handler belongs to one window, so a window opened from a preview page
+ * would otherwise open anything at all. Its navigation policy is "stay within this instance's
+ * loopback surface": a child lands on the preview host after the redirect, and the main
+ * window's stricter app-origin-only rule would bounce the preview itself out.
+ *
+ * `authorizationBridge` marks the main window's hidden Penguin Go bridge. Only the main window
+ * opens one, so every window further down passes false.
+ */
+function guardOpenedWindow(
+ child: BrowserWindow,
+ iconPath: string | null,
+ authorizationBridge: boolean,
+): void {
+ child.webContents.setWindowOpenHandler(({ url: target }) => openWindowFor(target, iconPath));
+ child.webContents.on("did-create-window", (next) => guardOpenedWindow(next, iconPath, false));
+ child.webContents.on("will-navigate", (event, target) => {
+ if (!isLocalSurfaceUrl(target, appOrigin)) {
event.preventDefault();
- void shell.openExternal(target);
+ openInSystem(target);
+ // A preview window stays open when one of its links opens externally. The hidden
+ // authorization bridge has completed its only job and must not linger.
+ if (authorizationBridge) child.close();
}
});
- win.webContents.on("render-process-gone", () => win?.webContents.reload());
- armSmokeProbe(win);
- void win.loadURL(url);
+}
+
+/** A navigation that leaves the app: a web or mail link goes to the system; any other scheme is refused. */
+function openInSystem(target: string): void {
+ if (isExternalScheme(target)) void shell.openExternal(target);
+ else process.stdout.write(`[shell] refused to hand ${urlForLog(target)} to the system\n`);
}
/**
diff --git a/packages/desktop/src/util.ts b/packages/desktop/src/util.ts
index bf3b8f52..4807a419 100644
--- a/packages/desktop/src/util.ts
+++ b/packages/desktop/src/util.ts
@@ -38,6 +38,15 @@ export function isAppUrl(url: string, origin: string | null): boolean {
}
}
+const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
+
+/**
+ * The host Workspace previews are served from. On loopback the server always puts the App on
+ * `localhost` and previews on this name (loopbackHostRoles in the server's preview-token
+ * service), and the desktop always loads the App on `localhost` (appOriginFor, attach mode).
+ */
+const PREVIEW_HOST = "127.0.0.1";
+
/**
* Whether a URL belongs to this instance's local surface: the app origin itself or its
* loopback counterpart on the same port, which is where Workspace previews are served.
@@ -55,8 +64,85 @@ export function isLocalSurfaceUrl(url: string, origin: string | null): boolean {
return false;
}
if (target.protocol !== app.protocol || target.port !== app.port) return false;
- const loopback = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
- return loopback.has(target.hostname) && loopback.has(app.hostname);
+ return LOOPBACK_HOSTS.has(target.hostname) && LOOPBACK_HOSTS.has(app.hostname);
+}
+
+/** "Open in a new tab" for a Workspace HTML file: mints a preview token, then 302s to the preview host. */
+const PREVIEW_REDIRECT_PATH = /^\/api\/sessions\/[^/]+\/files\/preview-redirect$/;
+
+/** A terminal detached from the dock into a window of its own. */
+const TERMINAL_PATH = "/terminal";
+
+/**
+ * Whether a URL may be handed to the operating system: a web page or a mail link. Never a
+ * file, a script or a custom protocol handler — a preview window runs Agent-written HTML, and
+ * `shell.openExternal` on such a URL launches whatever the OS has registered for it.
+ */
+export function isExternalScheme(url: string): boolean {
+ let protocol: string;
+ try {
+ protocol = new URL(url).protocol;
+ } catch {
+ return false;
+ }
+ return protocol === "http:" || protocol === "https:" || protocol === "mailto:";
+}
+
+/** What a window-open request may do; see classifyWindowOpen. */
+export type WindowOpenAction = "window" | "external" | "deny";
+
+/**
+ * Routes a request to open a new window — a `target="_blank"` link or a `window.open` call,
+ * from the main window or from any window it opened.
+ *
+ * `window`, a window of this app, is for the three URL shapes that cannot work anywhere else:
+ * - the Workspace preview hand-off, `/api/sessions/<id>/files/preview-redirect` on the app
+ * origin. It mints its token with the session cookie, so the system browser would get a 401;
+ * - a preview page, `/preview/…` on the preview host, which is where a preview's own links and
+ * `window.open` calls land;
+ * - a detached terminal, `/terminal` on the app origin: the page needs the session, and the
+ * opener watches the window it gets back to return the tab to the dock when it closes.
+ *
+ * `external`, the system browser, is for an http(s) or mailto URL that is not this instance —
+ * another site, or another port on this machine, such as a dev server a conversation started.
+ *
+ * `deny` is everything else. Every other path on the app origin serves the SPA, and the
+ * preview host redirects every non-preview path back to it, so a relative link in a chat reply
+ * (`/chat/x.html`) would boot a second copy of the App in a new window on a page that does not
+ * exist — one more window per click. Other schemes (`file:`, custom protocol handlers) are
+ * refused outright rather than handed to the OS (isExternalScheme). With no origin, which no
+ * window ever sees, everything is refused.
+ */
+export function classifyWindowOpen(url: string, origin: string | null): WindowOpenAction {
+ if (origin === null || !isExternalScheme(url)) return "deny";
+ const target = new URL(url);
+ if (!isLocalSurfaceUrl(url, origin)) return "external";
+ // Parses: isLocalSurfaceUrl answers false for an origin that does not.
+ const appHost = new URL(origin).hostname;
+ if (target.hostname === appHost) {
+ return PREVIEW_REDIRECT_PATH.test(target.pathname) || target.pathname === TERMINAL_PATH
+ ? "window"
+ : "deny";
+ }
+ return target.hostname === PREVIEW_HOST && target.pathname.startsWith("/preview/")
+ ? "window"
+ : "deny";
+}
+
+/**
+ * A URL as a log line may show it: origin and path for a web URL, the scheme alone for any
+ * other. A query or a fragment can carry a token, and neither says where the request went.
+ */
+export function urlForLog(url: string): string {
+ let target: URL;
+ try {
+ target = new URL(url);
+ } catch {
+ return "an unparsable URL";
+ }
+ return target.protocol === "http:" || target.protocol === "https:"
+ ? `${target.origin}${target.pathname}`
+ : `a ${target.protocol} URL`;
}
/**
diff --git a/packages/desktop/test/util.test.ts b/packages/desktop/test/util.test.ts
index 54a4e6e9..c0a56ef8 100644
--- a/packages/desktop/test/util.test.ts
+++ b/packages/desktop/test/util.test.ts
@@ -1,13 +1,16 @@
import { describe, expect, it } from "vitest";
import {
appOriginFor,
+ classifyWindowOpen,
desktopLoginUrl,
hidesOnClose,
isAppUrl,
isAuthorizationBridgeUrl,
+ isExternalScheme,
isLocalSurfaceUrl,
parsePortFile,
restartDelayMs,
+ urlForLog,
} from "../src/util.js";
describe("parsePortFile", () => {
@@ -62,6 +65,94 @@ describe("isLocalSurfaceUrl", () => {
});
});
+describe("classifyWindowOpen", () => {
+ const origin = "http://localhost:7364";
+
+ it("gives the Workspace preview hand-off a window of the app", () => {
+ // It mints the preview token with the session cookie, so the system browser would get a 401.
+ expect(
+ classifyWindowOpen(
+ "http://localhost:7364/api/sessions/s-1/files/preview-redirect?path=out%2Fpelican-bike.html",
+ origin,
+ ),
+ ).toBe("window");
+ });
+
+ it("gives a page on the preview host a window of the app", () => {
+ expect(
+ classifyWindowOpen("http://127.0.0.1:7364/preview/tok.sig/out/pelican-bike.html", origin),
+ ).toBe("window");
+ });
+
+ it("gives a detached terminal a window of the app", () => {
+ // The opener keeps the returned window to put the tab back when it closes.
+ expect(classifyWindowOpen("http://localhost:7364/terminal?id=t-1", origin)).toBe("window");
+ });
+
+ it("refuses a relative chat link resolved onto an SPA route", () => {
+ // The reported reply's [pelican-bike.html](pelican-bike.html), as the chat page resolves it:
+ // a window here was a second copy of the App, one more per click.
+ expect(classifyWindowOpen("http://localhost:7364/chat/pelican-bike.html", origin)).toBe("deny");
+ expect(classifyWindowOpen("http://localhost:7364/", origin)).toBe("deny");
+ expect(classifyWindowOpen("http://localhost:7364/chat/s-1#user-content-fn-1", origin)).toBe(
+ "deny",
+ );
+ });
+
+ it("refuses near misses of the allowed shapes", () => {
+ for (const url of [
+ // Other API routes, and the hand-off's path with a segment added or taken away.
+ "http://localhost:7364/api/sessions/s-1/files/content?path=a.html",
+ "http://localhost:7364/api/sessions/s-1/files/preview-redirect/extra",
+ "http://localhost:7364/api/sessions/files/preview-redirect",
+ // Dot segments resolve before the path is matched.
+ "http://localhost:7364/api/sessions/s-1/files/preview-redirect/../../../../chat",
+ "http://localhost:7364/terminal/other",
+ // A preview path on the app host, and a non-preview path on the preview host: the
+ // preview host 302s that back to the App.
+ "http://localhost:7364/preview/tok/x.html",
+ "http://127.0.0.1:7364/chat/pelican-bike.html",
+ "http://127.0.0.1:7364/terminal?id=t-1",
+ // The IPv6 loopback on the same port is this instance too, but serves no preview.
+ "http://[::1]:7364/preview/tok/x.html",
+ ]) {
+ expect(classifyWindowOpen(url, origin), url).toBe("deny");
+ }
+ });
+
+ it("sends other sites and other local ports to the system browser", () => {
+ expect(classifyWindowOpen("https://example.com/docs", origin)).toBe("external");
+ expect(classifyWindowOpen("mailto:[email protected]", origin)).toBe("external");
+ // A dev server a conversation started lives on its own port.
+ expect(classifyWindowOpen("http://localhost:3000/", origin)).toBe("external");
+ expect(classifyWindowOpen("http://127.0.0.1:3000/preview/x", origin)).toBe("external");
+ // Another scheme on the same port is not this instance either.
+ expect(classifyWindowOpen("https://localhost:7364/chat", origin)).toBe("external");
+ });
+
+ it("never hands a non-web scheme or junk to the system", () => {
+ for (const url of [
+ "file:///C:/Windows/System32/calc.exe",
+ "javascript:alert(1)",
+ "vscode://file/home/user/a.ts",
+ "not a url",
+ ]) {
+ expect(classifyWindowOpen(url, origin), url).toBe("deny");
+ }
+ });
+
+ it("with no origin yet, a non-web scheme is still refused", () => {
+ expect(classifyWindowOpen("file:///etc/passwd", null)).toBe("deny");
+ });
+
+ it("refuses the Penguin Go authorization bridge, which only the main window may open", () => {
+ // The main window's handler allows the bridge before it classifies anything. Every window
+ // shares this classification, so a preview page asking for about:blank gets no window.
+ expect(isAuthorizationBridgeUrl("about:blank")).toBe(true);
+ expect(classifyWindowOpen("about:blank", origin)).toBe("deny");
+ });
+});
+
describe("isAuthorizationBridgeUrl", () => {
it("accepts only the inert blank window used while authorization starts", () => {
expect(isAuthorizationBridgeUrl("about:blank")).toBe(true);
@@ -71,6 +162,28 @@ describe("isAuthorizationBridgeUrl", () => {
});
});
+describe("isExternalScheme", () => {
+ it("accepts web pages and mail links only", () => {
+ expect(isExternalScheme("https://example.com")).toBe(true);
+ expect(isExternalScheme("http://localhost:3000/")).toBe(true);
+ expect(isExternalScheme("mailto:[email protected]")).toBe(true);
+ expect(isExternalScheme("file:///etc/passwd")).toBe(false);
+ expect(isExternalScheme("ms-settings:privacy")).toBe(false);
+ expect(isExternalScheme("data:text/html,<p>x</p>")).toBe(false);
+ expect(isExternalScheme("/relative")).toBe(false);
+ });
+});
+
+describe("urlForLog", () => {
+ it("keeps origin and path, and drops what can carry a token", () => {
+ expect(urlForLog("http://localhost:7364/api/auth/claim?token=secret#frag")).toBe(
+ "http://localhost:7364/api/auth/claim",
+ );
+ expect(urlForLog("file:///home/user/secret.txt")).toBe("a file: URL");
+ expect(urlForLog("not a url")).toBe("an unparsable URL");
+ });
+});
+
describe("restartDelayMs", () => {
it("doubles from 1s and caps at 8s", () => {
expect([0, 1, 2, 3, 4].map(restartDelayMs)).toEqual([1000, 2000, 4000, 8000, 8000]);
diff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjs
index 03cabdf6..f9464320 100644
--- a/packages/web/e2e/chat.spec.mjs
+++ b/packages/web/e2e/chat.spec.mjs
@@ -130,8 +130,9 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })
await expect(page.locator('[aria-label="已批准 · 手动"]')).toBeVisible();
await expect(page.getByText(/已批准/).filter({ visible: true })).toHaveCount(0);
- // Chat links always open in a new tab and never navigate the SPA away — including bare URLs
- // that remark-gfm autolinks (the mock reply carries one inside a CJK sentence).
+ // External chat links open in a new tab and never navigate the SPA away — including bare URLs
+ // that remark-gfm autolinks (the mock reply carries one inside a CJK sentence). A reply's link
+ // to a Workspace file opens the Files panel instead (md.test.ts, reply-link.test.ts).
const replyLink = page.locator(".md-body a", { hasText: "example.com" }).first();
await expect(replyLink).toBeVisible();
await expect(replyLink).toHaveAttribute("href", /^https:\/\/example\.com\//);
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index c82b5fba..52c128e0 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -6,9 +6,10 @@
* element — subagents, Workspace files, Memory, Trace, terminals — is a tab in the right
* or bottom dock, arranged by the user and persisted globally. This page contributes the
* panel BODIES (they need its session/stream state) through DockPanel's renderPanel, and
- * the stream's jump commands: a message file card opens the Workspace tab on that file
- * (onOpenFile), a subagent chip opens the agents tab focused (onOpenSubagent), a
- * memory-change row opens the Memory tab located (onLocateMemoryChange).
+ * the stream's jump commands: a message file card, or a reply's link to a Workspace file,
+ * opens the Workspace tab on that file (onOpenFile), a subagent chip opens the agents tab
+ * focused (onOpenSubagent), a memory-change row opens the Memory tab located
+ * (onLocateMemoryChange).
* Approval mode and Model/context usage live in the input area's toolbar; context is compacted
* via the /compact slash command.
* Draft state (/chat/new) is carried by DraftView: Agent / Workspace / approval mode / Model are
@@ -352,8 +353,18 @@ export function ChatPage() {
// the conversation on screen.
useSyncExternalStore(subscribeDock, dockVersion);
useSyncExternalStore(subscribeTerminals, terminalApiSupported);
- /** Workspace tab: locate this file in the tree (a message file card's click). */
+ /** Workspace tab: locate this file in the tree (a message file card's click, or a reply's link to a file). */
const [fileOpenRequest, setFileOpenRequest] = useState<{ path: string } | null>(null);
+ /**
+ * Brings the Workspace tab up on a Workspace-relative path. Both callers have already
+ * normalized the text they hold (toWorkspaceRelative strips an absolute prefix and converts
+ * Windows separators). Stable on purpose: every link rendered in the transcript reads it
+ * through context, so a fresh function per render would re-render them all on every frame.
+ */
+ const openWorkspaceFile = useCallback((path: string) => {
+ openPanel("workspace");
+ setFileOpenRequest({ path });
+ }, []);
/** Memory tab: land on this memory's detail (a card row), or the list (null target). */
const [memoryRequest, setMemoryRequest] = useState<{
target: MemoryLocateTarget | null;
@@ -1572,13 +1583,7 @@ export function ChatPage() {
onGiveUp: () => {
void onStop();
},
- onOpenFile: (path) => {
- // The file card has already normalized the text path to a Workspace-relative path
- // (toWorkspaceRelative, including stripping absolute-path prefixes and converting
- // Windows separators), so this just brings the Workspace tab up and navigates to it.
- openPanel("workspace");
- setFileOpenRequest({ path });
- },
+ onOpenFile: openWorkspaceFile,
onOpenSubagent: (sessionId, origin) => {
// Chip click: the agents tab focused on that child (the focus chain ends with the
// child's own id), with the graph pinned to this chip's Task.
diff --git a/packages/web/src/features/chat/md.tsx b/packages/web/src/features/chat/md.tsx
index 5cd2d5b9..15957fe3 100644
--- a/packages/web/src/features/chat/md.tsx
+++ b/packages/web/src/features/chat/md.tsx
@@ -21,11 +21,13 @@
* this one. They only ever ADD to the shared stage and to the maps below; nothing a surface
* passes can take the shared plugins away.
*/
-import { isValidElement, memo } from "react";
+import { createContext, isValidElement, memo, useContext, useMemo } from "react";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import type { Components, ExtraProps, Options } from "react-markdown";
import { NO_REHYPE_PLUGINS, REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
+import { NEW_TAB, replyLinkBehavior } from "../../lib/reply-link";
+import type { WorkspaceLinks } from "../../lib/reply-link";
import { CodeBlock } from "./code-block";
/** Flatten a react-markdown code element's children to plain text (string or string array in practice). */
@@ -62,21 +64,56 @@ function MdPre({ children, streaming }: { children?: ReactNode; streaming: boole
}
/**
- * Link adapter: every chat link opens in a new tab (`target="_blank"` + `rel="noreferrer"`,
- * which also implies `noopener`), unconditionally — including relative and `#anchor` hrefs a
- * model may emit — so clicking a reply link never navigates the SPA away from the live
- * conversation. All other anchor props react-markdown supplies (`href`, `title` from
- * `[text](url "title")`, ...) are forwarded as-is — only its non-DOM `node` prop is stripped —
- * and `target`/`rel` sit after the spread so the new-tab behavior always wins.
- * Long-URL wrapping is CSS (`.md-body a` in styles.css), not handled here.
+ * The Workspace the Markdown below belongs to, when it belongs to one. Only a conversation
+ * provides it (MessageStream); every other surface — Memory, the handbook, tickets — renders
+ * without it and keeps a new tab for every link.
+ */
+const WorkspaceLinksContext = createContext<WorkspaceLinks | null>(null);
+
+/**
+ * Makes the links in the Markdown below Workspace-aware: a link naming a file of `workspace`
+ * opens it through `onOpenFile` (the Files panel) instead of a new tab — see lib/reply-link.ts
+ * for how an href is sorted. With no `onOpenFile` the links keep the new-tab behaviour.
+ *
+ * The value is memoized on its two inputs: a context change re-renders every link in the
+ * transcript, memoized message bodies included, so `onOpenFile` has to be a stable callback.
+ */
+export function WorkspaceLinksProvider({
+ workspace,
+ onOpenFile,
+ children,
+}: {
+ workspace: string | null;
+ onOpenFile: ((path: string) => void) | undefined;
+ children: ReactNode;
+}) {
+ const links = useMemo<WorkspaceLinks | null>(
+ () => (onOpenFile === undefined ? null : { workspace, openFile: onOpenFile }),
+ [workspace, onOpenFile],
+ );
+ return <WorkspaceLinksContext.Provider value={links}>{children}</WorkspaceLinksContext.Provider>;
+}
+
+/**
+ * Link adapter. Outside a conversation every link opens in a new tab (`target="_blank"` +
+ * `rel="noreferrer"`, which also implies `noopener`), unconditionally, so a click never
+ * navigates the SPA away. Inside one (WorkspaceLinksProvider above) only an external link does;
+ * a Workspace file opens in the Files panel, an `#anchor` scrolls within the page, and a
+ * relative href with nowhere to go stays put — a relative href resolves against the SPA's own
+ * route, so a new tab on it is a second copy of the App on a page that does not exist.
+ * All other anchor props react-markdown supplies (`href`, `title` from `[text](url "title")`,
+ * ...) are forwarded as-is — only its non-DOM `node` prop is stripped — and the behaviour sits
+ * after the spread so it always wins. Long-URL wrapping is CSS (`.md-body a` in styles.css).
*/
function MdLink({
node: _node,
children,
...anchorProps
}: ComponentPropsWithoutRef<"a"> & ExtraProps) {
+ const links = useContext(WorkspaceLinksContext);
+ const behavior = links === null ? NEW_TAB : replyLinkBehavior(anchorProps.href, links);
return (
- <a {...anchorProps} target="_blank" rel="noreferrer">
+ <a {...anchorProps} {...behavior}>
{children}
</a>
);
@@ -90,7 +127,8 @@ function MdLink({
* streams, including for blocks that closed long ago. `streaming` is the only thing the adapter
* closes over, so one frozen map per value is enough; the single flip between them happens on
* the settle render, which re-parses the message anyway — the same render the rehype stage
- * flips on. The `a` adapter closes over nothing, so both maps share the one `MdLink` reference.
+ * flips on. The `a` adapter closes over nothing — the Workspace it needs comes from context, not
+ * from a closure — so both maps share the one `MdLink` reference.
*/
const STREAMING_COMPONENTS: Components = {
pre: (props) => <MdPre streaming>{props.children}</MdPre>,
diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsx
index d3952f77..470b05ea 100644
--- a/packages/web/src/features/chat/message-stream.tsx
+++ b/packages/web/src/features/chat/message-stream.tsx
@@ -14,6 +14,7 @@ import type { TaskStats } from "../../lib/omni/task-stats";
import type { PendingApproval } from "./use-session-stream";
import { EmptyState } from "../../components/ui/empty-state";
import { MessageItem } from "./message-item";
+import { WorkspaceLinksProvider } from "./md";
import { WorkGroup, isWorkItem } from "./work-group";
import { createStreamFollow, stickToBottom } from "./stream-follow";
import type { StreamFollow } from "./stream-follow";
@@ -50,7 +51,12 @@ export interface StreamRenderContext {
onRetryNow?: () => void;
/** "Give up" on the live reconnect countdown: the ordinary session abort (same call as the Stop button). */
onGiveUp?: () => void;
- /** Opens the Files panel and navigates to this file (triggered by clicking the file-summary card at the end of a message; takes a Workspace-relative path); the card doesn't render if this isn't wired up. */
+ /**
+ * Opens the Files panel and navigates to this file (a file-summary card's row, or a link in
+ * the stream's Markdown naming a Workspace file; takes a Workspace-relative path). The card
+ * doesn't render and links keep opening a new tab if this isn't wired up. Must be stable:
+ * every rendered link reads it through context (see WorkspaceLinksProvider).
+ */
onOpenFile?: (path: string) => void;
/** Opens the subagents panel focused on this child session (subagent chip click); `origin` is the ctx.origin at the chip's render level — the child's ancestor chain, excluding its own id. */
onOpenSubagent?: (sessionId: string, origin: string[]) => void;
@@ -436,7 +442,11 @@ export function MessageStream({
{items.length === 0 ? (
<EmptyState title={S.chat.emptyStream} />
) : (
- <MessageItems items={items} ctx={ctx} />
+ // Links in replies, reasoning and compaction summaries name files of this Session's
+ // Workspace: they open in its Files panel rather than a new tab (see md.tsx).
+ <WorkspaceLinksProvider workspace={ctx.workspace ?? null} onOpenFile={ctx.onOpenFile}>
+ <MessageItems items={items} ctx={ctx} />
+ </WorkspaceLinksProvider>
)}
</div>
</div>
diff --git a/packages/web/src/lib/reply-link.ts b/packages/web/src/lib/reply-link.ts
new file mode 100644
index 00000000..b58ee821
--- /dev/null
+++ b/packages/web/src/lib/reply-link.ts
@@ -0,0 +1,130 @@
+/**
+ * Where a link in a conversation's Markdown goes.
+ *
+ * A model links the files it wrote the way a README would — `[pelican-bike.html](pelican-bike.html)`,
+ * relative to the Workspace it works in. The browser resolves that href against the SPA's own
+ * route instead (`/chat/pelican-bike.html`, a page that does not exist), so opening it in a new
+ * tab boots a second copy of the App on nothing, and inside the desktop shell every click used to
+ * open another app window. Inside a conversation an href is therefore sorted before it renders:
+ *
+ * - `external` — it names a scheme (`https:`, `mailto:`, …) or is protocol-relative (`//host`).
+ * Another site: it opens in a new tab, as every chat link always has.
+ * - `anchor` — `#id`: a place inside the rendered Markdown (GFM footnotes are the anchors the
+ * renderer emits), never a navigation of the App.
+ * - `file` — anything else that resolves to a Workspace-relative path. The href is
+ * percent-decoded first (the renderer encodes non-ASCII, so a CJK file name arrives as
+ * `%E4%B8%AD…`), its query and hash are dropped, and it is then normalized exactly as file
+ * mentions in a reply are (`toWorkspaceRelative`): `./` and empty segments drop, an inner `..`
+ * pops, and an absolute path counts only when it lies inside the Session's Workspace.
+ * - `none` — the rest: a `..` that climbs out of the Workspace, an absolute path outside it, a
+ * `~` path, and an href the renderer emptied (react-markdown replaces every scheme it does not
+ * trust with "", `file:` URLs and Windows drive-letter paths included). Nothing in the App
+ * can open it, so it does not navigate at all.
+ *
+ * Existence is deliberately not checked: a link to a file that is not there still opens the
+ * Files panel on that path, and the panel's own state says the file is missing.
+ */
+import type { MouseEvent } from "react";
+import { toWorkspaceRelative } from "./file-path";
+
+export type ReplyLink =
+ | { kind: "external" }
+ | { kind: "anchor"; id: string }
+ | { kind: "file"; path: string }
+ | { kind: "none" };
+
+/** A URL scheme, as the URL parser reads one: a letter, then letters, digits, `+`, `.` or `-`, then `:`. */
+const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
+
+const EXTERNAL: ReplyLink = { kind: "external" };
+const NONE: ReplyLink = { kind: "none" };
+
+function decode(text: string): string | null {
+ try {
+ return decodeURIComponent(text);
+ } catch {
+ return null;
+ }
+}
+
+/** Sorts one href from a conversation's Markdown; `workspace` is the Session's absolute Workspace path. */
+export function resolveReplyLink(href: string | undefined, workspace: string | null): ReplyLink {
+ if (href === undefined || href === "") return NONE;
+ if (href.startsWith("#")) {
+ const id = decode(href.slice(1));
+ return id === null || id === "" ? NONE : { kind: "anchor", id };
+ }
+ if (href.startsWith("//") || SCHEME_RE.test(href)) return EXTERNAL;
+ const decoded = decode(href.replace(/[?#].*$/, ""));
+ if (decoded === null) return NONE;
+ const path = toWorkspaceRelative(decoded, workspace);
+ return path === null ? NONE : { kind: "file", path };
+}
+
+/** What a conversation hands the Markdown it renders, so a link to a Workspace file opens in place. */
+export interface WorkspaceLinks {
+ /** The Session's absolute Workspace path, which an absolute href must lie inside. */
+ workspace: string | null;
+ /** Opens a Workspace-relative path in the conversation's Files panel. */
+ openFile: (path: string) => void;
+}
+
+/** The attributes a rendered link adds on top of its own. */
+export interface LinkBehavior {
+ target?: "_blank";
+ rel?: "noreferrer";
+ onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;
+}
+
+/**
+ * A new tab with no handle back to this window (`noreferrer` implies `noopener`): every Markdown
+ * link outside a conversation, and an external one inside it.
+ */
+export const NEW_TAB: LinkBehavior = { target: "_blank", rel: "noreferrer" };
+
+const preventNavigation = (event: MouseEvent<HTMLAnchorElement>): void => event.preventDefault();
+
+/**
+ * Scrolls to the element an in-page link names, searching outward from the link: every reply
+ * numbers its footnotes from 1, so one transcript can hold several `user-content-fn-1`, and the
+ * one meant is the one nearest the link that was clicked.
+ */
+function scrollToAnchor(from: Element, id: string): void {
+ for (let scope = from.parentElement; scope !== null; scope = scope.parentElement) {
+ const target = scope.querySelector(`#${CSS.escape(id)}`);
+ if (target !== null) {
+ target.scrollIntoView({ block: "center" });
+ return;
+ }
+ }
+}
+
+/**
+ * How a link behaves inside a conversation. Only an external link opens a new tab; a Workspace
+ * file opens in the Files panel, an anchor scrolls within the page, and an href with nowhere to
+ * go stays put. Each of the last three prevents the default for every click, modifier keys
+ * included — the href they would follow is a route of the App, never a page.
+ */
+export function replyLinkBehavior(href: string | undefined, links: WorkspaceLinks): LinkBehavior {
+ const link = resolveReplyLink(href, links.workspace);
+ switch (link.kind) {
+ case "external":
+ return NEW_TAB;
+ case "file":
+ return {
+ onClick: (event) => {
+ event.preventDefault();
+ links.openFile(link.path);
+ },
+ };
+ case "anchor":
+ return {
+ onClick: (event) => {
+ event.preventDefault();
+ scrollToAnchor(event.currentTarget, link.id);
+ },
+ };
+ case "none":
+ return { onClick: preventNavigation };
+ }
+}
diff --git a/packages/web/test/md.test.ts b/packages/web/test/md.test.ts
index 80c79cd6..16e17eea 100644
--- a/packages/web/test/md.test.ts
+++ b/packages/web/test/md.test.ts
@@ -1,27 +1,63 @@
/**
* Md (chat markdown) rendering contract, via react-dom/server static markup (node env, no DOM):
- * - every link — explicit [text](url), bare autolinked URL (remark-gfm), relative or #anchor —
- * opens in a new tab: target="_blank" + rel="noreferrer" (a chat link must never navigate the
- * SPA away from the live conversation);
+ * - outside a conversation every link — explicit [text](url), bare autolinked URL (remark-gfm),
+ * relative or #anchor — opens in a new tab: target="_blank" + rel="noreferrer";
+ * - inside one (WorkspaceLinksProvider, as MessageStream renders it) only an external link does:
+ * a link to a Workspace file, an #anchor and a relative href with nowhere to go render without
+ * a target, because a relative href resolves against the SPA's own route. What their clicks do
+ * is covered in reply-link.test.ts — static markup carries no handlers;
* - fenced code still routes through the module-scope pre override into CodeBlock (its chrome
* renders; Shiki only loads in an effect, which static markup never runs).
*/
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { createElement } from "react";
+import type { MouseEvent } from "react";
import { renderToStaticMarkup } from "react-dom/server";
-import { Md } from "../src/features/chat/md";
+import { Md, WorkspaceLinksProvider } from "../src/features/chat/md";
+import { replyLinkBehavior, resolveReplyLink } from "../src/lib/reply-link";
const render = (text: string, streaming = false) =>
renderToStaticMarkup(createElement(Md, { text, streaming }));
+const WS = "/home/user/workspaces/tmp-1";
+
+/**
+ * Renders inside a conversation's Workspace, the way MessageStream wraps its items. `onOpenFile`
+ * is passed through as given — undefined included — since that is how a stream with no file
+ * opener wired renders.
+ */
+const renderWithOpener = (
+ text: string,
+ onOpenFile: ((path: string) => void) | undefined,
+ streaming = false,
+) =>
+ renderToStaticMarkup(
+ createElement(WorkspaceLinksProvider, {
+ workspace: WS,
+ onOpenFile,
+ children: createElement(Md, { text, streaming }),
+ }),
+ );
+
+const renderInConversation = (text: string, streaming = false) =>
+ renderWithOpener(text, () => undefined, streaming);
+
/** All rendered <a ...> opening tags. */
const anchors = (html: string) => html.match(/<a\b[^>]*>/g) ?? [];
+/** The href attribute of a rendered opening tag, as react-dom escaped it. */
+const hrefOf = (tag: string | undefined) => /href="([^"]*)"/.exec(tag ?? "")?.[1];
+
const expectNewTab = (tag: string | undefined) => {
expect(tag).toContain('target="_blank"');
expect(tag).toContain('rel="noreferrer"');
};
+const expectInPlace = (tag: string | undefined) => {
+ expect(tag).not.toContain("target=");
+ expect(tag).not.toContain("rel=");
+};
+
describe("Md links", () => {
it("explicit markdown links open in a new tab", () => {
const html = render("See [the docs](https://example.com/docs) for details.");
@@ -49,7 +85,7 @@ describe("Md links", () => {
expectNewTab(tags[0]);
});
- it("relative and #anchor hrefs also open in a new tab (never SPA-navigate)", () => {
+ it("outside a conversation, relative and #anchor hrefs also open in a new tab (never SPA-navigate)", () => {
const html = render("[rel](./file.md) and [frag](#section)");
const tags = anchors(html);
expect(tags).toHaveLength(2);
@@ -65,6 +101,79 @@ describe("Md links", () => {
});
});
+describe("Md links inside a conversation", () => {
+ it("a reply's relative link to a Workspace file renders in place, and its click opens the file", () => {
+ // The reported reply, verbatim.
+ const html = renderInConversation(
+ "已创建: [pelican-bike.html](pelican-bike.html)\n\n用浏览器打开即可观看:",
+ );
+ const tags = anchors(html);
+ expect(tags).toHaveLength(1);
+ expect(hrefOf(tags[0])).toBe("pelican-bike.html");
+ expectInPlace(tags[0]);
+ // Static markup drops handlers, so the click goes through the behaviour MdLink spreads onto
+ // this anchor, fed the href the renderer actually produced.
+ const openFile = vi.fn();
+ const preventDefault = vi.fn();
+ replyLinkBehavior(hrefOf(tags[0]), { workspace: WS, openFile }).onClick!({
+ preventDefault,
+ } as unknown as MouseEvent<HTMLAnchorElement>);
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(openFile).toHaveBeenCalledExactlyOnceWith("pelican-bike.html");
+ });
+
+ it("a CJK file name reaches the adapter percent-encoded and still resolves to the name on disk", () => {
+ const tags = anchors(renderInConversation("[预览](./鹈鹕.html)"));
+ expect(tags).toHaveLength(1);
+ expectInPlace(tags[0]);
+ expect(resolveReplyLink(hrefOf(tags[0]), WS)).toEqual({ kind: "file", path: "鹈鹕.html" });
+ });
+
+ it("external links, bare URLs included, still open in a new tab", () => {
+ const tags = anchors(
+ renderInConversation("[docs](https://example.com/docs) and https://example.com/raw"),
+ );
+ expect(tags).toHaveLength(2);
+ for (const tag of tags) expectNewTab(tag);
+ });
+
+ it("an #anchor, a footnote reference and an href with nowhere to go render without a target", () => {
+ const html = renderInConversation(
+ "[frag](#section), [up](../outside.html), [sys](/etc/hosts)[^1]\n\n[^1]: A note.",
+ );
+ const tags = anchors(html);
+ // frag, up, sys, the footnote reference, and the footnote's back-reference.
+ expect(tags).toHaveLength(5);
+ for (const tag of tags) expectInPlace(tag);
+ expect(html).toContain('id="user-content-fn-1"');
+ });
+
+ it("a file: URL and a Windows drive-letter path reach the adapter emptied, and stay in place", () => {
+ const tags = anchors(
+ renderInConversation("[a](file:///home/user/a.html) and [b](C:/Users/me/ws/b.html)"),
+ );
+ expect(tags).toHaveLength(2);
+ for (const tag of tags) {
+ expect(hrefOf(tag)).toBe("");
+ expectInPlace(tag);
+ }
+ });
+
+ it("applies in both streaming and settled component maps", () => {
+ for (const streaming of [true, false]) {
+ const tags = anchors(renderInConversation("[x](report.md)", streaming));
+ expect(tags).toHaveLength(1);
+ expectInPlace(tags[0]);
+ }
+ });
+
+ it("with no file opener wired, a conversation's links keep the new tab", () => {
+ const tags = anchors(renderWithOpener("[x](pelican-bike.html)", undefined));
+ expect(tags).toHaveLength(1);
+ expectNewTab(tags[0]);
+ });
+});
+
describe("Md code blocks", () => {
it("fenced code still renders through the CodeBlock pre override", () => {
const html = render("```js\nconst a = 1;\n```");
diff --git a/packages/web/test/message-stream.test.ts b/packages/web/test/message-stream.test.ts
new file mode 100644
index 00000000..7e87ca66
--- /dev/null
+++ b/packages/web/test/message-stream.test.ts
@@ -0,0 +1,75 @@
+/**
+ * MessageStream hands the links in its Markdown the conversation's Workspace and file opener
+ * (react-dom/server static markup, node env, no DOM). Static markup carries no handlers, so
+ * replyLinkBehavior is wrapped rather than replaced: every call still returns the real behaviour,
+ * and the test keeps what the link adapter spread onto each rendered anchor in order to click it.
+ */
+import { describe, expect, it, vi } from "vitest";
+import { createElement } from "react";
+import type { MouseEvent } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { MessageStream } from "../src/features/chat/message-stream";
+import type { StreamRenderContext } from "../src/features/chat/message-stream";
+import type { LinkBehavior } from "../src/lib/reply-link";
+
+/** The behaviour each rendered link received, by the href it was sorted from. */
+const rendered = vi.hoisted(() => new Map<string | undefined, LinkBehavior>());
+
+vi.mock("../src/lib/reply-link", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../src/lib/reply-link")>();
+ return {
+ ...actual,
+ replyLinkBehavior: (...args: Parameters<typeof actual.replyLinkBehavior>) => {
+ const behavior = actual.replyLinkBehavior(...args);
+ rendered.set(args[0], behavior);
+ return behavior;
+ },
+ };
+});
+
+const WS = "/home/user/workspaces/tmp-1";
+
+/** All rendered <a ...> opening tags. */
+const anchors = (html: string) => html.match(/<a\b[^>]*>/g) ?? [];
+
+describe("MessageStream links", () => {
+ it("a reply's link to a Workspace file renders without a target, and its click opens the file", () => {
+ const onOpenFile = vi.fn();
+ const ctx: StreamRenderContext = {
+ pendingApprovals: new Map(),
+ onApprove: async () => {},
+ origin: [],
+ taskRunning: false,
+ workspace: WS,
+ onOpenFile,
+ };
+ const html = renderToStaticMarkup(
+ createElement(MessageStream, {
+ items: [
+ {
+ kind: "assistant_text",
+ id: 1,
+ text: `[a](a.html) and [b](${WS}/out/b.html)`,
+ streaming: false,
+ },
+ ],
+ version: 1,
+ ctx,
+ }),
+ );
+ const tags = anchors(html);
+ expect(tags).toHaveLength(2);
+ for (const tag of tags) expect(tag).not.toContain("target=");
+ // The absolute href resolves only because the stream passed its Workspace along.
+ for (const [href, path] of [
+ ["a.html", "a.html"],
+ [`${WS}/out/b.html`, "out/b.html"],
+ ] as const) {
+ const preventDefault = vi.fn();
+ onOpenFile.mockClear();
+ rendered.get(href)!.onClick!({ preventDefault } as unknown as MouseEvent<HTMLAnchorElement>);
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(onOpenFile).toHaveBeenCalledExactlyOnceWith(path);
+ }
+ });
+});
diff --git a/packages/web/test/reply-link.test.ts b/packages/web/test/reply-link.test.ts
new file mode 100644
index 00000000..9c2dd27d
--- /dev/null
+++ b/packages/web/test/reply-link.test.ts
@@ -0,0 +1,183 @@
+/**
+ * reply-link.ts: how an href in a conversation's Markdown is sorted (resolveReplyLink) and what a
+ * click on each kind does (replyLinkBehavior). The hrefs here are the shapes the renderer
+ * actually hands the link adapter — micromark percent-encodes non-ASCII, and react-markdown
+ * empties any scheme it does not trust — which md.test.ts pins through the real pipeline.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { MouseEvent } from "react";
+import { NEW_TAB, replyLinkBehavior, resolveReplyLink } from "../src/lib/reply-link";
+
+const WS = "/home/user/workspaces/tmp-1";
+
+describe("resolveReplyLink", () => {
+ it("a relative href is a Workspace file", () => {
+ expect(resolveReplyLink("pelican-bike.html", WS)).toEqual({
+ kind: "file",
+ path: "pelican-bike.html",
+ });
+ expect(resolveReplyLink("sub/dir/a.txt", WS)).toEqual({ kind: "file", path: "sub/dir/a.txt" });
+ });
+
+ it("a leading ./ and inner . segments drop", () => {
+ expect(resolveReplyLink("./pelican-bike.html", WS)).toEqual({
+ kind: "file",
+ path: "pelican-bike.html",
+ });
+ expect(resolveReplyLink("./sub/./a.md", WS)).toEqual({ kind: "file", path: "sub/a.md" });
+ });
+
+ it("percent-encoding is decoded, so CJK and spaced names resolve to the name on disk", () => {
+ expect(resolveReplyLink("%E9%B9%88%E9%B9%95.html", WS)).toEqual({
+ kind: "file",
+ path: "鹈鹕.html",
+ });
+ expect(resolveReplyLink("docs/%E6%8A%A5%E5%91%8A%20v2.md", WS)).toEqual({
+ kind: "file",
+ path: "docs/报告 v2.md",
+ });
+ });
+
+ it("a query or hash is ignored for the lookup", () => {
+ expect(resolveReplyLink("report.html?v=2#top", WS)).toEqual({
+ kind: "file",
+ path: "report.html",
+ });
+ expect(resolveReplyLink("report.html#section", WS)).toEqual({
+ kind: "file",
+ path: "report.html",
+ });
+ // Nothing left once the query is gone.
+ expect(resolveReplyLink("?v=2", WS)).toEqual({ kind: "none" });
+ });
+
+ it("a .. that climbs out of the Workspace goes nowhere; one that stays inside pops", () => {
+ expect(resolveReplyLink("../secret.txt", WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink("a/../../b.txt", WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink("%2E%2E/secret.txt", WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink("a/../b.txt", WS)).toEqual({ kind: "file", path: "b.txt" });
+ });
+
+ it("an absolute path counts only inside the Session's Workspace", () => {
+ expect(resolveReplyLink(`${WS}/out/pelican-bike.html`, WS)).toEqual({
+ kind: "file",
+ path: "out/pelican-bike.html",
+ });
+ expect(resolveReplyLink("/etc/hosts", WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink(`${WS}-other/a.txt`, WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink(WS, WS)).toEqual({ kind: "none" });
+ // No Workspace known: an absolute path cannot be placed, a relative one still can.
+ expect(resolveReplyLink(`${WS}/a.txt`, null)).toEqual({ kind: "none" });
+ expect(resolveReplyLink("a.txt", null)).toEqual({ kind: "file", path: "a.txt" });
+ });
+
+ it("a Windows Workspace matches its paths with either separator", () => {
+ const winWs = "C:\\Users\\me\\ws";
+ expect(resolveReplyLink("sub%5Ca.txt", winWs)).toEqual({ kind: "file", path: "sub/a.txt" });
+ expect(resolveReplyLink("./sub/a.txt", winWs)).toEqual({ kind: "file", path: "sub/a.txt" });
+ });
+
+ it("a scheme or a protocol-relative href is external", () => {
+ for (const href of [
+ "https://example.com/pelican-bike.html",
+ "HTTP://EXAMPLE.COM",
+ "mailto:[email protected]",
+ "//cdn.example.com/app.js",
+ ]) {
+ expect(resolveReplyLink(href, WS)).toEqual({ kind: "external" });
+ }
+ });
+
+ it("#id is an in-page anchor, decoded; a bare # goes nowhere", () => {
+ expect(resolveReplyLink("#user-content-fn-1", WS)).toEqual({
+ kind: "anchor",
+ id: "user-content-fn-1",
+ });
+ expect(resolveReplyLink("#%E7%BB%93%E8%AE%BA", WS)).toEqual({ kind: "anchor", id: "结论" });
+ expect(resolveReplyLink("#", WS)).toEqual({ kind: "none" });
+ });
+
+ it("an empty href (the renderer's replacement for an untrusted scheme), ~ paths and bad escapes go nowhere", () => {
+ expect(resolveReplyLink("", WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink(undefined, WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink("~/notes.md", WS)).toEqual({ kind: "none" });
+ expect(resolveReplyLink("%E9%B9", WS)).toEqual({ kind: "none" });
+ });
+});
+
+/** A click event carrying just what the handlers read. */
+function click(currentTarget: unknown = { parentElement: null }) {
+ return {
+ preventDefault: vi.fn(),
+ currentTarget,
+ } as unknown as MouseEvent<HTMLAnchorElement> & { preventDefault: ReturnType<typeof vi.fn> };
+}
+
+describe("replyLinkBehavior", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("a Workspace file opens in the Files panel instead of a new tab", () => {
+ const openFile = vi.fn();
+ const behavior = replyLinkBehavior("./pelican-bike.html", { workspace: WS, openFile });
+ expect(behavior.target).toBeUndefined();
+ expect(behavior.rel).toBeUndefined();
+ const event = click();
+ behavior.onClick!(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(openFile).toHaveBeenCalledExactlyOnceWith("pelican-bike.html");
+ });
+
+ it("a file that may not exist still opens the panel on its path", () => {
+ // No existence check on the way: the panel's own state reports a missing file.
+ const openFile = vi.fn();
+ replyLinkBehavior("missing/nowhere.html", { workspace: WS, openFile }).onClick!(click());
+ expect(openFile).toHaveBeenCalledExactlyOnceWith("missing/nowhere.html");
+ });
+
+ it("an external link keeps the new tab and no click handler", () => {
+ const openFile = vi.fn();
+ const behavior = replyLinkBehavior("https://example.com", { workspace: WS, openFile });
+ expect(behavior).toBe(NEW_TAB);
+ expect(behavior.onClick).toBeUndefined();
+ });
+
+ it("an href with nowhere to go neither navigates nor opens anything", () => {
+ const openFile = vi.fn();
+ for (const href of ["../secret.txt", "/etc/hosts", ""]) {
+ const behavior = replyLinkBehavior(href, { workspace: WS, openFile });
+ expect(behavior.target).toBeUndefined();
+ const event = click();
+ behavior.onClick!(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ }
+ expect(openFile).not.toHaveBeenCalled();
+ });
+
+ it("an anchor scrolls to the nearest element with that id, without navigating", () => {
+ vi.stubGlobal("CSS", { escape: (value: string) => value });
+ const openFile = vi.fn();
+ // Two replies in one transcript, each with its own footnote 1: the one in the clicked
+ // link's reply is the target, not the first in the document.
+ const inReply = { scrollIntoView: vi.fn() };
+ const elsewhere = { scrollIntoView: vi.fn() };
+ const transcript = {
+ parentElement: null,
+ querySelector: (selector: string) => (selector === "#user-content-fn-1" ? elsewhere : null),
+ };
+ const reply = {
+ parentElement: transcript,
+ querySelector: (selector: string) => (selector === "#user-content-fn-1" ? inReply : null),
+ };
+ const paragraph = { parentElement: reply, querySelector: () => null };
+ const behavior = replyLinkBehavior("#user-content-fn-1", { workspace: WS, openFile });
+ expect(behavior.target).toBeUndefined();
+ const event = click({ parentElement: paragraph });
+ behavior.onClick!(event);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(inReply.scrollIntoView).toHaveBeenCalledOnce();
+ expect(elsewhere.scrollIntoView).not.toHaveBeenCalled();
+ expect(openFile).not.toHaveBeenCalled();
+ });
+});