Files
kandev/apps/web/components/task/changes-panel-timeline.tsx
T
Kandev Agent 9e8079de69 feat(multi-repo): per-repo git ops, unified branch endpoint, chip-style task create
Bundles a string of multi-repo fixes and refactors that came up while
testing the feature end-to-end:

- workspace_path stored on multi-repo TaskEnvironment was one level too
  high, so agentctl booted with the wrong WorkDir on cold start; fixed
  in resolveTaskEnvWorkspacePath + GetWorkspaceInfoForSession.
- Stage/Unstage/Discard/Commit/Revert/Reset/Amend now thread `repo`
  through agentctl client → WS handler → frontend hook → SessionGit
  fan-out, so the right git repo is targeted (was running at the task
  root, which isn't a git repo for multi-repo tasks).
- agentctl GitLog is multi-repo aware: when no `repo` is specified and
  per-repo trackers exist, fans out one log per repo and merges sorted
  newest-first with RepositoryName stamped on each commit.
- Per-repo grouping for files (Changes panel) and commits, with
  collapsible group headers; commits section defaults to collapsed.
  Algorithm extracted into one generic groupByRepositoryName helper
  (was copy-pasted three times).
- Task creation dialog rewritten around a unified `fs.repositories[]`
  list — no more "primary vs extras" split. Chip-style row with one
  pill per repo + branch, "+" to add, x to remove, GitHub URL toggle
  inline. Discovered (on-machine) repos appear in any chip's dropdown.
  Removes ~6 fields and 3 helpers from the dialog state.
- Branch listing endpoints collapsed to one:
  GET /workspaces/:id/branches?repository_id=X | path=Y
  Frontend collapses to a single useBranches hook with a tagged-union
  source. Drops two HTTP routes, two service methods, two API client
  funcs, and one whole hook file.

Tests added across the chain: workspace_path resolver, sort-commits-
by-date, manager poll-mode propagation, RepoSubpaths, chip grouping
+ collapse + per-repo isLatest, group-by-repo helper, dialog payload
builder + chip wiring + discovered-repo flow.
2026-04-26 21:23:48 +01:00

679 lines
22 KiB
TypeScript

"use client";
import { useState, useMemo, useCallback } from "react";
import {
IconGitPullRequest,
IconCloudUpload,
IconChevronDown,
IconChevronRight,
IconLoader2,
} from "@tabler/icons-react";
import { useMultiSelect } from "@/hooks/use-multi-select";
import { Button } from "@kandev/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@kandev/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import type { FileInfo } from "@/lib/state/store";
import { LineStat } from "@/components/diff-stat";
import { FileStatusIcon } from "./file-status-icon";
import { FileRow, BulkActionBar, DefaultActionButtons } from "./changes-panel-file-row";
import { CommitRow, type CommitItem } from "./commit-row";
import { groupByRepositoryName } from "@/lib/group-by-repo";
// --- Timeline visual components ---
type ChangedFile = {
path: string;
status: FileInfo["status"];
staged: boolean;
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
/** Repository this file belongs to in multi-repo workspaces; empty for single-repo. */
repositoryName?: string;
};
// Per-repo grouping is shared with the Review dialog — see @/lib/group-by-repo.
// --- Timeline section dot colors ---
const DOT_COLORS = {
unstaged: "bg-yellow-500",
staged: "bg-emerald-500",
commits: "bg-blue-500",
pr: "bg-purple-500",
action: "bg-muted-foreground/25",
} as const;
function TimelineDot({ color }: { color: string }) {
return <div className={cn("relative z-10 size-1.5 rounded-full shrink-0 mt-[5px]", color)} />;
}
function TimelineSection({
dotColor,
label,
count,
action,
isLast,
children,
collapsible = true,
defaultCollapsed = false,
"data-testid": testId,
}: {
dotColor: string;
label?: string;
count?: number;
action?: React.ReactNode;
isLast?: boolean;
children?: React.ReactNode;
collapsible?: boolean;
defaultCollapsed?: boolean;
"data-testid"?: string;
}) {
const [collapsed, setCollapsed] = useState(defaultCollapsed);
const canCollapse = collapsible && !!label;
return (
<div className="relative flex gap-2.5" data-testid={testId}>
{/* Vertical line + dot */}
<div className="flex flex-col items-center">
<TimelineDot color={dotColor} />
{!isLast && <div className="w-px flex-1 bg-border/60" />}
</div>
{/* Content */}
<div className="flex-1 min-w-0 pb-3">
{/* Header */}
{label && (
<div className="flex items-center justify-between gap-2 -mt-0.5 mb-1">
{canCollapse ? (
<button
type="button"
className="flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-foreground/70 cursor-pointer hover:text-foreground/90"
onClick={() => setCollapsed((c) => !c)}
aria-expanded={!collapsed}
data-testid={`${testId ?? label.toLowerCase()}-collapse-toggle`}
>
{label}
{typeof count === "number" && (
<span className="text-muted-foreground/50 font-normal">({count})</span>
)}
{collapsed ? (
<IconChevronRight className="h-3 w-3 text-muted-foreground/50" />
) : (
<IconChevronDown className="h-3 w-3 text-muted-foreground/50" />
)}
</button>
) : (
<span className="text-[11px] font-medium uppercase tracking-wider text-foreground/70">
{label}
{typeof count === "number" && (
<span className="ml-1 text-muted-foreground/50 font-normal">({count})</span>
)}
</span>
)}
{action}
</div>
)}
{/* Children (file list, buttons, etc.) */}
{!collapsed && children}
</div>
</div>
);
}
// --- Commits section ---
type CommitsSectionProps = {
commits: CommitItem[];
isLast: boolean;
onOpenCommitDetail?: (sha: string) => void;
// Multi-repo: handlers receive the commit's repository_name so amend/revert/
// reset land in the right git repo. Without it the op runs at the workspace
// root, which fails ("can only revert latest commit") for multi-repo tasks.
onRevertCommit?: (sha: string, repo?: string) => void;
onAmendCommit?: (currentMessage: string, repo?: string) => void;
onResetToCommit?: (sha: string, repo?: string) => void;
};
// Commits grouping shares the helper above with files — see @/lib/group-by-repo.
export function CommitsSection({
commits,
isLast,
onOpenCommitDetail,
onRevertCommit,
onAmendCommit,
onResetToCommit,
}: CommitsSectionProps) {
const groups = groupByRepositoryName(commits, (c) => c.repository_name);
const showRepoHeaders = groups.length > 1 || (groups[0]?.repositoryName ?? "") !== "";
return (
<TimelineSection
dotColor={DOT_COLORS.commits}
label="Commits"
count={commits.length}
isLast={isLast}
// User preference: commits panel starts collapsed — the file changes are
// the primary signal; commit history is reference info you expand on demand.
defaultCollapsed
data-testid="commits-section"
>
<ul data-testid="commits-list" className="space-y-0.5">
{showRepoHeaders
? groups.map((g) => (
<CommitsRepoGroup
key={g.repositoryName || "__no_repo__"}
repositoryName={g.repositoryName}
groupCommits={g.items}
onOpenCommitDetail={onOpenCommitDetail}
onAmendCommit={onAmendCommit}
onRevertCommit={onRevertCommit}
onResetToCommit={onResetToCommit}
/>
))
: commits.map((commit, index) => (
<CommitRow
key={`${commit.commit_sha}-${index}`}
commit={commit}
// Single-repo: only the newest unpushed commit is "latest"
// (revert/amend are gated on this in CommitRow).
isLatest={index === commits.findIndex((c) => c.pushed !== true)}
onOpenCommitDetail={onOpenCommitDetail}
onAmendCommit={commit.pushed ? undefined : onAmendCommit}
onRevertCommit={commit.pushed ? undefined : onRevertCommit}
onResetToCommit={commit.pushed ? undefined : onResetToCommit}
/>
))}
</ul>
</TimelineSection>
);
}
function CommitsRepoGroup({
repositoryName,
groupCommits,
onOpenCommitDetail,
onAmendCommit,
onRevertCommit,
onResetToCommit,
}: {
repositoryName: string;
groupCommits: CommitItem[];
onOpenCommitDetail?: (sha: string) => void;
onAmendCommit?: (currentMessage: string, repo?: string) => void;
onRevertCommit?: (sha: string, repo?: string) => void;
onResetToCommit?: (sha: string, repo?: string) => void;
}) {
const [collapsed, setCollapsed] = useState(false);
// Each repo has its own "latest unpushed commit" — revert/amend in this
// group must target THIS repo's newest, not the merged-list newest. Using
// the global firstUnpushedIndex would mark only one commit across all repos
// as latest and trigger "can only revert latest commit" everywhere else.
const firstUnpushedInGroup = groupCommits.findIndex((c) => c.pushed !== true);
return (
<li
data-testid="commits-repo-group"
data-repository-name={repositoryName || ""}
>
<button
type="button"
className="w-full flex items-center gap-1.5 px-1 py-0.5 text-[11px] font-medium text-muted-foreground/80 uppercase tracking-wide cursor-pointer hover:text-foreground/80"
data-testid="commits-repo-header"
aria-expanded={!collapsed}
onClick={() => setCollapsed((c) => !c)}
>
{collapsed ? (
<IconChevronRight className="h-3 w-3 text-muted-foreground/50 shrink-0" />
) : (
<IconChevronDown className="h-3 w-3 text-muted-foreground/50 shrink-0" />
)}
<span className="truncate">{repositoryName || "Other"}</span>
<span className="text-muted-foreground/50 normal-case tracking-normal">
{groupCommits.length}
</span>
</button>
{!collapsed && (
<ul className="space-y-0.5">
{groupCommits.map((commit, index) => (
<CommitRow
key={commit.commit_sha}
commit={commit}
isLatest={index === firstUnpushedInGroup}
onOpenCommitDetail={onOpenCommitDetail}
onAmendCommit={commit.pushed ? undefined : onAmendCommit}
onRevertCommit={commit.pushed ? undefined : onRevertCommit}
onResetToCommit={commit.pushed ? undefined : onResetToCommit}
/>
))}
</ul>
)}
</li>
);
}
// --- Action buttons section (Create PR / Push) ---
type ActionButtonsSectionProps = {
onOpenPRDialog: () => void;
onPush: () => void;
onForcePush: () => void;
isLoading: boolean;
loadingOperation: string | null;
aheadCount: number;
canPush: boolean;
canCreatePR: boolean;
existingPrUrl?: string;
isLast?: boolean;
};
export function ActionButtonsSection({
onOpenPRDialog,
onPush,
onForcePush,
isLoading,
loadingOperation,
aheadCount,
canPush,
canCreatePR,
existingPrUrl,
isLast = true,
}: ActionButtonsSectionProps) {
const prExists = !!existingPrUrl;
const createPrDisabled = !canCreatePR || prExists || isLoading;
const pushDisabled = !canPush || isLoading;
const isPushing = loadingOperation === "push";
const isCreatingPR = loadingOperation === "create_pr";
let pushTooltip: string | null = null;
if (isLoading) pushTooltip = "A git operation is in progress";
else if (!canPush) pushTooltip = "No commits ahead of remote";
return (
<TimelineSection dotColor={DOT_COLORS.action} isLast={isLast}>
<div className="flex items-center gap-2 -mt-0.5">
<Tooltip>
<TooltipTrigger asChild>
<span>
<Button
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer"
onClick={onOpenPRDialog}
disabled={createPrDisabled}
>
{isCreatingPR ? (
<IconLoader2 className="h-3 w-3 animate-spin" />
) : (
<IconGitPullRequest className="h-3 w-3" />
)}
Create PR
</Button>
</span>
</TooltipTrigger>
{prExists && <TooltipContent>A pull request already exists for this task</TooltipContent>}
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<span className="flex items-center">
<Button
size="sm"
variant="outline"
className="h-6 text-[11px] px-2.5 gap-1 cursor-pointer rounded-r-none border-r-0"
onClick={onPush}
disabled={pushDisabled}
>
{isPushing ? (
<IconLoader2 className="h-3 w-3 animate-spin" />
) : (
<IconCloudUpload className="h-3 w-3" />
)}
Push
{aheadCount > 0 && !isPushing && (
<span className="text-muted-foreground">{aheadCount} ahead</span>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="sm"
variant="outline"
className="h-6 w-5 px-0 cursor-pointer rounded-l-none"
disabled={pushDisabled}
>
<IconChevronDown className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem className="cursor-pointer gap-2 text-xs" onClick={onForcePush}>
<IconCloudUpload className="h-3.5 w-3.5 shrink-0" />
Force Push (with lease)
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</span>
</TooltipTrigger>
{pushTooltip && <TooltipContent>{pushTooltip}</TooltipContent>}
</Tooltip>
</div>
</TimelineSection>
);
}
// --- File list sections (Unstaged / Staged) ---
type FileListSectionProps = {
variant: "unstaged" | "staged";
files: ChangedFile[];
pendingStageFiles: Set<string>;
isLast: boolean;
actionLabel: string;
isActionLoading?: boolean;
onAction: () => void;
secondaryActionLabel?: string;
isSecondaryActionLoading?: boolean;
onSecondaryAction?: () => void;
onOpenDiff: (path: string) => void;
onEditFile: (path: string) => void;
// Multi-repo: handlers receive the file's repositoryName so each per-file op
// hits the right git repo. Same-named files across repos collide by path.
onStage: (path: string, repo?: string) => void;
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string) => void;
onBulkStage?: (paths: string[]) => void;
onBulkUnstage?: (paths: string[]) => void;
onBulkDiscard?: (paths: string[]) => void;
};
/**
* Renders the body of a file-list section. For multi-repo workspaces it
* groups files by repository under per-repo subheaders; single-repo
* workspaces fall back to a flat list (no header) so the existing UI is
* unchanged.
*/
function FileListBody(props: {
variant: "unstaged" | "staged";
files: ChangedFile[];
pendingStageFiles: Set<string>;
multiSelect: ReturnType<typeof useMultiSelect>;
onKeyDown: (e: React.KeyboardEvent) => void;
onOpenDiff: (path: string) => void;
onEditFile: (path: string) => void;
onStage: (path: string, repo?: string) => void;
onUnstage: (path: string, repo?: string) => void;
onDiscard: (path: string, repo?: string) => void;
}) {
const { variant, files, pendingStageFiles, multiSelect } = props;
const groups = useMemo(
() => groupByRepositoryName(files, (f) => f.repositoryName),
[files],
);
const showRepoHeaders = groups.length > 1 || (groups[0]?.repositoryName ?? "") !== "";
// Per-repo collapsed state: keyed by repositoryName. Default expanded;
// setting an entry to true collapses that group. Persists across re-renders
// for the lifetime of this section instance (resets on unmount).
const [collapsedRepos, setCollapsedRepos] = useState<Set<string>>(() => new Set());
const toggleRepo = useCallback((name: string) => {
setCollapsedRepos((prev) => {
const next = new Set(prev);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
}, []);
const renderRow = (file: ChangedFile) => (
<FileRow
key={`${file.repositoryName ?? ""}:${file.path}`}
file={file}
isPending={pendingStageFiles.has(file.path)}
isSelected={multiSelect.isSelected(file.path)}
onSelect={multiSelect.handleClick}
onOpenDiff={props.onOpenDiff}
onStage={props.onStage}
onUnstage={props.onUnstage}
onDiscard={props.onDiscard}
onEditFile={props.onEditFile}
/>
);
return (
<div>
<ul
data-testid={`${variant}-file-list`}
className="space-y-0.5"
tabIndex={-1}
onKeyDown={props.onKeyDown}
>
{groups.map((group) =>
showRepoHeaders ? (
<li
key={group.repositoryName || "__no_repo__"}
data-testid="changes-repo-group"
data-repository-name={group.repositoryName || ""}
>
<button
type="button"
className="w-full flex items-center gap-1.5 px-1 py-0.5 text-[11px] font-medium text-muted-foreground/80 uppercase tracking-wide cursor-pointer hover:text-foreground/80"
data-testid="changes-repo-header"
aria-expanded={!collapsedRepos.has(group.repositoryName)}
onClick={() => toggleRepo(group.repositoryName)}
>
{collapsedRepos.has(group.repositoryName) ? (
<IconChevronRight className="h-3 w-3 text-muted-foreground/50 shrink-0" />
) : (
<IconChevronDown className="h-3 w-3 text-muted-foreground/50 shrink-0" />
)}
<span className="truncate">{group.repositoryName || "Other"}</span>
<span className="text-muted-foreground/50 normal-case tracking-normal">
{group.items.length}
</span>
</button>
{!collapsedRepos.has(group.repositoryName) && (
<ul className="space-y-0.5">{group.items.map(renderRow)}</ul>
)}
</li>
) : (
// Single-repo flat list: render rows inline so the DOM shape stays
// identical to the pre-multi-repo behavior.
group.items.map(renderRow)
),
)}
</ul>
</div>
);
}
export function FileListSection(props: FileListSectionProps) {
const {
variant,
files,
pendingStageFiles,
isLast,
onOpenDiff,
onEditFile,
onStage,
onUnstage,
onDiscard,
} = props;
const dotColor = variant === "unstaged" ? DOT_COLORS.unstaged : DOT_COLORS.staged;
const label = variant === "unstaged" ? "Unstaged" : "Staged";
const filePaths = useMemo(() => files.map((f) => f.path), [files]);
const multiSelect = useMultiSelect({ items: filePaths });
const hasSelection = multiSelect.selectedPaths.size > 0;
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === "Escape" && hasSelection) multiSelect.clearSelection();
},
[hasSelection, multiSelect],
);
return (
<TimelineSection
dotColor={dotColor}
label={label}
count={files.length}
isLast={isLast}
data-testid={`${variant}-files-section`}
>
{files.length > 0 && (
<FileListBody
variant={variant}
files={files}
pendingStageFiles={pendingStageFiles}
multiSelect={multiSelect}
onKeyDown={handleKeyDown}
onOpenDiff={onOpenDiff}
onStage={onStage}
onUnstage={onUnstage}
onDiscard={onDiscard}
onEditFile={onEditFile}
/>
)}
{files.length > 0 && (
<div className="mt-1.5 flex items-center gap-1.5">
{hasSelection ? (
<BulkActionBar
variant={variant}
selectionCount={multiSelect.selectedPaths.size}
selectedPaths={multiSelect.selectedPaths}
onBulkStage={props.onBulkStage}
onBulkUnstage={props.onBulkUnstage}
onBulkDiscard={props.onBulkDiscard}
/>
) : (
<DefaultActionButtons
actionLabel={props.actionLabel}
isActionLoading={props.isActionLoading}
onAction={props.onAction}
secondaryActionLabel={props.secondaryActionLabel}
isSecondaryActionLoading={props.isSecondaryActionLoading}
onSecondaryAction={props.onSecondaryAction}
/>
)}
</div>
)}
</TimelineSection>
);
}
// --- PR files section (read-only, from GitHub PR diff) ---
export type PRChangedFile = {
path: string;
status: FileInfo["status"];
plus: number | undefined;
minus: number | undefined;
oldPath: string | undefined;
};
type PRFilesSectionProps = {
files: PRChangedFile[];
isLast: boolean;
onOpenDiff: (path: string) => void;
};
export function PRFilesSection({ files, isLast, onOpenDiff }: PRFilesSectionProps) {
return (
<TimelineSection
dotColor={DOT_COLORS.pr}
label="PR Changes"
count={files.length}
isLast={isLast}
data-testid="pr-changes-section"
>
{files.length > 0 && (
<ul className="space-y-0.5">
{files.map((file) => (
<PRFileRow key={file.path} file={file} onOpenDiff={onOpenDiff} />
))}
</ul>
)}
</TimelineSection>
);
}
function PRFileRow({
file,
onOpenDiff,
}: {
file: PRChangedFile;
onOpenDiff: (path: string) => void;
}) {
const lastSlash = file.path.lastIndexOf("/");
const folder = lastSlash === -1 ? "" : file.path.slice(0, lastSlash);
const name = lastSlash === -1 ? file.path : file.path.slice(lastSlash + 1);
return (
<li
className="group flex items-center justify-between gap-2 text-sm rounded-md px-1 py-0.5 -mx-1 hover:bg-muted/60 cursor-pointer"
onClick={() => onOpenDiff(file.path)}
>
<div className="flex items-center gap-2 min-w-0">
<div className="flex-shrink-0 flex items-center justify-center size-4">
<IconGitPullRequest className="h-3 w-3 text-purple-500" />
</div>
<button type="button" className="min-w-0 text-left cursor-pointer" title={file.path}>
<p className="flex text-foreground text-xs min-w-0">
{folder && <span className="text-foreground/60 truncate shrink">{folder}/</span>}
<span className="font-medium text-foreground whitespace-nowrap shrink-0">{name}</span>
</p>
</button>
</div>
<div className="flex items-center gap-2">
<LineStat added={file.plus} removed={file.minus} />
<FileStatusIcon status={file.status} />
</div>
</li>
);
}
// --- Review progress bar ---
type ReviewProgressBarProps = {
reviewedCount: number;
totalFileCount: number;
onOpenReview?: () => void;
};
export function ReviewProgressBar({
reviewedCount,
totalFileCount,
onOpenReview,
}: ReviewProgressBarProps) {
const progressPercent = totalFileCount > 0 ? (reviewedCount / totalFileCount) * 100 : 0;
if (totalFileCount <= 0) return null;
return (
<Tooltip>
<TooltipTrigger asChild>
<div
className="shrink-0 flex items-center gap-2 pt-2 border-t border-border/40 cursor-pointer transition-colors"
onClick={onOpenReview}
>
<div className="flex-1 h-0.5 rounded-full bg-muted-foreground/10 overflow-hidden">
<div
className="h-full bg-muted-foreground/25 rounded-full transition-all duration-300"
style={{ width: `${progressPercent}%` }}
/>
</div>
<span className="text-[10px] text-muted-foreground/40 whitespace-nowrap">
{reviewedCount}/{totalFileCount} reviewed
</span>
</div>
</TooltipTrigger>
<TooltipContent>
{reviewedCount} of {totalFileCount} files reviewed
</TooltipContent>
</Tooltip>
);
}