fd79d6170f
* 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>
330 lines
13 KiB
TypeScript
330 lines
13 KiB
TypeScript
"use client";
|
|
|
|
import { useMemo } from "react";
|
|
import { useAppStore } from "@/components/state-provider";
|
|
import { useSessionGit } from "@/hooks/domains/session/use-session-git";
|
|
import { useSessionFileReviews } from "@/hooks/use-session-file-reviews";
|
|
import { useEnvironmentSessionId } from "@/hooks/use-environment-session-id";
|
|
import { useToast } from "@/components/toast-provider";
|
|
import { useVcsDialogs } from "@/components/vcs/vcs-dialogs";
|
|
import type { PRChangedFile } from "./changes-panel-timeline";
|
|
import type { PRDiffFile } from "@/lib/types/github";
|
|
import { useChangesGitHandlers, useChangesDialogHandlers } from "./changes-panel-hooks";
|
|
import { useRepoDisplayName } from "@/hooks/domains/session/use-repo-display-name";
|
|
import { useBaseBranchByRepo } from "@/hooks/domains/session/use-base-branch-by-repo";
|
|
import { useActiveTaskPR } from "@/hooks/domains/github/use-task-pr";
|
|
import { useActiveTaskPRsWithFiles } from "@/hooks/domains/github/use-active-task-pr-files";
|
|
import { usePRCommits } from "@/hooks/domains/github/use-pr-commits";
|
|
import {
|
|
type ChangedFile,
|
|
computePRGroupStamp,
|
|
computeReviewProgress,
|
|
computeStagedStats,
|
|
getBaseBranchDisplay,
|
|
mapPRFilesToChangedFiles,
|
|
mapToChangedFiles,
|
|
buildPrByRepoMap,
|
|
buildRepoNameById,
|
|
} from "./changes-panel-helpers";
|
|
import type { OpenDiffOptions } from "./changes-diff-target";
|
|
|
|
function useChangesPanelStoreData() {
|
|
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
|
|
const activeSessionId = useEnvironmentSessionId();
|
|
const taskTitle = useAppStore((state) => {
|
|
if (!state.tasks.activeTaskId) return undefined;
|
|
return state.kanban.tasks.find((t: { id: string }) => t.id === state.tasks.activeTaskId)?.title;
|
|
});
|
|
const baseBranch = useAppStore((state) =>
|
|
activeSessionId ? state.taskSessions.items[activeSessionId]?.base_branch : undefined,
|
|
);
|
|
const existingPrUrl = useAppStore((state) => {
|
|
const taskId = state.tasks.activeTaskId;
|
|
if (!taskId) return undefined;
|
|
// Multi-branch tasks hold N PRs per task. The panel-header "View PR"
|
|
// button is a single-URL surface, so collapse only when there's exactly
|
|
// one PR — otherwise the per-repo buttons (prByRepo) take over and the
|
|
// generic button is hidden to avoid silently linking to a sibling.
|
|
const taskPRs = state.taskPRs.byTaskId[taskId];
|
|
if (Array.isArray(taskPRs) && taskPRs.length === 1) return taskPRs[0]?.pr_url;
|
|
if (Array.isArray(taskPRs) && taskPRs.length > 1) return undefined;
|
|
return state.pendingPrUrlByTaskId.byTaskId[taskId]?.[""];
|
|
});
|
|
return { activeTaskId, activeSessionId, taskTitle, baseBranch, existingPrUrl };
|
|
}
|
|
|
|
type DialogsType = ReturnType<typeof useChangesDialogHandlers> & ReturnType<typeof useVcsDialogs>;
|
|
|
|
export type ChangesPanelBodyProps = {
|
|
hasAnything: boolean;
|
|
hasUnstaged: boolean;
|
|
hasStaged: boolean;
|
|
hasCommits: boolean;
|
|
hasPRFiles: boolean;
|
|
hasPRCommits: boolean;
|
|
canPush: boolean;
|
|
canCreatePR: boolean;
|
|
existingPrUrl: string | undefined;
|
|
unstagedFiles: ChangedFile[];
|
|
stagedFiles: ChangedFile[];
|
|
prFiles: PRChangedFile[];
|
|
prCommits: {
|
|
sha: string;
|
|
message: string;
|
|
author_login: string;
|
|
author_date: string;
|
|
additions: number;
|
|
deletions: number;
|
|
}[];
|
|
commits: {
|
|
commit_sha: string;
|
|
commit_message: string;
|
|
insertions: number;
|
|
deletions: number;
|
|
pushed?: boolean;
|
|
committed_at?: string;
|
|
}[];
|
|
pendingStageFiles: Set<string>;
|
|
reviewedCount: number;
|
|
totalFileCount: number;
|
|
aheadCount: number;
|
|
isLoading: boolean;
|
|
loadingOperation: string | null;
|
|
dialogs: DialogsType;
|
|
onOpenDiffFile: (path: string, options?: OpenDiffOptions) => void;
|
|
onEditFile: (path: string) => void;
|
|
onOpenCommitDetail?: (sha: string, repo?: string) => void;
|
|
onOpenReview?: () => void;
|
|
onRevertCommit?: (sha: string, repo?: string) => void;
|
|
onStageAll: () => void;
|
|
onUnstageAll: () => void;
|
|
onStage: (path: string, repo?: string) => Promise<void>;
|
|
onUnstage: (path: string, repo?: string) => Promise<void>;
|
|
onBulkStage: (paths: string[]) => void;
|
|
onBulkUnstage: (paths: string[]) => void;
|
|
onBulkDiscard: (paths: string[]) => void;
|
|
onPush: () => void;
|
|
onForcePush: () => void;
|
|
stagedFileCount: number;
|
|
stagedAdditions: number;
|
|
stagedDeletions: number;
|
|
onRepoStageAll?: (repo: string) => void;
|
|
onRepoUnstageAll?: (repo: string) => void;
|
|
onRepoCommit?: (repo: string) => void;
|
|
onRepoPush?: (repo: string) => void;
|
|
onRepoCreatePR?: (repo: string) => void;
|
|
repoDisplayName?: (repositoryName: string) => string | undefined;
|
|
perRepoStatus?: Array<{ repository_name: string; ahead: number }>;
|
|
prByRepo?: Record<string, string | undefined>;
|
|
};
|
|
|
|
function usePerRepoCallbacks(
|
|
git: ReturnType<typeof useSessionGit>,
|
|
vcsDialogs: ReturnType<typeof useVcsDialogs>,
|
|
gitHandlers: ReturnType<typeof useChangesGitHandlers>,
|
|
) {
|
|
return useMemo(
|
|
() => ({
|
|
onRepoStageAll: (repo: string) => {
|
|
gitHandlers.handleGitOperation(
|
|
() => git.stage(undefined, repo),
|
|
repo ? `Stage all (${repo})` : "Stage all",
|
|
);
|
|
},
|
|
onRepoUnstageAll: (repo: string) => {
|
|
gitHandlers.handleGitOperation(
|
|
() => git.unstage(undefined, repo),
|
|
repo ? `Unstage all (${repo})` : "Unstage all",
|
|
);
|
|
},
|
|
onRepoCommit: (repo: string) => vcsDialogs.openCommitDialog(repo),
|
|
onRepoPush: (repo: string) => gitHandlers.handlePush(repo),
|
|
onRepoCreatePR: (repo: string) => vcsDialogs.openPRDialog(repo),
|
|
onRepoPull: (repo: string) => gitHandlers.handlePull(repo),
|
|
onRepoRebase: (repo: string) => gitHandlers.handleRebase(repo),
|
|
onRepoMerge: (repo: string) => gitHandlers.handleMerge(repo),
|
|
}),
|
|
[git, vcsDialogs, gitHandlers],
|
|
);
|
|
}
|
|
|
|
function useChangesPanelPRData() {
|
|
const { prs, filesByPRKey } = useActiveTaskPRsWithFiles();
|
|
const reposByWorkspace = useAppStore((s) => s.repositories.itemsByWorkspaceId);
|
|
const repoNameById = useMemo(() => buildRepoNameById(reposByWorkspace), [reposByWorkspace]);
|
|
const taskHasMultipleRepos = useAppStore((s) => {
|
|
const taskId = s.tasks.activeTaskId;
|
|
if (!taskId) return false;
|
|
const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId);
|
|
return (task?.repositories?.length ?? 0) > 1;
|
|
});
|
|
const taskPR = useActiveTaskPR();
|
|
const refreshKey = taskPR?.last_synced_at ?? null;
|
|
const { commits: prCommitsList } = usePRCommits(
|
|
taskPR?.owner ?? null,
|
|
taskPR?.repo ?? null,
|
|
taskPR?.pr_number ?? null,
|
|
refreshKey,
|
|
);
|
|
const { prFiles, prDiffFiles } = useMemo(() => {
|
|
const merged: PRChangedFile[] = [];
|
|
const flat: PRDiffFile[] = [];
|
|
// Multi-branch tasks open multiple PRs on the same repo — files must
|
|
// split by PR so the agent's two branches don't get conflated under one
|
|
// "kandev" header. We stamp each row with a label unique per PR.
|
|
//
|
|
// - 1 PR total → no stamp (single section header is enough)
|
|
// - Multi-repo, 1 PR/repo → stamp = repo name (legacy behavior)
|
|
// - Multi-PR per repo → stamp = "<repo> · <head_branch>" so the
|
|
// group label still names the repo but
|
|
// disambiguates the branch the PR is on
|
|
// - Single repo + N PRs → stamp = head_branch (repo is redundant)
|
|
const prCountByRepoID = new Map<string, number>();
|
|
for (const pr of prs) {
|
|
const key = pr.repository_id ?? "";
|
|
prCountByRepoID.set(key, (prCountByRepoID.get(key) ?? 0) + 1);
|
|
}
|
|
const anyRepoMultiPR = Array.from(prCountByRepoID.values()).some((n) => n > 1);
|
|
const needsStamp = prs.length > 1;
|
|
for (const pr of prs) {
|
|
const key = `${pr.owner}/${pr.repo}/${pr.pr_number}/${pr.last_synced_at ?? ""}`;
|
|
const files = filesByPRKey[key] ?? [];
|
|
const repoName = pr.repository_id ? (repoNameById[pr.repository_id] ?? "") : "";
|
|
const branch = pr.head_branch ?? "";
|
|
const stamp = computePRGroupStamp({
|
|
needsStamp,
|
|
taskHasMultipleRepos,
|
|
anyRepoMultiPR,
|
|
repoName: repoName || `${pr.owner}/${pr.repo}`,
|
|
branch,
|
|
prNumber: pr.pr_number,
|
|
});
|
|
merged.push(...mapPRFilesToChangedFiles(files, stamp));
|
|
flat.push(...files);
|
|
}
|
|
return { prFiles: merged, prDiffFiles: flat };
|
|
}, [prs, filesByPRKey, repoNameById, taskHasMultipleRepos]);
|
|
const hasPRFiles = prFiles.length > 0;
|
|
const hasPRCommits = prCommitsList.length > 0;
|
|
return { prDiffFiles, prCommitsList, hasPRFiles, hasPRCommits, prFiles };
|
|
}
|
|
|
|
export function useChangesPanelData() {
|
|
const { activeTaskId, activeSessionId, baseBranch, existingPrUrl } = useChangesPanelStoreData();
|
|
const baseBranchByRepo = useBaseBranchByRepo(activeTaskId);
|
|
const git = useSessionGit(activeSessionId);
|
|
const { toast } = useToast();
|
|
const { reviews } = useSessionFileReviews(activeSessionId);
|
|
const prData = useChangesPanelPRData();
|
|
const vcsDialogs = useVcsDialogs();
|
|
const baseBranchDisplay = useMemo(() => getBaseBranchDisplay(baseBranch), [baseBranch]);
|
|
const unstagedFiles = useMemo(() => mapToChangedFiles(git.unstagedFiles), [git.unstagedFiles]);
|
|
const stagedFiles = useMemo(() => mapToChangedFiles(git.stagedFiles), [git.stagedFiles]);
|
|
const { reviewedCount, totalFileCount } = useMemo(
|
|
() => computeReviewProgress(git.allFiles, git.cumulativeDiff, reviews, prData.prDiffFiles),
|
|
[git.allFiles, git.cumulativeDiff, reviews, prData.prDiffFiles],
|
|
);
|
|
const staged = useMemo(() => computeStagedStats(git.stagedFiles), [git.stagedFiles]);
|
|
const gitHandlers = useChangesGitHandlers(git, toast, baseBranch);
|
|
const localDialogs = useChangesDialogHandlers(git, toast, gitHandlers.handleGitOperation);
|
|
const dialogs = { ...localDialogs, ...vcsDialogs };
|
|
const repoCallbacks = usePerRepoCallbacks(git, vcsDialogs, gitHandlers);
|
|
const repoDisplayName = useRepoDisplayName(activeSessionId);
|
|
const taskPRsForMap = useAppStore((state) =>
|
|
activeTaskId ? state.taskPRs.byTaskId[activeTaskId] : undefined,
|
|
);
|
|
const reposByWorkspace = useAppStore((s) => s.repositories.itemsByWorkspaceId);
|
|
const repoNameById = useMemo(() => buildRepoNameById(reposByWorkspace), [reposByWorkspace]);
|
|
const pendingByRepo = useAppStore((state) =>
|
|
activeTaskId ? state.pendingPrUrlByTaskId.byTaskId[activeTaskId] : undefined,
|
|
);
|
|
const prByRepo = useMemo(
|
|
() => buildPrByRepoMap(taskPRsForMap, repoNameById, pendingByRepo),
|
|
[taskPRsForMap, repoNameById, pendingByRepo],
|
|
);
|
|
return {
|
|
git,
|
|
baseBranchDisplay,
|
|
baseBranchByRepo,
|
|
unstagedFiles,
|
|
stagedFiles,
|
|
reviewedCount,
|
|
totalFileCount,
|
|
staged,
|
|
gitHandlers,
|
|
localDialogs,
|
|
dialogs,
|
|
repoCallbacks,
|
|
repoDisplayName,
|
|
prByRepo,
|
|
existingPrUrl,
|
|
...prData,
|
|
};
|
|
}
|
|
|
|
type ChangesPanelCallbacks = {
|
|
onOpenDiffFile: (path: string, options?: OpenDiffOptions) => void;
|
|
onEditFile: (path: string) => void;
|
|
onOpenCommitDetail?: (sha: string, repo?: string) => void;
|
|
onOpenReview?: () => void;
|
|
};
|
|
|
|
export function buildChangesPanelBodyProps(
|
|
data: ReturnType<typeof useChangesPanelData>,
|
|
callbacks: ChangesPanelCallbacks,
|
|
): ChangesPanelBodyProps {
|
|
const { git, gitHandlers, localDialogs, repoCallbacks, staged } = data;
|
|
return {
|
|
hasAnything: git.hasAnything || data.hasPRFiles || data.hasPRCommits,
|
|
hasUnstaged: git.hasUnstaged,
|
|
hasStaged: git.hasStaged,
|
|
hasCommits: git.hasCommits,
|
|
hasPRFiles: data.hasPRFiles,
|
|
hasPRCommits: data.hasPRCommits,
|
|
canPush: git.canPush,
|
|
canCreatePR: git.canCreatePR,
|
|
existingPrUrl: data.existingPrUrl,
|
|
unstagedFiles: data.unstagedFiles,
|
|
stagedFiles: data.stagedFiles,
|
|
prFiles: data.prFiles,
|
|
prCommits: data.prCommitsList,
|
|
commits: git.commits,
|
|
pendingStageFiles: git.pendingStageFiles,
|
|
reviewedCount: data.reviewedCount,
|
|
totalFileCount: data.totalFileCount,
|
|
aheadCount: git.ahead,
|
|
isLoading: git.isLoading,
|
|
loadingOperation: git.loadingOperation,
|
|
dialogs: data.dialogs,
|
|
onOpenDiffFile: callbacks.onOpenDiffFile,
|
|
onEditFile: callbacks.onEditFile,
|
|
onOpenCommitDetail: callbacks.onOpenCommitDetail,
|
|
onRevertCommit: gitHandlers.handleRevertCommit,
|
|
onOpenReview: callbacks.onOpenReview,
|
|
onStageAll: git.stageAll,
|
|
onUnstageAll: git.unstageAll,
|
|
onStage: (path, repo) => git.stageFile([path], repo).then(() => undefined),
|
|
onUnstage: (path, repo) => git.unstageFile([path], repo).then(() => undefined),
|
|
onBulkStage: (paths) => {
|
|
git.stageFile(paths).catch(() => undefined);
|
|
},
|
|
onBulkUnstage: (paths) => {
|
|
git.unstageFile(paths).catch(() => undefined);
|
|
},
|
|
onBulkDiscard: localDialogs.handleBulkDiscardClick,
|
|
onPush: () => gitHandlers.handlePush(),
|
|
onForcePush: () => gitHandlers.handleForcePush(),
|
|
stagedFileCount: staged.stagedFileCount,
|
|
stagedAdditions: staged.stagedAdditions,
|
|
stagedDeletions: staged.stagedDeletions,
|
|
onRepoStageAll: repoCallbacks.onRepoStageAll,
|
|
onRepoUnstageAll: repoCallbacks.onRepoUnstageAll,
|
|
onRepoCommit: repoCallbacks.onRepoCommit,
|
|
onRepoPush: repoCallbacks.onRepoPush,
|
|
onRepoCreatePR: repoCallbacks.onRepoCreatePR,
|
|
repoDisplayName: data.repoDisplayName,
|
|
perRepoStatus: git.perRepoStatus,
|
|
prByRepo: data.prByRepo,
|
|
};
|
|
}
|