Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(views): pick the local directory execution mode while creating a project (MUL-5707) (#6901)

Bohan Jiang940b9adf44b8
diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.json
index 1c6225bf8e..715c34348f 100644
--- a/packages/views/locales/en/projects.json
+++ b/packages/views/locales/en/projects.json
@@ -134,7 +134,8 @@
"mode_badge_worktree": "Parallel",
"mode_badge_worktree_tooltip": "Tasks run at the same time in their own git worktree and hand back a branch. Your working copy is untouched.",
"toast_local_mode_updated": "Execution mode updated",
- "toast_local_mode_update_failed": "Could not update the execution mode"
+ "toast_local_mode_update_failed": "Could not update the execution mode",
+ "mode_badge_in_place": "Direct"
},
"delete_dialog": {
"title": "Delete project",
diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.json
index e60f19c46b..2f7a8323ee 100644
--- a/packages/views/locales/ja/projects.json
+++ b/packages/views/locales/ja/projects.json
@@ -133,7 +133,8 @@
"mode_badge_worktree": "並行",
"mode_badge_worktree_tooltip": "タスクはそれぞれの git ワークツリーで同時に実行され、ブランチとして成果を返します。作業コピーは変更されません。",
"toast_local_mode_updated": "実行モードを更新しました",
- "toast_local_mode_update_failed": "実行モードを更新できませんでした"
+ "toast_local_mode_update_failed": "実行モードを更新できませんでした",
+ "mode_badge_in_place": "直接"
},
"delete_dialog": {
"title": "プロジェクトを削除",
diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.json
index 11f53f131d..fa2153f26c 100644
--- a/packages/views/locales/ko/projects.json
+++ b/packages/views/locales/ko/projects.json
@@ -133,7 +133,8 @@
"mode_badge_worktree": "병렬",
"mode_badge_worktree_tooltip": "작업이 각자의 git 워크트리에서 동시에 실행되고 브랜치로 결과를 돌려줍니다. 작업 사본은 변경되지 않습니다.",
"toast_local_mode_updated": "실행 모드를 업데이트했습니다",
- "toast_local_mode_update_failed": "실행 모드를 업데이트하지 못했습니다"
+ "toast_local_mode_update_failed": "실행 모드를 업데이트하지 못했습니다",
+ "mode_badge_in_place": "직접"
},
"delete_dialog": {
"title": "프로젝트 삭제",
diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.json
index 88edbe63a5..607ffcfac7 100644
--- a/packages/views/locales/zh-Hans/projects.json
+++ b/packages/views/locales/zh-Hans/projects.json
@@ -133,7 +133,8 @@
"mode_badge_worktree": "并行",
"mode_badge_worktree_tooltip": "任务在各自的 git worktree 中同时运行,并以分支形式交付结果。你的工作区不会被改动。",
"toast_local_mode_updated": "已更新执行方式",
- "toast_local_mode_update_failed": "无法更新执行方式"
+ "toast_local_mode_update_failed": "无法更新执行方式",
+ "mode_badge_in_place": "原地"
},
"delete_dialog": {
"title": "删除项目",
diff --git a/packages/views/modals/create-project-local-mode.test.tsx b/packages/views/modals/create-project-local-mode.test.tsx
new file mode 100644
index 0000000000..1da32687a8
--- /dev/null
+++ b/packages/views/modals/create-project-local-mode.test.tsx
@@ -0,0 +1,302 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { renderWithI18n } from "../test/i18n";
+
+// Runtime list drives the worktree version gate. Each test sets the reported
+// CLI version before rendering.
+let runtimeCliVersion = "9.9.9";
+// What the desktop validator reports for the picked folder.
+let pickedIsGitRepo: boolean | undefined = true;
+
+const createProjectMock = vi.fn().mockResolvedValue({ id: "p1", slug: "p1" });
+
+// jsdom has no IntersectionObserver; the modal's scroll affordances construct
+// one, and the resulting rejection aborts the submit handler mid-flight.
+class NoopIntersectionObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ takeRecords() {
+ return [];
+ }
+}
+vi.stubGlobal("IntersectionObserver", NoopIntersectionObserver);
+
+vi.mock("@tanstack/react-query", () => ({
+ // Query-aware: the modal issues several. Only the runtime list matters here;
+ // returning runtimes for all of them would feed them to the member/agent
+ // pickers, which expect a different shape.
+ useQuery: (options: { queryKey?: unknown[] }) => {
+ const key = options?.queryKey?.[0];
+ if (key === "members" || key === "agents") return { data: [] };
+ return {
+ data: [{ daemon_id: "daemon-1", metadata: { cli_version: runtimeCliVersion } }],
+ };
+ },
+ // runtimeListOptions builds its descriptor with this; the mocked useQuery
+ // reads queryKey off it, so an identity passthrough is enough.
+ queryOptions: (options: unknown) => options,
+}));
+
+vi.mock("@multica/core/projects/mutations", () => ({
+ useCreateProject: () => ({ mutateAsync: createProjectMock }),
+}));
+
+vi.mock("@multica/core/projects", () => ({
+ useProjectDraftStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ draft: {
+ title: "Game Client",
+ description: "",
+ status: "planned",
+ priority: "none",
+ icon: "📁",
+ leadId: null,
+ leadType: null,
+ startDate: null,
+ dueDate: null,
+ repos: [],
+ },
+ setDraft: vi.fn(),
+ clearDraft: vi.fn(),
+ resetDraft: vi.fn(),
+ }),
+}));
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "workspace-1", slug: "ws", repos: [] }),
+ useWorkspacePaths: () => ({ projectDetail: (id: string) => `/ws/projects/${id}` }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
+ agentListOptions: () => ({ queryKey: ["agents"], queryFn: vi.fn() }),
+}));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: vi.fn() }),
+}));
+vi.mock("../navigation", () => ({ useNavigation: () => ({ push: vi.fn() }) }));
+vi.mock("../editor", () => {
+ const ContentEditor = React.forwardRef<HTMLTextAreaElement, { placeholder?: string }>(
+ ({ placeholder }, ref) => <textarea ref={ref} placeholder={placeholder} />,
+ );
+ ContentEditor.displayName = "ContentEditor";
+ return {
+ ContentEditor,
+ TitleEditor: ({
+ placeholder,
+ onChange,
+ }: {
+ placeholder?: string;
+ onChange?: (value: string) => void;
+ }) => <input placeholder={placeholder} onChange={(e) => onChange?.(e.target.value)} />,
+ };
+});
+vi.mock("../issues/components/priority-icon", () => ({ PriorityIcon: () => <span /> }));
+vi.mock("../common/actor-avatar", () => ({ ActorAvatar: () => <span /> }));
+vi.mock("../projects/components/project-start-date-picker", () => ({
+ ProjectStartDatePicker: () => <button type="button">Start date</button>,
+}));
+vi.mock("../projects/components/project-due-date-picker", () => ({
+ ProjectDueDatePicker: () => <button type="button">Due date</button>,
+}));
+
+// Desktop-only surface: without these the Local directory tab never renders.
+vi.mock("../platform/local-directory", () => ({
+ isDesktopShell: () => true,
+ pickDirectory: () =>
+ Promise.resolve({ ok: true, path: "/Users/dev/work/game-client", basename: "game-client" }),
+ validateLocalDirectory: () => Promise.resolve({ ok: true, is_git_repo: pickedIsGitRepo }),
+}));
+vi.mock("../platform/use-local-daemon-status", () => ({
+ useLocalDaemonStatus: () => ({ daemonId: "daemon-1", deviceName: "MacBook", running: true }),
+}));
+
+// Render overlays inline so their contents are assertable.
+vi.mock("@multica/ui/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+vi.mock("@multica/ui/components/ui/popover", () => ({
+ Popover: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ PopoverTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
+ PopoverContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ DropdownMenuTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ DropdownMenuItem: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) => (
+ <button type="button" onClick={onClick}>
+ {children}
+ </button>
+ ),
+}));
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+import { CreateProjectModal, buildLocalDirectoryResourceRef } from "./create-project";
+
+async function pickLocalDirectory(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(screen.getByRole("button", { name: /Local directory/i }));
+ await user.click(screen.getByRole("button", { name: /Choose directory/i }));
+ await waitFor(() => expect(screen.getByText("/Users/dev/work/game-client")).toBeInTheDocument());
+}
+
+describe("CreateProjectModal — local directory execution mode", () => {
+ beforeEach(() => {
+ createProjectMock.mockClear();
+ runtimeCliVersion = "9.9.9";
+ pickedIsGitRepo = true;
+ });
+
+ // Preselection, not a silent default change: a git repo the runtime can
+ // actually run worktree mode on starts on parallel, because that is the mode
+ // that fits — and the user sees it selected in a control they can flip before
+ // creating anything.
+ it("preselects parallel for a git repository", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ expect(screen.getByRole("button", { name: /^Parallel$/i })).toBeInTheDocument();
+ expect(screen.getByRole("radio", { name: /Run in parallel, isolated/i })).toHaveAttribute(
+ "aria-checked",
+ "true",
+ );
+ });
+
+ it("preselects direct for a plain folder", async () => {
+ pickedIsGitRepo = false;
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument();
+ });
+
+ // A runtime that cannot run the mode must not be preselected into it, or the
+ // create call would be rejected by the server's version gate.
+ it("preselects direct when the daemon is too old, even for a git repository", async () => {
+ runtimeCliVersion = "0.1.0";
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument();
+ });
+
+ // Older desktop builds do not report is_git_repo. The option stays available
+ // (the daemon has the final say), but we do not guess parallel on the user's
+ // behalf without evidence.
+ it("preselects direct when the desktop build cannot report git-ness", async () => {
+ pickedIsGitRepo = undefined;
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument();
+ // Still selectable — unknown is permissive about what the user MAY choose.
+ expect(screen.getByRole("radio", { name: /Run in parallel, isolated/i })).not.toBeDisabled();
+ });
+
+ // The preselection is a starting point, not a correction: once the user says
+ // what they want, a later folder change must not silently undo it.
+ it("keeps an explicit choice when the folder changes to another git repository", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+ await user.click(screen.getByRole("radio", { name: /Edit this folder directly/i }));
+ expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument();
+
+ // Re-pick (the mocked picker returns the same git repo).
+ await user.click(screen.getByRole("button", { name: /Change directory/i }));
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument(),
+ );
+ });
+
+ // The whole point of this entry point: the mode is part of setting the
+ // folder up, not something to go and change afterwards.
+ it("offers the mode next to the change-directory action once a folder is picked", async () => {
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ // The compact button uses the short label; the picker carries the full
+ // title. A git repo preselects parallel, so that is the label here.
+ expect(screen.getByRole("button", { name: /^Parallel$/i })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Change directory/i })).toBeInTheDocument();
+ });
+
+ // The server refuses to save a worktree resource below the version floor, and
+ // here that rejection would fail the whole project creation — so the option
+ // has to be blocked before submit, not after.
+ it("blocks parallel mode when the daemon is too old", async () => {
+ runtimeCliVersion = "0.1.0";
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ const worktreeOption = screen.getByRole("radio", { name: /Run in parallel, isolated/i });
+ expect(worktreeOption).toBeDisabled();
+ expect(screen.getByText(/needs 0\.4\.24 or newer/i)).toBeInTheDocument();
+ });
+
+ it("blocks parallel mode for a folder that is not a git repository", async () => {
+ pickedIsGitRepo = false;
+ const user = userEvent.setup();
+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);
+
+ await pickLocalDirectory(user);
+
+ expect(screen.getByRole("radio", { name: /Run in parallel, isolated/i })).toBeDisabled();
+ expect(screen.getByText(/not a git repository/i)).toBeInTheDocument();
+ });
+});
+
+// The payload is what the server stores and the daemon later reads; a missing
+// or wrong execution_mode is invisible until a task actually runs. Asserted on
+// the builder directly rather than through a full modal submit, which drags in
+// unrelated modal machinery without testing anything more about this contract.
+describe("buildLocalDirectoryResourceRef", () => {
+ it("carries the chosen mode", () => {
+ expect(
+ buildLocalDirectoryResourceRef({
+ localPath: "/Users/dev/work/game-client",
+ daemonId: "daemon-1",
+ label: "game-client",
+ mode: "worktree",
+ }),
+ ).toEqual({
+ local_path: "/Users/dev/work/game-client",
+ daemon_id: "daemon-1",
+ label: "game-client",
+ execution_mode: "worktree",
+ });
+ });
+
+ it("defaults are explicit: in_place is sent, not omitted", () => {
+ // The server treats an absent field as in_place, but sending it keeps the
+ // stored ref self-describing for anyone reading it later.
+ expect(
+ buildLocalDirectoryResourceRef({
+ localPath: "/tmp/x",
+ daemonId: "d",
+ label: null,
+ mode: "in_place",
+ }),
+ ).toEqual({ local_path: "/tmp/x", daemon_id: "d", execution_mode: "in_place" });
+ });
+});
diff --git a/packages/views/modals/create-project.test.tsx b/packages/views/modals/create-project.test.tsx
index 0f517cd5f6..74b9d2b3a5 100644
--- a/packages/views/modals/create-project.test.tsx
+++ b/packages/views/modals/create-project.test.tsx
@@ -11,6 +11,9 @@ const webRepoUrl = "https://github.com/multica-ai/web";
vi.mock("@tanstack/react-query", () => ({
useQuery: () => ({ data: [] }),
+ // The modal now reads the runtime list to gate worktree mode, and
+ // runtimeListOptions builds its descriptor with queryOptions.
+ queryOptions: (options: unknown) => options,
}));
vi.mock("@multica/core/projects/mutations", () => ({
diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsx
index 71193727b8..39a10602e1 100644
--- a/packages/views/modals/create-project.tsx
+++ b/packages/views/modals/create-project.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, useRef } from "react";
-import { CalendarClock, CalendarDays, ChevronRight, FolderOpen, Maximize2, Minimize2, MoreHorizontal, Search, X as XIcon, UserMinus } from "lucide-react";
+import { CalendarClock, CalendarDays, ChevronRight, FolderOpen, GitBranch, Maximize2, Minimize2, MoreHorizontal, Pencil, Search, X as XIcon, UserMinus } from "lucide-react";
/**
* GitHub mark — lucide-react v1 dropped brand icons, so we inline the
@@ -67,6 +67,42 @@ import {
validateLocalDirectory,
} from "../platform/local-directory";
import { useLocalDaemonStatus } from "../platform/use-local-daemon-status";
+import {
+ MIN_LOCAL_WORKTREE_CLI_VERSION,
+ localWorktreeSupported,
+ readRuntimeCliVersion,
+ runtimeListOptions,
+} from "@multica/core/runtimes";
+import type { LocalDirectoryExecutionMode } from "@multica/core/types";
+import { LocalDirectoryModeOptions } from "../projects/components/local-directory-mode-dialog";
+
+/**
+ * Builds the resource_ref for a local directory attached during project
+ * creation.
+ *
+ * Exported so the execution-mode contract can be asserted directly: this is the
+ * payload the server stores and the daemon later reads to decide whether tasks
+ * edit the user's folder or hand back a branch, and getting `execution_mode`
+ * wrong here is invisible until a task runs.
+ */
+export function buildLocalDirectoryResourceRef({
+ localPath,
+ daemonId,
+ label,
+ mode,
+}: {
+ localPath: string;
+ daemonId: string;
+ label: string | null;
+ mode: LocalDirectoryExecutionMode;
+}): Record<string, unknown> {
+ return {
+ local_path: localPath,
+ daemon_id: daemonId,
+ ...(label ? { label } : {}),
+ execution_mode: mode,
+ };
+}
function RepoUrlText({
url,
@@ -93,6 +129,9 @@ function RepoUrlText({
export function CreateProjectModal({ onClose }: { onClose: () => void }) {
const { t } = useT("modals");
+ // The execution-mode copy lives in the projects namespace alongside the
+ // resource panel's, so both entry points describe the choice identically.
+ const { t: tProjects } = useT("projects");
const router = useNavigation();
const workspace = useCurrentWorkspace();
const workspaceName = workspace?.name;
@@ -150,6 +189,55 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
const [selectedLocalLabel, setSelectedLocalLabel] = useState<string | null>(null);
const [localPickError, setLocalPickError] = useState<string | null>(null);
const [localPicking, setLocalPicking] = useState(false);
+ // Execution mode is chosen here rather than after creation: it decides
+ // whether tasks edit this folder or hand back a branch, which is part of
+ // what the user is setting up, not a setting to discover later.
+ //
+ // null means "the user has not picked one" — distinct from an explicit
+ // in_place. Only then does the folder-derived preselection apply, so an
+ // explicit choice is never overridden by a later folder change.
+ const [localMode, setLocalMode] = useState<LocalDirectoryExecutionMode | null>(null);
+ // undefined = could not check (older desktop build); the daemon re-checks
+ // authoritatively, so unknown stays permissive.
+ const [localIsGitRepo, setLocalIsGitRepo] = useState<boolean | undefined>(undefined);
+ const [localModeOpen, setLocalModeOpen] = useState(false);
+
+ // Worktree mode needs a daemon new enough to implement it; the server refuses
+ // to save the resource otherwise. In this flow the resource is attached in the
+ // same call that creates the project, so an un-caught rejection would fail the
+ // whole creation — check up front and disable the option instead.
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
+ const localDaemonCliVersion = daemonStatus.daemonId
+ ? (runtimes
+ .filter((rt) => rt.daemon_id === daemonStatus.daemonId)
+ .map((rt) => readRuntimeCliVersion(rt.metadata))
+ .find((v) => v && v.length > 0) ?? "")
+ : "";
+ const worktreeUnavailableReason =
+ localIsGitRepo === false
+ ? ("not_git" as const)
+ : !localWorktreeSupported(localDaemonCliVersion)
+ ? ("daemon_outdated" as const)
+ : undefined;
+ // Preselection, not a default behavior change: when the folder is a git repo
+ // and the runtime can actually run worktree mode, parallel is the better fit,
+ // so it starts selected — visibly, in a control the user can flip in one
+ // click before creating anything. A plain folder starts on direct.
+ //
+ // `localIsGitRepo === undefined` (an older desktop build that doesn't report
+ // it) preselects direct. The asymmetry is deliberate: permissive about what
+ // the user MAY choose, conservative about what we choose FOR them.
+ const preselectedLocalMode: LocalDirectoryExecutionMode =
+ localIsGitRepo === true && worktreeUnavailableReason === undefined
+ ? "worktree"
+ : "in_place";
+ // Never submit a mode the picker would have blocked — the folder can change
+ // after a mode was chosen (pick a git repo, choose worktree, then pick a
+ // plain folder), and the stale choice would fail at task time.
+ const effectiveLocalMode: LocalDirectoryExecutionMode =
+ worktreeUnavailableReason !== undefined
+ ? "in_place"
+ : (localMode ?? preselectedLocalMode);
const handleSourceModeChange = (mode: "repos" | "local") => {
setSourceMode(mode);
@@ -179,6 +267,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
}
setSelectedLocalPath(picked.path);
setSelectedLocalLabel(picked.basename ?? null);
+ setLocalIsGitRepo(validation.is_git_repo);
} finally {
setLocalPicking(false);
}
@@ -188,6 +277,8 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
setSelectedLocalPath(null);
setSelectedLocalLabel(null);
setLocalPickError(null);
+ setLocalIsGitRepo(undefined);
+ setLocalMode(null);
};
// Sync field changes to draft store
@@ -237,11 +328,12 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
resources = [
{
resource_type: "local_directory" as const,
- resource_ref: {
- local_path: selectedLocalPath,
- daemon_id: daemonStatus.daemonId,
- ...(selectedLocalLabel ? { label: selectedLocalLabel } : {}),
- },
+ resource_ref: buildLocalDirectoryResourceRef({
+ localPath: selectedLocalPath,
+ daemonId: daemonStatus.daemonId,
+ label: selectedLocalLabel,
+ mode: effectiveLocalMode,
+ }),
},
];
}
@@ -763,16 +855,61 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {
<XIcon className="size-3" />
</button>
</div>
- <Button
- type="button"
- size="sm"
- variant="ghost"
- className="h-6 w-full text-caption"
- onClick={handlePickLocalDirectory}
- disabled={localPicking || !daemonStatus.running}
- >
- {t(($) => $.create_project.local_change)}
- </Button>
+ <div className="flex items-center gap-1.5">
+ <Popover open={localModeOpen} onOpenChange={setLocalModeOpen}>
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ // Sized to its (short) label so the wider
+ // "Change directory…" beside it fits whole.
+ className="h-6 shrink-0 text-caption"
+ >
+ {effectiveLocalMode === "worktree" ? (
+ <GitBranch className="size-3 shrink-0" />
+ ) : (
+ <Pencil className="size-3 shrink-0" />
+ )}
+ {/* Short labels: the panel is ~380px wide and
+ two buttons share it, so the full option
+ titles truncate to uselessness. The picker
+ below carries the full wording. */}
+ <span className="truncate">
+ {effectiveLocalMode === "worktree"
+ ? tProjects(($) => $.resources.mode_badge_worktree)
+ : tProjects(($) => $.resources.mode_badge_in_place)}
+ </span>
+ </Button>
+ }
+ />
+ <PopoverContent align="start" className="w-80 p-2">
+ <LocalDirectoryModeOptions
+ value={effectiveLocalMode}
+ onChange={(mode) => {
+ setLocalMode(mode);
+ setLocalModeOpen(false);
+ }}
+ unavailableReason={worktreeUnavailableReason}
+ currentVersion={localDaemonCliVersion}
+ minVersion={MIN_LOCAL_WORKTREE_CLI_VERSION}
+ />
+ </PopoverContent>
+ </Popover>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-6 flex-1 min-w-0 text-caption"
+ onClick={handlePickLocalDirectory}
+ disabled={localPicking || !daemonStatus.running}
+ >
+ <span className="truncate">
+ {t(($) => $.create_project.local_change)}
+ </span>
+ </Button>
+ </div>
</div>
) : (
<Button
diff --git a/packages/views/projects/components/local-directory-mode-dialog.tsx b/packages/views/projects/components/local-directory-mode-dialog.tsx
index 89cadef1f0..a2116c5ade 100644
--- a/packages/views/projects/components/local-directory-mode-dialog.tsx
+++ b/packages/views/projects/components/local-directory-mode-dialog.tsx
@@ -75,8 +75,6 @@ export function LocalDirectoryModeDialog({
if (open) setSelected(value);
}, [open, value]);
- const worktreeDisabled = unavailableReason !== undefined;
-
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
@@ -91,38 +89,13 @@ export function LocalDirectoryModeDialog({
{path}
</div>
- <div className="flex flex-col gap-2">
- <ModeOption
- icon={<Pencil className="size-4" />}
- title={t(($) => $.resources.mode_in_place_title)}
- description={t(($) => $.resources.mode_in_place_description)}
- identifier="in_place"
- selected={selected === "in_place"}
- onSelect={() => setSelected("in_place")}
- />
- <ModeOption
- icon={<GitBranch className="size-4" />}
- title={t(($) => $.resources.mode_worktree_title)}
- description={t(($) => $.resources.mode_worktree_description)}
- identifier="worktree"
- selected={selected === "worktree"}
- disabled={worktreeDisabled}
- disabledReason={
- unavailableReason === "not_git"
- ? t(($) => $.resources.mode_worktree_needs_git)
- : unavailableReason === "daemon_outdated"
- ? t(($) => $.resources.mode_worktree_needs_upgrade, {
- current:
- currentVersion && currentVersion.length > 0
- ? currentVersion
- : t(($) => $.resources.mode_version_unknown),
- min: minVersion ?? "",
- })
- : undefined
- }
- onSelect={() => setSelected("worktree")}
- />
- </div>
+ <LocalDirectoryModeOptions
+ value={selected}
+ onChange={setSelected}
+ unavailableReason={unavailableReason}
+ currentVersion={currentVersion}
+ minVersion={minVersion}
+ />
{errorMessage && (
<div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-caption text-destructive">
@@ -148,6 +121,67 @@ export function LocalDirectoryModeDialog({
);
}
+interface LocalDirectoryModeOptionsProps {
+ value: LocalDirectoryExecutionMode;
+ onChange: (mode: LocalDirectoryExecutionMode) => void;
+ unavailableReason?: WorktreeUnavailableReason;
+ currentVersion?: string;
+ minVersion?: string;
+}
+
+/**
+ * The two-option choice itself, without any surrounding chrome.
+ *
+ * Shared so the dialog (editing an existing resource) and the compact picker in
+ * the create-project modal offer literally the same options, copy and blocked
+ * states — the decision is identical, only the container differs.
+ */
+export function LocalDirectoryModeOptions({
+ value,
+ onChange,
+ unavailableReason,
+ currentVersion,
+ minVersion,
+}: LocalDirectoryModeOptionsProps) {
+ const { t } = useT("projects");
+ const worktreeDisabled = unavailableReason !== undefined;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <ModeOption
+ icon={<Pencil className="size-4" />}
+ title={t(($) => $.resources.mode_in_place_title)}
+ description={t(($) => $.resources.mode_in_place_description)}
+ identifier="in_place"
+ selected={value === "in_place"}
+ onSelect={() => onChange("in_place")}
+ />
+ <ModeOption
+ icon={<GitBranch className="size-4" />}
+ title={t(($) => $.resources.mode_worktree_title)}
+ description={t(($) => $.resources.mode_worktree_description)}
+ identifier="worktree"
+ selected={value === "worktree"}
+ disabled={worktreeDisabled}
+ disabledReason={
+ unavailableReason === "not_git"
+ ? t(($) => $.resources.mode_worktree_needs_git)
+ : unavailableReason === "daemon_outdated"
+ ? t(($) => $.resources.mode_worktree_needs_upgrade, {
+ current:
+ currentVersion && currentVersion.length > 0
+ ? currentVersion
+ : t(($) => $.resources.mode_version_unknown),
+ min: minVersion ?? "",
+ })
+ : undefined
+ }
+ onSelect={() => onChange("worktree")}
+ />
+ </div>
+ );
+}
+
interface ModeOptionProps {
icon: React.ReactNode;
title: string;
diff --git a/packages/views/projects/components/project-resources-section.tsx b/packages/views/projects/components/project-resources-section.tsx
index 4ff94acf68..80d34ff773 100644
--- a/packages/views/projects/components/project-resources-section.tsx
+++ b/packages/views/projects/components/project-resources-section.tsx
@@ -238,7 +238,15 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
setModeDialog({
path,
daemonId: localDaemonId,
- mode: "in_place",
+ // Same preselection rule as the create-project flow: a git repo this
+ // daemon can actually run worktree mode on starts on parallel, anything
+ // else starts on direct. Only the PRESELECTION differs by folder — the
+ // user still confirms, and existing resources keep whatever they have.
+ mode:
+ validation.is_git_repo === true &&
+ localWorktreeSupported(cliVersionForDaemon(localDaemonId))
+ ? "worktree"
+ : "in_place",
isGitRepo: validation.is_git_repo,
label: fallbackLabel,
});