Files
kandev/apps/web/components/folder-picker.tsx
T
João Salavisa 45a46f9899 feat: support tasks without a repository (#850)
* feat: support tasks without a repository

Lets users create a task with no repository attached — useful for research,
brainstorming, design discussions, or pointing the agent at an existing
non-git folder. The create-task dialog gains a 3-mode segmented control
(Repo / URL / None); "None" mode replaces the chip row with a folder
picker that browses the host filesystem via a new GET /api/v1/fs/list-dir
endpoint and either commits an absolute path or falls back to a kandev-
managed scratch workspace at <homeDir>/tasks/<workspaceID>/<taskID>/.

The worktree executor is hidden from the picker in no-repo mode (it
inherently needs a repo); the lifecycle manager also short-circuits
worktree mode server-side as a belt-and-suspenders guard. The Changes
panel auto-closes for repo-less tasks since it has nothing to show, and
the cumulative-diff handler returns null instead of erroring when no
base commit exists.

Spec + plan added at docs/specs/tasks-without-repositories/.

* fix(backend): anchor folder picker to discovery roots (CodeQL path traversal)

CodeQL flagged the new GET /api/v1/fs/list-dir handler for piping a
user-controlled path straight into os.Stat / os.ReadDir. Restrict the
listing to paths inside the configured discovery roots (defaults to
$HOME, same allowlist as repository discovery), reject anything outside
with ErrPathNotAllowed → HTTP 403, and clip the breadcrumb's "up"
button at the root so the picker can't be used to walk above the
allowed prefix.

Tests cover: rejection of paths outside roots, traversal escapes (../),
default-to-first-root, and parent exposure for nested paths.

* fix(backend): use os.Root for folder picker (recognized CodeQL sanitizer)

Previous attempt anchored to discovery roots via isPathAllowed, but
CodeQL's data flow doesn't model that helper as a sanitizer and kept
flagging os.Stat / os.ReadDir. Switch to os.Root (Go 1.24+): open the
matching discovery root once and run Stat/Open/ReadDir against the
relative path within it. The OS itself enforces containment — symlinks
and traversal cannot escape — and CodeQL recognizes os.Root as safe.

* fix: address PR review feedback

- Changes panel auto-close now distinguishes "task loading" from
  "task has no repos" (returns boolean | null), so the panel isn't
  permanently removed during the first-render window before task
  data lands in the store.
- Reset noRepository / workspacePath in resetDiscoveryState so
  reopening the dialog after a None-mode task doesn't carry the
  flag forward.
- Folder-picker breadcrumb: dropped dead `i > 0 && i > 1` condition
  (always equivalent to `i > 1`); chevrons now render between every
  segment as expected.
- list-dir HTTP handler returns a generic error message instead of
  forwarding raw OS errors that leak host paths.
- Document the dataDir → kandevHome inversion convention next to
  the scratch-path computation so future readers don't mistake the
  filepath.Dir call for a fragile derivation.

* fix: address CodeRabbit review nitpicks

- Trim whitespace on workspace_path before persisting to task metadata
  so a value of "   " doesn't get stored as a non-empty path.
- Extract the workspace_path metadata key into models.MetaKeyWorkspacePath
  alongside the existing MetaKeyAgentProfileID / MetaKeyExecutorProfileID
  so the set/read sites can't drift apart.
- Folder picker: reset cached listing when the popover closes, so
  reopening reloads from `value` instead of showing the last browsed
  directory the user navigated away from without committing.
- Submit payload: send `workspace_path: undefined` instead of an empty
  string when the trimmed value is empty, matching the noRepository=false
  case and keeping the API contract clear.

* fix: scratch path lands in kandev home, not its parent

Claude caught a real bug — `m.dataDir` is set from `cfg.ResolvedHomeDir()`
in cmd/kandev/agents.go, not `ResolvedDataDir()` (the field name is
misleading and the comment was wrong). My previous use of
`filepath.Dir(m.dataDir)` therefore walked one level above the kandev
home, so scratch dirs landed at e.g. `~/tasks/<ws>/<task>` instead of
`~/.kandev/tasks/<ws>/<task>` — and at the project root in dev mode
where `KANDEV_HOME_DIR=<project>/.kandev-dev`, which is what the user
saw on their machine.

Use `m.dataDir` directly (it's already the kandev home), document the
field's misnamed-but-correct semantics, and tighten the test fixtures.

Also:
- folder-picker trigger gets `cursor-pointer` (CodeRabbit nitpick).

* fix: pass workspacePath through handleCreateWithoutAgent too

The "create without agent" path called buildCreateTaskPayload without
the new workspacePath field, so picking a folder + clicking "Create
without starting" silently dropped the path. Now matches the
performCreate (with-agent) path.

* fix: satisfy DialogFormState in new-subtask form stub

PR #852 (merged after this branch was created) introduced
new-subtask-form-state.ts which stubs out a DialogFormState for the
subtask dialog. Adding noRepository / setNoRepository / workspacePath /
setWorkspacePath to the type made that stub incomplete, breaking the
Next.js production build (caught by CI, missed by tsc --noEmit).

Add the four inert fields to the stub, alongside the existing fresh-
branch inert fields, and pull both groups into named constants to
keep the useMemo body under the per-function line cap.

* fix: keep toggle-github-url testid as alias on URL-mode button

The new source-mode segmented control replaced the previous
"or paste a GitHub URL" text link, which had data-testid="toggle-github-url".
The existing e2e suite (create-task-github-url.spec.ts and the new
subtask.spec.ts from #852) still selects the URL toggle by that testid.
Keep "toggle-github-url" as the testid on the URL-mode button so both
suites pass without a sweep across all e2e files. Click semantics are
unchanged — single click enters URL mode.

* test(e2e): update toggle assertion for new source-mode segmented control

create-task-github-url.spec.ts:892 was checking the old text-link
toggle's two-way behavior with text labels ("or paste a GitHub URL" /
"use a workspace repository"). The new segmented control has explicit
mode buttons; assert aria-checked instead of label text. The other 9
clicks on `toggle-github-url` in this file still work via the legacy
testid alias on the URL-mode button.

* refactor: extract useActiveTaskHasRepos to its own hook file

dockview-desktop-layout.tsx grew to 609 lines with the new hook +
the Changes panel guard, over the 600-line cap documented in
CLAUDE.md (lint passed but the convention is real). Move the hook
to hooks/domains/kanban/use-active-task-has-repos.ts. File drops
to 590 lines.

* chore: gitignore .claude/scheduled_tasks.lock runtime file

* fix(web): lock chip-row min-height so modal doesn't shift on mode toggle

The chip row uses flex-wrap; Repo mode (chip + branch + add button +
segmented control) sometimes occupies a different vertical extent than
None mode (single folder picker + segmented control), causing the
create-task modal to jump a few pixels when toggling between sources.
Set min-h-9 so the row always reserves at least one chip-row of
height regardless of the active mode.

* feat: let folder picker browse anywhere, drop allowed-roots gate

The picker is for choosing a starting folder for a repo-less task —
users legitimately want /tmp, /var/log/foo, or any directory they have
read access to. Coupling it to the repo-discover endpoint's
discoveryRoots ($HOME by default) was too tight: paths like /tmp
returned 403 "path is not within allowed roots".

Decouple ListDirectory from discoveryRoots. The repo-discover endpoint
(DiscoverLocalRepositories, ValidateLocalRepositoryPath,
LocalRepositoryStatus, ListBranches) stays anchored to the allowlist
since picking a repo to import is a workspace-scoped operation; the
folder picker trusts the local-process boundary instead.

CodeQL is kept happy by routing the FS operations through os.Root
opened at "/" — the Go stdlib sanitizer for path injection still
recognises it (containment to / is trivially satisfied for every
absolute path on the host).

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-12 01:10:22 +01:00

267 lines
8.5 KiB
TypeScript

"use client";
import { Fragment, useCallback, useEffect, useState } from "react";
import { IconFolder, IconBox, IconChevronRight } from "@tabler/icons-react";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@/lib/utils";
import { listDirectory, type DirectoryListing } from "@/lib/api/domains/fs-api";
type FolderPickerProps = {
/** Currently chosen absolute path; empty when nothing is picked. */
value: string;
/** Called with the absolute path when the user chooses a folder. */
onChange: (path: string) => void;
placeholder?: string;
};
/**
* Folder picker for repo-less tasks. Drives GET /api/v1/fs/list-dir on the
* local kandev backend (browsers can't enumerate the host filesystem). The
* trigger lives in the chip row and the popover handles browse + commit.
*/
export function FolderPicker({ value, onChange, placeholder }: FolderPickerProps) {
const [open, setOpen] = useState(false);
const { listing, loading, error, load } = useDirectoryListing(open, value);
const leaf = leafName(value);
const triggerLabel = leaf || placeholder || "scratch workspace";
const hasValue = !!value;
const triggerClass = cn(
"h-7 inline-flex items-center gap-1.5 rounded-md px-2.5 text-xs cursor-pointer",
"border border-border/60 transition-colors",
hasValue
? "bg-primary/10 text-foreground hover:bg-primary/15"
: "bg-muted/30 text-muted-foreground hover:bg-muted/60",
);
const trigger = (
<button type="button" data-testid="folder-picker-trigger" className={triggerClass}>
{hasValue ? (
<IconFolder className="h-3.5 w-3.5 flex-shrink-0" />
) : (
<IconBox className="h-3.5 w-3.5 flex-shrink-0" />
)}
<span className="truncate max-w-[260px]">{triggerLabel}</span>
</button>
);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
{hasValue ? (
<Tooltip>
<TooltipTrigger asChild>{trigger}</TooltipTrigger>
<TooltipContent className="font-mono text-[11px]">{value}</TooltipContent>
</Tooltip>
) : (
trigger
)}
</PopoverTrigger>
<PopoverContent
className="w-[440px] gap-0 p-0 overflow-hidden"
align="start"
sideOffset={4}
data-testid="folder-picker-popover"
>
<Breadcrumb path={listing?.path ?? ""} onNavigate={(p) => void load(p)} />
<Entries
listing={listing}
loading={loading}
error={error}
onDescend={(p) => void load(p)}
/>
<Footer
choosable={!!listing?.path}
onUseScratch={() => {
onChange("");
setOpen(false);
}}
onChoose={() => {
if (!listing) return;
onChange(listing.path);
setOpen(false);
}}
/>
</PopoverContent>
</Popover>
);
}
function leafName(path: string): string {
if (!path) return "";
const trimmed = path.replace(/\/+$/, "");
const idx = trimmed.lastIndexOf("/");
return idx === -1 ? trimmed : trimmed.slice(idx + 1) || "/";
}
function useDirectoryListing(open: boolean, value: string) {
const [listing, setListing] = useState<DirectoryListing | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async (path: string) => {
setLoading(true);
setError(null);
try {
setListing(await listDirectory(path));
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load directory");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
// Reset cached listing when the popover closes so the next open reloads
// from `value`. Without this, a user who browsed deep into the tree,
// closed without committing, and reopened would still see the stale
// last-browsed directory instead of their picked folder (or the root).
if (!open) {
setListing(null);
return;
}
if (listing) return;
void load(value || "");
}, [open, listing, load, value]);
return { listing, loading, error, load };
}
/** Splits an absolute path into clickable breadcrumb segments. */
function pathSegments(path: string): Array<{ name: string; path: string }> {
if (!path) return [];
const parts = path.split("/").filter(Boolean);
const segs: Array<{ name: string; path: string }> = [{ name: "/", path: "/" }];
let acc = "";
for (const part of parts) {
acc += `/${part}`;
segs.push({ name: part, path: acc });
}
return segs;
}
function Breadcrumb({ path, onNavigate }: { path: string; onNavigate: (p: string) => void }) {
const segs = pathSegments(path);
return (
<div className="flex items-center gap-0.5 border-b border-border bg-muted/30 px-2 py-1.5 overflow-x-auto">
{segs.length === 0 && (
<span className="text-[11px] text-muted-foreground italic">Loading…</span>
)}
{segs.map((seg, i) => {
const last = i === segs.length - 1;
return (
<Fragment key={seg.path}>
{i > 0 && (
<IconChevronRight className="h-3 w-3 flex-shrink-0 text-muted-foreground/60" />
)}
<button
type="button"
onClick={() => !last && onNavigate(seg.path)}
disabled={last}
className={cn(
"rounded px-1.5 py-0.5 text-[11px] font-mono whitespace-nowrap",
last
? "text-foreground cursor-default"
: "text-muted-foreground hover:bg-accent hover:text-foreground cursor-pointer",
)}
>
{seg.name}
</button>
</Fragment>
);
})}
</div>
);
}
function Entries({
listing,
loading,
error,
onDescend,
}: {
listing: DirectoryListing | null;
loading: boolean;
error: string | null;
onDescend: (path: string) => void;
}) {
if (loading) return <EmptyRow text="Loading…" />;
if (error) return <EmptyRow text={error} variant="error" testId="folder-picker-error" />;
if (!listing || listing.entries.length === 0) {
return <EmptyRow text="No folders here — pick this one or go up" />;
}
return (
<div
className="max-h-[280px] overflow-y-auto overscroll-contain py-1"
onWheel={(e) => e.stopPropagation()}
>
{listing.entries.map((entry) => (
<button
key={entry.path}
type="button"
onClick={() => onDescend(entry.path)}
className="group flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs hover:bg-accent cursor-pointer"
data-testid="folder-picker-entry"
>
<IconFolder className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground group-hover:text-foreground" />
<span className="truncate flex-1">{entry.name}</span>
<IconChevronRight className="h-3 w-3 flex-shrink-0 text-muted-foreground/40 group-hover:text-muted-foreground" />
</button>
))}
</div>
);
}
function EmptyRow({ text, variant, testId }: { text: string; variant?: "error"; testId?: string }) {
return (
<div
className={cn(
"py-8 text-center text-xs",
variant === "error" ? "text-destructive" : "text-muted-foreground",
)}
data-testid={testId}
>
{text}
</div>
);
}
function Footer({
choosable,
onUseScratch,
onChoose,
}: {
choosable: boolean;
onUseScratch: () => void;
onChoose: () => void;
}) {
return (
<div className="flex items-center justify-between gap-2 border-t border-border bg-muted/20 px-2 py-1.5">
<button
type="button"
onClick={onUseScratch}
data-testid="folder-picker-use-scratch"
className="inline-flex items-center gap-1.5 rounded px-2 py-1 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground cursor-pointer"
>
<IconBox className="h-3 w-3" />
Use scratch instead
</button>
<button
type="button"
disabled={!choosable}
onClick={onChoose}
data-testid="folder-picker-choose"
className={cn(
"inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-[11px] font-medium transition-colors cursor-pointer",
"bg-primary text-primary-foreground hover:bg-primary/90",
"disabled:opacity-40 disabled:cursor-not-allowed",
)}
>
<IconFolder className="h-3 w-3" />
Use this folder
</button>
</div>
);
}