Files
kandev/apps/web/components/task-create-dialog-repo-chips.test.tsx
T
João Salavisa fd79d6170f feat(tasks): multi-branch tasks — N (repo, branch) pairs per task (#1226)
* feat(tasks): multi-branch tasks — N (repo, branch) pairs per task

Extends multi-repo into multi-branch so a single task can hold multiple
worktrees on the same repo (one per branch). Sibling worktrees layout at
<task>/<repo>/ + <task>/<repo>-<slug>/, dedicated PRWatch per branch,
live agentctl tracker rescan + frontend store updates so the UI splits
PRs / files / commits per branch without a session restart. MCP
add_branch_to_task_kandev tool is shielded to the worktree executor.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): unify multi-branch repo label as <repo> · <branch> across panels

PR Changes and Commits panels rendered repo labels differently for multi-branch
tasks — Commits showed "kandev · feature/x" while PR Changes leaked the raw
"kandev-feature-x" agentctl tracker tag. Reformat tracker-tagged repo names via
formatRepoLabel using the longest known-repo prefix so kandev-cli-* doesn't
collapse to kandev · cli-*.

* fix(tasks): address multi-branch PR review — data races, slug collisions, MCP error codes

Backend
- agentctl process.Manager: add repoTrackersMu RWMutex guarding repoTrackers
  + workspaceTracker. Reads snapshot under RLock; RescanRepositories builds
  trackers first, takes Lock for swap/append. Validates newWorkDir via
  os.Stat before publishing cfg.WorkDir.
- worktree.Manager: reject invalid explicit BranchSlug up-front; cache key
  uses sanitized wt.BranchSlug so read/write paths are symmetric.
- worktree.store: narrow isDuplicateColumnError to "duplicate column name".
- task service AddBranchToTask: slug-collision guard rejects feat/a vs feat-a.
- orchestrator resolvePushRepo: two-pass exact-name match before subdir
  prefix fallback so "backend" doesn't swallow pushes for "backend-admin".
- executor buildRepoSpecs: duplicate repos always get a non-empty BranchSlug
  (falls back to branch-N when both branch fields sanitize to empty).
- MCP handler: classifyAddBranchError maps service errors to NOT_FOUND /
  CONFLICT / VALIDATION_ERROR; add ErrorCodeConflict constant.
- MCP server: extract registerAddBranchToTaskTool, register in task mode
  only (external mode contract: config tools + create_task_kandev).
- workspace_rescan handler: reject malformed JSON with 400 instead of
  silently rescanning the current root.
- branch_materializer: split MaterializeBranch into prepare + finalize
  helpers to satisfy the 80-line cap.

Frontend
- existingPrUrl returns undefined when a task has >1 PR so per-repo View PR
  buttons take over (no silent linking to a sibling).
- formatRepoLabel checks exact known-repo match before prefix splitting so
  "kandev-cli" isn't mislabeled as "kandev · cli".
- Repo chip key now includes base_branch so siblings differing only on
  base render as distinct chips.

Docs
- multi-branch spec uniqueness wording aligned with the canonical 4-column
  key (task_id, repository_id, base_branch, checkout_branch).
- worktree.CreateRequest.BranchSlug doc describes the sibling layout
  (<repo>-<slug>) instead of the obsolete nested form.

* fix(tasks): scope slug-collision check to repo only + use errors.Is for ErrTaskNotFound

- service_branches: drop base_branch from the slug-collision check. Worktree
  path is (repo, slug); two rows on the same repo cut from different bases
  still collide on disk.
- service_branches: prepareBranchAdd wraps taskrepo.ErrTaskNotFound via
  fmt.Errorf with %w so classifiers don't have to substring-match the
  formatted task UUID.
- mcp handlers: classifyAddBranchError uses errors.Is(err, ErrTaskNotFound).

* fix(agentctl): sanitize rescan work_dir before os.Stat to clear CodeQL path-injection

CodeQL flagged the rescan endpoint as a path-injection sink (the
HTTP-supplied work_dir flowed straight into os.Stat and downstream
scanRepositorySubdirs). Add validateRescanPath which:
- requires the input to be a clean absolute path with no ".." segments
- rejects anything that isn't equal to or an ancestor of the current
  cfg.WorkDir — the only legitimate use case is the branch materializer
  promoting <task>/<repo>/ to <task>/

Defense in depth: agentctl binds to localhost, but any colocated process
could otherwise direct it at /etc or the user's home by POSTing
/api/v1/workspace/rescan.

* fix(agentctl): tighten validateRescanPath, close TOCTOU on existingTrackers, add tests

- Drop the strings.Contains(clean, "..") guard. filepath.Clean already
  resolves traversal; the substring check rejects legitimate names like
  /home/u/..hidden without adding defense (the ancestor check via
  filepath.Rel is the real boundary).
