Skip to content

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

Go
53.1 KB
Raw Blame
"use client";

import { useState, useRef } from "react";
import { CalendarClock, CalendarDays, ChevronRight, FolderOpen, GitBranch, Maximize2, Minimize2, MoreHorizontal, Pencil, Search, X as XIcon, User, UserMinus } from "@multica/ui/icons";

/**
 * GitHub mark — lucide-react v1 dropped brand icons, so we inline the
 * Octicon-style mark here (24×24 viewBox, currentColor fill so it inherits
 * the parent's text color). Stays in this file because there's only one
 * caller; promote to packages/ui if a second use crops up.
 */
function GithubIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="currentColor"
      aria-hidden="true"
      className={className}
    >
      <path d="M12 .5C5.73.5.66 5.57.66 11.84c0 5.01 3.25 9.26 7.76 10.76.57.1.78-.25.78-.55 0-.27-.01-1.17-.02-2.13-3.16.69-3.83-1.34-3.83-1.34-.52-1.31-1.27-1.66-1.27-1.66-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.68 1.24 3.34.95.1-.74.4-1.24.72-1.53-2.52-.29-5.18-1.26-5.18-5.62 0-1.24.45-2.26 1.18-3.06-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.17a10.93 10.93 0 0 1 5.74 0c2.19-1.48 3.15-1.17 3.15-1.17.62 1.57.23 2.73.11 3.02.74.8 1.18 1.82 1.18 3.06 0 4.37-2.67 5.32-5.21 5.61.41.35.78 1.04.78 2.1 0 1.52-.01 2.74-.01 3.11 0 .3.21.66.79.55 4.51-1.5 7.76-5.75 7.76-10.76C23.34 5.57 18.27.5 12 .5Z" />
    </svg>
  );
}
import { useQuery } from "@tanstack/react-query";
import { useCreateProject } from "@multica/core/projects/mutations";
import { useProjectDraftStore } from "@multica/core/projects";
import {
  PROJECT_STATUS_CONFIG,
  PROJECT_STATUS_ORDER,
  PROJECT_PRIORITY_ORDER,
} from "@multica/core/projects/config";
import { splitGithubUrlRef } from "@multica/core/github";
import { useWorkspaceId } from "@multica/core/hooks";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
import { useActorName } from "@multica/core/workspace/hooks";
import type { ProjectStatus, ProjectPriority, ProjectVisibility } from "@multica/core/types";
import { cn } from "@multica/ui/lib/utils";
import { toast } from "sonner";
import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";
import { Collapsible, CollapsibleContent } from "@multica/ui/components/ui/collapsible";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { Popover, PopoverTrigger, PopoverContent } from "@multica/ui/components/ui/popover";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
import { Button } from "@multica/ui/components/ui/button";
import { EmojiPicker } from "@multica/ui/components/common/emoji-picker";
import { ContentEditor, type ContentEditorRef, TitleEditor } from "../editor";
import { PriorityIcon } from "../issues/components/priority-icon";
import { ActorAvatar } from "../common/actor-avatar";
import { useNavigation } from "../navigation";
import { useT } from "../i18n";
import { matchesPinyin } from "../editor/extensions/pinyin-match";
import {
  useProjectStatusLabels,
  useProjectPriorityLabels,
} from "../projects/components/labels";
import { ProjectStartDatePicker } from "../projects/components/project-start-date-picker";
import { ProjectDueDatePicker } from "../projects/components/project-due-date-picker";
import { ProjectAccessDraftPicker } from "../projects/components/project-access";
import { usePaidFeatureErrorMessage } from "../billing";
import { PillButton } from "../common/pill-button";
import { WorkflowPill } from "../workflows/workflow-pill";
import { githubShortLabel } from "../common/github-url";
import {
  GithubRefField,
  githubRefHasError,
} from "../projects/components/github-ref-field";
import {
  isDesktopShell,
  pickDirectory,
  validateLocalDirectory,
} from "../platform/local-directory";
import { useLocalDaemonStatus } from "../platform/use-local-daemon-status";
import {
  runtimeAdvertisesLocalWorktree,
  runtimeListOptions,
} from "@multica/core/runtimes";
import { useConfigStore } from "@multica/core/config";
import type { LocalDirectoryExecutionMode } from "@multica/core/types";
import { LocalDirectoryModeOptions } from "../projects/components/local-directory-mode-options";
import { getProjectFoldersExtension, useProjectFolders } from "../extensions";

