Files
openchamber/packages/ui/src/components/session/DirectoryExplorerDialog.tsx
T
Bohdan Triapitsyn 18c5b4c7b5 feat: add multi-project support (#110)
* feat: Implement project management store with project path validation and synchronization

- Added `useProjectsStore` for managing projects, including adding, removing, renaming, and validating project paths.
- Implemented persistence for projects and active project ID using safe storage.
- Introduced synchronization from desktop settings to keep project data consistent.
- Enhanced session store to manage sessions by directory and added new methods for session management.
- Updated todo store to fetch session todos based on the directory context.
- Refactored server code to validate and resolve project directories for various API endpoints.
- Added project entry validation and sanitization to ensure data integrity.

* feat(settings): migrate legacy project settings and update settings loading logic

* feat: enhance project management with directory-aware settings and improved agent/command source handling

* feat: enhance session and project management with directory-aware settings and improved configuration refresh logic

* feat: enhance project management with worktree manager integration and project directory resolution

* feat: enhance agent groups store with project directory resolution and loading logic

* feat: add heartbeat management and global wrapping for SSE blocks in agent and chat providers

* feat: refactor command and project handling in useCommandsStore

- Replaced useDirectoryStore with useProjectsStore to manage project paths.
- Introduced getRequestDirectory function to determine the active project directory.
- Updated command fetching to respect project-level scoping.
- Enhanced error handling and logging for command configuration fetching.
- Improved command configuration saving and updating to utilize project directory context.

feat: enhance project path normalization in useProjectsStore

- Added resolveTildePath function to expand paths starting with ~.
- Updated normalizeProjectPath to utilize home directory for path expansion.

fix: update permission handling in useSessionStore

- Changed Permission type to PermissionRequest for clarity.
- Updated respondToPermission method to use requestId instead of permissionId.

refactor: improve permission utilities

- Introduced types for PermissionAction and PermissionRule.
- Enhanced getAgentDefinition and resolveConfigStore functions for better type safety.
- Added resolvePermissionAction to streamline permission resolution logic.

feat: add agent configuration retrieval endpoint

- Implemented new API endpoint to fetch agent configuration based on project directory.
- Enhanced getAgentPermissionSource to prioritize project-level permissions.

chore: update SDK version in package.json files

- Bumped @opencode-ai/sdk version to ^1.1.1 across all relevant package.json files.

refactor: streamline bridge message handling

- Updated handleBridgeMessage to accept directory parameter for agent and command requests.
- Improved local API request handling to extract directory from query parameters and headers.

feat: enhance project configuration management

- Added functions to retrieve and merge project configuration paths.
- Improved handling of existing project configuration files for agents and commands.

* feat: enhance VSCode integration and session management

- Added support for a sticky sidebar header background in light and dark themes.
- Introduced functions to read VSCode workspace directory and check if running in VSCode.
- Implemented detailed logging for session loading and creation processes.
- Enhanced session filtering based on directory structure and canonical paths.
- Added a new method to reorder projects and prevent modifications in VSCode workspace.
- Improved error handling and logging for app initialization and markdown file parsing.
- Updated API checks and health checks to ensure readiness before proceeding.
- Refactored code for better readability and maintainability across various modules.

* feat: improve agent and branch selection logic, enhance session management, and update multi-run creation response

* feat: add worktree management actions in agent group detail and sidebar, including delete and keep only options

* fix(ui): share IME guard and cover multi-run

* fix(session): reduce maximum visible sessions in group from 7 to 5
2026-01-06 21:31:04 +02:00

356 lines
11 KiB
TypeScript

import React from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} 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 { toast } from 'sonner';
import {
RiCheckboxBlankLine,
RiCheckboxLine,
} from '@remixicon/react';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { useDeviceInfo } from '@/lib/device';
import { MobileOverlayPanel } from '@/components/ui/MobileOverlayPanel';
const SHOW_HIDDEN_STORAGE_KEY = 'directoryTreeShowHidden';
interface DirectoryExplorerDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export const DirectoryExplorerDialog: React.FC<DirectoryExplorerDialogProps> = ({
open,
onOpenChange,
}) => {
const { currentDirectory, homeDirectory, isHomeReady } = useDirectoryStore();
const { addProject, getActiveProject } = useProjectsStore();
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, setShowHidden] = React.useState<boolean>(() => {
if (typeof window === 'undefined') {
return false;
}
try {
const stored = window.localStorage.getItem(SHOW_HIDDEN_STORAGE_KEY);
if (stored === 'true') {
return true;
}
if (stored === 'false') {
return false;
}
} catch { /* ignored */ }
return false;
});
const { isDesktop, requestAccess, startAccessing } = useFileSystemAccess();
const { isMobile } = useDeviceInfo();
// Helper to format path for display
const formatPath = React.useCallback((path: string | null) => {
if (!path) return '';
return formatPathForDisplay(path, homeDirectory);
}, [homeDirectory]);
// Reset state when dialog opens
React.useEffect(() => {
if (open) {
setHasUserSelection(false);
setIsConfirming(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]);
// Set initial pending path to home when ready (only if not yet selected)
React.useEffect(() => {
if (!open || hasUserSelection || pendingPath) {
return;
}
if (homeDirectory && isHomeReady) {
setPendingPath(homeDirectory);
setHasUserSelection(true);
setPathInputValue('~');
}
}, [open, hasUserSelection, pendingPath, homeDirectory, isHomeReady]);
// Persist show hidden setting
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
try {
window.localStorage.setItem(SHOW_HIDDEN_STORAGE_KEY, showHidden ? 'true' : 'false');
} catch { /* ignored */ }
}, [showHidden]);
const handleClose = React.useCallback(() => {
onOpenChange(false);
}, [onOpenChange]);
const finalizeSelection = React.useCallback(async (targetPath: string) => {
if (!targetPath || isConfirming) {
return;
}
setIsConfirming(true);
try {
let resolvedPath = targetPath;
let projectId: string | undefined;
if (isDesktop) {
const accessResult = await requestAccess(targetPath);
if (!accessResult.success) {
toast.error('Unable to access directory', {
description: accessResult.error || 'Desktop denied directory access.',
});
return;
}
resolvedPath = accessResult.path ?? targetPath;
projectId = accessResult.projectId;
const startResult = await startAccessing(resolvedPath);
if (!startResult.success) {
toast.error('Failed to open directory', {
description: startResult.error || 'Desktop could not grant file access.',
});
return;
}
}
const added = addProject(resolvedPath, { id: projectId });
if (!added) {
toast.error('Failed to add project', {
description: 'Please select a valid directory path.',
});
return;
}
handleClose();
} catch (error) {
toast.error('Failed to select directory', {
description: error instanceof Error ? error.message : 'Unknown error occurred.',
});
} finally {
setIsConfirming(false);
}
}, [
addProject,
handleClose,
isDesktop,
requestAccess,
startAccessing,
isConfirming,
]);
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);
// 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>) => {
if (e.key === 'Enter') {
e.preventDefault();
handleConfirm();
}
}, [handleConfirm]);
const toggleShowHidden = React.useCallback(() => {
setShowHidden(prev => !prev);
}, []);
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>Add project directory</DialogTitle>
<DialogDescription className="hidden sm:block">
Choose a folder to add as a project.
</DialogDescription>
</DialogHeader>
);
const pathInputSection = (
<Input
value={pathInputValue}
onChange={handlePathInputChange}
onKeyDown={handlePathInputKeyDown}
placeholder="Enter path or select from tree..."
className="font-mono typography-meta"
spellCheck={false}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
/>
);
const treeSection = (
<div className="flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 sm:p-2 sm:flex-none">
<DirectoryTree
variant="inline"
currentPath={pendingPath ?? currentDirectory}
onSelectPath={handleSelectPath}
onDoubleClickPath={handleDoubleClickPath}
className="h-full sm:min-h-[280px] sm:h-[380px]"
selectionBehavior="deferred"
showHidden={showHidden}
rootDirectory={isHomeReady ? homeDirectory : null}
isRootReady={isHomeReady}
/>
</div>
);
const showHiddenToggle = (
<button
type="button"
onClick={toggleShowHidden}
className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground"
>
{showHidden ? (
<RiCheckboxLine className="h-4 w-4 text-primary" />
) : (
<RiCheckboxBlankLine className="h-4 w-4" />
)}
Show hidden
</button>
);
// Mobile: use flex layout where tree takes remaining space
const mobileContent = (
<div className="flex flex-col gap-3 h-full">
<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 p-1.5 overflow-hidden">
<DirectoryTree
variant="inline"
currentPath={pendingPath ?? currentDirectory}
onSelectPath={handleSelectPath}
onDoubleClickPath={handleDoubleClickPath}
className="h-full"
selectionBehavior="deferred"
showHidden={showHidden}
rootDirectory={isHomeReady ? homeDirectory : null}
isRootReady={isHomeReady}
alwaysShowActions
/>
</div>
</div>
);
const desktopContent = (
<ScrollableOverlay
outerClassName="flex-1 min-h-0 overflow-hidden"
className="directory-dialog-body sm:px-0 sm:pb-0 flex flex-col gap-3"
>
{pathInputSection}
<div className="flex items-center justify-end">
{showHiddenToggle}
</div>
{treeSection}
</ScrollableOverlay>
);
const renderActionButtons = () => (
<>
<Button
variant="ghost"
onClick={handleClose}
disabled={isConfirming}
className="flex-1 sm:flex-none sm:w-auto"
>
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 ? 'Adding...' : 'Add Project'}
</Button>
</>
);
if (isMobile) {
return (
<MobileOverlayPanel
open={open}
onClose={() => onOpenChange(false)}
title="Add project directory"
className="max-w-full"
contentMaxHeightClassName="max-h-[min(70vh,520px)] h-[min(70vh,520px)]"
footer={<div className="flex flex-row gap-2">{renderActionButtons()}</div>}
>
{mobileContent}
</MobileOverlayPanel>
);
}
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();
}}
>
{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-3"
>
{renderActionButtons()}
</DialogFooter>
</DialogContent>
</Dialog>
);
};