- Drop the rel == "." branch in the ancestor check — early return for
  clean == currentClean already covers identity.
- Read existingTrackers inside the write-lock section (not under RLock
  then re-Lock) so two concurrent rescans can't both see 0 trackers and
  double-bootstrap the multi-repo set.
- Add table-driven TestValidateRescanPath covering rejection paths
  (relative, descendant, sibling, traversal-cleaned, empty input),
  legitimate ancestor promotion, exact match, no-anchor first-launch,
  and a /home/u/..hidden dotted-segment case.

* fix(agentctl): break taint flow into os.Stat — derive rescan path from cfg, not HTTP body

CodeQL's go/path-injection trace still flagged manager_rescan.go after the
prior sanitizer because the user-supplied newWorkDir flowed (after
validation) into os.Stat and then into cfg.WorkDir → tracker paths →
workspace_monitor os.Stat sinks.

Replace validateRescanPath with resolveRescanPath: it returns a path
DERIVED from currentWorkDir (no-op = currentClean, promotion =
filepath.Dir(currentClean)) and uses newPath only for comparison, never
as a source for the returned string. os.Stat now receives a path whose
provenance is trusted manager config.

Functionally the legitimate caller (branch materializer promoting
<task>/<repo>/ to <task>/) is unchanged.

* test(agentctl): make TestResolveRescanPath windows-portable

The Linux Backend Tests job passed but the Backend (windows) job rejected
every "absolute" case because filepath.IsAbs("/task/repo") is false on
Windows (no volume letter).

Build inputs via filepath.Join against absRoot() (filepath.Abs of "/" /
"\\") so the same table covers POSIX (`/...`) and Windows (`C:\...`)
without per-OS branches. Keep the traversal-after-Clean case POSIX-only
since filepath.Clean is the shared primitive and that input form needs a
volume to be considered absolute on Windows anyway.

* fix(agentctl): serialize RescanRepositories + re-check trackers under write lock

Two concurrent RescanRepositories calls could both observe an empty
tracker set (between the snapshot read and the bootstrap branch) and both
enter transitionToMultiRepoMode, leaking a duplicate bare-root tracker
and duplicate per-repo trackers. Same race in appendNewRepoTrackers would
double-append the same new child across both callers.

Fix:
- Add rescanMu sync.Mutex on Manager. Acquired for the full body of
  RescanRepositories so the snapshot → branch → mutate sequence is
  serialized. repoTrackersMu still guards individual field reads from
  unrelated goroutines (subscribe/unsubscribe/poll-mode).
- appendNewRepoTrackers re-checks membership inside the write-lock
  before appending and drops already-present trackers (Stop + detach
  outside the lock). Defense in depth.
- Test: add `dotted segment is legal as promotion` case so the
  ..hidden-segment promotion path stays exercised.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 19:36:20 +01:00

405 lines
15 KiB
TypeScript

