TypeScript
fix(web): folder breadcrumbs navigate to parent folders (#15045)
scratchyoneaa35fb3ec6b1
diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.tsindex 454392357fb..0d716b22375 100644--- a/apps/server/src/workspace/WorkspaceEntries.test.ts+++ b/apps/server/src/workspace/WorkspaceEntries.test.ts@@ -134,6 +134,30 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {}),);+ it.effect("lists a host folder and its parent, each from its own root", () =>+ // Folder links outside the workspace browse by passing the host folder as+ // `cwd`; walking up passes the parent. Each stays bounded by its own root.+ Effect.gen(function* () {+ const parent = yield* makeTempDir();+ const path = yield* Path.Path;+ yield* writeTextFile(parent, "linked/notes.md");+ yield* writeTextFile(parent, "sibling/readme.md");+ const linked = path.join(parent, "linked");++ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;+ expect(yield* workspaceEntries.list({ cwd: linked, directoryPath: "" })).toEqual({+ entries: [{ path: "notes.md", kind: "file" }],+ truncated: false,+ });+ const up = yield* workspaceEntries.list({ cwd: parent, directoryPath: "" });+ expect(up.entries.map((entry) => entry.path).toSorted()).toEqual(["linked", "sibling"]);+ const escape = yield* workspaceEntries+ .list({ cwd: linked, directoryPath: "../sibling" })+ .pipe(Effect.flip);+ expect(escape._tag).toBe("WorkspaceEntriesReadDirectoryError");+ }),+ );+it.effect("rejects directory traversal, git internals, and symlinks outside the workspace",() =>diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex f87663989a8..3347cae76a3 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -10980,6 +10980,18 @@ export default function ChatView(props: ChatViewProps) {: 0}onOpenFile={openFileSurfaceStable}+ onNavigateFolder={(relativePath, folderTrail, keepSource) =>+ useRightPanelStore+ .getState()+ .navigateFolder(+ activeThreadRef,+ renderedRightPanelSurface.id,+ relativePath,+ folderTrail,+ keepSource,+ )+ }+ folderTrail={renderedRightPanelSurface.folderTrail}onPendingChange={handleFilePendingChangeStable}selectedFilePending={renderedRightPanelSurface.kind === "file" &&diff --git a/apps/web/src/components/files/FileBreadcrumbs.tsx b/apps/web/src/components/files/FileBreadcrumbs.tsxindex 70a55b7bc6d..1190ddfa505 100644--- a/apps/web/src/components/files/FileBreadcrumbs.tsx+++ b/apps/web/src/components/files/FileBreadcrumbs.tsx@@ -22,19 +22,26 @@ import { cn } from "~/lib/utils";import { isAbsolutePath } from "@t3tools/shared/path";import {+ breadcrumbPathOf,type FileBreadcrumb,fileBreadcrumbChildren,fileBreadcrumbParent,fileBreadcrumbs,+ isListableHostFolder,} from "./filePath";import { useProjectEntriesQuery } from "./projectFilesQueryState";interface FileBreadcrumbsProps {readonly cwd: string;readonly environmentId: EnvironmentId;+ /** Moves the browser to a folder crumb; `""` is the workspace root. */+ readonly onNavigateFolder: (relativePath: string) => void;readonly onOpenFile: (relativePath: string) => void;readonly projectName: string;+ /** The current path; `""` is the workspace root. */readonly relativePath: string;+ /** The deepest path to show: `relativePath`, or a path inside it the browser came up from. */+ readonly trail: string;readonly workspaceMutationId: string | null;}@@ -213,7 +220,8 @@ function BreadcrumbMenuContent(props: {);}-function DirectoryBreadcrumb(props: FileBreadcrumbsProps & { readonly crumb: FileBreadcrumb }) {+/** The chevron after a folder crumb lists that folder's entries. */+function FolderContentsMenu(props: FileBreadcrumbsProps & { readonly crumb: FileBreadcrumb }) {const [open, setOpen] = useState(false);const [directoryPath, setDirectoryPath] = useState(props.crumb.path);@@ -229,24 +237,17 @@ function DirectoryBreadcrumb(props: FileBreadcrumbsProps & { readonly crumb: Filreturn (<Menu open={open} onOpenChange={handleOpenChange}>- <Tooltip>- <TooltipTrigger- render={- <MenuTrigger- render={- <button- type="button"- aria-label={`Browse ${props.crumb.label}`}- className="relative block max-w-40 cursor-pointer rounded-sm px-0.5 text-left text-muted-foreground outline-none pointer-coarse:after:-inset-y-3 pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring data-popup-open:bg-accent data-popup-open:text-foreground"- />- }- />- }- >- <span className="block truncate">{props.crumb.label}</span>- </TooltipTrigger>- <TooltipPopup side="top">{props.crumb.path || props.projectName}</TooltipPopup>- </Tooltip>+ <MenuTrigger+ render={+ <button+ type="button"+ aria-label={`Browse ${props.crumb.label}`}+ className="relative mx-0.5 flex h-5 w-4 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground/60 outline-none pointer-coarse:after:absolute pointer-coarse:after:-inset-3 hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring data-popup-open:bg-accent data-popup-open:text-foreground"+ />+ }+ >+ <ChevronRightIcon className="size-3.5" />+ </MenuTrigger>{open ? (<BreadcrumbMenuContentcwd={props.cwd}@@ -265,31 +266,90 @@ function DirectoryBreadcrumb(props: FileBreadcrumbsProps & { readonly crumb: Fil);}+function FolderBreadcrumb(props: {+ readonly crumb: FileBreadcrumb;+ /** Below the current folder, kept from where the browser came from. */+ readonly descendant: boolean;+ readonly onNavigate: (path: string) => void;+ readonly projectName: string;+}) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={() => props.onNavigate(props.crumb.path)}+ className={cn(+ "relative block max-w-40 cursor-pointer rounded-sm px-0.5 text-left outline-none pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:-inset-y-3 hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ props.descendant ? "text-muted-foreground/70" : "text-muted-foreground",+ )}+ />+ }+ >+ <span className="block truncate">{props.crumb.label}</span>+ </TooltipTrigger>+ <TooltipPopup side="top">{props.crumb.path || props.projectName}</TooltipPopup>+ </Tooltip>+ );+}++/**+ * Each folder crumb moves the browser to that folder, and the chevron after it+ * lists the folder's entries. A host path outside the workspace has no contents+ * menu: the browser below already lists the folder it moves to.+ */export function FileBreadcrumbs(props: FileBreadcrumbsProps) {const hostPath = isAbsolutePath(props.relativePath);const breadcrumbs = useMemo(- () => fileBreadcrumbs(props.projectName, props.relativePath),- [props.projectName, props.relativePath],+ () => fileBreadcrumbs(props.projectName, props.trail),+ [props.projectName, props.trail],);+ const currentPath = breadcrumbPathOf(props.relativePath);+ const currentIndex = breadcrumbs.findIndex((crumb) => crumb.path === currentPath);- return breadcrumbs.map((crumb, index) => (- <div- key={crumb.path || "project"}- className="flex min-w-0 shrink-0 items-center"- data-current-file-crumb={crumb.kind === "file"}- >- {index > 0 ? (- <ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />- ) : null}- {crumb.kind === "file" ? (- <span aria-current="page">- <BreadcrumbLabel current label={crumb.label} pathLabel={crumb.path} />- </span>- ) : hostPath ? (- <BreadcrumbLabel label={crumb.label} pathLabel={crumb.path} />- ) : (- <DirectoryBreadcrumb {...props} crumb={crumb} />- )}- </div>- ));+ return (+ <nav aria-label="File path" className="flex h-full">+ <ol className="flex items-center">+ {breadcrumbs.map((crumb, index) => {+ const current = index === currentIndex;+ return (+ <li+ key={crumb.path || "project"}+ className="flex min-w-0 shrink-0 items-center"+ data-file-crumb+ data-current-file-crumb={current}+ >+ {current ? (+ <span aria-current="page">+ <BreadcrumbLabel+ current+ label={crumb.label}+ pathLabel={crumb.path || props.projectName}+ />+ </span>+ ) : hostPath && !isListableHostFolder(crumb.path) ? (+ <BreadcrumbLabel label={crumb.label} pathLabel={crumb.path} />+ ) : (+ <FolderBreadcrumb+ crumb={crumb}+ descendant={index > currentIndex}+ onNavigate={props.onNavigateFolder}+ projectName={props.projectName}+ />+ )}+ {index === breadcrumbs.length - 1 ? null : hostPath ? (+ <ChevronRightIcon+ aria-hidden+ className="mx-1 size-3.5 shrink-0 text-muted-foreground/60"+ />+ ) : (+ <FolderContentsMenu {...props} crumb={crumb} />+ )}+ </li>+ );+ })}+ </ol>+ </nav>+ );}diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsxindex d9722303ab7..e7b722fb70e 100644--- a/apps/web/src/components/files/FileBrowserPanel.tsx+++ b/apps/web/src/components/files/FileBrowserPanel.tsx@@ -23,6 +23,7 @@ import { readLocalApi } from "~/localApi";import { T3_PIERRE_ICONS } from "~/pierre-icons";import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme";+import { joinHostPath } from "./filePath";import { createFileTreeDragMentionController } from "./fileTreeDragMention";import { areAllDirectoriesExpanded, setAllDirectoriesExpanded } from "./fileTreeExpansion";import { buildFileTreePathUpdates } from "./fileTreePathReconciliation";@@ -38,6 +39,13 @@ interface FileBrowserPanelProps {/** Bumped when the same path should be revealed again (e.g. re-opened from search). */selectedPathRevealId: number;onOpenFile: (relativePath: string) => void;+ /**+ * Set when `cwd` is a host folder outside the workspace rather than the+ * workspace root. Entries then open and mention as host paths. A host folder can+ * be a home directory, so nothing walks it whole: there is no expand-all, and+ * search filters the folders already loaded instead of indexing on the server.+ */+ hostFolder?: boolean;onRefreshSelectedFile?: () => void;workspaceMutationId: string | null;}@@ -104,7 +112,10 @@ export default function FileBrowserPanel({onOpenFile,onRefreshSelectedFile,workspaceMutationId,+ hostFolder = false,}: FileBrowserPanelProps) {+ const panelPath = (relativePath: string) =>+ hostFolder ? joinHostPath(cwd, relativePath) : relativePath;const { resolvedTheme } = useTheme();const composerRef = useComposerHandleContext();const fileContextMenu = useFileContextMenu(environmentId);@@ -119,7 +130,10 @@ export default function FileBrowserPanel({} = useDirectoryEntries(environmentId, cwd);const [query, setQuery] = useState("");const [expandAll, setExpandAll] = useState(false);- const pathSearch = useProjectPathSearch({ environmentId, cwd, query: query.slice(0, 256) }, 200);+ const pathSearch = useProjectPathSearch(+ { environmentId, cwd: hostFolder ? null : cwd, query: query.slice(0, 256) },+ 200,+ );const entries = useMemo(() => {const result = new Map(directoryEntries.map((entry) => [entry.path, entry]));if (query.trim() && !pathSearch.isPending) {@@ -172,7 +186,7 @@ export default function FileBrowserPanel({return;}const relativePath = item.path.replace(/\/$/, "");- const mention = serializeComposerFileLink(relativePath);+ const mention = serializeComposerFileLink(panelPath(relativePath));const pointer = contextMenuPointerRef.current;const pointerIsFresh = pointer !== null && performance.now() - pointer.at < 1000;const anchorRect = context.anchorElement.getBoundingClientRect();@@ -248,8 +262,9 @@ export default function FileBrowserPanel({() =>createFileTreeDragMentionController({deselect: (path) => treeModelRef.current?.getItem(path)?.deselect(),+ ...(hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {}),}),- [],+ [cwd, hostFolder],);const { model } = useFileTree({composition: {@@ -283,7 +298,7 @@ export default function FileBrowserPanel({const selectedPath = selectedPaths.at(-1)?.replace(/\/$/, "");if (selectedPath && entryKindsRef.current.get(selectedPath) === "file") {treeSelectionPathRef.current = selectedPath;- onOpenFile(selectedPath);+ onOpenFile(panelPath(selectedPath));}},paths: [],@@ -516,7 +531,7 @@ export default function FileBrowserPanel({onValueChange={handleSearchValueChange}onClose={closeSearch}/>- {directoryPaths.length > 0 ? (+ {directoryPaths.length > 0 && !hostFolder ? (<Tooltip><TooltipTriggerrender={diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsxindex 4c0767ad5af..e0238aa1923 100644--- a/apps/web/src/components/files/FilePreviewPanel.tsx+++ b/apps/web/src/components/files/FilePreviewPanel.tsx@@ -77,6 +77,7 @@ import { BrowserDocumentFrame, isPdfPreviewFile } from "./BrowserDocumentFrame";import { DelimitedTablePreview } from "./DelimitedTablePreview";import FileBrowserPanel from "./FileBrowserPanel";import { FileBreadcrumbs } from "./FileBreadcrumbs";+import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath";import { FileMarkdownPreview } from "./FileMarkdownPreview";import {type FileCommentAnnotationEntry,@@ -129,6 +130,10 @@ interface FilePreviewPanelProps {revealLine: number | null;revealRequestId: number;onOpenFile: (relativePath: string) => void;+ /** Moves this folder browser to another folder in place; see `navigateFolder`. */+ onNavigateFolder: (relativePath: string, folderTrail: string, keepSource: boolean) => void;+ /** The deeper path breadcrumbs keep after the browser moved up; see `navigateFolder`. */+ folderTrail: string | undefined;onPendingChange: (relativePath: string, pending: boolean) => void;selectedFilePending: boolean;workspaceMutationId: string | null;@@ -1038,6 +1043,8 @@ export default function FilePreviewPanel({revealLine,revealRequestId,onOpenFile,+ onNavigateFolder,+ folderTrail,onPendingChange,selectedFilePending,workspaceMutationId,@@ -1087,10 +1094,23 @@ export default function FilePreviewPanel({// a file surface and the read fails. Keep the breadcrumbs, drop the preview// pane, and let the tree fill the surface with the folder revealed. Mutation// refresh stays on so the surface notices if the path becomes a file. A host- // path cannot be revealed in the workspace tree, so it keeps the read error.- const isDirectory = file.isNotFile && !isHostFile;+ // folder outside the workspace gets a tree of its own, rooted at that folder.+ // `folderTrail` is set only when crumbs walked the browser up: the deeper path+ // kept for the way back down. The explorer (`""`) shows crumbs only then.+ const breadcrumbPath =+ attachment !== undefined ? null : (relativePath ?? (folderTrail === undefined ? null : ""));+ // A host trail that walked up to the workspace root (`/repo/project` is `""`) no+ // longer passes through the current path, so the crumbs start over there.+ const breadcrumbTrail =+ breadcrumbPath === null ? null : retainedBreadcrumbTrail(folderTrail, breadcrumbPath);+ // The trail only continues below folders, so a surface with one is a folder+ // before its read settles, and walking up never flashes a file preview.+ const isFolder =+ attachment === undefined &&+ (file.isNotFile || (folderTrail !== undefined && file.data === null && file.error === null));+ const hostFolderPath = isFolder && isHostFile ? relativePath : null;// Everything preview-related keys off previewPath; a folder has no preview.- const previewPath = isDirectory ? null : relativePath;+ const previewPath = isFolder ? null : relativePath;const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen);const showExplorer = shouldShowFileExplorer({relativePath: previewPath,@@ -1162,8 +1182,21 @@ export default function FilePreviewPanel({!isVideo &&previewAvailable &&isBrowserPreviewFile(previewPath);+ // A file keeps its tab; walking up from it opens a folder browser beside it.+ // The trail's end keeps its own spelling (`C:/a` or `C:\a`), so it finds its tab.+ const navigateToFolder = (crumbPath: string) => {+ const path =+ breadcrumbTrail !== null && breadcrumbPathOf(breadcrumbTrail) === crumbPath+ ? breadcrumbTrail+ : crumbPath;+ onNavigateFolder(path, retainedBreadcrumbTrail(breadcrumbTrail ?? undefined, path), !isFolder);+ };const absolutePath =- relativePath && attachment === undefined ? resolvePathLinkTarget(relativePath, cwd) : null;+ breadcrumbPath === ""+ ? cwd+ : relativePath && attachment === undefined+ ? resolvePathLinkTarget(relativePath, cwd)+ : null;const onFilePostRender = useFileLineReveal(relativePath, revealLine, revealRequestId);useWorkspaceMutationRefresh({enabled:@@ -1172,7 +1205,7 @@ export default function FilePreviewPanel({// Media and PDFs never show their contents, so re-reading them on every// workspace mutation is waste. A folder named like one still re-reads, so// it notices when the path becomes a file.- (isDirectory || (!isMedia && !isPdf)) &&+ (isFolder || (!isMedia && !isPdf)) &&!selectedFilePending,mutationId: workspaceMutationId,refresh: file.refresh,@@ -1180,11 +1213,13 @@ export default function FilePreviewPanel({});useEffect(() => {- const currentCrumb = breadcrumbRef.current?.querySelector<HTMLElement>(- "[data-current-file-crumb='true']",- );- currentCrumb?.scrollIntoView({ block: "nearest", inline: "end" });- }, [relativePath]);+ const crumbs = breadcrumbRef.current?.querySelectorAll<HTMLElement>("[data-file-crumb]");+ // Show the deepest crumb when it fits, but never at the cost of the current one.+ crumbs?.[crumbs.length - 1]?.scrollIntoView({ block: "nearest", inline: "end" });+ breadcrumbRef.current+ ?.querySelector<HTMLElement>("[data-current-file-crumb='true']")+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });+ }, [breadcrumbPath, breadcrumbTrail]);const toggleExplorer = () => {setExplorerOpen((current) => {@@ -1250,7 +1285,7 @@ export default function FilePreviewPanel({return (<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">- {relativePath && attachment === undefined ? (+ {breadcrumbPath !== null && breadcrumbTrail !== null ? (<div className={FILE_SURFACE_SUBHEADER_CLASS} data-surface-subheader><ScrollArearadius="none"@@ -1264,9 +1299,11 @@ export default function FilePreviewPanel({<FileBreadcrumbscwd={cwd}environmentId={environmentId}+ onNavigateFolder={navigateToFolder}onOpenFile={onOpenFile}projectName={projectName}- relativePath={relativePath}+ relativePath={breadcrumbPath}+ trail={breadcrumbTrail}workspaceMutationId={workspaceMutationId}/></div>@@ -1344,7 +1381,7 @@ export default function FilePreviewPanel({<divclassName={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}>- {isDirectory ? null : relativePath && attachment ? (+ {isFolder ? null : relativePath && attachment ? (<AttachmentFilePreviewkey={`${environmentId}:${attachment.id}`}name={attachment.name}@@ -1488,11 +1525,16 @@ export default function FilePreviewPanel({)}><FileBrowserPanel- key={`${environmentId}:${cwd}`}+ key={`${environmentId}:${hostFolderPath ?? cwd}`}environmentId={environmentId}- cwd={cwd}- projectName={projectName}- selectedPath={relativePath}+ cwd={hostFolderPath ?? cwd}+ projectName={hostFolderPath ?? projectName}+ hostFolder={hostFolderPath !== null}+ selectedPath={+ hostFolderPath === null+ ? relativePath+ : trailChildOf(hostFolderPath, breadcrumbTrail ?? hostFolderPath)+ }selectedPathRevealId={revealRequestId}onOpenFile={onOpenFile}workspaceMutationId={workspaceMutationId}diff --git a/apps/web/src/components/files/filePath.test.ts b/apps/web/src/components/files/filePath.test.tsindex b501562fee0..f9dc52658c7 100644--- a/apps/web/src/components/files/filePath.test.ts+++ b/apps/web/src/components/files/filePath.test.ts@@ -1,6 +1,15 @@import { describe, expect, it } from "vite-plus/test";-import { fileBreadcrumbChildren, fileBreadcrumbParent, fileBreadcrumbs } from "./filePath";+import {+ breadcrumbPathOf,+ fileBreadcrumbChildren,+ fileBreadcrumbParent,+ fileBreadcrumbs,+ isListableHostFolder,+ joinHostPath,+ retainedBreadcrumbTrail,+ trailChildOf,+} from "./filePath";describe("fileBreadcrumbs", () => {it("builds project, directory, and file crumbs", () => {@@ -28,7 +37,7 @@ describe("fileBreadcrumbs", () => {{ label: "report.md", path: "/tmp/t3-cleanup/report.md", kind: "file" },]);expect(fileBreadcrumbs("t3code", "C:\\Temp\\report.md")).toEqual([- { label: "C:", path: "C:", kind: "directory" },+ { label: "C:", path: "C:\\", kind: "directory" },{ label: "Temp", path: "C:\\Temp", kind: "directory" },{ label: "report.md", path: "C:\\Temp\\report.md", kind: "file" },]);@@ -40,6 +49,22 @@ describe("fileBreadcrumbs", () => {});});+describe("breadcrumbPathOf", () => {+ it.each([+ ["", ""],+ ["src", "src"],+ ["src/", "src"],+ ["src//components", "src/components"],+ ["/tmp/t3-demo/", "/tmp/t3-demo"],+ ["/", "/"],+ ["C:\\Users\\me\\", "C:\\Users\\me"],+ ["C:\\", "C:\\"],+ ["\\\\server\\share\\", "\\\\server\\share"],+ ])("writes %j as its crumb names it", (path, expected) => {+ expect(breadcrumbPathOf(path)).toBe(expected);+ });+});+describe("fileBreadcrumbChildren", () => {const entries = [{ path: "README.md", kind: "file" as const },@@ -86,6 +111,76 @@ describe("fileBreadcrumbChildren", () => {});});+describe("retainedBreadcrumbTrail", () => {+ it.each([+ // Walking up keeps the deeper path, all the way to the workspace root.+ ["apps/web/src", "apps/web", "apps/web/src"],+ ["apps/web/src", "", "apps/web/src"],+ // Walking back down inside the trail keeps it too.+ ["apps/web/src", "apps/web/src", "apps/web/src"],+ // Somewhere else starts over, including a sibling that shares a name prefix.+ ["apps/web/src", "apps/mobile", "apps/mobile"],+ ["src/lib", "src-old", "src-old"],+ ["apps/web", "apps/web/src/main.tsx", "apps/web/src/main.tsx"],+ // Workspace and host paths never share a trail.+ ["apps/web/src", "/tmp/report", "/tmp/report"],+ ["/tmp/report", "", ""],+ ["C:\\Temp\\a", "", ""],+ // Host folders outside the workspace keep their trail the same way.+ ["/Users/me/projects/scope", "/Users/me", "/Users/me/projects/scope"],+ ["/Users/me/projects/scope", "/Users/me/proj", "/Users/me/proj"],+ ["/Volumes/Work/a", "/Volumes/Work/a/", "/Volumes/Work/a"],+ ["C:\\Users\\me\\scope", "C:\\", "C:\\Users\\me\\scope"],+ ["C:\\Users\\me\\scope", "C:\\Users", "C:\\Users\\me\\scope"],+ ["C:\\Users\\me\\scope", "D:\\", "D:\\"],+ ["\\\\nas\\share\\docs\\notes", "\\\\nas\\share", "\\\\nas\\share\\docs\\notes"],+ ])("from trail %j to %j keeps %j", (trail, path, expected) => {+ expect(retainedBreadcrumbTrail(trail, path)).toBe(expected);+ });++ it("starts at the path when nothing came before", () => {+ expect(retainedBreadcrumbTrail(undefined, "apps")).toBe("apps");+ });+});++describe("trailChildOf", () => {+ it.each([+ ["/Users/me", "/Users/me/projects/scope", "projects"],+ ["/Users/me/projects/scope", "/Users/me/projects/scope", null],+ ["/Users/me", "/Users/meg/a", null],+ ["C:\\", "C:\\Users\\me", "Users"],+ ["C:\\Users", "C:\\Users\\me\\scope", "me"],+ ["\\\\nas\\share", "\\\\nas\\share\\docs\\notes", "docs"],+ ])("in %j toward %j selects %j", (folder, trail, expected) => {+ expect(trailChildOf(folder, trail)).toBe(expected);+ });+});++describe("joinHostPath", () => {+ it.each([+ ["/Users/me", "projects/scope", "/Users/me/projects/scope"],+ ["/", "Users", "/Users"],+ ["C:\\", "Users/me", "C:\\Users\\me"],+ ["C:\\Users", "me", "C:\\Users\\me"],+ ["\\\\nas\\share", "docs/notes.md", "\\\\nas\\share\\docs\\notes.md"],+ ])("joins %j and %j as %j", (folder, relativePath, expected) => {+ expect(joinHostPath(folder, relativePath)).toBe(expected);+ });+});++describe("isListableHostFolder", () => {+ it.each([+ ["/Users", true],+ ["C:\\", true],+ ["\\\\nas\\share", true],+ // A UNC server is not a directory the server can list.+ ["\\\\nas", false],+ ["apps/web", false],+ ])("%j is %j", (path, expected) => {+ expect(isListableHostFolder(path)).toBe(expected);+ });+});+describe("fileBreadcrumbParent", () => {it.each([["src/lib", "src"],diff --git a/apps/web/src/components/files/filePath.ts b/apps/web/src/components/files/filePath.tsindex aa6225381be..e30dab8647d 100644--- a/apps/web/src/components/files/filePath.ts+++ b/apps/web/src/components/files/filePath.ts@@ -22,14 +22,65 @@ export function fileBreadcrumbs(projectName: string, relativePath: string): Fileconst root = relativePath.startsWith("\\\\") ? "\\\\" : hostPath && separator === "/" ? "/" : "";return [...(hostPath ? [] : [{ label: projectName, path: "", kind: "project" as const }]),- ...parts.map((part, index) => ({- label: part,- path: root + parts.slice(0, index + 1).join(separator),- kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),- })),+ ...parts.map((part, index) => {+ const path = root + parts.slice(0, index + 1).join(separator);+ return {+ label: part,+ // A bare drive (`C:`) means the drive's current directory; its root is `C:\`.+ path: /^[A-Za-z]:$/.test(path) ? `${path}\\` : path,+ kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),+ };+ }),];}+/**+ * `relativePath` written the way its own crumb names it, so a link with a+ * trailing or repeated separator still finds its crumb.+ */+export function breadcrumbPathOf(relativePath: string): string {+ return fileBreadcrumbs("", relativePath).at(-1)?.path ?? relativePath;+}++/**+ * Whether a host folder crumb names a directory the server can list. A UNC+ * server (`\\server`) is not one; its shares (`\\server\share`) are.+ */+export function isListableHostFolder(path: string): boolean {+ return isAbsolutePath(path) && !/^\\\\[^\\/]+$/.test(path);+}++/** Index of `path`'s crumb among `trail`'s crumbs; -1 when the trail does not pass through it. */+function trailCrumbIndex(trail: string, path: string): number {+ const crumbPath = breadcrumbPathOf(path);+ return fileBreadcrumbs("", trail).findIndex((crumb) => crumb.path === crumbPath);+}++/**+ * The deepest path the breadcrumbs keep showing after the browser moves to `path`.+ * Going up keeps the folders below visible so the way back down is one click;+ * moving anywhere else starts over at `path`.+ */+export function retainedBreadcrumbTrail(trail: string | undefined, path: string): string {+ return trail !== undefined && trailCrumbIndex(trail, path) >= 0 ? trail : path;+}++/** The entry of `folder` that leads toward `trail`; null when the trail ends at the folder. */+export function trailChildOf(folder: string, trail: string): string | null {+ const index = trailCrumbIndex(trail, folder);+ return index < 0 ? null : (fileBreadcrumbs("", trail)[index + 1]?.label ?? null);+}++/**+ * A host path for `relativePath` (as a host folder's listing names it, with `/`)+ * inside host folder `folder`, using the folder's own separator.+ */+export function joinHostPath(folder: string, relativePath: string): string {+ const separator = isWindowsAbsolutePath(folder) ? "\\" : "/";+ const base = folder.endsWith(separator) ? folder : `${folder}${separator}`;+ return base + relativePath.split("/").join(separator);+}+export function fileBreadcrumbChildren(entries: readonly ProjectEntry[],directoryPath: string,diff --git a/apps/web/src/components/files/fileTreeDragMention.test.ts b/apps/web/src/components/files/fileTreeDragMention.test.tsindex 812501ab5d1..efac26f8158 100644--- a/apps/web/src/components/files/fileTreeDragMention.test.ts+++ b/apps/web/src/components/files/fileTreeDragMention.test.ts@@ -38,6 +38,19 @@ describe("createFileTreeDragMentionController", () => {expect(transfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toBe("[architecture](docs/architecture)");});+ it("mentions rows of a host folder by their host path", () => {+ const controller = createFileTreeDragMentionController({+ deselect: () => {},+ mentionPath: (path) => `/Users/me/scope/${path}`,+ });+ const transfer = makeTransfer();+ controller.handleDragStart({+ dataTransfer: transfer,+ composedPath: () => [rowNode("notes/")],+ });+ expect(transfer.getData(COMPOSER_MENTION_DRAG_TYPE)).toBe("[notes](/Users/me/scope/notes)");+ });+it("does not tag drags of selected text from the panel chrome", () => {// Only a drag that originates on a tree row is a mention; dragging a text// selection also carries text/plain, and tagging it would drop an invaliddiff --git a/apps/web/src/components/files/fileTreeDragMention.ts b/apps/web/src/components/files/fileTreeDragMention.tsindex 7c17639a649..a7aca87e2f6 100644--- a/apps/web/src/components/files/fileTreeDragMention.ts+++ b/apps/web/src/components/files/fileTreeDragMention.ts@@ -15,6 +15,8 @@ export interface FileTreeDragStartEvent {export interface FileTreeDragMentionHost {/** Drop the tree's gesture-applied selection of the dragged row. */deselect(treePath: string): void;+ /** The path a dragged row mentions; defaults to the tree path itself. */+ mentionPath?(treePath: string): string;}export interface FileTreeDragMentionController {@@ -74,7 +76,12 @@ export function createFileTreeDragMentionController(// part of the current selection drags the whole selection.const dragged = selection.includes(itemPath) ? selection : [itemPath];const mentions = dragged- .map((path) => composerMentionFromTreePath(path))+ .map((path) => {+ const treePath = path.replace(/\/+$/, "");+ return composerMentionFromTreePath(+ treePath && host.mentionPath ? host.mentionPath(treePath) : path,+ );+ }).filter((mention): mention is string => mention !== null);if (mentions.length === 0) {return;diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.tsindex 961a4a178da..fdc357a431a 100644--- a/apps/web/src/rightPanelStore.test.ts+++ b/apps/web/src/rightPanelStore.test.ts@@ -682,6 +682,101 @@ describe("rightPanelStore", () => {).toBe("files");});+ it("walks a folder browser up and back down in one tab", () => {+ const store = useRightPanelStore.getState();+ const state = () =>+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);+ store.openFile(refA, "README.md");+ store.openFile(refA, "apps/web/src");++ store.navigateFolder(refA, "file:apps/web/src", "apps", "apps/web/src");+ expect(state().activeSurfaceId).toBe("file:apps");+ expect(state().surfaces).toEqual([+ expect.objectContaining({ id: "file:README.md" }),+ expect.objectContaining({+ id: "file:apps",+ relativePath: "apps",+ folderTrail: "apps/web/src",+ }),+ ]);++ // The workspace root is the files explorer, still holding the way back down.+ store.navigateFolder(refA, "file:apps", "", "apps/web/src");+ expect(state().surfaces.map((surface) => surface.id)).toEqual(["file:README.md", "files"]);+ expect(state().surfaces[1]).toEqual({+ id: "files",+ kind: "files",+ folderTrail: "apps/web/src",+ });++ // Reaching the end of the trail leaves no trail behind.+ store.navigateFolder(refA, "files", "apps/web/src", "apps/web/src");+ expect(state().activeSurfaceId).toBe("file:apps/web/src");+ expect(state().surfaces[1]).toEqual({+ id: "file:apps/web/src",+ kind: "file",+ relativePath: "apps/web/src",+ revealLine: null,+ revealRequestId: 1,+ });+ });++ it("switches to a tab that already shows the folder instead of replacing it", () => {+ const store = useRightPanelStore.getState();+ store.openFile(refA, "apps");+ store.openFile(refA, "apps/web/src", 12);++ store.navigateFolder(refA, "file:apps/web/src", "apps", "apps/web/src");+ const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);+ expect(state.activeSurfaceId).toBe("file:apps");+ expect(state.surfaces).toEqual([+ { id: "file:apps", kind: "file", relativePath: "apps", revealLine: null, revealRequestId: 1 },+ ]);+ });++ it("keeps a file's tab when walking up from it, and comes back to it", () => {+ const store = useRightPanelStore.getState();+ const state = () =>+ selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);+ store.openFile(refA, "src/app.ts", 40);++ store.navigateFolder(refA, "file:src/app.ts", "src", "src/app.ts", true);+ expect(state().activeSurfaceId).toBe("file:src");+ expect(state().surfaces).toEqual([+ {+ id: "file:src/app.ts",+ kind: "file",+ relativePath: "src/app.ts",+ revealLine: 40,+ revealRequestId: 1,+ },+ expect.objectContaining({ id: "file:src", folderTrail: "src/app.ts" }),+ ]);++ // The trail's end is the file: its tab comes back as it was, the folder tab goes.+ store.navigateFolder(refA, "file:src", "src/app.ts", "src/app.ts");+ expect(state().activeSurfaceId).toBe("file:src/app.ts");+ expect(state().surfaces).toEqual([+ {+ id: "file:src/app.ts",+ kind: "file",+ relativePath: "src/app.ts",+ revealLine: 40,+ revealRequestId: 1,+ },+ ]);+ });++ it("ignores navigation from a tab that was closed", () => {+ const store = useRightPanelStore.getState();+ store.openFile(refA, "apps");+ const before = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);+ store.navigateFolder(refA, "file:gone", "", "gone");+ expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toBe(+ before,+ );+ });+it("replaces the standalone explorer with peer file surfaces", () => {useRightPanelStore.getState().open(refA, "files");useRightPanelStore.getState().openFile(refA, "src/index.ts");diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.tsindex fa417786a01..35a1545c376 100644--- a/apps/web/src/rightPanelStore.ts+++ b/apps/web/src/rightPanelStore.ts@@ -53,7 +53,12 @@ export type RightPanelSurface =splitDirection?: "horizontal" | "vertical";}| { id: "diff"; kind: "diff" }- | { id: "files"; kind: "files" }+ | {+ id: "files";+ kind: "files";+ /** Set when breadcrumbs moved a folder browser up to the workspace root. */+ folderTrail?: string;+ }| {id: `file:${string}` | `attachment:${string}`;kind: "file";@@ -64,6 +69,11 @@ export type RightPanelSurface =/** Present when the file lives in the thread's attachment store ratherthan at a workspace or host path. */attachment?: ChatFileAttachment;+ /**+ * Set when breadcrumbs moved a folder browser up from a deeper path: the+ * deepest workspace path the breadcrumbs keep offering on the way back down.+ */+ folderTrail?: string;}| {/**@@ -152,6 +162,19 @@ interface RightPanelStoreState {renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;+ /**+ * Moves the folder browser in `surfaceId` to `relativePath` in place, so walking+ * the breadcrumbs does not leave a tab behind per folder. `""` is the workspace+ * root, which is the files explorer. `folderTrail` is kept for the way back down.+ * `keepSource` opens the folder beside the source tab instead, for a file preview.+ */+ navigateFolder: (+ ref: ScopedThreadRef,+ surfaceId: string,+ relativePath: string,+ folderTrail: string,+ keepSource?: boolean,+ ) => void;openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;openPullRequest: (ref: ScopedThreadRef,@@ -471,6 +494,14 @@ export function migratePersistedRightPanelState(persistedState: unknown): {// Removed surfaces: plans render inline, agents in thread lineage.const kind = (surface as { kind?: string }).kind;if (kind === "plan" || kind === "agents") return [];+ if (+ (surface.kind === "file" || surface.kind === "files") &&+ "folderTrail" in surface &&+ typeof surface.folderTrail !== "string"+ ) {+ const { folderTrail: _invalid, ...rest } = surface;+ surface = rest;+ }if (surface.kind === "file") {const revealLine =typeof surface.revealLine === "number" &&@@ -741,6 +772,34 @@ export const useRightPanelStore = create<RightPanelStoreState>()(};}),),+ navigateFolder: (ref, surfaceId, relativePath, folderTrail, keepSource = false) =>+ set((state) =>+ userAction(state, scopedThreadKey(ref), (current) => {+ const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);+ if (index < 0) return current;+ const trail = folderTrail === relativePath ? {} : { folderTrail };+ const target: RightPanelSurface =+ relativePath === ""+ ? { ...singletonSurface("files"), ...trail }+ : { ...fileSurface(relativePath, null, 1), ...trail };+ const source = current.surfaces[index]!;+ // A tab already showing the target wins, so its state is never replaced.+ const existing = current.surfaces.some(+ (surface, i) => i !== index && surface.id === target.id,+ );+ const surfaces = current.surfaces.flatMap((surface, i) => {+ if (i === index) {+ const kept = keepSource ? [source] : [];+ return existing ? kept : [...kept, target];+ }+ // Like openFile: a file surface replaces the standalone explorer.+ return !existing && target.kind === "file" && surface.kind === "files"+ ? []+ : [surface];+ });+ return { ...current, isOpen: true, activeSurfaceId: target.id, surfaces };+ }),+ ),openAttachment: (ref, attachment) =>set((state) =>userAction(state, scopedThreadKey(ref), (current) => {