diff --git a/docs/webui.md b/docs/webui.md index 2b5d2006c..5f5f26ce9 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -293,13 +293,17 @@ or a result you must retain. Use the workspace picker to browse folders on the connected nanobot host, enter an absolute path, or return to recent and starred projects; favorites persist -across gateway restarts. The title identifies the host. Project paths refer to +across gateway restarts. The host name appears above saved locations. Project paths refer to that machine, not the browser's filesystem. -Use the breadcrumbs, Back, Forward, and Parent folder controls to navigate. -**Filter this folder** only filters the current directory. **Edit path** (or -**Cmd/Ctrl+Shift+G**) accepts a host path; Tab completes it and Enter opens it. -Browsing does not change the workspace until you choose **Select folder**. +Use the breadcrumb nodes or Back and Forward controls to navigate. **Last +visited folder** returns directly to the folder you most recently left, +restoring its directory columns, selected rows, filter, and scroll positions. +**Filter this folder** only filters the current directory. Click the empty area +in the path bar or press **Cmd/Ctrl+Shift+G** to enter a host path; Tab completes +it and Enter opens it. Click outside the input or press Escape to cancel path +editing; **Confirm** confirms the edited path. +Browsing does not change the workspace until you choose **Confirm**. **Cancel** leaves the current workspace unchanged. Desktop uses directory columns with Shift+wheel horizontal scrolling; narrow screens show one folder at a time, with favorites and recent projects under **Saved locations**. diff --git a/webui/src/components/SidebarSelectionHighlight.tsx b/webui/src/components/SidebarSelectionHighlight.tsx index 6d112188d..fb0b4dbea 100644 --- a/webui/src/components/SidebarSelectionHighlight.tsx +++ b/webui/src/components/SidebarSelectionHighlight.tsx @@ -62,10 +62,19 @@ export function SidebarSelectionHighlight({ const firstPosition = !positionedRef.current; if (firstPosition) highlight.style.transitionProperty = "none"; - highlight.style.width = `${targetRect.width}px`; - highlight.style.height = `${targetRect.height}px`; - highlight.style.transform = `translate3d(${targetRect.left - containerRect.left}px, ${ - targetRect.top - containerRect.top + // Align the paint origin and destination to layout pixels. A fractional + // origin rasterized before translation can leave seams beside row backgrounds. + const snap = Math.round; + const originLeft = snap(containerRect.left); + const originTop = snap(containerRect.top); + const targetLeft = snap(targetRect.left); + const targetTop = snap(targetRect.top); + highlight.style.left = `${originLeft - containerRect.left}px`; + highlight.style.top = `${originTop - containerRect.top}px`; + highlight.style.width = `${snap(targetRect.right) - targetLeft}px`; + highlight.style.height = `${snap(targetRect.bottom) - targetTop}px`; + highlight.style.transform = `translate3d(${targetLeft - originLeft}px, ${ + targetTop - originTop }px, 0)`; highlight.style.opacity = "1"; positionedRef.current = true; diff --git a/webui/src/components/thread/WorkspaceControls.tsx b/webui/src/components/thread/WorkspaceControls.tsx index 0aedba3f4..faebc0aee 100644 --- a/webui/src/components/thread/WorkspaceControls.tsx +++ b/webui/src/components/thread/WorkspaceControls.tsx @@ -1,7 +1,7 @@ import { FullAccessIcon, WorkspaceIcon, RestrictedAccessIcon } from "@/components/icons/product-icons"; import type { HTMLAttributes, ReactElement } from "react"; import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { ArrowLeft, ArrowRight, ArrowUp, Check, ChevronRight, FolderSearch, Pencil, Search, Star, X } from "lucide-react"; +import { ArrowLeft, ArrowRight, Check, ChevronRight, FolderSearch, History, Search, Star } from "lucide-react"; import { useTranslation } from "react-i18next"; import { ToggleButton } from "@/components/settings/ToggleButton"; import { Button } from "@/components/ui/button"; @@ -9,6 +9,7 @@ import { floatingItemClassName, floatingItemFocusClassName } from "@/components/ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Input } from "@/components/ui/input"; import { Dialog, DialogContent, DialogTrigger, DialogTitle, DialogDescription } from "@/components/ui/dialog"; +import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/components/SidebarSelectionHighlight"; import type { WorkspaceScopePayload, ProjectDirectory, WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types"; import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache"; import { useMediaQuery } from "@/hooks/useMediaQuery"; @@ -33,6 +34,13 @@ function WorkspaceFavoriteButton({ path, pinned, busy, onToggle }: { type PickerOption = ProjectDirectory & { kind: "directory" | "manual" }; type PickerColumn = { path: string; parent: string | null; options: PickerOption[]; selectedPath: string | null; hidden: boolean }; +type PickerAncestor = Pick; +type PickerVisit = { path: string; ancestors: PickerAncestor[]; filter: string; scrollLeft: number | null; scrollTops: number[] }; +type PickerHistory = { visits: PickerVisit[]; index: number; previous: PickerVisit | null; revision: number }; + +function directoryVisit(path: string, ancestors: PickerAncestor[] = [], scrollTops: number[] = []): PickerVisit { + return { path, ancestors: ancestors.map(({ path, parent, selectedPath }) => ({ path, parent, selectedPath })), filter: "", scrollLeft: null, scrollTops }; +} function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) { return ( @@ -55,9 +63,12 @@ function PickerToolButton({ label, disabled, onClick, children }: { const DIRECTORY_ROW_HEIGHT = 44; const DIRECTORY_OVERSCAN = 4; -function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: { +function WorkspaceDirectoryColumn({ options, activeIndex, selectedPath, initialScrollTop, visitRevision, renderOption, children, ...props }: { options: PickerOption[]; activeIndex: number | null; + selectedPath: string | null; + initialScrollTop: number; + visitRevision: number; renderOption: (option: PickerOption, index: number) => ReactElement; } & HTMLAttributes) { const viewportRef = useRef(null); @@ -75,9 +86,9 @@ function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children useLayoutEffect(() => { const viewport = viewportRef.current; if (!viewport) return; - viewport.scrollTop = 0; - setFirstRow(0); - }, [options]); + viewport.scrollTop = initialScrollTop; + setFirstRow(Math.floor(viewport.scrollTop / DIRECTORY_ROW_HEIGHT)); + }, [options, initialScrollTop, visitRevision]); useLayoutEffect(() => { const viewport = viewportRef.current; if (!viewport || activeIndex === null) return; @@ -91,14 +102,15 @@ function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children const end = Math.min(options.length, firstRow + visibleRows + DIRECTORY_OVERSCAN); return (
setFirstRow(Math.floor(event.currentTarget.scrollTop / DIRECTORY_ROW_HEIGHT))}> -
+ {options.slice(start, end).map((option, offset) => { const index = start + offset; return
{renderOption(option, index)}
; })} -
+ {children}
); @@ -135,12 +147,10 @@ function WorkspaceDirectorySkeleton() { function WorkspacePickerPath({ path }: { path: string }) { const parts = workspacePathCompletionQuery(path); return ( - - - {parts?.path ?? path} - {parts?.query && {parts.query}} - - + + {parts?.path ?? path} + {parts?.query && {parts.query}} + ); } @@ -172,15 +182,20 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, const [open, setOpen] = useState(false); const [pathDraft, setPathDraft] = useState(""); const [editingPath, setEditingPath] = useState(false); - const [filterQuery, setFilterQuery] = useState(""); const [showLocations, setShowLocations] = useState(false); - const [history, setHistory] = useState<{ paths: string[]; index: number }>({ paths: [], index: 0 }); + const [hoveredLocation, setHoveredLocation] = useState(null); + const [history, setHistory] = useState(() => ({ + visits: [directoryVisit(scope?.project_path ?? defaultScope?.project_path ?? "")], index: 0, previous: null, revision: 0, + })); + const currentVisit = history.visits[history.index]; + const basePath = currentVisit.path; + const filterQuery = currentVisit.filter; const compact = useMediaQuery("(max-width: 639px)"); - const [basePath, setBasePath] = useState(scope?.project_path ?? defaultScope?.project_path ?? ""); const [catalog, setCatalog] = useState(null); const [directory, setDirectory] = useState(null); const [loading, setLoading] = useState(false); const [showHidden, setShowHidden] = useState(false); + const [ancestorData, setAncestorData] = useState<{ hidden: boolean; listings: WorkspaceDirectoriesPayload[] }>({ hidden: false, listings: [] }); const [revision, setRevision] = useState(0); const [directoryError, setDirectoryError] = useState(null); const [pathError, setPathError] = useState(null); @@ -189,7 +204,6 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, const [activeIndex, setActiveIndex] = useState(0); const [activeColumn, setActiveColumn] = useState(0); const [highlightActive, setHighlightActive] = useState(false); - const [previousColumns, setPreviousColumns] = useState([]); const columnsRef = useRef(null); const breadcrumbRef = useRef(null); const attachBreadcrumb = useCallback((element: HTMLElement | null) => { @@ -203,12 +217,12 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, setColumnsElement(element); }, []); const [visibleColumns, setVisibleColumns] = useState(3); - const columnCount = Math.min(visibleColumns, previousColumns.length + 1); const pickerSession = useRef(0); const completionRequest = useRef(0); const triggerRef = useRef(null); - const keyboardInteraction = useRef(false); + const [keyboardInteraction, setKeyboardInteraction] = useState(false); const inputRef = useRef(null); + const confirmRef = useRef(null); const optionsId = useId(); const errorId = useId(); const currentProjectScope = selectedProjectScope(scope, defaultScope); @@ -217,24 +231,31 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false; const canBrowse = controls?.can_browse_directories === true && !!onBrowseDirectories; const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]); + const previousColumns = useMemo(() => currentVisit.ancestors.map(ancestor => { + const listing = directoryCache?.peek(ancestor.path, "", showHidden, true) + ?? (ancestorData.hidden === showHidden ? ancestorData.listings.find(listing => sameWorkspacePath(listing.path, ancestor.path)) : undefined); + return { ...ancestor, hidden: showHidden, options: listing?.entries.map(entry => ({ ...entry, kind: "directory" as const })) ?? [] }; + }), [currentVisit.ancestors, directoryCache, showHidden, ancestorData]); const absoluteDraft = isAbsoluteWorkspacePath(pathDraft); const requestedPath = editingPath && absoluteDraft ? pathDraft.trim() : basePath; + const previewingPath = editingPath && !sameWorkspacePath(pathDraft.trim(), basePath); + const displayedAncestors = previewingPath ? [] : previousColumns; + const currentColumnIndex = displayedAncestors.length; + const columnCount = Math.min(visibleColumns, currentColumnIndex + 1); const folderQuery = editingPath ? "" : filterQuery.trim(); useEffect(() => { pickerSession.current += 1; completionRequest.current += 1; if (!open) return; - setPreviousColumns([]); setActiveColumn(0); setHighlightActive(false); const initialPath = scope?.project_path ?? defaultScope?.project_path ?? ""; setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? ""); - setBasePath(initialPath); - setHistory({ paths: [initialPath], index: 0 }); + setHistory(current => ({ visits: [directoryVisit(initialPath)], index: 0, previous: null, revision: current.revision + 1 })); setEditingPath(false); - setFilterQuery(""); setShowLocations(false); + setHoveredLocation(null); setDirectory(null); setActiveIndex(0); setPathError(null); @@ -284,19 +305,18 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, return () => window.cancelAnimationFrame(frame); }, [open, pickingFolder, pathError, editingPath, canBrowse]); - const ancestorPaths = JSON.stringify(previousColumns.filter(column => column.hidden !== showHidden).map(column => column.path)); + const ancestorPaths = JSON.stringify(currentVisit.ancestors.map(column => column.path)); useEffect(() => { if (!open || !canBrowse || !directoryCache) return; const paths: string[] = JSON.parse(ancestorPaths); - if (!paths.length) return; + if (!paths.length) { + setAncestorData(current => current.listings.length ? { hidden: showHidden, listings: [] } : current); + return; + } let active = true; Promise.all(paths.map(path => directoryCache.load(path, "", showHidden, true))).then(results => { if (!active) return; - setPreviousColumns(columns => columns.map(column => { - const result = results.find(result => sameWorkspacePath(column.path, result.path)); - if (!result) return column; - return { ...column, hidden: showHidden, options: result.entries.map(entry => ({ ...entry, kind: "directory" as const })) }; - })); + setAncestorData({ hidden: showHidden, listings: results }); }).catch((err: Error) => { if (active) setPathError(err.message); }); return () => { active = false; }; }, [open, canBrowse, directoryCache, ancestorPaths, showHidden]); @@ -315,6 +335,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, const viewport = columnsElement; if (!open || !viewport) return; const onWheel = (event: WheelEvent) => { + setKeyboardInteraction(false); if (!event.shiftKey || event.ctrlKey || event.metaKey || viewport.scrollWidth <= viewport.clientWidth) return; const delta = event.deltaX || event.deltaY; if (!delta) return; @@ -328,8 +349,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, useLayoutEffect(() => { const viewport = columnsRef.current; - if (viewport) viewport.scrollLeft = viewport.clientWidth * Math.max(0, previousColumns.length + 1 - columnCount) / columnCount; - }, [previousColumns.length, columnCount]); + if (!viewport) return; + viewport.scrollLeft = !previewingPath && currentVisit.scrollLeft !== null + ? currentVisit.scrollLeft + : viewport.clientWidth * Math.max(0, currentColumnIndex + 1 - columnCount) / columnCount; + }, [history.revision, currentColumnIndex, columnCount, currentVisit.scrollLeft, previewingPath]); useLayoutEffect(() => { const viewport = columnsRef.current; @@ -341,13 +365,13 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, else if (right > viewport.scrollLeft + viewport.clientWidth) viewport.scrollLeft = right - viewport.clientWidth; }, [activeColumn, highlightActive, columnCount]); - function changeDraft(value: string, resetColumns = true) { + function changeDraft(value: string, query = "") { setHighlightActive(false); - if (resetColumns) { setPreviousColumns([]); setActiveColumn(0); } + setActiveColumn(sameWorkspacePath(value.trim(), basePath) ? previousColumns.length : 0); completionRequest.current += 1; setPathDraft(value); const absolute = isAbsoluteWorkspacePath(value); - const cached = absolute ? directoryCache?.peek(value.trim(), "", showHidden, true) : null; + const cached = absolute ? directoryCache?.peek(value.trim(), query, showHidden, true) : null; setDirectory(cached ?? null); setLoading(canBrowse && absolute && !cached); setDirectoryError(null); @@ -357,26 +381,51 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, function focusDirectory() { window.requestAnimationFrame(() => columnsRef.current?.querySelector("[data-current-directory]")?.focus()); } - function navigate(path: string, columnIndex?: number, keepEditing = false, historyIndex?: number) { - const source = columnIndex === undefined ? undefined : columns[columnIndex]; - const ancestors = columnIndex === undefined ? [] : columns.slice(0, columnIndex); - if (source?.options.length && !sameWorkspacePath(source.path, path)) ancestors.push({ ...source, selectedPath: path }); - setPreviousColumns(ancestors); - setActiveColumn(ancestors.length); - setBasePath(path); - setFilterQuery(""); + function captureVisit(): PickerVisit { + // A draft preview is not a committed navigation visit. + if (previewingPath) return currentVisit; + const viewport = columnsRef.current; + const scrollTops = [...currentVisit.scrollTops]; + viewport?.querySelectorAll('[data-workspace-column]').forEach(column => { + scrollTops[Number(column.dataset.workspaceColumn)] = column.scrollTop; + }); + return { ...currentVisit, scrollLeft: viewport?.scrollLeft ?? null, scrollTops }; + } + function visitDirectory(visit: PickerVisit, keepEditing = false, historyIndex?: number) { + const departed = captureVisit(); setShowLocations(false); setEditingPath(keepEditing); setHistory(current => { - if (historyIndex !== undefined) return { ...current, index: historyIndex }; - if (sameWorkspacePath(current.paths[current.index], path)) return current; - return { paths: [...current.paths.slice(0, current.index + 1), path], index: current.index + 1 }; + const visits = [...current.visits]; + visits[current.index] = departed; + const previous = sameWorkspacePath(departed.path, visit.path) ? current.previous : departed; + if (historyIndex !== undefined) return { visits, index: historyIndex, previous, revision: current.revision + 1 }; + if (sameWorkspacePath(departed.path, visit.path)) { + visits[current.index] = visit; + return { visits, index: current.index, previous, revision: current.revision + 1 }; + } + return { visits: [...visits.slice(0, current.index + 1), visit], index: current.index + 1, previous, revision: current.revision + 1 }; }); - changeDraft(workspaceDirectoryPrefix(path), false); + changeDraft(workspaceDirectoryPrefix(visit.path), visit.filter); + setActiveColumn(visit.ancestors.length); setRevision(value => value + 1); if (keepEditing) inputRef.current?.focus(); else focusDirectory(); } + function navigate(path: string, columnIndex?: number, keepEditing = false) { + const source = columnIndex === undefined ? undefined : columns[columnIndex]; + const ancestors = columnIndex === undefined ? [] : columns.slice(0, columnIndex); + if (source?.options.length && !sameWorkspacePath(source.path, path)) ancestors.push({ ...source, selectedPath: path }); + visitDirectory(directoryVisit(path, ancestors, captureVisit().scrollTops.slice(0, ancestors.length)), keepEditing); + } + function setFilterQuery(filter: string) { + setHistory(current => { + const visits = [...current.visits]; + const visit = visits[current.index]; + visits[current.index] = { ...visit, filter, scrollTops: visit.scrollTops.slice(0, visit.ancestors.length) }; + return { ...current, visits }; + }); + } const applyProjectPath = useCallback((path: string, name?: string) => { const base = scope ?? defaultScope; @@ -434,31 +483,46 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, if (!canBrowse) { void chooseProject(project.path, project.name); return; } navigate(project.path); } - const columns: PickerColumn[] = [...previousColumns, { path: directory?.path ?? requestedPath, parent: directory?.parent ?? null, options, selectedPath: null, hidden: showHidden }]; + const columns: PickerColumn[] = [...displayedAncestors, { path: directory?.path ?? requestedPath, parent: directory?.parent ?? null, options, selectedPath: null, hidden: showHidden }]; const activeOptions = columns[activeColumn]?.options ?? options; const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0)); - const selectionPath = canBrowse ? (!loading && directory && !directory.partial ? directory.path : null) : (pathDraft.trim() ? absoluteDraft ? pathDraft.trim() : null : scope?.project_path ?? defaultScope?.project_path); + const browsedSelectionPath = directoryError || directory?.partial ? null : directory?.path ?? basePath; + const resolvedDraftPath = !loading && directory && !directory.partial ? directory.path : null; + const selectionPath = canBrowse + ? editingPath ? resolvedDraftPath : browsedSelectionPath + : (pathDraft.trim() ? absoluteDraft ? pathDraft.trim() : null : scope?.project_path ?? defaultScope?.project_path); const displayedError = pathError ?? error ?? directoryError; const currentPath = editingPath ? basePath : directory?.path ?? basePath; + let savedSelectionJoin: "top" | "bottom" | null = null; + for (const projects of [favorites, recentProjects]) { + const selectedIndex = projects.findIndex(project => sameWorkspacePath(project.path, currentPath)); + if (selectedIndex < 0 || !hoveredLocation) continue; + if (selectedIndex > 0 && sameWorkspacePath(projects[selectedIndex - 1].path, hoveredLocation)) savedSelectionJoin = "top"; + else if (selectedIndex + 1 < projects.length && sameWorkspacePath(projects[selectedIndex + 1].path, hoveredLocation)) savedSelectionJoin = "bottom"; + } const breadcrumbs = workspaceBreadcrumbs(currentPath); const parentPath = directory?.parent; const hostName = catalog?.host?.name ?? directory?.host; - const hostPlatform = catalog?.host?.platform ?? directory?.platform; useLayoutEffect(() => { if (breadcrumbRef.current) breadcrumbRef.current.scrollLeft = breadcrumbRef.current.scrollWidth; }, [currentPath, editingPath, open]); function editPath() { + const visit = captureVisit(); + setHistory(current => { + const visits = [...current.visits]; + visits[current.index] = { ...visit, filter: "" }; + return { ...current, visits }; + }); setEditingPath(true); - setFilterQuery(""); changeDraft(workspaceDirectoryPrefix(currentPath)); window.requestAnimationFrame(() => inputRef.current?.select()); } - function cancelPathEditing() { + function cancelPathEditing(focusColumns = true) { setEditingPath(false); changeDraft(workspaceDirectoryPrefix(basePath)); - focusDirectory(); + if (focusColumns) focusDirectory(); } async function completePath(keepEditing = true) { @@ -490,14 +554,14 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, function moveHistory(offset: number) { const index = history.index + offset; - if (index >= 0 && index < history.paths.length) navigate(history.paths[index], undefined, false, index); + if (index >= 0 && index < history.visits.length) visitDirectory(history.visits[index], false, index); } - const filterToolbar = canBrowse && !(compact && editingPath) &&
+ const filterToolbar = canBrowse && !(compact && editingPath) &&
{compact && }
- { setFilterQuery(event.target.value); setActiveIndex(0); setActiveColumn(previousColumns.length); setHighlightActive(false); }} className="h-11 rounded-control border-transparent bg-muted/60 pl-8 text-[16px] shadow-none sm:h-9 sm:text-[12px]" /> + { setFilterQuery(event.target.value); setActiveIndex(0); setActiveColumn(currentColumnIndex); setHighlightActive(false); }} className={cn("h-11 rounded-control border-transparent pl-8 text-[16px] shadow-none sm:h-9 sm:text-[12px]", compact ? "bg-muted/60" : "bg-background/80")} />
; @@ -508,7 +572,7 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, - @@ -516,9 +580,9 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, { event.preventDefault(); if (canBrowse) focusDirectory(); else inputRef.current?.focus(); }} - onPointerDownCapture={() => { keyboardInteraction.current = false; }} + onPointerDownCapture={() => setKeyboardInteraction(false)} onKeyDownCapture={event => { - keyboardInteraction.current = true; + if (!["Alt", "Control", "Meta", "Shift"].includes(event.key)) setKeyboardInteraction(true); if (!canBrowse || pickingFolder || event.nativeEvent.isComposing) return; if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "g") { event.preventDefault(); editPath(); } else if (event.altKey && event.key === "ArrowLeft") { event.preventDefault(); moveHistory(-1); } @@ -526,21 +590,18 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, else if (event.altKey && event.key === "ArrowUp" && parentPath) { event.preventDefault(); navigate(parentPath); } }} onEscapeKeyDown={event => { if (editingPath) { event.preventDefault(); cancelPathEditing(); } }} - onCloseAutoFocus={event => { if (!keyboardInteraction.current) event.preventDefault(); }}> -
- {t("workspace.picker.title")} - {hostName && - {t("workspace.picker.host", { name: hostName })} - } -
+ onCloseAutoFocus={event => { if (!keyboardInteraction) event.preventDefault(); }}> + {t("workspace.picker.title")} {t("workspace.picker.description")} -
+
{canBrowse &&
moveHistory(-1)}> - {!compact && = history.paths.length - 1} onClick={() => moveHistory(1)}>} - parentPath && navigate(parentPath)}> + {!compact && = history.visits.length - 1} onClick={() => moveHistory(1)}>} + history.previous && visitDirectory(history.previous)}>
} - {editingPath || !canBrowse ? changeDraft(event.target.value)} placeholder={t("workspace.dialog.manual")} aria-label={t("workspace.dialog.manual")} aria-invalid={displayedError ? true : undefined} aria-describedby={displayedError ? errorId : undefined} className="h-9 min-w-0 flex-1 rounded-control text-[16px] sm:text-[13px]" onKeyDown={event => { +
+ {editingPath || !canBrowse ? changeDraft(event.target.value)} onBlur={event => { if (canBrowse && !keyboardInteraction && event.relatedTarget !== confirmRef.current) cancelPathEditing(false); }} placeholder={t("workspace.dialog.manual")} aria-label={t("workspace.dialog.manual")} aria-invalid={displayedError ? true : undefined} aria-describedby={displayedError ? errorId : undefined} className="h-9 min-w-0 flex-1 rounded-control text-[16px] sm:text-[13px]" onKeyDown={event => { if (event.nativeEvent.isComposing) return; if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) { event.preventDefault(); @@ -554,46 +615,54 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, else if ((event.ctrlKey || event.metaKey) && selectionPath) void chooseProject(selectionPath); else void completePath(false); } - }} /> :
+ {!compact && filterToolbar}
{compact && filterToolbar} -
- {(!compact || showLocations || !canBrowse) &&
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 2cad48005..261cf729b 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -2498,18 +2498,19 @@ "loading": "Loading folders…", "truncated": "Showing 500 folders. Continue typing the path to narrow the list.", "hidden": "Show hidden folders", - "select": "Select folder", + "select": "Confirm", "title": "Choose a working folder", "host": "Host: {{name}}", "back": "Back", "forward": "Forward", + "history": "Last visited folder", "up": "Parent folder", "editPath": "Edit path", "cancelPath": "Cancel path editing", "location": "Current location", - "filter": "Filter this folder…", + "filter": "Filter this folder", "pathNotFound": "No matching folder. Check the path and try again.", - "empty": "This folder is empty. You can still select it.", + "empty": "No subfolders", "noMatches": "No matching folders.", "retry": "Try again", "cancel": "Cancel", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 2d8e4e2df..49adf1226 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -2299,18 +2299,19 @@ "loading": "Cargando carpetas…", "truncated": "Se muestran 500 carpetas. Sigue escribiendo la ruta para reducir la lista.", "hidden": "Mostrar carpetas ocultas", - "select": "Seleccionar carpeta", + "select": "Confirmar", "title": "Elegir carpeta de trabajo", "host": "Servidor: {{name}}", "back": "Atrás", "forward": "Adelante", + "history": "Última carpeta visitada", "up": "Carpeta superior", "editPath": "Editar ruta", "cancelPath": "Cancelar edición de ruta", "location": "Ubicación actual", - "filter": "Filtrar esta carpeta…", + "filter": "Filtrar esta carpeta", "pathNotFound": "No hay carpetas coincidentes. Comprueba la ruta.", - "empty": "Esta carpeta está vacía. Puedes seleccionarla igualmente.", + "empty": "Sin subcarpetas", "noMatches": "No hay carpetas coincidentes.", "retry": "Reintentar", "cancel": "Cancelar", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 5425f6598..c85e34d45 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -2298,18 +2298,19 @@ "loading": "Chargement des dossiers…", "truncated": "500 dossiers affichés. Continuez à saisir le chemin pour réduire la liste.", "hidden": "Afficher les dossiers cachés", - "select": "Choisir ce dossier", + "select": "Confirmer", "title": "Choisir un dossier de travail", "host": "Hôte : {{name}}", "back": "Précédent", "forward": "Suivant", + "history": "Dernier dossier visité", "up": "Dossier parent", "editPath": "Modifier le chemin", "cancelPath": "Annuler la saisie du chemin", "location": "Emplacement actuel", - "filter": "Filtrer ce dossier…", + "filter": "Filtrer ce dossier", "pathNotFound": "Aucun dossier correspondant. Vérifiez le chemin.", - "empty": "Ce dossier est vide. Vous pouvez tout de même le choisir.", + "empty": "Aucun sous-dossier", "noMatches": "Aucun dossier correspondant.", "retry": "Réessayer", "cancel": "Annuler", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index a5050d655..de0487cf4 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -2298,18 +2298,19 @@ "loading": "Memuat folder…", "truncated": "Menampilkan 500 folder. Lanjutkan mengetik jalur untuk mempersempit daftar.", "hidden": "Tampilkan folder tersembunyi", - "select": "Pilih folder", + "select": "Konfirmasi", "title": "Pilih folder kerja", "host": "Host: {{name}}", "back": "Kembali", "forward": "Maju", + "history": "Folder terakhir dikunjungi", "up": "Folder induk", "editPath": "Edit jalur", "cancelPath": "Batalkan pengeditan jalur", "location": "Lokasi saat ini", - "filter": "Filter folder ini…", + "filter": "Filter folder ini", "pathNotFound": "Tidak ada folder yang cocok. Periksa jalurnya.", - "empty": "Folder ini kosong. Anda tetap dapat memilihnya.", + "empty": "Tidak ada subfolder", "noMatches": "Tidak ada folder yang cocok.", "retry": "Coba lagi", "cancel": "Batal", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 59dbaaab7..2072bad8a 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -2298,18 +2298,19 @@ "loading": "フォルダーを読み込み中…", "truncated": "500 個のフォルダーを表示しています。パスの入力を続けて絞り込んでください。", "hidden": "隠しフォルダーを表示", - "select": "フォルダーを選択", + "select": "確認", "title": "作業フォルダーを選択", "host": "ホスト:{{name}}", "back": "戻る", "forward": "進む", + "history": "直前に訪問したフォルダー", "up": "親フォルダー", "editPath": "パスを編集", "cancelPath": "パスの編集をキャンセル", "location": "現在の場所", - "filter": "このフォルダーを絞り込み…", + "filter": "このフォルダーを絞り込み", "pathNotFound": "一致するフォルダーがありません。パスを確認してください。", - "empty": "空のフォルダーです。このフォルダーも選択できます。", + "empty": "サブフォルダーなし", "noMatches": "一致するフォルダーがありません。", "retry": "再試行", "cancel": "キャンセル", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 13484bf15..9d2ab9f3c 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -2298,18 +2298,19 @@ "loading": "폴더 불러오는 중…", "truncated": "폴더 500개를 표시합니다. 경로를 계속 입력하여 목록을 좁히세요.", "hidden": "숨김 폴더 표시", - "select": "폴더 선택", + "select": "확인", "title": "작업 폴더 선택", "host": "호스트: {{name}}", "back": "뒤로", "forward": "앞으로", + "history": "직전에 방문한 폴더", "up": "상위 폴더", "editPath": "경로 편집", "cancelPath": "경로 편집 취소", "location": "현재 위치", - "filter": "현재 폴더 필터링…", + "filter": "현재 폴더 필터링", "pathNotFound": "일치하는 폴더가 없습니다. 경로를 확인해 주세요.", - "empty": "빈 폴더입니다. 이 폴더도 선택할 수 있습니다.", + "empty": "하위 폴더 없음", "noMatches": "일치하는 폴더가 없습니다.", "retry": "다시 시도", "cancel": "취소", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 0a03914ff..c6d48ca46 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -2312,18 +2312,19 @@ "loading": "Carregando pastas…", "truncated": "Exibindo 500 pastas. Continue digitando o caminho para reduzir a lista.", "hidden": "Mostrar pastas ocultas", - "select": "Selecionar pasta", + "select": "Confirmar", "title": "Escolher pasta de trabalho", "host": "Host: {{name}}", "back": "Voltar", "forward": "Avançar", + "history": "Última pasta visitada", "up": "Pasta superior", "editPath": "Editar caminho", "cancelPath": "Cancelar edição do caminho", "location": "Localização atual", - "filter": "Filtrar esta pasta…", + "filter": "Filtrar esta pasta", "pathNotFound": "Nenhuma pasta correspondente. Verifique o caminho.", - "empty": "Esta pasta está vazia. Você ainda pode selecioná-la.", + "empty": "Sem subpastas", "noMatches": "Nenhuma pasta correspondente.", "retry": "Tentar novamente", "cancel": "Cancelar", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index a44dd20b2..d35a7c9d9 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -2298,18 +2298,19 @@ "loading": "Đang tải thư mục…", "truncated": "Hiển thị 500 thư mục. Tiếp tục nhập đường dẫn để thu hẹp danh sách.", "hidden": "Hiện thư mục ẩn", - "select": "Chọn thư mục", + "select": "Xác nhận", "title": "Chọn thư mục làm việc", "host": "Máy chủ: {{name}}", "back": "Quay lại", "forward": "Tiến tới", + "history": "Thư mục vừa truy cập", "up": "Thư mục cha", "editPath": "Sửa đường dẫn", "cancelPath": "Hủy sửa đường dẫn", "location": "Vị trí hiện tại", - "filter": "Lọc thư mục này…", + "filter": "Lọc thư mục này", "pathNotFound": "Không có thư mục phù hợp. Hãy kiểm tra đường dẫn.", - "empty": "Thư mục trống. Bạn vẫn có thể chọn thư mục này.", + "empty": "Không có thư mục con", "noMatches": "Không có thư mục phù hợp.", "retry": "Thử lại", "cancel": "Hủy", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 0014aa9fd..58d12b427 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -2498,18 +2498,19 @@ "loading": "正在加载文件夹…", "truncated": "已显示 500 个文件夹,继续输入路径以缩小范围。", "hidden": "显示隐藏文件夹", - "select": "选择此文件夹", + "select": "确认", "title": "选择工作文件夹", "host": "主机:{{name}}", "back": "返回", "forward": "前进", + "history": "上一次访问的目录", "up": "上级文件夹", "editPath": "编辑路径", "cancelPath": "取消路径编辑", "location": "当前位置", - "filter": "筛选当前文件夹…", + "filter": "筛选当前文件夹", "pathNotFound": "没有匹配的文件夹,请检查路径后重试。", - "empty": "文件夹为空,仍可选择它。", + "empty": "无子文件夹", "noMatches": "没有匹配的文件夹。", "retry": "重试", "cancel": "取消", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 565063512..93fa4e283 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -2298,18 +2298,19 @@ "loading": "正在載入資料夾…", "truncated": "已顯示 500 個資料夾,繼續輸入路徑以縮小範圍。", "hidden": "顯示隱藏資料夾", - "select": "選擇此資料夾", + "select": "確認", "title": "選擇工作資料夾", "host": "主機:{{name}}", "back": "返回", "forward": "前進", + "history": "上一次造訪的目錄", "up": "上層資料夾", "editPath": "編輯路徑", "cancelPath": "取消路徑編輯", "location": "目前位置", - "filter": "篩選目前資料夾…", + "filter": "篩選目前資料夾", "pathNotFound": "沒有相符的資料夾,請檢查路徑後重試。", - "empty": "資料夾為空,仍可選擇它。", + "empty": "無子資料夾", "noMatches": "沒有相符的資料夾。", "retry": "重試", "cancel": "取消", diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 422ec5009..8ebe6d5b7 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -381,7 +381,7 @@ describe("App layout", () => { }] }, }); render(); - await screen.findByRole("textbox"); + await screen.findByRole("textbox", {}, { timeout: 5_000 }); if (supported) await screen.findByRole("button", { name: /Config check Running/ }); else expect(screen.queryByText("Config check")).not.toBeInTheDocument(); const reads = vi.mocked(fetch).mock.calls.filter(([url]) => String(url).endsWith("/subagents")); @@ -1173,12 +1173,12 @@ describe("App layout", () => { await waitFor(() => expect(connectSpy).toHaveBeenCalled()); fireEvent.click(await screen.findByRole("button", { name: "Switch working directory" })); - fireEvent.click(screen.getByRole("button", { name: "Edit path" })); + fireEvent.click(screen.getByRole("button", { name: /^Edit path:/ })); fireEvent.change(await screen.findByRole("combobox"), { target: { value: projectPath }, }); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - fireEvent.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + fireEvent.click(screen.getByRole("button", { name: "Confirm" })); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); const message = screen.getByLabelText("Message input"); @@ -1193,7 +1193,7 @@ describe("App layout", () => { "The gateway rejected this project or access mode. Choose an existing project or a different access mode, then try again.", ); fireEvent.click(projectButton); - fireEvent.click(screen.getByRole("button", { name: "Edit path" })); + fireEvent.click(screen.getByRole("button", { name: /^Edit path:/ })); const pathInput = await screen.findByRole("combobox"); expect(pathInput).toHaveValue(`${projectPath}\\`); expect(pathInput).toHaveAttribute("aria-invalid", "true"); diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx index a1f6839db..dc24dacec 100644 --- a/webui/src/tests/thread-composer.test.tsx +++ b/webui/src/tests/thread-composer.test.tsx @@ -1500,15 +1500,15 @@ describe("ThreadComposer", () => { expect(await screen.findByRole("button", { name: "/Users/test/.nanobot/workspace" })).toBeInTheDocument(); expect(screen.getByRole("dialog")).toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); fireEvent.change(input, { target: { value: "relative/project" } }); expect(screen.queryByRole("option", { name: "relative/project" })).not.toBeInTheDocument(); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); fireEvent.change(input, { target: { value: "/Users/test/project-alpha" } }); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/Users/test/project-alpha", @@ -1518,11 +1518,11 @@ describe("ThreadComposer", () => { })); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const reopenedInput = await screen.findByRole("combobox"); fireEvent.change(reopenedInput, { target: { value: "~/Pictures/Photos" } }); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onWorkspaceScopeChange).toHaveBeenLastCalledWith(expect.objectContaining({ project_path: "/Users/test/Pictures/Photos", @@ -1563,7 +1563,7 @@ describe("ThreadComposer", () => { await user.click(screen.getByRole("button", { name: "Switch working directory" })); fireEvent.change(await screen.findByRole("combobox"), { target: { value: selectedPath } }); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); fireEvent.keyDown(screen.getByRole("combobox"), { key: "Enter" }); await waitFor(() => expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: selectedPath }))); }); @@ -1676,9 +1676,9 @@ describe("ThreadComposer", () => { await user.click(screen.getByRole("button", { name: "Switch working directory" })); expect(screen.getByRole("dialog", { name: "Choose a working folder" })).toBeInTheDocument(); await user.click(await screen.findByRole("option", { name: project.path })); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); expect(onWorkspaceScopeChange).not.toHaveBeenCalled(); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await user.click(screen.getByRole("button", { name: "Confirm" })); await waitFor(() => expect(screen.queryByRole("dialog", { name: "Choose a working folder" })).not.toBeInTheDocument()); expect(onResolveWorkspaceProject).toHaveBeenCalledWith(project.path); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ @@ -1721,8 +1721,8 @@ describe("ThreadComposer", () => { fireEvent.change(screen.getByRole("combobox"), { target: { value: "/srv/nas-project" }, }); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onWorkspaceScopeChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/nas-project", diff --git a/webui/src/tests/workspace-picker.test.tsx b/webui/src/tests/workspace-picker.test.tsx index 96270cdf8..621aaf15d 100644 --- a/webui/src/tests/workspace-picker.test.tsx +++ b/webui/src/tests/workspace-picker.test.tsx @@ -25,7 +25,7 @@ describe("Workspace project picker", () => { ["/srv/中文 项目/src", ["/", "/srv", "/srv/中文 项目", "/srv/中文 项目/src"]], ["C:\\Projects\\alpha", ["C:\\", "C:\\Projects", "C:\\Projects\\alpha"]], ["\\\\server\\share\\alpha", ["\\\\server\\share\\", "\\\\server\\share\\alpha"]], - ])("keeps host breadcrumb roots navigable: %s", (path, expected) => { + ])("keeps host breadcrumb roots intact: %s", (path, expected) => { expect(workspaceBreadcrumbs(path).map(crumb => crumb.path)).toEqual(expected); }); @@ -38,34 +38,106 @@ describe("Workspace project picker", () => { }); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - expect(await screen.findByText("Host: dev-server")).toBeInTheDocument(); await user.click(await screen.findByRole("button", { name: "/srv/beta" })); await screen.findByRole("listbox", { name: "/srv/beta" }); await user.click(screen.getByRole("button", { name: "Back", exact: true })); await screen.findByRole("listbox", { name: scope.project_path }); await user.click(screen.getByRole("button", { name: "Forward", exact: true })); await screen.findByRole("listbox", { name: "/srv/beta" }); - await user.click(screen.getByRole("button", { name: "Parent folder" })); + await user.click(within(screen.getByRole("navigation", { name: "Current location" })).getByRole("button", { name: "srv", exact: true })); await screen.findByRole("listbox", { name: "/srv" }); - const location = screen.getByRole("navigation", { name: "Current location" }); - await user.click(within(location).getByRole("button", { name: "/", exact: true })); + await user.click(within(screen.getByRole("navigation", { name: "Current location" })).getByRole("button", { name: "/", exact: true })); await screen.findByRole("listbox", { name: "/", exact: true }); - expect(screen.getByRole("button", { name: "Parent folder" })).toBeDisabled(); + expect(screen.queryByRole("button", { name: "Parent folder" })).not.toBeInTheDocument(); expect(screen.getByRole("button", { name: "Forward", exact: true })).toBeDisabled(); await user.click(screen.getByRole("button", { name: "Cancel", exact: true })); expect(onChange).not.toHaveBeenCalled(); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); + it("returns directly to the last visited folder after backward and branching navigation", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + const browse = vi.fn((raw: string) => Promise.resolve({ ...directory, path: raw.replace(/\/$/, ""), entries: [] })); + render(); + await user.click(screen.getByRole("button", { name: "Switch working directory" })); + const lastVisited = screen.getByRole("button", { name: "Last visited folder" }); + expect(lastVisited).toBeDisabled(); + await user.click(await screen.findByRole("button", { name: "/srv/alpha" })); + await screen.findByRole("listbox", { name: "/srv/alpha" }); + await user.click(screen.getByRole("button", { name: "Back", exact: true })); + await screen.findByRole("listbox", { name: scope.project_path }); + await user.click(lastVisited); + await screen.findByRole("listbox", { name: "/srv/alpha" }); + await user.click(screen.getByRole("button", { name: "/srv/beta" })); + await screen.findByRole("listbox", { name: "/srv/beta" }); + await user.click(lastVisited); + await screen.findByRole("listbox", { name: "/srv/alpha" }); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); + await user.click(screen.getByRole("button", { name: "Cancel", exact: true })); + await user.click(screen.getByRole("button", { name: "Switch working directory" })); + expect(screen.getByRole("button", { name: "Last visited folder" })).toBeDisabled(); + }); + + it("restores the directory columns and their selection when returning to a sibling visit", async () => { + const user = userEvent.setup(); + let rootChanged = false; + const browse = vi.fn((raw: string) => { + const path = raw.replace(/\/$/, ""); + const names = path === scope.project_path ? ["memory", "prompts"] : path.endsWith("/memory") ? ["reference"] : []; + if (rootChanged && path === scope.project_path) names.push("new-folder"); + return Promise.resolve({ ...directory, path, entries: names.map(name => ({ name, path: `${path}/${name}` })) }); + }); + render(); + await user.click(screen.getByRole("button", { name: "Switch working directory" })); + await user.click(await screen.findByRole("option", { name: "/srv/workspace/memory" })); + await screen.findByRole("option", { name: "/srv/workspace/memory/reference" }); + const parent = screen.getByRole("listbox", { name: scope.project_path }); + parent.scrollTop = 44; + fireEvent.scroll(parent); + await user.click(screen.getByRole("option", { name: "/srv/workspace/prompts" })); + await screen.findByText("No subfolders"); + await user.click(screen.getByRole("button", { name: "Last visited folder" })); + await screen.findByRole("option", { name: "/srv/workspace/memory/reference" }); + expect(screen.getAllByRole("listbox")).toHaveLength(2); + expect(screen.getByRole("option", { name: "/srv/workspace/memory" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getByRole("listbox", { name: scope.project_path }).scrollTop).toBe(44); + await user.click(screen.getByRole("button", { name: "Back", exact: true })); + await screen.findByRole("listbox", { name: "/srv/workspace/prompts" }); + expect(screen.getAllByRole("listbox")).toHaveLength(2); + expect(screen.getByRole("option", { name: "/srv/workspace/prompts" })).toHaveAttribute("aria-selected", "true"); + await user.click(screen.getByRole("button", { name: "Forward", exact: true })); + await screen.findByRole("option", { name: "/srv/workspace/memory/reference" }); + expect(screen.getAllByRole("listbox")).toHaveLength(2); + await user.click(within(screen.getByRole("navigation", { name: "Current location" })).getByRole("button", { name: "workspace", exact: true })); + await screen.findByRole("listbox", { name: scope.project_path }); + rootChanged = true; + const systemNow = Date.now; + const clock = vi.spyOn(Date, "now").mockImplementation(() => systemNow() + 31_000); + try { + await user.click(screen.getByRole("button", { name: "Back", exact: true })); + await screen.findByRole("option", { name: "/srv/workspace/new-folder" }); + expect(screen.getByRole("option", { name: "/srv/workspace/memory" })).toHaveAttribute("aria-selected", "true"); + expect(screen.getAllByRole("listbox")).toHaveLength(2); + } finally { + clock.mockRestore(); + } + }); + it("does not let address editing or text arrows silently change the working folder", async () => { const user = userEvent.setup(); const onChange = vi.fn(); const browse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path.replace(/\/$/, ""), entries: [] })); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - await screen.findByText("This folder is empty. You can still select it."); - await user.keyboard("{Meta>}{Shift>}g{/Shift}{/Meta}"); - const input = screen.getByRole("combobox"); + await screen.findByText("No subfolders"); + await user.click(screen.getByRole("button", { name: `Edit path: ${scope.project_path}` })); + const input = screen.getByRole("combobox") as HTMLInputElement; + await waitFor(() => expect(input).toHaveFocus()); + expect(input).toHaveValue(`${scope.project_path}/`); + expect(input.selectionStart).toBe(0); + expect(input.selectionEnd).toBe(`${scope.project_path}/`.length); await user.clear(input); await user.type(input, "/srv/alpha"); expect(fireEvent.keyDown(input, { key: "ArrowRight" })).toBe(true); @@ -73,29 +145,69 @@ describe("Workspace project picker", () => { await user.keyboard("{Escape}"); expect(screen.queryByRole("combobox")).not.toBeInTheDocument(); await screen.findByRole("listbox", { name: scope.project_path }); - await user.click(screen.getByRole("button", { name: "Edit path" })); + act(() => screen.getByRole("button", { name: `Edit path: ${scope.project_path}` }).focus()); + await user.keyboard("{Enter}"); + await waitFor(() => expect(screen.getByRole("combobox")).toHaveFocus()); + await user.keyboard("{Escape}"); + await user.keyboard("{Meta>}{Shift>}g{/Shift}{/Meta}"); await user.clear(screen.getByRole("combobox")); await user.type(screen.getByRole("combobox"), "/srv/alpha{Enter}"); await screen.findByRole("listbox", { name: "/srv/alpha" }); expect(onChange).not.toHaveBeenCalled(); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/alpha" })); }); - it("distinguishes an empty folder, a failed listing, and a filter with no matches", async () => { + it("distinguishes a folder without subfolders, a failed listing, and a filter with no matches", async () => { const user = userEvent.setup(); const browse = vi.fn().mockRejectedValueOnce(new Error("Permission denied")) .mockResolvedValue({ ...directory, entries: [] }); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); expect(await screen.findByRole("alert")).toHaveTextContent("Permission denied"); - expect(screen.getByRole("button", { name: "Select folder" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Confirm" })).toBeDisabled(); await user.click(screen.getByRole("button", { name: "Try again" })); - await screen.findByText("This folder is empty. You can still select it."); - expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled(); - await user.type(screen.getByRole("textbox", { name: "Filter this folder…" }), "missing"); + await screen.findByText("No subfolders"); + expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled(); + await user.type(screen.getByRole("textbox", { name: "Filter this folder" }), "missing"); await screen.findByText("No matching folders."); - expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled(); + expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled(); + }); + + it("keeps the chosen folder selectable while its contents are loading", async () => { + const user = userEvent.setup(); + const project = { name: "alpha", path: "/srv/workspace/alpha" }; + let finish!: (result: WorkspaceDirectoriesPayload) => void; + const browse = vi.fn((path: string) => path === scope.project_path + ? Promise.resolve(directory) + : new Promise(resolve => { finish = resolve; })); + const resolve = vi.fn().mockResolvedValue(project); + const onChange = vi.fn(); + render(); + await user.click(screen.getByRole("button", { name: "Switch working directory" })); + await user.click(await screen.findByRole("option", { name: project.path })); + await waitFor(() => expect(screen.getByRole("listbox", { name: project.path })).toHaveAttribute("aria-busy", "true")); + expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled(); + await user.click(screen.getByRole("button", { name: "Confirm" })); + expect(resolve).toHaveBeenCalledWith(project.path); + expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: project.path })); + await act(async () => { finish({ ...directory, path: project.path, entries: [] }); }); + }); + + it("confirms the edited address when clicking Confirm", async () => { + const user = userEvent.setup(); + const onChange = vi.fn(); + const browse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path.replace(/\/$/, ""), entries: [] })); + render(); + await user.click(screen.getByRole("button", { name: "Switch working directory" })); + await screen.findByText("No subfolders"); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); + await user.clear(screen.getByRole("combobox")); + await user.type(screen.getByRole("combobox"), "/srv/beta/"); + await screen.findByRole("listbox", { name: "/srv/beta" }); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); + expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/beta" })); }); it("uses one directory at a time on narrow screens and keeps saved locations reachable", async () => { @@ -110,13 +222,13 @@ describe("Workspace project picker", () => { await user.click(screen.getByRole("button", { name: "Switch working directory" })); await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" })); expect(screen.getAllByRole("listbox")).toHaveLength(1); - await screen.findByText("This folder is empty. You can still select it."); + await screen.findByText("No subfolders"); await user.click(screen.getByRole("button", { name: "Saved locations" })); await user.click(await screen.findByRole("button", { name: "/srv/beta" })); await screen.findByRole("listbox", { name: "/srv/beta" }); expect(screen.getAllByRole("listbox")).toHaveLength(1); expect(screen.getByRole("button", { name: "Saved locations" })).toHaveAttribute("aria-expanded", "false"); - expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled(); + expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled(); } finally { media.mockRestore(); } }); it.each([ @@ -140,10 +252,10 @@ describe("Workspace project picker", () => { expect(within(second).getByText("src", { exact: true })).toBeInTheDocument(); expect(within(second).getByText(secondParent, { exact: true })).toBeInTheDocument(); act(() => first.focus()); - expect(await screen.findByRole("tooltip")).toHaveTextContent(firstPath); + expect(first).toHaveFocus(); await user.click(second); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: secondPath })); }); @@ -154,21 +266,21 @@ describe("Workspace project picker", () => { render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); const shortcut = await screen.findByRole("button", { name: "/srv/beta" }); - await user.type(screen.getByRole("textbox", { name: "Filter this folder…" }), "al"); + await user.type(screen.getByRole("textbox", { name: "Filter this folder" }), "al"); await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "al", false, true)); expect(shortcut).toBeInTheDocument(); expect(screen.getAllByRole("listbox")).toHaveLength(1); onBrowse.mockResolvedValue({ ...directory, path: "/srv/beta", entries: [] }); await user.click(shortcut); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); expect(screen.getAllByRole("listbox")).toHaveLength(1); - expect(screen.getByRole("textbox", { name: "Filter this folder…" })).toHaveValue(""); + expect(screen.getByRole("textbox", { name: "Filter this folder" })).toHaveValue(""); expect(onChange).not.toHaveBeenCalled(); - await user.type(screen.getByRole("textbox", { name: "Filter this folder…" }), "oth"); + await user.type(screen.getByRole("textbox", { name: "Filter this folder" }), "oth"); await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/beta", "oth", false, true)); expect(shortcut).toBeInTheDocument(); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/beta", access_mode: "restricted" })); }); @@ -179,7 +291,7 @@ describe("Workspace project picker", () => { render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" })); - await screen.findByText("This folder is empty. You can still select it."); + await screen.findByText("No subfolders"); expect(onBrowse).toHaveBeenCalledTimes(2); await user.click(screen.getByRole("button", { name: "/srv/workspace" })); expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toBeInTheDocument(); @@ -199,7 +311,7 @@ describe("Workspace project picker", () => { render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" })); - await screen.findByText("This folder is empty. You can still select it."); + await screen.findByText("No subfolders"); const viewport = screen.getAllByRole("listbox")[0].closest("[data-workspace-columns]") as HTMLElement; Object.defineProperties(viewport, { clientWidth: { value: 300 }, scrollWidth: { value: 600 } }); viewport.scrollLeft = 0; @@ -256,8 +368,8 @@ describe("Workspace project picker", () => { await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "", true, true)); onBrowse.mockResolvedValue({ ...directory, path: "/srv/workspace/alpha", entries: [] }); await user.click(screen.getByRole("option", { name: "/srv/workspace/alpha" })); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/workspace/alpha" })); await waitFor(() => expect(screen.getByRole("button", { name: "Switch working directory" })).not.toHaveFocus()); }); @@ -292,7 +404,7 @@ describe("Workspace project picker", () => { await user.click(screen.getByRole("button", { name: "Switch working directory" })); expect(screen.queryByRole("option", { name: "Browse folders…" })).not.toBeInTheDocument(); await user.type(screen.getByRole("combobox"), "relative-path"); - expect(screen.getByRole("button", { name: "Select folder" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Confirm" })).toBeDisabled(); await user.keyboard("{Enter}"); expect(await screen.findByRole("alert")).toHaveTextContent("Enter an absolute folder path"); expect(onChange).not.toHaveBeenCalled(); @@ -370,7 +482,7 @@ describe("Workspace project picker", () => { const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: completed, partial: path === draft, entries: path === draft ? [{ name: "alpha", path: completed }] : [] })); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); await user.clear(input); await user.type(input, draft); @@ -380,9 +492,9 @@ describe("Workspace project picker", () => { expect(input).toHaveFocus(); expect(screen.getByRole("combobox")).toBe(input); expect(onChange).not.toHaveBeenCalled(); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); expect(fireEvent.keyDown(input, { key: "Tab", shiftKey: true })).toBe(true); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: completed })); }); @@ -391,18 +503,18 @@ describe("Workspace project picker", () => { const onBrowse = vi.fn((path: string) => Promise.resolve({ ...directory, path: path === "/srv/al" ? "/srv" : path, parent: "/srv", partial: path === "/srv/al", entries: path === "/srv/al" ? [{ name: "alpha", path: "/srv/alpha" }, { name: "alpine", path: "/srv/alpine" }] : [] })); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); await user.clear(input); await user.type(input, "/srv/al"); await screen.findByRole("option", { name: "/srv/alpine" }); - expect(screen.getByRole("button", { name: "Select folder" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Confirm" })).toBeDisabled(); expect(screen.queryByRole("alert")).not.toBeInTheDocument(); await user.keyboard("{ArrowDown}{ArrowDown}{Tab}"); expect(input).toHaveValue("/srv/alpine/"); expect(screen.getAllByRole("combobox")).toHaveLength(1); expect(screen.getAllByRole("listbox")).toHaveLength(1); - await waitFor(() => expect(screen.getByRole("button", { name: "Select folder" })).toBeEnabled()); + await waitFor(() => expect(screen.getByRole("button", { name: "Confirm" })).toBeEnabled()); expect(input).toHaveFocus(); }); @@ -415,7 +527,7 @@ describe("Workspace project picker", () => { render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); await screen.findByRole("option", { name: "/srv/workspace/docs" }); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); fireEvent.change(input, { target: { value: "/srv/alpha" } }); if (loaded) await screen.findByRole("option", { name: "/srv/alpha/docs" }); @@ -438,7 +550,7 @@ describe("Workspace project picker", () => { const onBrowse = vi.fn((path: string) => path === "/srv/al" ? new Promise(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] })); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); await user.clear(input); await user.type(input, "/srv/al"); @@ -457,7 +569,7 @@ describe("Workspace project picker", () => { : Promise.resolve({ ...directory, path, entries: [] })); render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); await user.clear(input); await user.type(input, "/srv/al"); @@ -477,12 +589,12 @@ describe("Workspace project picker", () => { render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); await screen.findByRole("option", { name: "/srv/workspace/child" }); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); const input = screen.getByRole("combobox"); await user.clear(input); await user.type(input, "/srv/old/"); expect(screen.queryByRole("option", { name: "/srv/workspace/child" })).not.toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Select folder" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Confirm" })).toBeDisabled(); await waitFor(() => expect(onBrowse).toHaveBeenCalledWith("/srv/old/", "", false, true)); await user.clear(input); await user.type(input, "/srv/new/"); @@ -491,7 +603,7 @@ describe("Workspace project picker", () => { await waitFor(() => expect(screen.queryByRole("option", { name: "/srv/old/child" })).not.toBeInTheDocument()); expect(screen.getByRole("combobox")).toBe(input); expect(input).toHaveFocus(); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/new/" })); }); @@ -501,11 +613,11 @@ describe("Workspace project picker", () => { render(); await user.click(screen.getByRole("button", { name: "Switch working directory" })); await screen.findByRole("option", { name: "/srv/workspace/alpha" }); - const input = screen.getByRole("textbox", { name: "Filter this folder…" }); + const input = screen.getByRole("textbox", { name: "Filter this folder" }); await user.type(input, "alp"); await waitFor(() => expect(onBrowse).toHaveBeenLastCalledWith("/srv/workspace", "alp", false, true)); expect(screen.queryByRole("combobox")).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Edit path" })); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); expect(input).toBeDisabled(); expect(screen.getByRole("combobox")).toHaveValue("/srv/workspace/"); }); @@ -541,6 +653,18 @@ describe("Workspace project picker", () => { await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha" })); await user.click(await screen.findByRole("option", { name: "/srv/workspace/alpha/child" })); expect(screen.getAllByRole("listbox")).toHaveLength(3); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); + expect(screen.getAllByRole("listbox")).toHaveLength(3); + await user.click(screen.getByRole("listbox", { name: "/srv/workspace/alpha/child" })); + expect(screen.queryByRole("combobox")).not.toBeInTheDocument(); + expect(screen.getAllByRole("listbox")).toHaveLength(3); + await user.click(screen.getByRole("button", { name: /^Edit path:/ })); + await user.clear(screen.getByRole("combobox")); + await user.type(screen.getByRole("combobox"), "/srv/workspace/beta/"); + await screen.findByRole("option", { name: "/srv/workspace/beta/other" }); + await user.keyboard("{Escape}"); + expect(screen.getAllByRole("listbox")).toHaveLength(3); + expect(screen.queryByRole("option", { name: "/srv/workspace/beta/other" })).not.toBeInTheDocument(); expect(screen.getByRole("option", { name: "/srv/workspace/alpha" })).toHaveAttribute("aria-selected", "true"); expect(onChange).not.toHaveBeenCalled(); expect(onBrowse.mock.calls.filter(call => call[0].replace(/\/$/, "") === scope.project_path)).toHaveLength(1); @@ -552,7 +676,7 @@ describe("Workspace project picker", () => { await screen.findByRole("option", { name: "/srv/workspace/beta/other" }); expect(screen.getAllByRole("listbox")).toHaveLength(2); expect(screen.queryByRole("option", { name: "/srv/workspace/alpha/child" })).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Select folder" })); + await user.click(screen.getByRole("button", { name: "Confirm" })); expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ project_path: "/srv/workspace/beta" })); });