Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/browser/App.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ function setupMockAPI(options: {
data: { projectConfig: { workspaces: [] }, normalizedPath: "/mock/project/path" },
}),
remove: () => Promise.resolve({ success: true, data: undefined }),
pickDirectory: () => Promise.resolve(null),
listBranches: () =>
Promise.resolve({
branches: ["main", "develop", "feature/new-feature"],
Expand Down
4 changes: 4 additions & 0 deletions src/browser/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,13 +193,17 @@ const webApi: IPCApi = {
calculateStats: (messages, model) =>
invokeIPC(IPC_CHANNELS.TOKENIZER_CALCULATE_STATS, messages, model),
},
fs: {
listDirectory: (root) => invokeIPC(IPC_CHANNELS.FS_LIST_DIRECTORY, root),
},
providers: {
setProviderConfig: (provider, keyPath, value) =>
invokeIPC(IPC_CHANNELS.PROVIDERS_SET_CONFIG, provider, keyPath, value),
list: () => invokeIPC(IPC_CHANNELS.PROVIDERS_LIST),
},
projects: {
create: (projectPath) => invokeIPC(IPC_CHANNELS.PROJECT_CREATE, projectPath),
pickDirectory: () => Promise.resolve(null),
remove: (projectPath) => invokeIPC(IPC_CHANNELS.PROJECT_REMOVE, projectPath),
list: () => invokeIPC(IPC_CHANNELS.PROJECT_LIST),
listBranches: (projectPath) => invokeIPC(IPC_CHANNELS.PROJECT_LIST_BRANCHES, projectPath),
Expand Down
119 changes: 119 additions & 0 deletions src/browser/components/DirectoryPickerModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import React, { useCallback, useEffect, useState } from "react";
import { Modal, ModalActions, CancelButton, PrimaryButton } from "./Modal";
import type { FileTreeNode } from "@/common/utils/git/numstatParser";
import { DirectoryTree } from "./DirectoryTree";
import type { IPCApi } from "@/common/types/ipc";

interface DirectoryPickerModalProps {
isOpen: boolean;
initialPath: string;
onClose: () => void;
onSelectPath: (path: string) => void;
}

export const DirectoryPickerModal: React.FC<DirectoryPickerModalProps> = ({
isOpen,
initialPath,
onClose,
onSelectPath,
}) => {
type FsListDirectoryResponse = FileTreeNode & { success?: boolean; error?: unknown };
const [root, setRoot] = useState<FileTreeNode | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

const loadDirectory = useCallback(async (path: string) => {
const api = window.api as unknown as IPCApi;
if (!api.fs?.listDirectory) {
setError("Directory picker is not available in this environment.");
return;
}

setIsLoading(true);
setError(null);

try {
const tree = (await api.fs.listDirectory(path)) as FsListDirectoryResponse;

// In browser/server mode, HttpIpcMainAdapter wraps handler errors as
// { success: false, error }, and invokeIPC returns that object instead
// of throwing. Detect that shape and surface a friendly error instead
// of crashing when accessing tree.children.
if (tree.success === false) {
const errorMessage = typeof tree.error === "string" ? tree.error : "Unknown error";
setError(`Failed to load directory: ${errorMessage}`);
setRoot(null);
return;
}

setRoot(tree);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
setError(`Failed to load directory: ${message}`);
setRoot(null);
} finally {
setIsLoading(false);
}
}, []);

useEffect(() => {
if (!isOpen) return;
void loadDirectory(initialPath || ".");
}, [isOpen, initialPath, loadDirectory]);

const handleNavigateTo = useCallback(
(path: string) => {
void loadDirectory(path);
},
[loadDirectory]
);

const handleNavigateParent = useCallback(() => {
if (!root) return;
void loadDirectory(`${root.path}/..`);
}, [loadDirectory, root]);

const handleConfirm = useCallback(() => {
if (!root) {
return;
}

onSelectPath(root.path);
onClose();
}, [onClose, onSelectPath, root]);

if (!isOpen) return null;
const entries =
root?.children
.filter((child) => child.isDirectory)
.map((child) => ({ name: child.name, path: child.path })) ?? [];

return (
<Modal
isOpen={isOpen}
title="Select Project Directory"
subtitle={root ? root.path : "Select a directory to use as your project root"}
onClose={onClose}
isLoading={isLoading}
>
{error && <div className="text-error mb-3 text-xs">{error}</div>}
<div className="bg-modal-bg border-border-medium mb-4 h-64 overflow-hidden rounded border">
<DirectoryTree
currentPath={root ? root.path : null}
entries={entries}
isLoading={isLoading}
onNavigateTo={handleNavigateTo}
onNavigateParent={handleNavigateParent}
/>
</div>
<ModalActions>
<CancelButton onClick={onClose} disabled={isLoading}>
Cancel
</CancelButton>
<PrimaryButton onClick={() => void handleConfirm()} disabled={isLoading || !root}>
Select
</PrimaryButton>
</ModalActions>
</Modal>
);
};
64 changes: 64 additions & 0 deletions src/browser/components/DirectoryTree.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React from "react";

interface DirectoryTreeEntry {
name: string;
path: string;
}

interface DirectoryTreeProps {
currentPath: string | null;
entries: DirectoryTreeEntry[];
isLoading?: boolean;
onNavigateTo: (path: string) => void;
onNavigateParent: () => void;
}

export const DirectoryTree: React.FC<DirectoryTreeProps> = (props) => {
const { currentPath, entries, isLoading = false, onNavigateTo, onNavigateParent } = props;

const hasEntries = entries.length > 0;
const containerRef = React.useRef<HTMLDivElement | null>(null);

React.useEffect(() => {
if (containerRef.current) {
containerRef.current.scrollTop = 0;
}
}, [currentPath]);

return (
<div ref={containerRef} className="h-full overflow-y-auto p-2 font-mono text-xs">
{isLoading && !currentPath ? (
<div className="text-muted py-4 text-center">Loading directories...</div>
) : (
<ul className="m-0 list-none p-0">
{currentPath && (
<li
className="text-muted cursor-pointer rounded px-2 py-1 text-xs hover:bg-white/5"
onClick={onNavigateParent}
>
...
</li>
)}

{!isLoading && !hasEntries ? (
<li className="text-muted px-2 py-1 text-xs">No subdirectories found</li>
) : null}

{entries.map((entry) => (
<li
key={entry.path}
className="text-muted cursor-pointer rounded px-2 py-1 text-xs hover:bg-white/5"
onClick={() => onNavigateTo(entry.path)}
>
{entry.name}
</li>
))}

{isLoading && currentPath && !hasEntries ? (
<li className="text-muted px-2 py-1 text-xs">Loading directories...</li>
) : null}
</ul>
)}
</div>
);
};
111 changes: 82 additions & 29 deletions src/browser/components/ProjectCreateModal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React, { useState, useCallback } from "react";
import { Modal, ModalActions, CancelButton, PrimaryButton } from "./Modal";
import type { IPCApi } from "@/common/types/ipc";
import { DirectoryPickerModal } from "./DirectoryPickerModal";
import type { ProjectConfig } from "@/node/config";

interface ProjectCreateModalProps {
Expand All @@ -21,14 +23,37 @@ export const ProjectCreateModal: React.FC<ProjectCreateModalProps> = ({
}) => {
const [path, setPath] = useState("");
const [error, setError] = useState("");
// Detect desktop environment where native directory picker is available
const isDesktop =
window.api.platform !== "browser" && typeof window.api.projects.pickDirectory === "function";
const api = window.api as unknown as IPCApi;
const hasWebFsPicker = window.api.platform === "browser" && !!api.fs?.listDirectory;
const [isCreating, setIsCreating] = useState(false);
const [isDirPickerOpen, setIsDirPickerOpen] = useState(false);

const handleCancel = useCallback(() => {
setPath("");
setError("");
onClose();
}, [onClose]);

const handleWebPickerPathSelected = useCallback((selected: string) => {
setPath(selected);
setError("");
}, []);

const handleBrowse = useCallback(async () => {
try {
const selectedPath = await window.api.projects.pickDirectory();
if (selectedPath) {
setPath(selectedPath);
setError("");
}
} catch (err) {
console.error("Failed to pick directory:", err);
}
}, []);

const handleSelect = useCallback(async () => {
const trimmedPath = path.trim();
if (!trimmedPath) {
Expand Down Expand Up @@ -78,6 +103,14 @@ export const ProjectCreateModal: React.FC<ProjectCreateModalProps> = ({
}
}, [path, onSuccess, onClose]);

const handleBrowseClick = useCallback(() => {
if (isDesktop) {
void handleBrowse();
} else if (hasWebFsPicker) {
setIsDirPickerOpen(true);
}
}, [handleBrowse, hasWebFsPicker, isDesktop]);

const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Enter") {
Expand All @@ -89,35 +122,55 @@ export const ProjectCreateModal: React.FC<ProjectCreateModalProps> = ({
);

return (
<Modal
isOpen={isOpen}
title="Add Project"
subtitle="Enter the path to your project directory"
onClose={handleCancel}
isLoading={isCreating}
>
<input
type="text"
value={path}
onChange={(e) => {
setPath(e.target.value);
setError("");
}}
onKeyDown={handleKeyDown}
placeholder="/home/user/projects/my-project"
autoFocus
disabled={isCreating}
className="bg-modal-bg border-border-medium focus:border-accent placeholder:text-muted mb-5 w-full rounded border px-3 py-2 font-mono text-sm text-white focus:outline-none disabled:opacity-50"
<>
<Modal
isOpen={isOpen}
title="Add Project"
subtitle="Enter the path to your project directory"
onClose={handleCancel}
isLoading={isCreating}
>
<div className="mb-5 flex gap-2">
<input
type="text"
value={path}
onChange={(e) => {
setPath(e.target.value);
setError("");
}}
onKeyDown={handleKeyDown}
placeholder="/home/user/projects/my-project"
autoFocus
disabled={isCreating}
className="bg-modal-bg border-border-medium focus:border-accent placeholder:text-muted w-full flex-1 rounded border px-3 py-2 font-mono text-sm text-white focus:outline-none disabled:opacity-50"
/>
{(isDesktop || hasWebFsPicker) && (
<button
type="button"
onClick={handleBrowseClick}
disabled={isCreating}
className="bg-border-medium hover:bg-border-darker border-border-medium rounded border px-4 text-sm font-medium text-white transition-colors disabled:opacity-50"
>
Browse...
</button>
)}
</div>
{error && <div className="text-error -mt-3 mb-3 text-xs">{error}</div>}
<ModalActions>
<CancelButton onClick={handleCancel} disabled={isCreating}>
Cancel
</CancelButton>
<PrimaryButton onClick={() => void handleSelect()} disabled={isCreating}>
{isCreating ? "Adding..." : "Add Project"}
</PrimaryButton>
</ModalActions>
</Modal>
<DirectoryPickerModal
isOpen={isDirPickerOpen}
initialPath={path || "."}
onClose={() => setIsDirPickerOpen(false)}
onSelectPath={handleWebPickerPathSelected}
/>
{error && <div className="text-error -mt-3 mb-3 text-xs">{error}</div>}
<ModalActions>
<CancelButton onClick={handleCancel} disabled={isCreating}>
Cancel
</CancelButton>
<PrimaryButton onClick={() => void handleSelect()} disabled={isCreating}>
{isCreating ? "Adding..." : "Add Project"}
</PrimaryButton>
</ModalActions>
</Modal>
</>
);
};
1 change: 1 addition & 0 deletions src/browser/contexts/ProjectContext.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ function createMockAPI(overrides: Partial<IPCApi["projects"]>) {
data: undefined,
}))
),
pickDirectory: mock(overrides.pickDirectory ?? (() => Promise.resolve(null))),
secrets: {
get: mock(
overrides.secrets?.get
Expand Down
2 changes: 2 additions & 0 deletions src/common/constants/ipc-constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ export const IPC_CHANNELS = {
PROVIDERS_LIST: "providers:list",

// Project channels
PROJECT_PICK_DIRECTORY: "project:pickDirectory",
PROJECT_CREATE: "project:create",
PROJECT_REMOVE: "project:remove",
PROJECT_LIST: "project:list",
PROJECT_LIST_BRANCHES: "project:listBranches",
PROJECT_SECRETS_GET: "project:secrets:get",
FS_LIST_DIRECTORY: "fs:listDirectory",
PROJECT_SECRETS_UPDATE: "project:secrets:update",

// Workspace channels
Expand Down
Loading