Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(chat): add HTML open-with destinations

vastsa08ace631ba10
diff --git a/apps/desktop/src/components/ContextMenu.tsx b/apps/desktop/src/components/ContextMenu.tsx
index 037322d55..525308405 100644
--- a/apps/desktop/src/components/ContextMenu.tsx
+++ b/apps/desktop/src/components/ContextMenu.tsx
@@ -25,9 +25,11 @@ import {
useState,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
+ type RefObject,
type ReactNode,
} from "react";
import { portalToBody } from "../lib/portal-visibility";
+import { IconChevronRight } from "./icons";
import {
placeContextMenu,
type ContextMenuPlacement,
@@ -35,7 +37,7 @@ import {
} from "../lib/context-menu";
import { texClipboardPayload } from "../lib/selection-tex";
-export type ContextMenuItem = {
+type ContextMenuAction = {
/** Stable identity for React keys and for tests naming a row. */
id: string;
label: string;
@@ -45,7 +47,14 @@ export type ContextMenuItem = {
danger?: boolean;
/** Hairline above this item, splitting the menu into groups. */
separatorBefore?: boolean;
- onSelect: (selection: string) => void;
+ onSelect?: (selection: string) => void;
+};
+
+export type ContextMenuSubmenuItem = ContextMenuAction;
+
+export type ContextMenuItem = ContextMenuAction & {
+ /** A single secondary level; submenus stay within the same menu surface. */
+ submenu?: ContextMenuSubmenuItem[];
};
export type ContextMenuRequest = {
@@ -186,7 +195,17 @@ export function ContextMenu({
onClose: () => void;
}) {
const menuRef = useRef<HTMLDivElement>(null);
+ const submenuRef = useRef<HTMLDivElement>(null);
+ const submenuTriggerRef = useRef<HTMLButtonElement>(null);
const [placement, setPlacement] = useState<ContextMenuPlacement | null>(null);
+ const [openSubmenuId, setOpenSubmenuId] = useState<string | null>(null);
+
+ const closeSubmenu = useCallback(() => setOpenSubmenuId(null), []);
+
+ const setHoveredSubmenu = useCallback((item: ContextMenuItem) => {
+ const next = item.submenu?.length ? item.id : null;
+ setOpenSubmenuId((current) => current === next ? current : next);
+ }, []);
const measure = useCallback(
(request: ContextMenuState) => {
@@ -210,7 +229,10 @@ export function ContextMenu({
// A menu that is not on screen owns no placement; the closed surface is
// unmounted, so the next one starts over from its own measurement.
useEffect(() => {
- if (!state) setPlacement(null);
+ setOpenSubmenuId(null);
+ if (!state) {
+ setPlacement(null);
+ }
}, [state]);
/*
@@ -257,7 +279,10 @@ export function ContextMenu({
*/
const onOutside = (event: Event) => {
const target = event.target as Node | null;
- if (target && menu?.contains(target)) return;
+ if (
+ target &&
+ (menu?.contains(target) || submenuRef.current?.contains(target))
+ ) return;
onClose();
};
const onKeyDown = (event: KeyboardEvent) => {
@@ -265,7 +290,12 @@ export function ContextMenu({
// Stop so a surrounding overlay does not also close on this Escape.
event.preventDefault();
event.stopPropagation();
- onClose();
+ if (openSubmenuId) {
+ closeSubmenu();
+ submenuTriggerRef.current?.focus();
+ } else {
+ onClose();
+ }
};
window.addEventListener("pointerdown", onOutside, true);
window.addEventListener("contextmenu", onOutside, true);
@@ -281,7 +311,7 @@ export function ContextMenu({
window.removeEventListener("blur", onClose);
window.removeEventListener("keydown", onKeyDown, true);
};
- }, [onClose, state]);
+ }, [closeSubmenu, onClose, openSubmenuId, state]);
// Keyboard users land on the first item; Enter then runs it instead of
// re-opening the menu.
@@ -306,7 +336,7 @@ export function ContextMenu({
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
const items = Array.from(
event.currentTarget.querySelectorAll<HTMLButtonElement>(
- '[role="menuitem"]:not(:disabled)',
+ '[data-context-menu-root-item]:not(:disabled)',
),
);
if (!items.length) return;
@@ -341,7 +371,175 @@ export function ContextMenu({
: undefined
}
>
- {state.items.map((item, index) => (
+ {state.items.map((item, index) => {
+ const hasSubmenu = Boolean(item.submenu?.length);
+ const submenuOpen = hasSubmenu && openSubmenuId === item.id;
+ return (
+ <Fragment key={item.id}>
+ {item.separatorBefore && index > 0 ? (
+ <div className="context-menu-separator" role="separator" />
+ ) : null}
+ <button
+ ref={submenuOpen ? submenuTriggerRef : undefined}
+ type="button"
+ role="menuitem"
+ aria-haspopup={hasSubmenu ? "menu" : undefined}
+ aria-expanded={hasSubmenu ? submenuOpen : undefined}
+ className={`context-menu-item${item.danger ? " danger" : ""}${hasSubmenu ? " has-submenu" : ""}`}
+ data-context-menu-root-item
+ data-context-menu-item={item.id}
+ disabled={item.disabled}
+ onMouseEnter={() => setHoveredSubmenu(item)}
+ onKeyDown={(event) => {
+ if (!hasSubmenu || event.key !== "ArrowRight") return;
+ event.preventDefault();
+ event.stopPropagation();
+ setOpenSubmenuId(item.id);
+ requestAnimationFrame(() => {
+ submenuRef.current
+ ?.querySelector<HTMLButtonElement>(
+ '[data-context-menu-submenu-item]:not(:disabled)',
+ )
+ ?.focus();
+ });
+ }}
+ onClick={() => {
+ if (hasSubmenu) {
+ setOpenSubmenuId(item.id);
+ return;
+ }
+ // Close first: an item that opens a dialog must not leave a menu
+ // layered over it.
+ onClose();
+ item.onSelect?.(state.selection);
+ }}
+ >
+ {item.icon ? (
+ <span className="context-menu-icon" aria-hidden>
+ {item.icon}
+ </span>
+ ) : null}
+ <span className="context-menu-label">{item.label}</span>
+ {hasSubmenu ? (
+ <span className="context-menu-submenu-chevron" aria-hidden>
+ <IconChevronRight size={14} />
+ </span>
+ ) : null}
+ </button>
+ {submenuOpen && item.submenu ? (
+ <ContextMenuSubmenu
+ anchorRef={submenuTriggerRef}
+ menuRef={submenuRef}
+ label={item.label}
+ items={item.submenu}
+ selection={state.selection}
+ onClose={onClose}
+ onCloseSubmenu={closeSubmenu}
+ />
+ ) : null}
+ </Fragment>
+ );
+ })}
+ </div>,
+ );
+}
+
+function ContextMenuSubmenu({
+ anchorRef,
+ menuRef,
+ label,
+ items,
+ selection,
+ onClose,
+ onCloseSubmenu,
+}: {
+ anchorRef: RefObject<HTMLButtonElement | null>;
+ menuRef: RefObject<HTMLDivElement | null>;
+ label: string;
+ items: ContextMenuSubmenuItem[];
+ selection: string;
+ onClose: () => void;
+ onCloseSubmenu: () => void;
+}) {
+ const [placement, setPlacement] = useState<ContextMenuPlacement | null>(null);
+
+ const measure = useCallback(() => {
+ const anchor = anchorRef.current?.getBoundingClientRect();
+ const menu = menuRef.current;
+ if (!anchor || !menu) return;
+ const rect = menu.getBoundingClientRect();
+ const margin = 8;
+ const gap = 2;
+ const opensLeft = anchor.right + rect.width > window.innerWidth - margin;
+ const left = opensLeft
+ ? Math.max(margin, anchor.left - rect.width - gap)
+ : anchor.right + gap;
+ const top = Math.min(
+ Math.max(margin, anchor.top),
+ Math.max(margin, window.innerHeight - rect.height - margin),
+ );
+ setPlacement((previous) =>
+ previous && previous.top === top && previous.left === left
+ ? previous
+ : { top, left },
+ );
+ }, [anchorRef, menuRef]);
+
+ useLayoutEffect(() => {
+ measure();
+ }, [measure, items]);
+
+ useEffect(() => {
+ if (typeof ResizeObserver === "undefined") return;
+ const menu = menuRef.current;
+ if (!menu) return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(menu);
+ return () => observer.disconnect();
+ }, [measure, menuRef]);
+
+ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (event.key === "Escape" || event.key === "ArrowLeft") {
+ event.preventDefault();
+ event.stopPropagation();
+ onCloseSubmenu();
+ anchorRef.current?.focus();
+ return;
+ }
+ if (!(["ArrowDown", "ArrowUp", "Home", "End"] as string[]).includes(event.key)) return;
+ const buttons = Array.from(
+ event.currentTarget.querySelectorAll<HTMLButtonElement>(
+ '[data-context-menu-submenu-item]:not(:disabled)',
+ ),
+ );
+ if (!buttons.length) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const current = buttons.indexOf(document.activeElement as HTMLButtonElement);
+ const next = event.key === "Home"
+ ? 0
+ : event.key === "End"
+ ? buttons.length - 1
+ : (current + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length;
+ buttons[next]?.focus();
+ };
+
+ return portalToBody(
+ <div
+ ref={menuRef}
+ className={`context-menu context-menu-submenu${placement ? " is-open" : ""}`}
+ role="menu"
+ aria-label={label}
+ onKeyDown={onMenuKeyDown}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ style={placement
+ ? { top: `${placement.top}px`, left: `${placement.left}px` }
+ : undefined}
+ >
+ {items.map((item, index) => (
<Fragment key={item.id}>
{item.separatorBefore && index > 0 ? (
<div className="context-menu-separator" role="separator" />
@@ -351,12 +549,11 @@ export function ContextMenu({
role="menuitem"
className={`context-menu-item${item.danger ? " danger" : ""}`}
data-context-menu-item={item.id}
+ data-context-menu-submenu-item
disabled={item.disabled}
onClick={() => {
- // Close first: an item that opens a dialog must not leave a menu
- // layered over it.
onClose();
- item.onSelect(state.selection);
+ item.onSelect?.(selection);
}}
>
{item.icon ? (
diff --git a/apps/desktop/src/hooks/use-chat-file-menu.tsx b/apps/desktop/src/hooks/use-chat-file-menu.tsx
index 0e1a167a1..a9d85f5d2 100644
--- a/apps/desktop/src/hooks/use-chat-file-menu.tsx
+++ b/apps/desktop/src/hooks/use-chat-file-menu.tsx
@@ -1,13 +1,10 @@
/**
* The right-click action every file reference in the conversation shares.
*
- * A reference the transcript already recognises as a file — a chip on a turn, an
- * inline code span, a link, a local image — is a file the user can open with one
- * click, so its menu offers the destination a click has no room for: the file's
- * own folder in the system file manager. The reference travels through the same
- * completion a click uses (`useRevealChatFileRef`, ADR 0262/0263), so a
- * reference that resolved to nothing says so instead of revealing a lookalike
- * somewhere else.
+ * HTML references expose explicit open destinations in the context menu: the
+ * bundled File Manager, built-in browser, and default browser. Each destination
+ * goes through the same resolver as a normal click, so a reference that resolves
+ * to nothing cannot open a lookalike somewhere else.
*
* Items are data, exactly as `ContextMenu` takes them: every surface keeps the
* menu instance it already owns and shares only this vocabulary, so a row that
@@ -17,9 +14,19 @@
import { useCallback, type MouseEvent as ReactMouseEvent } from "react";
import { useTranslation } from "react-i18next";
import { useContextMenu, type ContextMenuItem } from "../components/ContextMenu";
-import { IconCopy, IconFolderOpen } from "../components/icons";
+import {
+ IconBrowser,
+ IconCopy,
+ IconExternal,
+ IconFolderOpen,
+ IconGlobe,
+} from "../components/icons";
+import { isHtmlFilePath } from "../lib/chat-links";
import { useChatNativeFilesAllowed } from "./use-chat-session-capability";
-import { useCopyChatFileRef, useRevealChatFileRef } from "./use-preview-target";
+import {
+ useCopyChatFileRef,
+ useOpenChatFileRef,
+} from "./use-preview-target";
export type ChatFileMenuTarget = {
/** The reference as the surface spelled it, before completion. */
@@ -31,21 +38,51 @@ export type ChatFileMenuTarget = {
export function useChatFileMenuItems() {
const { t } = useTranslation();
const nativeFilesAllowed = useChatNativeFilesAllowed();
- const revealFileRef = useRevealChatFileRef();
+ const openFileRef = useOpenChatFileRef();
const copyFileRef = useCopyChatFileRef();
return useCallback(
({ path, baseDir }: ChatFileMenuTarget): ContextMenuItem[] => [
- ...(nativeFilesAllowed ? [{
- id: "reveal-in-folder",
- label: t("chat.revealFileInFolder"),
- icon: <IconFolderOpen size={14} />,
- onSelect: () => revealFileRef(path, baseDir),
- }] : []),
+ ...(nativeFilesAllowed && isHtmlFilePath(path)
+ ? [{
+ id: "open-with",
+ label: t("chat.openWith"),
+ icon: <IconExternal size={14} />,
+ submenu: [
+ {
+ id: "open-with-file-manager",
+ label: t("chat.openWithFileManager"),
+ icon: <IconFolderOpen size={14} />,
+ onSelect: () =>
+ openFileRef(path, baseDir, undefined, {
+ destination: "file-manager",
+ }),
+ },
+ {
+ id: "open-with-built-in-browser",
+ label: t("chat.openWithBuiltInBrowser"),
+ icon: <IconBrowser size={14} />,
+ onSelect: () =>
+ openFileRef(path, baseDir, undefined, {
+ destination: "built-in-browser",
+ }),
+ },
+ {
+ id: "open-with-default-browser",
+ label: t("chat.openWithDefaultBrowser"),
+ icon: <IconGlobe size={14} />,
+ onSelect: () =>
+ openFileRef(path, baseDir, undefined, {
+ destination: "default-browser",
+ }),
+ },
+ ],
+ }]
+ : []),
{
id: "copy-full-path",
label: t("chat.copyFullPath"),
icon: <IconCopy size={14} />,
- separatorBefore: nativeFilesAllowed,
+ separatorBefore: nativeFilesAllowed && isHtmlFilePath(path),
onSelect: () => copyFileRef(path, baseDir, "absolute"),
},
{
@@ -55,7 +92,7 @@ export function useChatFileMenuItems() {
onSelect: () => copyFileRef(path, baseDir, "relative"),
},
],
- [copyFileRef, nativeFilesAllowed, revealFileRef, t],
+ [copyFileRef, nativeFilesAllowed, openFileRef, t],
);
}
diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.ts
index 00b955486..93f613337 100644
--- a/apps/desktop/src/hooks/use-preview-target.ts
+++ b/apps/desktop/src/hooks/use-preview-target.ts
@@ -88,6 +88,17 @@ export type ResolvedChatFileRef = {
scratch: boolean;
};
+export type ChatFileOpenDestination =
+ | "file-manager"
+ | "built-in-browser"
+ | "default-browser";
+
+export type ChatFileOpenOptions = {
+ line?: number;
+ column?: number;
+ destination?: ChatFileOpenDestination;
+};
+
/**
* Load the bundled file view on demand when a user explicitly opens a project
* file. Its enabled state can be off or its runtime can have failed even though
@@ -242,10 +253,11 @@ export function useOpenChatFileRef() {
path: string,
baseDir?: string,
mimeType?: string,
- position?: { line?: number; column?: number },
+ options?: ChatFileOpenOptions,
) => {
- const line = position?.line;
- const column = position?.column;
+ const line = options?.line;
+ const column = options?.column;
+ const destination = options?.destination;
void (async () => {
const resolved = await resolveRef(path, baseDir);
if (!resolved) return;
@@ -256,6 +268,59 @@ export function useOpenChatFileRef() {
) {
return;
}
+ if (destination === "file-manager") {
+ if (current.workspace?.remote) {
+ showToast(t("chat.fileManagerOpenFailed"), { variant: "error" });
+ return;
+ }
+ const ready = await ensureFileManagerView(workspacePath);
+ const latest = useAppStore.getState();
+ if (
+ (latest.workspace?.path ?? null) !== workspacePath ||
+ latest.activeSessionId !== sessionId
+ ) {
+ return;
+ }
+ if (!ready) {
+ showToast(t("chat.fileManagerOpenFailed"), { variant: "error" });
+ return;
+ }
+ openTab(
+ fileManagerPluginTab(
+ resolved.inProject ? resolved.path : resolved.absolutePath,
+ ),
+ );
+ return;
+ }
+ if (destination === "built-in-browser") {
+ if (
+ current.workspace?.remote ||
+ !hasPluginView(current.pluginViews, BROWSER_PLUGIN_TAB)
+ ) {
+ showToast(t("chat.builtInBrowserUnavailable"), {
+ variant: "error",
+ });
+ return;
+ }
+ openUrl(resolved.absolutePath);
+ return;
+ }
+ if (destination === "default-browser") {
+ if (current.workspace?.remote) {
+ showToast(t("chat.defaultBrowserOpenFailed"), {
+ variant: "error",
+ });
+ return;
+ }
+ try {
+ await api.fsOpen(resolved.absolutePath, mimeType, sessionId);
+ } catch {
+ showToast(t("chat.defaultBrowserOpenFailed"), {
+ variant: "error",
+ });
+ }
+ return;
+ }
const hasPosition = line !== undefined || column !== undefined;
if (
!current.workspace?.remote &&
@@ -307,37 +372,6 @@ export function useOpenChatFileRef() {
);
}
-/**
- * Show a file reference in the system file manager.
- *
- * It travels through the same completion and the same address rule a click
- * uses (`useOpenChatFileRef`), so a right-click never reveals a differently
- * named file that happens to sit in the same folder: a reference that matched
- * nothing says so instead.
- */
-export function useRevealChatFileRef() {
- const { t } = useTranslation();
- const resolveRef = useResolveChatFileRef();
- const paneSessionId = useSlotSessionId();
- const sessionId = useAppStore((s) => paneSessionId || s.activeSessionId);
- const showToast = useAppStore((s) => s.showToast);
-
- return useCallback(
- (path: string, baseDir?: string) => {
- void (async () => {
- const resolved = await resolveRef(path, baseDir);
- if (!resolved) return;
- try {
- await api.fsReveal(resolved.path, sessionId);
- } catch {
- showToast(t("chat.fileRevealFailed"), { variant: "error" });
- }
- })();
- },
- [resolveRef, sessionId, showToast, t],
- );
-}
-
/**
* Copy a reference as an address a user can paste somewhere else.
*
diff --git a/apps/desktop/src/styles/ui-kit.css b/apps/desktop/src/styles/ui-kit.css
index 9dadbf076..58f333b14 100644
--- a/apps/desktop/src/styles/ui-kit.css
+++ b/apps/desktop/src/styles/ui-kit.css
@@ -307,6 +307,21 @@
opacity: 0.55;
}
+.context-menu-item.has-submenu {
+ gap: 8px;
+}
+
+.context-menu-submenu-chevron {
+ display: inline-flex;
+ flex: 0 0 auto;
+ margin-left: auto;
+ color: var(--ds-text-muted);
+}
+
+.context-menu-submenu {
+ z-index: 61;
+}
+
.context-menu-item.danger {
color: var(--ds-error);
}
diff --git a/apps/desktop/test/chat-context-menu-surface.test.mjs b/apps/desktop/test/chat-context-menu-surface.test.mjs
index 1df34d56e..cc810e0de 100644
--- a/apps/desktop/test/chat-context-menu-surface.test.mjs
+++ b/apps/desktop/test/chat-context-menu-surface.test.mjs
@@ -33,7 +33,12 @@ test("the pointer-anchored menu portals, measures, and closes without trapping f
assert.match(menuSource, /live\.isCollapsed/);
assert.match(menuSource, /root\.contains\(anchorNode\)/);
assert.match(menuSource, /root\.contains\(focusNode\)/);
- assert.match(menuSource, /item\.onSelect\(state\.selection\)/);
+ assert.match(menuSource, /item\.onSelect\?\.\(state\.selection\)/);
+ assert.match(menuSource, /aria-haspopup=\{hasSubmenu \? "menu" : undefined\}/);
+ assert.match(menuSource, /setOpenSubmenuId\(item\.id\)/);
+ assert.match(menuSource, /event\.key !== "ArrowRight"/);
+ assert.match(menuSource, /event\.key === "ArrowLeft"/);
+ assert.match(menuSource, /role="menu"[\s\S]*aria-label=\{label\}/);
assert.match(menuSource, /if \(!request\.items\.length\) return;/);
});
diff --git a/apps/desktop/test/chat-file-reveal-menu.test.mjs b/apps/desktop/test/chat-file-open-with-menu.test.mjs
similarity index 73%
rename from apps/desktop/test/chat-file-reveal-menu.test.mjs
rename to apps/desktop/test/chat-file-open-with-menu.test.mjs
index 1f9181e54..d0740136d 100644
--- a/apps/desktop/test/chat-file-reveal-menu.test.mjs
+++ b/apps/desktop/test/chat-file-open-with-menu.test.mjs
@@ -1,16 +1,13 @@
/**
* A file the conversation already recognised is a file the user can act on.
*
- * Opening it is one click, so the only destination left for the pointer path is
- * the file's own folder in the system file manager. Every surface that names a
- * file offers it — a turn's chip, an inline code span, a markdown link, a local
- * image — and all of them reveal through the same completion a click uses, so a
- * shorthand that resolved to nothing reports that instead of revealing a
- * lookalike file in another folder (ADR 0262/0263).
+ * HTML references have explicit open destinations in their context menu. Each
+ * destination goes through the same completion as a click, so a shorthand that
+ * resolves to nothing cannot open a different file (ADR 0262/0263).
*
* The destination half is asserted behaviorally: the real hooks run against a
- * recorded store and stubbed host replies, because the contract is the address
- * a reveal hands the host, not the shape of the code that builds it.
+ * recorded store and stubbed host replies, because the contract is the resolved
+ * address handed to each destination, not the shape of the menu.
*/
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
@@ -47,10 +44,10 @@ function loadModule(relative, imports) {
}
const calls = {
- reveals: [],
tabs: [],
files: [],
urls: [],
+ defaultBrowsers: [],
toasts: [],
resolved: [],
menus: [],
@@ -60,7 +57,10 @@ const state = {
sessions: [],
workspace: { path: "C:/project" },
activeSessionId: "session-1",
- pluginViews: [{ pluginId: "pi.file-manager", viewId: "manager" }],
+ pluginViews: [
+ { pluginId: "pi.file-manager", viewId: "manager" },
+ { pluginId: "pi.browser", viewId: "browser" },
+ ],
openFileInWorkPanel: (...args) => calls.files.push(args),
openUrlInWorkPanel: (...args) => calls.urls.push(args),
openWorkPanelTab: (tab) => calls.tabs.push(tab),
@@ -75,9 +75,6 @@ const useAppStore = Object.assign(
);
let nextMatch = null;
-let revealFails = false;
-
-
let clipboardFails = false;
const copied = [];
@@ -112,14 +109,12 @@ const previewTarget = loadModule("../src/hooks/use-preview-target.ts", {
"../lib/api": {
api: {
listPluginViews: async () => state.pluginViews,
+ fsOpen: async (path, mimeType, sessionId) =>
+ calls.defaultBrowsers.push([path, mimeType, sessionId]),
fsResolveRef: async (ref) => {
calls.resolved.push(ref);
return { match: nextMatch };
},
- fsReveal: async (path) => {
- if (revealFails) throw new Error("host refused to reveal");
- calls.reveals.push(path);
- },
},
},
"../lib/chat-links": loadModule("../src/lib/chat-links.ts", {
@@ -145,7 +140,16 @@ const { useChatFileMenu, useChatFileMenuItems } = loadModule(
react: React,
"react/jsx-runtime": jsxRuntime,
"react-i18next": { useTranslation: translate },
- "../components/icons": { IconCopy: () => null, IconFolderOpen: () => null },
+ "../components/icons": {
+ IconBrowser: () => null,
+ IconCopy: () => null,
+ IconExternal: () => null,
+ IconFolderOpen: () => null,
+ IconGlobe: () => null,
+ },
+ "../lib/chat-links": {
+ isHtmlFilePath: (path) => /\.html?$/i.test(path),
+ },
"../components/ContextMenu": {
useContextMenu: () => ({
contextMenu: null,
@@ -163,7 +167,6 @@ const flush = () => new Promise((resolve) => setImmediate(resolve));
function reset(match) {
Object.values(calls).forEach((list) => list.splice(0, list.length));
nextMatch = match;
- revealFails = false;
clipboardFails = false;
}
@@ -184,101 +187,97 @@ function projectMatch(overrides = {}) {
* right-click would have offered. Both run inside a render, so no side effect
* fires while React is rendering.
*/
-async function clickAndReveal(path) {
+async function openWithDestination(path, destination) {
let open = null;
- let items = null;
function Harness() {
open = previewTarget.useOpenChatFileRef();
- items = useChatFileMenuItems()({ path });
return null;
}
renderToStaticMarkup(React.createElement(Harness));
assert.equal(typeof open, "function", "the hook returned a click handler");
- const item = items.find((entry) => entry.id === "reveal-in-folder");
- assert.ok(item, "every file reference offers its folder");
- open(path);
- await flush();
- item.onSelect("");
+ open(path, undefined, undefined, { destination });
await flush();
}
-test("a project file is revealed at the address the click opens", async () => {
+test("the HTML menu exposes three open destinations as one submenu", () => {
reset(projectMatch());
- await clickAndReveal("src/dir/a.ts");
- // Completion ran for both actions, so neither can act on a different file.
- assert.deepEqual(calls.resolved, ["src/dir/a.ts", "src/dir/a.ts"]);
- assert.equal(calls.tabs[0].location, "src/dir/a.ts");
- assert.deepEqual(calls.reveals, ["src/dir/a.ts"]);
- assert.deepEqual(calls.toasts, []);
+ let openFileMenu = null;
+ function Harness() {
+ openFileMenu = useChatFileMenu().openFileMenu;
+ return null;
+ }
+ renderToStaticMarkup(React.createElement(Harness));
+ openFileMenu({}, { path: "src/dir/a.html" });
+ const menu = calls.menus[0].items;
+ assert.deepEqual(menu.map((item) => item.id), [
+ "open-with",
+ "copy-full-path",
+ "copy-relative-path",
+ ]);
+ assert.equal(menu[0].label, "chat.openWith:");
+ assert.deepEqual(
+ menu[0].submenu.map((item) => [item.id, item.label]),
+ [
+ ["open-with-file-manager", "chat.openWithFileManager:"],
+ ["open-with-built-in-browser", "chat.openWithBuiltInBrowser:"],
+ ["open-with-default-browser", "chat.openWithDefaultBrowser:"],
+ ],
+ );
+ assert.equal(menu.some((item) => item.id === "reveal-in-folder"), false);
});
-test("a sibling folder file is revealed by absolute path, as it is opened", async () => {
- reset(
- projectMatch({
- relativePath: "lib/only-here.ts",
- absolutePath: "C:/project-second/lib/only-here.ts",
- projectRoot: { primary: false },
- }),
- );
- await clickAndReveal("lib/only-here.ts");
- assert.equal(calls.tabs[0].location, "C:/project-second/lib/only-here.ts");
- assert.deepEqual(calls.reveals, ["C:/project-second/lib/only-here.ts"]);
+test("non-HTML references keep copy actions without an open-with submenu", () => {
+ reset(projectMatch());
+ let openFileMenu = null;
+ function Harness() {
+ openFileMenu = useChatFileMenu().openFileMenu;
+ return null;
+ }
+ renderToStaticMarkup(React.createElement(Harness));
+ openFileMenu({}, { path: "src/dir/a.ts" });
+ assert.deepEqual(calls.menus[0].items.map((item) => item.id), [
+ "copy-full-path",
+ "copy-relative-path",
+ ]);
});
-test("a scratch or attachment file is revealed by absolute path", async () => {
+test("the File Manager opens the resolved project or scratch path", async () => {
+ reset(projectMatch({ relativePath: "page.html", absolutePath: "C:/project/page.html" }));
+ await openWithDestination("page.html", "file-manager");
+ assert.deepEqual(calls.resolved, ["page.html"]);
+ assert.equal(calls.tabs[0].location, "page.html");
+
reset({
root: "scratch",
- relativePath: "notes.md",
- absolutePath: "C:/data/scratch/session-1/notes.md",
+ relativePath: "page.html",
+ absolutePath: "C:/data/scratch/session-1/page.html",
matchedBy: "exact-relative",
});
- await clickAndReveal("notes.md");
- assert.equal(calls.files[0][0], "C:/data/scratch/session-1/notes.md");
- assert.deepEqual(calls.reveals, ["C:/data/scratch/session-1/notes.md"]);
+ await openWithDestination("page.html", "file-manager");
+ assert.equal(calls.tabs[0].location, "C:/data/scratch/session-1/page.html");
});
-test("a reference nothing answers reports itself and reveals nothing", async () => {
- reset(null);
- await clickAndReveal("missing-helper.js");
- assert.deepEqual(calls.reveals, []);
- assert.deepEqual(calls.files, []);
- assert.deepEqual(calls.tabs, []);
- assert.deepEqual(
- calls.toasts.map(([message]) => message),
- ["chat.fileRefMissing:missing-helper.js", "chat.fileRefMissing:missing-helper.js"],
- );
-});
+test("HTML can open in the embedded or default browser at its resolved address", async () => {
+ reset(projectMatch({ relativePath: "page.html", absolutePath: "C:/project/page.html" }));
+ await openWithDestination("page.html", "built-in-browser");
+ assert.deepEqual(calls.urls, [["C:/project/page.html"]]);
-test("a refused reveal is reported instead of failing silently", async () => {
- reset(projectMatch());
- revealFails = true;
- await clickAndReveal("src/dir/a.ts");
- assert.deepEqual(calls.reveals, []);
- assert.deepEqual(
- calls.toasts.map(([message]) => message),
- ["chat.fileRevealFailed:"],
- );
+ await openWithDestination("page.html", "default-browser");
+ assert.deepEqual(calls.defaultBrowsers, [
+ ["C:/project/page.html", undefined, "session-1"],
+ ]);
});
-test("the menu a reference opens carries the reveal and both copies", () => {
- reset(projectMatch());
- let openFileMenu = null;
- function Harness() {
- openFileMenu = useChatFileMenu().openFileMenu;
- return null;
- }
- renderToStaticMarkup(React.createElement(Harness));
- openFileMenu({}, { path: "src/dir/a.ts" });
- assert.deepEqual(
- calls.menus.map((menu) => menu.items.map((item) => [item.id, item.label])),
- [
- [
- ["reveal-in-folder", "chat.revealFileInFolder:"],
- ["copy-full-path", "chat.copyFullPath:"],
- ["copy-relative-path", "chat.copyRelativePath:"],
- ],
- ],
- );
+test("an unresolved HTML reference is reported and opened nowhere", async () => {
+ reset(null);
+ await openWithDestination("missing.html", "built-in-browser");
+ assert.deepEqual(calls.tabs, []);
+ assert.deepEqual(calls.files, []);
+ assert.deepEqual(calls.urls, []);
+ assert.deepEqual(calls.defaultBrowsers, []);
+ assert.deepEqual(calls.toasts.map(([message]) => message), [
+ "chat.fileRefMissing:missing.html",
+ ]);
});
/** Run one copy item of the reference menu on the reference it names. */
@@ -406,35 +405,39 @@ test("every transcript surface that names a file opens that item", () => {
);
});
-test("a URL never reaches the reveal", () => {
+test("HTTP URLs keep their own menu instead of the file open submenu", () => {
const menu = read("../src/hooks/use-chat-file-menu.tsx");
- // The item is file-only by construction: it is built where the reference is a
- // path, and an HTTP link keeps its own external/work-panel/copy menu.
- assert.match(menu, /useRevealChatFileRef\(\)/);
- assert.doesNotMatch(menu, /openHttpUrl|browserOpenExternal/);
- // An HTTP link is not a file on disk, so it never grows this item; it keeps
- // the menu it already has.
+ // The submenu only recognizes HTML paths, and an HTTP link keeps its own
+ // external/work-panel/copy menu.
+ assert.match(menu, /isHtmlFilePath\(path\)/);
+ assert.doesNotMatch(menu, /useRevealChatFileRef|reveal-in-folder/);
assert.ok(markdown.includes('if (!/^https?:\\/\\//i.test(href)) {'));
});
test("the reference labels ship in the catalogs the menu reads", () => {
const en = read("../../../packages/i18n/src/locales/en/index.ts");
const zhCN = read("../../../packages/i18n/src/locales/zh-CN/index.ts");
- assert.match(en, /revealFileInFolder: "Show in folder"/);
- assert.match(en, /fileRevealFailed: "Could not show the file in its folder\."/);
+ assert.match(en, /openWith: "Open with"/);
+ assert.match(en, /openWithFileManager: "File Manager"/);
+ assert.match(en, /openWithBuiltInBrowser: "Built-in browser"/);
+ assert.match(en, /openWithDefaultBrowser: "Default browser"/);
+ assert.match(en, /defaultBrowserOpenFailed:/);
assert.match(en, /copyFullPath: "Copy full path"/);
assert.match(en, /copyRelativePath: "Copy relative path"/);
- assert.match(zhCN, /revealFileInFolder: "在文件夹中显示"/);
- assert.match(zhCN, /fileRevealFailed: "无法在文件夹中打开该文件。"/);
+ assert.match(zhCN, /openWith: "打开方式"/);
+ assert.match(zhCN, /openWithFileManager: "文件管理器"/);
+ assert.match(zhCN, /openWithBuiltInBrowser: "内置浏览器"/);
+ assert.match(zhCN, /openWithDefaultBrowser: "默认浏览器"/);
+ assert.match(zhCN, /defaultBrowserOpenFailed:/);
assert.match(zhCN, /copyFullPath: "复制完整地址"/);
assert.match(zhCN, /copyRelativePath: "复制相对地址"/);
});
-test("remote workspace references retain copy actions but never offer local OS reveal", () => {
+test("remote workspace references retain copy actions but never offer local open actions", () => {
const before = state.sessions;
state.sessions = [{ id: state.activeSessionId, remoteWorkspace: { hostKey: "ssh", path: "/work/app" } }];
let items;
- function Harness() { items = useChatFileMenuItems()({ path: "README.md" }); return null; }
+ function Harness() { items = useChatFileMenuItems()({ path: "index.html" }); return null; }
renderToStaticMarkup(React.createElement(Harness));
assert.deepEqual(items.map(item => item.id), ["copy-full-path", "copy-relative-path"]);
state.sessions = before;
diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjs
index c9e551f50..3cff0bce9 100644
--- a/apps/desktop/test/transcript-file-chips.test.mjs
+++ b/apps/desktop/test/transcript-file-chips.test.mjs
@@ -82,9 +82,23 @@ test("a file chip is routed by where the reference resolved, never optimisticall
// roots, and positioned references need the host viewer's line navigation.
assert.match(hook, /inProject: false/);
assert.match(hook, /openFile\(resolved\.path, mimeType, \{ line, column \}\)/);
- // The OS handoff is no longer what a chat click does; the channel itself
- // stays part of the public IPC surface.
- assert.doesNotMatch(hook, /api\.fsOpen\(/);
+ // Only the explicit default-browser destination may request the OS handoff;
+ // an ordinary transcript click keeps its resolved in-app destination.
+ const defaultBrowserIndex = hook.indexOf(
+ 'if (destination === "default-browser")',
+ );
+ const defaultBrowserBranch = hook.slice(
+ defaultBrowserIndex,
+ hook.indexOf("const hasPosition", defaultBrowserIndex),
+ );
+ assert.match(
+ defaultBrowserBranch,
+ /await api\.fsOpen\(resolved\.absolutePath, mimeType, sessionId\)/,
+ );
+ assert.doesNotMatch(
+ hook.slice(0, defaultBrowserIndex),
+ /api\.fsOpen\(/,
+ );
assert.match(
api,
/fsOpen: \(path: string, mimeType\?: string, sessionId\?: string\) =>\s*invoke\(IPC\.invoke\.fsOpen, \{ path, mimeType, \.\.\.\(sessionId \? \{ sessionId \} : \{\}\) \}\)/,
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 3c6921c27..9379776e1 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3551,13 +3551,13 @@ Anatomy:
primary-folder file is addressed to the view as a project-relative path and a
sibling-folder file as an absolute one, which is also how scratch and
attachment files are addressed. A reference that matches no file opens nothing
- and reports itself, as does right-clicking it: the file-reference menu offers
- that file's own folder in the system file manager and copies its full path or
- its project-relative path. The same items are offered on a sent `@path` chip,
- an inline code span, a markdown link, a local image, a tool row's file path,
- and a path in a tool result's file or match list, through the same completion
- and the same address; a file outside the project has no relative path to copy
- and says so instead.
+ and reports itself. Right-clicking a transcript file reference offers Copy
+ full path and Copy relative path on every surface that names it. Unpositioned
+ `.html` and `.htm` references also offer an **Open with** submenu containing
+ File Manager, built-in browser, and default browser. Each choice completes the
+ reference first and opens that exact resolved file. Other file types keep the
+ copy actions only; the transcript menu has no **Show in folder** action. A
+ file outside the project has no relative path to copy and reports that fact.
The OS default application is no longer what this click does. HTTP(S)
URLs stay text links. Plain clicks follow the Link open destination setting,
and right-clicking a URL exposes the same external, work-panel, and copy
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index b9926b327..12da70af2 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -1390,16 +1390,14 @@ Project drag/drop follows these patterns:
the work panel follows the folder that answered: a file of the primary folder
travels as a project-relative path, a file of a sibling folder of the same
project as an absolute one, exactly as a scratch or attachment file does. A
- chip whose reference matches nothing opens nothing and reports itself, and so
- does a right-click on it: the file-reference menu — offered on every
- reference the transcript renders, a sent `@path` chip, an inline code span, a
- local link, a local image, a tool row's own file path, a path in a tool
- result's file or match list, and an image attachment's thumbnail — shows the
- file in the system file manager through that same completion and that same
- address, and copies that file's full path or its project-relative path. A file
- outside the project has no relative path to copy and says so. The OS default
- application is no longer what this click does, though that action stays
- reachable from the file view's own context menu.
+ chip whose reference matches nothing opens nothing and reports itself. Right-
+ clicking a transcript file reference offers Copy full path and Copy relative
+ path on every surface that names it. Unpositioned `.html` and `.htm`
+ references also offer an **Open with** submenu containing File Manager,
+ built-in browser, and default browser. Each choice completes the reference
+ first and opens that exact resolved file. Other file types keep the copy
+ actions only; the transcript menu has no **Show in folder** action. A file
+ outside the project has no relative path to copy and reports that fact.
- In the host `file:` tab, a conversation MP4 that cannot be previewed because
it is binary or exceeds the text preview limit offers **Open with default
application**. This applies to named `.mp4` files and extensionless
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 89654cfdd..6eb3a6169 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13292,7 +13292,8 @@ are withdrawn with ADR 0165.
canonical path. Quoted and scratch-absolute paths are included.
- A chip plus a short prompt keeps the user plate content-sized; it does
not stretch to the `min(82%, 600px)` ceiling.
- - Clicking the HTML chip opens the work-panel browser on that file.
+ - Clicking an unpositioned project or scratch HTML chip opens the work-panel
+ browser on that file.
- Clicking the workspace source chip opens it in the File Manager work-panel
view on that file; the host `file:` tab and the OS default application are
no longer what a chip click opens.
@@ -13391,8 +13392,9 @@ are withdrawn with ADR 0165.
#### E2E-CHAT-file-ref-opens-the-surface-that-owns-it
- **Preconditions**: The bundled File Manager plugin is loaded and enabled and
- the work panel is closed. The open session's scratch store holds one file and
- the attachment store one blob. The project is a group whose primary folder
+ the work panel is closed. The open session's scratch store holds one HTML
+ file and one other file, and the attachment store holds one blob. The project
+ is a group whose primary folder
contains an `.html` page and a text file, and whose second folder holds a text
file of its own. The same session's transcript carries a `Read` row whose
summary names a project file, a `Glob` result listing project paths, and a
@@ -13401,7 +13403,8 @@ are withdrawn with ADR 0165.
unsaved edit into that view and click the same reference again. 3) Click a
reference that resolves into the session scratch store, then the
`attachments/<sha256>` reference. 4) Click a workspace `.html` reference in an
- assistant reply and the same reference as a sent user chip. 5) Click the file
+ assistant reply and the same reference as a sent user chip; click the scratch
+ HTML reference too. 5) Click the file
path in the tool row's summary, then a path in the `Glob` result's file list
and a path heading of the `Grep` result. 6) Disable the File Manager plugin,
then click a project file reference and the tool row summary. 7) Click a
@@ -13409,16 +13412,18 @@ are withdrawn with ADR 0165.
in its primary folder. 8) Right-click the sent `@path` chip, the inline-code
reference, the markdown link, the local image, a tool row's file path, a tool
result's file list, and an attachment image chip; then right-click a reference
- that matches nothing. 9) On that chip, use Copy full path and Copy relative
- path, then do the same on a reference that resolves in the session scratch
- store.
+ that matches nothing. On an HTML reference, open the Open with submenu and
+ choose File Manager, built-in browser, and default browser; repeat for the
+ scratch HTML file. 9) Use Copy full path and Copy relative path, then do the
+ same on a reference that resolves in the session scratch store.
- **Expected**:
- - Right-clicking a file reference opens the renderer's own menu with the
- file's own folder (Show in folder) and both of its addresses (Copy full
- path, Copy relative path). The inline-code reference, the file link, the
- local image, a tool row's path, a tool result's file or match list, and an
- attachment image chip offer the same items, and a reference that matches
- nothing reports itself instead of revealing a same-named file elsewhere.
+ - Right-clicking a file reference offers Copy full path and Copy relative
+ path on each transcript surface that names it. The transcript menu has no
+ Show in folder item. An unpositioned HTML reference also has a second-level
+ Open with submenu for File Manager, built-in browser, and default browser;
+ non-HTML references keep only the copy actions. Each open choice resolves
+ the reference first, and a missing reference reports itself without opening
+ a same-named file elsewhere.
- A copy writes exactly what it names: the absolute address for the full copy
and the project-relative spelling for the relative one; a scratch or
attachment file reports that it has no relative path instead of copying an
@@ -13430,11 +13435,12 @@ are withdrawn with ADR 0165.
is still in the editor and no second tab appears.
- A scratch or attachment file opens in the host `file:` tab under Open
resources, addressed by its absolute path, never in the File Manager view.
- - A `.html` / `.htm` page of the project's primary folder opens in the
- work-panel side browser, from the assistant reply and the user chip alike; a
- page in a sibling folder is a project file like any other and opens in the
- File Manager view, because the side browser is rooted at the primary folder
- (ADR 0263).
+ - A plain click on an unpositioned `.html` / `.htm` reference from any
+ project folder or session scratch opens it in the work-panel side browser.
+ In the Open with submenu, File Manager opens the resolved file in that
+ plugin view, built-in browser opens the same absolute path in the side
+ browser, and default browser uses the host's validated OS file-open path.
+ A positioned HTML reference keeps its line-aware host file tab behavior.
- A tool surface reaches the destination of the file it names, not one of its
own: the tool row's summary path and the paths of the `Glob` file list and
the `Grep` path headings open the same project file in the File Manager view.
@@ -13456,12 +13462,15 @@ are withdrawn with ADR 0165.
- **Acceptance**: C (conversation & stream), G (plugins), Quality
- **Milestone**: M5
- **Status**: Unit-covered
- (`apps/desktop/test/transcript-file-chips.test.mjs` for the wiring and
- `apps/desktop/test/tool-row-file-refs.test.mjs` for the work-panel entry each
- shape of resolution produces). The isolated Electron renderer journey in
+ (`apps/desktop/test/chat-file-open-with-menu.test.mjs` for menu destinations
+ and resolved-path routing, `apps/desktop/test/transcript-file-chips.test.mjs`
+ for the wiring, and `apps/desktop/test/tool-row-file-refs.test.mjs` for the
+ work-panel entry each shape of resolution produces). The isolated Electron renderer journey in
`scripts/e2e-file-ref-line-scroll.mjs` verifies a Markdown link enables the
File Manager on demand and a positioned reference still opens in the host
- viewer; the full packaged UI journey remains Draft.
+ viewer. `pnpm test:e2e:transcript` also exercises the rendered second-level
+ menu, destination selection, and keyboard focus return; the full
+ file-reference journey through all three destinations remains Draft.
#### E2E-CHAT-mp4-attachment-opens-in-system-player
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index aa4de1102..61f6382d1 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -435,8 +435,13 @@ export const de = {
"fileRefRestricted": "{{name}} liegt außerhalb der für die App zugänglichen Orte",
"fileRefLookupFailed": "Dieser Dateiverweis konnte nicht geprüft werden.",
"fileManagerUnavailable": "Der Dateimanager ist nicht verfügbar. Die Datei wurde im integrierten Viewer geöffnet.",
- "revealFileInFolder": "Im Ordner anzeigen",
- "fileRevealFailed": "Die Datei konnte nicht im Ordner angezeigt werden.",
+ "openWith": "Öffnen mit",
+ "openWithFileManager": "Dateimanager",
+ "openWithBuiltInBrowser": "Integrierter Browser",
+ "openWithDefaultBrowser": "Standardbrowser",
+ "fileManagerOpenFailed": "Die Datei konnte nicht im Dateimanager geöffnet werden.",
+ "builtInBrowserUnavailable": "Der integrierte Browser ist nicht verfügbar.",
+ "defaultBrowserOpenFailed": "Die Datei konnte nicht im Standardbrowser geöffnet werden.",
"copyFullPath": "Vollständigen Pfad kopieren",
"copyRelativePath": "Relativen Pfad kopieren",
"relativePathUnavailable": "Die Datei liegt außerhalb des Projekts und hat keinen relativen Pfad",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 55c1408ec..2419f3eec 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -450,8 +450,13 @@ export const en = {
fileRefRestricted: "{{name}} is outside the locations this app can access",
fileRefLookupFailed: "Could not check this file reference.",
fileManagerUnavailable: "The File Manager is unavailable. The file was opened in the built-in viewer.",
- revealFileInFolder: "Show in folder",
- fileRevealFailed: "Could not show the file in its folder.",
+ openWith: "Open with",
+ openWithFileManager: "File Manager",
+ openWithBuiltInBrowser: "Built-in browser",
+ openWithDefaultBrowser: "Default browser",
+ fileManagerOpenFailed: "Could not open the file in File Manager.",
+ builtInBrowserUnavailable: "The built-in browser is unavailable.",
+ defaultBrowserOpenFailed: "Could not open the file in the default browser.",
copyFullPath: "Copy full path",
copyRelativePath: "Copy relative path",
relativePathUnavailable: "That file is outside the project, so it has no relative path",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 8bc1900b5..f6b434484 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -435,8 +435,13 @@ export const es = {
"fileRefRestricted": "{{name}} está fuera de las ubicaciones a las que puede acceder la aplicación",
"fileRefLookupFailed": "No se pudo comprobar esta referencia de archivo.",
"fileManagerUnavailable": "El administrador de archivos no está disponible. El archivo se abrió en el visor integrado.",
- "revealFileInFolder": "Mostrar en carpeta",
- "fileRevealFailed": "No se pudo mostrar el archivo en su carpeta.",
+ "openWith": "Abrir con",
+ "openWithFileManager": "Administrador de archivos",
+ "openWithBuiltInBrowser": "Navegador integrado",
+ "openWithDefaultBrowser": "Navegador predeterminado",
+ "fileManagerOpenFailed": "No se pudo abrir el archivo en el administrador de archivos.",
+ "builtInBrowserUnavailable": "El navegador integrado no está disponible.",
+ "defaultBrowserOpenFailed": "No se pudo abrir el archivo en el navegador predeterminado.",
"copyFullPath": "Copiar ruta completa",
"copyRelativePath": "Copiar ruta relativa",
"relativePathUnavailable": "El archivo está fuera del proyecto y no tiene ruta relativa",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 260b9e294..248d861ad 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -435,8 +435,13 @@ export const fr = {
"fileRefRestricted": "{{name}} se trouve hors des emplacements accessibles à l'application",
"fileRefLookupFailed": "Impossible de vérifier cette référence de fichier.",
"fileManagerUnavailable": "Le gestionnaire de fichiers est indisponible. Le fichier a été ouvert dans le lecteur intégré.",
- "revealFileInFolder": "Afficher dans le dossier",
- "fileRevealFailed": "Impossible d'afficher le fichier dans son dossier.",
+ "openWith": "Ouvrir avec",
+ "openWithFileManager": "Gestionnaire de fichiers",
+ "openWithBuiltInBrowser": "Navigateur intégré",
+ "openWithDefaultBrowser": "Navigateur par défaut",
+ "fileManagerOpenFailed": "Impossible d'ouvrir le fichier dans le gestionnaire de fichiers.",
+ "builtInBrowserUnavailable": "Le navigateur intégré est indisponible.",
+ "defaultBrowserOpenFailed": "Impossible d'ouvrir le fichier dans le navigateur par défaut.",
"copyFullPath": "Copier le chemin complet",
"copyRelativePath": "Copier le chemin relatif",
"relativePathUnavailable": "Ce fichier est hors du projet et n'a pas de chemin relatif",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 1eb6ffa5f..9fdf3b7b0 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -447,8 +447,13 @@ export const ko = {
fileRefRestricted: "{{name}}은(는) 앱이 접근할 수 있는 위치 밖에 있습니다",
fileRefLookupFailed: "이 파일 참조를 확인할 수 없습니다.",
fileManagerUnavailable: "파일 관리자를 사용할 수 없어 내장 파일 보기에서 열었습니다.",
- revealFileInFolder: "폴더에서 보기",
- fileRevealFailed: "폴더에서 파일을 표시할 수 없습니다.",
+ openWith: "다음으로 열기",
+ openWithFileManager: "파일 관리자",
+ openWithBuiltInBrowser: "내장 브라우저",
+ openWithDefaultBrowser: "기본 브라우저",
+ fileManagerOpenFailed: "파일 관리자에서 파일을 열 수 없습니다.",
+ builtInBrowserUnavailable: "내장 브라우저를 사용할 수 없습니다.",
+ defaultBrowserOpenFailed: "기본 브라우저에서 파일을 열 수 없습니다.",
copyFullPath: "전체 경로 복사",
copyRelativePath: "상대 경로 복사",
relativePathUnavailable: "이 파일은 프로젝트 밖에 있어 상대 경로가 없습니다",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 989024b44..ace318154 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -437,8 +437,13 @@ export const ptBR = {
fileRefRestricted: "{{name}} está fora dos locais que o aplicativo pode acessar",
fileRefLookupFailed: "Não foi possível verificar esta referência de arquivo.",
fileManagerUnavailable: "O gerenciador de arquivos está indisponível. O arquivo foi aberto no visualizador integrado.",
- revealFileInFolder: "Mostrar na pasta",
- fileRevealFailed: "Não foi possível mostrar o arquivo na pasta.",
+ openWith: "Abrir com",
+ openWithFileManager: "Gerenciador de arquivos",
+ openWithBuiltInBrowser: "Navegador integrado",
+ openWithDefaultBrowser: "Navegador padrão",
+ fileManagerOpenFailed: "Não foi possível abrir o arquivo no gerenciador de arquivos.",
+ builtInBrowserUnavailable: "O navegador integrado está indisponível.",
+ defaultBrowserOpenFailed: "Não foi possível abrir o arquivo no navegador padrão.",
copyFullPath: "Copiar caminho completo",
copyRelativePath: "Copiar caminho relativo",
relativePathUnavailable: "O arquivo está fora do projeto e não tem caminho relativo",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 8d75d07f5..14c60e47c 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -447,8 +447,13 @@ export const tr = {
fileRefRestricted: "{{name}} uygulamanın erişebildiği konumların dışında",
fileRefLookupFailed: "Bu dosya başvurusu denetlenemedi.",
fileManagerUnavailable: "Dosya yöneticisi kullanılamıyor. Dosya yerleşik görüntüleyicide açıldı.",
- revealFileInFolder: "Klasörde göster",
- fileRevealFailed: "Dosya klasörde gösterilemedi.",
+ openWith: "Birlikte aç",
+ openWithFileManager: "Dosya yöneticisi",
+ openWithBuiltInBrowser: "Yerleşik tarayıcı",
+ openWithDefaultBrowser: "Varsayılan tarayıcı",
+ fileManagerOpenFailed: "Dosya, dosya yöneticisinde açılamadı.",
+ builtInBrowserUnavailable: "Yerleşik tarayıcı kullanılamıyor.",
+ defaultBrowserOpenFailed: "Dosya varsayılan tarayıcıda açılamadı.",
copyFullPath: "Tam yolu kopyala",
copyRelativePath: "Göreli yolu kopyala",
relativePathUnavailable: "Dosya proje dışında olduğu için göreli yolu yok",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 82a68cb94..809a8550f 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -440,8 +440,13 @@ export const zhCN = {
fileRefRestricted: "{{name}} 不在应用允许访问的范围内",
fileRefLookupFailed: "无法检查此文件引用。",
fileManagerUnavailable: "文件管理器当前不可用,已在内置文件查看器中打开。",
- revealFileInFolder: "在文件夹中显示",
- fileRevealFailed: "无法在文件夹中打开该文件。",
+ openWith: "打开方式",
+ openWithFileManager: "文件管理器",
+ openWithBuiltInBrowser: "内置浏览器",
+ openWithDefaultBrowser: "默认浏览器",
+ fileManagerOpenFailed: "无法在文件管理器中打开此文件。",
+ builtInBrowserUnavailable: "内置浏览器当前不可用。",
+ defaultBrowserOpenFailed: "无法在默认浏览器中打开此文件。",
copyFullPath: "复制完整地址",
copyRelativePath: "复制相对地址",
relativePathUnavailable: "该文件不在项目内,没有相对地址",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 554d1b128..c85d8ff97 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -440,8 +440,13 @@ export const zhTW = {
fileRefRestricted: "{{name}} 不在應用程式允許存取的範圍內",
fileRefLookupFailed: "無法檢查此檔案參照。",
fileManagerUnavailable: "檔案管理器目前無法使用,已在內建檔案檢視器中開啟。",
- revealFileInFolder: "在資料夾中顯示",
- fileRevealFailed: "無法在資料夾中開啟該檔案。",
+ openWith: "開啟方式",
+ openWithFileManager: "檔案管理器",
+ openWithBuiltInBrowser: "內建瀏覽器",
+ openWithDefaultBrowser: "預設瀏覽器",
+ fileManagerOpenFailed: "無法在檔案管理器中開啟此檔案。",
+ builtInBrowserUnavailable: "內建瀏覽器目前無法使用。",
+ defaultBrowserOpenFailed: "無法在預設瀏覽器中開啟此檔案。",
copyFullPath: "複製完整位址",
copyRelativePath: "複製相對位址",
relativePathUnavailable: "該檔案不在專案內,沒有相對位址",
diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsx
index afb2f1031..af9a818c9 100644
--- a/scripts/e2e/transcript-render.tsx
+++ b/scripts/e2e/transcript-render.tsx
@@ -8,7 +8,15 @@ import { useState } from "react";
import { createInstance } from "i18next";
import { I18nextProvider } from "react-i18next";
import { en } from "@pi-desktop/i18n";
-import type { AgentActivity, AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
+import type {
+ AgentActivity,
+ AgentEventEnvelope,
+ UiMessage,
+} from "@pi-desktop/shared";
+import {
+ ContextMenu,
+ useContextMenu,
+} from "../../apps/desktop/src/components/ContextMenu";
import { Markdown } from "../../apps/desktop/src/components/Markdown";
import { AssistantTurn } from "../../apps/desktop/src/features/chat/transcript/AssistantTurn";
import { ChatTranscript } from "../../apps/desktop/src/features/chat/transcript/ChatTranscript";
@@ -126,6 +134,142 @@ async function markdownLinkInteractionProbe(
}
}
+async function contextMenuSubmenuInteractionProbe() {
+ const host = document.createElement("div");
+ host.style.cssText = "position:fixed;top:24px;left:24px";
+ document.body.append(host);
+ const root = createRoot(host);
+ const selections: string[] = [];
+ const items = [
+ {
+ id: "open-with",
+ label: "Open with",
+ submenu: [
+ {
+ id: "file-manager",
+ label: "File Manager",
+ onSelect: () => selections.push("file-manager"),
+ },
+ {
+ id: "built-in-browser",
+ label: "Built-in browser",
+ onSelect: () => selections.push("built-in-browser"),
+ },
+ {
+ id: "default-browser",
+ label: "Default browser",
+ onSelect: () => selections.push("default-browser"),
+ },
+ ],
+ },
+ ];
+
+ function Fixture() {
+ const { contextMenu, openContextMenu, closeContextMenu } = useContextMenu();
+ return (
+ <>
+ <button
+ type="button"
+ data-testid="html-file-reference"
+ onContextMenu={(event) => openContextMenu(event, { items })}
+ >
+ page.html
+ </button>
+ <ContextMenu state={contextMenu} onClose={closeContextMenu} />
+ </>
+ );
+ }
+
+ const nextFrame = () =>
+ new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ const openMenu = async () => {
+ const target = host.querySelector<HTMLButtonElement>(
+ "[data-testid=html-file-reference]",
+ );
+ assert(target, "HTML reference fixture did not render");
+ flushSync(() =>
+ target.dispatchEvent(
+ new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ button: 2,
+ clientX: 80,
+ clientY: 80,
+ }),
+ ),
+ );
+ await nextFrame();
+ const menuTrigger = document.body.querySelector<HTMLButtonElement>(
+ '[data-context-menu-item="open-with"]',
+ );
+ assert(menuTrigger, "HTML reference menu did not render Open with");
+ return menuTrigger;
+ };
+
+ try {
+ flushSync(() => root.render(<Fixture />));
+ const trigger = await openMenu();
+ assert(
+ document.body.querySelector('[data-context-menu-item="open-with"]'),
+ "HTML reference menu did not render Open with",
+ );
+ flushSync(() => trigger.click());
+ assert(
+ document.body.querySelector('[data-context-menu-item="file-manager"]'),
+ "clicking Open with did not reveal its second-level actions",
+ );
+ flushSync(() => trigger.click());
+ assert(
+ document.body.querySelector('[data-context-menu-item="file-manager"]'),
+ "clicking an already-open Open with row closed its submenu",
+ );
+ flushSync(() =>
+ document.body
+ .querySelector<HTMLButtonElement>('[data-context-menu-item="built-in-browser"]')
+ ?.click(),
+ );
+ assert(
+ selections.length === 1 && selections[0] === "built-in-browser",
+ `selecting a submenu destination returned ${selections.join(", ") || "nothing"}`,
+ );
+ assert(
+ !document.body.querySelector('[data-context-menu-item="open-with"]'),
+ "choosing a destination did not close the context menu",
+ );
+
+ const keyboardTrigger = await openMenu();
+ keyboardTrigger.focus();
+ flushSync(() =>
+ keyboardTrigger.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
+ ),
+ );
+ await nextFrame();
+ const firstSubmenuItem = document.body.querySelector<HTMLButtonElement>(
+ '[data-context-menu-item="file-manager"]',
+ );
+ assert(
+ firstSubmenuItem && document.activeElement === firstSubmenuItem,
+ "ArrowRight did not open and focus the submenu",
+ );
+ flushSync(() =>
+ window.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
+ ),
+ );
+ assert(
+ !document.body.querySelector('[data-context-menu-item="file-manager"]') &&
+ document.body.querySelector('[data-context-menu-item="open-with"]') &&
+ document.activeElement === keyboardTrigger,
+ "Escape did not return focus to Open with while keeping the root menu open",
+ );
+ return { ok: true, selections, keyboardEscapeReturnedFocus: true };
+ } finally {
+ flushSync(() => root.unmount());
+ host.remove();
+ }
+}
+
const createdAt = "2026-09-13T00:00:00.000Z";
const message = (
id: string,
@@ -501,11 +645,13 @@ globalThis.transcriptRenderProbe = async () => {
const statusLifecycle = await transcriptStatusProbe();
const markdownLinks = await markdownLinkInteractionProbe(i18n);
+ const contextMenuSubmenu = await contextMenuSubmenuInteractionProbe();
const turnProcess = await turnProcessProbe();
return {
- ok: statusLifecycle.ok && markdownLinks.ok && turnProcess.ok,
+ ok: statusLifecycle.ok && markdownLinks.ok && contextMenuSubmenu.ok && turnProcess.ok,
statusLifecycle,
markdownLinks,
+ contextMenuSubmenu,
groups,
textUpdates: 20,
textUpdateRenders,