From cc5f2a84d3e7f43a49c34169a06994fc5b6bca8a Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 8 Oct 2026 10:06:31 +0800 Subject: [PATCH] fix(webui): refine workspace picker navigation and macOS behavior --- nanobot/webui/workspace_browser.py | 4 + nanobot/webui/workspaces.py | 3 + tests/utils/test_workspace_browser.py | 14 + .../components/thread/WorkspaceControls.tsx | 328 +++++++++++++----- webui/src/i18n/locales/en/common.json | 22 +- webui/src/i18n/locales/es/common.json | 22 +- webui/src/i18n/locales/fr/common.json | 22 +- webui/src/i18n/locales/id/common.json | 22 +- webui/src/i18n/locales/ja/common.json | 22 +- webui/src/i18n/locales/ko/common.json | 22 +- webui/src/i18n/locales/pt-BR/common.json | 22 +- webui/src/i18n/locales/vi/common.json | 22 +- webui/src/i18n/locales/zh-CN/common.json | 22 +- webui/src/i18n/locales/zh-TW/common.json | 22 +- webui/src/lib/types.ts | 3 + webui/src/lib/workspace.ts | 18 + webui/src/tests/app-layout.test.tsx | 4 +- webui/src/tests/thread-composer.test.tsx | 8 +- webui/src/tests/workspace-picker.test.tsx | 301 ++++++++++++---- 19 files changed, 716 insertions(+), 187 deletions(-) diff --git a/nanobot/webui/workspace_browser.py b/nanobot/webui/workspace_browser.py index 0d7239395..c1f9bf2cc 100644 --- a/nanobot/webui/workspace_browser.py +++ b/nanobot/webui/workspace_browser.py @@ -7,6 +7,7 @@ import os import platform import socket import stat +import sys from collections.abc import Iterator from pathlib import Path from typing import TypedDict @@ -70,6 +71,9 @@ def browse_workspace_directories( hidden = entry.name.startswith(".") or ( os.name == "nt" and bool(entry.stat(follow_symlinks=False).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN) + ) or ( + sys.platform == "darwin" + and bool(entry.stat(follow_symlinks=False).st_flags & stat.UF_HIDDEN) ) if show_hidden or prefix.startswith(".") or not hidden: yield {"name": entry.name, "path": entry.path} diff --git a/nanobot/webui/workspaces.py b/nanobot/webui/workspaces.py index 14fb9a4e4..2354cb694 100644 --- a/nanobot/webui/workspaces.py +++ b/nanobot/webui/workspaces.py @@ -204,6 +204,9 @@ def workspaces_payload( "controls": { "can_change_project": can_change_project, "can_use_full_access": can_use_full_access, + "can_browse_directories": can_change_project, + "can_resolve_project": can_change_project, + "can_manage_favorites": can_change_project, }, } diff --git a/tests/utils/test_workspace_browser.py b/tests/utils/test_workspace_browser.py index 0a9d6b59e..1a3fbad3a 100644 --- a/tests/utils/test_workspace_browser.py +++ b/tests/utils/test_workspace_browser.py @@ -1,5 +1,8 @@ """Project selection directory metadata contracts.""" +import os +import stat +import sys from pathlib import Path import pytest @@ -21,6 +24,17 @@ def test_directory_browser_filters_folders_and_exposes_navigation(tmp_path: Path assert hidden["entries"] == [{"name": ".hidden", "path": str(tmp_path / ".hidden")}] +@pytest.mark.skipif(sys.platform != "darwin", reason="Finder hidden flags are macOS metadata") +def test_directory_browser_honors_finder_hidden_flag(tmp_path: Path) -> None: + hidden = tmp_path / "Finder hidden" + hidden.mkdir() + os.chflags(hidden, stat.UF_HIDDEN) + visible = browse_workspace_directories(str(tmp_path), default_workspace=tmp_path) + assert visible["entries"] == [] + shown = browse_workspace_directories(str(tmp_path), default_workspace=tmp_path, show_hidden=True) + assert shown["entries"] == [{"name": hidden.name, "path": str(hidden)}] + + def test_directory_filter_reaches_folders_beyond_display_limit(tmp_path: Path) -> None: for index in range(501): (tmp_path / f"project-{index:03}").mkdir() diff --git a/webui/src/components/thread/WorkspaceControls.tsx b/webui/src/components/thread/WorkspaceControls.tsx index c8a88817c..9cc0922c7 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 { Check, Search, Star } from "lucide-react"; +import { ArrowLeft, ArrowRight, ArrowUp, Check, ChevronRight, FolderSearch, Pencil, Search, Star, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { ToggleButton } from "@/components/settings/ToggleButton"; import { Button } from "@/components/ui/button"; @@ -11,8 +11,9 @@ import { Input } from "@/components/ui/input"; import { Dialog, DialogContent, DialogTrigger, DialogTitle, DialogDescription } from "@/components/ui/dialog"; import type { WorkspaceScopePayload, ProjectDirectory, WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types"; import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache"; +import { useMediaQuery } from "@/hooks/useMediaQuery"; import { cn } from "@/lib/utils"; -import { isAbsoluteWorkspacePath, projectNameFromPath, sameWorkspacePath, scopeWithAccessMode, workspacePathCompletionQuery, workspaceDirectoryPrefix, selectedProjectScope, type BrowseWorkspaceDirectories } from "@/lib/workspace"; +import { isAbsoluteWorkspacePath, projectNameFromPath, sameWorkspacePath, scopeWithAccessMode, workspaceBreadcrumbs, workspacePathCompletionQuery, workspaceDirectoryPrefix, selectedProjectScope, type BrowseWorkspaceDirectories } from "@/lib/workspace"; function WorkspaceFavoriteButton({ path, pinned, busy, onToggle }: { path: string; pinned: boolean; busy: boolean; onToggle: () => void; @@ -30,7 +31,8 @@ function WorkspaceFavoriteButton({ path, pinned, busy, onToggle }: { ); } -type PickerColumn = { path: string; options: ProjectDirectory[]; selectedPath: string | null; hidden: boolean }; +type PickerOption = ProjectDirectory & { kind: "directory" | "manual" }; +type PickerColumn = { path: string; options: PickerOption[]; selectedPath: string | null; hidden: boolean }; function WorkspacePickerTooltip({ label, children }: { label: string; children: ReactElement }) { return ( @@ -41,13 +43,22 @@ function WorkspacePickerTooltip({ label, children }: { label: string; children: ); } +function PickerToolButton({ label, disabled, onClick, children }: { + label: string; disabled?: boolean; onClick: () => void; children: ReactElement; +}) { + return + + ; +} + const DIRECTORY_ROW_HEIGHT = 44; const DIRECTORY_OVERSCAN = 4; function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: { - options: ProjectDirectory[]; + options: PickerOption[]; activeIndex: number | null; - renderOption: (option: ProjectDirectory, index: number) => ReactElement; + renderOption: (option: PickerOption, index: number) => ReactElement; } & HTMLAttributes) { const viewportRef = useRef(null); const [firstRow, setFirstRow] = useState(0); @@ -83,7 +94,7 @@ function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children
{options.slice(start, end).map((option, offset) => { const index = start + offset; - return
+ return
{renderOption(option, index)}
; })} @@ -133,6 +144,16 @@ function WorkspacePickerPath({ path }: { path: string }) { ); } +function WorkspaceSavedProjectLabel({ path }: { path: string }) { + const parts = workspacePathCompletionQuery(path); + return ( + + {projectNameFromPath(path)} + {parts?.query && {parts.path}} + + ); +} + export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, controls, error, onLoadProjects, onResolveProject, onFavoriteProject, onBrowseDirectories, layoutAnchor, onChange }: { layoutAnchor?: HTMLElement | null; isHero: boolean; @@ -141,15 +162,20 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, defaultScope: WorkspaceScopePayload | null; controls: WorkspacesPayload["controls"] | null; error?: string | null; - onResolveProject: (path: string) => Promise; - onLoadProjects: () => Promise; - onFavoriteProject: (path: string, pinned: boolean) => Promise; - onBrowseDirectories: BrowseWorkspaceDirectories; + onResolveProject?: (path: string) => Promise; + onLoadProjects?: () => Promise; + onFavoriteProject?: (path: string, pinned: boolean) => Promise; + onBrowseDirectories?: BrowseWorkspaceDirectories; onChange?: (scope: WorkspaceScopePayload) => void; }) { const { t } = useTranslation(); 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 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); @@ -165,12 +191,19 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, const [highlightActive, setHighlightActive] = useState(false); const [previousColumns, setPreviousColumns] = useState([]); const columnsRef = useRef(null); + const breadcrumbRef = useRef(null); + const attachBreadcrumb = useCallback((element: HTMLElement | null) => { + breadcrumbRef.current = element; + // Dialog portals mount after the parent's layout effect on first open. + if (element) window.requestAnimationFrame(() => { if (element.isConnected) element.scrollLeft = element.scrollWidth; }); + }, []); const [columnsElement, setColumnsElement] = useState(null); const attachColumns = useCallback((element: HTMLDivElement | null) => { columnsRef.current = element; 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); @@ -182,10 +215,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, const displayedScope = scope ?? defaultScope; const projectLabel = displayedScope ? displayedScope.project_name || projectNameFromPath(displayedScope.project_path) : ""; const visible = isHero && !!defaultScope && !!onChange && controls?.can_change_project !== false; - const directoryCache = useMemo(() => createWorkspaceDirectoryCache(onBrowseDirectories), [onBrowseDirectories]); + const canBrowse = controls?.can_browse_directories === true && !!onBrowseDirectories; + const directoryCache = useMemo(() => onBrowseDirectories ? createWorkspaceDirectoryCache(onBrowseDirectories) : null, [onBrowseDirectories]); const absoluteDraft = isAbsoluteWorkspacePath(pathDraft); - const requestedPath = absoluteDraft ? pathDraft.trim() : basePath; - const folderQuery = absoluteDraft ? "" : pathDraft.trim(); + const requestedPath = editingPath && absoluteDraft ? pathDraft.trim() : basePath; + const folderQuery = editingPath ? "" : filterQuery.trim(); useEffect(() => { pickerSession.current += 1; @@ -195,15 +229,19 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, setActiveColumn(0); setHighlightActive(false); const initialPath = scope?.project_path ?? defaultScope?.project_path ?? ""; - setPathDraft(workspaceDirectoryPrefix(initialPath)); + setPathDraft(canBrowse ? workspaceDirectoryPrefix(initialPath) : currentProjectScope?.project_path ?? ""); setBasePath(initialPath); + setHistory({ paths: [initialPath], index: 0 }); + setEditingPath(false); + setFilterQuery(""); + setShowLocations(false); setDirectory(null); setActiveIndex(0); setPathError(null); - }, [scope?.project_path, defaultScope?.project_path, open]); + }, [scope?.project_path, defaultScope?.project_path, open, canBrowse]); useEffect(() => { - if (!open) return; + if (!open || !onLoadProjects) return; let active = true; setCatalog(null); onLoadProjects().then(payload => { if (active) setCatalog(payload); }).catch((err: Error) => { if (active) setPathError(err.message); }); @@ -211,26 +249,26 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, }, [onLoadProjects, open]); useEffect(() => { - if (!open) return; + if (!open || !canBrowse || !directoryCache) return; + if (editingPath && !absoluteDraft) { setDirectory(null); setLoading(false); return; } let active = true; const apply = (result: WorkspaceDirectoriesPayload) => { if (!active) return; setDirectory(result); setLoading(false); - if (absoluteDraft) setBasePath(result.path); }; setDirectoryError(null); const cached = directoryCache.peek(requestedPath, folderQuery, showHidden, true); if (cached) { apply(cached); return; } setLoading(true); setDirectory(null); - const typing = !!folderQuery || absoluteDraft && !/[\\/]$/.test(pathDraft); + const typing = !!folderQuery || editingPath && !/[\\/]$/.test(pathDraft); const timer = window.setTimeout(() => { directoryCache.load(requestedPath, folderQuery, showHidden, true).then(apply).catch((err: Error) => { if (active) { setDirectoryError(err.message); setLoading(false); } }); }, typing ? 150 : 0); return () => { active = false; window.clearTimeout(timer); }; - }, [open, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft]); + }, [open, canBrowse, directoryCache, requestedPath, folderQuery, showHidden, revision, absoluteDraft, pathDraft, editingPath]); useEffect(() => { if (disabled) setOpen(false); }, [disabled]); useEffect(() => { @@ -240,13 +278,15 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, }, [disabled, error, visible]); useEffect(() => { if (!open || pickingFolder) return; - const frame = window.requestAnimationFrame(() => inputRef.current?.focus()); + const frame = window.requestAnimationFrame(() => { + if (editingPath || !canBrowse) inputRef.current?.focus(); + }); return () => window.cancelAnimationFrame(frame); - }, [open, pickingFolder, pathError]); + }, [open, pickingFolder, pathError, editingPath, canBrowse]); const ancestorPaths = JSON.stringify(previousColumns.filter(column => column.hidden !== showHidden).map(column => column.path)); useEffect(() => { - if (!open) return; + if (!open || !canBrowse || !directoryCache) return; const paths: string[] = JSON.parse(ancestorPaths); if (!paths.length) return; let active = true; @@ -255,11 +295,11 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, 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 }; + return { ...column, hidden: showHidden, options: result.entries.map(entry => ({ ...entry, kind: "directory" as const })) }; })); }).catch((err: Error) => { if (active) setPathError(err.message); }); return () => { active = false; }; - }, [open, directoryCache, ancestorPaths, showHidden]); + }, [open, canBrowse, directoryCache, ancestorPaths, showHidden]); useLayoutEffect(() => { const viewport = columnsElement; @@ -288,18 +328,18 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, useLayoutEffect(() => { const viewport = columnsRef.current; - if (viewport) viewport.scrollLeft = viewport.clientWidth * Math.max(0, previousColumns.length + 1 - visibleColumns) / visibleColumns; - }, [previousColumns.length, visibleColumns]); + if (viewport) viewport.scrollLeft = viewport.clientWidth * Math.max(0, previousColumns.length + 1 - columnCount) / columnCount; + }, [previousColumns.length, columnCount]); useLayoutEffect(() => { const viewport = columnsRef.current; if (!viewport || !highlightActive) return; - const width = viewport.clientWidth / visibleColumns; + const width = viewport.clientWidth / columnCount; const left = activeColumn * width; const right = left + width; if (left < viewport.scrollLeft) viewport.scrollLeft = left; else if (right > viewport.scrollLeft + viewport.clientWidth) viewport.scrollLeft = right - viewport.clientWidth; - }, [activeColumn, highlightActive, visibleColumns]); + }, [activeColumn, highlightActive, columnCount]); function changeDraft(value: string, resetColumns = true) { setHighlightActive(false); @@ -307,37 +347,51 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, completionRequest.current += 1; setPathDraft(value); const absolute = isAbsoluteWorkspacePath(value); - const cached = directoryCache.peek(absolute ? value.trim() : basePath, absolute ? "" : value.trim(), showHidden, true); + const cached = absolute ? directoryCache?.peek(value.trim(), "", showHidden, true) : null; setDirectory(cached ?? null); - setLoading(!cached); + setLoading(canBrowse && absolute && !cached); setDirectoryError(null); setPathError(null); setActiveIndex(0); } - function navigate(path: string, columnIndex = activeColumn) { - const source = columns[columnIndex]; - const ancestors = columns.slice(0, columnIndex); - if (source?.options.length) ancestors.push({ ...source, selectedPath: path }); + 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(""); + 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 }; + }); changeDraft(workspaceDirectoryPrefix(path), false); setRevision(value => value + 1); - inputRef.current?.focus(); + if (keepEditing) inputRef.current?.focus(); + else focusDirectory(); } - const applyProjectPath = useCallback((path: string, name: string) => { + const applyProjectPath = useCallback((path: string, name?: string) => { const base = scope ?? defaultScope; const trimmed = path.trim(); if (!base || !onChange) return; + if (!trimmed || !isAbsoluteWorkspacePath(trimmed)) { setPathError(t("workspace.dialog.absolutePathRequired")); return; } const accessMode = controls?.can_use_full_access === false && !sameWorkspacePath(trimmed, base.project_path) ? "restricted" : base.access_mode; - onChange({ ...base, project_path: trimmed, project_name: name, access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" }); + onChange({ ...base, project_path: trimmed, project_name: name || projectNameFromPath(trimmed), access_mode: accessMode, restrict_to_workspace: accessMode === "restricted" }); setPathError(null); setOpen(false); - }, [controls?.can_use_full_access, defaultScope, onChange, scope]); + }, [controls?.can_use_full_access, defaultScope, onChange, scope, t]); - const chooseProject = useCallback(async (path: string) => { + const chooseProject = useCallback(async (path: string, name?: string) => { const session = pickerSession.current; + if (controls?.can_resolve_project !== true || !onResolveProject) { applyProjectPath(path, name); return; } setPickingFolder(true); setPathError(null); try { const project = await onResolveProject(path); @@ -345,10 +399,10 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, } catch (err) { if (session === pickerSession.current) setPathError((err as Error).message); } finally { setPickingFolder(false); } - }, [applyProjectPath, onResolveProject]); + }, [applyProjectPath, controls?.can_resolve_project, onResolveProject]); const favorites = catalog?.favorite_projects ?? []; - const canFavorite = catalog !== null; + const canFavorite = catalog?.controls.can_manage_favorites === true && !!onFavoriteProject; const isFavorite = (path: string) => favorites.some(item => sameWorkspacePath(item.path, path)); function favoriteButton(path: string) { return canFavorite ? { - if (favoriteBusy) return; + if (!onFavoriteProject || favoriteBusy) return; const session = pickerSession.current; setFavoriteBusy(true); setPathError(null); try { @@ -372,41 +426,82 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, ...(defaultScope ? [{ name: projectNameFromPath(defaultScope.project_path), path: defaultScope.project_path }] : []), ...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []), ].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path)); - const options = useMemo(() => directory && !loading ? directory.entries : [], [directory, loading]); + const options = useMemo(() => { + if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" })); + return !canBrowse && absoluteDraft ? [{ name: projectNameFromPath(pathDraft.trim()), path: pathDraft.trim(), kind: "manual" }] : []; + }, [directory, loading, canBrowse, absoluteDraft, pathDraft]); function openShortcut(project: ProjectDirectory) { - setBasePath(project.path); - changeDraft(workspaceDirectoryPrefix(project.path)); - setRevision(value => value + 1); - inputRef.current?.focus(); + if (!canBrowse) { void chooseProject(project.path, project.name); return; } + navigate(project.path); } const columns: PickerColumn[] = [...previousColumns, { path: directory?.path ?? requestedPath, options, selectedPath: null, hidden: showHidden }]; const activeOptions = columns[activeColumn]?.options ?? options; const activeOption = Math.min(activeIndex, Math.max(activeOptions.length - 1, 0)); - const selectionPath = !loading && directory && !directory.partial ? directory.path : null; + const selectionPath = canBrowse ? (!loading && directory && !directory.partial ? directory.path : null) : (pathDraft.trim() ? absoluteDraft ? pathDraft.trim() : null : scope?.project_path ?? defaultScope?.project_path); const displayedError = pathError ?? error ?? directoryError; + const currentPath = editingPath ? basePath : directory?.path ?? basePath; + const breadcrumbs = workspaceBreadcrumbs(currentPath); + const parentPath = directory?.parent; + const hostName = catalog?.host?.name ?? directory?.host; + const hostPlatform = catalog?.host?.platform ?? directory?.platform; - async function completePath() { + useLayoutEffect(() => { + if (breadcrumbRef.current) breadcrumbRef.current.scrollLeft = breadcrumbRef.current.scrollWidth; + }, [currentPath, editingPath, open]); + + function editPath() { + setEditingPath(true); + setFilterQuery(""); + changeDraft(workspaceDirectoryPrefix(currentPath)); + window.requestAnimationFrame(() => inputRef.current?.select()); + } + function cancelPathEditing() { + setEditingPath(false); + changeDraft(workspaceDirectoryPrefix(basePath)); + focusDirectory(); + } + + async function completePath(keepEditing = true) { + if (!absoluteDraft) { setPathError(t("workspace.dialog.absolutePathRequired")); return; } + const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: "" }; + // Complete an exact address before descending into its implicitly active child. + const completingAddress = absoluteDraft && !!request.query && !highlightActive; const option = activeOptions[activeOption]; - if (option) { navigate(option.path); return; } - const request = workspacePathCompletionQuery(pathDraft) ?? { path: basePath, query: pathDraft.trim() }; + if (highlightActive && option && option.kind !== "manual" && !completingAddress) { navigate(option.path, undefined, keepEditing); return; } + if (!directoryCache || !canBrowse) return; const id = ++completionRequest.current; const session = pickerSession.current; try { const result = await directoryCache.load(requestedPath, folderQuery, showHidden || request.query.startsWith("."), true); if (id !== completionRequest.current || session !== pickerSession.current) return; - if (absoluteDraft && !result.partial && request.query) { navigate(result.path); return; } + if (!result.partial) { navigate(result.path, undefined, keepEditing); return; } const prefix = request.query.toLocaleLowerCase(); const first = result.entries.find(entry => entry.name.toLocaleLowerCase().startsWith(prefix)); - if (first) navigate(first.path); + if (first) navigate(first.path, undefined, keepEditing); + else setPathError(t("workspace.picker.pathNotFound")); } catch (err) { if (id === completionRequest.current && session === pickerSession.current) setPathError((err as Error).message); } } - function activate(option: ProjectDirectory, columnIndex = activeColumn) { + function activate(option: PickerOption, columnIndex = activeColumn) { if (pickingFolder) return; - navigate(option.path, columnIndex); + if (canBrowse && option.kind !== "manual") navigate(option.path, columnIndex); + else void chooseProject(option.path, option.kind === "manual" ? undefined : option.name); } + function moveHistory(offset: number) { + const index = history.index + offset; + if (index >= 0 && index < history.paths.length) navigate(history.paths[index], undefined, false, index); + } + + 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]" /> +
+
; + if (!visible || !defaultScope || !onChange) return null; return (
@@ -420,75 +515,122 @@ export function WorkspaceProjectPicker({ isHero, disabled, scope, defaultScope, - { event.preventDefault(); inputRef.current?.focus(); }} onPointerDownCapture={() => { keyboardInteraction.current = false; }} onKeyDownCapture={() => { keyboardInteraction.current = true; }} onCloseAutoFocus={event => { if (!keyboardInteraction.current) event.preventDefault(); }}> - {t("thread.composer.workspace.projectAria")} + { event.preventDefault(); if (canBrowse) focusDirectory(); else inputRef.current?.focus(); }} + onPointerDownCapture={() => { keyboardInteraction.current = false; }} + onKeyDownCapture={event => { + keyboardInteraction.current = 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); } + else if (event.altKey && event.key === "ArrowRight") { event.preventDefault(); moveHistory(1); } + 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 })} + } +
{t("workspace.picker.description")} -
- - changeDraft(event.target.value)} placeholder={t("workspace.picker.search")} aria-label={t("workspace.picker.search")} aria-invalid={displayedError || directoryError ? true : undefined} aria-describedby={displayedError || directoryError ? errorId : undefined} className="h-10 min-w-0 flex-1 border-0 bg-transparent pl-10 pr-3 text-[14px] shadow-none focus-visible:ring-0" onKeyDown={event => { +
+ {canBrowse &&
+ moveHistory(-1)}> + {!compact && = history.paths.length - 1} onClick={() => moveHistory(1)}>} + parentPath && navigate(parentPath)}> +
} + {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 => { if (event.nativeEvent.isComposing) return; if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) { event.preventDefault(); - const next = (activeOption + (event.key === "ArrowDown" ? 1 : -1) + activeOptions.length) % activeOptions.length; + const next = highlightActive ? (activeOption + (event.key === "ArrowDown" ? 1 : -1) + activeOptions.length) % activeOptions.length : event.key === "ArrowDown" ? 0 : activeOptions.length - 1; setHighlightActive(true); setActiveIndex(next); - } else if (event.key === "ArrowLeft" && activeColumn > 0 && event.currentTarget.selectionStart === 0 && event.currentTarget.selectionEnd === 0) { - event.preventDefault(); - const parent = columns[activeColumn - 1]; - setHighlightActive(true); - setActiveColumn(activeColumn - 1); - setActiveIndex(Math.max(0, parent.options.findIndex(option => sameWorkspacePath(option.path, parent.selectedPath)))); - } else if (event.key === "Tab" && !event.shiftKey && !!pathDraft.trim() || event.key === "ArrowRight" && !event.shiftKey && event.currentTarget.selectionStart === pathDraft.length && event.currentTarget.selectionEnd === pathDraft.length) { + } else if (event.key === "Tab" && !event.shiftKey && canBrowse && absoluteDraft && (highlightActive || !/[\\/]$/.test(pathDraft))) { event.preventDefault(); void completePath(); } else if (event.key === "Enter") { event.preventDefault(); - if ((event.ctrlKey || event.metaKey) && selectionPath) void chooseProject(selectionPath); - else if (activeOptions[activeOption]) activate(activeOptions[activeOption]); - else if (selectionPath) void chooseProject(selectionPath); + if (!canBrowse) void chooseProject(pathDraft); + else if ((event.ctrlKey || event.metaKey) && selectionPath) void chooseProject(selectionPath); + else void completePath(false); } - }} /> - + }} /> : } + {canBrowse && + {editingPath ? : } + }
-
-