TypeScript
feat(web): open diff files from a right-click context menu (#11842)
Alex Southwell9051ed9c3923
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 89518a6f829..c1e52cfdaab 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -27,6 +27,7 @@ import * as DateTime from "effect/DateTime";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useCodeViewFileReveal } from "./diffs/useCodeViewFileReveal";import { useOpenInPreferredEditor } from "../editorPreferences";+import { useFileContextMenuHandler } from "../fileContextMenu";import { type DraftId } from "../composerDraftStore";import { openDiffFilePrimaryAction } from "../diffFileActions";import { useCheckpointDiff } from "~/lib/checkpointDiffState";@@ -170,6 +171,7 @@ export default function DiffPanel({const serverConfig = useAtomValue(serverEnvironment.configValueAtom(activeThread?.environmentId ?? null),);+ const onFileContextMenu = useFileContextMenuHandler(activeThread?.environmentId ?? null);const openInPreferredEditor = useOpenInPreferredEditor(activeThread?.environmentId ?? null,serverConfig?.availableEditors ?? [],@@ -1067,6 +1069,25 @@ export default function DiffPanel({);if (file) toggleDiffFileCollapsed(file.fileKey);}}+ onContextMenuCapture={(event) => {+ const composedPath = event.nativeEvent.composedPath?.() ?? [];+ const title = composedPath.find(+ (node): node is HTMLElement =>+ node instanceof HTMLElement && node.hasAttribute("data-title"),+ );+ const filePath = title?.textContent?.trim();+ if (!filePath) return;+ event.preventDefault();+ onFileContextMenu(+ {+ environmentId: activeThread?.environmentId ?? null,+ filePath,+ workspaceRoot: activeCwd,+ repositoryRoot: activeRepositoryRoot,+ },+ event,+ );+ }}><AnnotatableCodeViewkey={collapseScopeKey ?? reviewSectionId}diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsxindex 5ac9f09613f..f0cdc0163ce 100644--- a/apps/web/src/components/chat/ChangedFilesTree.tsx+++ b/apps/web/src/components/chat/ChangedFilesTree.tsx@@ -1,5 +1,5 @@import { type TurnId } from "@t3tools/contracts";-import { memo, useCallback, useMemo, useState } from "react";+import { type MouseEvent, memo, useCallback, useMemo, useState } from "react";import { type TurnDiffFileChange } from "../../types";import {buildTurnDiffTree,@@ -22,6 +22,9 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};+/** Opens the OS-level context menu for a changed file (reveal in file manager, open in editor). */+export type ChangedFileContextMenuHandler = (filePath: string, event: MouseEvent) => void;+export const ChangedFilesCard = memo(function ChangedFilesCard(props: {turnId: TurnId;files: ReadonlyArray<TurnDiffFileChange>;@@ -29,6 +32,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {resolvedTheme: "light" | "dark";onToggleAllDirectories: () => void;onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;+ onFileContextMenu?: ChangedFileContextMenuHandler | undefined;}) {const {turnId,@@ -37,6 +41,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {resolvedTheme,onToggleAllDirectories,onOpenTurnDiff,+ onFileContextMenu,} = props;const summaryStat = useMemo(() => summarizeTurnDiffStats(files), [files]);const hasDirectories = files.some((file) => /[/\\]/.test(file.path));@@ -117,6 +122,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {allDirectoriesExpanded={allDirectoriesExpanded}resolvedTheme={resolvedTheme}onOpenTurnDiff={onOpenTurnDiff}+ onFileContextMenu={onFileContextMenu}/></div>);@@ -128,8 +134,16 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {allDirectoriesExpanded: boolean;resolvedTheme: "light" | "dark";onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;+ onFileContextMenu?: ChangedFileContextMenuHandler | undefined;}) {- const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;+ const {+ files,+ allDirectoriesExpanded,+ onOpenTurnDiff,+ resolvedTheme,+ turnId,+ onFileContextMenu,+ } = props;const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"),@@ -214,6 +228,14 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {className="group flex w-full items-center gap-2 rounded-md py-1.5 pr-2 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"style={{ paddingLeft: `${leftPadding}px` }}onClick={() => onOpenTurnDiff(turnId, node.path)}+ onContextMenu={+ onFileContextMenu+ ? (event) => {+ event.preventDefault();+ onFileContextMenu(node.path, event);+ }+ : undefined+ }>{hasDirectoryNodes || depth > 0 ? (<span aria-hidden="true" className="size-3.5 shrink-0" />diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 03775a22f10..8305cb1d528 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -151,6 +151,10 @@ import {} from "./SnapShotAttachmentDetails";import { ProposedPlanCard } from "./ProposedPlanCard";import { ChangedFilesCard } from "./ChangedFilesTree";+import { useAtomValue } from "@effect/atom-react";+import { useFileContextMenuHandler } from "../../fileContextMenu";+import { useProject, useThread } from "../../state/entities";+import { serverEnvironment } from "../../state/server";import {CHAT_TIMELINE_ANCHOR_OFFSET,readTimelinePosition,@@ -3355,12 +3359,24 @@ function AssistantChangedFilesSectionInner({resolvedTheme: "light" | "dark";onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;}) {+ const ctx = use(TimelineRowCtx);const persistedExpanded = useUiStateStore((store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],);const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);const allDirectoriesExpanded = persistedExpanded ?? false;+ const thread = useThread(ctx.threadRef);+ const activeProject = useProject(+ thread && thread.projectId+ ? { environmentId: thread.environmentId, projectId: thread.projectId }+ : null,+ );+ const serverConfig = useAtomValue(+ serverEnvironment.configValueAtom(ctx.activeThreadEnvironmentId),+ );+ const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId);+return (<ChangedFilesCardturnId={turnSummary.turnId}@@ -3371,6 +3387,20 @@ function AssistantChangedFilesSectionInner({setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)}onOpenTurnDiff={onOpenTurnDiff}+ onFileContextMenu={(filePath, event) =>+ onFileContextMenu(+ {+ environmentId: ctx.activeThreadEnvironmentId,+ filePath,+ workspaceRoot: ctx.workspaceRoot,+ repositoryRoot:+ thread?.worktreePath == null+ ? activeProject?.repositoryIdentity?.rootPath+ : undefined,+ },+ event,+ )+ }/>);}diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsxindex 3703025cdcd..69e8714a329 100644--- a/apps/web/src/components/files/FileBrowserPanel.tsx+++ b/apps/web/src/components/files/FileBrowserPanel.tsx@@ -17,6 +17,7 @@ import { useComposerHandleContext } from "~/composerHandleContext";import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";import { useTheme } from "~/hooks/useTheme";import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";+import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu";import { readLocalApi } from "~/localApi";import { T3_PIERRE_ICONS } from "~/pierre-icons";import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";@@ -105,6 +106,7 @@ export default function FileBrowserPanel({}: FileBrowserPanelProps) {const { resolvedTheme } = useTheme();const composerRef = useComposerHandleContext();+ const fileContextMenu = useFileContextMenu(environmentId);const {entries: directoryEntries,load,@@ -157,6 +159,7 @@ export default function FileBrowserPanel({return () => document.removeEventListener("contextmenu", capturePointer, true);}, []);+ /** Combines the file actions (open/reveal/open with) with the panel's own mention actions. */const showEntryContextMenu = async (item: TreeContextMenuItem,context: TreeContextMenuOpenContext,@@ -174,14 +177,26 @@ export default function FileBrowserPanel({const position = pointerIsFresh? { x: pointer.x, y: pointer.y }: { x: anchorRect.left, y: anchorRect.bottom };+ const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd };+ const fileMenuItems = fileContextMenu.buildItems(fileTarget);try {const clicked = await api.contextMenu.show([+ ...fileMenuItems,{ id: "copy-mention", label: "Copy mention" },{ id: "add-to-chat", label: "Add to chat" },],position,);+ if (clicked === null) return;+ // "Open with" submenu selections report the child id ("editor:<id>"),+ // which is not present in the top-level item list.+ const isFileMenuAction =+ fileMenuItems.some((entry) => entry.id === clicked) || clicked.startsWith("editor:");+ if (isFileMenuAction) {+ await fileContextMenu.activate(clicked as FileContextMenuAction, fileTarget);+ return;+ }if (clicked === "copy-mention") {try {await writeTextToClipboard(mention);diff --git a/apps/web/src/fileContextMenu.test.ts b/apps/web/src/fileContextMenu.test.tsnew file mode 100644index 00000000000..02cae8b5dab--- /dev/null+++ b/apps/web/src/fileContextMenu.test.ts@@ -0,0 +1,102 @@+import { EnvironmentId } from "@t3tools/contracts";+import * as NodeAssert from "node:assert/strict";+import { describe, expect, it } from "vite-plus/test";++import { buildFileContextMenuItems, resolveFileContextMenuAbsolutePath } from "./fileContextMenu";++const BASE_TARGET = {+ environmentId: EnvironmentId.make("environment-local"),+ filePath: "src/index.ts",+ workspaceRoot: "/workspace/project",+};++const EMPTY_CAPABILITIES = {+ revealLabel: undefined,+ canOpenDefault: false,+ editorIds: [],+};++describe("resolveFileContextMenuAbsolutePath", () => {+ it("joins workspace-relative diff paths onto the workspace root", () => {+ expect(resolveFileContextMenuAbsolutePath(BASE_TARGET)).toBe("/workspace/project/src/index.ts");+ });++ it("strips the repository prefix when the repo root is nested in the workspace", () => {+ expect(+ resolveFileContextMenuAbsolutePath({+ ...BASE_TARGET,+ workspaceRoot: "/workspace/project/packages/app",+ repositoryRoot: "/workspace/project",+ filePath: "packages/app/src/index.ts",+ }),+ ).toBe("/workspace/project/packages/app/src/index.ts");+ });++ it("returns null for paths outside the workspace when a repository root is set", () => {+ expect(+ resolveFileContextMenuAbsolutePath({+ ...BASE_TARGET,+ workspaceRoot: "/workspace/project/packages/app",+ repositoryRoot: "/workspace/project",+ filePath: "other/src/index.ts",+ }),+ ).toBeNull();+ });++ it("rejects absolute paths without a workspace root, matching diff path resolution", () => {+ expect(+ resolveFileContextMenuAbsolutePath({+ ...BASE_TARGET,+ workspaceRoot: undefined,+ filePath: "/absolute/src/index.ts",+ }),+ ).toBeNull();+ });+});++describe("buildFileContextMenuItems", () => {+ it("offers open, reveal, and an open-with submenu when all are available", () => {+ const items = buildFileContextMenuItems({+ hasAbsolutePath: true,+ capabilities: {+ revealLabel: "Reveal in Finder",+ canOpenDefault: true,+ editorIds: ["vscode", "cursor", "file-manager"],+ },+ });++ expect(items.map((item) => item.id)).toEqual(["open", "reveal-in-folder", "open-with"]);+ expect(items[0]).toMatchObject({ label: "Open" });+ expect(items[1]).toMatchObject({ label: "Reveal in Finder" });+ const openWith = items[2];+ NodeAssert.ok(openWith);+ expect(openWith.children?.map((child) => child.id)).toEqual(["editor:vscode", "editor:cursor"]);+ });++ it("offers only the reveal item when just reveal is enabled", () => {+ const items = buildFileContextMenuItems({+ hasAbsolutePath: true,+ capabilities: {+ revealLabel: "Reveal in File Explorer",+ canOpenDefault: false,+ editorIds: [],+ },+ });++ expect(items.map((item) => item.id)).toEqual(["reveal-in-folder"]);+ expect(items[0]).toMatchObject({ label: "Reveal in File Explorer" });+ });++ it("offers nothing when the path cannot be resolved", () => {+ expect(+ buildFileContextMenuItems({+ hasAbsolutePath: false,+ capabilities: {+ revealLabel: "Reveal in Finder",+ canOpenDefault: true,+ editorIds: ["vscode"],+ },+ }),+ ).toEqual([]);+ });+});diff --git a/apps/web/src/fileContextMenu.ts b/apps/web/src/fileContextMenu.tsnew file mode 100644index 00000000000..05425f20595--- /dev/null+++ b/apps/web/src/fileContextMenu.ts@@ -0,0 +1,206 @@+/**+ * Right-click actions for a workspace file: reveal it in the environment's+ * file manager and open it in an editor. Reuse the chat file-chip menu's+ * machinery: reveal rides `shell.openInEditor` with `reveal: true`, which the+ * server only honors when its `shellRevealInFileManager` config flag is set,+ * so both actions work for every client and connection mode.+ */+import {+ EDITORS,+ type ContextMenuItem,+ type EditorId,+ type EnvironmentId,+} from "@t3tools/contracts";+import { useCallback, useMemo } from "react";++import { resolveDiffPathForWorkspace } from "./diffFileActions";+import {+ revealInFileExplorerLabelForKind,+ revealInFileExplorerLabelForOs,+} from "~/components/preview/fileExplorerLabel";+import { readLocalApi } from "./localApi";+import { serverEnvironment } from "./state/server";+import { shellEnvironment } from "./state/shell";+import { useAtomCommand } from "./state/use-atom-command";+import { resolvePathLinkTarget } from "./terminal-links";+import { toastManager } from "./components/ui/toast";+import { useAtomValue } from "@effect/atom-react";++export type FileContextMenuAction =+ | "reveal-in-folder"+ | "open"+ /** Submenu parent; never the activated id. */+ | "open-with"+ | `editor:${EditorId}`;++export interface FileContextMenuTarget {+ readonly environmentId: EnvironmentId | null;+ /** Repo- or workspace-relative file path, as shown in diffs. */+ readonly filePath: string;+ readonly workspaceRoot: string | undefined;+ readonly repositoryRoot?: string | undefined;+}++/** Absolute path on the environment host, or null when it cannot be resolved. */+/**+ * Absolute path on the environment host for a diff-style target, resolving+ * repo-relative paths through the workspace root like every other diff+ * surface. Returns null when the path cannot be resolved, which callers must+ * treat as "no file actions available".+ */+export function resolveFileContextMenuAbsolutePath(target: FileContextMenuTarget): string | null {+ const workspaceFilePath = resolveDiffPathForWorkspace({+ filePath: target.filePath,+ workspaceRoot: target.workspaceRoot,+ repositoryRoot: target.repositoryRoot,+ });+ if (workspaceFilePath === null) return null;+ if (target.workspaceRoot === undefined) {+ return workspaceFilePath.startsWith("/") || /^[a-zA-Z]:/.test(workspaceFilePath)+ ? workspaceFilePath+ : null;+ }+ return resolvePathLinkTarget(workspaceFilePath, target.workspaceRoot);+}++const EDITOR_LABEL_BY_ID = new Map(EDITORS.map((editor) => [editor.id, editor.label]));++export interface FileContextMenuCapabilities {+ readonly revealLabel: string | undefined;+ readonly canOpenDefault: boolean;+ readonly editorIds: ReadonlyArray<EditorId>;+}++/**+ * Menu items for a resolved file, offering only what the environment's config+ * advertises: default-app open, reveal (with server-provided wording), and an+ * "Open with" submenu of detected editors. Empty when nothing can act.+ */+export function buildFileContextMenuItems(input: {+ readonly hasAbsolutePath: boolean;+ readonly capabilities: FileContextMenuCapabilities;+}): readonly ContextMenuItem<FileContextMenuAction>[] {+ // Without a resolvable absolute path nothing here can act on the file.+ if (!input.hasAbsolutePath) return [];+ const items: ContextMenuItem<FileContextMenuAction>[] = [];+ if (input.capabilities.canOpenDefault) {+ items.push({ id: "open", label: "Open", icon: "pencil" });+ }+ if (input.capabilities.revealLabel !== undefined) {+ items.push({+ id: "reveal-in-folder",+ label: input.capabilities.revealLabel,+ icon: "folder-tree",+ });+ }+ const editorIds = input.capabilities.editorIds.filter((id) => id !== "file-manager");+ if (editorIds.length > 0) {+ items.push({+ id: "open-with",+ label: "Open with",+ children: editorIds.map((editorId) => ({+ id: `editor:${editorId}` as FileContextMenuAction,+ label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId,+ })),+ });+ }+ return items;+}++/**+ * Context-menu actions for files. The environment id is fixed per component+ * (a thread's environment, a file browser's environment), so capabilities+ * resolve once per hook call.+ */+/** Builds and dispatches the file context menu for one environment's files. */+export function useFileContextMenu(environmentId: EnvironmentId | null) {+ const openInEditor = useAtomCommand(shellEnvironment.openInEditor, { reportFailure: false });+ const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));++ return useMemo(() => {+ const availableEditors = serverConfig?.availableEditors ?? [];+ const capabilities: FileContextMenuCapabilities = {+ // The reveal wording comes from the server because on WSL the reveal can+ // run through Windows File Explorer even though the host reports Linux.+ revealLabel:+ environmentId !== null &&+ serverConfig?.shellRevealInFileManager === true &&+ serverConfig.availableEditors.includes("file-manager")+ ? serverConfig.shellRevealInFileManagerKind === undefined+ ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os)+ : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind)+ : undefined,+ canOpenDefault: availableEditors.includes("file-manager"),+ editorIds: availableEditors,+ };++ const activate = async (+ action: FileContextMenuAction,+ target: FileContextMenuTarget,+ ): Promise<void> => {+ const absolutePath = resolveFileContextMenuAbsolutePath(target);+ if (absolutePath === null || environmentId === null) return;++ const reveal = action === "reveal-in-folder";+ const editor =+ action === "open" || reveal+ ? ("file-manager" as const)+ : (action.slice("editor:".length) as EditorId);+ if (action !== "open" && !reveal && !capabilities.editorIds.includes(editor)) return;++ const result = await openInEditor({+ environmentId,+ input: { cwd: absolutePath, editor, ...(reveal ? { reveal: true } : {}) },+ });+ if (result._tag !== "Failure") return;+ toastManager.add({+ type: "error",+ title:+ action === "open"+ ? "Could not open file"+ : reveal+ ? "Unable to reveal file"+ : `Could not open in ${EDITOR_LABEL_BY_ID.get(editor) ?? editor}`,+ description: absolutePath,+ });+ };++ const show = async (+ target: FileContextMenuTarget,+ position?: { x: number; y: number },+ ): Promise<void> => {+ const api = readLocalApi();+ const items = buildFileContextMenuItems({+ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null,+ capabilities,+ });+ if (items.length === 0 || api === undefined) return;+ const clicked = await api.contextMenu.show(items, position);+ if (clicked === null) return;+ await activate(clicked as FileContextMenuAction, target);+ };++ return {+ buildItems: (target: FileContextMenuTarget) =>+ buildFileContextMenuItems({+ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null,+ capabilities,+ }),+ capabilities,+ activate,+ show,+ };+ }, [environmentId, openInEditor, serverConfig]);+}++/** Convenience callback for onContextMenu handlers. */+/** Returns an onContextMenu callback that shows the menu at the pointer. */+export function useFileContextMenuHandler(environmentId: EnvironmentId | null) {+ const contextMenu = useFileContextMenu(environmentId);+ return useCallback(+ (target: FileContextMenuTarget, event?: { clientX: number; clientY: number }) => {+ void contextMenu.show(target, event ? { x: event.clientX, y: event.clientY } : undefined);+ },+ [contextMenu],+ );+}