import { describe, it, expect, vi, afterEach } from "vitest";
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
import type { Branch, Repository } from "@/lib/types/http";
import type { DialogFormState, TaskRepoRow } from "./task-create-dialog-types";
import { TooltipProvider } from "@kandev/ui/tooltip";
// One mocked branches hook now — id-based and path-based rows go through
// the same loader. Tests can override the return value when they need
// branch-specific assertions; the mockBySource handle lets a test prove
// which kind of source the chip passed in.
const lastBranchSource = vi.hoisted((): { value: unknown } => ({ value: null }));
const mockBranches = vi.hoisted((): { value: { branches: Branch[]; isLoading: boolean } } => ({
value: { branches: [], isLoading: false },
}));
vi.mock("@/hooks/domains/workspace/use-repository-branches", () => ({
useBranches: (source: unknown) => {
lastBranchSource.value = source;
return mockBranches.value;
},
}));
// The Remote-mode branch of RepoChipsRow renders RemoteRepoChipsRow, which
// in turn renders RemoteRepoChip — a heavy popover with its own GitHub
// hook. Stub the chip here so tests for this row stay focused on the
// branching logic (workspace chips vs. remote chips vs. folder picker).
vi.mock("./task-create-dialog-remote-repo-chip", () => ({
RemoteRepoChip: () => <div data-testid="remote-repo-chip" />,
}));
import { RepoChipsRow } from "./task-create-dialog-repo-chips";
afterEach(cleanup);
const REPO_FRONT_ID = "repo-front";
const REPO_BACK_ID = "repo-back";
function makeRepo(id: string, name: string): Repository {
return {
id,
workspace_id: "ws-1",
name,
source_type: "local",
local_path: `/repos/${name}`,
default_branch: "main",
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
} as Repository;
}
function row(overrides: Partial<TaskRepoRow> = {}): TaskRepoRow {
return { key: `row-${Math.random()}`, branch: "", ...overrides };
}
function makeFs(overrides: Partial<DialogFormState>): DialogFormState {
// Only the fields RepoChipsRow actually reads/sets need to be real.
const remoteUrl = (overrides.remoteRepos?.[0]?.url ?? "") as string;
const branchesByUrl = {
branches: (url: string) =>
url === remoteUrl
? ((overrides as Partial<DialogFormState>).branchesByUrl?.branches(url) ?? [])
: [],
loading: () => false,
ensure: () => undefined,
};
return {
repositories: [] as TaskRepoRow[],
useRemote: false,
discoveredRepositories: [],
remoteRepos: [] as DialogFormState["remoteRepos"],
setRemoteRepos: vi.fn(),
addRemoteRepo: vi.fn(),
removeRemoteRepo: vi.fn(),
updateRemoteRepo: vi.fn(),
githubUrlError: null,
branchesByUrl,
prInfoByUrl: {
info: () => undefined,
loading: () => false,
ensure: () => undefined,
clear: () => undefined,
},
addRepository: vi.fn(),
removeRepository: vi.fn(),
updateRepository: vi.fn(),
setRepositories: vi.fn(),
...overrides,
} as unknown as DialogFormState;
}
const NOOP = (_key: string, _value: string) => undefined;
function renderInProvider(ui: Parameters<typeof render>[0]) {
return render(<TooltipProvider>{ui}</TooltipProvider>);
}
// eslint-disable-next-line max-lines-per-function -- test describe block, splitting hurts readability
describe("RepoChipsRow", () => {
it("renders one chip per row plus an Add button", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({ repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })] })}
repositories={[makeRepo(REPO_FRONT_ID, "frontend"), makeRepo(REPO_BACK_ID, "backend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
expect(screen.getAllByTestId("repo-chip")).toHaveLength(1);
expect(screen.getByTestId("add-repository")).toBeTruthy();
});
it("renders one chip per row across multiple repos", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [
row({ key: "r0", repositoryId: REPO_FRONT_ID }),
row({ key: "r1", repositoryId: REPO_BACK_ID, branch: "main" }),
],
})}
repositories={[makeRepo(REPO_FRONT_ID, "frontend"), makeRepo(REPO_BACK_ID, "backend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
expect(screen.getAllByTestId("repo-chip")).toHaveLength(2);
});
it("renders the remote chips row in Remote mode (workspace chips suppressed)", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({
useRemote: true,
remoteRepos: [{ key: "remote-0", url: "", branch: "", source: "paste" }],
})}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
onToggleRemote={() => undefined}
/>,
);
expect(screen.getByTestId("repo-chips-row")).toBeTruthy();
expect(screen.queryAllByTestId("repo-chip")).toHaveLength(0);
expect(screen.getByTestId("remote-repo-chips-row")).toBeTruthy();
});
it("hides the chip row when the task is already started", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({ repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })] })}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
expect(screen.queryByTestId("repo-chips-row")).toBeNull();
});
it("local-executor row autoselects the workspace's current branch when available", () => {
mockBranches.value = {
branches: [
{ name: "main", type: "local" } as Branch,
{ name: "feature/x", type: "local" } as Branch,
],
isLoading: false,
};
const onRowBranchChange = vi.fn();
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })],
currentLocalBranch: "feature/x",
currentLocalBranchLoading: false,
})}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={onRowBranchChange}
isLocalExecutor
/>,
);
// The autoselect effect prefers preferredDefaultBranch (currentLocalBranch
// for local mode) over the last-used / main fallback. This is what surfaces
// the workspace's actual on-disk branch in the chip and ensures the submit
// payload always carries an explicit value (not "" → backend default).
expect(onRowBranchChange).toHaveBeenCalledWith("r0", "feature/x");
});
it("local-executor row shows the loading placeholder while resolving the current branch", () => {
mockBranches.value = { branches: [], isLoading: false };
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })],
currentLocalBranch: "",
currentLocalBranchLoading: true,
})}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
isLocalExecutor
/>,
);
// The chip shouldn't lie about an unset state during the brief window
// before local-status resolves; preferredDefaultBranchLoading drives the
// "loading…" placeholder.
expect(screen.getByText(/loading…/i)).toBeTruthy();
});
it("keeps Add enabled when all repos are selected (multi-branch: same repo + different branch is valid)", () => {
// With multi-branch support, the same repo can appear on multiple rows as long
// as each row uses a different branch. Therefore Add is always enabled when
// any workspace repos exist — the user can always add another branch of an
// existing repo.
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [
row({ key: "r0", repositoryId: REPO_FRONT_ID }),
row({ key: "r1", repositoryId: REPO_BACK_ID }),
],
})}
repositories={[makeRepo(REPO_FRONT_ID, "frontend"), makeRepo(REPO_BACK_ID, "backend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
const btn = screen.getByTestId("add-repository") as HTMLButtonElement;
expect(btn.disabled).toBe(false);
});
it("calls fs.addRepository when the + button is clicked", () => {
const fs = makeFs({ repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })] });
renderInProvider(
<RepoChipsRow
fs={fs}
repositories={[makeRepo(REPO_FRONT_ID, "frontend"), makeRepo(REPO_BACK_ID, "backend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
fireEvent.click(screen.getByTestId("add-repository"));
expect(fs.addRepository).toHaveBeenCalledOnce();
});
it("removing a chip calls fs.removeRepository(key)", () => {
const fs = makeFs({
repositories: [
row({ key: "r0", repositoryId: REPO_FRONT_ID, branch: "main" }),
row({ key: "r1", repositoryId: REPO_BACK_ID, branch: "develop" }),
],
});
renderInProvider(
<RepoChipsRow
fs={fs}
repositories={[makeRepo(REPO_FRONT_ID, "frontend"), makeRepo(REPO_BACK_ID, "backend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
fireEvent.click(screen.getAllByTestId("remove-repo-chip")[0]);
expect(fs.removeRepository).toHaveBeenCalledWith("r0");
});
// Regression: discovered (on-machine) repos must surface in the picker
// dropdown alongside workspace repos. A previous rewrite passed [] for
// discovered repos and lost them.
it("includes discovered (on-machine) repos in the picker dropdown", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [row({ key: "r0" })],
discoveredRepositories: [
{ path: "/home/me/projects/local-project", name: "local-project" },
// Same path as a workspace repo — should NOT appear (dedup by path).
{ path: "/repos/frontend", name: "frontend-dup" },
] as unknown as DialogFormState["discoveredRepositories"],
})}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
fireEvent.click(screen.getByTestId("repo-chip-trigger"));
expect(screen.getByText("frontend")).toBeTruthy();
expect(screen.getByText("~/projects/local-project")).toBeTruthy();
expect(screen.queryByText("frontend-dup")).toBeNull();
});
// Regression: picking a discovered repo passes its path as the value;
// onRowRepositoryChange must receive it (the handler then resolves to a
// workspace id or local path). Previously the chip wrote the path into
// a workspace `repository_id`, causing FK failures on submit.
it("calls onRowRepositoryChange with the discovered path when picked", () => {
const onRowRepositoryChange = vi.fn();
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [row({ key: "r0" })],
discoveredRepositories: [
{ path: "/home/me/projects/local-project", name: "local-project" },
] as unknown as DialogFormState["discoveredRepositories"],
})}
repositories={[]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={onRowRepositoryChange}
onRowBranchChange={NOOP}
/>,
);
fireEvent.click(screen.getByTestId("repo-chip-trigger"));
fireEvent.click(screen.getByText("~/projects/local-project"));
expect(onRowRepositoryChange).toHaveBeenCalledWith("r0", "/home/me/projects/local-project");
});
// Regression: discovered (path-keyed) rows used to call the branch loader
// with no path source, so their branch picker stayed empty. The chip must
// build a `kind: "path"` source for discovered rows so the unified hook
// hits the path-based query param instead of trying an id lookup.
it("discovered rows build a path-source for the branch loader", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({
repositories: [row({ key: "r0", localPath: "/home/me/projects/proj" })],
})}
repositories={[]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
expect(lastBranchSource.value).toEqual({
kind: "path",
workspaceId: "ws-1",
path: "/home/me/projects/proj",
});
});
it("workspace rows build an id-source for the branch loader", () => {
renderInProvider(
<RepoChipsRow
fs={makeFs({ repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })] })}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
expect(lastBranchSource.value).toEqual({
kind: "id",
workspaceId: "ws-1",
repositoryId: REPO_FRONT_ID,
});
});
// Regression: remote branches must keep their "origin/" prefix so users
// can distinguish a local "main" from "origin/main". A prior rewrite
// dropped the prefix, producing two indistinguishable rows.
it("remote branches keep their origin/ prefix and don't collide with local names", () => {
mockBranches.value = {
isLoading: false,
branches: [
{ name: "main", type: "local" },
{ name: "main", type: "remote", remote: "origin" },
] as unknown as Branch[],
};
renderInProvider(
<RepoChipsRow
fs={makeFs({ repositories: [row({ key: "r0", repositoryId: REPO_FRONT_ID })] })}
repositories={[makeRepo(REPO_FRONT_ID, "frontend")]}
isTaskStarted={false}
workspaceId="ws-1"
onRowRepositoryChange={NOOP}
onRowBranchChange={NOOP}
/>,
);
fireEvent.click(screen.getByTestId("branch-chip-trigger"));
expect(screen.getByText("main")).toBeTruthy();
expect(screen.getByText("origin/main")).toBeTruthy();
// Reset for sibling tests.
mockBranches.value = { branches: [], isLoading: false };
});
});