feat: improve project directory picker

Adds command-palette style project browsing
Keeps native Finder picker as optional desktop action
Supports disabled existing projects and create-and-add paths
This commit is contained in:
Bohdan Triapitsyn
2026-04-27 15:45:14 +03:00
parent 54a09914ac
commit c83986cd94
14 changed files with 642 additions and 412 deletions
@@ -38,8 +38,6 @@ import { CSS } from '@dnd-kit/utilities';
import type { SessionContextUsage } from '@/stores/types/sessionTypes';
import { PROJECT_ICON_MAP, PROJECT_COLOR_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { toast } from '@/components/ui';
import { isTauriShell, isDesktopLocalOriginActive, requestDirectoryAccess } from '@/lib/desktop';
import { sessionEvents } from '@/lib/sessionEvents';
import {
Dialog,
@@ -1450,7 +1448,6 @@ export const MobileSessionStatusBar: React.FC<MobileSessionStatusBarProps> = ({
const projects = useProjectsStore((state) => state.projects);
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
const setActiveProject = useProjectsStore((state) => state.setActiveProject);
const addProject = useProjectsStore((state) => state.addProject);
const removeProject = useProjectsStore((state) => state.removeProject);
const getActiveProject = useProjectsStore((state) => state.getActiveProject);
@@ -1492,7 +1489,6 @@ export const MobileSessionStatusBar: React.FC<MobileSessionStatusBarProps> = ({
const contextUsage = getContextUsage(contextLimit, outputLimit);
const [isExpanded, setIsExpanded] = React.useState(false);
const tauriIpcAvailable = React.useMemo(() => isTauriShell(), []);
if (!isMobile || !showMobileSessionStatusBar || totalCount === 0) {
return null;
@@ -1520,29 +1516,7 @@ export const MobileSessionStatusBar: React.FC<MobileSessionStatusBarProps> = ({
};
const handleAddProject = () => {
if (!tauriIpcAvailable || !isDesktopLocalOriginActive()) {
sessionEvents.requestDirectoryDialog();
return;
}
requestDirectoryAccess('')
.then((result) => {
if (result.success && result.path) {
const added = addProject(result.path, { id: result.projectId });
if (!added) {
toast.error(t('chat.mobileStatus.toast.addProjectFailed'), {
description: t('chat.mobileStatus.toast.selectValidDirectory'),
});
}
} else if (result.error && result.error !== 'Directory selection cancelled') {
toast.error(t('chat.mobileStatus.toast.selectDirectoryFailed'), {
description: result.error,
});
}
})
.catch((error) => {
console.error('Failed to select directory:', error);
toast.error(t('chat.mobileStatus.toast.selectDirectoryFailed'));
});
sessionEvents.requestDirectoryDialog();
};
if (isMobileSessionStatusBarCollapsed) {
@@ -7,52 +7,24 @@ import { SettingsSidebarItem } from '@/components/sections/shared/SettingsSideba
import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/lib/projectMeta';
import { cn } from '@/lib/utils';
import { RiAddLine, RiFolderLine } from '@remixicon/react';
import { isDesktopLocalOriginActive, isTauriShell, isVSCodeRuntime, requestDirectoryAccess } from '@/lib/desktop';
import { isVSCodeRuntime } from '@/lib/desktop';
import { sessionEvents } from '@/lib/sessionEvents';
import { toast } from '@/components/ui';
import { useThemeSystem } from '@/contexts/useThemeSystem';
import { useI18n } from '@/lib/i18n';
export const ProjectsSidebar: React.FC<{ onItemSelect?: () => void }> = ({ onItemSelect }) => {
const { t } = useI18n();
const projects = useProjectsStore((state) => state.projects);
const addProject = useProjectsStore((state) => state.addProject);
const selectedId = useUIStore((state) => state.settingsProjectsSelectedId);
const setSelectedId = useUIStore((state) => state.setSettingsProjectsSelectedId);
const { currentTheme } = useThemeSystem();
const [brokenIconIds, setBrokenIconIds] = React.useState<Set<string>>(new Set());
const isVSCode = React.useMemo(() => isVSCodeRuntime(), []);
const tauriIpcAvailable = React.useMemo(() => isTauriShell(), []);
const handleAddProject = React.useCallback(() => {
if (!tauriIpcAvailable || !isDesktopLocalOriginActive()) {
sessionEvents.requestDirectoryDialog();
return;
}
requestDirectoryAccess('')
.then((result) => {
if (result.success && result.path) {
const added = addProject(result.path, { id: result.projectId });
if (!added) {
toast.error(t('sessions.sidebar.directory.errorAddProjectTitle'), {
description: t('sessions.sidebar.directory.errorAddProjectDescription'),
});
return;
}
setSelectedId(added.id);
} else if (result.error && result.error !== 'Directory selection cancelled') {
toast.error(t('sessions.sidebar.directory.errorSelectDirectoryTitle'), {
description: result.error,
});
}
})
.catch((error) => {
console.error('Failed to select directory:', error);
toast.error(t('sessions.sidebar.directory.errorSelectDirectoryTitle'));
});
}, [addProject, setSelectedId, tauriIpcAvailable, t]);
sessionEvents.requestDirectoryDialog();
}, []);
React.useEffect(() => {
if (projects.length === 0) {
@@ -9,19 +9,24 @@ import {
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DirectoryTree } from './DirectoryTree';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useFileSystemAccess } from '@/hooks/useFileSystemAccess';
import { cn, formatPathForDisplay } from '@/lib/utils';
import { cn } from '@/lib/utils';
import { toast } from '@/components/ui';
import {
RiArrowDownSLine,
RiArrowLeftSLine,
RiArrowUpSLine,
RiCheckboxBlankLine,
RiCheckboxLine,
RiCornerDownLeftLine,
RiFolder6Line,
RiFolderAddLine,
} from '@remixicon/react';
import { useDeviceInfo } from '@/lib/device';
import { MobileOverlayPanel } from '@/components/ui/MobileOverlayPanel';
import { DirectoryAutocomplete, type DirectoryAutocompleteHandle } from './DirectoryAutocomplete';
import { opencodeClient } from '@/lib/opencode/client';
import {
setDirectoryShowHidden,
useDirectoryShowHidden,
@@ -33,100 +38,327 @@ interface DirectoryExplorerDialogProps {
onOpenChange: (open: boolean) => void;
}
type BrowseEntry = {
name: string;
path: string;
};
type BrowseRow =
| { type: 'up'; value: 'browse:up'; name: string; path: string | null; disabled?: false }
| { type: 'directory'; value: string; name: string; path: string; disabled: boolean };
const isRootPath = (value: string): boolean => value === '/';
const normalizeSeparators = (value: string): string => value.replace(/\\/g, '/');
const trimTrailingSeparators = (value: string): string => {
if (!value || isRootPath(value)) return value;
let result = value;
while (result.length > 1 && result.endsWith('/')) {
result = result.slice(0, -1);
}
return result;
};
const hasTrailingPathSeparator = (value: string): boolean => value.endsWith('/');
const ensureBrowseDirectoryPath = (value: string): string => {
const trimmed = value.trim();
if (!trimmed || hasTrailingPathSeparator(trimmed)) return trimmed;
return `${trimmed}/`;
};
const getLastPathSeparatorIndex = (value: string): number => value.lastIndexOf('/');
const getBrowseDirectoryPath = (value: string): string => {
if (hasTrailingPathSeparator(value)) return value;
const lastSeparator = getLastPathSeparatorIndex(value);
if (lastSeparator < 0) return value;
return value.slice(0, lastSeparator + 1);
};
const getBrowseLeafPathSegment = (value: string): string => {
const lastSeparator = getLastPathSeparatorIndex(value);
return value.slice(lastSeparator + 1);
};
const getBrowseParentPath = (value: string): string | null => {
const trimmed = trimTrailingSeparators(value.trim());
if (!trimmed || trimmed === '~' || trimmed === '~/' || trimmed === '/') return null;
const lastSeparator = getLastPathSeparatorIndex(trimmed);
if (lastSeparator < 0) return null;
if (trimmed.startsWith('~/') && lastSeparator <= 1) return '~/';
if (lastSeparator === 0) return '/';
return `${trimmed.slice(0, lastSeparator)}/`;
};
const canNavigateUp = (value: string): boolean => hasTrailingPathSeparator(value) && getBrowseParentPath(value) !== null;
const appendBrowsePathSegment = (currentPath: string, segment: string): string => (
`${getBrowseDirectoryPath(currentPath)}${segment}/`
);
const normalizeDirectoryPath = (path: string | null | undefined): string | null => {
if (!path) return null;
const normalized = trimTrailingSeparators(normalizeSeparators(path.trim()));
if (!normalized) return null;
return normalized.toLowerCase();
};
const displayPathToAbsolutePath = (value: string, homeDirectory: string): string => {
const trimmed = value.trim();
if (trimmed === '~') return homeDirectory;
if (trimmed.startsWith('~/')) return `${homeDirectory}${trimmed.slice(1)}`;
return trimmed;
};
const isPrimaryModifierPressed = (event: React.KeyboardEvent<HTMLInputElement>): boolean => {
const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
return isMac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
};
const focusPathInput = (input: HTMLInputElement | null): void => {
if (!input) return;
input.focus({ preventScroll: true });
const valueLength = input.value.length;
input.setSelectionRange(valueLength, valueLength);
input.scrollLeft = input.scrollWidth;
};
const resolveFreshFilesystemHome = async (): Promise<string | null> => {
try {
const response = await fetch('/api/fs/home', {
method: 'GET',
headers: { Accept: 'application/json' },
});
if (response.ok) {
const data = await response.json() as { home?: unknown };
if (typeof data.home === 'string' && data.home.trim().length > 0) {
return normalizeSeparators(data.home.trim());
}
}
} catch {
// Fall back to the client helper below.
}
return opencodeClient.getFilesystemHome().catch(() => null);
};
export const DirectoryExplorerDialog: React.FC<DirectoryExplorerDialogProps> = ({
open,
onOpenChange,
}) => {
const { t } = useI18n();
const currentDirectory = useDirectoryStore((s) => s.currentDirectory);
const homeDirectory = useDirectoryStore((s) => s.homeDirectory);
const isHomeReady = useDirectoryStore((s) => s.isHomeReady);
const projects = useProjectsStore((s) => s.projects);
const addProject = useProjectsStore((s) => s.addProject);
const getActiveProject = useProjectsStore((s) => s.getActiveProject);
const [pendingPath, setPendingPath] = React.useState<string | null>(null);
const [pathInputValue, setPathInputValue] = React.useState('');
const [hasUserSelection, setHasUserSelection] = React.useState(false);
const [isConfirming, setIsConfirming] = React.useState(false);
const showHidden = useDirectoryShowHidden();
const { isDesktop, requestAccess, startAccessing } = useFileSystemAccess();
const { isMobile } = useDeviceInfo();
const [autocompleteVisible, setAutocompleteVisible] = React.useState(false);
const autocompleteRef = React.useRef<DirectoryAutocompleteHandle>(null);
const inputRef = React.useRef<HTMLInputElement>(null);
const addButtonRef = React.useRef<HTMLButtonElement>(null);
const rowRefs = React.useRef(new Map<string, HTMLButtonElement>());
const [dialogHomeDirectory, setDialogHomeDirectory] = React.useState('');
const [query, setQuery] = React.useState('~/');
const [entries, setEntries] = React.useState<BrowseEntry[]>([]);
const [isLoading, setIsLoading] = React.useState(false);
const [isBrowseDirectoryMissing, setIsBrowseDirectoryMissing] = React.useState(false);
const [highlightedIndex, setHighlightedIndex] = React.useState(0);
const [isConfirming, setIsConfirming] = React.useState(false);
const [isOpeningFinder, setIsOpeningFinder] = React.useState(false);
const [addButtonWidth, setAddButtonWidth] = React.useState(0);
// Helper to format path for display
const formatPath = React.useCallback((path: string | null) => {
if (!path) return '';
return formatPathForDisplay(path, homeDirectory);
}, [homeDirectory]);
const explorerRootDirectory = dialogHomeDirectory || homeDirectory;
const addedProjectPaths = React.useMemo(() => new Set(
projects
.map((project) => normalizeDirectoryPath(project.path))
.filter((path): path is string => Boolean(path))
), [projects]);
// Reset state when dialog opens
React.useEffect(() => {
if (open) {
setHasUserSelection(false);
setIsConfirming(false);
setAutocompleteVisible(false);
// Initialize with active project or current directory
const activeProject = getActiveProject();
const initialPath = activeProject?.path || currentDirectory || homeDirectory || '';
setPendingPath(initialPath);
setPathInputValue(formatPath(initialPath));
}
}, [open, currentDirectory, homeDirectory, formatPath, getActiveProject]);
if (!open) return;
setQuery('~/');
setEntries([]);
setHighlightedIndex(0);
setIsConfirming(false);
setIsOpeningFinder(false);
requestAnimationFrame(() => focusPathInput(inputRef.current));
let cancelled = false;
const resolveHome = async () => {
const resolved = await resolveFreshFilesystemHome();
if (cancelled) return;
setDialogHomeDirectory(resolved || homeDirectory || '');
requestAnimationFrame(() => focusPathInput(inputRef.current));
};
void resolveHome();
return () => {
cancelled = true;
};
}, [homeDirectory, open]);
const browseDirectoryDisplayPath = React.useMemo(() => getBrowseDirectoryPath(query), [query]);
const browseFilterQuery = React.useMemo(
() => (hasTrailingPathSeparator(query) ? '' : getBrowseLeafPathSegment(query)),
[query]
);
const browseDirectoryAbsolutePath = React.useMemo(
() => explorerRootDirectory ? displayPathToAbsolutePath(browseDirectoryDisplayPath, explorerRootDirectory) : '',
[browseDirectoryDisplayPath, explorerRootDirectory]
);
// Set initial pending path to home when ready (only if not yet selected)
React.useEffect(() => {
if (!open || hasUserSelection || pendingPath) {
if (!open || !browseDirectoryAbsolutePath) {
setEntries([]);
return;
}
if (homeDirectory && isHomeReady) {
setPendingPath(homeDirectory);
setHasUserSelection(true);
setPathInputValue('~');
}
}, [open, hasUserSelection, pendingPath, homeDirectory, isHomeReady]);
let cancelled = false;
setIsLoading(true);
setIsBrowseDirectoryMissing(false);
opencodeClient.listLocalDirectory(browseDirectoryAbsolutePath)
.then((result) => {
if (cancelled) return;
setIsBrowseDirectoryMissing(false);
const nextEntries = result
.filter((entry) => entry.isDirectory)
.map((entry) => ({
name: entry.name,
path: normalizeSeparators(entry.path),
}))
.sort((left, right) => left.name.localeCompare(right.name));
setEntries(nextEntries);
})
.catch(() => {
if (!cancelled) {
setEntries([]);
setIsBrowseDirectoryMissing(true);
}
})
.finally(() => {
if (!cancelled) setIsLoading(false);
});
return () => {
cancelled = true;
};
}, [browseDirectoryAbsolutePath, open]);
const filteredEntries = React.useMemo(() => {
const lowerFilter = browseFilterQuery.toLowerCase();
const includeHidden = showHidden || browseFilterQuery.startsWith('.');
return entries.filter((entry) => (
entry.name.toLowerCase().startsWith(lowerFilter) && (includeHidden || !entry.name.startsWith('.'))
));
}, [browseFilterQuery, entries, showHidden]);
const rows = React.useMemo<BrowseRow[]>(() => {
const nextRows: BrowseRow[] = [];
if (canNavigateUp(query)) {
nextRows.push({ type: 'up', value: 'browse:up', name: '..', path: getBrowseParentPath(query) });
}
for (const entry of filteredEntries) {
const normalized = normalizeDirectoryPath(entry.path);
nextRows.push({
type: 'directory',
value: `browse:${entry.path}`,
name: entry.name,
path: entry.path,
disabled: Boolean(normalized && addedProjectPaths.has(normalized)),
});
}
return nextRows;
}, [addedProjectPaths, filteredEntries, query]);
React.useEffect(() => {
setHighlightedIndex(0);
}, [query, rows.length]);
const targetPath = React.useMemo(() => {
if (!explorerRootDirectory) return '';
return trimTrailingSeparators(displayPathToAbsolutePath(query, explorerRootDirectory));
}, [explorerRootDirectory, query]);
const normalizedTargetPath = normalizeDirectoryPath(targetPath);
const isAlreadyAdded = Boolean(normalizedTargetPath && addedProjectPaths.has(normalizedTargetPath));
const exactEntry = React.useMemo(() => {
if (!browseFilterQuery) return null;
return filteredEntries.find((entry) => entry.name === browseFilterQuery) ?? null;
}, [browseFilterQuery, filteredEntries]);
const shouldCreateTarget = Boolean(
targetPath
&& !isAlreadyAdded
&& (
(hasTrailingPathSeparator(query) && isBrowseDirectoryMissing)
|| (!hasTrailingPathSeparator(query) && browseFilterQuery.trim().length > 0 && exactEntry === null)
)
);
const canAddProject = !isConfirming && !isOpeningFinder && !isAlreadyAdded && Boolean(targetPath);
const highlightedRow = rows[highlightedIndex] ?? null;
const hasHighlightedBrowseItem = Boolean(
highlightedRow && (highlightedRow.type === 'up' || (highlightedRow.type === 'directory' && !highlightedRow.disabled))
);
const submitModifierLabel = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform)
? '⌘'
: 'Ctrl';
const submitActionLabel = isAlreadyAdded
? t('directoryExplorerDialog.actions.alreadyAdded')
: shouldCreateTarget
? t('directoryExplorerDialog.actions.createAndAdd')
: t('directoryExplorerDialog.actions.addProject');
React.useLayoutEffect(() => {
const button = addButtonRef.current;
if (!button) return;
const updateWidth = () => setAddButtonWidth(Math.ceil(button.getBoundingClientRect().width));
updateWidth();
if (typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(updateWidth);
observer.observe(button);
return () => observer.disconnect();
}, [submitActionLabel]);
React.useLayoutEffect(() => {
const input = inputRef.current;
if (!input) return;
input.scrollLeft = input.scrollWidth;
}, [addButtonWidth, query]);
React.useLayoutEffect(() => {
if (!open) return;
focusPathInput(inputRef.current);
}, [open]);
React.useLayoutEffect(() => {
const row = rows[highlightedIndex];
if (!row) return;
rowRefs.current.get(row.value)?.scrollIntoView({ block: 'nearest' });
}, [highlightedIndex, rows]);
const handleClose = React.useCallback(() => {
onOpenChange(false);
}, [onOpenChange]);
const finalizeSelection = React.useCallback(async (targetPath: string) => {
if (!targetPath || isConfirming) {
return;
}
const finalizeSelection = React.useCallback(async (target: string) => {
if (!target || isConfirming) return;
const normalized = normalizeDirectoryPath(target);
if (normalized && addedProjectPaths.has(normalized)) return;
setIsConfirming(true);
try {
let resolvedPath = targetPath;
let projectId: string | undefined;
if (isDesktop) {
const accessResult = await requestAccess(targetPath);
if (!accessResult.success) {
toast.error(t('directoryExplorerDialog.toast.unableToAccessDirectory'), {
description: accessResult.error || t('directoryExplorerDialog.toast.desktopDeniedAccess'),
});
return;
}
resolvedPath = accessResult.path ?? targetPath;
projectId = accessResult.projectId;
const startResult = await startAccessing(resolvedPath);
if (!startResult.success) {
toast.error(t('directoryExplorerDialog.toast.failedToOpenDirectory'), {
description: startResult.error || t('directoryExplorerDialog.toast.desktopCouldNotGrantAccess'),
});
return;
}
const shouldCreateSelection = shouldCreateTarget && normalizeDirectoryPath(target) === normalizeDirectoryPath(targetPath);
if (shouldCreateSelection) {
await opencodeClient.createDirectory(target, { allowOutsideWorkspace: true });
}
const added = addProject(resolvedPath, { id: projectId });
const added = addProject(target);
if (!added) {
toast.error(t('directoryExplorerDialog.toast.failedToAddProject'), {
description: t('directoryExplorerDialog.toast.selectValidDirectoryPath'),
});
return;
}
handleClose();
} catch (error) {
toast.error(t('directoryExplorerDialog.toast.failedToSelectDirectory'), {
@@ -135,197 +367,241 @@ export const DirectoryExplorerDialog: React.FC<DirectoryExplorerDialogProps> = (
} finally {
setIsConfirming(false);
}
}, [
addProject,
handleClose,
isDesktop,
requestAccess,
startAccessing,
isConfirming,
t,
]);
}, [addProject, addedProjectPaths, handleClose, isConfirming, shouldCreateTarget, targetPath, t]);
const handleConfirm = React.useCallback(async () => {
const pathToUse = pathInputValue.trim() || pendingPath;
if (!pathToUse) {
return;
}
await finalizeSelection(pathToUse);
}, [finalizeSelection, pathInputValue, pendingPath]);
const handleSelectPath = React.useCallback((path: string) => {
setPendingPath(path);
setHasUserSelection(true);
setPathInputValue(formatPath(path));
}, [formatPath]);
const handleDoubleClickPath = React.useCallback(async (path: string) => {
setPendingPath(path);
setHasUserSelection(true);
setPathInputValue(formatPath(path));
await finalizeSelection(path);
}, [finalizeSelection, formatPath]);
const handlePathInputChange = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setPathInputValue(value);
setHasUserSelection(true);
// Show autocomplete when typing a path
setAutocompleteVisible(value.startsWith('/') || value.startsWith('~'));
// Update pending path if it looks like a valid path
if (value.startsWith('/') || value.startsWith('~')) {
// Expand ~ to home directory
const expandedPath = value.startsWith('~') && homeDirectory
? value.replace(/^~/, homeDirectory)
: value;
setPendingPath(expandedPath);
}
}, [homeDirectory]);
const handlePathInputKeyDown = React.useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
// Let autocomplete handle the key first if visible
if (autocompleteRef.current?.handleKeyDown(e)) {
return;
}
if (e.key === 'Enter') {
e.preventDefault();
handleConfirm();
}
}, [handleConfirm]);
const handleAutocompleteSuggestion = React.useCallback((path: string) => {
setPendingPath(path);
setHasUserSelection(true);
setPathInputValue(formatPath(path));
// Keep autocomplete open to allow further drilling down
}, [formatPath]);
const handleAutocompleteClose = React.useCallback(() => {
setAutocompleteVisible(false);
const browseToDisplayPath = React.useCallback((displayPath: string) => {
setQuery(ensureBrowseDirectoryPath(displayPath));
}, []);
const toggleShowHidden = React.useCallback(() => {
setDirectoryShowHidden(!showHidden);
}, [showHidden]);
const browseToEntry = React.useCallback((entry: BrowseEntry) => {
setQuery(appendBrowsePathSegment(query, entry.name));
}, [query]);
const executeRow = React.useCallback((row: BrowseRow | null) => {
if (!row) return;
if (row.type === 'up') {
if (row.path) browseToDisplayPath(row.path);
return;
}
if (row.disabled) return;
browseToEntry(row);
}, [browseToDisplayPath, browseToEntry]);
const handleOpenInFinder = React.useCallback(async () => {
if (!isDesktop || isOpeningFinder) return;
setIsOpeningFinder(true);
try {
const result = await requestAccess(targetPath);
if (!result.success || !result.path) {
if (result.error && result.error !== 'Directory selection cancelled') {
toast.error(t('directoryExplorerDialog.toast.failedToSelectDirectory'), {
description: result.error,
});
}
return;
}
const accessResult = await startAccessing(result.path);
if (!accessResult.success) {
toast.error(t('directoryExplorerDialog.toast.failedToOpenDirectory'), {
description: accessResult.error || t('directoryExplorerDialog.toast.desktopCouldNotGrantAccess'),
});
return;
}
await finalizeSelection(result.path);
} catch (error) {
toast.error(t('directoryExplorerDialog.toast.failedToSelectDirectory'), {
description: error instanceof Error ? error.message : t('directoryExplorerDialog.toast.unknownError'),
});
} finally {
setIsOpeningFinder(false);
}
}, [finalizeSelection, isDesktop, isOpeningFinder, requestAccess, startAccessing, t, targetPath]);
const handleKeyDown = React.useCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'ArrowDown') {
event.preventDefault();
setHighlightedIndex((index) => Math.min(rows.length - 1, index + 1));
return;
}
if (event.key === 'ArrowUp') {
event.preventDefault();
setHighlightedIndex((index) => Math.max(0, index - 1));
return;
}
if (event.key === 'Enter') {
event.preventDefault();
if (isPrimaryModifierPressed(event)) {
void finalizeSelection(targetPath);
return;
}
if (hasHighlightedBrowseItem) {
executeRow(highlightedRow);
}
return;
}
if (event.key === 'Backspace' && query === '') {
event.preventDefault();
handleClose();
}
}, [executeRow, finalizeSelection, handleClose, hasHighlightedBrowseItem, highlightedRow, query, rows.length, targetPath]);
const showHiddenToggle = (
<button
type="button"
onClick={toggleShowHidden}
className="flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-interactive-hover/40 transition-colors typography-meta text-muted-foreground flex-shrink-0"
onClick={() => setDirectoryShowHidden(!showHidden)}
className="flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40"
>
{showHidden ? (
<RiCheckboxLine className="h-4 w-4 text-primary" />
) : (
<RiCheckboxBlankLine className="h-4 w-4" />
)}
{showHidden ? <RiCheckboxLine className="h-4 w-4 text-primary" /> : <RiCheckboxBlankLine className="h-4 w-4" />}
{t('directoryExplorerDialog.toggle.showHidden')}
</button>
);
const dialogHeader = (
<DialogHeader className="flex-shrink-0 px-4 pb-2 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-3 sm:pt-0">
<DialogTitle>{t('directoryExplorerDialog.title')}</DialogTitle>
<div className="hidden sm:flex sm:items-center sm:justify-between sm:gap-4">
<DialogDescription className="flex-1">
{t('directoryExplorerDialog.description')}
</DialogDescription>
{showHiddenToggle}
</div>
</DialogHeader>
);
const pathInputSection = (
<div className="relative">
const inputSection = (
<div className="relative px-2.5 py-1.5">
<RiFolderAddLine className="pointer-events-none absolute left-5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80" />
<Input
value={pathInputValue}
onChange={handlePathInputChange}
onKeyDown={handlePathInputKeyDown}
ref={inputRef}
value={query}
onChange={(event) => setQuery(normalizeSeparators(event.target.value))}
onKeyDown={handleKeyDown}
placeholder={t('directoryExplorerDialog.pathInput.placeholder')}
className="font-mono typography-meta"
className="border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0"
style={!isMobile && addButtonWidth > 0 ? { paddingRight: `${addButtonWidth + 24}px` } : undefined}
spellCheck={false}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
/>
<DirectoryAutocomplete
ref={autocompleteRef}
inputValue={pathInputValue}
homeDirectory={homeDirectory}
onSelectSuggestion={handleAutocompleteSuggestion}
visible={autocompleteVisible}
onClose={handleAutocompleteClose}
showHidden={showHidden}
/>
{!isMobile ? (
<Button
ref={addButtonRef}
variant="outline"
size="xs"
tabIndex={-1}
className="absolute right-4 top-1/2 h-7 -translate-y-1/2 gap-1 px-2 typography-meta"
disabled={!canAddProject}
onMouseDown={(event) => event.preventDefault()}
onClick={() => void finalizeSelection(targetPath)}
title={submitActionLabel}
>
{submitActionLabel}
</Button>
) : null}
</div>
);
const treeSection = (
<div className="flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col">
<DirectoryTree
variant="inline"
currentPath={pendingPath ?? currentDirectory}
onSelectPath={handleSelectPath}
onDoubleClickPath={handleDoubleClickPath}
className="flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]"
selectionBehavior="deferred"
showHidden={showHidden}
rootDirectory={isHomeReady ? homeDirectory : null}
isRootReady={isHomeReady}
/>
</div>
);
// Mobile: use flex layout where tree takes remaining space
const mobileContent = (
<div className="flex h-full min-h-0 flex-col gap-3">
<div className="flex-shrink-0">{pathInputSection}</div>
<div className="flex-shrink-0 flex items-center justify-end">
{showHiddenToggle}
</div>
<div className="flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col">
<DirectoryTree
variant="inline"
currentPath={pendingPath ?? currentDirectory}
onSelectPath={handleSelectPath}
onDoubleClickPath={handleDoubleClickPath}
className="flex-1 min-h-0"
selectionBehavior="deferred"
showHidden={showHidden}
rootDirectory={isHomeReady ? homeDirectory : null}
isRootReady={isHomeReady}
alwaysShowActions
/>
const resultsSection = (
<div className="relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm">
<div className="max-h-[min(28rem,58vh)] overflow-y-auto p-2">
<div className="px-2 pb-1 pt-0.5 typography-meta font-medium uppercase tracking-wide text-muted-foreground/80">
{t('directoryExplorerDialog.browse.directories')}
</div>
{isLoading ? (
<div className="py-10 text-center typography-ui-label text-muted-foreground">
{t('directoryExplorerDialog.browse.loading')}
</div>
) : rows.length === 0 ? (
<div className="py-10 text-center typography-ui-label text-muted-foreground">
{t('directoryExplorerDialog.browse.empty')}
</div>
) : (
<div className="space-y-0.5">
{rows.map((row, index) => {
const isActive = index === highlightedIndex;
return (
<button
key={row.value}
ref={(node) => {
if (node) {
rowRefs.current.set(row.value, node);
} else {
rowRefs.current.delete(row.value);
}
}}
type="button"
disabled={row.type === 'directory' && row.disabled}
onMouseEnter={() => setHighlightedIndex(index)}
onMouseDown={(event) => event.preventDefault()}
onClick={() => executeRow(row)}
className={cn(
'flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50',
isActive && 'bg-interactive-selection text-interactive-selection-foreground',
!isActive && 'hover:bg-interactive-hover/50',
row.type === 'directory' && row.disabled && 'cursor-not-allowed opacity-45 hover:bg-transparent'
)}
>
{row.type === 'up' ? (
<RiArrowLeftSLine className="h-4 w-4 flex-shrink-0 text-muted-foreground/80" />
) : (
<RiFolder6Line className="h-4 w-4 flex-shrink-0 text-muted-foreground/80" />
)}
<span className="flex min-w-0 flex-1 items-center gap-1.5">
<span className="truncate typography-ui-label text-foreground">{row.name}</span>
</span>
{row.type === 'directory' && row.disabled ? (
<span className="rounded-full border border-border/60 px-2 py-0.5 typography-meta text-muted-foreground">
{t('directoryExplorerDialog.browse.addedBadge')}
</span>
) : null}
</button>
);
})}
</div>
)}
</div>
</div>
);
const desktopContent = (
<div className="flex-1 min-h-0 overflow-hidden flex flex-col gap-3">
{pathInputSection}
{treeSection}
const content = (
<div className="flex min-h-0 flex-1 flex-col gap-3">
{inputSection}
{resultsSection}
</div>
);
const renderActionButtons = () => (
const footerHints = (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground">
<span className="inline-flex items-center gap-1">
<RiArrowUpSLine className="h-3.5 w-3.5" />
<RiArrowDownSLine className="-ml-1 h-3.5 w-3.5" />
{t('directoryExplorerDialog.footer.navigate')}
</span>
<span className="inline-flex items-center gap-1">
<RiCornerDownLeftLine className="h-3.5 w-3.5" />
{t('directoryExplorerDialog.footer.select')}
</span>
<span className="inline-flex items-center gap-1">
<span>{submitModifierLabel}</span>
<RiCornerDownLeftLine className="h-3.5 w-3.5" />
{t('directoryExplorerDialog.footer.add')}
</span>
<span className="inline-flex items-center gap-1">
<span>Esc</span>
{t('directoryExplorerDialog.footer.close')}
</span>
</div>
);
const renderFooter = () => (
<>
<Button
variant="ghost"
onClick={handleClose}
disabled={isConfirming}
className="flex-1 sm:flex-none sm:w-auto"
>
{t('directoryExplorerDialog.actions.cancel')}
</Button>
<Button
onClick={handleConfirm}
disabled={isConfirming || !hasUserSelection || (!pendingPath && !pathInputValue.trim())}
className="flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]"
>
{isConfirming ? t('directoryExplorerDialog.actions.adding') : t('directoryExplorerDialog.actions.addProject')}
</Button>
{!isMobile ? footerHints : null}
<div className={cn('flex w-full flex-row justify-end gap-2 sm:w-auto', isMobile && 'justify-stretch')}>
{isDesktop ? (
<Button variant="ghost" size="xs" onClick={handleOpenInFinder} disabled={isConfirming || isOpeningFinder}>
{isOpeningFinder ? t('directoryExplorerDialog.actions.openingFinder') : t('directoryExplorerDialog.actions.openInFinder')}
</Button>
) : null}
<Button variant="ghost" size="xs" onClick={handleClose} disabled={isConfirming || isOpeningFinder} className={cn(isMobile && 'flex-1')}>
{t('directoryExplorerDialog.actions.cancel')}
</Button>
{isMobile ? (
<Button size="xs" onClick={() => void finalizeSelection(targetPath)} disabled={!canAddProject} className="flex-1">
{submitActionLabel}
</Button>
) : null}
</div>
</>
);
@@ -333,13 +609,16 @@ export const DirectoryExplorerDialog: React.FC<DirectoryExplorerDialogProps> = (
return (
<MobileOverlayPanel
open={open}
onClose={() => onOpenChange(false)}
onClose={handleClose}
title={t('directoryExplorerDialog.title')}
className="h-[88dvh] max-h-[720px] max-w-full"
contentMaxHeightClassName="flex-1"
footer={<div className="flex flex-row gap-2">{renderActionButtons()}</div>}
footer={<div className="flex flex-col gap-2">{renderFooter()}</div>}
>
{mobileContent}
<div className="flex h-full min-h-0 flex-col gap-3">
<div className="flex justify-end">{showHiddenToggle}</div>
{content}
</div>
</MobileOverlayPanel>
);
}
@@ -347,20 +626,21 @@ export const DirectoryExplorerDialog: React.FC<DirectoryExplorerDialogProps> = (
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className={cn(
'flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6'
)}
onOpenAutoFocus={(e) => {
// Prevent auto-focus on input to avoid text selection
e.preventDefault();
}}
className="flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]"
onOpenAutoFocus={(event) => event.preventDefault()}
>
{dialogHeader}
{desktopContent}
<DialogFooter
className="sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-4 sm:pb-0"
>
{renderActionButtons()}
<DialogHeader className="px-5 pb-2 pt-5">
<div className="flex items-start justify-between gap-4">
<div>
<DialogTitle>{t('directoryExplorerDialog.title')}</DialogTitle>
<DialogDescription className="mt-2">{t('directoryExplorerDialog.description')}</DialogDescription>
</div>
{showHiddenToggle}
</div>
</DialogHeader>
<div className="min-h-0 flex-1 px-2 pb-0">{content}</div>
<DialogFooter className="flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between">
{renderFooter()}
</DialogFooter>
</DialogContent>
</Dialog>
@@ -39,6 +39,7 @@ interface DirectoryTreeProps {
isRootReady?: boolean;
/** Always show action icons (add, pin) instead of only on hover */
alwaysShowActions?: boolean;
disabledPaths?: Iterable<string>;
}
export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
@@ -53,6 +54,7 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
rootDirectory = null,
isRootReady,
alwaysShowActions = false,
disabledPaths,
}) => {
const { t } = useI18n();
const { isMobile } = useDeviceInfo();
@@ -85,6 +87,20 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
return trimmed.length === 0 ? '/' : trimmed;
}, []);
const normalizedDisabledPaths = React.useMemo(() => {
const normalized = new Set<string>();
for (const path of disabledPaths ?? []) {
const value = stripTrailingSlashes(path.replace(/\\/g, '/'));
if (value) normalized.add(value.toLowerCase());
}
return normalized;
}, [disabledPaths, stripTrailingSlashes]);
const isPathDisabled = React.useCallback((path: string) => {
const normalized = stripTrailingSlashes(path.replace(/\\/g, '/'));
return normalized ? normalizedDisabledPaths.has(normalized.toLowerCase()) : false;
}, [normalizedDisabledPaths, stripTrailingSlashes]);
const normalizedHomeDirectory = React.useMemo(() => {
if (!homeDirectory) {
return null;
@@ -665,6 +681,7 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
const isPinned = pinnedPaths.has(item.path);
const isSelected = currentPath === item.path;
const isInlineVariant = variant === 'inline';
const isDisabled = isPathDisabled(item.path);
const rowContent = (
<>
@@ -688,6 +705,9 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
<button
onClick={(e) => {
e.stopPropagation();
if (isDisabled) {
return;
}
handleDirectorySelect(item.path);
if (variant === 'dropdown' && selectionBehavior === 'immediate') {
setIsOpen(false);
@@ -695,13 +715,15 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
}}
onDoubleClick={(e) => {
e.stopPropagation();
if (onDoubleClickPath) {
if (!isDisabled && onDoubleClickPath) {
onDoubleClickPath(item.path);
}
}}
disabled={isDisabled}
className={cn(
'flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded',
isMobile ? 'gap-1.5' : 'gap-1.5',
isDisabled && 'cursor-not-allowed opacity-45',
isInlineVariant ? (isSelected ? 'text-primary' : 'text-foreground') : 'text-foreground'
)}
>
@@ -709,6 +731,7 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
className={cn(
'text-muted-foreground flex-shrink-0',
isMobile ? 'h-4 w-4' : 'h-3.5 w-3.5',
isDisabled && 'text-muted-foreground',
isInlineVariant && isSelected && 'text-primary'
)}
/>
@@ -716,6 +739,7 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
className={cn(
'font-medium truncate',
isMobile ? 'typography-ui-label' : 'typography-ui-label',
isDisabled && 'text-muted-foreground',
isInlineVariant && isSelected ? 'text-primary' : 'text-foreground'
)}
>
@@ -768,7 +792,9 @@ export const DirectoryTree: React.FC<DirectoryTreeProps> = ({
isMobile ? 'px-1.5 py-1' : 'px-2 py-1.5',
isSelected
? 'bg-primary/10 text-primary'
: 'hover:bg-interactive-hover/50 text-foreground'
: isDisabled
? 'text-muted-foreground'
: 'hover:bg-interactive-hover/50 text-foreground'
)}
style={{ paddingLeft: `${level * (isMobile ? 12 : 14) + (isMobile ? 4 : 6)}px` }}
>
@@ -23,8 +23,6 @@ import * as sessionActions from '@/sync/session-actions';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useUIStore } from '@/stores/useUIStore';
import { useFileSystemAccess } from '@/hooks/useFileSystemAccess';
import { isDesktopLocalOriginActive, isTauriShell } from '@/lib/desktop';
import { useDeviceInfo } from '@/lib/device';
import { sessionEvents } from '@/lib/sessionEvents';
import { useI18n } from '@/lib/i18n';
@@ -76,9 +74,7 @@ export const SessionDialogs: React.FC = () => {
const homeDirectory = useDirectoryStore((s) => s.homeDirectory);
const isHomeReady = useDirectoryStore((s) => s.isHomeReady);
const projects = useProjectsStore((s) => s.projects);
const addProject = useProjectsStore((s) => s.addProject);
const activeProjectId = useProjectsStore((s) => s.activeProjectId);
const { requestAccess, startAccessing } = useFileSystemAccess();
const { isMobile, isTablet, hasTouchInput } = useDeviceInfo();
const useMobileOverlay = isMobile || isTablet || hasTouchInput;
@@ -126,49 +122,11 @@ export const SessionDialogs: React.FC = () => {
setHasShownInitialDirectoryPrompt(true);
if (isTauriShell() && isDesktopLocalOriginActive()) {
requestAccess('')
.then(async (result) => {
if (!result.success || !result.path) {
if (result.error && result.error !== 'Directory selection cancelled') {
toast.error(t('sessions.sidebar.sessionDialogs.directory.errorSelectTitle'), {
description: result.error,
});
}
return;
}
const accessResult = await startAccessing(result.path);
if (!accessResult.success) {
toast.error(t('sessions.sidebar.sessionDialogs.directory.errorOpenTitle'), {
description: accessResult.error || t('sessions.sidebar.sessionDialogs.directory.errorOpenDescription'),
});
return;
}
const added = addProject(result.path, { id: result.projectId });
if (!added) {
toast.error(t('sessions.sidebar.sessionDialogs.directory.errorAddProjectTitle'), {
description: t('sessions.sidebar.sessionDialogs.directory.errorAddProjectDescription'),
});
}
})
.catch((error) => {
console.error('Desktop: Error selecting directory:', error);
toast.error(t('sessions.sidebar.sessionDialogs.directory.errorSelectTitle'));
});
return;
}
setIsDirectoryDialogOpen(true);
}, [
addProject,
hasShownInitialDirectoryPrompt,
isHomeReady,
projects.length,
requestAccess,
startAccessing,
t,
]);
const openDeleteDialog = React.useCallback((payload: { sessions: Session[]; dateLabel?: string; mode?: 'session' | 'worktree'; worktree?: WorktreeMetadata | null }) => {
@@ -4,7 +4,7 @@ import { RiLayoutLeftLine } from '@remixicon/react';
import { toast } from '@/components/ui';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useI18n } from '@/lib/i18n';
import { isDesktopLocalOriginActive, isDesktopShell, isTauriShell } from '@/lib/desktop';
import { isDesktopShell } from '@/lib/desktop';
import { isDesktopWindowFullscreen as getDesktopWindowFullscreen, onDesktopWindowResized, startDesktopWindowDrag } from '@/lib/desktopNative';
import { sessionEvents } from '@/lib/sessionEvents';
import { formatDirectoryName, cn } from '@/lib/utils';
@@ -249,7 +249,6 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
const projects = useProjectsStore((state) => state.projects);
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
const addProject = useProjectsStore((state) => state.addProject);
const removeProject = useProjectsStore((state) => state.removeProject);
const setActiveProjectIdOnly = useProjectsStore((state) => state.setActiveProjectIdOnly);
const updateProjectMeta = useProjectsStore((state) => state.updateProjectMeta);
@@ -430,7 +429,6 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
};
}, []);
const tauriIpcAvailable = React.useMemo(() => isTauriShell(), []);
const isDesktopShellRuntime = React.useMemo(() => isDesktopShell(), []);
const [isDesktopWindowFullscreen, setIsDesktopWindowFullscreen] = React.useState(false);
@@ -690,32 +688,8 @@ export const SessionSidebar: React.FC<SessionSidebarProps> = ({
}, [deleteFolderConfirm, deleteFolder]);
const handleOpenDirectoryDialog = React.useCallback(() => {
if (!tauriIpcAvailable || !isDesktopLocalOriginActive()) {
sessionEvents.requestDirectoryDialog();
return;
}
import('@/lib/desktop')
.then(({ requestDirectoryAccess }) => requestDirectoryAccess(''))
.then((result) => {
if (result.success && result.path) {
const added = addProject(result.path, { id: result.projectId });
if (!added) {
toast.error(t('sessions.sidebar.directory.errorAddProjectTitle'), {
description: t('sessions.sidebar.directory.errorAddProjectDescription'),
});
}
} else if (result.error && result.error !== 'Directory selection cancelled') {
toast.error(t('sessions.sidebar.directory.errorSelectDirectoryTitle'), {
description: result.error,
});
}
})
.catch((error) => {
console.error('Desktop: Error selecting directory:', error);
toast.error(t('sessions.sidebar.directory.errorSelectDirectoryTitle'));
});
}, [addProject, t, tauriIpcAvailable]);
sessionEvents.requestDirectoryDialog();
}, []);
// Auto-expand parent session when navigating to a subagent (child) session
React.useEffect(() => {