/**
 * 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,
  description,
  className,
}: {
  url: string;
  description?: string;
  className?: string;
}) {
  const label = description?.trim();
  return (
    <Tooltip>
      <TooltipTrigger
        render={
          <span className={cn("min-w-0 flex-1 text-left", className)}>
            <span className="block truncate">{githubShortLabel(url)}</span>
            {label && (
              <span className="block truncate text-micro text-muted-foreground">
                {label}
              </span>
            )}
          </span>
        }
      />
      <TooltipContent side="top" align="start" className="max-w-sm break-all">
        {url}
      </TooltipContent>
    </Tooltip>
  );
}

export function CreateProjectModal({
  open = true,
  onClose,
  onOpenChangeComplete,
  data,
}: {
  open?: boolean;
  onClose: () => void;
  onOpenChangeComplete?: (open: boolean) => void;
  data?: Record<string, unknown> | null;
}) {
  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;
  const wsPaths = useWorkspacePaths();
  const wsId = useWorkspaceId();
  const { data: members = [] } = useQuery(memberListOptions(wsId));
  const { data: agents = [] } = useQuery(agentListOptions(wsId));
  const { getActorName } = useActorName();
  const projectStatusLabels = useProjectStatusLabels();
  const projectPriorityLabels = useProjectPriorityLabels();

  const draft = useProjectDraftStore((s) => s.draft);
  const setDraft = useProjectDraftStore((s) => s.setDraft);
  const clearDraft = useProjectDraftStore((s) => s.clearDraft);

  const [title, setTitle] = useState(draft.title);
  const descEditorRef = useRef<ContentEditorRef>(null);
  const [status, setStatus] = useState<ProjectStatus>(draft.status);
  const [priority, setPriority] = useState<ProjectPriority>(draft.priority);
  const [leadType, setLeadType] = useState<"member" | "agent" | undefined>(draft.leadType);
  const [leadId, setLeadId] = useState<string | undefined>(draft.leadId);
  const [icon, setIcon] = useState<string | undefined>(draft.icon);
  const [startDate, setStartDate] = useState<string>(draft.startDate ?? "");
  const [dueDate, setDueDate] = useState<string>(draft.dueDate ?? "");
  const [visibility, setVisibility] = useState<ProjectVisibility>(draft.visibility ?? "workspace");
  const [memberIds, setMemberIds] = useState<string[]>(draft.memberIds ?? []);
  // Optional properties stay in the ⋯ menu until selected or opened.
  const [startDatePickerOpen, setStartDatePickerOpen] = useState(false);
  const [dueDatePickerOpen, setDueDatePickerOpen] = useState(false);
  const [iconPickerOpen, setIconPickerOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  // Repos selected to attach as github_repo resources after the project is
  // created. Stored as URLs (not full ProjectResource rows) — they're not
  // persisted until handleSubmit fires the createProjectResource calls.
  const [selectedRepos, setSelectedRepos] = useState<string[]>([]);
  // Checkout ref per selected repo URL, absent when the repo starts from its
  // default branch. Keyed by URL rather than folded into selectedRepos so
  // toggling a repo off and on again does not silently drop the ref.
  const [repoRefs, setRepoRefs] = useState<Record<string, string>>({});
  const [repoPopoverOpen, setRepoPopoverOpen] = useState(false);
  const [repoSearch, setRepoSearch] = useState("");
  const [customRepoUrl, setCustomRepoUrl] = useState("");
  const [customRepoRef, setCustomRepoRef] = useState("");
  const [editingRefFor, setEditingRefFor] = useState<string | null>(null);
  const workspaceRepos = workspace?.repos ?? [];
  const repoQuery = repoSearch.trim().toLowerCase();
  const filteredWorkspaceRepos = workspaceRepos.filter((repo) =>
    repo.url.toLowerCase().includes(repoQuery),
  );

  // A project's source is binary: either a set of GitHub repos OR a local
  // working directory — never both. Mode is the source of truth for what
  // gets persisted on submit; switching mode does NOT clear the other
  // side's stash, so toggling back and forth restores the user's prior
  // selection. Only the mode-matching side is sent to the API. Local mode
  // is hidden entirely on web (no daemon to bind the path to).
  const desktop = isDesktopShell();
  const daemonStatus = useLocalDaemonStatus();
  const [sourceMode, setSourceMode] = useState<"repos" | "local">("repos");
  const [selectedLocalPath, setSelectedLocalPath] = useState<string | null>(null);
  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));
  // Capability, not version: a dev-built daemon reports a git-describe string
  // that the version floor exempts, so the version check passed for a binary
  // with no worktree implementation (MUL-5707). A backend too old to record the
  // capability at all is its own answer — blaming this machine for that sent a
  // user off to update the one piece already on the newest release (#7113).
  // Preselection only — the server gates the save, including on this bundled
  // create path, and rejects with a message the modal surfaces.
  const localAdvertisesWorktree = runtimeAdvertisesLocalWorktree(
    runtimes,
    daemonStatus.daemonId,
  );
  // One declared boolean from the live server. Servers older than the worktree
  // save gate drop execution_mode and answer 201, so "the backend will check"
  // is only true once the backend says it checks (#7113).
  const serverValidatesWorktree = useConfigStore((state) => state.localWorktreeSupported);
  const worktreeUnavailableReason =
    localIsGitRepo === false
      ? ("not_git" as const)
      : !serverValidatesWorktree
        ? ("server_outdated" as const)
        : undefined;
  // Preselection, not a default behavior change: when the folder is a git repo
  // and the machine has advertised that it can 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, and so does a machine that has not advertised: it may still be able
  // to (an old row proves nothing), but choosing it FOR the user is how a
  // rejected save would turn into a failed project creation.
  //
  // `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 && localAdvertisesWorktree && 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);
    setLocalPickError(null);
  };

  const handlePickLocalDirectory = async () => {
    if (localPicking) return;
    setLocalPickError(null);
    setLocalPicking(true);
    try {
      const picked = await pickDirectory(selectedLocalPath ?? undefined);
      if (!picked.ok || !picked.path) {
        if (picked.reason && picked.reason !== "cancelled") {
          setLocalPickError(
            picked.error ?? t(($) => $.create_project.local_pick_failed),
          );
        }
        return;
      }
      const validation = await validateLocalDirectory(picked.path);
      if (!validation.ok) {
        setLocalPickError(
          validation.error ?? t(($) => $.create_project.local_invalid_dir),
        );
        return;
      }
      setSelectedLocalPath(picked.path);
      setSelectedLocalLabel(picked.basename ?? null);
      setLocalIsGitRepo(validation.is_git_repo);
    } finally {
      setLocalPicking(false);
    }
  };

  const clearLocalDirectory = () => {
    setSelectedLocalPath(null);
    setSelectedLocalLabel(null);
    setLocalPickError(null);
    setLocalIsGitRepo(undefined);
    setLocalMode(null);
  };

  const [workflowId, setWorkflowId] = useState<string | null>(null);
  const folders = useProjectFolders(wsId);
  const FolderField = getProjectFoldersExtension()?.CreateProjectField;
  const [folderId, setFolderId] = useState<string | null>(
    typeof data?.folderId === "string" ? data.folderId : null,
  );

  // Sync field changes to draft store
  const updateTitle = (v: string) => { setTitle(v); setDraft({ title: v }); };
  const updateStatus = (v: ProjectStatus) => { setStatus(v); setDraft({ status: v }); };
  const updatePriority = (v: ProjectPriority) => { setPriority(v); setDraft({ priority: v }); };
  const updateLead = (type?: "member" | "agent", id?: string) => {
    setLeadType(type); setLeadId(id);
    setDraft({ leadType: type, leadId: id });
  };
  const updateIcon = (v: string | undefined) => { setIcon(v); setDraft({ icon: v }); };
  const updateStartDate = (v: string) => { setStartDate(v); setDraft({ startDate: v || undefined }); };
  const updateDueDate = (v: string) => { setDueDate(v); setDraft({ dueDate: v || undefined }); };

  const [leadOpen, setLeadOpen] = useState(false);
  const [leadFilter, setLeadFilter] = useState("");
  const moreOptionsRef = useRef<HTMLButtonElement>(null);

  const leadQuery = leadFilter.toLowerCase();
  const filteredMembers = members.filter((m) => m.name.toLowerCase().includes(leadQuery) || matchesPinyin(m.name, leadQuery));
  const filteredAgents = agents.filter(
    (a) => !a.archived_at && (a.name.toLowerCase().includes(leadQuery) || matchesPinyin(a.name, leadQuery)),
  );

  const leadLabel =
    leadType && leadId ? getActorName(leadType, leadId) : t(($) => $.create_project.lead);
  const hasLead = !!(leadType && leadId);
  const hasSource = sourceMode === "local" ? !!selectedLocalPath : selectedRepos.length > 0;

  const createProject = useCreateProject();
  const paidFeatureError = usePaidFeatureErrorMessage();

  // Every selected repo's branch, not just the one in the add field. A branch
  // edited on an already-selected row goes through setRepoRef and used to
  // reach the payload with only an inline error to show for it — the server
  // accepts commit ids by design, so nothing downstream would have caught it.
  const hasRejectedRepoRef = selectedRepos.some((url) =>
    githubRefHasError(repoRefs[url] ?? ""),
  );

  const handleSubmit = async () => {
    // Checked here as well as on the button: TitleEditor's onSubmit calls this
    // directly, so a disabled button alone leaves the keyboard path open.
    if (!title.trim() || submitting) return;
    if (sourceMode === "repos" && hasRejectedRepoRef) return;
    // `sourceMode` decides which side's stash gets persisted — the other
    // side is silently dropped, so repos picked then abandoned for local
    // mode don't leak into the project.
    let resources:
      | Array<{ resource_type: "github_repo" | "local_directory"; resource_ref: Record<string, unknown> }>
      | undefined;
    if (sourceMode === "repos" && selectedRepos.length > 0) {
      resources = selectedRepos.map((url) => {
        const ref = repoRefs[url]?.trim();
        return {
          resource_type: "github_repo" as const,
          // Omit the key entirely when empty: an absent ref is what "use the
          // default branch" looks like on the wire.
          resource_ref: ref ? { url, ref } : { url },
        };
      });
    } else if (
      sourceMode === "local" &&
      selectedLocalPath &&
      daemonStatus.daemonId
    ) {
      resources = [
        {
          resource_type: "local_directory" as const,
          resource_ref: buildLocalDirectoryResourceRef({
            localPath: selectedLocalPath,
            daemonId: daemonStatus.daemonId,
            label: selectedLocalLabel,
            mode: effectiveLocalMode,
          }),
        },
      ];
    }
    setSubmitting(true);
    try {
      const project = await createProject.mutateAsync({
        title: title.trim(),
        description: descEditorRef.current?.getMarkdown()?.trim() || undefined,
        icon,
        status,
        priority,
        lead_type: leadType,
        lead_id: leadId,
        start_date: startDate || undefined,
        due_date: dueDate || undefined,
        ...(workflowId ? { workflow_id: workflowId } : {}),
        // Server attaches these in the same transaction as the project.
        resources,
        ...(visibility === "private" ? { visibility, member_ids: memberIds } : {}),
      });
      if (folderId && folders.canFile) folders.moveProject(project.id, folderId);
      clearDraft();
      onClose();
      toast.success(t(($) => $.create_project.toast_created));
      router.push(wsPaths.projectDetail(project.id));
    } catch (err) {
      toast.error(
        paidFeatureError(
          err,
          err instanceof Error && err.message
            ? err.message
            : t(($) => $.create_project.toast_failed),
        ),
      );
    } finally {
      setSubmitting(false);
    }
  };

  const toggleRepo = (url: string) => {
    setSelectedRepos((prev) =>
      prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url],
    );
  };

  const addCustomRepo = () => {
    const url = customRepoUrl.trim();
    const ref = customRepoRef.trim();
    if (!url || githubRefHasError(ref)) return;
    setSelectedRepos((prev) => (prev.includes(url) ? prev : [...prev, url]));
    setRepoRefs((prev) => {
      if (!ref) {
        const { [url]: _dropped, ...rest } = prev;
        return rest;
      }
      return { ...prev, [url]: ref };
    });
    setCustomRepoUrl("");
    setCustomRepoRef("");
  };

  // Someone who wants a branch copies it out of the address bar, so a pasted
  // .../tree/<branch> URL is split into its two halves rather than added whole
  // as a clone URL that does not exist. Both halves land in visible fields, so
  // a wrong guess is obvious before the project is created.
  //
  // Normalising the URL is unconditional. Gating it on the branch field being
  // empty meant a second pasted browse URL — changing your mind about which
  // repo — was stored whole, producing a clone target that does not exist.
  // Whether to overwrite the BRANCH is the separate question, and the pasted
  // pair wins: the branch field only appears once a URL is present, so a value
  // sitting in it came from the previous URL, not from something the user
  // typed ahead of time.
  const handleCustomRepoUrlChange = (next: string) => {
    const split = splitGithubUrlRef(next);
    setCustomRepoUrl(split.url);
    if (split.ref) setCustomRepoRef(split.ref);
  };

  const setRepoRef = (url: string, ref: string) => {
    const trimmed = ref.trim();
    setRepoRefs((prev) => {
      if (!trimmed) {
        const { [url]: _dropped, ...rest } = prev;
        return rest;
      }
      return { ...prev, [url]: trimmed };
    });
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(v) => { if (!v) onClose(); }}
      onOpenChangeComplete={onOpenChangeComplete}
    >
      <DialogContent
        showCloseButton={false}
        className={cn(
          "p-0 gap-0 flex flex-col overflow-hidden",
          "!top-1/2 !left-1/2 !-translate-x-1/2",
          "[transition-property:width,max-width,height] [transition-duration:200ms] [transition-timing-function:cubic-bezier(0.23,1,0.32,1)] motion-reduce:[transition-duration:0ms]",
          isExpanded
            ? "!max-w-4xl !w-full !h-5/6 !-translate-y-1/2"
            : "!max-w-2xl !w-full !h-96 !-translate-y-1/2",
        )}
      >
        <DialogTitle className="sr-only">{t(($) => $.create_project.title)}</DialogTitle>

        <div className="flex items-center justify-between px-5 pt-3 pb-2 shrink-0">
          <div className="flex items-center gap-1.5 text-caption">
            <span className="text-muted-foreground">{workspaceName}</span>
            <ChevronRight className="size-3 text-faint-foreground" />
            <span className="font-medium">{t(($) => $.create_project.title_breadcrumb)}</span>
          </div>
          <div className="flex items-center gap-1">
            <Tooltip>
              <TooltipTrigger
                render={
                  <button
                    type="button"
                    onClick={() => setIsExpanded(!isExpanded)}
                    className="rounded-sm p-1.5 opacity-70 hover:opacity-100 hover:bg-accent/60 transition-all cursor-pointer"
                    aria-label={
                      isExpanded
                        ? t(($) => $.common.collapse_tooltip)
                        : t(($) => $.common.expand_tooltip)
                    }
                  >
                    {isExpanded ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
                  </button>
                }
              />
              <TooltipContent side="bottom">
                {isExpanded
                  ? t(($) => $.common.collapse_tooltip)
                  : t(($) => $.common.expand_tooltip)}
              </TooltipContent>
            </Tooltip>
            <Tooltip>
              <TooltipTrigger
                render={
                  <button
                    type="button"
                    onClick={onClose}
                    className="rounded-sm p-1.5 opacity-70 hover:opacity-100 hover:bg-accent/60 transition-all cursor-pointer"
                    aria-label={t(($) => $.common.close)}
                  >
                    <XIcon className="size-4" />
                  </button>
                }
              />
              <TooltipContent side="bottom">{t(($) => $.common.close)}</TooltipContent>
            </Tooltip>
          </div>
        </div>

        <div className="px-5 pb-2 shrink-0">
          <Popover open={iconPickerOpen} onOpenChange={setIconPickerOpen}>
            <TooltipHint label={t(($) => $.create_project.icon_tooltip)}>
              <PopoverTrigger
                render={
                  <button
                    type="button"
                    className="text-display-sm cursor-pointer rounded-lg p-1 -ml-1 hover:bg-accent/60 transition-colors"
                    aria-label={t(($) => $.create_project.icon_tooltip)}
                  >
                    {icon || "📁"}
                  </button>
                }
              />
            </TooltipHint>
            <PopoverContent align="start" className="w-auto p-0">
              <EmojiPicker
                onSelect={(emoji) => {
                  updateIcon(emoji);
                  setIconPickerOpen(false);
                }}
              />
            </PopoverContent>
          </Popover>
          <TitleEditor
            autoFocus
            defaultValue={draft.title}
            placeholder={t(($) => $.create_project.title_placeholder)}
            className="text-title font-semibold"
            onChange={(v) => updateTitle(v)}
            onSubmit={handleSubmit}
          />
        </div>

        <div className="flex-1 min-h-0 overflow-y-auto px-5">
          <ContentEditor
            ref={descEditorRef}
            defaultValue={draft.description}
            placeholder={t(($) => $.create_project.description_placeholder)}
            onUpdate={(md) => setDraft({ description: md })}
            debounceMs={500}
          />
          <p className="mt-1 text-caption text-muted-foreground">
            {t(($) => $.create_project.description_hint)}
          </p>
        </div>

        {/* Optional properties appear inline once selected; their pickers
            open from ⋯ with the inline pill as the anchor. */}
        <div className="flex items-center gap-1.5 px-4 py-2 shrink-0 flex-wrap">
          <DropdownMenu>
            <DropdownMenuTrigger
              render={
                <PillButton>
                  <span className={cn("size-2 rounded-full", PROJECT_STATUS_CONFIG[status].dotColor)} />
                  <span>{projectStatusLabels[status]}</span>
                </PillButton>
              }
            />
            <DropdownMenuContent align="start" className="w-44">
              {PROJECT_STATUS_ORDER.map((s) => (
                <DropdownMenuItem key={s} onClick={() => updateStatus(s)}>
                  <span className={cn("size-2 rounded-full", PROJECT_STATUS_CONFIG[s].dotColor)} />
                  <span>{projectStatusLabels[s]}</span>
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>

          <DropdownMenu>
            <DropdownMenuTrigger
              render={
                <PillButton>
                  <PriorityIcon priority={priority} />
                  <span>{projectPriorityLabels[priority]}</span>
                </PillButton>
              }
            />
            <DropdownMenuContent align="start" className="w-44">
              {PROJECT_PRIORITY_ORDER.map((pr) => (
                <DropdownMenuItem key={pr} onClick={() => updatePriority(pr)}>
                  <PriorityIcon priority={pr} />
                  <span>{projectPriorityLabels[pr]}</span>
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>

          <WorkflowPill value={workflowId} onChange={setWorkflowId} />
          {FolderField && <FolderField value={folderId} onChange={setFolderId} />}
          {<ProjectAccessDraftPicker visibility={visibility} memberIds={memberIds} members={members}
            leadId={leadType === "member" ? leadId : undefined}
            onChange={(value, ids) => { setVisibility(value); setMemberIds(ids); setDraft({ visibility: value, memberIds: ids }); }} />}

          <Popover
            open={leadOpen}
            onOpenChange={(v) => {
              setLeadOpen(v);
              if (!v) setLeadFilter("");
            }}
          >
            {(hasLead || leadOpen) && (
              <PopoverTrigger
                render={
                  <PillButton>
                    {leadType && leadId ? (
                      <>
                        <ActorAvatar actorType={leadType} actorId={leadId} size="sm" showStatusDot />
                        <span className="truncate">{leadLabel}</span>
                      </>
                    ) : (
                      <>
                        <User className="size-3.5 shrink-0 text-muted-foreground" />
                        <span className="text-muted-foreground">{t(($) => $.create_project.lead)}</span>
                      </>
                    )}
                  </PillButton>
                }
              />
            )}
            <PopoverContent align="start" className="w-52 p-0" finalFocus={hasLead ? undefined : moreOptionsRef}>
              <div className="px-2 py-1.5 border-b">
                <input
                  type="text"
                  value={leadFilter}
                  onChange={(e) => setLeadFilter(e.target.value)}
                  placeholder={t(($) => $.create_project.lead_placeholder)}
                  className="w-full bg-transparent text-body placeholder:text-muted-foreground outline-none"
                />
              </div>
              <div className="p-1 max-h-60 overflow-y-auto">
                <button
                  type="button"
                  onClick={() => {
                    updateLead(undefined, undefined);
                    setLeadOpen(false);
                  }}
                  className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body hover:bg-accent transition-colors"
                >
                  <UserMinus className="h-3.5 w-3.5 text-muted-foreground" />
                  <span className="text-muted-foreground">{t(($) => $.create_project.no_lead)}</span>
                </button>
                {filteredMembers.length > 0 && (
                  <>
                    <div className="px-2 pt-2 pb-1 text-caption font-medium text-muted-foreground uppercase tracking-wider">
                      {t(($) => $.create_project.members_group)}
                    </div>
                    {filteredMembers.map((m) => (
                      <button
                        type="button"
                        key={m.user_id}
                        onClick={() => {
                          updateLead("member", m.user_id);
                          setLeadOpen(false);
                        }}
                        className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body hover:bg-accent transition-colors"
                      >
                        <ActorAvatar actorType="member" actorId={m.user_id} size="sm" />
                        <span>{m.name}</span>
                      </button>
                    ))}
                  </>
                )}
                {filteredAgents.length > 0 && (
                  <>
                    <div className="px-2 pt-2 pb-1 text-caption font-medium text-muted-foreground uppercase tracking-wider">
                      {t(($) => $.create_project.agents_group)}
                    </div>
                    {filteredAgents.map((a) => (
                      <button
                        type="button"
                        key={a.id}
                        onClick={() => {
                          updateLead("agent", a.id);
                          setLeadOpen(false);
                        }}
                        className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body hover:bg-accent transition-colors"
                      >
                        <ActorAvatar actorType="agent" actorId={a.id} size="sm" showStatusDot />
                        <span>{a.name}</span>
                      </button>
                    ))}
                  </>
                )}
                {filteredMembers.length === 0 &&
                  filteredAgents.length === 0 &&
                  leadFilter && (
                    <div className="px-2 py-3 text-center text-body text-muted-foreground">
                      {t(($) => $.create_project.no_results)}
                    </div>
                  )}
              </div>
            </PopoverContent>
          </Popover>

          {/* Start date — collapsed into ⋯ unless it has a value or was just
              opened from the overflow (the calendar anchors on the inline pill). */}
          {(startDate || startDatePickerOpen) && (
            <ProjectStartDatePicker
              startDate={startDate || null}
              onUpdate={(u) => updateStartDate(u.start_date ?? "")}
              triggerRender={<PillButton />}
              open={startDatePickerOpen}
              onOpenChange={setStartDatePickerOpen}
            />
          )}

          {(dueDate || dueDatePickerOpen) && (
            <ProjectDueDatePicker
              dueDate={dueDate || null}
              onUpdate={(u) => updateDueDate(u.due_date ?? "")}
              triggerRender={<PillButton />}
              open={dueDatePickerOpen}
              onOpenChange={setDueDatePickerOpen}
            />
          )}

          <Popover
            open={repoPopoverOpen}
            onOpenChange={(v) => {
              setRepoPopoverOpen(v);
              if (!v) setRepoSearch("");
            }}
          >
            {(hasSource || repoPopoverOpen) && (
              <PopoverTrigger
                render={
                  <PillButton>
                    {sourceMode === "local" ? (
                      <>
                        <FolderOpen className="size-3" />
                        <span className="max-w-[12rem] truncate">
                          {selectedLocalPath
                            ? selectedLocalLabel ?? selectedLocalPath
                            : t(($) => $.create_project.source_pill_local)}
                        </span>
                      </>
                    ) : (
                      <>
                        <GithubIcon className="size-3" />
                        <span>
                          {selectedRepos.length === 0
                            ? t(($) => $.create_project.repos_pill)
                            : t(($) => $.create_project.repos_pill_count, { count: selectedRepos.length })}
                        </span>
                      </>
                    )}
                  </PillButton>
                }
              />
            )}
            <PopoverContent side="top" align="start" className="w-72 p-2 space-y-2" finalFocus={hasSource ? undefined : moreOptionsRef}>
              {/* Source mode is binary — repo OR local directory, never both.
                  Local option is desktop-only because a local_directory
                  resource has to be pinned to a daemon_id, which doesn't
                  exist on the web. */}
              {desktop && (
                <div className="grid grid-cols-2 gap-1 rounded-md bg-muted/60 p-0.5">
                  <button
                    type="button"
                    onClick={() => handleSourceModeChange("repos")}
                    className={cn(
                      "rounded-xs px-2 py-1 text-caption transition-colors",
                      sourceMode === "repos"
                        ? "bg-background shadow-sm font-medium"
                        : "text-muted-foreground hover:text-foreground",
                    )}
                  >
                    {t(($) => $.create_project.source_tab_repos)}
                  </button>
                  <button
                    type="button"
                    onClick={() => handleSourceModeChange("local")}
                    className={cn(
                      "rounded-xs px-2 py-1 text-caption transition-colors",
                      sourceMode === "local"
                        ? "bg-background shadow-sm font-medium"
                        : "text-muted-foreground hover:text-foreground",
                    )}
                  >
                    {t(($) => $.create_project.source_tab_local)}
                  </button>
                </div>
              )}

              {sourceMode === "repos" ? (
                <>
                  <div className="text-caption font-medium text-muted-foreground">
                    {t(($) => $.create_project.repos_heading)}
                  </div>
                  {workspaceRepos.length > 0 ? (
                    <>
                      <div className="relative">
                        <Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
                        <input
                          type="text"
                          value={repoSearch}
                          onChange={(e) => setRepoSearch(e.target.value)}
                          aria-label={t(($) => $.create_project.repos_search_placeholder)}
                          placeholder={t(($) => $.create_project.repos_search_placeholder)}
                          className="h-8 w-full rounded-md border bg-transparent pl-7 pr-2 text-caption outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring"
                        />
                      </div>
                      <div className="max-h-48 space-y-1 overflow-y-auto">
                        {filteredWorkspaceRepos.length === 0 && repoQuery && (
                          <p className="py-2 text-center text-caption text-muted-foreground">
                            {t(($) => $.create_project.repos_search_empty)}
                          </p>
                        )}
                        {filteredWorkspaceRepos.map((repo) => {
                          const checked = selectedRepos.includes(repo.url);
                          return (
                            <button
                              type="button"
                              key={repo.url}
                              onClick={() => toggleRepo(repo.url)}
                              className={cn(
                                "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-caption hover:bg-accent transition-colors",
                                checked && "bg-accent",
                              )}
                            >
                              <input
                                type="checkbox"
                                checked={checked}
                                readOnly
                                className="size-3.5"
                              />
                              <GithubIcon className="size-3.5" />
                              <RepoUrlText url={repo.url} description={repo.description} />
                            </button>
                          );
                        })}
                      </div>
                    </>
                  ) : (
                    <p className="text-caption text-muted-foreground">
                      {t(($) => $.create_project.repos_empty)}
                    </p>
                  )}
                  <form
                    onSubmit={(e) => {
                      e.preventDefault();
                      addCustomRepo();
                    }}
                    className="space-y-1.5 pt-1 border-t"
                  >
                    <div className="flex items-center gap-1.5">
                      <input
                        type="text"
                        value={customRepoUrl}
                        onChange={(e) => handleCustomRepoUrlChange(e.target.value)}
                        placeholder={t(($) => $.create_project.repos_url_placeholder)}
                        className="flex-1 min-w-0 bg-transparent text-caption px-2 py-1 outline-none placeholder:text-muted-foreground"
                      />
                      <Button
                        type="submit"
                        size="sm"
                        variant="ghost"
                        className="h-6 px-2 text-caption"
                        disabled={!customRepoUrl.trim() || githubRefHasError(customRepoRef)}
                      >
                        {t(($) => $.create_project.repos_add)}
                      </Button>
                    </div>
                    {/* Only once a URL is entered: an empty form should still
                        read as one field, and the default branch is the right
                        answer often enough that this must not look like a
                        second required step. */}
                    <Collapsible open={Boolean(customRepoUrl.trim())}>
                      <CollapsibleContent>
                        <GithubRefField
                          id="create-project-repo-ref"
                          value={customRepoRef}
                          onChange={setCustomRepoRef}
                        />
                      </CollapsibleContent>
                    </Collapsible>
                  </form>
                  {selectedRepos.length > 0 && (
                    <div className="space-y-1 pt-1 border-t">
                      <div className="text-micro font-medium text-muted-foreground uppercase tracking-wider">
                        {t(($) => $.create_project.repos_selected)}
                      </div>
                      {selectedRepos.map((url) => (
                        <div key={url} className="space-y-1">
                          <div className="flex items-center gap-2 text-caption">
                            <GithubIcon className="size-3 shrink-0 text-muted-foreground" />
                            <RepoUrlText
                              url={url}
                              description={workspaceRepos.find((repo) => repo.url === url)?.description}
                            />
                            {/* The ref rides beside the repo it belongs to,
                                not in one field for the whole list: each repo
                                can start somewhere different. */}
                            <button
                              type="button"
                              onClick={() =>
                                setEditingRefFor(editingRefFor === url ? null : url)
                              }
                              className={cn(
                                "flex shrink-0 items-center gap-1 rounded-sm px-1 py-0.5 text-micro transition-colors hover:bg-accent",
                                repoRefs[url]
                                  ? "text-foreground"
                                  : "text-muted-foreground",
                              )}
                            >
                              <GitBranch className="size-3" />
                              <span className="max-w-24 truncate">
                                {repoRefs[url] ??
                                  t(($) => $.create_project.repos_ref_default)}
                              </span>
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                toggleRepo(url);
                                if (editingRefFor === url) setEditingRefFor(null);
                              }}
                              className="shrink-0 text-muted-foreground hover:text-foreground"
                              aria-label={t(($) => $.create_project.repos_remove_aria, {
                                repo: githubShortLabel(url),
                              })}
                            >
                              <XIcon className="size-3" />
                            </button>
                          </div>
                          {editingRefFor === url && (
                            <div className="pl-5">
                              <GithubRefField
                                value={repoRefs[url] ?? ""}
                                onChange={(next) => setRepoRef(url, next)}
                                onSubmit={() => setEditingRefFor(null)}
                                autoFocus
                              />
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </>
              ) : (
                <>
                  <div className="text-caption font-medium text-muted-foreground">
                    {t(($) => $.create_project.local_heading)}
                  </div>
                  {/* Daemon must be online — daemon_id is required to bind
                      the resource. If it's offline, surface why and disable
                      the picker; once it boots we re-render automatically
                      via useLocalDaemonStatus. */}
                  {daemonStatus.daemonId && daemonStatus.running ? (
                    <p className="text-micro text-muted-foreground">
                      {t(($) => $.create_project.local_on_device, {
                        device: daemonStatus.deviceName ?? t(($) => $.create_project.local_this_machine),
                      })}
                    </p>
                  ) : (
                    <p className="text-micro text-amber-600 dark:text-amber-400">
                      {t(($) => $.create_project.local_daemon_offline)}
                    </p>
                  )}

                  {selectedLocalPath ? (
                    <div className="rounded-md border px-2 py-2 space-y-1">
                      <div className="flex items-start gap-2 text-caption">
                        <FolderOpen className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
                        <div className="min-w-0 flex-1">
                          {selectedLocalLabel && (
                            <div className="font-medium truncate">{selectedLocalLabel}</div>
                          )}
                          <div className="font-mono text-micro text-muted-foreground break-all">
                            {selectedLocalPath}
                          </div>
                        </div>
                        <TooltipHint label={t(($) => $.create_project.local_clear)}>
                          <button
                            type="button"
                            onClick={clearLocalDirectory}
                            className="text-muted-foreground hover:text-foreground"
                            aria-label={t(($) => $.create_project.local_clear)}
                          >
                            <XIcon className="size-3" />
                          </button>
                        </TooltipHint>
                      </div>
                      <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 folder..." 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}
                            />
                          </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
                      type="button"
                      size="sm"
                      variant="outline"
                      className="w-full text-caption"
                      onClick={handlePickLocalDirectory}
                      disabled={localPicking || !daemonStatus.running}
                    >
                      <FolderOpen className="size-3" />
                      {localPicking
                        ? t(($) => $.create_project.local_picking)
                        : t(($) => $.create_project.local_pick)}
                    </Button>
                  )}

                  {localPickError && (
                    <p className="text-micro text-destructive">{localPickError}</p>
                  )}

                  <p className="text-micro text-muted-foreground leading-snug">
                    {t(($) => $.create_project.local_hint)}
                  </p>
                </>
              )}
            </PopoverContent>
          </Popover>

          {/* Keep overflow last in the wrap flow while any property is unset. */}
          {(!hasLead || !hasSource || !startDate || !dueDate) && (
            <DropdownMenu>
              <DropdownMenuTrigger
                render={
                  <PillButton ref={moreOptionsRef} aria-label={t(($) => $.create_project.more_options_aria)}>
                    <MoreHorizontal className="size-3.5" />
                  </PillButton>
                }
              />
              <DropdownMenuContent align="start" className="w-auto">
                {!hasLead && (
                  <DropdownMenuItem onClick={() => setLeadOpen(true)}>
                    <User className="size-3.5" />
                    {t(($) => $.create_project.lead)}
                  </DropdownMenuItem>
                )}
                {!hasSource && (
                  <DropdownMenuItem onClick={() => setRepoPopoverOpen(true)}>
                    {sourceMode === "local" ? <FolderOpen className="size-3.5" /> : <GithubIcon className="size-3.5" />}
                    {sourceMode === "local" ? t(($) => $.create_project.source_pill_local) : t(($) => $.create_project.repos_pill)}
                  </DropdownMenuItem>
                )}
                {!dueDate && (
                  <DropdownMenuItem onClick={() => setDueDatePickerOpen(true)}>
                    <CalendarDays className="h-3.5 w-3.5" />
                    {t(($) => $.create_project.set_due_date)}
                  </DropdownMenuItem>
                )}
                {!startDate && (
                  <DropdownMenuItem onClick={() => setStartDatePickerOpen(true)}>
                    <CalendarClock className="h-3.5 w-3.5" />
                    {t(($) => $.create_project.set_start_date)}
                  </DropdownMenuItem>
                )}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>

        {/* Footer action bar — primary action in its own strip, matching
            create-issue. */}
        <div className="flex items-center justify-end border-t px-4 py-3 shrink-0">
          <Button
            size="sm"
            onClick={handleSubmit}
            disabled={
              !title.trim() ||
              submitting ||
              (sourceMode === "repos" && hasRejectedRepoRef)
            }
            className="shrink-0"
          >
            {submitting ? t(($) => $.create_project.submitting) : t(($) => $.create_project.submit)}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}