feat: link GitHub issues to tasks (#1672) (#1676)

This commit is contained in:
Carlos Florêncio
2026-07-13 19:19:23 +01:00
committed by GitHub
parent 3eaa0e6702
commit 0f266c319d
33 changed files with 1141 additions and 161 deletions
@@ -13,8 +13,9 @@ import {
import { Spinner } from "@kandev/ui/spinner";
import { cn } from "@/lib/utils";
import { formatRelativeTime } from "@/lib/utils";
import type { GitHubIssue } from "@/lib/types/github";
import type { GitHubIssue, TaskIssueLink } from "@/lib/types/github";
import type { LaunchPayload, TaskPreset } from "./quick-task-launcher";
import { TaskRowIndicator } from "./task-row-indicator";
type IssueListProps = {
items: GitHubIssue[];
@@ -22,6 +23,7 @@ type IssueListProps = {
error: string | null;
presets: TaskPreset[];
onStartTask: (payload: LaunchPayload) => void;
issueKeyToTasks?: Map<string, TaskIssueLink[]>;
};
function StartTaskMenu({
@@ -85,10 +87,12 @@ function IssueRow({
issue,
presets,
onStartTask,
tasks,
}: {
issue: GitHubIssue;
presets: TaskPreset[];
onStartTask: IssueListProps["onStartTask"];
tasks: TaskIssueLink[] | undefined;
}) {
const StateIcon = issue.state === "open" ? IconCircle : IconCircleCheck;
const stateClass =
@@ -96,7 +100,11 @@ function IssueRow({
? "text-emerald-600 dark:text-emerald-400"
: "text-purple-600 dark:text-purple-400";
return (
<div className="flex items-start gap-3 px-4 py-3 hover:bg-muted/40 transition-colors">
<div
className="flex items-start gap-3 px-4 py-3 hover:bg-muted/40 transition-colors"
data-testid="issue-row"
data-issue-number={issue.number}
>
<StateIcon className={cn("h-4 w-4 mt-1 shrink-0", stateClass)} />
<div className="min-w-0 flex-1">
<Link
@@ -116,6 +124,14 @@ function IssueRow({
by {issue.author_login} · opened {formatRelativeTime(issue.created_at)}
</span>
<IssueLabels labels={issue.labels} />
<TaskRowIndicator
tasks={tasks?.map((task) => ({
id: task.task_id,
taskId: task.task_id,
fallbackTitle: task.task_title,
}))}
testIdPrefix="issue-row-task-indicator"
/>
</div>
</div>
<div className="shrink-0">
@@ -125,7 +141,14 @@ function IssueRow({
);
}
function IssueListBody({ loading, error, items, presets, onStartTask }: IssueListProps) {
function IssueListBody({
loading,
error,
items,
presets,
onStartTask,
issueKeyToTasks,
}: IssueListProps) {
if (loading) {
return (
<div className="flex justify-center py-10">
@@ -145,14 +168,18 @@ function IssueListBody({ loading, error, items, presets, onStartTask }: IssueLis
}
return (
<div className="divide-y">
{items.map((issue) => (
<IssueRow
key={`${issue.repo_owner}/${issue.repo_name}#${issue.number}`}
issue={issue}
presets={presets}
onStartTask={onStartTask}
/>
))}
{items.map((issue) => {
const key = `${issue.repo_owner}/${issue.repo_name}#${issue.number}`;
return (
<IssueRow
key={key}
issue={issue}
presets={presets}
onStartTask={onStartTask}
tasks={issueKeyToTasks?.get(key)}
/>
);
})}
</div>
);
}
@@ -81,11 +81,11 @@ describe("PRRowTaskIndicator", () => {
expect(container.textContent).toContain("2");
});
it("truncates long task titles (>40 chars)", () => {
it("keeps long task titles in the DOM while visually truncating them", () => {
const longTitle = "This is an extremely long pull request title that should be truncated";
renderWithStore(<PRRowTaskIndicator tasks={[makeTaskPR({ pr_title: longTitle })]} />);
const btn = screen.getByRole("button");
expect(btn.textContent).toContain("…");
expect(btn.textContent!.length).toBeLessThan(longTitle.length + 5);
expect(btn.textContent).toContain(longTitle);
expect(screen.getByText(longTitle).classList.contains("truncate")).toBe(true);
});
});
@@ -1,144 +1,22 @@
"use client";
import { useCallback } from "react";
import { useRouter } from "@/lib/routing/client-router";
import { IconChecklist } from "@tabler/icons-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@kandev/ui/dropdown-menu";
import { Badge } from "@kandev/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useAppStore } from "@/components/state-provider";
import { cn } from "@/lib/utils";
import { linkToTask } from "@/lib/links";
import { useTaskById } from "@/hooks/domains/kanban/use-task-by-id";
import type { KanbanState } from "@/lib/state/slices";
import type { TaskPR } from "@/lib/types/github";
import { TaskRowIndicator } from "./task-row-indicator";
type PRRowTaskIndicatorProps = {
tasks: TaskPR[] | undefined;
};
function useTaskStepTitle(workflowStepId: string | undefined): string | null {
return useAppStore((state) => {
if (!workflowStepId) return null;
const findIn = (steps: KanbanState["steps"]) =>
steps.find((s) => s.id === workflowStepId)?.title ?? null;
const fromActive = findIn(state.kanban.steps);
if (fromActive) return fromActive;
for (const snap of Object.values(state.kanbanMulti.snapshots)) {
const t = findIn(snap.steps);
if (t) return t;
}
return null;
});
}
function truncateTitle(title: string): string {
return title.length > 40 ? title.slice(0, 40) + "…" : title;
}
function TaskTitle({ taskId, fallback }: { taskId: string; fallback: string }) {
const taskData = useTaskById(taskId);
const title = taskData?.title ?? fallback;
return <span className="truncate text-foreground/80">{truncateTitle(title)}</span>;
}
function SingleTaskButton({
task,
onNavigate,
}: {
task: TaskPR;
onNavigate: (taskId: string) => void;
}) {
const taskData = useTaskById(task.task_id);
const stepTitle = useTaskStepTitle(taskData?.workflowStepId);
const title = taskData?.title ?? task.pr_title;
return (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
data-testid="pr-row-task-indicator-single"
onClick={() => onNavigate(task.task_id)}
className={buttonClass}
>
<IconChecklist className={iconClass} />
<span className="truncate text-foreground/80">{truncateTitle(title)}</span>
</button>
</TooltipTrigger>
<TooltipContent>
<div className="flex flex-col gap-0.5 text-xs">
<span>Task: {title}</span>
{stepTitle ? <span className="text-muted-foreground">Step: {stepTitle}</span> : null}
</div>
</TooltipContent>
</Tooltip>
);
}
const buttonClass = cn(
"inline-flex items-center gap-1.5 rounded px-1.5 py-0.5 text-xs",
"hover:bg-muted/70 transition-colors cursor-pointer w-fit max-w-full",
);
const iconClass = "h-3 w-3 shrink-0 text-muted-foreground";
export function PRRowTaskIndicator({ tasks }: PRRowTaskIndicatorProps) {
const setActiveTask = useAppStore((state) => state.setActiveTask);
const router = useRouter();
const navigate = useCallback(
(taskId: string) => {
setActiveTask(taskId);
router.push(linkToTask(taskId));
},
[setActiveTask, router],
);
if (!tasks || tasks.length === 0) {
return (
<span
data-testid="pr-row-task-indicator-empty"
className="inline-flex items-center gap-1 text-xs text-muted-foreground"
>
No task created yet
</span>
);
}
if (tasks.length === 1) {
return <SingleTaskButton task={tasks[0]} onNavigate={navigate} />;
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button type="button" data-testid="pr-row-task-indicator-multi" className={buttonClass}>
<IconChecklist className={iconClass} />
<span className="text-foreground/80">Tasks</span>
<Badge variant="outline" className="h-4 px-1 py-0 text-[10px] shrink-0">
{tasks.length}
</Badge>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
{tasks.map((t) => (
// Use the TaskPR row id rather than task_id — multi-repo tasks can
// produce more than one TaskPR row for the same PR, which would
// collide on task_id.
<DropdownMenuItem
key={t.id}
className="cursor-pointer"
onSelect={() => navigate(t.task_id)}
>
<TaskTitle taskId={t.task_id} fallback={t.pr_title} />
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<TaskRowIndicator
tasks={tasks?.map((task) => ({
id: task.id,
taskId: task.task_id,
fallbackTitle: task.pr_title,
}))}
testIdPrefix="pr-row-task-indicator"
emptyLabel="No task created yet"
/>
);
}
@@ -1,4 +1,4 @@
import { render } from "@testing-library/react";
import { render, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Icon } from "@tabler/icons-react";
import type { GitHubIssue, GitHubPR } from "@/lib/types/github";
@@ -6,6 +6,7 @@ import {
repositoryId,
workspaceId,
type Repository,
type Task,
type Workflow,
type WorkflowStep,
} from "@/lib/types/http";
@@ -19,11 +20,16 @@ const TASK_WORKTREE_ROOT = "/root/.kandev/tasks";
const TASK_WORKTREE_PATH = "/root/.kandev/tasks/pr-1541-fix-skip-cle_3bm/kdlbs-kandev";
const REPO_URL = "https://github.com/kdlbs/kandev/pull/1567";
const ISSUE_URL = "https://github.com/kdlbs/kandev/issues/1567";
const LOCAL_REPO_ID = "local-repo";
const mocks = vi.hoisted(() => ({
dialogProps: undefined as { initialValues?: Record<string, unknown> } | undefined,
dialogProps: undefined as
| { initialValues?: Record<string, unknown>; onSuccess?: (task: Task) => void }
| undefined,
push: vi.fn(),
createTaskPR: vi.fn(),
linkTaskIssue: vi.fn(),
upsertTaskIssue: vi.fn(),
}));
vi.mock("@/components/task-create-dialog", () => ({
@@ -37,8 +43,13 @@ vi.mock("@/lib/routing/client-router", () => ({
useRouter: () => ({ push: mocks.push }),
}));
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: typeof mocks) => unknown) => selector(mocks),
}));
vi.mock("@/lib/api/domains/github-api", () => ({
createTaskPR: mocks.createTaskPR,
linkTaskIssue: mocks.linkTaskIssue,
}));
const preset: TaskPreset = {
@@ -176,6 +187,8 @@ afterEach(() => {
mocks.dialogProps = undefined;
mocks.push.mockClear();
mocks.createTaskPR.mockClear();
mocks.linkTaskIssue.mockClear();
mocks.upsertTaskIssue.mockClear();
});
describe("QuickTaskLauncher repository defaults", () => {
@@ -216,11 +229,11 @@ describe("QuickTaskLauncher repository defaults", () => {
it("still preselects an ordinary matching local GitHub repo for issues", () => {
const initialValues = renderIssueLauncher([
repo({ id: "local-repo", local_path: "/work/kandev" }),
repo({ id: LOCAL_REPO_ID, local_path: "/work/kandev" }),
]);
expect(initialValues).toMatchObject({
repositoryId: "local-repo",
repositoryId: LOCAL_REPO_ID,
});
expect(initialValues?.githubUrl).toBeUndefined();
});
@@ -252,3 +265,38 @@ describe("QuickTaskLauncher repository defaults", () => {
expect(initialValues?.repositoryId).toBeUndefined();
});
});
describe("QuickTaskLauncher issue linking", () => {
it("links and immediately stores a newly created task for the launched issue", async () => {
const link = {
task_id: "task-1",
task_title: "Review: add Download option",
owner: "kdlbs",
repo: "kandev",
issue_number: 1567,
issue_url: ISSUE_URL,
issue_title: "add Download option",
};
mocks.linkTaskIssue.mockResolvedValue(link);
renderIssueLauncher([repo({ id: LOCAL_REPO_ID })]);
mocks.dialogProps?.onSuccess?.({ id: "task-1" } as Task);
expect(mocks.linkTaskIssue).toHaveBeenCalledWith("task-1", { issue: ISSUE_URL });
await waitFor(() => {
expect(mocks.upsertTaskIssue).toHaveBeenCalledWith(WORKSPACE_ID, link);
});
expect(mocks.push).toHaveBeenCalledWith("/tasks/task-1");
});
it("navigates when issue linking fails", async () => {
mocks.linkTaskIssue.mockRejectedValueOnce(new Error("offline"));
renderIssueLauncher([repo({ id: LOCAL_REPO_ID })]);
mocks.dialogProps?.onSuccess?.({ id: "task-1" } as Task);
expect(mocks.push).toHaveBeenCalledWith("/tasks/task-1");
await waitFor(() => expect(mocks.linkTaskIssue).toHaveBeenCalledTimes(1));
expect(mocks.upsertTaskIssue).not.toHaveBeenCalled();
});
});
@@ -4,7 +4,8 @@ import { useMemo } from "react";
import { useRouter } from "@/lib/routing/client-router";
import type { Icon } from "@tabler/icons-react";
import { TaskCreateDialog } from "@/components/task-create-dialog";
import { createTaskPR } from "@/lib/api/domains/github-api";
import { useAppStore } from "@/components/state-provider";
import { createTaskPR, linkTaskIssue } from "@/lib/api/domains/github-api";
import type { Repository, Task, TaskRepository, Workflow, WorkflowStep } from "@/lib/types/http";
import type { GitHubPR, GitHubIssue } from "@/lib/types/github";
@@ -180,6 +181,7 @@ export function QuickTaskLauncher({
onClose,
}: QuickTaskLauncherProps) {
const router = useRouter();
const upsertTaskIssue = useAppStore((state) => state.upsertTaskIssue);
const defaultWorkflow = workflows[0];
const sortedStepsForWorkflow = useMemo(
@@ -222,6 +224,15 @@ export function QuickTaskLauncher({
// (legacy behavior) if branch matching succeeds.
});
}
if (payload?.kind === "issue") {
void linkTaskIssue(task.id, { issue: payload.issue.html_url })
.then((issue) => {
if (workspaceId) upsertTaskIssue(workspaceId, issue);
})
.catch(() => {
// Task creation succeeded; keep navigation available if GitHub linking fails.
});
}
onClose();
router.push(`/tasks/${task.id}`);
};
@@ -0,0 +1,146 @@
"use client";
import { useCallback } from "react";
import { useRouter } from "@/lib/routing/client-router";
import { IconChecklist } from "@tabler/icons-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@kandev/ui/dropdown-menu";
import { Badge } from "@kandev/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useAppStore } from "@/components/state-provider";
import { cn } from "@/lib/utils";
import { linkToTask } from "@/lib/links";
import { useTaskById } from "@/hooks/domains/kanban/use-task-by-id";
import type { KanbanState } from "@/lib/state/slices";
export type TaskRowLink = {
id: string;
taskId: string;
fallbackTitle: string;
};
type TaskRowIndicatorProps = {
tasks: TaskRowLink[] | undefined;
testIdPrefix: string;
emptyLabel?: string;
};
function useTaskStepTitle(workflowStepId: string | undefined): string | null {
return useAppStore((state) => {
if (!workflowStepId) return null;
const findIn = (steps: KanbanState["steps"]) =>
steps.find((step) => step.id === workflowStepId)?.title ?? null;
const activeTitle = findIn(state.kanban.steps);
if (activeTitle) return activeTitle;
for (const snapshot of Object.values(state.kanbanMulti.snapshots)) {
const title = findIn(snapshot.steps);
if (title) return title;
}
return null;
});
}
function TaskTitle({ task }: { task: TaskRowLink }) {
const taskData = useTaskById(task.taskId);
const title = taskData?.title ?? task.fallbackTitle;
return (
<span className="truncate text-foreground/80" title={title}>
{title}
</span>
);
}
const buttonClass = cn(
"inline-flex items-center gap-1.5 rounded px-1.5 py-0.5 text-xs",
"hover:bg-muted/70 transition-colors cursor-pointer w-fit max-w-full",
);
const iconClass = "h-3 w-3 shrink-0 text-muted-foreground";
function SingleTaskButton({
task,
testIdPrefix,
onNavigate,
}: {
task: TaskRowLink;
testIdPrefix: string;
onNavigate: (taskId: string) => void;
}) {
const taskData = useTaskById(task.taskId);
const stepTitle = useTaskStepTitle(taskData?.workflowStepId);
const title = taskData?.title ?? task.fallbackTitle;
return (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
data-testid={`${testIdPrefix}-single`}
onClick={() => onNavigate(task.taskId)}
className={buttonClass}
>
<IconChecklist className={iconClass} />
<span className="truncate text-foreground/80">{title}</span>
</button>
</TooltipTrigger>
<TooltipContent>
<div className="flex flex-col gap-0.5 text-xs">
<span>Task: {title}</span>
{stepTitle ? <span className="text-muted-foreground">Step: {stepTitle}</span> : null}
</div>
</TooltipContent>
</Tooltip>
);
}
export function TaskRowIndicator({ tasks, testIdPrefix, emptyLabel }: TaskRowIndicatorProps) {
const setActiveTask = useAppStore((state) => state.setActiveTask);
const router = useRouter();
const navigate = useCallback(
(taskId: string) => {
setActiveTask(taskId);
router.push(linkToTask(taskId));
},
[router, setActiveTask],
);
if (!tasks || tasks.length === 0) {
return emptyLabel ? (
<span
data-testid={`${testIdPrefix}-empty`}
className="inline-flex items-center gap-1 text-xs text-muted-foreground"
>
{emptyLabel}
</span>
) : null;
}
if (tasks.length === 1) {
return <SingleTaskButton task={tasks[0]} testIdPrefix={testIdPrefix} onNavigate={navigate} />;
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button type="button" data-testid={`${testIdPrefix}-multi`} className={buttonClass}>
<IconChecklist className={iconClass} />
<span className="text-foreground/80">Tasks</span>
<Badge variant="outline" className="h-4 px-1 py-0 text-[10px] shrink-0">
{tasks.length}
</Badge>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
{tasks.map((task) => (
<DropdownMenuItem
key={task.id}
className="cursor-pointer"
onSelect={() => navigate(task.taskId)}
>
<TaskTitle task={task} />
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}