⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
Merge branch 'main' into feat/subtask-indentation
Juan6dff165db8b9
diff --cc apps/api/src/task-relation/index.tsindex 5357492ef,4d5e4c0ab..aa50ab18f--- a/apps/api/src/task-relation/index.ts+++ b/apps/api/src/task-relation/index.ts@@@ -124,31 -121,6 +124,31 @@@ const getTaskRelationsRoute = createRou},});+const getProjectTaskRelationsRoute = createRoute({+ method: "get",+ operationId: "getProjectTaskRelations",+ path: "/project/{projectId}",+ tags: ["Task Relations"],+ summary: "Get a project's task relations",+ description:+ "Get every relation joining two tasks in the project, without the task summaries the per-task endpoint returns. Intended for views that render many tasks at once and already hold them. Relations reaching outside the project are omitted.",+ middleware: [+ workspaceAccess.fromProject("projectId"),+ requireWorkspacePermission({ task: ["read"] }),+ ] as const,+ request: { params: projectIdParam },+ responses: {+ 200: jsonResponse(+ "Relations between tasks in the project",+ taskRelationListSchema,+ ),- 400: errorResponse(- "Unknown project, or its workspace could not be determined",++ 403: errorResponse(++ "No access to the project, or missing task:read permission",+ ),- 403: errorResponse("No workspace access, or missing task:read permission"),++ 404: errorResponse("Project not found"),+ },+});+const createTaskRelationRoute = createRoute({method: "post",operationId: "createTaskRelation",diff --cc apps/docs/openapi.jsonindex 1fd5278b6,e196867dc..553e43a3f--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@@ -20201,64 -20934,6 +20934,74 @@@}}},+ "/task-relation/project/{projectId}": {+ "get": {+ "operationId": "getProjectTaskRelations",+ "tags": [+ "Task Relations"+ ],+ "summary": "Get a project's task relations",+ "description": "Get every relation joining two tasks in the project, without the task summaries the per-task endpoint returns. Intended for views that render many tasks at once and already hold them. Relations reaching outside the project are omitted.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "projectId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Relations between tasks in the project",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/TaskRelation"+ }+ }+ }+ }+ },- "400": {- "description": "Unknown project, or its workspace could not be determined",++ "401": {++ "description": "Missing or invalid credentials",+ "content": {- "text/plain": {++ "application/json": {+ "schema": {- "type": "string"++ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },- "401": {- "description": "Missing or invalid credentials"- },+ "403": {- "description": "No workspace access, or missing task:read permission",++ "description": "No access to the project, or missing task:read permission",+ "content": {- "text/plain": {++ "application/json": {+ "schema": {- "type": "string"++ "$ref": "#/components/schemas/ApiError"++ }++ }++ }++ },++ "404": {++ "description": "Project not found",++ "content": {++ "application/json": {++ "schema": {++ "$ref": "#/components/schemas/ApiError"+ }+ }+ }++ },++ "429": {++ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },"/task-relation/{taskId}": {"get": {"operationId": "getTaskRelations",diff --cc apps/web/src/components/list-view/focus.test.tsxindex 05e7a7c02,000000000..c3cc1c454mode 100644,000000..100644--- a/apps/web/src/components/list-view/focus.test.tsx+++ b/apps/web/src/components/list-view/focus.test.tsx@@@ -1,130 -1,0 +1,143 @@@++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";++import type { ReactNode } from "react";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import type { ProjectWithTasks } from "@/types/project";+import ListView from ".";+- vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));++function Providers({ children }: { children: ReactNode }) {++ return (++ <QueryClientProvider client={new QueryClient()}>++ {children}++ </QueryClientProvider>++ );++}++++vi.mock("@tanstack/react-router", () => ({++ useNavigate: () => vi.fn(),++ useRouter: () => ({ preloadRoute: () => Promise.resolve() }),++}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/hooks/mutations/task/use-update-task", () => ({+ useUpdateTask: () => ({ mutate: vi.fn() }),+}));+vi.mock("@/hooks/use-keyboard-shortcuts", () => ({+ useRegisterShortcuts: vi.fn(),+}));+vi.mock("@/hooks/queries/task-relation/use-get-project-task-relations", () => ({+ default: () => ({+ isLoading: false,+ data: [+ {+ sourceTaskId: "parent",+ targetTaskId: "child",+ relationType: "subtask",+ },+ {+ sourceTaskId: "child",+ targetTaskId: "grandchild",+ relationType: "subtask",+ },+ ],+ }),+}));+vi.mock("../bulk-selection/bulk-toolbar", () => ({ default: () => null }));+vi.mock("../shared/modals/create-task-modal", () => ({ default: () => null }));+vi.mock("../shared/modals/archive-tasks-modal", () => ({+ ArchiveTasksModal: () => null,+}));+vi.mock("./task-row", () => ({+ default: ({+ rowId,+ childCount,+ isExpanded,+ onToggleExpanded,+ }: {+ rowId: string;+ childCount: number;+ isExpanded: boolean;- onToggleExpanded: () => void;++ onToggleExpanded: (rowId: string) => void;+ }) => (+ <div>+ {rowId}+ {childCount > 0 && (+ <button+ type="button"+ aria-label={`Toggle ${rowId}`}+ aria-expanded={isExpanded}- onClick={onToggleExpanded}++ onClick={() => onToggleExpanded(rowId)}+ >+ Toggle+ </button>+ )}+ </div>+ ),+}));++const project = {+ id: "project-focus",+ slug: "FOC",+ workspaceId: "workspace-1",+ columns: [+ {+ id: "to-do",+ name: "To Do",+ isFinal: false,+ icon: null,+ tasks: ["parent", "child", "grandchild"].map((id) => ({+ id,+ title: id,+ status: "to-do",+ })),+ },+ ],+} as ProjectWithTasks;++afterEach(() => {+ cleanup();+ localStorage.clear();+});++describe("ListView focus", () => {+ it("retains the focused toggle when expanding and collapsing parent and nested rows", () => {- render(<ListView project={project} />);++ render(<ListView project={project} />, { wrapper: Providers });++ for (const rowId of ["parent", "parent/child"]) {+ const toggle = screen.getByRole("button", { name: `Toggle ${rowId}` });+ toggle.focus();+ fireEvent.click(toggle);++ expect(toggle).toHaveFocus();+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ }++ for (const rowId of ["parent/child", "parent"]) {+ const toggle = screen.getByRole("button", { name: `Toggle ${rowId}` });+ toggle.focus();+ fireEvent.click(toggle);++ expect(toggle).toHaveFocus();+ expect(toggle).toHaveAttribute("aria-expanded", "false");+ }+ });++ it("retains header focus when collapsing and expanding a status group", () => {- render(<ListView project={project} />);++ render(<ListView project={project} />, { wrapper: Providers });+ const header = screen.getByRole("button", { name: /^To Do/ });+ header.focus();++ fireEvent.click(header);+ expect(header).toHaveFocus();+ expect(+ screen.queryByRole("button", { name: "Toggle parent" }),+ ).not.toBeInTheDocument();++ fireEvent.click(header);+ expect(header).toHaveFocus();+ expect(+ screen.getByRole("button", { name: "Toggle parent" }),+ ).toBeInTheDocument();+ });+});diff --cc apps/web/src/components/list-view/index.test.tsxindex 3d5508c4a,588efbb74..b006ac8ef--- a/apps/web/src/components/list-view/index.test.tsx+++ b/apps/web/src/components/list-view/index.test.tsx@@@ -9,9 -10,15 +11,17 @@@ importimport { afterEach, expect, it, vi } from "vite-plus/test";import type { DragEndEvent } from "@dnd-kit/core";import type { ProjectWithTasks } from "@/types/project";+import { writeExpandedRows } from "@/lib/expanded-rows-storage";+import useBulkSelectionStore from "@/store/bulk-selection";import ListView from "./index";++ const queryClient = new QueryClient();++ function Providers({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ }const m = vi.hoisted(() => ({props: {} as {sensors?: unknown[];@@@ -61,7 -61,7 +71,8 @@@ vi.mock("../shared/modals/archive-tasksafterEach(() => {cleanup();vi.clearAllMocks();+ m.relations = { data: [], isLoading: false, isError: false };+ window.localStorage.clear();});it("disables keyboard sensors and rejects drag completion on a partial board", () => {const project = {@@@ -136,79 -140,34 +151,111 @@@ it("blocks archive-all during paginatioexpect(m.setProject).toHaveBeenCalledOnce();});+// Without relations every task renders as a top-level row, which reads+// exactly like a project with no subtasks. A failure has to say so, and let+// the viewer try again.+it("says when subtasks could not be loaded, and retries on request", () => {+ m.relations = {+ data: undefined as unknown as unknown[],+ isLoading: false,+ isError: true,+ };+ const project = {+ id: "p",+ workspaceId: "w",+ columns: [{ id: "todo", slug: "todo", name: "To do", tasks: [] }],+ plannedTasks: [],+ archivedTasks: [],+ } as unknown as ProjectWithTasks;+- render(<ListView project={project} />);++ render(<ListView project={project} />, { wrapper: Providers });++ const alert = screen.getByRole("alert");+ fireEvent.click(within(alert).getByRole("button"));+ expect(m.refetchRelations).toHaveBeenCalledOnce();+});++it("shows no notice when subtasks load", () => {+ const project = {+ id: "p",+ workspaceId: "w",+ columns: [{ id: "todo", slug: "todo", name: "To do", tasks: [] }],+ plannedTasks: [],+ archivedTasks: [],+ } as unknown as ProjectWithTasks;+- render(<ListView project={project} />);++ render(<ListView project={project} />, { wrapper: Providers });++ expect(screen.queryByRole("alert")).toBeNull();+});++// j and k follow this order. Built from the top-level tasks alone, it jumped+// past an expanded parent's subtasks to the next top-level row.+it("orders keyboard navigation by the rows as shown, subtasks included", () => {+ writeExpandedRows("p", { a: true });+ m.relations = {+ data: [{ sourceTaskId: "a", targetTaskId: "c", relationType: "subtask" }],+ isLoading: false,+ isError: false,+ };+ const project = {+ id: "p",+ workspaceId: "w",+ columns: [+ {+ id: "todo",+ slug: "todo",+ name: "To do",+ tasks: [+ { id: "a", position: 0 },+ { id: "b", position: 1 },+ { id: "c", position: 2 },+ ],+ },+ ],+ plannedTasks: [],+ archivedTasks: [],+ } as unknown as ProjectWithTasks;+- render(<ListView project={project} />);++ render(<ListView project={project} />, { wrapper: Providers });++ // c follows its parent; its own top-level row is not listed a second time.+ expect(useBulkSelectionStore.getState().availableTaskIds).toEqual([+ "a",+ "c",+ "b",+ ]);+ localStorage.clear();+});+++ it("keeps collapsed lanes per project after the list view unmounts", () => {+ const makeProject = (id: string) =>+ ({+ id,+ workspaceId: "w",+ columns: [+ { id: "todo", slug: "todo", name: "To do", tasks: [] },+ { id: "done", slug: "done", name: "Done", tasks: [] },+ ],+ plannedTasks: [],+ archivedTasks: [],+ }) as unknown as ProjectWithTasks;+ const lane = (name: string) =>+ screen.getByRole("button", { name: new RegExp(`^${name}`) });++ const { unmount } = render(<ListView project={makeProject("p")} />, {+ wrapper: Providers,+ });+ fireEvent.click(lane("To do"));+ expect(lane("To do")).toHaveAttribute("aria-expanded", "false");+ // Visiting the backlog unmounts the list view.+ unmount();++ render(<ListView project={makeProject("p")} />, { wrapper: Providers });+ expect(lane("To do")).toHaveAttribute("aria-expanded", "false");+ expect(lane("Done")).toHaveAttribute("aria-expanded", "true");+ cleanup();++ render(<ListView project={makeProject("other")} />, { wrapper: Providers });+ expect(lane("To do")).toHaveAttribute("aria-expanded", "true");+ });diff --cc apps/web/src/components/list-view/index.tsxindex 92b16cb17,5f793012d..d5a5fc940--- a/apps/web/src/components/list-view/index.tsx+++ b/apps/web/src/components/list-view/index.tsx@@@ -13,22 -12,16 +12,23 @@@ importuseSensors,} from "@dnd-kit/core";import { snapCenterToCursor } from "@dnd-kit/modifiers";- import { useNavigate } from "@tanstack/react-router";import { produce } from "immer";- import { Flag } from "lucide-react";+ import { Flag, ArchiveIcon } from "lucide-react";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";+ import { useReducedMotion } from "framer-motion";import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";import { priorityColorsTaskCard } from "@/constants/priority-colors";import { useUpdateTask } from "@/hooks/mutations/task/use-update-task";+import useGetProjectTaskRelations from "@/hooks/queries/task-relation/use-get-project-task-relations";- import { useRegisterShortcuts } from "@/hooks/use-keyboard-shortcuts";+ import { useTaskViewShortcuts } from "@/components/project/task-view-keys/use-task-view-shortcuts";+ import { useCollapsedSections } from "@/hooks/use-collapsed-sections";import { cn } from "@/lib/cn";+import {+ readExpandedRows,+ writeExpandedRows,+} from "@/lib/expanded-rows-storage";+import { buildSubtaskChildren, flattenSubtaskRows } from "@/lib/subtask-tree";import { toast } from "@/lib/toast";import useBulkSelectionStore from "@/store/bulk-selection";import useProjectStore from "@/store/project";@@@ -81,93 -64,14 +71,103 @@@ function ListView((column) => column.id === columnToArchive,);+ // isLoading rather than isPending: a disabled query is also pending, and an+ // empty project should not look like it is still fetching.+ const {+ data: relations,+ isLoading: relationsLoading,+ isError: relationsFailed,+ refetch: refetchRelations,+ } = useGetProjectTaskRelations(project?.id ?? "");++ const subtaskChildren = useMemo(+ () => buildSubtaskChildren(relations ?? []),+ [relations],+ );++ const tasksById = useMemo(() => {+ const index = new Map<+ string,+ ProjectWithTasks["columns"][number]["tasks"][number]+ >();+ for (const column of project?.columns ?? []) {+ for (const task of column.tasks) {+ index.set(task.id, task);+ }+ }+ return index;+ }, [project?.columns]);++ // Per viewer and per project, and only a convenience: a row that cannot be+ // restored simply starts collapsed.+ const projectId = project?.id ?? "";+ const [expanded, setExpanded] = useState(() => ({+ projectId,+ rows: readExpandedRows(projectId),+ }));++ // The board route swaps this component's project rather than remounting it,+ // so a lazy initializer would keep the previous project's map and then save+ // it under the new project's key.+ if (expanded.projectId !== projectId) {+ setExpanded({ projectId, rows: readExpandedRows(projectId) });+ }++ const expandedTasks = expanded.rows;++ useEffect(() => {+ writeExpandedRows(projectId, expandedTasks);+ }, [projectId, expandedTasks]);++ // Collapsing removes the row rather than recording false, so the stored map+ // holds only expanded rows and does not grow with every row ever touched.+ const toggleTaskExpanded = useCallback((rowId: string) => {+ setExpanded((previous) => {+ const rows = { ...previous.rows };+ if (rows[rowId]) delete rows[rowId];+ else rows[rowId] = true;+ return { ...previous, rows };+ });+ }, []);+- // j/k, select-all and shift-click ranges follow this order, so it is the- // order rows are shown in, expanded subtasks included -- built the same- // way each section builds its rows. Selection and focus stay per task, so- // a task shown both under its parent and in its own place is listed once,- // where it first appears.- useEffect(() => {- if (project?.columns) {- const visibleTaskIds = project.columns- .filter((column) => expandedSections[column.id])- .flatMap((column) =>++ // Each section's rows, in the order they are shown, expanded subtasks++ // included. Built once per change and shared with the sections, so their++ // memoization holds. Nothing stays expanded while a drag is in flight.++ const rowsByColumn = useMemo(++ () =>++ new Map(++ (project?.columns ?? []).map((column) => [++ column.id,+ flattenSubtaskRows({+ tasks: column.tasks,+ children: subtaskChildren,+ tasksById,+ isExpanded: (rowId) => !activeId && Boolean(expandedTasks[rowId]),- }).map((row) => row.task.id),- );++ }),++ ]),++ ),++ [project?.columns, subtaskChildren, tasksById, expandedTasks, activeId],++ );++++ // j/k, select-all and shift-click ranges follow this order, so it is the++ // order rows are shown in. Selection and focus stay per task, so a task++ // shown both under its parent and in its own place is listed once, where it++ // first appears.++ const shownTaskIds = useCallback(++ (column: ProjectWithTasks["columns"][number]) => [++ ...new Set((rowsByColumn.get(column.id) ?? []).map((row) => row.task.id)),++ ],++ [rowsByColumn],++ );+++ useEffect(() => {+ if (project?.columns) {+ const visibleTaskIds = project.columns+ .filter((column) => isExpanded(column.id))- .flatMap((column) => column.tasks.map((task) => task.id));- setAvailableTasks(visibleTaskIds);++ .flatMap(shownTaskIds);+ setAvailableTasks([...new Set(visibleTaskIds)]);}- }, [- project,- expandedSections,- setAvailableTasks,- subtaskChildren,- tasksById,- expandedTasks,- activeId,- ]);- }, [project, isExpanded, setAvailableTasks]);++ }, [project, isExpanded, setAvailableTasks, shownTaskIds]);useEffect(() => {clearFocus();@@@ -324,30 -189,48 +285,55 @@@setProject(updatedProject);};+ const handleDragEnd = ({ active, over }: DragEndEvent) => {+ setActiveId(null);+ setOverColumnId(null);+ if (over) moveTask(active.id.toString(), over.id.toString());+ };++ // Escape ends a drag without onDragEnd, so without this the dragged row+ // stays active: its children remain collapsed and the overlay lingers.+ const handleDragCancel = () => {+ setActiveId(null);+ setOverColumnId(null);+ };+- const toggleSection = (sectionId: string) => {- setExpandedSections((prev) => ({- ...prev,- [sectionId]: !prev[sectionId],- }));- };+ useTaskViewShortcuts({+ layout: "list",+ selection: useBulkSelectionStore,+ getGroups: () =>+ project.columns.map((column) => ({+ id: column.id,- taskIds: column.tasks.map((task) => task.id),++ taskIds: shownTaskIds(column),+ collapsed: !isExpanded(column.id),+ })),+ project,+ enabled: activeId === null,+ canMove: !disableDragDrop,+ onMove: moveTask,+ onToggleGroup: toggleSection,+ onToggleAllGroups: () =>+ toggleAllSections(project.columns.map((column) => column.id)),+ });- const handleArchiveClick = (column: ProjectWithTasks["columns"][number]) => {- if (- disableCollectionActions ||- !column.isFinal ||- column.tasks.length === 0- )- return;- setColumnToArchive(column.id);- setIsArchiveModalOpen(true);- };+ const handleAddTask = useCallback((columnId: string) => {+ setIsTaskModalOpen(true);+ setActiveColumn(columnId);+ }, []);++ const handleArchiveClick = useCallback(+ (column: ProjectWithTasks["columns"][number]) => {+ if (+ disableCollectionActions ||+ !column.isFinal ||+ column.tasks.length === 0+ )+ return;+ setColumnToArchive(column.id);+ setIsArchiveModalOpen(true);+ },+ [disableCollectionActions],+ );const handleConfirmArchive = () => {if (disableCollectionActions || !archiveColumn?.isFinal) return;@@@ -398,44 -286,20 +390,41 @@@modifiers={[snapCenterToCursor]}><div className="w-full h-full overflow-auto bg-muted/20">- <div className="divide-y divide-border/50">+ {relationsFailed && (+ // Without relations every task renders as a top-level row, which+ // reads exactly like a project with no subtasks; this says it isn't.+ <div+ role="alert"+ className="flex items-center justify-between gap-3 border-b border-border/50 px-4 py-2 text-sm text-muted-foreground"+ >+ <span>{t("tasks:listView.subtasksLoadError")}</span>+ <Button+ variant="outline"+ size="sm"+ onClick={() => void refetchRelations()}+ >+ {t("common:error.tryAgain")}+ </Button>+ </div>+ )}+ <div aria-busy={relationsLoading} className="divide-y divide-border/50">{project.columns.map((column) => (- <ColumnSection+ <ListColumnSectionkey={column.id}column={column}- projectSlug={project.slug}- activeId={activeId}- overColumnId={overColumnId}- isExpanded={expandedSections[column.id]}- expandedTasks={expandedTasks}- subtaskChildren={subtaskChildren}- tasksById={tasksById}- relationsLoading={relationsLoading}+ projectSlug={project.slug ?? ""}+ isExpanded={isExpanded(column.id)}+ showDropIndicator={+ Boolean(activeId) && overColumnId === column.id+ }disableCollectionActions={disableCollectionActions}- toggleSection={toggleSection}- toggleTaskExpanded={toggleTaskExpanded}- onAddTask={(columnId) => {- setIsTaskModalOpen(true);- setActiveColumn(columnId);- }}- handleArchiveClick={handleArchiveClick}+ onToggle={toggleSection}+ onAddTask={handleAddTask}+ onArchive={handleArchiveClick}++ rows={rowsByColumn.get(column.id) ?? []}++ onToggleTaskExpanded={toggleTaskExpanded}++ relationsLoading={relationsLoading}++ draggingTaskId={activeId === null ? null : String(activeId)}/>))}</div>diff --cc apps/web/src/components/list-view/list-column-section.tsxindex ff5bde0ab,e8a2c96ac..3d823d79e--- a/apps/web/src/components/list-view/list-column-section.tsx+++ b/apps/web/src/components/list-view/list-column-section.tsx@@@ -8,83 -9,40 +9,61 @@@ import { memo, useState } from "react"import { useTranslation } from "react-i18next";import { cn } from "@/lib/cn";import { getColumnIcon } from "@/lib/column";- import { flattenSubtaskRows } from "@/lib/subtask-tree";+ import { EASE_OUT } from "@/lib/motion";++import type { SubtaskRow } from "@/lib/subtask-tree";import type { ProjectWithTasks } from "@/types/project";import TaskRow from "./task-row";type Column = ProjectWithTasks["columns"][number];++type ColumnTask = Column["tasks"][number];- type ColumnSectionProps = {+ type ListColumnSectionProps = {column: Column;projectSlug: string;- activeId: UniqueIdentifier | null;- overColumnId: string | null;isExpanded: boolean;- expandedTasks: Record<string, boolean>;- subtaskChildren: Map<string, string[]>;- tasksById: Map<string, Column["tasks"][number]>;- relationsLoading: boolean;+ showDropIndicator: boolean;disableCollectionActions: boolean;- toggleSection: (columnId: string) => void;- toggleTaskExpanded: (rowId: string) => void;+ onToggle: (columnId: string) => void;onAddTask: (columnId: string) => void;- handleArchiveClick: (column: Column) => void;+ onArchive: (column: Column) => void;++ /**++ * The section's rows in display order. A subtask keeps its own row and is++ * repeated, indented, beneath each expanded parent.++ */++ rows: SubtaskRow<ColumnTask>[];++ onToggleTaskExpanded: (rowId: string) => void;++ relationsLoading: boolean;++ draggingTaskId: string | null;};- // Keep the component identity stable so list updates preserve focus and drag state.- export default function ColumnSection({+ const ListColumnSection = memo(function ListColumnSection({column,projectSlug,- activeId,- overColumnId,isExpanded,- expandedTasks,- subtaskChildren,- tasksById,- relationsLoading,+ showDropIndicator,disableCollectionActions,- toggleSection,- toggleTaskExpanded,+ onToggle,onAddTask,- handleArchiveClick,- }: ColumnSectionProps) {+ onArchive,++ rows,++ onToggleTaskExpanded,++ relationsLoading,++ draggingTaskId,+ }: ListColumnSectionProps) {const { t } = useTranslation();+ const [animateExpand, setAnimateExpand] = useState(false);const { setNodeRef } = useDroppable({id: column.id,- data: {- type: "column",- column,- },+ data: { type: "column", column },});- const showDropIndicator = activeId && overColumnId === column.id;-- // A dragged parent collapses for the duration: moving a row while its- // children are rendered beneath it has no single correct outcome, and- // hiding them keeps the drag to the one row the user grabbed.+ // Reserving the toggle column on every row keeps the titles aligned, but- // only where the group actually has subtasks; a project without any keeps- // the original left edge.- const rows = flattenSubtaskRows({- tasks: column.tasks,- children: subtaskChildren,- tasksById,- // Nothing stays expanded while a drag is in flight. Nested repeats are- // not in the SortableContext, so they never receive the transforms- // applied to the top-level rows: dragging any task past an expanded- // parent would slide the parent while its children stayed put, and the- // subtree would visibly split. Collapsing happens once, as the drag- // starts, rather than shifting rows under a moving pointer.- isExpanded: (rowId) => !activeId && Boolean(expandedTasks[rowId]),- });-- // Until the relations arrive, every task looks childless. Holding the- // toggle column open means the chevrons appear in place instead of- // shifting every title sideways, and aria-busy below says the region is- // still resolving rather than settled and flat.++ // only where the group actually has subtasks. Until the relations arrive,++ // every task looks childless; holding the column open means the chevrons++ // appear in place instead of shifting every title sideways.+ const groupHasSubtasks =+ relationsLoading || rows.some((row) => row.childCount > 0 || row.depth > 0);+return (<divclassName={cn(@@@ -144,10 -106,12 +127,14 @@@{isExpanded && (<divref={setNodeRef}- className="bg-card transition-[translate,opacity] duration-150 ease-out starting:-translate-y-1 starting:opacity-0 motion-reduce:starting:translate-y-0"+ className={cn(+ "bg-card",+ animateExpand &&+ "transition-[translate,opacity] duration-150 ease-out starting:-translate-y-1 starting:opacity-0 motion-reduce:starting:translate-y-0",+ )}>+ {/* Only the top-level rows are sortable; the nested repeats share+ their task id with one of them. */}<SortableContextitems={column.tasks}strategy={verticalListSortingStrategy}@@@ -159,19 -123,9 +146,19 @@@initial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}- transition={{ duration: 0.15, ease: [0.23, 1, 0.32, 1] }}+ transition={{ duration: 0.15, ease: EASE_OUT }}>- <TaskRow task={task} projectSlug={projectSlug} />+ <TaskRow+ task={row.task}+ projectSlug={projectSlug}- reserveToggleSpace={groupHasSubtasks}- isTaskDragging={activeId === row.task.id}+ depth={row.depth}+ rowId={row.rowId}+ childCount={row.childCount}+ isExpanded={row.isExpanded}- onToggleExpanded={() => toggleTaskExpanded(row.rowId)}++ onToggleExpanded={onToggleTaskExpanded}++ reserveToggleSpace={groupHasSubtasks}++ isTaskDragging={draggingTaskId === row.task.id}+ /></motion.div>))}</AnimatePresence>diff --cc apps/web/src/components/list-view/task-row.test.tsxindex 0c4af4051,71ab0579a..b90190688--- a/apps/web/src/components/list-view/task-row.test.tsx+++ b/apps/web/src/components/list-view/task-row.test.tsx@@@ -265,147 -315,6 +321,145 @@@ describe("TaskRow", () =>expect(useExternalLinks).not.toHaveBeenCalled();expect(useGetLabelsByTask).not.toHaveBeenCalled();});++ it("shows no subtask toggle when the task has no children", () => {+ render(<TaskRow task={task} projectSlug="kan" />);++ expect(+ screen.queryByLabelText("tasks:listView.expandSubtasks"),+ ).not.toBeInTheDocument();+ });++ it("keeps the subtask toggle outside the drag activator", () => {+ render(+ <TaskRow+ task={task}+ projectSlug="kan"+ rowId="parent/task-1"+ depth={1}+ childCount={2}+ onToggleExpanded={vi.fn()}+ />,+ );++ const toggle = screen.getByLabelText("tasks:listView.expandSubtasks");+ const activator = document.querySelector('[role="button"]');++ // dnd-kit gives its activator role="button". A button nested inside one is+ // an ambiguous control for assistive technology, so the toggle has to be a+ // sibling of the draggable region rather than a descendant.+ expect(activator).not.toBeNull();+ expect(activator?.contains(toggle)).toBe(false);+ expect(toggle.closest('[role="button"]')).toBeNull();+ });++ it("reserves the toggle column so titles stay aligned in a group", () => {+ const { container: withToggle } = render(+ <TaskRow+ task={task}+ projectSlug="kan"+ childCount={1}+ reserveToggleSpace+ onToggleExpanded={vi.fn()}+ />,+ );+ const { container: withoutToggle } = render(+ <TaskRow task={task} projectSlug="kan" reserveToggleSpace />,+ );++ const gutter = (root: HTMLElement) =>+ root.firstElementChild?.firstElementChild;++ // A row with no children still renders the column, so its number and title+ // start at the same offset as a sibling that does have one.+ expect(gutter(withToggle)).not.toBeNull();+ expect(gutter(withoutToggle)).not.toBeNull();+ expect(gutter(withoutToggle)?.className).toEqual(+ gutter(withToggle)?.className,+ );+ });++ it("keeps the original left edge when a group has no subtasks", () => {+ const { container } = render(<TaskRow task={task} projectSlug="kan" />);+ const draggable = container.querySelector('[role="button"]');+- expect(draggable?.className).toContain("pl-4");++ expect(draggable?.className).toContain("pl-3.5");+ });++ it("announces the nesting level, which the indent cannot", () => {+ render(+ <TaskRow task={task} projectSlug="kan" rowId="a/b/task-1" depth={2} />,+ );++ // A nested repeat and its top-level row otherwise expose identical+ // content, so the hierarchy would be inaudible.+ expect(screen.getByText("tasks:listView.subtaskLevel")).toBeInTheDocument();+ });++ it("adds no level announcement to a top-level row", () => {+ render(<TaskRow task={task} projectSlug="kan" />);++ expect(+ screen.queryByText("tasks:listView.subtaskLevel"),+ ).not.toBeInTheDocument();+ });++ it("names the toggle by its task, not the action alone", () => {+ render(+ <TaskRow+ task={task}+ projectSlug="kan"+ childCount={1}+ onToggleExpanded={vi.fn()}+ />,+ );++ // Several rows each offering "Show subtasks" would be indistinguishable,+ // so the label interpolates the title.+ expect(interpolations).toContainEqual({ title: "Row from payload" });+ });++ it("does not announce a repeated row as disabled", () => {+ render(+ <TaskRow task={task} projectSlug="kan" rowId="parent/task-1" depth={1} />,+ );++ // The repeat is not a drag source, but it still opens its task, so the+ // aria-disabled dnd-kit puts on a disabled sortable must not reach it.+ const row = screen.getByRole("button", { name: /Row from payload/ });+ expect(row).not.toHaveAttribute("aria-disabled", "true");+ expect(row).toHaveAttribute("tabindex", "0");+ });+- it("opens a repeated row with Space as well as Enter", () => {++ // Enter is the view's shortcut for the focused row, so it reaches a repeat++ // the same way it reaches a top-level row.++ it("opens a repeated row with Space", () => {+ render(+ <TaskRow task={task} projectSlug="kan" rowId="parent/task-1" depth={1} />,+ );++ const row = screen.getByRole("button", { name: /Row from payload/ });++ // The repeat carries button semantics but none of dnd-kit's keyboard+ // listeners, so Space has to be handled for it to activate like one.+ fireEvent.keyDown(row, { key: " " });+ expect(navigate).toHaveBeenCalled();-- navigate.mockClear();- fireEvent.keyDown(row, { key: "Enter" });- expect(navigate).toHaveBeenCalled();+ });++ it("labels the toggle by its resulting state", () => {+ render(+ <TaskRow+ task={task}+ projectSlug="kan"+ childCount={1}+ isExpanded+ onToggleExpanded={vi.fn()}+ />,+ );++ const toggle = screen.getByLabelText("tasks:listView.collapseSubtasks");+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ });});vi.mock(diff --cc apps/web/src/components/list-view/task-row.tsxindex 750aa0baf,3fefc4d8e..9ebdbd5a0--- a/apps/web/src/components/list-view/task-row.tsx+++ b/apps/web/src/components/list-view/task-row.tsx@@@ -1,12 -2,9 +2,9 @@@ import { useRestoreTaskFocus } from "@/import { useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { useNavigate } from "@tanstack/react-router";- import { format } from "date-fns";- import { Calendar, CalendarClock, CalendarX, ChevronRight } from "lucide-react";- import { type CSSProperties, memo, useMemo, useState } from "react";-import { Trash2Icon } from "lucide-react";++import { ChevronRight, Trash2Icon } from "lucide-react";+ import { type CSSProperties, useMemo, useState, memo } from "react";import { useTranslation } from "react-i18next";- import { TaskProgressBadges } from "@/components/task/task-progress-badges";- import { TaskPullRequests } from "@/components/task/task-pull-requests";import {AlertDialog,AlertDialogClose,@@@ -41,48 -35,11 +35,49 @@@ import { EASE_OUT_CSS } from "@/lib/mottype TaskRowProps = {task: Task;projectSlug: string;++ // A subtask keeps its own top-level row and is repeated, indented, under++ // each expanded parent.+ /** Nesting level; 0 for a task shown in its own status group. */+ depth?: number;+ /**- * Identifies the row rather than the task. A subtask keeps its own top-level- * row and is repeated under each parent, so the task id is not unique here- * and cannot be used as a drag identity.++ * Identifies the row rather than the task. The task id is not unique when a++ * subtask is repeated, so it cannot be used as a drag identity.+ */+ rowId?: string;+ childCount?: number;+ isExpanded?: boolean;- onToggleExpanded?: () => void;++ onToggleExpanded?: (rowId: string) => void;+ /**+ * Keeps the toggle column present on rows that have no toggle, so titles in+ * a group containing subtasks stay on one vertical line.+ */+ reserveToggleSpace?: boolean;+ /**- * True while this task is being dragged from another of its rows. A subtask- * is repeated under each parent, and only the top-level row is the drag- * source, so the repeats would otherwise sit at full opacity beside it.++ * True while this task is being dragged from another of its rows. Only the++ * top-level row is the drag source, so the repeats would otherwise sit at++ * full opacity beside it.+ */+ isTaskDragging?: boolean;};-function TaskRow({ task, projectSlug }: TaskRowProps) {+function TaskRow({+ task,+ projectSlug,+ depth = 0,+ rowId,+ childCount = 0,+ isExpanded = false,+ onToggleExpanded,+ reserveToggleSpace = false,+ isTaskDragging = false,+}: TaskRowProps) {- const showToggleColumn = depth > 0 || childCount > 0 || reserveToggleSpace;const { t } = useTranslation();const navigate = useNavigate();++ const showToggleColumn = depth > 0 || childCount > 0 || reserveToggleSpace;+ // Only the top-level row is a drag source. A nested repeat shares its task+ // id with that row, so making it sortable would register the same id twice+ // and move the wrong row.+ const isNestedRepeat = depth > 0;const {attributes,listeners,@@@ -90,7 -47,10 +85,11 @@@transform,transition,isDragging,- } = useSortable({ id: rowId ?? task.id, disabled: isNestedRepeat });+ } = useSortable({- id: task.id,++ id: rowId ?? task.id,++ disabled: isNestedRepeat,+ transition: { duration: 200, easing: EASE_OUT_CSS },+ });const { project } = useProjectStore();const taskIsCompleted = isTaskCompleted(task.status, project?.columns);@@@ -137,8 -93,8 +132,25 @@@touchAction: isDragging ? "none" : "auto",};- const handleClick = (e: React.MouseEvent | React.KeyboardEvent) => {- if (!project || !task) return;++ const openTask = () => {++ const currentParams = new URLSearchParams(window.location.search);++ const currentTaskId = currentParams.get("taskId");++++ if (currentTaskId === task.id) {++ navigate({++ to: ".",++ search: {},++ });++ } else {++ navigate({++ to: ".",++ search: { taskId: task.id },++ });++ }++ };+++ const handleClick = (e: React.MouseEvent) => {+ if (!project || !task || !isOwnDomEvent(e)) return;if (e.defaultPrevented) return;if (e.shiftKey) {@@@ -154,44 -110,28 +166,24 @@@}setSelectionAnchor(task.id);-- const currentParams = new URLSearchParams(window.location.search);-- const currentTaskId = currentParams.get("taskId");---- if (currentTaskId === task.id) {-- navigate({-- to: ".",-- search: {},-- });-- } else {-- navigate({-- to: ".",-- search: { taskId: task.id },-- });-- }++ openTask();};const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {if (e.defaultPrevented || e.target !== e.currentTarget) return;- if (e.key === "Enter") {- handleClick(e);+ if (e.key === "Enter" && e.shiftKey) {e.preventDefault();+ selectRange(task.id);+ return;+ }-+ // A repeated row is not sortable, so it takes none of dnd-kit's keys.+ // Space activates a control with button semantics; the top-level rows+ // hand it to dnd-kit instead, which starts a keyboard drag with it.- if (isNestedRepeat) {- if (e.key === " ") {- // Opened before the default is prevented: handleClick ignores an- // event that is already defaultPrevented, and preventing it here- // still stops the page scrolling.- handleClick(e);- e.preventDefault();- }- return;++ if (isNestedRepeat && e.key === " ") {++ e.preventDefault();++ setSelectionAnchor(task.id);++ openTask();}- listeners?.onKeyDown?.(e);};const handleDeleteTask = async () => {@@@ -209,62 -149,15 +201,62 @@@<divref={setNodeRef}style={style}- data-kaneo-sortable++ data-kaneo-sortable={isNestedRepeat ? undefined : true}className={cn(- "border-b border-border/50 transition-colors duration-150",- isDragging && "opacity-50",+ // The indent and the toggle sit beside the draggable region rather+ // than inside it: dnd-kit gives its activator role="button", and a+ // button nested in one is an ambiguous control for assistive tech.- "group flex items-stretch border-b border-border/50 transition-colors duration-150",++ "group/row flex items-stretch border-b border-border/50 transition-colors duration-150",+ (isDragging || isTaskDragging) && "opacity-50",isTaskSelected &&"bg-accent/60 shadow-sm ring-1 ring-inset ring-ring/30",- isTaskFocused && "ring-2 ring-inset ring-ring/50",+ isTaskFocused && "ring-1 ring-board-card-focus ring-inset",)}>+ {showToggleColumn && (+ <div+ className={cn(- "flex flex-shrink-0 items-center pl-4",- isTaskSelected ? "bg-accent/45" : "group-hover:bg-accent/60",++ "flex shrink-0 items-center pl-3.5",++ isTaskSelected ? "bg-accent/45" : "group-hover/row:bg-accent/60",+ )}+ >+ {depth > 0 && (+ <span+ aria-hidden="true"- className="flex-shrink-0"- // Indentation is capped so a deep chain cannot push the title- // off the row; the chevrons still convey the nesting.++ className="shrink-0"++ // Capped so a deep chain cannot push the title off the row; the++ // chevrons still convey the nesting.+ style={{ width: `${Math.min(depth, 6) * 1.25}rem` }}+ />+ )}++ {childCount > 0 ? (+ <button+ type="button"- onClick={onToggleExpanded}++ onClick={() => onToggleExpanded?.(rowId ?? task.id)}+ aria-expanded={isExpanded}- // Named with the task, not just the action: the toggle sits- // outside the row's own control, so several identical "Show- // subtasks" buttons would be indistinguishable in a rotor.++ // Named with the task, not just the action: several identical++ // "Show subtasks" buttons would be indistinguishable in a rotor.+ aria-label={+ isExpanded+ ? t("tasks:listView.collapseSubtasks", { title: task.title })+ : t("tasks:listView.expandSubtasks", { title: task.title })+ }- className="flex-shrink-0 rounded p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"++ className="touch-hitbox relative shrink-0 rounded p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ <ChevronRight+ className={cn(- "w-3 h-3 transition-transform",++ "size-3 transition-transform duration-150 ease-out",+ isExpanded && "rotate-90",+ )}+ />+ </button>+ ) : (- <span aria-hidden="true" className="w-5 flex-shrink-0" />++ <span aria-hidden="true" className="w-5 shrink-0" />+ )}+ </div>+ )}+<ContextMenuonOpenChange={(open) => {if (open) setHasOpenedMenu(true);@@@ -274,100 -167,29 +266,42 @@@{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions -- false positive for onClick and onKeyDown */}<divonClick={handleClick}+ className={cn(- "group relative flex h-10 cursor-pointer items-center gap-3 px-3.5 outline-none transition-colors",- isTaskSelected ? "bg-accent/45" : "hover:bg-accent/60",++ "group relative flex h-10 min-w-0 flex-1 cursor-pointer items-center gap-3 pr-3.5 outline-none transition-colors",++ showToggleColumn ? "pl-2" : "pl-3.5",++ isTaskSelected ? "bg-accent/45" : "group-hover/row:bg-accent/60",+ )}+ data-task-id={task.id}+ data-shortcut-surface- {...attributes}- {...listeners}+ // A repeated row opens its task like any other, so it keeps the+ // button semantics but takes none of dnd-kit's attributes: those+ // carry aria-disabled for a disabled sortable, which would tell+ // assistive technology the row cannot be used.+ {...(isNestedRepeat+ ? { role: "button" as const, tabIndex: 0 }+ : { ...attributes, ...listeners })}- // After the spread, so it replaces dnd-kit's own handler, which- // it calls for the keys it does not handle itself.+ {...hoverPrefetch}onKeyDown={handleKeyDown}- className={cn(- "relative flex min-w-0 flex-1 items-center gap-3 py-1.5 pr-4 transition-colors cursor-pointer",- showToggleColumn ? "pl-2" : "pl-4",- isTaskSelected ? "bg-accent/45" : "group-hover:bg-accent/60",- )}+ onFocus={(event) => {+ if (event.target !== event.currentTarget) return;+ setFocusedTask(isKeyboardFocus(event) ? task.id : null);+ }}>+ {depth > 0 && (- // The indent is decorative, so nesting is otherwise inaudible:- // a repeat and its top-level row expose identical content. This- // joins the row's accessible name, which the drag activator- // builds from its text.++ // The indent is decorative, so nesting is otherwise inaudible: a++ // repeat and its top-level row expose identical content.+ <span className="sr-only">+ {t("tasks:listView.subtaskLevel", { level: depth })}+ </span>+ )}-- {showPriority && (- <div className="flex-shrink-0 first:[&_svg]:h-4 first:[&_svg]:w-4">- {getPriorityIcon(task.priority ?? "")}- </div>- )}- {showTaskNumbers && (- <div className="text-xs font-mono text-muted-foreground flex-shrink-0">- {projectSlug}-{task.number}- </div>- )}-- <div className="flex-1 min-w-0 flex items-center gap-2">- <div className="flex items-center gap-2 justify-between w-full">- <span className="text-sm text-foreground truncate">- {task.title}- </span>- <div className="flex items-center gap-1">- <TaskProgressBadges task={task} />- {showLabels && <TaskLabels labels={task.labels ?? []} />}-- <TaskPullRequests- externalLinks={task.externalLinks}- className="border-border bg-sidebar"- />- </div>- </div>- </div>-- {showDueDates && task.dueDate && (- <div- className={`flex items-center gap-1 text-[10px] px-2 py-1 rounded flex-shrink-0 ${dueDateStatusColors[getDueDateStatus(task.dueDate, taskIsCompleted)]}`}- >- {getDueDateStatus(task.dueDate, taskIsCompleted) ===- "overdue" && <CalendarX className="w-3 h-3" />}- {getDueDateStatus(task.dueDate, taskIsCompleted) ===- "due-soon" && <CalendarClock className="w-3 h-3" />}- {(getDueDateStatus(task.dueDate, taskIsCompleted) ===- "far-future" ||- getDueDateStatus(task.dueDate, taskIsCompleted) ===- "no-due-date") && <Calendar className="w-3 h-3" />}- <span>{format(new Date(task.dueDate), "MMM d")}</span>- </div>- )}-- {showAssignees && (- <div className="flex-shrink-0">- {task.userId ? (- <Avatar className="h-6 w-6">- <AvatarImage- src={assignee?.user?.image ?? ""}- alt={assignee?.user?.name || ""}- />- <AvatarFallback className="text-xs font-medium border border-border/30">- {getInitials(assignee?.user?.name)}- </AvatarFallback>- </Avatar>- ) : (- <div- className="w-6 h-6 rounded-full bg-muted border border-border flex items-center justify-center"- title={t("tasks:assignee.unassigned")}- >- <span className="text-[10px] font-medium text-muted-foreground">- ?- </span>- </div>- )}- </div>- )}+ <TaskRowBody+ task={task}+ projectSlug={projectSlug}+ workspaceId={workspace?.id ?? ""}+ isCompleted={taskIsCompleted}+ assigneeName={assignee?.user?.name ?? task.assigneeName}+ assigneeImage={assignee?.user?.image}+ /></div></ContextMenuTrigger>diff --cc i18n/schema.jsonindex 31be11435,39b444ac6..0e5e013f5--- a/i18n/schema.json+++ b/i18n/schema.json@@@ -8221,84 -12792,85 +12792,105 @@@"type": "object","additionalProperties": false,"properties": {- "suggestions": {+ "title": {"type": "string"},- "commands": {+ "description": {"type": "string"},- "projects": {+ "action": {"type": "string"},- "search": {+ "success": {"type": "string"},- "members": {+ "error": {+ "type": "string"+ }+ },+ "required": ["title", "description", "action", "success", "error"]+ },+ "duplicate": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "titleSuffix": {"type": "string"},- "createTask": {+ "success": {"type": "string"},- "createProject": {+ "error": {+ "type": "string"+ }+ },+ "required": ["titleSuffix", "success", "error"]+ },+ "archive": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "success": {"type": "string"},- "createWorkspace": {+ "success_zero": {"type": "string"},- "lightTheme": {+ "success_one": {"type": "string"},- "darkTheme": {+ "success_two": {"type": "string"},- "systemTheme": {+ "success_few": {"type": "string"},- "keyboardShortcuts": {+ "success_many": {"type": "string"},- "inputPlaceholder": {+ "success_other": {+ "type": "string"+ }+ },+ "required": []+ },+ "listView": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "addTask": {"type": "string"},- "empty": {+ "archiveAllTooltip": {"type": "string"},- "footer": {- "type": "object",- "additionalProperties": false,- "properties": {- "navigate": {- "type": "string"- },- "open": {- "type": "string"- },- "close": {- "type": "string"- }- },- "required": ["navigate", "open", "close"]+ "noTasks": {+ "type": "string"++ },++ "expandSubtasks": {++ "type": "string"++ },++ "collapseSubtasks": {++ "type": "string"++ },++ "subtaskLevel": {++ "type": "string"++ },++ "subtasksLoadError": {++ "type": "string"}},- "required": ["addTask", "archiveAllTooltip", "noTasks"]+ "required": [- "suggestions",- "commands",- "projects",- "search",- "members",- "createTask",- "createProject",- "createWorkspace",- "lightTheme",- "darkTheme",- "systemTheme",- "keyboardShortcuts",- "inputPlaceholder",- "empty",- "footer"++ "addTask",++ "archiveAllTooltip",++ "noTasks",++ "expandSubtasks",++ "collapseSubtasks",++ "subtaskLevel",++ "subtasksLoadError"+ ]},- "sidebar": {+ "kanban": {"type": "object","additionalProperties": false,"properties": {diff --cc tests/api-integration/task-relation-project.test.tsindex 137ba2556,000000000..0fcf1c753mode 100644,000000..100644--- a/tests/api-integration/task-relation-project.test.ts+++ b/tests/api-integration/task-relation-project.test.ts@@@ -1,185 -1,0 +1,186 @@@+import { beforeEach, describe, expect, it } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++type RelationRow = typeof schema.taskRelationTable.$inferSelect;++let taskCounter = 0;++async function seedTask(+ userId: string,+ projectId: string,+ title: string,+ status = "to-do",+) {+ taskCounter += 1;+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId,+ userId,+ title,+ status,+ priority: "medium",+ number: taskCounter,+ position: taskCounter,+ })+ .returning();+ return task;+}++async function relate(+ sourceTaskId: string,+ targetTaskId: string,+ relationType = "subtask",+) {+ const [relation] = await db+ .insert(schema.taskRelationTable)+ .values({ sourceTaskId, targetTaskId, relationType })+ .returning();+ return relation;+}++async function fetchProjectRelations(projectId: string) {+ const { app } = createApp();+ return app.request(`/api/task-relation/project/${projectId}`);+}++describe("API integration: project task relations", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ taskCounter = 0;+ });++ it("returns the relations joining two tasks in the project", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });++ const parent = await seedTask(member.user.id, project.id, "Parent");+ const child = await seedTask(member.user.id, project.id, "Child");+ const blocker = await seedTask(member.user.id, project.id, "Blocker");++ const subtask = await relate(parent.id, child.id, "subtask");+ const blocks = await relate(blocker.id, parent.id, "blocks");++ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(200);+ const payload = (await response.json()) as RelationRow[];++ // Every type is returned; narrowing to subtasks is the caller's business.+ expect(payload.map((relation) => relation.id).sort()).toEqual(+ [subtask.id, blocks.id].sort(),+ );+ expect(+ payload.find((relation) => relation.id === subtask.id),+ ).toMatchObject({+ sourceTaskId: parent.id,+ targetTaskId: child.id,+ relationType: "subtask",+ });+ });++ it("omits a relation whose other end is in a different project", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const other = await createProjectFixture({+ workspaceId: member.workspace.id,+ slug: "other-project",+ });++ const parent = await seedTask(member.user.id, project.id, "Parent");+ const inside = await seedTask(member.user.id, project.id, "Inside");+ const outside = await seedTask(member.user.id, other.project.id, "Outside");++ const kept = await relate(parent.id, inside.id);+ // Both directions: the endpoint requires each end to be in the project,+ // so an outward and an inward edge exercise a different check each.+ await relate(parent.id, outside.id);+ await relate(outside.id, parent.id);++ const response = await fetchProjectRelations(project.id);+ const payload = (await response.json()) as RelationRow[];++ expect(payload.map((relation) => relation.id)).toEqual([kept.id]);+ });++ it("returns an empty list for a project with no relations", async () => {+ const member = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });++ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual([]);+ });++ it("refuses a member whose role does not grant task:read", async () => {+ const member = await createWorkspaceMember({ role: "viewer" });+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ await seedTask(member.user.id, project.id, "Parent");++ // A workspace can redefine its roles, and the stored definition wins over+ // the compiled-in one. This is the shape an API key restricted below+ // task:read also takes.+ await db.insert(schema.workspaceRoleTable).values({+ workspaceId: member.workspace.id,+ role: "viewer",+ permission: JSON.stringify({ project: ["read"], workspace: ["read"] }),+ });++ mockAuthenticatedSession(member.user);+ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(403);+ });++ it("allows a viewer, whose built-in role grants task:read", async () => {+ const member = await createWorkspaceMember({ role: "viewer" });+ mockAuthenticatedSession(member.user);+ const { project } = await createProjectFixture({+ workspaceId: member.workspace.id,+ });+ const parent = await seedTask(member.user.id, project.id, "Parent");+ const child = await seedTask(member.user.id, project.id, "Child");+ const relation = await relate(parent.id, child.id);++ const response = await fetchProjectRelations(project.id);++ expect(response.status).toBe(200);+ const payload = (await response.json()) as RelationRow[];+ expect(payload.map((row) => row.id)).toEqual([relation.id]);+ });++ it("refuses a caller outside the project's workspace", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ await seedTask(owner.user.id, project.id, "Parent");++ const outsider = await createWorkspaceMember({ role: "owner" });+ mockAuthenticatedSession(outsider.user);++ const response = await fetchProjectRelations(project.id);+- expect(response.status).toBe(403);++ // Outside the workspace, the project is reported as not found.++ expect(response.status).toBe(404);+ });+});