feat(office): unify project repository pickers across create and edit (#1722)
This commit is contained in:
@@ -1,16 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { IconCode, IconWorld, IconX } from "@tabler/icons-react";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { toast } from "sonner";
|
||||
import { updateProject } from "@/lib/api/domains/office-api";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
||||
import { formatUserHomePath } from "@/lib/utils";
|
||||
import type { Project } from "@/lib/state/slices/office/types";
|
||||
import type { Repository } from "@/lib/types/http";
|
||||
import { ProjectRepositoryPicker } from "./project-repository-picker";
|
||||
import { ProjectRepositoryPicker } from "../project-repository-picker";
|
||||
import { RepoChip } from "../repo-chip";
|
||||
import { normalizeRepos } from "../normalize-repos";
|
||||
|
||||
type ProjectReposSectionProps = {
|
||||
@@ -73,7 +70,12 @@ export function ProjectReposSection({ project }: ProjectReposSectionProps) {
|
||||
onRemove={() => handleRemove(repo)}
|
||||
/>
|
||||
))}
|
||||
<ProjectRepositoryPicker workspaceId={workspaceId} exclude={repos} onSelect={handleAdd} />
|
||||
<ProjectRepositoryPicker
|
||||
workspaceId={workspaceId}
|
||||
repositories={repositories}
|
||||
exclude={repos}
|
||||
onSelect={handleAdd}
|
||||
/>
|
||||
</div>
|
||||
{repos.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground">No repositories added yet.</p>
|
||||
@@ -81,63 +83,3 @@ export function ProjectReposSection({ project }: ProjectReposSectionProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A single attached repository, rendered as a chip with friendly label
|
||||
* + remove button. Falls back to the raw stored string when no
|
||||
* workspace row matches (custom URL or unimported local path).
|
||||
*/
|
||||
function RepoChip({
|
||||
value,
|
||||
workspaceRepos,
|
||||
onRemove,
|
||||
}: {
|
||||
value: string;
|
||||
workspaceRepos: Repository[];
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const matched = workspaceRepos.find((r) => r.local_path === value);
|
||||
const isUrl = looksLikeUrl(value);
|
||||
const label = matched?.name ?? (isUrl ? value : leafSegment(value));
|
||||
const detail = matched?.local_path ?? value;
|
||||
const displayDetail = isUrl ? value : formatUserHomePath(detail);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-input bg-input/20 dark:bg-input/30 pl-2.5 pr-0.5 h-8 text-xs"
|
||||
data-testid="project-repo-chip"
|
||||
data-repository-value={value}
|
||||
>
|
||||
{isUrl ? (
|
||||
<IconWorld className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<IconCode className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="truncate max-w-[240px]">{label}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
aria-label="Remove repository"
|
||||
className="h-6 w-6 inline-flex items-center justify-center rounded text-muted-foreground hover:text-destructive hover:bg-muted/60 cursor-pointer"
|
||||
data-testid="project-repo-chip-remove"
|
||||
>
|
||||
<IconX className="h-3 w-3" />
|
||||
</button>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{displayDetail}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function looksLikeUrl(value: string): boolean {
|
||||
return /^(https?:\/\/|git@|ssh:\/\/|git:\/\/)/i.test(value);
|
||||
}
|
||||
|
||||
function leafSegment(path: string): string {
|
||||
const cleaned = path.replace(/\\/g, "/").replace(/\/+$/g, "");
|
||||
const idx = cleaned.lastIndexOf("/");
|
||||
return idx >= 0 ? cleaned.slice(idx + 1) : cleaned;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import { IconPlus, IconX } from "@tabler/icons-react";
|
||||
import { toast } from "sonner";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@kandev/ui/dialog";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Input } from "@kandev/ui/input";
|
||||
import { Label } from "@kandev/ui/label";
|
||||
import { Textarea } from "@kandev/ui/textarea";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
||||
import { createProject } from "@/lib/api/domains/office-api";
|
||||
import type { AgentProfile } from "@/lib/state/slices/office/types";
|
||||
import { ProjectRepositoryPicker } from "./project-repository-picker";
|
||||
import { RepoChip } from "./repo-chip";
|
||||
|
||||
const COLOR_OPTIONS = [
|
||||
"#ef4444",
|
||||
@@ -53,66 +54,39 @@ function ColorPicker({ color, onChange }: { color: string; onChange: (c: string)
|
||||
}
|
||||
|
||||
function ReposField({
|
||||
workspaceId,
|
||||
repos,
|
||||
repoInput,
|
||||
onRepoInputChange,
|
||||
onAddRepo,
|
||||
onRemoveRepo,
|
||||
}: {
|
||||
workspaceId: string;
|
||||
repos: string[];
|
||||
repoInput: string;
|
||||
onRepoInputChange: (v: string) => void;
|
||||
onAddRepo: () => void;
|
||||
onAddRepo: (repo: string) => void;
|
||||
onRemoveRepo: (r: string) => void;
|
||||
}) {
|
||||
const { repositories } = useRepositories(workspaceId);
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Label>Repositories</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Git URLs or local paths where agents will work
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="URL or path"
|
||||
value={repoInput}
|
||||
onChange={(e) => onRepoInputChange(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && (e.preventDefault(), onAddRepo())}
|
||||
className="flex-1"
|
||||
<div className="flex flex-wrap items-center gap-2" data-testid="project-repo-chips">
|
||||
{repos.map((repo) => (
|
||||
<RepoChip
|
||||
key={repo}
|
||||
value={repo}
|
||||
workspaceRepos={repositories}
|
||||
onRemove={() => onRemoveRepo(repo)}
|
||||
/>
|
||||
))}
|
||||
<ProjectRepositoryPicker
|
||||
workspaceId={workspaceId}
|
||||
repositories={repositories}
|
||||
exclude={repos}
|
||||
onSelect={onAddRepo}
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={onAddRepo}
|
||||
className="cursor-pointer shrink-0"
|
||||
>
|
||||
<IconPlus className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Add repository</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{repos.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 mt-1">
|
||||
{repos.map((repo) => (
|
||||
<span
|
||||
key={repo}
|
||||
className="inline-flex items-center gap-1 rounded-md bg-muted px-2 py-1 text-xs"
|
||||
>
|
||||
{repo}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemoveRepo(repo)}
|
||||
className="cursor-pointer hover:text-destructive"
|
||||
>
|
||||
<IconX className="h-3 w-3" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -175,7 +149,6 @@ type ProjectFormState = {
|
||||
description: string;
|
||||
color: string;
|
||||
repos: string[];
|
||||
repoInput: string;
|
||||
leadAgentId: string;
|
||||
executorType: string;
|
||||
dockerImage: string;
|
||||
@@ -186,7 +159,6 @@ const INITIAL_PROJECT_STATE: ProjectFormState = {
|
||||
description: "",
|
||||
color: COLOR_OPTIONS[5],
|
||||
repos: [],
|
||||
repoInput: "",
|
||||
leadAgentId: "",
|
||||
executorType: "",
|
||||
dockerImage: "",
|
||||
@@ -202,12 +174,15 @@ function useProjectForm(workspaceId: string, onClose: () => void) {
|
||||
[],
|
||||
);
|
||||
|
||||
const handleAddRepo = useCallback(() => {
|
||||
const trimmed = form.repoInput.trim();
|
||||
if (trimmed && !form.repos.includes(trimmed)) {
|
||||
update({ repos: [...form.repos, trimmed], repoInput: "" });
|
||||
}
|
||||
}, [form.repoInput, form.repos, update]);
|
||||
const handleAddRepo = useCallback(
|
||||
(repo: string) => {
|
||||
const trimmed = repo.trim();
|
||||
if (trimmed && !form.repos.includes(trimmed)) {
|
||||
update({ repos: [...form.repos, trimmed] });
|
||||
}
|
||||
},
|
||||
[form.repos, update],
|
||||
);
|
||||
|
||||
const handleRemoveRepo = useCallback(
|
||||
(repo: string) => update({ repos: form.repos.filter((r) => r !== repo) }),
|
||||
@@ -246,6 +221,7 @@ function ProjectFormBody({
|
||||
form,
|
||||
agents,
|
||||
executorTypes,
|
||||
workspaceId,
|
||||
onUpdate,
|
||||
onAddRepo,
|
||||
onRemoveRepo,
|
||||
@@ -253,8 +229,9 @@ function ProjectFormBody({
|
||||
form: ProjectFormState;
|
||||
agents: AgentProfile[];
|
||||
executorTypes: Array<{ id: string; label: string }>;
|
||||
workspaceId: string;
|
||||
onUpdate: (patch: Partial<ProjectFormState>) => void;
|
||||
onAddRepo: () => void;
|
||||
onAddRepo: (repo: string) => void;
|
||||
onRemoveRepo: (r: string) => void;
|
||||
}) {
|
||||
return (
|
||||
@@ -281,9 +258,8 @@ function ProjectFormBody({
|
||||
</div>
|
||||
<ColorPicker color={form.color} onChange={(c) => onUpdate({ color: c })} />
|
||||
<ReposField
|
||||
workspaceId={workspaceId}
|
||||
repos={form.repos}
|
||||
repoInput={form.repoInput}
|
||||
onRepoInputChange={(v) => onUpdate({ repoInput: v })}
|
||||
onAddRepo={onAddRepo}
|
||||
onRemoveRepo={onRemoveRepo}
|
||||
/>
|
||||
@@ -338,6 +314,7 @@ export function CreateProjectDialog({ open, onOpenChange, workspaceId }: CreateP
|
||||
form={form}
|
||||
agents={agents}
|
||||
executorTypes={executorTypes}
|
||||
workspaceId={workspaceId}
|
||||
onUpdate={update}
|
||||
onAddRepo={handleAddRepo}
|
||||
onRemoveRepo={handleRemoveRepo}
|
||||
|
||||
+33
-48
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { IconCode, IconPlus, IconWorld } from "@tabler/icons-react";
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import {
|
||||
@@ -13,13 +13,19 @@ import {
|
||||
} from "@kandev/ui/command";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
|
||||
import { cn, formatUserHomePath } from "@/lib/utils";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
import type { Repository } from "@/lib/types/http";
|
||||
import { normalizeRepoValue, shouldShowCustomEntry } from "./repo-entry";
|
||||
import { useDiscoveredRepositories } from "./use-discovered-repositories";
|
||||
|
||||
type Props = {
|
||||
workspaceId: string | null;
|
||||
/**
|
||||
* The workspace's registered repositories. Supplied by the caller —
|
||||
* which already loads them for chip labels — so mounting the picker
|
||||
* does not issue a second repository-list fetch.
|
||||
*/
|
||||
repositories: Repository[];
|
||||
/** Already-attached entries (raw stored values) — excluded from suggestions. */
|
||||
exclude: string[];
|
||||
onSelect: (value: string) => void;
|
||||
@@ -36,43 +42,28 @@ type RepoOption = { key: string; value: string; name: string; path: string };
|
||||
*
|
||||
* - selecting a workspace repo stores its `local_path`;
|
||||
* - selecting a discovered on-disk repo stores its absolute path;
|
||||
* - typing a URL or path that doesn't match anything offers an
|
||||
* "Add custom" row which stores the literal input.
|
||||
* - typing a URL or path offers an "Add custom" row storing the
|
||||
* literal input, hidden only when the value exactly matches an
|
||||
* existing entry (see `shouldShowCustomEntry`).
|
||||
*
|
||||
* On-disk discovery runs lazily the first time the popover opens.
|
||||
*/
|
||||
export function ProjectRepositoryPicker({ workspaceId, exclude, onSelect, triggerLabel }: Props) {
|
||||
export function ProjectRepositoryPicker({
|
||||
workspaceId,
|
||||
repositories,
|
||||
exclude,
|
||||
onSelect,
|
||||
triggerLabel,
|
||||
}: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const { repositories } = useRepositories(workspaceId);
|
||||
// `null` means "discovery not yet attempted" — used to drive the
|
||||
// "Searching your machine…" empty-state copy without an extra
|
||||
// loading flag (the lint rule discourages synchronous setState in
|
||||
// an effect body).
|
||||
const [discovered, setDiscovered] = useState<LocalRepository[] | null>(null);
|
||||
const discoveredOnce = useRef(false);
|
||||
const discovered = useDiscoveredRepositories(open, workspaceId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !workspaceId || discoveredOnce.current) return;
|
||||
discoveredOnce.current = true;
|
||||
let cancelled = false;
|
||||
discoverRepositoriesAction(workspaceId)
|
||||
.then((res) => {
|
||||
if (!cancelled) setDiscovered(res.repositories ?? []);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setDiscovered([]);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, workspaceId]);
|
||||
|
||||
const excludeSet = useMemo(() => new Set(exclude.map(normalize)), [exclude]);
|
||||
const excludeSet = useMemo(() => new Set(exclude.map(normalizeRepoValue)), [exclude]);
|
||||
const workspaceOptions = useMemo<RepoOption[]>(
|
||||
() =>
|
||||
repositories
|
||||
.filter((r) => r.local_path && !excludeSet.has(normalize(r.local_path)))
|
||||
.filter((r) => r.local_path && !excludeSet.has(normalizeRepoValue(r.local_path)))
|
||||
.map((r) => ({
|
||||
key: `ws-${r.id}`,
|
||||
value: r.local_path,
|
||||
@@ -83,9 +74,12 @@ export function ProjectRepositoryPicker({ workspaceId, exclude, onSelect, trigge
|
||||
);
|
||||
const discoveredOptions = useMemo<RepoOption[]>(() => {
|
||||
if (!discovered) return [];
|
||||
const wsPaths = new Set(workspaceOptions.map((o) => normalize(o.path)));
|
||||
const wsPaths = new Set(workspaceOptions.map((o) => normalizeRepoValue(o.path)));
|
||||
return discovered
|
||||
.filter((r) => !wsPaths.has(normalize(r.path)) && !excludeSet.has(normalize(r.path)))
|
||||
.filter(
|
||||
(r) =>
|
||||
!wsPaths.has(normalizeRepoValue(r.path)) && !excludeSet.has(normalizeRepoValue(r.path)),
|
||||
)
|
||||
.map((r) => ({
|
||||
key: `disc-${r.path}`,
|
||||
value: r.path,
|
||||
@@ -104,11 +98,11 @@ export function ProjectRepositoryPicker({ workspaceId, exclude, onSelect, trigge
|
||||
);
|
||||
|
||||
const trimmed = query.trim();
|
||||
const showCustom =
|
||||
trimmed.length > 0 &&
|
||||
!excludeSet.has(normalize(trimmed)) &&
|
||||
!workspaceOptions.some((o) => matches(o, trimmed)) &&
|
||||
!discoveredOptions.some((o) => matches(o, trimmed));
|
||||
const showCustom = shouldShowCustomEntry(
|
||||
trimmed,
|
||||
[...workspaceOptions, ...discoveredOptions].map((o) => o.value),
|
||||
exclude,
|
||||
);
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
@@ -251,21 +245,12 @@ function RepoGroup({
|
||||
);
|
||||
}
|
||||
|
||||
function normalize(value: string): string {
|
||||
return value.trim().replace(/\\/g, "/").replace(/\/+$/g, "").toLowerCase();
|
||||
}
|
||||
|
||||
function leafSegment(path: string): string {
|
||||
const cleaned = path.replace(/\\/g, "/").replace(/\/+$/g, "");
|
||||
const idx = cleaned.lastIndexOf("/");
|
||||
return idx >= 0 ? cleaned.slice(idx + 1) : cleaned;
|
||||
}
|
||||
|
||||
function matches(option: { name: string; path: string }, query: string): boolean {
|
||||
const q = query.toLowerCase();
|
||||
return option.name.toLowerCase().includes(q) || option.path.toLowerCase().includes(q);
|
||||
}
|
||||
|
||||
function looksLikeUrl(value: string): boolean {
|
||||
return /^(https?:\/\/|git@|ssh:\/\/|git:\/\/)/i.test(value);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import { IconCode, IconWorld, IconX } from "@tabler/icons-react";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { formatUserHomePath } from "@/lib/utils";
|
||||
import type { Repository } from "@/lib/types/http";
|
||||
|
||||
/**
|
||||
* A single attached repository, rendered as a chip with friendly label
|
||||
* + remove button. Falls back to the raw stored string when no
|
||||
* workspace row matches (custom URL or unimported local path).
|
||||
*/
|
||||
export function RepoChip({
|
||||
value,
|
||||
workspaceRepos,
|
||||
onRemove,
|
||||
}: {
|
||||
value: string;
|
||||
workspaceRepos: Repository[];
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const matched = workspaceRepos.find((r) => r.local_path === value);
|
||||
const isUrl = looksLikeUrl(value);
|
||||
const label = matched?.name ?? (isUrl ? value : leafSegment(value));
|
||||
const detail = matched?.local_path ?? value;
|
||||
const displayDetail = isUrl ? value : formatUserHomePath(detail);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-input bg-input/20 dark:bg-input/30 pl-2.5 pr-0.5 h-8 text-xs"
|
||||
data-testid="project-repo-chip"
|
||||
data-repository-value={value}
|
||||
>
|
||||
{isUrl ? (
|
||||
<IconWorld className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<IconCode className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="truncate max-w-[240px]">{label}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
aria-label="Remove repository"
|
||||
className="h-6 w-6 inline-flex items-center justify-center rounded text-muted-foreground hover:text-destructive hover:bg-muted/60 cursor-pointer"
|
||||
data-testid="project-repo-chip-remove"
|
||||
>
|
||||
<IconX className="h-3 w-3" />
|
||||
</button>
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{displayDetail}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function looksLikeUrl(value: string): boolean {
|
||||
return /^(https?:\/\/|git@|ssh:\/\/|git:\/\/)/i.test(value);
|
||||
}
|
||||
|
||||
function leafSegment(path: string): string {
|
||||
const cleaned = path.replace(/\\/g, "/").replace(/\/+$/g, "");
|
||||
const idx = cleaned.lastIndexOf("/");
|
||||
return idx >= 0 ? cleaned.slice(idx + 1) : cleaned;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { normalizeRepoValue, shouldShowCustomEntry } from "./repo-entry";
|
||||
|
||||
describe("normalizeRepoValue", () => {
|
||||
it("normalizes separators, trailing slashes, and case", () => {
|
||||
expect(normalizeRepoValue("C:\\Work\\App\\")).toBe("c:/work/app");
|
||||
expect(normalizeRepoValue(" /work/app/ ")).toBe("/work/app");
|
||||
expect(normalizeRepoValue("https://GitHub.com/Org/Repo")).toBe("https://github.com/org/repo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldShowCustomEntry", () => {
|
||||
it("keeps the custom row when a suggestion only partially matches", () => {
|
||||
// /work/app must stay addable even though /work/app-old is listed —
|
||||
// selecting the near-miss suggestion would attach the wrong repo.
|
||||
expect(shouldShowCustomEntry("/work/app", ["/work/app-old"], [])).toBe(true);
|
||||
expect(shouldShowCustomEntry("app", ["/work/app-old"], [])).toBe(true);
|
||||
});
|
||||
|
||||
it("hides the custom row on an exact match with an option", () => {
|
||||
expect(shouldShowCustomEntry("/work/app", ["/work/app"], [])).toBe(false);
|
||||
});
|
||||
|
||||
it("treats normalization variants as exact matches", () => {
|
||||
expect(shouldShowCustomEntry("C:\\Work\\App\\", ["c:/work/app"], [])).toBe(false);
|
||||
expect(shouldShowCustomEntry("/work/app/", ["/work/app"], [])).toBe(false);
|
||||
});
|
||||
|
||||
it("hides the custom row when the value is already attached", () => {
|
||||
expect(shouldShowCustomEntry("/work/app", [], ["/work/app"])).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for empty or whitespace-only queries", () => {
|
||||
expect(shouldShowCustomEntry("", ["/work/app"], [])).toBe(false);
|
||||
expect(shouldShowCustomEntry(" ", [], [])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
// Value normalization + custom-entry visibility for the project
|
||||
// repository picker.
|
||||
|
||||
/**
|
||||
* Canonical form for comparing repository entries: trimmed, forward
|
||||
* slashes, no trailing slash, case-insensitive. Repo values mix git
|
||||
* URLs, Windows paths, and POSIX paths, so comparisons must survive
|
||||
* `C:\repo\` vs `c:/repo`.
|
||||
*/
|
||||
export function normalizeRepoValue(value: string): string {
|
||||
return value.trim().replace(/\\/g, "/").replace(/\/+$/g, "").toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the picker should offer the free-form "Use <query>" row.
|
||||
*
|
||||
* Only an exact normalized match against an option or an
|
||||
* already-attached entry hides the row. A substring or prefix overlap
|
||||
* must NOT hide it: with `/work/app-old` in the suggestions, typing
|
||||
* `/work/app` has to stay addable as a literal path — selecting the
|
||||
* near-miss suggestion would attach the wrong repo.
|
||||
*/
|
||||
export function shouldShowCustomEntry(
|
||||
query: string,
|
||||
optionValues: string[],
|
||||
excludedValues: string[],
|
||||
): boolean {
|
||||
const q = normalizeRepoValue(query);
|
||||
if (!q) return false;
|
||||
const taken = (v: string) => normalizeRepoValue(v) === q;
|
||||
return !excludedValues.some(taken) && !optionValues.some(taken);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { useDiscoveredRepositories } from "./use-discovered-repositories";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
|
||||
vi.mock("@/app/actions/workspaces", () => ({
|
||||
discoverRepositoriesAction: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockDiscover = vi.mocked(discoverRepositoriesAction);
|
||||
|
||||
const repoA: LocalRepository = { path: "/work/a", name: "a", default_branch: "main" };
|
||||
const repoB: LocalRepository = { path: "/work/b", name: "b", default_branch: "main" };
|
||||
|
||||
function deferred() {
|
||||
let resolve!: (v: { repositories: LocalRepository[] }) => void;
|
||||
const promise = new Promise<{ repositories: LocalRepository[] }>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function renderDiscovery(open: boolean, ws: string | null) {
|
||||
return renderHook(
|
||||
({ o, w }: { o: boolean; w: string | null }) => useDiscoveredRepositories(o, w),
|
||||
{
|
||||
initialProps: { o: open, w: ws },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
describe("useDiscoveredRepositories", () => {
|
||||
beforeEach(() => {
|
||||
mockDiscover.mockReset();
|
||||
});
|
||||
|
||||
it("returns null until discovery resolves, then the repos", async () => {
|
||||
mockDiscover.mockResolvedValue({ repositories: [repoA] } as never);
|
||||
const { result } = renderDiscovery(true, "ws1");
|
||||
expect(result.current).toBeNull();
|
||||
await waitFor(() => expect(result.current).toEqual([repoA]));
|
||||
expect(mockDiscover).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not fetch while closed", () => {
|
||||
renderDiscovery(false, "ws1");
|
||||
expect(mockDiscover).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retries after a request interrupted by closing the popover", async () => {
|
||||
const first = deferred();
|
||||
mockDiscover.mockReturnValueOnce(first.promise as never);
|
||||
const { result, rerender } = renderDiscovery(true, "ws1");
|
||||
|
||||
// Close before the first request resolves — its response is discarded.
|
||||
rerender({ o: false, w: "ws1" });
|
||||
await act(async () => first.resolve({ repositories: [repoA] }));
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
// Reopen: must refetch instead of latching "searching" forever.
|
||||
mockDiscover.mockResolvedValueOnce({ repositories: [repoB] } as never);
|
||||
rerender({ o: true, w: "ws1" });
|
||||
await waitFor(() => expect(result.current).toEqual([repoB]));
|
||||
expect(mockDiscover).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("never surfaces another workspace's results after a switch", async () => {
|
||||
const slowWs1 = deferred();
|
||||
mockDiscover.mockReturnValueOnce(slowWs1.promise as never);
|
||||
mockDiscover.mockResolvedValueOnce({ repositories: [repoB] } as never);
|
||||
const { result, rerender } = renderDiscovery(true, "ws1");
|
||||
|
||||
// Switch workspaces while ws1's request is still in flight.
|
||||
rerender({ o: true, w: "ws2" });
|
||||
expect(result.current).toBeNull();
|
||||
await waitFor(() => expect(result.current).toEqual([repoB]));
|
||||
|
||||
// ws1's late response must not clobber ws2's result.
|
||||
await act(async () => slowWs1.resolve({ repositories: [repoA] }));
|
||||
expect(result.current).toEqual([repoB]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { discoverRepositoriesAction } from "@/app/actions/workspaces";
|
||||
import type { LocalRepository } from "@/lib/types/http";
|
||||
|
||||
type DiscoveryResult = { ws: string; repos: LocalRepository[] };
|
||||
|
||||
/**
|
||||
* Lazily discovers on-disk repositories while the picker popover is
|
||||
* open. Returns `null` until the current workspace's discovery has
|
||||
* resolved — used to drive the "Searching your machine…" empty-state
|
||||
* copy without an extra loading flag.
|
||||
*
|
||||
* The result is keyed by workspace id and derived on read, so a
|
||||
* workspace switch immediately yields `null` (never another
|
||||
* workspace's paths) and triggers a fresh scan, and a request
|
||||
* interrupted by closing the popover simply retries on reopen
|
||||
* instead of latching a never-resolved state.
|
||||
*/
|
||||
export function useDiscoveredRepositories(
|
||||
open: boolean,
|
||||
workspaceId: string | null,
|
||||
): LocalRepository[] | null {
|
||||
const [result, setResult] = useState<DiscoveryResult | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !workspaceId) return;
|
||||
if (result?.ws === workspaceId) return;
|
||||
let cancelled = false;
|
||||
discoverRepositoriesAction(workspaceId)
|
||||
.then((res) => {
|
||||
if (!cancelled) setResult({ ws: workspaceId, repos: res.repositories ?? [] });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setResult({ ws: workspaceId, repos: [] });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, workspaceId, result]);
|
||||
|
||||
return result?.ws === workspaceId ? result.repos : null;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { test, expect } from "../../fixtures/office-fixture";
|
||||
|
||||
/**
|
||||
@@ -62,6 +64,17 @@ test.describe("Project repository picker", () => {
|
||||
// Empty-state line disappears once a chip exists.
|
||||
await expect(testPage.getByText("No repositories added yet.")).toHaveCount(0);
|
||||
|
||||
// Re-open the picker: the exact attached value must not offer a
|
||||
// duplicate custom row, but a prefix of it must stay addable —
|
||||
// partial overlap with existing entries cannot block literal input.
|
||||
await testPage.getByTestId("project-add-repository").click();
|
||||
await expect(searchInput).toBeVisible();
|
||||
await searchInput.fill(url);
|
||||
await expect(testPage.getByTestId("project-add-custom")).toHaveCount(0);
|
||||
await searchInput.fill(url.replace(/\.git$/, ""));
|
||||
await expect(testPage.getByTestId("project-add-custom")).toBeVisible();
|
||||
await testPage.keyboard.press("Escape");
|
||||
|
||||
// Remove the chip; empty state comes back.
|
||||
await chip.getByTestId("project-repo-chip-remove").click();
|
||||
await expect(chip).toHaveCount(0, { timeout: 10_000 });
|
||||
@@ -85,4 +98,78 @@ test.describe("Project repository picker", () => {
|
||||
await expect(testPage.getByTestId("project-add-custom")).toBeVisible({ timeout: 5_000 });
|
||||
await expect(testPage.getByTestId("project-add-custom")).toContainText(/Add as local path/i);
|
||||
});
|
||||
|
||||
test("a near-miss workspace suggestion does not block adding the literal path", async ({
|
||||
apiClient,
|
||||
testPage,
|
||||
officeSeed,
|
||||
backend,
|
||||
}) => {
|
||||
const projectId = await createProject(apiClient, officeSeed.workspaceId, "Repo Picker Overlap");
|
||||
// Register a workspace repo whose path is a superstring of the one
|
||||
// we'll type — the classic /work/app vs /work/app-old overlap.
|
||||
const oldPath = path.join(backend.tmpDir, "repos", "app-old");
|
||||
fs.mkdirSync(oldPath, { recursive: true });
|
||||
await apiClient.createRepository(officeSeed.workspaceId, oldPath, "main", { name: "app-old" });
|
||||
|
||||
await testPage.goto(`/office/projects/${projectId}`);
|
||||
await testPage.getByTestId("project-add-repository").click();
|
||||
const searchInput = testPage.getByPlaceholder(/Search or paste a URL/i);
|
||||
await expect(searchInput).toBeVisible();
|
||||
|
||||
const newPath = path.join(backend.tmpDir, "repos", "app");
|
||||
await searchInput.fill(newPath);
|
||||
|
||||
// Both the near-miss suggestion and the free-form row must be offered.
|
||||
await expect(testPage.getByRole("option", { name: /app-old/ })).toBeVisible();
|
||||
const customRow = testPage.getByTestId("project-add-custom");
|
||||
await expect(customRow).toBeVisible();
|
||||
await customRow.click();
|
||||
|
||||
// The literal path is attached — not the near-miss suggestion.
|
||||
const chip = testPage.getByTestId("project-repo-chip");
|
||||
await expect(chip).toHaveAttribute("data-repository-value", newPath, { timeout: 10_000 });
|
||||
});
|
||||
|
||||
// The create-project dialog embeds the same picker as the detail page.
|
||||
// Without this, a dialog-side regression (picker not wired to the form
|
||||
// state, repositories dropped from the create payload) would silently
|
||||
// break attaching a repo at creation time.
|
||||
test("create-project dialog: pick a repo → create → repo persists on detail page", async ({
|
||||
testPage,
|
||||
officeSeed: _,
|
||||
}) => {
|
||||
await testPage.goto("/office/projects");
|
||||
await testPage
|
||||
.getByRole("button", { name: /New Project|Create your first project/ })
|
||||
.first()
|
||||
.click();
|
||||
|
||||
const dialog = testPage.getByRole("dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
const projectName = `Picker Create ${Date.now()}`;
|
||||
await dialog.locator("#project-name").fill(projectName);
|
||||
|
||||
// Add a repository through the picker's custom-entry row.
|
||||
const url = "https://github.com/example/created-with-picker.git";
|
||||
await dialog.getByTestId("project-add-repository").click();
|
||||
const searchInput = dialog.getByPlaceholder(/Search or paste a URL/i);
|
||||
await expect(searchInput).toBeVisible();
|
||||
await searchInput.fill(url);
|
||||
const customRow = dialog.getByTestId("project-add-custom");
|
||||
await expect(customRow).toBeVisible({ timeout: 5_000 });
|
||||
await customRow.click();
|
||||
|
||||
// Chip renders inside the dialog before submitting.
|
||||
const dialogChip = dialog.locator('[data-testid="project-repo-chip"]', { hasText: url });
|
||||
await expect(dialogChip).toBeVisible();
|
||||
|
||||
await dialog.getByRole("button", { name: "Create Project" }).click();
|
||||
await expect(dialog).toHaveCount(0, { timeout: 10_000 });
|
||||
|
||||
// The new project card appears; opening it shows the persisted repo chip.
|
||||
await testPage.getByText(projectName).first().click();
|
||||
const detailChip = testPage.locator('[data-testid="project-repo-chip"]', { hasText: url });
|
||||
await expect(detailChip).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user