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
13 changes: 13 additions & 0 deletions src-tauri/src/bin/codex_monitor_daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,20 @@ impl DaemonState {
result
}

async fn is_workspace_path_dir(&self, path: String) -> bool {
PathBuf::from(&path).is_dir()
}

async fn add_workspace(
&self,
path: String,
codex_bin: Option<String>,
client_version: String,
) -> Result<WorkspaceInfo, String> {
if !PathBuf::from(&path).is_dir() {
return Err("Workspace path must be a folder.".to_string());
}

let name = PathBuf::from(&path)
.file_name()
.and_then(|s| s.to_str())
Expand Down Expand Up @@ -1474,6 +1482,11 @@ async fn handle_rpc_request(
let workspaces = state.list_workspaces().await;
serde_json::to_value(workspaces).map_err(|err| err.to_string())
}
"is_workspace_path_dir" => {
let path = parse_string(&params, "path")?;
let is_dir = state.is_workspace_path_dir(path).await;
serde_json::to_value(is_dir).map_err(|err| err.to_string())
}
"add_workspace" => {
let path = parse_string(&params, "path")?;
let codex_bin = parse_optional_string(&params, "codex_bin");
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ pub fn run() {
settings::update_app_settings,
codex::codex_doctor,
workspaces::list_workspaces,
workspaces::is_workspace_path_dir,
workspaces::add_workspace,
workspaces::add_clone,
workspaces::add_worktree,
Expand Down
23 changes: 23 additions & 0 deletions src-tauri/src/workspaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,25 @@ pub(crate) async fn list_workspaces(
Ok(result)
}

#[tauri::command]
pub(crate) async fn is_workspace_path_dir(
path: String,
state: State<'_, AppState>,
app: AppHandle,
) -> Result<bool, String> {
if remote_backend::is_remote_mode(&*state).await {
let response = remote_backend::call_remote(
&*state,
app,
"is_workspace_path_dir",
json!({ "path": path }),
)
.await?;
return serde_json::from_value(response).map_err(|err| err.to_string());
}
Ok(PathBuf::from(&path).is_dir())
}

#[tauri::command]
pub(crate) async fn add_workspace(
path: String,
Expand All @@ -429,6 +448,10 @@ pub(crate) async fn add_workspace(
return serde_json::from_value(response).map_err(|err| err.to_string());
}

if !PathBuf::from(&path).is_dir() {
return Err("Workspace path must be a folder.".to_string());
}

let name = PathBuf::from(&path)
.file_name()
.and_then(|s| s.to_str())
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"height": 700,
"minWidth": 360,
"minHeight": 600,
"dragDropEnabled": false,
"dragDropEnabled": true,
"titleBarStyle": "Overlay",
"hiddenTitle": true,
"transparent": true,
Expand Down
116 changes: 110 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { AlignLeft, Columns2 } from "lucide-react";
import { AlignLeft, Columns2, FolderOpen } from "lucide-react";
import "./styles/base.css";
import "./styles/buttons.css";
import "./styles/sidebar.css";
Expand Down Expand Up @@ -37,6 +37,7 @@ import { TabletLayout } from "./features/layout/components/TabletLayout";
import { PhoneLayout } from "./features/layout/components/PhoneLayout";
import { useLayoutNodes } from "./features/layout/hooks/useLayoutNodes";
import { useWorkspaces } from "./features/workspaces/hooks/useWorkspaces";
import { useWorkspaceDropZone } from "./features/workspaces/hooks/useWorkspaceDropZone";
import { useThreads } from "./features/threads/hooks/useThreads";
import { useWindowDrag } from "./features/layout/hooks/useWindowDrag";
import { useGitStatus } from "./features/git/hooks/useGitStatus";
Expand Down Expand Up @@ -342,6 +343,8 @@ function MainApp() {
activeWorkspaceId,
setActiveWorkspaceId,
addWorkspace,
addWorkspaceFromPath,
filterWorkspacePaths,
addCloneAgent,
addWorktreeAgent,
connectWorkspace,
Expand Down Expand Up @@ -1389,14 +1392,21 @@ function MainApp() {
listThreadsForWorkspace
});

const handleWorkspaceAdded = useCallback(
(workspace: WorkspaceInfo) => {
setActiveThreadId(null, workspace.id);
if (isCompact) {
setActiveTab("codex");
}
},
[isCompact, setActiveTab, setActiveThreadId],
);

const handleAddWorkspace = useCallback(async () => {
try {
const workspace = await addWorkspace();
if (workspace) {
setActiveThreadId(null, workspace.id);
if (isCompact) {
setActiveTab("codex");
}
handleWorkspaceAdded(workspace);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
Expand All @@ -1409,7 +1419,75 @@ function MainApp() {
});
alert(`Failed to add workspace.\n\n${message}`);
}
}, [addDebugEntry, addWorkspace, isCompact, setActiveTab, setActiveThreadId]);
}, [addDebugEntry, addWorkspace, handleWorkspaceAdded]);

const handleAddWorkspaceFromPath = useCallback(
async (path: string) => {
try {
const workspace = await addWorkspaceFromPath(path);
if (workspace) {
handleWorkspaceAdded(workspace);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
addDebugEntry({
id: `${Date.now()}-client-add-workspace-error`,
timestamp: Date.now(),
source: "error",
label: "workspace/add error",
payload: message
});
alert(`Failed to add workspace.\n\n${message}`);
}
},
[addDebugEntry, addWorkspaceFromPath, handleWorkspaceAdded],
);

const dropIndicatorTimeoutRef = useRef<number | null>(null);
const [dropIndicatorActive, setDropIndicatorActive] = useState(false);
const showDropAddIndicator = useCallback(() => {
setDropIndicatorActive(true);
if (dropIndicatorTimeoutRef.current !== null) {
window.clearTimeout(dropIndicatorTimeoutRef.current);
}
dropIndicatorTimeoutRef.current = window.setTimeout(() => {
dropIndicatorTimeoutRef.current = null;
setDropIndicatorActive(false);
}, 900);
}, []);

useEffect(() => {
return () => {
if (dropIndicatorTimeoutRef.current !== null) {
window.clearTimeout(dropIndicatorTimeoutRef.current);
}
};
}, []);

const handleDropWorkspacePaths = useCallback(
async (paths: string[]) => {
showDropAddIndicator();
const uniquePaths = Array.from(
new Set(paths.map((path) => path.trim()).filter(Boolean)),
);
const allowedPaths = await filterWorkspacePaths(uniquePaths);
allowedPaths.forEach((path) => {
void handleAddWorkspaceFromPath(path);
});
},
[filterWorkspacePaths, handleAddWorkspaceFromPath, showDropAddIndicator],
);

const {
dropTargetRef: workspaceDropTargetRef,
isDragOver: isWorkspaceDropActive,
handleDragOver: handleWorkspaceDragOver,
handleDragEnter: handleWorkspaceDragEnter,
handleDragLeave: handleWorkspaceDragLeave,
handleDrop: handleWorkspaceDrop,
} = useWorkspaceDropZone({
onDropPaths: handleDropWorkspacePaths,
});

const handleAddAgent = useCallback(
async (workspace: (typeof workspaces)[number]) => {
Expand Down Expand Up @@ -1678,6 +1756,10 @@ function MainApp() {
onDebug: addDebugEntry,
});
const isDefaultScale = Math.abs(uiScale - 1) < 0.001;
const dropOverlayActive = isWorkspaceDropActive || dropIndicatorActive;
const dropOverlayText = isWorkspaceDropActive
? "Drop Project Here"
: "Adding Project...";
const appClassName = `app ${isCompact ? "layout-compact" : "layout-desktop"}${
isPhone ? " layout-phone" : ""
}${isTablet ? " layout-tablet" : ""}${
Expand Down Expand Up @@ -2096,9 +2178,31 @@ function MainApp() {
"--ui-scale": String(uiScale)
} as React.CSSProperties
}
ref={workspaceDropTargetRef}
onDragOver={handleWorkspaceDragOver}
onDragEnter={handleWorkspaceDragEnter}
onDragLeave={handleWorkspaceDragLeave}
onDrop={handleWorkspaceDrop}
>
<div className="drag-strip" id="titlebar" data-tauri-drag-region />
<TitlebarExpandControls {...sidebarToggleProps} />
<div
className={`workspace-drop-overlay${
dropOverlayActive ? " is-active" : ""
}`}
aria-hidden
>
<div
className={`workspace-drop-overlay-text${
dropOverlayText === "Adding Project..." ? " is-busy" : ""
}`}
>
{dropOverlayText === "Drop Project Here" && (
<FolderOpen className="workspace-drop-overlay-icon" aria-hidden />
)}
{dropOverlayText}
</div>
</div>
{isPhone ? (
<PhoneLayout
approvalToastsNode={approvalToastsNode}
Expand Down
1 change: 1 addition & 0 deletions src/features/threads/hooks/useThreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,7 @@ export function useThreads({
getCustomName,
handleWorkspaceConnected,
handleItemUpdate,
handleTerminalInteraction,
handleToolOutputDelta,
markProcessing,
onDebug,
Expand Down
113 changes: 113 additions & 0 deletions src/features/workspaces/hooks/useWorkspaceDropZone.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/** @vitest-environment jsdom */
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useWorkspaceDropZone } from "./useWorkspaceDropZone";

let mockOnDragDropEvent:
| ((event: {
payload: {
type: "enter" | "over" | "leave" | "drop";
position: { x: number; y: number };
paths: string[];
};
}) => void)
| null = null;

vi.mock("@tauri-apps/api/window", () => ({
getCurrentWindow: () => ({
onDragDropEvent: (handler: typeof mockOnDragDropEvent) => {
mockOnDragDropEvent = handler;
return Promise.resolve(() => {});
},
}),
}));

type HookResult = ReturnType<typeof useWorkspaceDropZone>;

type RenderedHook = {
result: HookResult;
unmount: () => void;
};

function renderDropHook(options: {
disabled?: boolean;
onDropPaths: (paths: string[]) => void | Promise<void>;
}): RenderedHook {
let result: HookResult | undefined;

function Test() {
result = useWorkspaceDropZone(options);
return null;
}

const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);

act(() => {
root.render(React.createElement(Test));
});

return {
get result() {
if (!result) {
throw new Error("Hook not rendered");
}
return result;
},
unmount: () => {
act(() => {
root.unmount();
});
container.remove();
},
};
}

describe("useWorkspaceDropZone", () => {
beforeEach(() => {
mockOnDragDropEvent = null;
});

it("tracks drag over state for file transfers", () => {
const hook = renderDropHook({ onDropPaths: () => {} });
const preventDefault = vi.fn();

act(() => {
hook.result.handleDragOver({
dataTransfer: { types: ["Files"] },
preventDefault,
} as unknown as React.DragEvent<HTMLElement>);
});

expect(preventDefault).toHaveBeenCalled();
expect(hook.result.isDragOver).toBe(true);

act(() => {
hook.result.handleDragLeave({} as React.DragEvent<HTMLElement>);
});

expect(hook.result.isDragOver).toBe(false);

hook.unmount();
});

it("emits file paths on drop when available", () => {
const onDropPaths = vi.fn();
const hook = renderDropHook({ onDropPaths });
const file = new File(["data"], "project", { type: "application/octet-stream" });
(file as File & { path?: string }).path = "/tmp/project";

act(() => {
hook.result.handleDrop({
dataTransfer: { files: [file], items: [] },
preventDefault: () => {},
} as unknown as React.DragEvent<HTMLElement>);
});

expect(onDropPaths).toHaveBeenCalledWith(["/tmp/project"]);

hook.unmount();
});
});
Loading