- {renderSubagentCountChip(
- task,
- t("common:activeSubagents", { count: task.activeSubagentCount ?? 0 }),
- )}
- {statusIcon}
- {showMaximizeButton && onOpenFullPage && hasKnownSession && (
-
- )}
-
-
- );
-}
-
-type KanbanCardMenuProps = KanbanCardActionProps & {
- effectiveMenuOpen: boolean;
- setMenuOpen: (open: boolean) => void;
-};
-
-function KanbanCardMenu(props: KanbanCardMenuProps) {
- const { t } = useTranslation();
- const { effectiveMenuOpen, setMenuOpen, isDeleting, isArchiving, menuTriggerRef } = props;
- const { menuEntries } = props;
- const isProcessing = isDeleting || isArchiving;
-
- return (
-
diff --git a/apps/web/components/kanban-card-status-icon.tsx b/apps/web/components/kanban-card-status-icon.tsx
new file mode 100644
index 0000000000..3f3d80a935
--- /dev/null
+++ b/apps/web/components/kanban-card-status-icon.tsx
@@ -0,0 +1,122 @@
+import { IconUsersGroup } from "@tabler/icons-react";
+import {
+ getTaskStateIcon,
+ shouldUsePermissionTaskIcon,
+ shouldUseQuestionTaskIcon,
+} from "@/lib/ui/state-icons";
+import type { Task } from "@/components/kanban-card";
+
+// Status markers that mask the launch spinner and gate the "resting" no-affordance
+// case. Bundled together so renderTaskStatusIcon's own branching stays under the
+// complexity limit — see the helpers below for what each flag means for masking.
+type StatusMaskFlags = {
+ needsMe: boolean;
+ showInterrupted: boolean;
+ showAutoStartFailed: boolean;
+ parkedOnBackgroundWork: boolean;
+ showWorkspaceOrphaned: boolean;
+};
+
+function hasNoStatusAffordance(
+ showRunningSpinner: boolean,
+ hasActivity: boolean,
+ flags: StatusMaskFlags,
+): boolean {
+ return (
+ !showRunningSpinner &&
+ !flags.needsMe &&
+ !hasActivity &&
+ !flags.showInterrupted &&
+ !flags.showAutoStartFailed &&
+ !flags.parkedOnBackgroundWork &&
+ !flags.showWorkspaceOrphaned
+ );
+}
+
+// A "needs me" prompt (pending clarification / permission) must not be masked
+// by the launch-spinner short-circuit — a mid-turn prompt can coincide with a
+// coarse running state. Live foreground activity still wins, handled inside
+// getTaskStateIcon. A failed auto-start or an orphaned workspace must not be
+// masked either: startTask sets the task to SCHEDULING before the launch, so
+// a session-less SCHEDULING/IN_PROGRESS task (whether from a launch failure
+// or a vanished parent workspace) reads as showRunningSpinner=true, the exact
+// shape both markers exist to surface. The parked affordance (AC-58) is
+// likewise never masked by the generic spinner — it renders through
+// getTaskStateIcon below.
+function resolveForegroundActivity(
+ task: Task,
+ showRunningSpinner: boolean,
+ flags: StatusMaskFlags,
+): Task["foregroundActivity"] {
+ const shouldForceGenerating =
+ showRunningSpinner &&
+ !flags.needsMe &&
+ !flags.showAutoStartFailed &&
+ !flags.parkedOnBackgroundWork &&
+ !flags.showWorkspaceOrphaned &&
+ task.foregroundActivity !== "background";
+ return shouldForceGenerating ? "generating" : task.foregroundActivity;
+}
+
+/**
+ * Resolves the card status icon, or null when the actions cluster shows none
+ * (a resting done/todo task). The backend task-level MOST-ACTIVE-WINS
+ * aggregate takes precedence: a background-running task shows the distinct
+ * background affordance — even when its primary session has finished and
+ * only a secondary session is still working, so it reads as working, not
+ * done — while any generating session keeps the spinner. When the aggregate
+ * is absent it falls back to the primary-session-driven spinner (covers
+ * STARTING/SCHEDULING before a session reads RUNNING) or the pending-input
+ * question icon.
+ */
+export function renderTaskStatusIcon(
+ task: Task,
+ showRunningSpinner: boolean,
+ hasPendingClarification: boolean,
+ hasPendingPermission: boolean,
+) {
+ const flags: StatusMaskFlags = {
+ needsMe:
+ shouldUseQuestionTaskIcon(task.state, hasPendingClarification) ||
+ shouldUsePermissionTaskIcon(hasPendingPermission),
+ showInterrupted: !!task.interrupted,
+ showAutoStartFailed: !!task.autoStartFailed,
+ parkedOnBackgroundWork: !!task.parkedOnBackgroundWork,
+ showWorkspaceOrphaned: !!task.workspaceOrphaned,
+ };
+ const hasActivity =
+ task.foregroundActivity === "generating" || task.foregroundActivity === "background";
+ if (hasNoStatusAffordance(showRunningSpinner, hasActivity, flags)) return null;
+ const foregroundActivity = resolveForegroundActivity(task, showRunningSpinner, flags);
+ return getTaskStateIcon(task.state, "h-4 w-4", {
+ hasPendingClarification,
+ foregroundActivity,
+ hasPendingPermission,
+ interrupted: flags.showInterrupted,
+ autoStartFailed: flags.showAutoStartFailed,
+ parkedOnBackgroundWork: flags.parkedOnBackgroundWork,
+ workspaceOrphaned: flags.showWorkspaceOrphaned,
+ });
+}
+
+/**
+ * The board's only window into a fan-out. `activeSubagentCount` is derived
+ * from the live registry (never a mutable counter) and summed across a
+ * task's sessions, so it needs no local reconciliation: at zero there is
+ * nothing live and the chip is absent.
+ */
+export function renderSubagentCountChip(task: Task, label: string) {
+ const count = task.activeSubagentCount ?? 0;
+ if (count <= 0) return null;
+ return (
+
+
+ {count}
+
+ );
+}
diff --git a/apps/web/components/kanban-card.render-stability.test.tsx b/apps/web/components/kanban-card.render-stability.test.tsx
index 74577c5564..63f3747adf 100644
--- a/apps/web/components/kanban-card.render-stability.test.tsx
+++ b/apps/web/components/kanban-card.render-stability.test.tsx
@@ -63,6 +63,9 @@ describe("KanbanCard render isolation", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_A]: {
workflowId: WORKFLOW_A,
diff --git a/apps/web/components/kanban-card.tsx b/apps/web/components/kanban-card.tsx
index 36496315b0..7098296770 100644
--- a/apps/web/components/kanban-card.tsx
+++ b/apps/web/components/kanban-card.tsx
@@ -153,6 +153,10 @@ export interface KanbanCardProps {
/** Shift-click range select within this card's column. */
onRangeSelect?: (taskId: string) => void;
isMultiSelectMode?: boolean;
+ /** Keyboard reorder (REQ-TASKS-KANBAN-TASK-REORDERING-001.12): pick up/move/drop/cancel. */
+ onCardKeyDown?: (event: React.KeyboardEvent, task: Task) => void;
+ /** Whether this card is the one currently picked up for a keyboard reorder. */
+ isPickedUpForReorder?: boolean;
}
/**
@@ -207,6 +211,8 @@ function KanbanCardFrame({
onClick,
onToggleSelect,
onOpenFullPage,
+ onKeyDown,
+ isPickedUpForReorder,
}: Pick<
KanbanCardProps,
| "task"
@@ -220,11 +226,13 @@ function KanbanCardFrame({
| "onArchive"
| "onToggleSelect"
| "onOpenFullPage"
+ | "isPickedUpForReorder"
> & {
draggable: ReturnType;
menu: KanbanCardMenuState;
isPreviewed: boolean;
onClick: (e: React.MouseEvent) => void;
+ onKeyDown?: (event: React.KeyboardEvent) => void;
}) {
return (
<>
@@ -252,6 +260,8 @@ function KanbanCardFrame({
onToggleSelect?.(task.id);
}}
onOpenFullPage={onOpenFullPage}
+ onKeyDown={onKeyDown}
+ isPickedUpForReorder={isPickedUpForReorder}
/>
@@ -302,6 +312,8 @@ export function KanbanCard({
onToggleSelect,
onRangeSelect,
isMultiSelectMode,
+ onCardKeyDown,
+ isPickedUpForReorder,
}: KanbanCardProps) {
const draggable = useDraggable({
id: task.id,
@@ -351,6 +363,8 @@ export function KanbanCard({
onClick={handleClick}
onToggleSelect={onToggleSelect}
onOpenFullPage={onOpenFullPage}
+ onKeyDown={onCardKeyDown ? (event) => onCardKeyDown(event, task) : undefined}
+ isPickedUpForReorder={isPickedUpForReorder}
/>
({ count: 0 }));
+
+vi.mock("@dnd-kit/core", () => ({
+ useDroppable: () => ({ setNodeRef: vi.fn(), isOver: false }),
+}));
+
+vi.mock("./kanban/virtualized-column-task-list", () => ({
+ VirtualizedColumnTaskList: () => {
+ taskListRenderCounts.count += 1;
+ return ;
+ },
+}));
+
+import { StateProvider } from "@/components/state-provider";
+import type { Task } from "@/components/kanban-card";
+import { defaultState } from "@/lib/state/default-state";
+import { KanbanColumn, type WorkflowStep } from "@/components/kanban-column";
+
+const STEP: WorkflowStep = { id: "step-1", title: "Todo", color: "bg-blue-500" };
+const TASK_A: Task = { id: "task-a", title: "Task A", workflowStepId: STEP.id, position: 0 };
+const TASK_B: Task = { id: "task-b", title: "Task B", workflowStepId: STEP.id, position: 1 };
+const EXTERNAL_LINK_AVAILABILITY = { gitlab: false, jira: false, linear: false, sentry: false };
+const HANDLERS = {
+ onPreviewTask: vi.fn(),
+ onOpenTask: vi.fn(),
+ onEditTask: vi.fn(),
+ onDeleteTask: vi.fn(),
+};
+
+function Column(props: {
+ activeTaskId?: string | null;
+ keyboardDraft?: {
+ taskId: string;
+ stepId: string;
+ band: "admitted" | "queued";
+ order: string[];
+ } | null;
+ onCardKeyDown?: (event: React.KeyboardEvent, task: Task) => void;
+}) {
+ return (
+
+
+
+ );
+}
+
+afterEach(() => {
+ taskListRenderCounts.count = 0;
+ cleanup();
+});
+
+describe("KanbanColumn memo comparator", () => {
+ it("rerenders when keyboardDraft changes even though every other prop is unchanged", () => {
+ const view = render();
+ expect(taskListRenderCounts.count).toBe(1);
+
+ view.rerender(
+ ,
+ );
+
+ expect(taskListRenderCounts.count).toBe(2);
+ });
+
+ it("rerenders when activeTaskId changes even though every other prop is unchanged", () => {
+ const view = render();
+ expect(taskListRenderCounts.count).toBe(1);
+
+ view.rerender();
+
+ expect(taskListRenderCounts.count).toBe(2);
+ });
+
+ it("rerenders when onCardKeyDown changes even though every other prop is unchanged", () => {
+ const view = render();
+ expect(taskListRenderCounts.count).toBe(1);
+
+ view.rerender();
+
+ expect(taskListRenderCounts.count).toBe(2);
+ });
+});
diff --git a/apps/web/components/kanban-column.tsx b/apps/web/components/kanban-column.tsx
index a9e3876921..82fcbef501 100644
--- a/apps/web/components/kanban-column.tsx
+++ b/apps/web/components/kanban-column.tsx
@@ -12,7 +12,10 @@ import type { Repository } from "@/lib/types/http";
import { countAdmittedTasks, formatWipCount, isOverWipLimit } from "@/lib/kanban/wip-limit";
import { partitionWipTasks } from "@/lib/kanban/wip-queue";
import { useTranslation } from "react-i18next";
-import { VirtualizedColumnTaskList } from "./kanban/virtualized-column-task-list";
+import {
+ VirtualizedColumnTaskList,
+ type KeyboardReorderDraft,
+} from "./kanban/virtualized-column-task-list";
export interface WorkflowStep {
id: string;
@@ -48,6 +51,11 @@ interface KanbanColumnProps {
onSelectRange?: (taskId: string, orderedIds: string[]) => void;
isMultiSelectMode?: boolean;
externalLinkAvailability: KanbanExternalLinkAvailability;
+ /** The task currently being dragged anywhere on the board, if any (AC.7's insertion indicator). */
+ activeTaskId?: string | null;
+ /** The card currently picked up via the keyboard, if any (AC.12). */
+ keyboardDraft?: KeyboardReorderDraft | null;
+ onCardKeyDown?: (event: React.KeyboardEvent, task: Task) => void;
}
function ColumnHeader({
@@ -120,7 +128,8 @@ function columnCallbacksEqual(previous: KanbanColumnProps, next: KanbanColumnPro
previous.onArchiveTask === next.onArchiveTask &&
previous.onMoveTask === next.onMoveTask &&
previous.onToggleSelect === next.onToggleSelect &&
- previous.onSelectRange === next.onSelectRange
+ previous.onSelectRange === next.onSelectRange &&
+ previous.onCardKeyDown === next.onCardKeyDown
);
}
@@ -143,7 +152,12 @@ function kanbanColumnPropsEqual(previous: KanbanColumnProps, next: KanbanColumnP
taskItemsEqual(previous.tasks, next.tasks) &&
columnCallbacksEqual(previous, next) &&
columnDisplayPropsEqual(previous, next) &&
- externalLinkAvailabilityEqual(previous.externalLinkAvailability, next.externalLinkAvailability)
+ externalLinkAvailabilityEqual(
+ previous.externalLinkAvailability,
+ next.externalLinkAvailability,
+ ) &&
+ previous.activeTaskId === next.activeTaskId &&
+ previous.keyboardDraft === next.keyboardDraft
);
}
@@ -168,6 +182,9 @@ export const KanbanColumn = memo(function KanbanColumn({
onSelectRange,
isMultiSelectMode,
externalLinkAvailability,
+ activeTaskId,
+ keyboardDraft,
+ onCardKeyDown,
}: KanbanColumnProps) {
const { setNodeRef, isOver } = useDroppable({
id: step.id,
@@ -225,6 +242,9 @@ export const KanbanColumn = memo(function KanbanColumn({
deletingTaskId={deletingTaskId}
archivingTaskId={archivingTaskId}
selectedIds={selectedIds}
+ activeTaskId={activeTaskId}
+ keyboardDraft={keyboardDraft}
+ onCardKeyDown={onCardKeyDown}
onPreviewTask={onPreviewTask}
onOpenTask={onOpenTask}
onEditTask={onEditTask}
diff --git a/apps/web/components/kanban/graph2-task-pipeline.test.tsx b/apps/web/components/kanban/graph2-task-pipeline.test.tsx
index 78b802f4a9..794b62c031 100644
--- a/apps/web/components/kanban/graph2-task-pipeline.test.tsx
+++ b/apps/web/components/kanban/graph2-task-pipeline.test.tsx
@@ -95,6 +95,9 @@ function renderPipelineWithWorkflowSnapshot(
},
},
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
},
}}
>
@@ -158,6 +161,49 @@ describe("Graph2TaskPipeline — no resolvable current step (AC-UI-PIPELINE-ROW-
});
});
+describe("Graph2TaskPipeline — no reorder surface (AC.38)", () => {
+ it("ignores the AC.12 keyboard-reorder commands: a row lays out one task, so none apply", () => {
+ const onMoveTask = vi.fn();
+ renderPipeline(makeTask("step-2"), STEPS, { onMoveTask });
+
+ const card = screen.getByTestId("pipeline-task-task-1");
+ fireEvent.keyDown(card, { key: " " });
+ fireEvent.keyDown(card, { key: "ArrowDown" });
+ fireEvent.keyDown(card, { key: "ArrowUp" });
+ fireEvent.keyDown(card, { key: "Enter" });
+ fireEvent.keyDown(card, { key: "Escape" });
+
+ expect(onMoveTask).not.toHaveBeenCalled();
+ // AC.12 requires an assistive-technology announcement on pickup/move; its
+ // absence here confirms no reorder gesture was recognized.
+ expect(screen.queryByRole("status")).toBeNull();
+ });
+});
+
+describe("Graph2TaskPipeline — actions cluster stays reachable off-screen (defect 2)", () => {
+ it("keeps the actions menu trigger outside the horizontally-scrollable step run region", () => {
+ renderPipeline(makeTask("step-2"), STEPS);
+
+ const region = screen.getByTestId("pipeline-row-overflow-region");
+ const trigger = screen.getByTestId("pipeline-row-menu-trigger-task-1");
+ expect(region.contains(trigger)).toBe(false);
+ });
+
+ it("does not render the actions menu trigger in multi-select mode", () => {
+ renderPipeline(makeTask("step-2"), STEPS, { isMultiSelectMode: true });
+
+ expect(screen.queryByTestId("pipeline-row-menu-trigger-task-1")).toBeNull();
+ });
+
+ it("keeps the action trigger touch-sized on coarse pointers", () => {
+ renderPipeline(makeTask("step-2"), STEPS);
+
+ const trigger = screen.getByTestId("pipeline-row-menu-trigger-task-1");
+ expect(trigger.className).toContain("[@media(pointer:coarse)]:h-11");
+ expect(trigger.className).toContain("[@media(pointer:coarse)]:w-11");
+ });
+});
+
describe("Graph2TaskPipeline — first/last step move-control boundaries", () => {
it("shows a single next control at the first step (Triage -> In Progress)", () => {
renderPipeline(makeTask("step-1"), STEPS);
diff --git a/apps/web/components/kanban/swimlane-container.render-stability.test.tsx b/apps/web/components/kanban/swimlane-container.render-stability.test.tsx
index ab7d9fa25f..9fc2210d87 100644
--- a/apps/web/components/kanban/swimlane-container.render-stability.test.tsx
+++ b/apps/web/components/kanban/swimlane-container.render-stability.test.tsx
@@ -116,6 +116,9 @@ function renderSwimlanes(
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_A]: snapshot(WORKFLOW_A, "task-a"),
[WORKFLOW_B]: snapshot(WORKFLOW_B, "task-b"),
diff --git a/apps/web/components/kanban/swimlane-graph2-content.tsx b/apps/web/components/kanban/swimlane-graph2-content.tsx
index beb166d154..080451ed75 100644
--- a/apps/web/components/kanban/swimlane-graph2-content.tsx
+++ b/apps/web/components/kanban/swimlane-graph2-content.tsx
@@ -13,6 +13,30 @@ import type { Task } from "@/components/kanban-card";
import type { WorkflowStep } from "@/components/kanban-column";
import { useTranslation } from "react-i18next";
import { areAllEmptyStepsAutoHidden } from "@/lib/kanban/auto-hide-empty-columns";
+import { compareStepOrder } from "@/lib/kanban/task-order";
+
+/**
+ * Pipeline row order: each step's contiguous run of rows in step-list order
+ * (a task with no resolvable current step sorts after every task that has
+ * one), then within one step the full AC.1 total order
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.2, .38) — position is not by itself a
+ * total order, and ties are the ship-time norm for tasks that arrived
+ * together.
+ */
+export function sortGraph2Tasks(displayTasks: Task[], displaySteps: WorkflowStep[]): Task[] {
+ // A finite sentinel, not Number.POSITIVE_INFINITY: two no-resolvable-step
+ // tasks must still subtract to a finite, sortable delta so compareStepOrder
+ // below is reachable (Infinity - Infinity is NaN, which a sort comparator
+ // cannot use to order a pair).
+ const noStepSentinel = displaySteps.length;
+ const stepIndex = new Map(displaySteps.map((step, index) => [step.id, index]));
+ const resolvedStepIndex = (task: Task) => stepIndex.get(task.workflowStepId) ?? noStepSentinel;
+ return [...displayTasks].sort((a, b) => {
+ const stepDelta = resolvedStepIndex(a) - resolvedStepIndex(b);
+ if (stepDelta !== 0) return stepDelta;
+ return compareStepOrder(a, b);
+ });
+}
export function getGraph2DisplayState(
tasks: Task[],
@@ -27,32 +51,6 @@ export function getGraph2DisplayState(
};
}
-/**
- * Sorts by displayed-step-index ascending (a task with no resolvable current
- * step sorts after every task that has one), then `position` ascending
- * (absent treated as 0), then task id ascending.
- */
-export function sortGraph2Tasks(tasks: Task[], displaySteps: WorkflowStep[]): Task[] {
- // A finite sentinel, not Number.POSITIVE_INFINITY: two no-resolvable-step
- // tasks must still subtract to a finite, sortable delta so their position/id
- // tiebreak below is reachable (Infinity - Infinity is NaN, which a sort
- // comparator cannot use to order a pair).
- const noStepSentinel = displaySteps.length;
- const stepIndex = (task: Task) => {
- const index = displaySteps.findIndex((step) => step.id === task.workflowStepId);
- return index === -1 ? noStepSentinel : index;
- };
- return [...tasks].sort((a, b) => {
- const stepDelta = stepIndex(a) - stepIndex(b);
- if (stepDelta !== 0) return stepDelta;
- const positionDelta = (a.position ?? 0) - (b.position ?? 0);
- if (positionDelta !== 0) return positionDelta;
- if (a.id < b.id) return -1;
- if (a.id > b.id) return 1;
- return 0;
- });
-}
-
export function SwimlaneGraph2Content({
workflowId,
steps,
diff --git a/apps/web/components/kanban/swimlane-graph2-orphan-display.test.ts b/apps/web/components/kanban/swimlane-graph2-orphan-display.test.ts
index 80d2717dab..47ca7053c2 100644
--- a/apps/web/components/kanban/swimlane-graph2-orphan-display.test.ts
+++ b/apps/web/components/kanban/swimlane-graph2-orphan-display.test.ts
@@ -136,6 +136,29 @@ describe("sortGraph2Tasks (AC-UI-PIPELINE-ROW-005.1)", () => {
expect(sorted.map((t) => t.id)).toEqual(["no-position", "first", "second"]);
});
+ it("breaks a same-step position tie using the full AC.1 order rather than bare position", () => {
+ // REQ-TASKS-KANBAN-TASK-REORDERING-001.2/.38: bare `position` is not a
+ // total order, so two tasks that arrived together (same position) must
+ // still resolve deterministically via priority, then queuedAt/createdAt,
+ // then id — not fall back to whatever order they arrived in the array.
+ const sorted = sortGraph2Tasks(
+ [
+ {
+ ...makeTask("low", "todo", 1),
+ priority: "low",
+ createdAt: "2026-08-12T09:00:00Z",
+ } as Task,
+ {
+ ...makeTask("critical", "todo", 1),
+ priority: "critical",
+ createdAt: "2026-08-12T09:00:00Z",
+ } as Task,
+ ],
+ steps,
+ );
+ expect(sorted.map((t) => t.id)).toEqual(["critical", "low"]);
+ });
+
it("breaks a step-index and position tie by task id ascending", () => {
const sorted = sortGraph2Tasks([makeTask("b", "todo", 0), makeTask("a", "todo", 0)], steps);
expect(sorted.map((t) => t.id)).toEqual(["a", "b"]);
diff --git a/apps/web/components/kanban/swimlane-kanban-content.tsx b/apps/web/components/kanban/swimlane-kanban-content.tsx
index e0a46a17eb..efbb89a491 100644
--- a/apps/web/components/kanban/swimlane-kanban-content.tsx
+++ b/apps/web/components/kanban/swimlane-kanban-content.tsx
@@ -1,27 +1,18 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import {
- DragEndEvent,
- DragStartEvent,
- PointerSensor,
- TouchSensor,
- useSensor,
- useSensors,
-} from "@dnd-kit/core";
+import { useCallback, useEffect, useMemo } from "react";
import { KanbanColumn } from "@/components/kanban-column";
import { type Task } from "@/components/kanban-card";
import type { WorkflowStep } from "@/components/kanban-column";
import type { MoveTaskError } from "@/hooks/use-drag-and-drop";
-import { useTaskActions } from "@/hooks/use-task-actions";
-import { useAppStore, useAppStoreApi } from "@/components/state-provider";
+import { useAppStore } from "@/components/state-provider";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import { MobileColumnTabs } from "./mobile-column-tabs";
import { SwipeableColumns } from "./swipeable-columns";
import { MobileDropTargets } from "./mobile-drop-targets";
import { KanbanDragSurface } from "./kanban-drag-surface";
import { getDesktopEmptyState } from "./desktop-auto-hidden-empty-state";
-import { isOrphanMoveTarget, useOrphanDisplay } from "./swimlane-orphan-display";
+import { useOrphanDisplay } from "./swimlane-orphan-display";
export {
ORPHAN_STEP,
ORPHAN_STEP_ID,
@@ -29,18 +20,13 @@ export {
remapOrphanTasks,
} from "./swimlane-orphan-display";
import { AdaptiveDesktopKanban } from "./adaptive-desktop-kanban";
-import type { KanbanState } from "@/lib/state/slices/kanban/types";
import type { MobileWorkflowNavigation } from "@/lib/kanban/view-registry";
import { resolveMobileColumnIndex } from "@/lib/kanban/mobile-column-index";
-import { compareTasksByCreatedDesc } from "@/lib/kanban/task-order";
-import { getTaskMoveErrorMessage } from "@/components/task/task-move-error-message";
+import { compareStepOrder } from "@/lib/kanban/task-order";
+import { useSwimlaneKanbanPresentationDnd } from "@/hooks/domains/kanban/use-swimlane-kanban-dnd";
+import { useKeyboardReorder } from "@/hooks/domains/kanban/use-keyboard-reorder";
import { countAdmittedTasks } from "@/lib/kanban/wip-limit";
import { areAllEmptyStepsAutoHidden } from "@/lib/kanban/auto-hide-empty-columns";
-import {
- getDragDisplaySteps,
- getTemporaryStepIds,
- useKanbanDragScrollAnchor,
-} from "@/hooks/domains/kanban/use-kanban-drag-scroll-anchor";
import {
type SharedKanbanLayoutProps,
useSharedKanbanLayoutProps,
@@ -48,12 +34,8 @@ import {
import { cn } from "@kandev/ui/lib/utils";
import { useKanbanExternalLinkAvailability } from "@/components/kanban-external-link-availability";
import { useTranslation } from "react-i18next";
-import { t } from "@/lib/i18n";
import { useCompactSwimlaneHeight } from "@/hooks/domains/kanban/use-compact-swimlane-height";
-const TASK_POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
-const TASK_TOUCH_SENSOR_OPTIONS = { activationConstraint: { delay: 250, tolerance: 5 } };
-
export type SwimlaneKanbanContentProps = {
compactHeight?: boolean;
workflowId: string;
@@ -76,137 +58,6 @@ export type SwimlaneKanbanContentProps = {
mobileWorkflowNavigation?: MobileWorkflowNavigation;
};
-type SwimlaneKanbanDndOptions = {
- tasks: Task[];
- workflowId: string;
- onMoveError?: (error: MoveTaskError) => void;
-};
-
-function useSwimlaneKanbanDnd({ tasks, workflowId, onMoveError }: SwimlaneKanbanDndOptions) {
- const store = useAppStoreApi();
- const { moveTaskById } = useTaskActions();
- const [activeTaskId, setActiveTaskId] = useState(null);
- const tasksRef = useRef(tasks);
- tasksRef.current = tasks;
-
- const sensors = useSensors(
- useSensor(PointerSensor, TASK_POINTER_SENSOR_OPTIONS),
- useSensor(TouchSensor, TASK_TOUCH_SENSOR_OPTIONS),
- );
-
- const handleDragStart = useCallback((event: DragStartEvent) => {
- setActiveTaskId(event.active.id as string);
- }, []);
-
- const handleDragEnd = useCallback(
- async (event: DragEndEvent) => {
- const { active, over } = event;
- setActiveTaskId(null);
- if (!over) return;
-
- const taskId = active.id as string;
- const targetStepId = over.id as string;
- const task = tasksRef.current.find((candidate) => candidate.id === taskId);
- if (!task || task.workflowStepId === targetStepId || isOrphanMoveTarget(targetStepId)) return;
-
- const state = store.getState();
- const snapshot = state.kanbanMulti.snapshots[workflowId];
- if (!snapshot) return;
-
- const targetTasks = snapshot.tasks.filter(
- (t: KanbanState["tasks"][number]) => t.workflowStepId === targetStepId && t.id !== taskId,
- );
- const nextPosition = targetTasks.length;
- const originalTasks = snapshot.tasks;
-
- state.setWorkflowSnapshot(workflowId, {
- ...snapshot,
- tasks: snapshot.tasks.map((t: KanbanState["tasks"][number]) =>
- t.id === taskId ? { ...t, workflowStepId: targetStepId, position: nextPosition } : t,
- ),
- });
-
- try {
- await moveTaskById(taskId, {
- workflow_id: workflowId,
- workflow_step_id: targetStepId,
- position: nextPosition,
- });
- } catch (error) {
- const currentSnapshot = store.getState().kanbanMulti.snapshots[workflowId];
- if (currentSnapshot) {
- store
- .getState()
- .setWorkflowSnapshot(workflowId, { ...currentSnapshot, tasks: originalTasks });
- }
- const message = getTaskMoveErrorMessage(error, t("task:taskMoveErrorGeneric"), t);
- onMoveError?.({ message, taskId, sessionId: task.primarySessionId ?? null });
- }
- },
- [workflowId, store, moveTaskById, onMoveError],
- );
-
- const handleDragCancel = useCallback(() => {
- setActiveTaskId(null);
- }, []);
-
- const moveTaskToStep = useCallback(
- async (task: Task, targetStepId: string) => {
- if (task.workflowStepId === targetStepId) return;
- await handleDragEnd({ active: { id: task.id }, over: { id: targetStepId } } as DragEndEvent);
- },
- [handleDragEnd],
- );
-
- const activeTask = useMemo(
- () => tasks.find((t) => t.id === activeTaskId) ?? null,
- [tasks, activeTaskId],
- );
-
- return {
- sensors,
- handleDragStart,
- handleDragEnd,
- handleDragCancel,
- moveTaskToStep,
- activeTask,
- };
-}
-
-function useSwimlaneKanbanPresentationDnd({
- displaySteps,
- moveTargetSteps,
- isMobile,
- ...dndOptions
-}: SwimlaneKanbanDndOptions & {
- displaySteps: WorkflowStep[];
- moveTargetSteps: WorkflowStep[];
- isMobile: boolean;
-}) {
- const dnd = useSwimlaneKanbanDnd(dndOptions);
- const renderedSteps = useMemo(
- () => getDragDisplaySteps(displaySteps, moveTargetSteps, !!dnd.activeTask, isMobile),
- [displaySteps, moveTargetSteps, dnd.activeTask, isMobile],
- );
- const { boardRef, handleAnchoredDragStart } = useKanbanDragScrollAnchor({
- tasks: dndOptions.tasks,
- activeTask: dnd.activeTask,
- renderedSteps,
- onDragStart: dnd.handleDragStart,
- });
- const temporaryStepIds = useMemo(
- () => getTemporaryStepIds(displaySteps, moveTargetSteps),
- [displaySteps, moveTargetSteps],
- );
- return {
- ...dnd,
- renderedSteps,
- temporaryStepIds,
- boardRef,
- handleDragStart: handleAnchoredDragStart,
- };
-}
-
function useMobileColumnIndex(workflowId: string, steps: WorkflowStep[], tasks: Task[]) {
const storedStepId = useAppStore(
(state) => state.mobileKanban.activeStepIdByWorkflowId[workflowId],
@@ -238,12 +89,25 @@ function useMobileColumnIndex(workflowId: string, steps: WorkflowStep[], tasks:
function useTasksByStep(tasks: Task[]) {
return useCallback(
- (stepId: string) =>
- tasks.filter((t) => t.workflowStepId === stepId).sort(compareTasksByCreatedDesc),
+ (stepId: string) => tasks.filter((t) => t.workflowStepId === stepId).sort(compareStepOrder),
[tasks],
);
}
+function MobileKanbanEmptyState({ allStepsAutoHidden }: { allStepsAutoHidden: boolean }) {
+ const { t } = useTranslation();
+ return (
+
+ {allStepsAutoHidden
+ ? t("kanban:allEmptyStepsAutoHidden")
+ : t("kanban:noStepsConfiguredChooseAnotherWorkflow")}
+
+ );
+}
+
function MobileKanbanLayout({
steps,
moveTargetSteps,
@@ -265,6 +129,9 @@ function MobileKanbanLayout({
onSelectRange,
isMultiSelectMode,
externalLinkAvailability,
+ activeTaskId,
+ keyboardDraft,
+ onCardKeyDown,
mobileWorkflowNavigation,
}: SharedKanbanLayoutProps & {
activeIndex: number;
@@ -272,7 +139,6 @@ function MobileKanbanLayout({
activeTask: Task | null;
mobileWorkflowNavigation?: MobileWorkflowNavigation;
}) {
- const { t } = useTranslation();
const taskCounts = useMemo(() => {
const counts: Record = {};
for (const step of steps) {
@@ -300,16 +166,7 @@ function MobileKanbanLayout({
/>
)}
{steps.length === 0 ? (
-
- {allStepsAutoHidden
- ? t("kanban:allEmptyStepsAutoHidden")
- : t("kanban:noStepsConfiguredChooseAnotherWorkflow")}
-
+
) : (
)}
))}
@@ -431,6 +297,9 @@ function DesktopKanbanLayout({
externalLinkAvailability,
temporaryStepIds,
isDragging,
+ activeTaskId,
+ keyboardDraft,
+ onCardKeyDown,
}: SharedKanbanLayoutProps) {
const getTasksForStep = useTasksByStep(tasks);
@@ -461,6 +330,9 @@ function DesktopKanbanLayout({
onSelectRange={onSelectRange}
isMultiSelectMode={isMultiSelectMode}
externalLinkAvailability={externalLinkAvailability}
+ activeTaskId={activeTaskId}
+ keyboardDraft={keyboardDraft}
+ onCardKeyDown={onCardKeyDown}
/>
)}
@@ -506,6 +378,7 @@ function renderKanbanLayout({
return ;
}
+// eslint-disable-next-line max-lines-per-function -- composes compact sizing, keyboard reorder, and responsive layouts.
export function SwimlaneKanbanContent({
compactHeight = false,
workflowId,
@@ -546,6 +419,7 @@ export function SwimlaneKanbanContent({
moveTargetSteps,
isMobile,
});
+ const keyboard = useKeyboardReorder(workflowId, displayTasks);
const sizing = useCompactSwimlaneHeight(
compactHeight && !isMobile,
displaySteps,
@@ -569,6 +443,16 @@ export function SwimlaneKanbanContent({
onSelectRange,
isMultiSelectMode,
externalLinkAvailability,
+ keyboardDraft:
+ keyboard.pickedUpTaskId && keyboard.draftStepId && keyboard.draftBand && keyboard.draftOrder
+ ? {
+ taskId: keyboard.pickedUpTaskId,
+ stepId: keyboard.draftStepId,
+ band: keyboard.draftBand,
+ order: keyboard.draftOrder,
+ }
+ : null,
+ onCardKeyDown: keyboard.handleKeyDown,
});
const desktopEmptyState = getDesktopEmptyState(isMobile, displaySteps, moveTargetSteps);
@@ -585,14 +469,24 @@ export function SwimlaneKanbanContent({
});
return (
-
+ <>
+
+ {keyboard.announcement}
+
+
+ >
);
}
diff --git a/apps/web/components/kanban/swipeable-columns.tsx b/apps/web/components/kanban/swipeable-columns.tsx
index c07700f353..eb3d0ff029 100644
--- a/apps/web/components/kanban/swipeable-columns.tsx
+++ b/apps/web/components/kanban/swipeable-columns.tsx
@@ -4,8 +4,9 @@ import { useEffect, useCallback, useRef, useMemo, useState } from "react";
import useEmblaCarousel from "embla-carousel-react";
import { KanbanColumn, WorkflowStep } from "../kanban-column";
import { Task, type KanbanPresentation } from "../kanban-card";
-import { compareTasksByCreatedDesc } from "@/lib/kanban/task-order";
+import { compareStepOrder } from "@/lib/kanban/task-order";
import type { KanbanExternalLinkAvailability } from "../kanban-external-link-availability";
+import type { KeyboardReorderDraft } from "./virtualized-column-task-list";
type SwipeableColumnsProps = {
steps: WorkflowStep[];
@@ -30,6 +31,9 @@ type SwipeableColumnsProps = {
onSelectRange?: (taskId: string, orderedIds: string[]) => void;
isMultiSelectMode?: boolean;
externalLinkAvailability: KanbanExternalLinkAvailability;
+ activeTaskId?: string | null;
+ keyboardDraft?: KeyboardReorderDraft | null;
+ onCardKeyDown?: (event: React.KeyboardEvent, task: Task) => void;
};
/** Two-way sync between Embla's carousel position and the external activeIndex. */
@@ -89,6 +93,9 @@ export function SwipeableColumns({
onSelectRange,
isMultiSelectMode,
externalLinkAvailability,
+ activeTaskId,
+ keyboardDraft,
+ onCardKeyDown,
}: SwipeableColumnsProps) {
// Stable options to avoid Embla reinitializing on every activeIndex change
const [initialIndex] = useState(activeIndex);
@@ -108,7 +115,7 @@ export function SwipeableColumns({
return tasks
.filter((task) => task.workflowStepId === stepId)
.map((task) => (task.position == null ? { ...task, position: 0 } : task))
- .sort(compareTasksByCreatedDesc);
+ .sort(compareStepOrder);
},
[tasks],
);
@@ -142,6 +149,9 @@ export function SwipeableColumns({
onSelectRange={onSelectRange}
isMultiSelectMode={isMultiSelectMode}
externalLinkAvailability={externalLinkAvailability}
+ activeTaskId={activeTaskId}
+ keyboardDraft={keyboardDraft}
+ onCardKeyDown={onCardKeyDown}
hideHeader
/>
diff --git a/apps/web/components/kanban/virtualized-column-task-list.test.tsx b/apps/web/components/kanban/virtualized-column-task-list.test.tsx
new file mode 100644
index 0000000000..e2401425c5
--- /dev/null
+++ b/apps/web/components/kanban/virtualized-column-task-list.test.tsx
@@ -0,0 +1,238 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Task } from "../kanban-card";
+
+const droppableState = vi.hoisted(() => ({ isOverId: null as string | null }));
+
+// AC.7's DroppableTaskRow calls dnd-kit's real useDroppable, which needs a
+// live DndContext to resolve isOver during a pointer drag. Mocking it lets
+// the render test below drive isOver directly, isolating "does the indicator
+// actually render" from dnd-kit's own collision-detection machinery (already
+// exercised by e2e).
+vi.mock("@dnd-kit/core", () => ({
+ useDroppable: ({ id }: { id: string }) => ({
+ setNodeRef: () => {},
+ isOver: id === droppableState.isOverId,
+ }),
+}));
+
+import {
+ computeInsertionEdge,
+ computeKeyboardInsertionEdge,
+ DroppableTaskRow,
+ findTaskIndex,
+ type KeyboardReorderDraft,
+} from "./virtualized-column-task-list";
+
+function fakeTask(id: string): Task {
+ return { id, workflowStepId: "step-1", title: id, position: 0 } as Task;
+}
+
+describe("computeInsertionEdge", () => {
+ const queuedStartIndex = 2; // "a","b" admitted; "c","d" queued
+
+ it("returns null when nothing is being dragged", () => {
+ expect(computeInsertionEdge(queuedStartIndex, null, 1)).toBeNull();
+ });
+
+ it("returns null for the dragged card's own row", () => {
+ expect(computeInsertionEdge(queuedStartIndex, 1, 1)).toBeNull();
+ });
+
+ it("returns 'bottom' when the hovered row is later than the dragged row in the same band", () => {
+ expect(computeInsertionEdge(queuedStartIndex, 0, 1)).toBe("bottom");
+ });
+
+ it("returns 'top' when the hovered row is earlier than the dragged row in the same band", () => {
+ expect(computeInsertionEdge(queuedStartIndex, 1, 0)).toBe("top");
+ });
+
+ it("returns null across a band boundary (AC.11 cross-band reject shows no indicator)", () => {
+ expect(computeInsertionEdge(queuedStartIndex, 0, 3)).toBeNull();
+ });
+});
+
+describe("findTaskIndex", () => {
+ const orderedTasks = [fakeTask("a"), fakeTask("b"), fakeTask("c")];
+
+ it("returns the task's index", () => {
+ expect(findTaskIndex(orderedTasks, "b")).toBe(1);
+ });
+
+ it("returns null for a missing or absent id", () => {
+ expect(findTaskIndex(orderedTasks, "missing")).toBeNull();
+ expect(findTaskIndex(orderedTasks, null)).toBeNull();
+ expect(findTaskIndex(orderedTasks, undefined)).toBeNull();
+ });
+});
+
+describe("computeKeyboardInsertionEdge", () => {
+ function draft(overrides: Partial = {}): KeyboardReorderDraft {
+ return {
+ taskId: "a",
+ stepId: "step-1",
+ band: "admitted",
+ order: ["a", "b", "c", "d"],
+ ...overrides,
+ };
+ }
+
+ it("returns null when there is no draft", () => {
+ expect(computeKeyboardInsertionEdge(null, "step-1", "b")).toBeNull();
+ });
+
+ it("returns null when the draft belongs to a different step", () => {
+ expect(computeKeyboardInsertionEdge(draft(), "step-2", "b")).toBeNull();
+ });
+
+ it("returns null for a row not present in the draft's band order", () => {
+ expect(computeKeyboardInsertionEdge(draft(), "step-1", "queued-task")).toBeNull();
+ });
+
+ it("returns null for the dragged card's own row", () => {
+ expect(computeKeyboardInsertionEdge(draft(), "step-1", "a")).toBeNull();
+ });
+
+ it("returns 'bottom' on the row immediately before the draft's position", () => {
+ expect(
+ computeKeyboardInsertionEdge(draft({ order: ["b", "a", "c", "d"] }), "step-1", "b"),
+ ).toBe("bottom");
+ });
+
+ it("returns 'top' on the row immediately after the draft's position", () => {
+ expect(
+ computeKeyboardInsertionEdge(draft({ order: ["b", "a", "c", "d"] }), "step-1", "c"),
+ ).toBe("top");
+ });
+
+ it("tracks the draft's neighbors by identity after multiple moves, not by original DOM index", () => {
+ // "a" starts at index 0 ([a,b,c,d]) and is moved down twice, landing
+ // between "c" and "d" ([b,c,a,d]). The DOM never re-renders (only the
+ // draft evolves), so this proves the indicator follows "a"'s actual
+ // neighbors rather than whatever row sits at a numerically-adjacent DOM
+ // index (a regression that would flag "b" - "a"'s original DOM
+ // neighbor, not its current one).
+ const moved = draft({ order: ["b", "c", "a", "d"] });
+ expect(computeKeyboardInsertionEdge(moved, "step-1", "b")).toBeNull();
+ expect(computeKeyboardInsertionEdge(moved, "step-1", "c")).toBe("bottom");
+ expect(computeKeyboardInsertionEdge(moved, "step-1", "d")).toBe("top");
+ });
+});
+
+// AC.7: "while a card is dragged over its own band, show which edge of the
+// hovered card the drop would insert next to". The suites above only cover
+// the math (computeInsertionEdge / computeKeyboardInsertionEdge); nothing
+// asserted the indicator itself ever reaches the DOM. These tests render
+// DroppableTaskRow directly (bypassing the virtualizer and the full
+// KanbanCard tree, neither of which this indicator's rendering depends on)
+// and check the actual border classes and data-testid it produces.
+const INDICATOR_BOTTOM_TESTID = "kanban-insertion-indicator-bottom";
+const INDICATOR_TOP_TESTID = "kanban-insertion-indicator-top";
+
+describe("DroppableTaskRow (AC.7 insertion-point indicator)", () => {
+ afterEach(() => {
+ cleanup();
+ droppableState.isOverId = null;
+ });
+
+ it("renders the bottom-edge indicator while the row is a pointer drag's drop target", () => {
+ droppableState.isOverId = "row-b";
+ render(
+ {}}
+ insertionEdge="bottom"
+ forceShowIndicator={false}
+ >
+ card
+ ,
+ );
+
+ const indicator = screen.getByTestId(INDICATOR_BOTTOM_TESTID);
+ expect(indicator.className).toContain("border-b-2");
+ expect(indicator.className).toContain("border-primary");
+ expect(indicator.className).not.toContain("border-t-2");
+ });
+
+ it("renders the top-edge indicator while the row is a pointer drag's drop target", () => {
+ droppableState.isOverId = "row-b";
+ render(
+ {}}
+ insertionEdge="top"
+ forceShowIndicator={false}
+ >
+ card
+ ,
+ );
+
+ const indicator = screen.getByTestId(INDICATOR_TOP_TESTID);
+ expect(indicator.className).toContain("border-t-2");
+ expect(indicator.className).toContain("border-primary");
+ expect(indicator.className).not.toContain("border-b-2");
+ });
+
+ it("renders the indicator for a keyboard reorder's adjacent row even though isOver is false", () => {
+ // forceShowIndicator is how the keyboard path (no pointer, so dnd-kit
+ // never reports isOver) drives the same visual indicator as a pointer
+ // drag (AC.12).
+ droppableState.isOverId = null;
+ render(
+ {}}
+ insertionEdge="bottom"
+ forceShowIndicator={true}
+ >
+ card
+ ,
+ );
+
+ expect(screen.getByTestId(INDICATOR_BOTTOM_TESTID)).toBeTruthy();
+ });
+
+ it("renders no indicator when the row is not a drop target and no keyboard draft targets it", () => {
+ droppableState.isOverId = null;
+ render(
+ {}}
+ insertionEdge="bottom"
+ forceShowIndicator={false}
+ >
+ card
+ ,
+ );
+
+ expect(screen.queryByTestId(INDICATOR_BOTTOM_TESTID)).toBeNull();
+ expect(screen.queryByTestId(INDICATOR_TOP_TESTID)).toBeNull();
+ });
+
+ it("renders no indicator when isOver is true but insertionEdge is null (AC.11 cross-band reject)", () => {
+ droppableState.isOverId = "row-b";
+ render(
+ {}}
+ insertionEdge={null}
+ forceShowIndicator={false}
+ >
+ card
+ ,
+ );
+
+ expect(screen.queryByTestId(INDICATOR_BOTTOM_TESTID)).toBeNull();
+ expect(screen.queryByTestId(INDICATOR_TOP_TESTID)).toBeNull();
+ });
+});
diff --git a/apps/web/components/kanban/virtualized-column-task-list.tsx b/apps/web/components/kanban/virtualized-column-task-list.tsx
index a882f2e39c..582103447f 100644
--- a/apps/web/components/kanban/virtualized-column-task-list.tsx
+++ b/apps/web/components/kanban/virtualized-column-task-list.tsx
@@ -1,18 +1,28 @@
"use client";
-import { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react";
+import { memo, useCallback, useLayoutEffect, useRef } from "react";
+import { useDroppable } from "@dnd-kit/core";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useTranslation } from "react-i18next";
+import { cn } from "@kandev/ui/lib/utils";
import {
KanbanCard,
resolveTaskRepositoryChips,
Task,
type KanbanPresentation,
} from "../kanban-card";
-import type { Repository } from "@/lib/types/http";
+import type { ReorderBand, Repository } from "@/lib/types/http";
import type { WorkflowStep } from "../kanban-column";
import type { KanbanExternalLinkAvailability } from "../kanban-external-link-availability";
+/** A card picked up for a keyboard reorder gesture (REQ-TASKS-KANBAN-TASK-REORDERING-001.12). */
+export type KeyboardReorderDraft = {
+ taskId: string;
+ stepId: string;
+ band: ReorderBand;
+ order: string[];
+};
+
type VirtualizedColumnTaskListProps = {
onContentHeightChange?: (height: number, element: HTMLDivElement) => void;
orderedTasks: Task[];
@@ -28,6 +38,11 @@ type VirtualizedColumnTaskListProps = {
deletingTaskId?: string | null;
archivingTaskId?: string | null;
selectedIds?: Set;
+ /** The task currently being dragged anywhere on the board, if any (AC.7's insertion indicator). */
+ activeTaskId?: string | null;
+ /** The card currently picked up via the keyboard, if any (AC.12). */
+ keyboardDraft?: KeyboardReorderDraft | null;
+ onCardKeyDown?: (event: React.KeyboardEvent, task: Task) => void;
onPreviewTask: (task: Task) => void;
onOpenTask: (task: Task) => void;
onEditTask: (task: Task) => void;
@@ -39,75 +54,6 @@ type VirtualizedColumnTaskListProps = {
isMultiSelectMode?: boolean;
};
-type VirtualizedKanbanCardProps = Omit<
- VirtualizedColumnTaskListProps,
- "orderedTasks" | "queuedStartIndex" | "queuedCount" | "deletingTaskId" | "archivingTaskId"
-> & {
- task: Task;
- columnTaskIds: string[];
- isDeleting: boolean;
- isArchiving: boolean;
-};
-
-const VirtualizedKanbanCard = memo(function VirtualizedKanbanCard({
- task,
- columnTaskIds,
- step,
- steps,
- presentation,
- workspaceId,
- repositories,
- externalLinkAvailability,
- showMaximizeButton,
- isDeleting,
- isArchiving,
- selectedIds,
- onPreviewTask,
- onOpenTask,
- onEditTask,
- onDeleteTask,
- onArchiveTask,
- onMoveTask,
- onToggleSelect,
- onSelectRange,
- isMultiSelectMode,
-}: VirtualizedKanbanCardProps) {
- const displayTask = useMemo(() => queuedTaskWithTitle(task, steps, step), [step, steps, task]);
- const repositoryChips = useMemo(
- () => resolveTaskRepositoryChips(task, repositories),
- [repositories, task],
- );
- const handleRangeSelect = useCallback(
- (taskId: string) => onSelectRange?.(taskId, columnTaskIds),
- [columnTaskIds, onSelectRange],
- );
-
- return (
-
- );
-});
-
function useStableTaskIds(tasks: Task[]): string[] {
const previousRef = useRef([]);
const next = tasks.map((task) => task.id);
@@ -132,6 +78,296 @@ function useStableExternalLinkAvailability(
return isUnchanged ? previous : availability;
}
+/**
+ * Wraps one rendered card so it is also a dnd-kit drop target (`over.id`
+ * resolves to a task id, enabling within-band reorder classification) while
+ * staying measured by the virtualizer. Renders the AC.7 insertion-point
+ * indicator when this card is the current drop target for a same-band drag.
+ */
+export function DroppableTaskRow({
+ taskId,
+ index,
+ top,
+ measureElement,
+ insertionEdge,
+ forceShowIndicator,
+ children,
+}: {
+ taskId: string;
+ index: number;
+ top: number;
+ measureElement: (node: HTMLDivElement | null) => void;
+ insertionEdge: "top" | "bottom" | null;
+ /** True while a keyboard reorder (no pointer drag, so no `isOver`) targets this row. */
+ forceShowIndicator: boolean;
+ children: React.ReactNode;
+}) {
+ const { setNodeRef, isOver } = useDroppable({ id: taskId });
+ const mergedRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ measureElement(node);
+ setNodeRef(node);
+ },
+ [measureElement, setNodeRef],
+ );
+ const showIndicator = (isOver || forceShowIndicator) && insertionEdge !== null;
+
+ return (
+
+ {children}
+
+ );
+}
+
+/**
+ * AC.7: while a card is dragged over its own band, show which edge of the
+ * hovered card the drop would insert next to. `null` for a different band
+ * (AC.11's cross-band reject) or when nothing is being dragged. Takes the
+ * dragged/picked-up card's index directly rather than resolving it from an
+ * id, so the same math serves both the pointer path (its static starting
+ * index, gated by that row's own `isOver`) and the keyboard path (the
+ * draft's current virtual index, gated by strict adjacency below).
+ */
+export function computeInsertionEdge(
+ queuedStartIndex: number,
+ activeIndex: number | null,
+ index: number,
+): "top" | "bottom" | null {
+ if (activeIndex === null || activeIndex === index) return null;
+ if (activeIndex < queuedStartIndex !== index < queuedStartIndex) return null;
+ return activeIndex < index ? "bottom" : "top";
+}
+
+export function findTaskIndex(
+ orderedTasks: Task[],
+ taskId: string | null | undefined,
+): number | null {
+ if (!taskId) return null;
+ const index = orderedTasks.findIndex((task) => task.id === taskId);
+ return index === -1 ? null : index;
+}
+
+/**
+ * The insertion edge to render on a rendered row for an in-progress keyboard
+ * reorder (REQ-TASKS-KANBAN-TASK-REORDERING-001.12), or `null` if that row is
+ * not adjacent to the draft's current position. Unlike the pointer path, this
+ * cannot compare numeric indices: `draft.order` is the band-local proposed
+ * order and evolves with every arrow press, while keyboard reorder never
+ * live-reorders the DOM, so a rendered row's index stays fixed to the
+ * unmoved order - after more than one move, the two index spaces name
+ * different tasks at the same offset. Row identity is compared by task id
+ * against the draft's immediate neighbors instead.
+ */
+export function computeKeyboardInsertionEdge(
+ draft: KeyboardReorderDraft | null | undefined,
+ stepId: string,
+ rowTaskId: string,
+): "top" | "bottom" | null {
+ if (!draft || draft.stepId !== stepId) return null;
+ const draftIndex = draft.order.indexOf(draft.taskId);
+ if (draftIndex === -1) return null;
+ const rowIndex = draft.order.indexOf(rowTaskId);
+ if (rowIndex === -1) return null;
+ if (rowIndex === draftIndex - 1) return "bottom";
+ if (rowIndex === draftIndex + 1) return "top";
+ return null;
+}
+
+type VirtualizedTaskRowProps = Pick<
+ VirtualizedColumnTaskListProps,
+ | "step"
+ | "steps"
+ | "presentation"
+ | "workspaceId"
+ | "repositories"
+ | "externalLinkAvailability"
+ | "showMaximizeButton"
+ | "selectedIds"
+ | "keyboardDraft"
+ | "onCardKeyDown"
+ | "onPreviewTask"
+ | "onOpenTask"
+ | "onEditTask"
+ | "onDeleteTask"
+ | "onArchiveTask"
+ | "onMoveTask"
+ | "onToggleSelect"
+ | "onSelectRange"
+ | "isMultiSelectMode"
+> & {
+ task: Task;
+ queuedCount: number;
+ queuedStartIndex: number;
+ virtualIndex: number;
+ top: number;
+ measureElement: (node: HTMLDivElement | null) => void;
+ insertionEdge: "top" | "bottom" | null;
+ forceShowIndicator: boolean;
+ columnTaskIds: string[];
+ isDeleting: boolean;
+ isArchiving: boolean;
+};
+
+function rowIdentityEqual(
+ previous: VirtualizedTaskRowProps,
+ next: VirtualizedTaskRowProps,
+): boolean {
+ return (
+ previous.task === next.task &&
+ previous.queuedCount === next.queuedCount &&
+ previous.queuedStartIndex === next.queuedStartIndex &&
+ previous.virtualIndex === next.virtualIndex &&
+ previous.top === next.top &&
+ previous.columnTaskIds === next.columnTaskIds &&
+ previous.insertionEdge === next.insertionEdge &&
+ previous.forceShowIndicator === next.forceShowIndicator &&
+ previous.keyboardDraft === next.keyboardDraft
+ );
+}
+
+function rowDisplayPropsEqual(
+ previous: VirtualizedTaskRowProps,
+ next: VirtualizedTaskRowProps,
+): boolean {
+ return (
+ previous.step === next.step &&
+ previous.steps === next.steps &&
+ previous.presentation === next.presentation &&
+ previous.workspaceId === next.workspaceId &&
+ previous.repositories === next.repositories &&
+ previous.externalLinkAvailability === next.externalLinkAvailability &&
+ previous.showMaximizeButton === next.showMaximizeButton &&
+ previous.isDeleting === next.isDeleting &&
+ previous.isArchiving === next.isArchiving &&
+ previous.selectedIds === next.selectedIds &&
+ previous.isMultiSelectMode === next.isMultiSelectMode
+ );
+}
+
+function rowCallbacksEqual(
+ previous: VirtualizedTaskRowProps,
+ next: VirtualizedTaskRowProps,
+): boolean {
+ return (
+ previous.onCardKeyDown === next.onCardKeyDown &&
+ previous.onPreviewTask === next.onPreviewTask &&
+ previous.onOpenTask === next.onOpenTask &&
+ previous.onEditTask === next.onEditTask &&
+ previous.onDeleteTask === next.onDeleteTask &&
+ previous.onArchiveTask === next.onArchiveTask &&
+ previous.onMoveTask === next.onMoveTask &&
+ previous.onToggleSelect === next.onToggleSelect &&
+ previous.onSelectRange === next.onSelectRange
+ );
+}
+
+/**
+ * `measureElement` is excluded: it is a virtualizer-bound ref callback whose
+ * identity is an implementation detail of the (possibly mocked) virtualizer
+ * instance, not a signal that this row's rendered output should change.
+ */
+function virtualizedTaskRowPropsEqual(
+ previous: VirtualizedTaskRowProps,
+ next: VirtualizedTaskRowProps,
+): boolean {
+ return (
+ rowIdentityEqual(previous, next) &&
+ rowDisplayPropsEqual(previous, next) &&
+ rowCallbacksEqual(previous, next)
+ );
+}
+
+/** One rendered card row, including its optional "Queued" section header. */
+const VirtualizedTaskRow = memo(function VirtualizedTaskRow({
+ task,
+ queuedCount,
+ queuedStartIndex,
+ virtualIndex,
+ top,
+ measureElement,
+ insertionEdge,
+ forceShowIndicator,
+ columnTaskIds,
+ step,
+ steps,
+ presentation,
+ workspaceId,
+ repositories,
+ externalLinkAvailability,
+ showMaximizeButton,
+ isDeleting,
+ isArchiving,
+ selectedIds,
+ keyboardDraft,
+ onCardKeyDown,
+ onPreviewTask,
+ onOpenTask,
+ onEditTask,
+ onDeleteTask,
+ onArchiveTask,
+ onMoveTask,
+ onToggleSelect,
+ onSelectRange,
+ isMultiSelectMode,
+}: VirtualizedTaskRowProps) {
+ const { t } = useTranslation();
+ return (
+
+ {queuedCount > 0 && virtualIndex === queuedStartIndex && (
+
+ {t("kanban:queuedSection")}
+ {queuedCount}
+
+ )}
+ onSelectRange(taskId, columnTaskIds) : undefined}
+ isMultiSelectMode={isMultiSelectMode}
+ />
+
+ );
+}, virtualizedTaskRowPropsEqual);
+
+// eslint-disable-next-line max-lines-per-function -- coordinates virtualization and pointer/keyboard insertion indicators.
export function VirtualizedColumnTaskList({
onContentHeightChange,
orderedTasks,
@@ -147,6 +383,9 @@ export function VirtualizedColumnTaskList({
deletingTaskId,
archivingTaskId,
selectedIds,
+ activeTaskId,
+ keyboardDraft,
+ onCardKeyDown,
onPreviewTask,
onOpenTask,
onEditTask,
@@ -157,7 +396,6 @@ export function VirtualizedColumnTaskList({
onSelectRange,
isMultiSelectMode,
}: VirtualizedColumnTaskListProps) {
- const { t } = useTranslation();
const scrollRef = useRef(null);
const columnTaskIds = useStableTaskIds(orderedTasks);
const stableExternalLinkAvailability =
@@ -169,6 +407,7 @@ export function VirtualizedColumnTaskList({
getItemKey: (index) => orderedTasks[index]?.id ?? index,
overscan: 5,
});
+ const pointerActiveIndex = findTaskIndex(orderedTasks, activeTaskId);
const totalHeight = virtualizer.getTotalSize();
useLayoutEffect(() => {
if (scrollRef.current) onContentHeightChange?.(totalHeight, scrollRef.current);
@@ -185,47 +424,50 @@ export function VirtualizedColumnTaskList({
const task = orderedTasks[virtualItem.index];
if (!task) return null;
+ const keyboardInsertionEdge = computeKeyboardInsertionEdge(
+ keyboardDraft,
+ step.id,
+ task.id,
+ );
+ const isKeyboardAdjacent = keyboardInsertionEdge !== null;
+ const insertionEdge = isKeyboardAdjacent
+ ? keyboardInsertionEdge
+ : computeInsertionEdge(queuedStartIndex, pointerActiveIndex, virtualItem.index);
+
return (
-
- {queuedCount > 0 && virtualItem.index === queuedStartIndex && (
-
- {t("kanban:queuedSection")}
- {queuedCount}
-
- )}
-
-
+ task={task}
+ queuedCount={queuedCount}
+ queuedStartIndex={queuedStartIndex}
+ virtualIndex={virtualItem.index}
+ top={virtualItem.start}
+ measureElement={virtualizer.measureElement}
+ insertionEdge={insertionEdge}
+ forceShowIndicator={isKeyboardAdjacent}
+ columnTaskIds={columnTaskIds}
+ step={step}
+ steps={steps}
+ presentation={presentation}
+ workspaceId={workspaceId}
+ repositories={repositories}
+ externalLinkAvailability={stableExternalLinkAvailability}
+ showMaximizeButton={showMaximizeButton}
+ isDeleting={deletingTaskId === task.id}
+ isArchiving={archivingTaskId === task.id}
+ selectedIds={selectedIds}
+ keyboardDraft={keyboardDraft}
+ onCardKeyDown={onCardKeyDown}
+ onPreviewTask={onPreviewTask}
+ onOpenTask={onOpenTask}
+ onEditTask={onEditTask}
+ onDeleteTask={onDeleteTask}
+ onArchiveTask={onArchiveTask}
+ onMoveTask={onMoveTask}
+ onToggleSelect={onToggleSelect}
+ onSelectRange={onSelectRange}
+ isMultiSelectMode={isMultiSelectMode}
+ />
);
})}
diff --git a/apps/web/components/task/task-move-error-message.ts b/apps/web/components/task/task-move-error-message.ts
index e1e93e0079..42f3d09614 100644
--- a/apps/web/components/task/task-move-error-message.ts
+++ b/apps/web/components/task/task-move-error-message.ts
@@ -18,6 +18,7 @@ const MOVE_ERROR_TRANSLATIONS: Record = {
};
const GENERIC_MOVE_ERROR_TRANSLATION = "task:taskMoveErrorGeneric";
+const GENERIC_REORDER_ERROR_TRANSLATION = "task:taskReorderErrorGeneric";
function getTaskMoveErrorCode(error: unknown): string | null {
if (!(error instanceof ApiError) || !error.body || typeof error.body !== "object") return null;
@@ -39,6 +40,26 @@ export function getTaskMoveErrorMessage(
return fallback;
}
+/**
+ * Localized failure message for a rejected reorder request
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.20). The reorder endpoint's only
+ * caller-facing failure codes (`invalid_reorder`; `step_changed` is handled
+ * silently before this is ever called) carry no code-specific copy, so this
+ * always resolves to the one generic message for an ApiError.
+ */
+export function getTaskReorderErrorMessage(
+ error: unknown,
+ fallback: string,
+ translate?: Translate,
+): string {
+ if (translate && error instanceof ApiError) {
+ return translate(GENERIC_REORDER_ERROR_TRANSLATION);
+ }
+ if (error instanceof Error && error.message.trim()) return error.message;
+ if (typeof error === "string" && error.trim()) return error;
+ return fallback;
+}
+
/**
* The detail worth rendering beneath the headline, or null when extraction fell
* back to the headline itself. Repeating the same sentence twice reads as a
diff --git a/apps/web/components/task/task-title-hover-card.test.tsx b/apps/web/components/task/task-title-hover-card.test.tsx
index 34e2017399..e697aa8699 100644
--- a/apps/web/components/task/task-title-hover-card.test.tsx
+++ b/apps/web/components/task/task-title-hover-card.test.tsx
@@ -387,6 +387,9 @@ describe("TaskTitleHoverCard — description and parent content (AC-UI-PIPELINE-
},
},
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
},
}}
>
diff --git a/apps/web/components/threads/thread-task-actions.test.tsx b/apps/web/components/threads/thread-task-actions.test.tsx
index 13f27f90ed..0b8955a736 100644
--- a/apps/web/components/threads/thread-task-actions.test.tsx
+++ b/apps/web/components/threads/thread-task-actions.test.tsx
@@ -18,6 +18,9 @@ it("opens task A's actions from its named overflow without navigating", async ()
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
workflow: {
workflowId: "workflow",
diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts
index d6053c0c85..5fd00366b4 100644
--- a/apps/web/e2e/helpers/api-client.ts
+++ b/apps/web/e2e/helpers/api-client.ts
@@ -2563,6 +2563,7 @@ export class ApiClient {
queued_for_step_id?: string;
priority?: TaskPriority;
parent_id?: string;
+ position?: number;
metadata?: Record | null;
repositories?: Array<{
id: string;
diff --git a/apps/web/e2e/tests/kanban/kanban-reorder.spec.ts b/apps/web/e2e/tests/kanban/kanban-reorder.spec.ts
new file mode 100644
index 0000000000..829b6867d7
--- /dev/null
+++ b/apps/web/e2e/tests/kanban/kanban-reorder.spec.ts
@@ -0,0 +1,159 @@
+import { type Locator, type Page } from "@playwright/test";
+import { test, expect } from "../../fixtures/test-base";
+import { KanbanPage } from "../../pages/kanban-page";
+import { settledBoundingBox } from "../../helpers/settled-box";
+import { waitForHttp } from "../../helpers/causal-waits";
+
+const REORDER_PATH = /\/workflow-steps\/.+\/tasks\/reorder$/;
+
+/**
+ * Drags `fromCard` (the whole card is the drag source — REQ-TASKS-KANBAN-TASK-REORDERING-001.6,
+ * no grab handle) and drops it directly on `toCard`'s row. dnd-kit's
+ * `pointerWithin` collision detection resolves `over.id` to the smaller,
+ * nested card droppable rather than the enclosing column, so landing the
+ * pointer on a card's center targets that exact card.
+ */
+async function dragCardOntoCard(page: Page, fromCard: Locator, toCard: Locator) {
+ // Both boxes are read before the mouse button goes down: settledBoundingBox
+ // scrolls and polls, and doing that while the drag is active could scroll
+ // the viewport mid-drag and make startX/startY stale.
+ const from = await settledBoundingBox(fromCard);
+ const to = await settledBoundingBox(toCard);
+ const startX = from.x + from.width / 2;
+ const startY = from.y + from.height / 2;
+ await page.mouse.move(startX, startY);
+ await page.mouse.down();
+ // Exceed the 8px PointerSensor activation distance so the drag starts.
+ await page.mouse.move(startX + 12, startY, { steps: 3 });
+ await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 12 });
+ await page.mouse.up();
+}
+
+/** Titles of the cards rendered in a column, top to bottom. */
+async function columnOrder(kanban: KanbanPage, stepId: string): Promise {
+ return kanban.columnByStepId(stepId).locator('[data-testid="task-card-title"]').allTextContents();
+}
+
+test.describe("Kanban card reordering", () => {
+ test("pointer drag reorders cards within a column and persists across reload", async ({
+ testPage,
+ apiClient,
+ seedData,
+ }) => {
+ const placement = {
+ workflow_id: seedData.workflowId,
+ workflow_step_id: seedData.startStepId,
+ };
+ // Created sequentially: arrival position is assigned max+1 per create, so
+ // this fixes the starting order A, B, C (position ascending, AC.1).
+ const taskA = await apiClient.createTask(seedData.workspaceId, "Reorder drag A", placement);
+ const taskB = await apiClient.createTask(seedData.workspaceId, "Reorder drag B", placement);
+ const taskC = await apiClient.createTask(seedData.workspaceId, "Reorder drag C", placement);
+
+ const kanban = new KanbanPage(testPage);
+ await kanban.goto();
+
+ await expect(kanban.taskCard(taskC.id)).toBeVisible();
+ await expect
+ .poll(() => columnOrder(kanban, seedData.startStepId))
+ .toEqual(["Reorder drag A", "Reorder drag B", "Reorder drag C"]);
+
+ const reorderResponse = waitForHttp(testPage, "PUT", REORDER_PATH);
+ await dragCardOntoCard(testPage, kanban.taskCard(taskC.id), kanban.taskCard(taskA.id));
+ await reorderResponse;
+
+ await expect
+ .poll(() => columnOrder(kanban, seedData.startStepId))
+ .toEqual(["Reorder drag C", "Reorder drag A", "Reorder drag B"]);
+ await expect
+ .poll(async () => {
+ const [a, b, c] = await Promise.all([
+ apiClient.getTask(taskA.id),
+ apiClient.getTask(taskB.id),
+ apiClient.getTask(taskC.id),
+ ]);
+ return { a: a.position, b: b.position, c: c.position };
+ })
+ .toEqual({ c: 0, a: 1, b: 2 });
+
+ // A second drag, without a reload in between: the board's fetched task
+ // array is still in creation order (A, B, C) while true step order is
+ // now C, A, B (REQ-TASKS-KANBAN-TASK-REORDERING-001.15) — this is
+ // exactly the case an unsorted band computation gets wrong (drags the
+ // card to the opposite end of where the gesture pointed).
+ const secondReorderResponse = waitForHttp(testPage, "PUT", REORDER_PATH);
+ await dragCardOntoCard(testPage, kanban.taskCard(taskB.id), kanban.taskCard(taskC.id));
+ await secondReorderResponse;
+
+ await expect
+ .poll(() => columnOrder(kanban, seedData.startStepId))
+ .toEqual(["Reorder drag B", "Reorder drag C", "Reorder drag A"]);
+ await expect
+ .poll(async () => {
+ const [a, b, c] = await Promise.all([
+ apiClient.getTask(taskA.id),
+ apiClient.getTask(taskB.id),
+ apiClient.getTask(taskC.id),
+ ]);
+ return { b: b.position, c: c.position, a: a.position };
+ })
+ .toEqual({ b: 0, c: 1, a: 2 });
+
+ await testPage.reload();
+ await kanban.board.waitFor({ state: "visible" });
+ await expect
+ .poll(() => columnOrder(kanban, seedData.startStepId))
+ .toEqual(["Reorder drag B", "Reorder drag C", "Reorder drag A"]);
+ });
+
+ test("keyboard reorder moves a card and persists the new order", async ({
+ testPage,
+ apiClient,
+ seedData,
+ }) => {
+ const placement = {
+ workflow_id: seedData.workflowId,
+ workflow_step_id: seedData.startStepId,
+ };
+ const taskD = await apiClient.createTask(seedData.workspaceId, "Reorder keys D", placement);
+ const taskE = await apiClient.createTask(seedData.workspaceId, "Reorder keys E", placement);
+
+ const kanban = new KanbanPage(testPage);
+ await kanban.goto();
+
+ const cardD = kanban.taskCard(taskD.id);
+ await expect(cardD).toBeVisible();
+ await expect
+ .poll(() => columnOrder(kanban, seedData.startStepId))
+ .toEqual(["Reorder keys D", "Reorder keys E"]);
+
+ // Space picks the card up: announce its place in the band (position 1 of 2).
+ await cardD.focus();
+ await testPage.keyboard.press(" ");
+ await expect(cardD).toHaveAttribute("aria-grabbed", "true");
+ const announcement = testPage.getByTestId("kanban-reorder-announcement");
+ await expect(announcement).toContainText("position 1 of 2", { timeout: 5_000 });
+
+ // Arrow Down moves it one place — announce position 2 of 2.
+ await testPage.keyboard.press("ArrowDown");
+ await expect(announcement).toContainText("position 2 of 2", { timeout: 5_000 });
+
+ const reorderResponse = waitForHttp(testPage, "PUT", REORDER_PATH);
+ await testPage.keyboard.press(" ");
+ await reorderResponse;
+ await expect(cardD).not.toHaveAttribute("aria-grabbed", "true");
+
+ await expect
+ .poll(() => columnOrder(kanban, seedData.startStepId))
+ .toEqual(["Reorder keys E", "Reorder keys D"]);
+ await expect
+ .poll(async () => {
+ const [d, e] = await Promise.all([
+ apiClient.getTask(taskD.id),
+ apiClient.getTask(taskE.id),
+ ]);
+ return { d: d.position, e: e.position };
+ })
+ .toEqual({ e: 0, d: 1 });
+ });
+});
diff --git a/apps/web/e2e/tests/kanban/mobile-kanban-reorder.spec.ts b/apps/web/e2e/tests/kanban/mobile-kanban-reorder.spec.ts
new file mode 100644
index 0000000000..bec7591395
--- /dev/null
+++ b/apps/web/e2e/tests/kanban/mobile-kanban-reorder.spec.ts
@@ -0,0 +1,111 @@
+import { type CDPSession, type Locator, type Page } from "@playwright/test";
+import { test, expect } from "../../fixtures/test-base";
+import { MobileKanbanPage } from "../../pages/mobile-kanban-page";
+import { settledBoundingBox } from "../../helpers/settled-box";
+import { dwell, waitForHttp } from "../../helpers/causal-waits";
+
+const REORDER_PATH = /\/workflow-steps\/.+\/tasks\/reorder$/;
+
+/**
+ * Touch-drags `fromCard` onto `toCard`'s row via CDP touch events. dnd-kit's
+ * TouchSensor arms a 250ms activation timer on touchstart and only starts the
+ * drag if the touch is still held when it fires and then moves >5px
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.6). Cards don't live-reorder mid-drag
+ * (only the insertion indicator does), so both boxes are stable to read
+ * up front.
+ */
+async function touchDragCardOntoCard(
+ page: Page,
+ cdp: CDPSession,
+ fromCard: Locator,
+ toCard: Locator,
+) {
+ const from = await settledBoundingBox(fromCard);
+ const to = await settledBoundingBox(toCard);
+ const startX = from.x + from.width / 2;
+ const startY = from.y + from.height / 2;
+ await cdp.send("Input.dispatchTouchEvent", {
+ type: "touchStart",
+ touchPoints: [{ x: startX, y: startY }],
+ });
+ await dwell(
+ page,
+ 350,
+ "library-timer",
+ "dnd-kit's TouchSensor arms a 250ms activation timer on touchStart and only starts the drag if the touch is still held when it fires",
+ );
+ const endX = to.x + to.width / 2;
+ const endY = to.y + to.height / 2;
+ for (let i = 1; i <= 10; i++) {
+ await cdp.send("Input.dispatchTouchEvent", {
+ type: "touchMove",
+ touchPoints: [
+ { x: startX + ((endX - startX) * i) / 10, y: startY + ((endY - startY) * i) / 10 },
+ ],
+ });
+ }
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] });
+}
+
+async function columnOrder(page: Page): Promise {
+ return page
+ .getByTestId("mobile-kanban-layout")
+ .locator('[data-testid="task-card-title"]')
+ .allTextContents();
+}
+
+test.describe("Mobile kanban card reordering", () => {
+ test("touch drag reorders cards within a column and persists across reload", async ({
+ testPage,
+ apiClient,
+ seedData,
+ }) => {
+ const placement = {
+ workflow_id: seedData.workflowId,
+ workflow_step_id: seedData.startStepId,
+ };
+ // Created sequentially: arrival position is assigned max+1 per create, so
+ // this fixes the starting order A, B, C (position ascending, AC.1).
+ const taskA = await apiClient.createTask(seedData.workspaceId, "Mobile reorder A", placement);
+ const taskB = await apiClient.createTask(seedData.workspaceId, "Mobile reorder B", placement);
+ const taskC = await apiClient.createTask(seedData.workspaceId, "Mobile reorder C", placement);
+
+ const mobile = new MobileKanbanPage(testPage);
+ await mobile.goto();
+
+ await expect(mobile.taskCard(taskC.id)).toBeVisible();
+ await expect
+ .poll(() => columnOrder(testPage))
+ .toEqual(["Mobile reorder A", "Mobile reorder B", "Mobile reorder C"]);
+
+ const cdp = await testPage.context().newCDPSession(testPage);
+ const reorderResponse = waitForHttp(testPage, "PUT", REORDER_PATH);
+ await touchDragCardOntoCard(
+ testPage,
+ cdp,
+ mobile.taskCard(taskC.id),
+ mobile.taskCard(taskA.id),
+ );
+ await reorderResponse;
+
+ await expect
+ .poll(() => columnOrder(testPage))
+ .toEqual(["Mobile reorder C", "Mobile reorder A", "Mobile reorder B"]);
+ await expect
+ .poll(async () => {
+ const [a, b, c] = await Promise.all([
+ apiClient.getTask(taskA.id),
+ apiClient.getTask(taskB.id),
+ apiClient.getTask(taskC.id),
+ ]);
+ return { a: a.position, b: b.position, c: c.position };
+ })
+ .toEqual({ c: 0, a: 1, b: 2 });
+
+ await testPage.reload();
+ await mobile.board.waitFor({ state: "visible" });
+ await expect
+ .poll(() => columnOrder(testPage))
+ .toEqual(["Mobile reorder C", "Mobile reorder A", "Mobile reorder B"]);
+ });
+});
diff --git a/apps/web/e2e/tests/kanban/swimlane-height.spec.ts b/apps/web/e2e/tests/kanban/swimlane-height.spec.ts
index 19d97d24d7..fbaae5d8d1 100644
--- a/apps/web/e2e/tests/kanban/swimlane-height.spec.ts
+++ b/apps/web/e2e/tests/kanban/swimlane-height.spec.ts
@@ -128,7 +128,11 @@ test("dense and sparse workflows size independently and keep the final task reac
test.setTimeout(120_000);
await testPage.setViewportSize({ width: 1440, height: 900 });
await withHeightWorkflows(apiClient, seedData, async (second) => {
- await seedLargeColumnTasks(apiClient, seedData, "Dense height", 439);
+ const denseTaskCount = 439;
+ await seedLargeColumnTasks(apiClient, seedData, "Dense height", denseTaskCount);
+ const { tasks } = await apiClient.listTasks(seedData.workspaceId);
+ const finalTask = tasks.find((task) => task.title === `Dense height ${denseTaskCount}`);
+ if (!finalTask) throw new Error("final dense task was not created");
const kanban = new KanbanPage(testPage);
await kanban.goto();
const dense = kanban.columnByStepId(seedData.startStepId);
@@ -137,13 +141,13 @@ test("dense and sparse workflows size independently and keep the final task reac
await expect.poll(async () => (await sparse.boundingBox())?.height).toBe(200);
await expectBoundedMountedCards(dense);
await scrollColumnToBottom(dense.getByTestId("kanban-column-scroll"));
- const oldest = dense.getByTestId(`task-card-${second.seedWorkflowTaskId}`);
- await expect(oldest).toBeInViewport();
+ const finalCard = dense.getByTestId(`task-card-${finalTask.id}`);
+ await expect(finalCard).toBeInViewport();
await expectBoundedMountedCards(dense);
expect(await taskCards(dense).count()).toBeLessThan(50);
await expectNoDocumentOverflow(testPage);
- await oldest.click();
- await expect(testPage).toHaveURL(new RegExp(`/t/${second.seedWorkflowTaskId}`));
+ await finalCard.click();
+ await expect(testPage).toHaveURL(new RegExp(`/t/${finalTask.id}`));
});
});
diff --git a/apps/web/e2e/tests/kanban/task-multi-select.spec.ts b/apps/web/e2e/tests/kanban/task-multi-select.spec.ts
index 7d3d28e4e7..8af9527e64 100644
--- a/apps/web/e2e/tests/kanban/task-multi-select.spec.ts
+++ b/apps/web/e2e/tests/kanban/task-multi-select.spec.ts
@@ -217,4 +217,81 @@ test.describe("Multi-select bulk actions", () => {
// Task should be visible in the target column
await expect(kanban.taskCardInColumn("MS Move Task", targetStep.id)).toBeVisible();
});
+
+ // REQ-TASKS-KANBAN-TASK-REORDERING-001.29 (F34): bulk move must land the
+ // selected tasks in a deterministic order derived from their source
+ // position, not from selection click order or network arrival order. The
+ // kanban multi-select bulk-move path previously fanned out one concurrent
+ // HTTP call per task with a caller-assigned `position: i`, so the final
+ // order depended on which request the server happened to receive first — a
+ // race that would make an order assertion here flaky by construction if the
+ // underlying fix regressed. Selecting the tasks in reverse order (and
+ // asserting against their creation order, not click order) pins that this
+ // is not an accident of how the test happens to click.
+ test("bulk move lands tasks in deterministic source order (AC.29)", async ({
+ testPage,
+ apiClient,
+ seedData,
+ }) => {
+ const targetStep = seedData.steps.find((s) => s.id !== seedData.startStepId);
+ if (!targetStep) {
+ test.skip(true, "Workflow has only one step — cannot test move");
+ return;
+ }
+
+ const placement = {
+ workflow_id: seedData.workflowId,
+ workflow_step_id: seedData.startStepId,
+ };
+ // Created sequentially so arrival position (max+1 per create) fixes a
+ // known source order: first=0, second=1, third=2, fourth=3.
+ const first = await apiClient.createTask(seedData.workspaceId, "MS Order 1", placement);
+ const second = await apiClient.createTask(seedData.workspaceId, "MS Order 2", placement);
+ const third = await apiClient.createTask(seedData.workspaceId, "MS Order 3", placement);
+ const fourth = await apiClient.createTask(seedData.workspaceId, "MS Order 4", placement);
+
+ const kanban = new KanbanPage(testPage);
+ await kanban.goto();
+
+ // Select in reverse of source order — the resulting order must not
+ // reflect this click order.
+ await kanban.selectTask(fourth.id);
+ await kanban.selectTask(third.id);
+ await kanban.selectTask(second.id);
+ await kanban.selectTask(first.id);
+ await expect(kanban.multiSelectToolbar).toContainText("4 selected");
+
+ await kanban.bulkMoveButton.click();
+ const targetOption = kanban.bulkMoveStepOption(targetStep.id);
+ await expect(targetOption).toBeVisible();
+ await targetOption.click();
+
+ await expect(kanban.taskCardInColumn("MS Order 4", targetStep.id)).toBeVisible({
+ timeout: 10000,
+ });
+
+ // Positions in the target step are consecutive and match source order,
+ // not selection order.
+ await expect
+ .poll(async () => {
+ const [t1, t2, t3, t4] = await Promise.all([
+ apiClient.getTask(first.id),
+ apiClient.getTask(second.id),
+ apiClient.getTask(third.id),
+ apiClient.getTask(fourth.id),
+ ]);
+ return { t1: t1.position, t2: t2.position, t3: t3.position, t4: t4.position };
+ })
+ .toEqual({ t1: 0, t2: 1, t3: 2, t4: 3 });
+
+ // The column itself renders them in that same order, top to bottom.
+ await expect
+ .poll(() =>
+ kanban
+ .columnByStepId(targetStep.id)
+ .locator('[data-testid="task-card-title"]')
+ .allTextContents(),
+ )
+ .toEqual(["MS Order 1", "MS Order 2", "MS Order 3", "MS Order 4"]);
+ });
});
diff --git a/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts b/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts
index 21408b9b8b..0499b9bf3b 100644
--- a/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts
+++ b/apps/web/hooks/domains/kanban/use-all-workflow-snapshots.ts
@@ -226,6 +226,7 @@ async function fetchAndWriteSnapshot(
wip_limit: step.wip_limit,
pull_from_step_id: step.pull_from_step_id ?? null,
stage_type: step.stage_type,
+ order_revision: step.order_revision,
}));
const stepIds = new Set(steps.map((s) => s.id));
diff --git a/apps/web/hooks/domains/kanban/use-cross-step-move.test.ts b/apps/web/hooks/domains/kanban/use-cross-step-move.test.ts
new file mode 100644
index 0000000000..d1b046ce94
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-cross-step-move.test.ts
@@ -0,0 +1,78 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Task } from "@/components/kanban-card";
+
+const mockMoveTaskById = vi.fn();
+vi.mock("@/hooks/use-task-actions", () => ({
+ useTaskActions: () => ({ moveTaskById: mockMoveTaskById }),
+}));
+
+type FakeTask = { id: string; workflowStepId: string; position: number };
+
+const WORKFLOW_ID = "wf1";
+const SOURCE_STEP = "step-source";
+const TARGET_STEP = "step-target";
+
+let storeState: {
+ kanbanMulti: { snapshots: Record };
+ setWorkflowSnapshot: (wfId: string, snapshot: { tasks: FakeTask[] }) => void;
+};
+
+function resetStore(tasks: FakeTask[]) {
+ storeState = {
+ kanbanMulti: { snapshots: { [WORKFLOW_ID]: { tasks } } },
+ setWorkflowSnapshot(wfId, snapshot) {
+ storeState.kanbanMulti.snapshots[wfId] = snapshot;
+ },
+ };
+}
+
+const store = { getState: () => storeState };
+vi.mock("@/components/state-provider", () => ({
+ useAppStoreApi: () => store,
+}));
+
+import { useCrossStepMove } from "./use-swimlane-kanban-dnd";
+
+beforeEach(() => {
+ resetStore([
+ { id: "moving", workflowStepId: SOURCE_STEP, position: 0 },
+ { id: "occupant", workflowStepId: TARGET_STEP, position: 0 },
+ ]);
+ mockMoveTaskById.mockReset();
+});
+
+describe("useCrossStepMove", () => {
+ it("moves the card to the target step without a client-computed position (server always assigns arrival position)", async () => {
+ mockMoveTaskById.mockResolvedValue({});
+ const { result } = renderHook(() => useCrossStepMove(WORKFLOW_ID));
+ const task = { id: "moving", workflowStepId: SOURCE_STEP } as Task;
+
+ await act(async () => {
+ await result.current("moving", TARGET_STEP, task);
+ });
+
+ expect(mockMoveTaskById).toHaveBeenCalledWith("moving", {
+ workflow_id: WORKFLOW_ID,
+ workflow_step_id: TARGET_STEP,
+ });
+ expect(mockMoveTaskById.mock.calls[0]?.[1]).not.toHaveProperty("position");
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "moving")?.workflowStepId).toBe(TARGET_STEP);
+ });
+
+ it("restores the original snapshot on failure", async () => {
+ mockMoveTaskById.mockRejectedValue(new Error("move failed"));
+ const onMoveError = vi.fn();
+ const { result } = renderHook(() => useCrossStepMove(WORKFLOW_ID, onMoveError));
+ const task = { id: "moving", workflowStepId: SOURCE_STEP } as Task;
+
+ await act(async () => {
+ await result.current("moving", TARGET_STEP, task);
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "moving")?.workflowStepId).toBe(SOURCE_STEP);
+ expect(onMoveError).toHaveBeenCalledWith(expect.objectContaining({ taskId: "moving" }));
+ });
+});
diff --git a/apps/web/hooks/domains/kanban/use-keyboard-reorder.test.ts b/apps/web/hooks/domains/kanban/use-keyboard-reorder.test.ts
new file mode 100644
index 0000000000..cc44e7bd66
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-keyboard-reorder.test.ts
@@ -0,0 +1,193 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Task } from "@/components/kanban-card";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, params?: Record) =>
+ params ? `${key}:${JSON.stringify(params)}` : key,
+ }),
+}));
+
+const reorderBand = vi.fn();
+let bandPending = false;
+vi.mock("./use-step-reorder", () => ({
+ useStepReorder: () => ({
+ reorderBand: (...args: unknown[]) => reorderBand(...args),
+ isBandPending: () => bandPending,
+ }),
+}));
+
+import { useKeyboardReorder } from "./use-keyboard-reorder";
+
+const WORKFLOW_ID = "wf1";
+const STEP_ID = "step-1";
+
+function admittedTask(id: string, position: number): Task {
+ return { id, title: id, workflowStepId: STEP_ID, position, wipAdmitted: true } as Task;
+}
+
+function keyEvent(key: string) {
+ return { key, preventDefault: vi.fn() } as unknown as React.KeyboardEvent;
+}
+
+function bubbledKeyEvent(key: string) {
+ // Simulates a key event bubbling up from a focused descendant (e.g. a
+ // card action button), where target !== currentTarget.
+ return {
+ key,
+ preventDefault: vi.fn(),
+ target: {},
+ currentTarget: {},
+ } as unknown as React.KeyboardEvent;
+}
+
+beforeEach(() => {
+ reorderBand.mockReset();
+ bandPending = false;
+});
+
+describe("useKeyboardReorder", () => {
+ const tasks = [admittedTask("a", 0), admittedTask("b", 1), admittedTask("c", 2)];
+
+ it("picks a card up on Space and announces its position", () => {
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), tasks[0]);
+ });
+
+ expect(result.current.pickedUpTaskId).toBe("a");
+ expect(result.current.draftOrder).toEqual(["a", "b", "c"]);
+ expect(result.current.announcement).toContain("kanban:reorderPositionAnnouncement");
+ expect(result.current.announcement).toContain('"position":1');
+ expect(result.current.announcement).toContain('"total":3');
+ });
+
+ it("builds the draft order from position, not from the tasks array's own order (AC.15)", () => {
+ // tasks arrives in creation order while positions reflect a prior
+ // reorder: true step order by position is c(0), a(1), b(2).
+ const outOfOrderTasks = [admittedTask("a", 1), admittedTask("b", 2), admittedTask("c", 0)];
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, outOfOrderTasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), outOfOrderTasks[0]);
+ });
+
+ expect(result.current.draftOrder).toEqual(["c", "a", "b"]);
+ });
+
+ it("moves the picked-up card down one place on ArrowDown and re-announces", () => {
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), tasks[0]);
+ });
+ act(() => {
+ result.current.handleKeyDown(keyEvent("ArrowDown"), tasks[0]);
+ });
+
+ expect(result.current.draftOrder).toEqual(["b", "a", "c"]);
+ expect(result.current.announcement).toContain('"position":2');
+ });
+
+ it("ignores an arrow press that would move the card past the band edge", () => {
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), tasks[0]);
+ });
+ act(() => {
+ result.current.handleKeyDown(keyEvent("ArrowUp"), tasks[0]);
+ });
+
+ expect(result.current.draftOrder).toEqual(["a", "b", "c"]);
+ });
+
+ it("commits the draft order on Enter and clears the picked-up state", async () => {
+ reorderBand.mockResolvedValue(undefined);
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), tasks[0]);
+ });
+ act(() => {
+ result.current.handleKeyDown(keyEvent("ArrowDown"), tasks[0]);
+ });
+ await act(async () => {
+ result.current.handleKeyDown(keyEvent("Enter"), tasks[0]);
+ });
+
+ expect(reorderBand).toHaveBeenCalledWith({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "a",
+ visibleOrderAfterMove: ["b", "a", "c"],
+ });
+ expect(result.current.pickedUpTaskId).toBeNull();
+ });
+
+ it("cancels on Escape without calling reorderBand", () => {
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), tasks[0]);
+ });
+ act(() => {
+ result.current.handleKeyDown(keyEvent("Escape"), tasks[0]);
+ });
+
+ expect(result.current.pickedUpTaskId).toBeNull();
+ expect(reorderBand).not.toHaveBeenCalled();
+ });
+
+ it("refuses to pick up a card while its band has a reorder in flight (AC.27)", () => {
+ bandPending = true;
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), tasks[0]);
+ });
+
+ expect(result.current.pickedUpTaskId).toBeNull();
+ });
+
+ it("refuses to pick up a card whose band has fewer than two members (AC.32)", () => {
+ const soleTask = [admittedTask("solo", 0)];
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, soleTask));
+
+ act(() => {
+ result.current.handleKeyDown(keyEvent(" "), soleTask[0]);
+ });
+ expect(result.current.pickedUpTaskId).toBeNull();
+
+ // A second Space/Enter with nothing picked up calls pickUp again, not
+ // commit - it must keep refusing rather than issue a no-op reorder
+ // request for the single-member band.
+ act(() => {
+ result.current.handleKeyDown(keyEvent("Enter"), soleTask[0]);
+ });
+ expect(result.current.pickedUpTaskId).toBeNull();
+ expect(reorderBand).not.toHaveBeenCalled();
+ });
+});
+
+describe("useKeyboardReorder — bubbled key events", () => {
+ const tasks = [admittedTask("a", 0), admittedTask("b", 1), admittedTask("c", 2)];
+
+ it("ignores Space/Enter bubbling from a focused descendant (e.g. a card action button)", () => {
+ const { result } = renderHook(() => useKeyboardReorder(WORKFLOW_ID, tasks));
+
+ act(() => {
+ result.current.handleKeyDown(bubbledKeyEvent(" "), tasks[0]);
+ });
+ expect(result.current.pickedUpTaskId).toBeNull();
+
+ act(() => {
+ result.current.handleKeyDown(bubbledKeyEvent("Enter"), tasks[0]);
+ });
+ expect(result.current.pickedUpTaskId).toBeNull();
+ expect(reorderBand).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/hooks/domains/kanban/use-keyboard-reorder.ts b/apps/web/hooks/domains/kanban/use-keyboard-reorder.ts
new file mode 100644
index 0000000000..8d3b6daeb0
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-keyboard-reorder.ts
@@ -0,0 +1,163 @@
+"use client";
+
+import { useCallback, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { useTranslation } from "react-i18next";
+import type { Task } from "@/components/kanban-card";
+import { moveOneStep, type ArrowDirection } from "@/lib/kanban/keyboard-reorder";
+import { partitionWipTasks } from "@/lib/kanban/wip-queue";
+import type { ReorderBand } from "@/lib/types/http";
+import { useStepReorder } from "./use-step-reorder";
+
+type PickedUp = {
+ taskId: string;
+ stepId: string;
+ band: ReorderBand;
+ order: string[];
+};
+
+function bandOrderFor(tasks: Task[], stepId: string, taskId: string) {
+ const stepTasks = tasks.filter((task) => task.workflowStepId === stepId);
+ const { admitted, queued } = partitionWipTasks(stepTasks, stepId);
+ if (admitted.some((task) => task.id === taskId)) {
+ return { band: "admitted" as ReorderBand, order: admitted.map((task) => task.id) };
+ }
+ if (queued.some((task) => task.id === taskId)) {
+ return { band: "queued" as ReorderBand, order: queued.map((task) => task.id) };
+ }
+ return null;
+}
+
+/**
+ * Whether a card in bandInfo's band may be picked up: the band must resolve,
+ * have no reorder already in flight (AC.27), and - REQ-TASKS-KANBAN-TASK-REORDERING-001.32 -
+ * have at least two members, since a band that small offers no reorder at
+ * all and committing with no arrow presses would otherwise still issue a
+ * no-op reorder request.
+ */
+function canPickUp(
+ bandInfo: ReturnType,
+ stepId: string,
+ isBandPending: (stepId: string, band: ReorderBand) => boolean,
+): bandInfo is NonNullable> {
+ return bandInfo !== null && bandInfo.order.length >= 2 && !isBandPending(stepId, bandInfo.band);
+}
+
+/**
+ * Bespoke keyboard reorder (REQ-TASKS-KANBAN-TASK-REORDERING-001.12): Space
+ * or Enter picks a focused card up, Up/Down Arrow move it one place among
+ * the band members currently rendered, Space or Enter drops and commits,
+ * Escape cancels under .9. Deliberately not dnd-kit's
+ * `sortableKeyboardCoordinates` — that needs a real `SortableContext`, which
+ * the virtualized column doesn't have (see the task plan's "Design
+ * decisions" section).
+ */
+export function useKeyboardReorder(workflowId: string, tasks: Task[]) {
+ const { reorderBand, isBandPending } = useStepReorder();
+ const { t } = useTranslation("kanban");
+ const [pickedUp, setPickedUp] = useState(null);
+ const [announcement, setAnnouncement] = useState("");
+ const tasksRef = useRef(tasks);
+ tasksRef.current = tasks;
+
+ const announcePosition = useCallback(
+ (title: string, order: string[], taskId: string) => {
+ const index = order.indexOf(taskId);
+ setAnnouncement(
+ t("kanban:reorderPositionAnnouncement", {
+ title,
+ position: index + 1,
+ total: order.length,
+ }),
+ );
+ },
+ [t],
+ );
+
+ const pickUp = useCallback(
+ (task: Task) => {
+ const bandInfo = bandOrderFor(tasksRef.current, task.workflowStepId, task.id);
+ if (!canPickUp(bandInfo, task.workflowStepId, isBandPending)) return;
+ setPickedUp({
+ taskId: task.id,
+ stepId: task.workflowStepId,
+ band: bandInfo.band,
+ order: bandInfo.order,
+ });
+ announcePosition(task.title, bandInfo.order, task.id);
+ },
+ [isBandPending, announcePosition],
+ );
+
+ const move = useCallback(
+ (task: Task, direction: ArrowDirection) => {
+ setPickedUp((current) => {
+ if (!current || current.taskId !== task.id) return current;
+ const nextOrder = moveOneStep(current.order, task.id, direction);
+ if (!nextOrder) return current;
+ announcePosition(task.title, nextOrder, task.id);
+ return { ...current, order: nextOrder };
+ });
+ },
+ [announcePosition],
+ );
+
+ const commit = useCallback(
+ async (task: Task) => {
+ if (!pickedUp || pickedUp.taskId !== task.id) return;
+ const { stepId, band, order } = pickedUp;
+ setPickedUp(null);
+ await reorderBand({
+ workflowId,
+ stepId,
+ band,
+ draggedId: task.id,
+ visibleOrderAfterMove: order,
+ });
+ },
+ [pickedUp, reorderBand, workflowId],
+ );
+
+ const cancel = useCallback(() => {
+ setPickedUp(null);
+ }, []);
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent, task: Task) => {
+ // Ignore a key event bubbling up from a focused interactive
+ // descendant (e.g. the card's own action buttons) so it does not also
+ // pick up or commit a reorder in addition to that descendant's action.
+ if (event.target !== event.currentTarget) return;
+ if (pickedUp && pickedUp.taskId !== task.id) return;
+ if (event.key === " " || event.key === "Enter") {
+ event.preventDefault();
+ if (pickedUp) void commit(task);
+ else pickUp(task);
+ return;
+ }
+ if (!pickedUp) return;
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ move(task, "up");
+ } else if (event.key === "ArrowDown") {
+ event.preventDefault();
+ move(task, "down");
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ cancel();
+ }
+ },
+ [pickedUp, pickUp, move, commit, cancel],
+ );
+
+ return useMemo(
+ () => ({
+ handleKeyDown,
+ pickedUpTaskId: pickedUp?.taskId ?? null,
+ draftOrder: pickedUp?.order ?? null,
+ draftStepId: pickedUp?.stepId ?? null,
+ draftBand: pickedUp?.band ?? null,
+ announcement,
+ }),
+ [handleKeyDown, pickedUp, announcement],
+ );
+}
diff --git a/apps/web/hooks/domains/kanban/use-shared-kanban-layout-props.ts b/apps/web/hooks/domains/kanban/use-shared-kanban-layout-props.ts
index 6a4eab91b3..15acbd1dd8 100644
--- a/apps/web/hooks/domains/kanban/use-shared-kanban-layout-props.ts
+++ b/apps/web/hooks/domains/kanban/use-shared-kanban-layout-props.ts
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import type { Task } from "@/components/kanban-card";
import type { WorkflowStep } from "@/components/kanban-column";
import type { KanbanExternalLinkAvailability } from "@/components/kanban-external-link-availability";
+import type { KeyboardReorderDraft } from "@/components/kanban/virtualized-column-task-list";
export type SharedKanbanLayoutProps = {
columnHeight?: string;
@@ -25,6 +26,9 @@ export type SharedKanbanLayoutProps = {
externalLinkAvailability: KanbanExternalLinkAvailability;
temporaryStepIds: Set;
isDragging: boolean;
+ activeTaskId: string | null;
+ keyboardDraft: KeyboardReorderDraft | null;
+ onCardKeyDown: (event: React.KeyboardEvent, task: Task) => void;
};
type SharedLayoutDragState = {
@@ -36,7 +40,7 @@ type SharedLayoutDragState = {
type SharedLayoutHookOptions = Omit<
SharedKanbanLayoutProps,
- "steps" | "tasks" | "moveTaskToStep" | "temporaryStepIds" | "isDragging"
+ "steps" | "tasks" | "moveTaskToStep" | "temporaryStepIds" | "isDragging" | "activeTaskId"
> & {
drag: SharedLayoutDragState;
displayTasks: Task[];
@@ -69,6 +73,9 @@ export function useSharedKanbanLayoutProps(
externalLinkAvailability,
temporaryStepIds: drag.temporaryStepIds,
isDragging: !!drag.activeTask,
+ activeTaskId: drag.activeTask?.id ?? null,
+ keyboardDraft: options.keyboardDraft,
+ onCardKeyDown: options.onCardKeyDown,
}),
[
options.columnHeight,
@@ -92,6 +99,8 @@ export function useSharedKanbanLayoutProps(
options.onSelectRange,
options.isMultiSelectMode,
externalLinkAvailability,
+ options.keyboardDraft,
+ options.onCardKeyDown,
],
);
}
diff --git a/apps/web/hooks/domains/kanban/use-step-reorder-reconciliation.test.ts b/apps/web/hooks/domains/kanban/use-step-reorder-reconciliation.test.ts
new file mode 100644
index 0000000000..eaf0deb4d9
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-step-reorder-reconciliation.test.ts
@@ -0,0 +1,461 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "@/lib/api/client";
+
+// use-step-reorder.test.ts already sits near the file-length/function-length
+// limit, so the AC.27 in-flight reconciliation coverage gets its own file —
+// same split rationale as lib/ws/handlers/task-reordered.test.ts.
+
+const mockToast = vi.fn();
+vi.mock("@/components/toast-provider", () => ({ useToast: () => ({ toast: mockToast }) }));
+
+const reorderStepTasks = vi.fn();
+vi.mock("@/lib/api/domains/kanban-api", () => ({
+ reorderStepTasks: (...args: unknown[]) => reorderStepTasks(...args),
+}));
+
+type FakeTask = {
+ id: string;
+ workflowStepId: string;
+ position: number;
+ wipAdmitted?: boolean;
+ queuedForStepId?: string;
+};
+
+type WithheldEntry = { revision: number; tasks: Array<{ id: string; position: number }> };
+
+let storeState: {
+ kanban: { tasks: FakeTask[] };
+ kanbanMulti: {
+ snapshots: Record;
+ pendingReorderBandKeys: Record;
+ orderRevisionByStepId: Record;
+ withheldReorderByBandKey: Record;
+ };
+ setWorkflowSnapshot: (wfId: string, snapshot: { tasks: FakeTask[] }) => void;
+ hydrate: (state: { kanban?: { tasks: FakeTask[] } }) => void;
+ setBandReorderPending: (stepId: string, band: string, pending: boolean) => void;
+ setStepOrderRevision: (stepId: string, revision: number) => void;
+ setWithheldReorder: (stepId: string, band: string, payload: WithheldEntry | null) => void;
+};
+
+const WORKFLOW_ID = "wf1";
+const STEP_ID = "step-1";
+
+function admittedTask(id: string, position: number): FakeTask {
+ return { id, workflowStepId: STEP_ID, position, wipAdmitted: true };
+}
+
+function queuedTask(id: string, position: number): FakeTask {
+ return { id, workflowStepId: STEP_ID, position, wipAdmitted: false, queuedForStepId: STEP_ID };
+}
+
+function resetStore(tasks: FakeTask[]) {
+ storeState = {
+ kanban: { tasks: tasks.map((task) => ({ ...task })) },
+ kanbanMulti: {
+ snapshots: { [WORKFLOW_ID]: { tasks } },
+ pendingReorderBandKeys: {},
+ orderRevisionByStepId: {},
+ withheldReorderByBandKey: {},
+ },
+ setWorkflowSnapshot(wfId, snapshot) {
+ storeState.kanbanMulti.snapshots[wfId] = snapshot;
+ },
+ hydrate(state) {
+ if (state.kanban?.tasks) storeState.kanban.tasks = state.kanban.tasks;
+ },
+ setBandReorderPending(stepId, band, pending) {
+ const key = `${stepId}:${band}`;
+ if (pending) storeState.kanbanMulti.pendingReorderBandKeys[key] = true;
+ else delete storeState.kanbanMulti.pendingReorderBandKeys[key];
+ },
+ setStepOrderRevision(stepId, revision) {
+ storeState.kanbanMulti.orderRevisionByStepId[stepId] = revision;
+ },
+ setWithheldReorder(stepId, band, payload) {
+ const key = `${stepId}:${band}`;
+ if (payload) storeState.kanbanMulti.withheldReorderByBandKey[key] = payload;
+ else delete storeState.kanbanMulti.withheldReorderByBandKey[key];
+ },
+ };
+}
+
+const store = { getState: () => storeState };
+vi.mock("@/components/state-provider", () => ({
+ useAppStoreApi: () => store,
+ useAppStore: (selector: (s: typeof storeState) => unknown) => selector(storeState),
+}));
+
+import { useStepReorder } from "./use-step-reorder";
+
+beforeEach(() => {
+ resetStore([admittedTask("a", 0), admittedTask("b", 1), admittedTask("c", 2)]);
+ reorderStepTasks.mockReset();
+ mockToast.mockReset();
+});
+
+function deferred() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+describe("useStepReorder — in-flight reconciliation (AC.27), own-response paths", () => {
+ it("applies the withheld order instead of a stale own-response when it carries a higher revision", async () => {
+ const { promise, resolve } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "c",
+ visibleOrderAfterMove: ["c", "a", "b"],
+ });
+ });
+
+ // Simulates a WS `task.reordered` event withheld by the kanban handler
+ // while this band's request was still in flight.
+ storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`] = {
+ revision: 2,
+ tasks: [
+ { id: "a", position: 0 },
+ { id: "b", position: 1 },
+ { id: "c", position: 2 },
+ ],
+ };
+
+ await act(async () => {
+ resolve({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "c", position: 0 },
+ { id: "a", position: 1 },
+ { id: "b", position: 2 },
+ ],
+ });
+ await pending;
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(1);
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(2);
+ expect(storeState.kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(2);
+ expect(storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+
+ it("lets the response win a same-revision tie against a withheld order", async () => {
+ const { promise, resolve } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "c",
+ visibleOrderAfterMove: ["c", "a", "b"],
+ });
+ });
+
+ storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`] = {
+ revision: 1,
+ tasks: [{ id: "a", position: 77 }],
+ };
+
+ await act(async () => {
+ resolve({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "c", position: 0 },
+ { id: "a", position: 1 },
+ { id: "b", position: 2 },
+ ],
+ });
+ await pending;
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(1);
+ });
+});
+
+describe("useStepReorder — in-flight reconciliation (AC.27), conflict and sibling-band paths", () => {
+ it("reconciles against a withheld higher-revision order on a step_changed conflict too", async () => {
+ storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`] = {
+ revision: 9,
+ tasks: [
+ { id: "a", position: 10 },
+ { id: "b", position: 11 },
+ { id: "c", position: 12 },
+ ],
+ };
+ reorderStepTasks.mockRejectedValue(
+ new ApiError("conflict", 409, {
+ code: "step_changed",
+ workflow_step_id: STEP_ID,
+ revision: 5,
+ tasks: [
+ { id: "a", position: 0 },
+ { id: "c", position: 1 },
+ { id: "b", position: 2 },
+ ],
+ }),
+ );
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a", "c"],
+ });
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(10);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(11);
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(12);
+ expect(storeState.kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(9);
+ expect(storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+
+ it("does not let a stale whole-step response clobber the sibling band's already-fresher positions", async () => {
+ resetStore([
+ admittedTask("a", 0),
+ admittedTask("b", 1),
+ queuedTask("q1", 2),
+ queuedTask("q2", 3),
+ ]);
+ const { promise, resolve } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a"],
+ });
+ });
+
+ // A sibling-band WS event is applied locally while this band's request
+ // is still in flight (kanban.ts applies it immediately since only the
+ // admitted band is pending).
+ storeState.kanbanMulti.snapshots[WORKFLOW_ID] = {
+ tasks: storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks.map((t) =>
+ t.id === "q1" ? { ...t, position: 9 } : t,
+ ),
+ };
+ storeState.kanbanMulti.orderRevisionByStepId[STEP_ID] = 2;
+
+ await act(async () => {
+ resolve({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "b", position: 0 },
+ { id: "a", position: 1 },
+ // Stale queued-band snapshot from before the fresher WS update above.
+ { id: "q1", position: 2 },
+ { id: "q2", position: 3 },
+ ],
+ });
+ await pending;
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "q1")?.position).toBe(9);
+ });
+});
+
+describe("useStepReorder — whole-step reconciliation", () => {
+ it("applies the accepted whole-step response to both bands and the main board copy", async () => {
+ resetStore([
+ admittedTask("a", 0),
+ admittedTask("b", 1),
+ queuedTask("q1", 8),
+ queuedTask("q2", 9),
+ ]);
+ const { promise, resolve } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a"],
+ });
+ });
+
+ await act(async () => {
+ resolve({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "b", position: 0 },
+ { id: "a", position: 1 },
+ { id: "q1", position: 2 },
+ { id: "q2", position: 3 },
+ ],
+ });
+ await pending;
+ });
+
+ expect(storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks).toEqual([
+ expect.objectContaining({ id: "a", position: 1 }),
+ expect.objectContaining({ id: "b", position: 0 }),
+ expect.objectContaining({ id: "q1", position: 2 }),
+ expect.objectContaining({ id: "q2", position: 3 }),
+ ]);
+ expect(storeState.kanban.tasks).toEqual([
+ expect.objectContaining({ id: "a", position: 1 }),
+ expect.objectContaining({ id: "b", position: 0 }),
+ expect.objectContaining({ id: "q1", position: 2 }),
+ expect.objectContaining({ id: "q2", position: 3 }),
+ ]);
+ });
+});
+
+describe("useStepReorder — in-flight reconciliation (AC.27), plain-failure sibling-band paths", () => {
+ it("does not let a plain request failure roll back the sibling band's already-fresher positions", async () => {
+ resetStore([
+ admittedTask("a", 0),
+ admittedTask("b", 1),
+ queuedTask("q1", 2),
+ queuedTask("q2", 3),
+ ]);
+ const { promise, reject } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a"],
+ });
+ });
+
+ // A sibling-band WS event is applied locally while this band's request
+ // is still in flight, exactly as in the success-path test above.
+ storeState.kanbanMulti.snapshots[WORKFLOW_ID] = {
+ tasks: storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks.map((t) =>
+ t.id === "q1" ? { ...t, position: 9 } : t,
+ ),
+ };
+
+ await act(async () => {
+ reject(new Error("network error"));
+ await pending;
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ // The sibling (queued) band's fresher WS-applied position must survive a
+ // failure of the unrelated admitted-band request.
+ expect(tasks.find((t) => t.id === "q1")?.position).toBe(9);
+ // This band reverts to its own pre-drag positions.
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(1);
+ });
+
+ it("applies a withheld higher-revision order on a plain request failure without rolling back the sibling band", async () => {
+ resetStore([
+ admittedTask("a", 0),
+ admittedTask("b", 1),
+ queuedTask("q1", 2),
+ queuedTask("q2", 3),
+ ]);
+ const { promise, reject } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a"],
+ });
+ });
+
+ // A whole-step task.reordered event arrives while this band's request is
+ // in flight: the sibling (queued) band's positions are applied live, and
+ // this band's own positions are withheld under AC.27.
+ storeState.kanbanMulti.snapshots[WORKFLOW_ID] = {
+ tasks: storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks.map((t) =>
+ t.id === "q1" ? { ...t, position: 9 } : t,
+ ),
+ };
+ storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`] = {
+ revision: 3,
+ tasks: [
+ { id: "a", position: 20 },
+ { id: "b", position: 21 },
+ ],
+ };
+
+ await act(async () => {
+ reject(new Error("network error"));
+ await pending;
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "q1")?.position).toBe(9);
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(20);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(21);
+ expect(storeState.kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(3);
+ expect(storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+});
diff --git a/apps/web/hooks/domains/kanban/use-step-reorder.test.ts b/apps/web/hooks/domains/kanban/use-step-reorder.test.ts
new file mode 100644
index 0000000000..fe2fd76283
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-step-reorder.test.ts
@@ -0,0 +1,390 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "@/lib/api/client";
+
+const mockToast = vi.fn();
+vi.mock("@/components/toast-provider", () => ({ useToast: () => ({ toast: mockToast }) }));
+
+const reorderStepTasks = vi.fn();
+vi.mock("@/lib/api/domains/kanban-api", () => ({
+ reorderStepTasks: (...args: unknown[]) => reorderStepTasks(...args),
+}));
+
+type FakeTask = {
+ id: string;
+ workflowStepId: string;
+ position: number;
+ wipAdmitted?: boolean;
+ queuedForStepId?: string;
+};
+
+type WithheldEntry = { revision: number; tasks: Array<{ id: string; position: number }> };
+
+let storeState: {
+ kanban: { tasks: FakeTask[] };
+ kanbanMulti: {
+ snapshots: Record;
+ pendingReorderBandKeys: Record;
+ orderRevisionByStepId: Record;
+ withheldReorderByBandKey: Record;
+ };
+ hydrate: (state: { kanban?: { tasks: FakeTask[] } }) => void;
+ setWorkflowSnapshot: (wfId: string, snapshot: { tasks: FakeTask[] }) => void;
+ setBandReorderPending: (stepId: string, band: string, pending: boolean) => void;
+ setStepOrderRevision: (stepId: string, revision: number) => void;
+ setWithheldReorder: (stepId: string, band: string, payload: WithheldEntry | null) => void;
+};
+
+const WORKFLOW_ID = "wf1";
+const STEP_ID = "step-1";
+
+function admittedTask(id: string, position: number): FakeTask {
+ return { id, workflowStepId: STEP_ID, position, wipAdmitted: true };
+}
+
+function resetStore(tasks: FakeTask[]) {
+ storeState = {
+ kanban: { tasks: tasks.map((task) => ({ ...task })) },
+ kanbanMulti: {
+ snapshots: { [WORKFLOW_ID]: { tasks } },
+ pendingReorderBandKeys: {},
+ orderRevisionByStepId: {},
+ withheldReorderByBandKey: {},
+ },
+ hydrate(state) {
+ if (state.kanban?.tasks) storeState.kanban.tasks = state.kanban.tasks;
+ },
+ setWorkflowSnapshot(wfId, snapshot) {
+ storeState.kanbanMulti.snapshots[wfId] = snapshot;
+ },
+ setBandReorderPending(stepId, band, pending) {
+ const key = `${stepId}:${band}`;
+ if (pending) storeState.kanbanMulti.pendingReorderBandKeys[key] = true;
+ else delete storeState.kanbanMulti.pendingReorderBandKeys[key];
+ },
+ setStepOrderRevision(stepId, revision) {
+ storeState.kanbanMulti.orderRevisionByStepId[stepId] = revision;
+ },
+ setWithheldReorder(stepId, band, payload) {
+ const key = `${stepId}:${band}`;
+ if (payload) storeState.kanbanMulti.withheldReorderByBandKey[key] = payload;
+ else delete storeState.kanbanMulti.withheldReorderByBandKey[key];
+ },
+ };
+}
+
+const store = { getState: () => storeState };
+vi.mock("@/components/state-provider", () => ({
+ useAppStoreApi: () => store,
+ useAppStore: (selector: (s: typeof storeState) => unknown) => selector(storeState),
+}));
+
+import { useStepReorder } from "./use-step-reorder";
+
+beforeEach(() => {
+ resetStore([admittedTask("a", 0), admittedTask("b", 1), admittedTask("c", 2)]);
+ reorderStepTasks.mockReset();
+ mockToast.mockReset();
+});
+
+function deferred() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+describe("useStepReorder", () => {
+ it("submits the band's full reordered membership and applies the returned positions", async () => {
+ reorderStepTasks.mockResolvedValue({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "b", position: 0 },
+ { id: "a", position: 1 },
+ { id: "c", position: 2 },
+ ],
+ });
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a", "c"],
+ });
+ });
+
+ expect(reorderStepTasks).toHaveBeenCalledWith(STEP_ID, {
+ band: "admitted",
+ ordered_task_ids: ["b", "a", "c"],
+ });
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(1);
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(2);
+ expect(storeState.kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(1);
+ });
+
+ it("applies the optimistic order and marks the band pending before the request resolves", async () => {
+ const { promise, resolve } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "c",
+ visibleOrderAfterMove: ["c", "a", "b"],
+ });
+ });
+
+ // Optimistic order applied immediately (AC.8), before the request settles.
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(0);
+ expect(storeState.kanbanMulti.pendingReorderBandKeys[`${STEP_ID}:admitted`]).toBe(true);
+
+ await act(async () => {
+ resolve({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "c", position: 0 },
+ { id: "a", position: 1 },
+ { id: "b", position: 2 },
+ ],
+ });
+ await pending;
+ });
+
+ expect(storeState.kanbanMulti.pendingReorderBandKeys[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+
+ it("issues no request when the drop reproduces the order already displayed (AC.10)", async () => {
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "a",
+ visibleOrderAfterMove: ["a", "b", "c"],
+ });
+ });
+
+ expect(reorderStepTasks).not.toHaveBeenCalled();
+ });
+
+ it("issues no request for a band with fewer than two tasks (AC.32)", async () => {
+ resetStore([admittedTask("solo", 0)]);
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "solo",
+ visibleOrderAfterMove: ["solo"],
+ });
+ });
+
+ expect(reorderStepTasks).not.toHaveBeenCalled();
+ });
+});
+
+describe("useStepReorder — board filter membership", () => {
+ it("keeps a board-filtered-out task in the band without reordering it (AC.34)", async () => {
+ // Full membership includes "h", a task the current board filter hides;
+ // the caller (the board) only ever sees/submits a, b, c.
+ resetStore([
+ admittedTask("a", 0),
+ admittedTask("b", 1),
+ admittedTask("h", 2),
+ admittedTask("c", 3),
+ ]);
+ reorderStepTasks.mockResolvedValue({
+ workflow_step_id: STEP_ID,
+ revision: 1,
+ tasks: [
+ { id: "c", position: 0 },
+ { id: "a", position: 1 },
+ { id: "b", position: 2 },
+ { id: "h", position: 3 },
+ ],
+ });
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "c",
+ visibleOrderAfterMove: ["c", "a", "b"],
+ });
+ });
+
+ // The hidden task's full-membership order is preserved (still last,
+ // behind a and b) — only the dragged task moved.
+ expect(reorderStepTasks).toHaveBeenCalledWith(STEP_ID, {
+ band: "admitted",
+ ordered_task_ids: ["c", "a", "b", "h"],
+ });
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(1);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(2);
+ expect(tasks.find((t) => t.id === "h")?.position).toBe(3);
+ });
+});
+
+describe("useStepReorder — failure handling", () => {
+ it("reconciles silently to the authoritative order on a step_changed conflict, without a toast", async () => {
+ reorderStepTasks.mockRejectedValue(
+ new ApiError("conflict", 409, {
+ code: "step_changed",
+ workflow_step_id: STEP_ID,
+ revision: 5,
+ tasks: [
+ { id: "a", position: 0 },
+ { id: "c", position: 1 },
+ { id: "b", position: 2 },
+ ],
+ }),
+ );
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a", "c"],
+ });
+ });
+
+ expect(mockToast).not.toHaveBeenCalled();
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(1);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(2);
+ expect(storeState.kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(5);
+ expect(storeState.kanbanMulti.pendingReorderBandKeys[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+
+ it("restores the original order and shows a localized error toast on any other failure (AC.20)", async () => {
+ reorderStepTasks.mockRejectedValue(
+ new ApiError("bad request", 400, { code: "invalid_reorder" }),
+ );
+ const { result } = renderHook(() => useStepReorder());
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "b",
+ visibleOrderAfterMove: ["b", "a", "c"],
+ });
+ });
+
+ const tasks = storeState.kanbanMulti.snapshots[WORKFLOW_ID].tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(1);
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(2);
+ expect(mockToast).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Failed to reorder tasks", variant: "error" }),
+ );
+ expect(storeState.kanbanMulti.pendingReorderBandKeys[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+
+ it("refuses to start a second request for a band that already has one in flight (AC.27)", async () => {
+ const { promise } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ act(() => {
+ void result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "c",
+ visibleOrderAfterMove: ["c", "a", "b"],
+ });
+ });
+
+ await act(async () => {
+ await result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "a",
+ visibleOrderAfterMove: ["a", "c", "b"],
+ });
+ });
+
+ expect(reorderStepTasks).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("useStepReorder — withheld-order cleanup", () => {
+ it("clears a withheld order for the band when the workflow snapshot disappears before the request settles", async () => {
+ const { promise, reject } = deferred<{
+ workflow_step_id: string;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+ }>();
+ reorderStepTasks.mockReturnValue(promise);
+ const { result } = renderHook(() => useStepReorder());
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current.reorderBand({
+ workflowId: WORKFLOW_ID,
+ stepId: STEP_ID,
+ band: "admitted",
+ draggedId: "c",
+ visibleOrderAfterMove: ["c", "a", "b"],
+ });
+ });
+
+ // A published order arrives and is withheld while this request is
+ // in flight (AC.27), then the user navigates away, removing the
+ // workflow's snapshot entirely.
+ storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`] = {
+ revision: 5,
+ tasks: [
+ { id: "a", position: 0 },
+ { id: "c", position: 1 },
+ { id: "b", position: 2 },
+ ],
+ };
+ delete (storeState.kanbanMulti.snapshots as Record)[WORKFLOW_ID];
+
+ await act(async () => {
+ reject(new ApiError("network error", 0, {}));
+ await pending;
+ });
+
+ expect(storeState.kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toBeUndefined();
+ });
+});
diff --git a/apps/web/hooks/domains/kanban/use-step-reorder.ts b/apps/web/hooks/domains/kanban/use-step-reorder.ts
new file mode 100644
index 0000000000..837c66d7a5
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-step-reorder.ts
@@ -0,0 +1,299 @@
+"use client";
+
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import type { StoreApi } from "zustand";
+import { useAppStore, useAppStoreApi } from "@/components/state-provider";
+import { useToast } from "@/components/toast-provider";
+import { ApiError } from "@/lib/api/client";
+import { reorderStepTasks } from "@/lib/api/domains/kanban-api";
+import { compareStepOrder } from "@/lib/kanban/task-order";
+import { arraysEqual, mergeVisibleReorderIntoBand } from "@/lib/kanban/reorder-merge";
+import { partitionWipTasks } from "@/lib/kanban/wip-queue";
+import { getTaskReorderErrorMessage } from "@/components/task/task-move-error-message";
+import type { AppState } from "@/lib/state/app-state-types";
+import type { KanbanState, WorkflowSnapshotData } from "@/lib/state/slices/kanban/types";
+import type {
+ ReorderBand,
+ ReorderedTaskPosition,
+ ReorderStepTasksResponse,
+} from "@/lib/types/http";
+
+type SnapshotTask = KanbanState["tasks"][number];
+
+function bandOrder(tasks: SnapshotTask[], stepId: string, band: ReorderBand): SnapshotTask[] {
+ const { admitted, queued } = partitionWipTasks(tasks, stepId);
+ const stepTasks = band === "admitted" ? admitted : queued;
+ return [...stepTasks].sort(compareStepOrder);
+}
+
+function applyBandPositions(
+ tasks: SnapshotTask[],
+ stepId: string,
+ band: ReorderBand,
+ orderedIds: string[],
+ admittedCount: number,
+): SnapshotTask[] {
+ const offset = band === "admitted" ? 0 : admittedCount;
+ const positionById = new Map(orderedIds.map((id, index) => [id, offset + index]));
+ return tasks.map((task) =>
+ task.workflowStepId === stepId && positionById.has(task.id)
+ ? { ...task, position: positionById.get(task.id)! }
+ : task,
+ );
+}
+
+function bandTaskIds(tasks: SnapshotTask[], stepId: string, band: ReorderBand): Set {
+ return new Set(bandOrder(tasks, stepId, band).map((task) => task.id));
+}
+
+function reconciliationTaskIds(
+ tasks: SnapshotTask[],
+ stepId: string,
+ activeBand: ReorderBand,
+ pendingBands: Record,
+): Set {
+ const { admitted, queued } = partitionWipTasks(tasks, stepId);
+ const allowed = new Set();
+ for (const task of admitted) {
+ if (activeBand === "admitted" || !pendingBands[`${stepId}:admitted`]) allowed.add(task.id);
+ }
+ for (const task of queued) {
+ if (activeBand === "queued" || !pendingBands[`${stepId}:queued`]) allowed.add(task.id);
+ }
+ return allowed;
+}
+
+/**
+ * Applies `orderedTasks`' positions, restricted to `allowedIds` when given.
+ * Reconciliation allows the active band and any sibling band that is not also
+ * in flight, while keeping a second optimistic band untouched
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.27).
+ */
+function applyOrderedPositions(
+ tasks: SnapshotTask[],
+ orderedTasks: ReorderedTaskPosition[],
+ allowedIds?: Set,
+): SnapshotTask[] {
+ const positionById = new Map(
+ orderedTasks.filter((t) => !allowedIds || allowedIds.has(t.id)).map((t) => [t.id, t.position]),
+ );
+ return tasks.map((task) =>
+ positionById.has(task.id) ? { ...task, position: positionById.get(task.id)! } : task,
+ );
+}
+
+/**
+ * Restores `band`'s pre-drag positions (from `originalTasks`) onto the LIVE
+ * `current` snapshot, scoped to `band`'s own task ids. Used when a plain
+ * (non-409) reorder failure leaves nothing more authoritative to reconcile
+ * to: replacing the whole snapshot with `originalTasks` would also roll back
+ * any sibling-band or other-step update applied during the in-flight window
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.27).
+ */
+function restoreBandOnFailure(params: {
+ store: StoreApi;
+ workflowId: string;
+ stepId: string;
+ band: ReorderBand;
+ originalTasks: SnapshotTask[];
+ current: WorkflowSnapshotData;
+}) {
+ const { store, workflowId, stepId, band, originalTasks, current } = params;
+ const bandIds = bandTaskIds(
+ originalTasks.filter((task) => task.workflowStepId === stepId),
+ stepId,
+ band,
+ );
+ const originalPositions: ReorderedTaskPosition[] = originalTasks
+ .filter((task) => bandIds.has(task.id))
+ .map((task) => ({ id: task.id, position: task.position }));
+ store.getState().setWorkflowSnapshot(workflowId, {
+ ...current,
+ tasks: applyOrderedPositions(current.tasks, originalPositions, bandIds),
+ });
+}
+
+/**
+ * Picks the causally-later of a withheld WS order (received while this
+ * band's own request was in flight) and the request's own resolution: the
+ * higher revision wins, and the response breaks a tie since an equal
+ * revision from the withheld side was necessarily observed before this
+ * request's own commit (REQ-TASKS-KANBAN-TASK-REORDERING-001.27).
+ */
+function pickReconciledOrder(
+ withheld: { revision: number; tasks: ReorderedTaskPosition[] } | undefined,
+ response: { revision: number; tasks: ReorderedTaskPosition[] },
+): { revision: number; tasks: ReorderedTaskPosition[] } {
+ if (withheld && withheld.revision > response.revision) return withheld;
+ return response;
+}
+
+function reconcileAndApplyReorderResponse(params: {
+ store: StoreApi;
+ workflowId: string;
+ stepId: string;
+ band: ReorderBand;
+ candidate: { revision: number; tasks: ReorderedTaskPosition[] };
+}): void {
+ const { store, workflowId, stepId, band, candidate } = params;
+ const state = store.getState();
+ const current = state.kanbanMulti.snapshots[workflowId];
+ if (!current) return;
+
+ const bandKey = `${stepId}:${band}`;
+ const withheld = state.kanbanMulti.withheldReorderByBandKey[bandKey];
+ const chosen = pickReconciledOrder(withheld, candidate);
+ const recordedRevision = state.kanbanMulti.orderRevisionByStepId[stepId] ?? -1;
+ if (chosen.revision < recordedRevision) {
+ state.setWithheldReorder(stepId, band, null);
+ return;
+ }
+
+ const allowedIds = reconciliationTaskIds(
+ current.tasks,
+ stepId,
+ band,
+ state.kanbanMulti.pendingReorderBandKeys,
+ );
+ state.setWorkflowSnapshot(workflowId, {
+ ...current,
+ tasks: applyOrderedPositions(current.tasks, chosen.tasks, allowedIds),
+ });
+ state.hydrate({
+ kanban: {
+ ...state.kanban,
+ tasks: applyOrderedPositions(state.kanban.tasks, chosen.tasks, allowedIds),
+ },
+ });
+ state.setStepOrderRevision(stepId, Math.max(chosen.revision, recordedRevision));
+ state.setWithheldReorder(stepId, band, null);
+}
+
+/**
+ * Submits a within-band reorder (REQ-TASKS-KANBAN-TASK-REORDERING-001.5,
+ * .12): applies the new order optimistically, calls the reorder endpoint —
+ * the only request surface, per the frozen design — then reconciles to the
+ * server's authoritative positions. A `step_changed` conflict (.19)
+ * reconciles silently to the authoritative order carried on the error body;
+ * any other failure restores the pre-drag order and shows a localized
+ * message (.20).
+ */
+export function useStepReorder() {
+ const store = useAppStoreApi();
+ const { toast } = useToast();
+ const { t } = useTranslation("task");
+ const pendingBandKeys = useAppStore((state) => state.kanbanMulti.pendingReorderBandKeys);
+
+ const isBandPending = useCallback(
+ (stepId: string, band: ReorderBand) => Boolean(pendingBandKeys[`${stepId}:${band}`]),
+ [pendingBandKeys],
+ );
+
+ const reorderBand = useCallback(
+ async (params: {
+ workflowId: string;
+ stepId: string;
+ band: ReorderBand;
+ draggedId: string;
+ visibleOrderAfterMove: string[];
+ }) => {
+ const { workflowId, stepId, band, draggedId, visibleOrderAfterMove } = params;
+ const state = store.getState();
+ if (state.kanbanMulti.pendingReorderBandKeys[`${stepId}:${band}`]) return;
+
+ const snapshot = state.kanbanMulti.snapshots[workflowId];
+ if (!snapshot) return;
+
+ const stepTasks = snapshot.tasks.filter((task) => task.workflowStepId === stepId);
+ const currentBandOrder = bandOrder(stepTasks, stepId, band).map((task) => task.id);
+ const nextBandOrder = mergeVisibleReorderIntoBand(
+ currentBandOrder,
+ visibleOrderAfterMove,
+ draggedId,
+ );
+ if (arraysEqual(nextBandOrder, currentBandOrder)) return;
+
+ const admittedCount = partitionWipTasks(stepTasks, stepId).admitted.length;
+ const originalTasks = snapshot.tasks;
+
+ state.setWorkflowSnapshot(workflowId, {
+ ...snapshot,
+ tasks: applyBandPositions(snapshot.tasks, stepId, band, nextBandOrder, admittedCount),
+ });
+ state.setBandReorderPending(stepId, band, true);
+ const bandKey = `${stepId}:${band}`;
+
+ try {
+ const response = await reorderStepTasks(stepId, { band, ordered_task_ids: nextBandOrder });
+ const current = store.getState().kanbanMulti.snapshots[workflowId];
+ if (current) {
+ reconcileAndApplyReorderResponse({
+ store,
+ workflowId,
+ stepId,
+ band,
+ candidate: response,
+ });
+ }
+ } catch (error) {
+ const current = store.getState().kanbanMulti.snapshots[workflowId];
+ if (current) {
+ const conflictBody =
+ error instanceof ApiError &&
+ error.status === 409 &&
+ error.body &&
+ typeof error.body === "object" &&
+ Array.isArray((error.body as ReorderStepTasksResponse).tasks)
+ ? (error.body as ReorderStepTasksResponse)
+ : null;
+ if (conflictBody) {
+ // step_changed (.19): reconcile silently, no error toast.
+ reconcileAndApplyReorderResponse({
+ store,
+ workflowId,
+ stepId,
+ band,
+ candidate: conflictBody,
+ });
+ } else {
+ const withheld = store.getState().kanbanMulti.withheldReorderByBandKey[bandKey];
+ if (withheld) {
+ // A published order for this band arrived and was withheld
+ // while the (now-failed) request was in flight; it is more
+ // authoritative than this band's own pre-drag order. Reconcile
+ // against the LIVE snapshot, not `originalTasks`, so a sibling
+ // band or another step that changed during the in-flight
+ // window is preserved rather than rolled back.
+ reconcileAndApplyReorderResponse({
+ store,
+ workflowId,
+ stepId,
+ band,
+ candidate: withheld,
+ });
+ } else {
+ restoreBandOnFailure({ store, workflowId, stepId, band, originalTasks, current });
+ }
+ toast({
+ title: t("task:failedToReorderTasks"),
+ description: getTaskReorderErrorMessage(error, t("task:taskReorderErrorGeneric"), t),
+ variant: "error",
+ });
+ }
+ }
+ } finally {
+ state.setBandReorderPending(stepId, band, false);
+ // reconcileAndApply already clears this on every path that runs it;
+ // this covers the one it cannot reach, when the workflow snapshot
+ // was removed (e.g. navigation away) while the request was in
+ // flight, so a withheld order never leaks into this band's next
+ // reorder.
+ state.setWithheldReorder(stepId, band, null);
+ }
+ },
+ [store, toast, t],
+ );
+
+ return { reorderBand, isBandPending };
+}
diff --git a/apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.test.ts b/apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.test.ts
new file mode 100644
index 0000000000..bc26099073
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.test.ts
@@ -0,0 +1,132 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DragEndEvent, DragStartEvent } from "@dnd-kit/core";
+import type { Task } from "@/components/kanban-card";
+
+const reorderBand = vi.fn();
+vi.mock("@/hooks/domains/kanban/use-step-reorder", () => ({
+ useStepReorder: () => ({ reorderBand, isBandPending: () => false }),
+}));
+
+const mockMoveTaskById = vi.fn();
+vi.mock("@/hooks/use-task-actions", () => ({
+ useTaskActions: () => ({ moveTaskById: mockMoveTaskById }),
+}));
+
+const storeState = {
+ kanbanMulti: { snapshots: {} as Record },
+ setWorkflowSnapshot: vi.fn(),
+};
+const store = { getState: () => storeState };
+vi.mock("@/components/state-provider", () => ({
+ useAppStoreApi: () => store,
+}));
+
+import { useCrossStepMove, useSwimlaneKanbanDnd } from "./use-swimlane-kanban-dnd";
+
+const WORKFLOW_ID = "wf1";
+
+function makeTask(id: string, stepId: string): Task {
+ return { id, workflowStepId: stepId, title: id } as Task;
+}
+
+beforeEach(() => {
+ reorderBand.mockReset();
+ mockMoveTaskById.mockReset();
+ storeState.setWorkflowSnapshot.mockReset();
+});
+
+describe("useSwimlaneKanbanDnd — Escape/drop-outside cancellation (AC.9)", () => {
+ it("clears the active task and issues no reorder or move request on handleDragCancel", () => {
+ const tasks = [makeTask("a", "step-1"), makeTask("b", "step-1")];
+ const { result } = renderHook(() =>
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test-only cast: exercises the non-presentation hook directly
+ (useSwimlaneKanbanDnd as any)({ tasks, workflowId: WORKFLOW_ID }),
+ );
+
+ act(() => {
+ result.current.handleDragStart({ active: { id: "a" } } as DragStartEvent);
+ });
+ expect(result.current.activeTask?.id).toBe("a");
+
+ act(() => {
+ result.current.handleDragCancel();
+ });
+
+ expect(result.current.activeTask).toBeNull();
+ expect(reorderBand).not.toHaveBeenCalled();
+ expect(mockMoveTaskById).not.toHaveBeenCalled();
+ });
+
+ it("clears the active task and issues no reorder or move request when the pointer is released outside every droppable (over: null)", async () => {
+ // This is the real AC.9 drop-outside-any-band path: dnd-kit reports
+ // `over: null` on DragEndEvent (not DragCancelEvent/Escape) when the
+ // pointer is released over empty space. handleDragEnd's own `if (!over)
+ // return` is what implements the no-op — drop-classification.test.ts's
+ // "overId: null" case never actually runs in production, since
+ // classifyDrop is called after that guard.
+ const tasks = [makeTask("a", "step-1"), makeTask("b", "step-1")];
+ const { result } = renderHook(() =>
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- test-only cast: exercises the non-presentation hook directly
+ (useSwimlaneKanbanDnd as any)({ tasks, workflowId: WORKFLOW_ID }),
+ );
+
+ act(() => {
+ result.current.handleDragStart({ active: { id: "a" } } as DragStartEvent);
+ });
+ expect(result.current.activeTask?.id).toBe("a");
+
+ await act(async () => {
+ await result.current.handleDragEnd({
+ active: { id: "a" },
+ over: null,
+ } as DragEndEvent);
+ });
+
+ expect(result.current.activeTask).toBeNull();
+ expect(reorderBand).not.toHaveBeenCalled();
+ expect(mockMoveTaskById).not.toHaveBeenCalled();
+ expect(storeState.setWorkflowSnapshot).not.toHaveBeenCalled();
+ });
+});
+
+describe("useCrossStepMove — rollback on failure", () => {
+ it("reverts only the moved task's step, preserving a concurrent update to another task", async () => {
+ const taskA = makeTask("a", "step-1");
+ const taskB = makeTask("b", "step-1");
+ storeState.kanbanMulti.snapshots[WORKFLOW_ID] = { tasks: [taskA, taskB] };
+
+ let rejectMove!: (error: unknown) => void;
+ mockMoveTaskById.mockReturnValue(
+ new Promise((_resolve, reject) => {
+ rejectMove = reject;
+ }),
+ );
+
+ const { result } = renderHook(() => useCrossStepMove(WORKFLOW_ID));
+
+ let pending!: Promise;
+ act(() => {
+ pending = result.current("a", "step-2", taskA);
+ });
+
+ // A concurrent, unrelated update lands on task b while the move is
+ // still in flight — the rollback must not discard it.
+ storeState.kanbanMulti.snapshots[WORKFLOW_ID] = {
+ tasks: [
+ storeState.setWorkflowSnapshot.mock.calls.at(-1)?.[1].tasks.find((t: Task) => t.id === "a"),
+ { ...taskB, title: "b (concurrently renamed)" },
+ ],
+ };
+
+ await act(async () => {
+ rejectMove(new Error("network error"));
+ await pending;
+ });
+
+ const lastCall = storeState.setWorkflowSnapshot.mock.calls.at(-1);
+ const finalTasks = lastCall?.[1].tasks as Task[];
+ expect(finalTasks.find((t) => t.id === "a")?.workflowStepId).toBe("step-1");
+ expect(finalTasks.find((t) => t.id === "b")?.title).toBe("b (concurrently renamed)");
+ });
+});
diff --git a/apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.ts b/apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.ts
new file mode 100644
index 0000000000..7a1b48a61c
--- /dev/null
+++ b/apps/web/hooks/domains/kanban/use-swimlane-kanban-dnd.ts
@@ -0,0 +1,201 @@
+"use client";
+
+import { useCallback, useMemo, useRef, useState } from "react";
+import {
+ DragEndEvent,
+ DragStartEvent,
+ PointerSensor,
+ TouchSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { type Task } from "@/components/kanban-card";
+import type { WorkflowStep } from "@/components/kanban-column";
+import type { MoveTaskError } from "@/hooks/use-drag-and-drop";
+import { useTaskActions } from "@/hooks/use-task-actions";
+import { useAppStoreApi } from "@/components/state-provider";
+import { isOrphanMoveTarget } from "@/components/kanban/swimlane-orphan-display";
+import type { KanbanState } from "@/lib/state/slices/kanban/types";
+import { classifyDrop } from "@/lib/kanban/drop-classification";
+import { useStepReorder } from "@/hooks/domains/kanban/use-step-reorder";
+import { getTaskMoveErrorMessage } from "@/components/task/task-move-error-message";
+import {
+ getDragDisplaySteps,
+ getTemporaryStepIds,
+ useKanbanDragScrollAnchor,
+} from "@/hooks/domains/kanban/use-kanban-drag-scroll-anchor";
+import { t } from "@/lib/i18n";
+
+const TASK_POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
+const TASK_TOUCH_SENSOR_OPTIONS = { activationConstraint: { delay: 250, tolerance: 5 } };
+
+export type SwimlaneKanbanDndOptions = {
+ tasks: Task[];
+ workflowId: string;
+ onMoveError?: (error: MoveTaskError) => void;
+};
+
+export function useCrossStepMove(workflowId: string, onMoveError?: (error: MoveTaskError) => void) {
+ const store = useAppStoreApi();
+ const { moveTaskById } = useTaskActions();
+
+ return useCallback(
+ async (taskId: string, targetStepId: string, task: Task) => {
+ const state = store.getState();
+ const snapshot = state.kanbanMulti.snapshots[workflowId];
+ if (!snapshot) return;
+
+ const originalStepId = task.workflowStepId;
+
+ // The server always computes a cross-step arrival's position itself
+ // (REQ-TASKS-KANBAN-TASK-REORDERING-001.28: it sorts last in the
+ // destination), so there is no locally-computed position to apply
+ // here — the eventual task.updated/task.moved event carries the real
+ // one. Until then the card just needs to show the right step.
+ state.setWorkflowSnapshot(workflowId, {
+ ...snapshot,
+ tasks: snapshot.tasks.map((t: KanbanState["tasks"][number]) =>
+ t.id === taskId ? { ...t, workflowStepId: targetStepId } : t,
+ ),
+ });
+
+ try {
+ await moveTaskById(taskId, {
+ workflow_id: workflowId,
+ workflow_step_id: targetStepId,
+ });
+ } catch (error) {
+ const currentSnapshot = store.getState().kanbanMulti.snapshots[workflowId];
+ if (currentSnapshot) {
+ // Revert only this task's optimistic step change, not the whole
+ // array: a concurrent update to another task while this move was
+ // in flight must survive the rollback.
+ store.getState().setWorkflowSnapshot(workflowId, {
+ ...currentSnapshot,
+ tasks: currentSnapshot.tasks.map((t: KanbanState["tasks"][number]) =>
+ t.id === taskId ? { ...t, workflowStepId: originalStepId } : t,
+ ),
+ });
+ }
+ const message = getTaskMoveErrorMessage(error, t("task:taskMoveErrorGeneric"), t);
+ onMoveError?.({ message, taskId, sessionId: task.primarySessionId ?? null });
+ }
+ },
+ [workflowId, store, moveTaskById, onMoveError],
+ );
+}
+
+export function useSwimlaneKanbanDnd({ tasks, workflowId, onMoveError }: SwimlaneKanbanDndOptions) {
+ const { reorderBand } = useStepReorder();
+ const moveTaskAcrossSteps = useCrossStepMove(workflowId, onMoveError);
+ const [activeTaskId, setActiveTaskId] = useState(null);
+ const tasksRef = useRef(tasks);
+ tasksRef.current = tasks;
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, TASK_POINTER_SENSOR_OPTIONS),
+ useSensor(TouchSensor, TASK_TOUCH_SENSOR_OPTIONS),
+ );
+
+ const handleDragStart = useCallback((event: DragStartEvent) => {
+ setActiveTaskId(event.active.id as string);
+ }, []);
+
+ const handleDragEnd = useCallback(
+ async (event: DragEndEvent) => {
+ const { active, over } = event;
+ setActiveTaskId(null);
+ if (!over) return;
+
+ const taskId = active.id as string;
+ const overId = over.id as string;
+ const task = tasksRef.current.find((t) => t.id === taskId);
+ if (!task) return;
+
+ const classification = classifyDrop({
+ draggedTaskId: taskId,
+ overId,
+ stepTasks: tasksRef.current.filter((t) => t.workflowStepId === task.workflowStepId),
+ allTasks: tasksRef.current,
+ });
+
+ if (classification.kind === "reorder") {
+ await reorderBand({
+ workflowId,
+ stepId: classification.stepId,
+ band: classification.band,
+ draggedId: taskId,
+ visibleOrderAfterMove: classification.visibleOrderAfterMove,
+ });
+ return;
+ }
+
+ if (classification.kind !== "cross-step" || isOrphanMoveTarget(classification.targetStepId)) {
+ return;
+ }
+
+ await moveTaskAcrossSteps(taskId, classification.targetStepId, task);
+ },
+ [workflowId, reorderBand, moveTaskAcrossSteps],
+ );
+
+ const handleDragCancel = useCallback(() => {
+ setActiveTaskId(null);
+ }, []);
+
+ const moveTaskToStep = useCallback(
+ async (task: Task, targetStepId: string) => {
+ if (task.workflowStepId === targetStepId) return;
+ await handleDragEnd({ active: { id: task.id }, over: { id: targetStepId } } as DragEndEvent);
+ },
+ [handleDragEnd],
+ );
+
+ const activeTask = useMemo(
+ () => tasks.find((t) => t.id === activeTaskId) ?? null,
+ [tasks, activeTaskId],
+ );
+
+ return {
+ sensors,
+ handleDragStart,
+ handleDragEnd,
+ handleDragCancel,
+ moveTaskToStep,
+ activeTask,
+ };
+}
+
+export function useSwimlaneKanbanPresentationDnd({
+ displaySteps,
+ moveTargetSteps,
+ isMobile,
+ ...dndOptions
+}: SwimlaneKanbanDndOptions & {
+ displaySteps: WorkflowStep[];
+ moveTargetSteps: WorkflowStep[];
+ isMobile: boolean;
+}) {
+ const dnd = useSwimlaneKanbanDnd(dndOptions);
+ const renderedSteps = useMemo(
+ () => getDragDisplaySteps(displaySteps, moveTargetSteps, !!dnd.activeTask, isMobile),
+ [displaySteps, moveTargetSteps, dnd.activeTask, isMobile],
+ );
+ const { boardRef, handleAnchoredDragStart } = useKanbanDragScrollAnchor({
+ tasks: dndOptions.tasks,
+ activeTask: dnd.activeTask,
+ renderedSteps,
+ onDragStart: dnd.handleDragStart,
+ });
+ const temporaryStepIds = useMemo(
+ () => getTemporaryStepIds(displaySteps, moveTargetSteps),
+ [displaySteps, moveTargetSteps],
+ );
+ return {
+ ...dnd,
+ renderedSteps,
+ temporaryStepIds,
+ boardRef,
+ handleDragStart: handleAnchoredDragStart,
+ };
+}
diff --git a/apps/web/hooks/domains/kanban/use-swimlane-move.ts b/apps/web/hooks/domains/kanban/use-swimlane-move.ts
index 9a02c03f6a..ddbf39c9b6 100644
--- a/apps/web/hooks/domains/kanban/use-swimlane-move.ts
+++ b/apps/web/hooks/domains/kanban/use-swimlane-move.ts
@@ -51,7 +51,6 @@ export function useSwimlaneMove(
await moveTaskById(task.id, {
workflow_id: workflowId,
workflow_step_id: targetStepId,
- position: nextPosition,
});
// Backend handles on_enter actions (auto_start_agent, plan_mode, etc.)
// via the task.moved event → orchestrator processOnEnter()
diff --git a/apps/web/hooks/domains/kanban/use-task-subtasks.test.tsx b/apps/web/hooks/domains/kanban/use-task-subtasks.test.tsx
index be28dd49cb..7d7d2a6b7f 100644
--- a/apps/web/hooks/domains/kanban/use-task-subtasks.test.tsx
+++ b/apps/web/hooks/domains/kanban/use-task-subtasks.test.tsx
@@ -72,6 +72,9 @@ describe("useTaskSubtasks", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
"wf-2": {
workflowId: "wf-2",
diff --git a/apps/web/hooks/use-change-request-provider-target.test.tsx b/apps/web/hooks/use-change-request-provider-target.test.tsx
index b02bb7d014..07d09708c5 100644
--- a/apps/web/hooks/use-change-request-provider-target.test.tsx
+++ b/apps/web/hooks/use-change-request-provider-target.test.tsx
@@ -57,6 +57,9 @@ describe("useChangeRequestProviderTarget", () => {
taskSessions: { items: { "session-a": { task_id: "task-a" } as never } },
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
"workflow-b": {
tasks: [
diff --git a/apps/web/hooks/use-task-actions.ts b/apps/web/hooks/use-task-actions.ts
index ccd0b00087..3be3a45041 100644
--- a/apps/web/hooks/use-task-actions.ts
+++ b/apps/web/hooks/use-task-actions.ts
@@ -10,7 +10,7 @@ import { useTranslation } from "react-i18next";
type MovePayload = {
workflow_id: string;
workflow_step_id: string;
- position: number;
+ position?: number;
entry_options?: WorkflowMoveEntryOptions;
};
diff --git a/apps/web/hooks/use-task-in-flight.test.tsx b/apps/web/hooks/use-task-in-flight.test.tsx
index d898c658df..7f34b2a8e1 100644
--- a/apps/web/hooks/use-task-in-flight.test.tsx
+++ b/apps/web/hooks/use-task-in-flight.test.tsx
@@ -43,6 +43,9 @@ function snapshotWrapper(tasks: Task[]) {
"wf-1": { workflowId: "wf-1", workflowName: "wf", steps: [], tasks },
},
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
},
}}
>
diff --git a/apps/web/hooks/use-task-multi-select-bulk-move.test.ts b/apps/web/hooks/use-task-multi-select-bulk-move.test.ts
new file mode 100644
index 0000000000..8740ac7ec2
--- /dev/null
+++ b/apps/web/hooks/use-task-multi-select-bulk-move.test.ts
@@ -0,0 +1,106 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const deleteTaskById = vi.fn();
+const archiveTaskById = vi.fn();
+const moveTasks = vi.fn();
+
+vi.mock("./use-task-actions", () => ({
+ useTaskActions: () => ({ deleteTaskById, archiveTaskById }),
+}));
+vi.mock("./use-task-removal", () => ({
+ useTaskRemovalSuccessNotifier: () => vi.fn(),
+ useTaskRemoval: () => ({ removeTaskFromBoard: vi.fn(), runTaskRemovalBatch: vi.fn() }),
+}));
+vi.mock("./use-task-workflow-move", () => ({ useTaskWorkflowMove: () => moveTasks }));
+
+type FakeTask = { id: string; workflowStepId: string };
+
+let storeState: {
+ kanban: { workflowId: string | null; tasks: FakeTask[] };
+ kanbanMulti: { snapshots: Record };
+ hydrate: (patch: Record) => void;
+ setWorkflowSnapshot: (wfId: string, snapshot: { tasks: FakeTask[] }) => void;
+};
+
+function resetStore() {
+ storeState = {
+ kanban: {
+ workflowId: "wf1",
+ tasks: [
+ { id: "a", workflowStepId: "step-1" },
+ { id: "b", workflowStepId: "step-1" },
+ ],
+ },
+ kanbanMulti: { snapshots: {} },
+ hydrate(patch) {
+ storeState = { ...storeState, ...(patch as typeof storeState) };
+ },
+ setWorkflowSnapshot(wfId, snapshot) {
+ storeState.kanbanMulti.snapshots[wfId] = snapshot;
+ },
+ };
+}
+
+const store = { getState: () => storeState };
+vi.mock("@/components/state-provider", () => ({ useAppStoreApi: () => store }));
+
+import { useTaskMultiSelect } from "./use-task-multi-select";
+
+beforeEach(() => {
+ resetStore();
+ deleteTaskById.mockReset().mockResolvedValue(undefined);
+ archiveTaskById.mockReset().mockResolvedValue(undefined);
+ moveTasks.mockReset().mockResolvedValue(undefined);
+});
+
+describe("useTaskMultiSelect — bulk move", () => {
+ it("routes the whole selection through the batch endpoint in one call", async () => {
+ const { result } = renderHook(() => useTaskMultiSelect("wf1"));
+ act(() => result.current.toggleSelect("a"));
+ act(() => result.current.toggleSelect("b"));
+
+ await act(async () => {
+ await result.current.bulkMove("step-2");
+ });
+
+ // A single batched call, not one moveTaskById per selected task — the
+ // previous Promise.allSettled fan-out raced each task's arrival position
+ // against the others' (REQ-TASKS-KANBAN-TASK-REORDERING-001.29).
+ expect(moveTasks).toHaveBeenCalledTimes(1);
+ expect(moveTasks).toHaveBeenCalledWith(["a", "b"], "wf1", "step-2", "step");
+ expect(storeState.kanban.tasks.map((t) => t.workflowStepId)).toEqual(["step-2", "step-2"]);
+ });
+
+ it("does nothing for an empty selection", async () => {
+ const { result } = renderHook(() => useTaskMultiSelect("wf1"));
+ await act(async () => {
+ await result.current.bulkMove("step-2");
+ });
+ expect(moveTasks).not.toHaveBeenCalled();
+ });
+
+ it("does nothing without a workflow id", async () => {
+ const { result } = renderHook(() => useTaskMultiSelect(null));
+ act(() => result.current.toggleSelect("a"));
+ await act(async () => {
+ await result.current.bulkMove("step-2");
+ });
+ expect(moveTasks).not.toHaveBeenCalled();
+ });
+
+ it("leaves the store unchanged and swallows the rejection on failure", async () => {
+ moveTasks.mockRejectedValue(new Error("locked"));
+ const { result } = renderHook(() => useTaskMultiSelect("wf1"));
+ act(() => result.current.toggleSelect("a"));
+
+ await act(async () => {
+ await result.current.bulkMove("step-2");
+ });
+
+ expect(storeState.kanban.tasks.find((t) => t.id === "a")?.workflowStepId).toBe("step-1");
+ // The selection itself is left as-is by bulkMove; useTaskWorkflowMove
+ // already surfaced the failure toast.
+ expect(result.current.selectedIds).toEqual(new Set(["a"]));
+ });
+});
diff --git a/apps/web/hooks/use-task-multi-select.ts b/apps/web/hooks/use-task-multi-select.ts
index 9c84bc471e..4424162710 100644
--- a/apps/web/hooks/use-task-multi-select.ts
+++ b/apps/web/hooks/use-task-multi-select.ts
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, type RefObject } from "react";
import { useTaskActions, type TaskActionOptions } from "@/hooks/use-task-actions";
import { useTaskRemoval, useTaskRemovalSuccessNotifier } from "@/hooks/use-task-removal";
+import { useTaskWorkflowMove } from "@/hooks/use-task-workflow-move";
import { useAppStoreApi } from "@/components/state-provider";
import type { KanbanState } from "@/lib/state/slices";
import { sortIdsByCreatedDesc } from "@/lib/kanban/task-order";
@@ -99,43 +100,6 @@ export function useTaskMultiSelectStore() {
return { removeTasksFromStore, applyMoveInStore, getWorkflowIdForTask, sortByDisplayOrder };
}
-type BulkMoveParams = {
- workflowId: string | null;
- selectedIdsRef: RefObject>;
- moveTaskById: ReturnType["moveTaskById"];
- applyMoveInStore: (ids: Set, stepId: string) => void;
- getWorkflowIdForTask: (id: string) => string | null;
- sortByDisplayOrder: (ids: string[]) => string[];
-};
-
-async function runBulkMove(
- {
- workflowId,
- selectedIdsRef,
- moveTaskById,
- applyMoveInStore,
- getWorkflowIdForTask,
- sortByDisplayOrder,
- }: BulkMoveParams,
- targetStepId: string,
-): Promise {
- const idList = sortByDisplayOrder([...(selectedIdsRef.current ?? [])]);
- if (idList.length === 0) return;
- const results = await Promise.allSettled(
- idList.map((id, i) => {
- const wfId = getWorkflowIdForTask(id) ?? workflowId;
- if (!wfId) return Promise.reject(new Error("no workflow"));
- return moveTaskById(id, {
- workflow_id: wfId,
- workflow_step_id: targetStepId,
- position: i,
- });
- }),
- );
- const succeeded = new Set(idList.filter((_, i) => results[i].status === "fulfilled"));
- applyMoveInStore(succeeded, targetStepId);
-}
-
function useBulkOperations({
workflowId,
selectedIdsRef,
@@ -143,14 +107,12 @@ function useBulkOperations({
setIsDeleting,
setIsArchiving,
setIsMultiSelectEnabled,
- moveTaskById,
deleteTaskById,
archiveTaskById,
runTaskRemovalBatch,
removeTasksFromStore,
applyMoveInStore,
- getWorkflowIdForTask,
- sortByDisplayOrder,
+ moveTasks,
}: {
workflowId: string | null;
selectedIdsRef: RefObject>;
@@ -158,14 +120,12 @@ function useBulkOperations({
setIsDeleting: (v: boolean) => void;
setIsArchiving: (v: boolean) => void;
setIsMultiSelectEnabled: (v: boolean) => void;
- moveTaskById: ReturnType["moveTaskById"];
deleteTaskById: ReturnType["deleteTaskById"];
archiveTaskById: ReturnType["archiveTaskById"];
runTaskRemovalBatch: ReturnType["runTaskRemovalBatch"];
removeTasksFromStore: (ids: Set) => void;
applyMoveInStore: (ids: Set, stepId: string) => void;
- getWorkflowIdForTask: (id: string) => string | null;
- sortByDisplayOrder: (ids: string[]) => string[];
+ moveTasks: ReturnType;
}) {
const runBulk = useCallback(
async (
@@ -214,26 +174,23 @@ function useBulkOperations({
);
const bulkMove = useCallback(
- (targetStepId: string) =>
- runBulkMove(
- {
- workflowId,
- selectedIdsRef,
- moveTaskById,
- applyMoveInStore,
- getWorkflowIdForTask,
- sortByDisplayOrder,
- },
- targetStepId,
- ),
- [
- workflowId,
- moveTaskById,
- applyMoveInStore,
- getWorkflowIdForTask,
- sortByDisplayOrder,
- selectedIdsRef,
- ],
+ async (targetStepId: string) => {
+ const idList = [...(selectedIdsRef.current ?? [])];
+ if (idList.length === 0 || !workflowId) return;
+ // Routed through the batch endpoint (mirrors use-sidebar-multi-select's
+ // bulkMove) rather than fanning out one moveTaskById call per task: a
+ // concurrent Promise.allSettled fan-out raced each task's arrival
+ // position against the others', so the resulting order depended on
+ // response timing rather than the selection (REQ-TASKS-KANBAN-TASK-REORDERING-001.29).
+ // The server re-derives submission order from each task's current step.
+ try {
+ await moveTasks(idList, workflowId, targetStepId, "step");
+ applyMoveInStore(new Set(idList), targetStepId);
+ } catch {
+ // useTaskWorkflowMove already shows the failure toast.
+ }
+ },
+ [workflowId, moveTasks, applyMoveInStore, selectedIdsRef],
);
return { bulkDelete, bulkArchive, bulkMove };
@@ -375,12 +332,12 @@ export function useTaskMultiSelect(workflowId: string | null) {
dispatch({ type: "reset" });
}, [workflowId]);
- const { moveTaskById, deleteTaskById, archiveTaskById } = useTaskActions();
+ const { deleteTaskById, archiveTaskById } = useTaskActions();
const store = useAppStoreApi();
const notifySuccess = useTaskRemovalSuccessNotifier();
const { runTaskRemovalBatch } = useTaskRemoval({ store, notifySuccess });
- const { removeTasksFromStore, applyMoveInStore, getWorkflowIdForTask, sortByDisplayOrder } =
- useTaskMultiSelectStore();
+ const { removeTasksFromStore, applyMoveInStore } = useTaskMultiSelectStore();
+ const moveTasks = useTaskWorkflowMove();
const toggleSelect = useCallback(
(taskId: string) => dispatch({ type: "toggle_select", taskId }),
@@ -419,14 +376,12 @@ export function useTaskMultiSelect(workflowId: string | null) {
setIsDeleting,
setIsArchiving,
setIsMultiSelectEnabled,
- moveTaskById,
deleteTaskById,
archiveTaskById,
runTaskRemovalBatch,
removeTasksFromStore,
applyMoveInStore,
- getWorkflowIdForTask,
- sortByDisplayOrder,
+ moveTasks,
});
return {
diff --git a/apps/web/lib/api/domains/kanban-api.test.ts b/apps/web/lib/api/domains/kanban-api.test.ts
index 1252b7c8bd..8c3bb19024 100644
--- a/apps/web/lib/api/domains/kanban-api.test.ts
+++ b/apps/web/lib/api/domains/kanban-api.test.ts
@@ -6,9 +6,11 @@ import {
getTaskDeletePreflight,
listTasksByWorkspace,
moveTask,
+ reorderStepTasks,
updateTask,
updateTaskPortForwarding,
} from "./kanban-api";
+import { ApiError } from "../client";
const fetchSpy = vi.fn();
const API_BASE_URL = "http://api.test";
@@ -103,6 +105,91 @@ describe("updateTask", () => {
});
});
+describe("reorderStepTasks", () => {
+ it("PUTs the band and ordered ids to the hyphenated collection route", async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ workflow_step_id: "step-1",
+ revision: 1,
+ tasks: [
+ { id: "task-b", position: 0 },
+ { id: "task-a", position: 1 },
+ ],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+
+ const result = await reorderStepTasks(
+ "step-1",
+ { band: "admitted", ordered_task_ids: ["task-b", "task-a"] },
+ { baseUrl: API_BASE_URL },
+ );
+
+ expect(fetchSpy).toHaveBeenCalledOnce();
+ const [url, init] = fetchSpy.mock.calls[0];
+ expect(url).toBe(`${API_BASE_URL}/api/v1/workflow-steps/step-1/tasks/reorder`);
+ expect(init?.method).toBe("PUT");
+ expect(init?.body).toBe(
+ JSON.stringify({ band: "admitted", ordered_task_ids: ["task-b", "task-a"] }),
+ );
+ expect(result.revision).toBe(1);
+ expect(result.tasks).toEqual([
+ { id: "task-b", position: 0 },
+ { id: "task-a", position: 1 },
+ ]);
+ });
+
+ it("surfaces a step_changed conflict as an ApiError carrying the authoritative order", async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ code: "step_changed",
+ workflow_step_id: "step-1",
+ revision: 3,
+ tasks: [{ id: "task-a", position: 0 }],
+ }),
+ { status: 409, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+
+ await expect(
+ reorderStepTasks(
+ "step-1",
+ { band: "admitted", ordered_task_ids: ["task-a"] },
+ { baseUrl: API_BASE_URL },
+ ),
+ ).rejects.toMatchObject({
+ status: 409,
+ body: { code: "step_changed", revision: 3 },
+ });
+ });
+
+ it("surfaces an invalid_reorder rejection with no task list", async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(JSON.stringify({ code: "invalid_reorder" }), {
+ status: 400,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ let caught: unknown;
+ try {
+ await reorderStepTasks(
+ "step-1",
+ { band: "admitted", ordered_task_ids: [] },
+ { baseUrl: API_BASE_URL },
+ );
+ } catch (error) {
+ caught = error;
+ }
+ expect(caught).toBeInstanceOf(ApiError);
+ expect((caught as ApiError).status).toBe(400);
+ expect((caught as ApiError).body).toEqual({ code: "invalid_reorder" });
+ });
+});
+
describe("updateTaskPortForwarding", () => {
it("patches only the task-scoped preference endpoint", async () => {
fetchSpy.mockResolvedValueOnce(
diff --git a/apps/web/lib/api/domains/kanban-api.ts b/apps/web/lib/api/domains/kanban-api.ts
index 0e21a731ce..2e57ba34d8 100644
--- a/apps/web/lib/api/domains/kanban-api.ts
+++ b/apps/web/lib/api/domains/kanban-api.ts
@@ -10,6 +10,8 @@ import type {
Task,
TaskPriority,
MoveTaskResponse,
+ ReorderBand,
+ ReorderStepTasksResponse,
} from "@/lib/types/http";
// Workflow operations
@@ -267,7 +269,8 @@ export type WorkflowMoveEntryOptions = {
export type MoveTaskPayload = {
workflow_id: string;
workflow_step_id: string;
- position: number;
+ /** @deprecated Server computes arrival position per AC.28; this field is transmitted but ignored. */
+ position?: number;
entry_options?: WorkflowMoveEntryOptions | null;
};
@@ -312,6 +315,28 @@ export async function moveTask(
});
}
+/**
+ * Reorders one workflow step's band. The only request surface for a reorder
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001) — a WebSocket action was cut in the
+ * design. On a 409 `step_changed` conflict the thrown ApiError's `body`
+ * carries this same ReorderStepTasksResponse shape (the authoritative order
+ * to reconcile to silently); on a 400 `invalid_reorder` it carries only
+ * `{code}`.
+ */
+export async function reorderStepTasks(
+ workflowStepId: string,
+ payload: { band: ReorderBand; ordered_task_ids: string[] },
+ options?: ApiRequestOptions,
+) {
+ return fetchJson(
+ `/api/v1/workflow-steps/${workflowStepId}/tasks/reorder`,
+ {
+ ...options,
+ init: { method: "PUT", body: JSON.stringify(payload), ...(options?.init ?? {}) },
+ },
+ );
+}
+
export async function bulkMoveSelectedTasks(
payload: { task_ids: string[]; target_workflow_id: string; target_step_id: string },
options?: ApiRequestOptions,
diff --git a/apps/web/lib/kanban/drop-classification.test.ts b/apps/web/lib/kanban/drop-classification.test.ts
new file mode 100644
index 0000000000..2d61fa22a7
--- /dev/null
+++ b/apps/web/lib/kanban/drop-classification.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from "vitest";
+import { classifyDrop } from "./drop-classification";
+
+const STEP_A = "step-a";
+const STEP_B = "step-b";
+
+type FakeTask = {
+ id: string;
+ workflowStepId: string;
+ position: number;
+ wipAdmitted?: boolean;
+ queuedForStepId?: string;
+};
+
+function admitted(id: string, position: number, stepId = STEP_A): FakeTask {
+ return { id, workflowStepId: stepId, position, wipAdmitted: true };
+}
+
+function queued(id: string, position: number, stepId = STEP_A): FakeTask {
+ return { id, workflowStepId: stepId, position, wipAdmitted: false, queuedForStepId: stepId };
+}
+
+describe("classifyDrop", () => {
+ it("classifies a same-band drop as a reorder with the moved visible order (AC.5)", () => {
+ const stepTasks = [admitted("a", 0), admitted("b", 1), admitted("c", 2)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: "c",
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({
+ kind: "reorder",
+ stepId: STEP_A,
+ band: "admitted",
+ visibleOrderAfterMove: ["b", "c", "a"],
+ });
+ });
+
+ it("classifies a queued-band drop the same way as admitted", () => {
+ const stepTasks = [admitted("a", 0), queued("b", 1), queued("c", 2)];
+
+ const result = classifyDrop({
+ draggedTaskId: "b",
+ overId: "c",
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({
+ kind: "reorder",
+ stepId: STEP_A,
+ band: "queued",
+ visibleOrderAfterMove: ["c", "b"],
+ });
+ });
+
+ it("rejects a drop onto the other band of the same step, without a request (AC.11)", () => {
+ const stepTasks = [admitted("a", 0), queued("b", 1)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: "b",
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "reject" });
+ });
+
+ it("is a no-op when the drop reproduces the order already displayed (AC.10)", () => {
+ const stepTasks = [admitted("a", 0), admitted("b", 1)];
+
+ // Dropping "a" back onto itself.
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: "a",
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "no-op" });
+ });
+
+ it("is a no-op when overId is null (defensive: the real AC.9 drop-outside-any-band path never reaches classifyDrop, since useSwimlaneKanbanDnd's handleDragEnd returns early on a null `over` — see use-swimlane-kanban-dnd.test.ts)", () => {
+ const stepTasks = [admitted("a", 0), admitted("b", 1)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: null,
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "no-op" });
+ });
+
+ it("is a no-op when dropped on the column itself with no specific card underneath", () => {
+ const stepTasks = [admitted("a", 0), admitted("b", 1)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: STEP_A,
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "no-op" });
+ });
+
+ it("classifies a drop onto a different step's column as cross-step (AC.13)", () => {
+ const stepTasks = [admitted("a", 0), admitted("b", 1)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: STEP_B,
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "cross-step", targetStepId: STEP_B });
+ });
+
+ it("is a no-op when the dragged task cannot be found", () => {
+ const stepTasks = [admitted("a", 0), admitted("b", 1)];
+
+ const result = classifyDrop({
+ draggedTaskId: "missing",
+ overId: "b",
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "no-op" });
+ });
+});
+
+describe("classifyDrop — band computed from position (AC.15)", () => {
+ it("classifies a same-band drop by position, not by stepTasks' array order", () => {
+ // stepTasks arrives in creation order (as it would after a prior reorder
+ // changed positions but arrival order stayed the same) — true step order
+ // by position is c(0), a(1), b(2), not the array's own a, b, c order.
+ const stepTasks = [admitted("a", 1), admitted("b", 2), admitted("c", 0)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: "b",
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({
+ kind: "reorder",
+ stepId: STEP_A,
+ band: "admitted",
+ visibleOrderAfterMove: ["c", "b", "a"],
+ });
+ });
+});
+
+describe("classifyDrop — cross-step target resolution (AC.13)", () => {
+ it("classifies a drop onto a card that belongs to a different step as cross-step, resolving the target from the whole board rather than the dragged task's own step", () => {
+ // `stepTasks` is scoped to the dragged task's own step, exactly as the
+ // real caller (`useSwimlaneKanbanDnd`) produces it — it never contains a
+ // foreign-step card. Only `allTasks` (the whole board) has "x".
+ const stepTasks = [admitted("a", 0)];
+ const allTasks = [...stepTasks, admitted("x", 0, STEP_B)];
+
+ const result = classifyDrop({ draggedTaskId: "a", overId: "x", stepTasks, allTasks });
+
+ expect(result).toEqual({ kind: "cross-step", targetStepId: STEP_B });
+ });
+
+ it("treats an overId that matches no task anywhere on the board as a literal step id (dropped on an empty column)", () => {
+ const stepTasks = [admitted("a", 0)];
+
+ const result = classifyDrop({
+ draggedTaskId: "a",
+ overId: STEP_B,
+ stepTasks,
+ allTasks: stepTasks,
+ });
+
+ expect(result).toEqual({ kind: "cross-step", targetStepId: STEP_B });
+ });
+});
diff --git a/apps/web/lib/kanban/drop-classification.ts b/apps/web/lib/kanban/drop-classification.ts
new file mode 100644
index 0000000000..8db65e893c
--- /dev/null
+++ b/apps/web/lib/kanban/drop-classification.ts
@@ -0,0 +1,94 @@
+/**
+ * Pure classifier for a kanban drag-and-drop end event
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.5, .10, .11, .13). Kept free of React
+ * and dnd-kit so the reorder-vs-reject-vs-cross-step-vs-no-op decision is
+ * unit-testable without simulating a drag gesture.
+ */
+
+import { partitionWipTasks, type WipQueueTask } from "./wip-queue";
+import { moveWithinOrder } from "./reorder-merge";
+import type { ReorderBand } from "@/lib/types/http";
+
+export type DropClassification =
+ | { kind: "no-op" }
+ | { kind: "reject" }
+ | { kind: "cross-step"; targetStepId: string }
+ | {
+ kind: "reorder";
+ stepId: string;
+ band: ReorderBand;
+ visibleOrderAfterMove: string[];
+ };
+
+type ClassifiableTask = WipQueueTask & { id: string; workflowStepId: string };
+
+export type ClassifyDropParams = {
+ draggedTaskId: string;
+ /** `over.id` from the drag-end event: a task id, a step id, or absent. */
+ overId: string | null;
+ /** Every task currently displayed in the dragged task's step, in display order. */
+ stepTasks: T[];
+ /**
+ * Every task on the board, across every step. Used only to resolve
+ * `overId` to its owning step when the drop lands on a card outside the
+ * dragged task's own step: every card is its own drop target (for the
+ * insertion indicator), so a cross-step drop's `over.id` is a foreign
+ * task's id, not the destination column's step id
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.13).
+ */
+ allTasks: T[];
+};
+
+/**
+ * Classifies a drop against the dragged task's OWN step's currently
+ * displayed tasks. `stepTasks` must be scoped to the dragged task's step
+ * (whatever step it started in) so band membership (admitted vs queued) can
+ * be computed the same way the board renders it. `allTasks` resolves a
+ * foreign card's step; `overId` is treated as a literal step id only when it
+ * names no task anywhere on the board (a drop on an empty column).
+ */
+export function classifyDrop(
+ params: ClassifyDropParams,
+): DropClassification {
+ const { draggedTaskId, overId, stepTasks, allTasks } = params;
+ if (!overId) return { kind: "no-op" };
+
+ const draggedTask = stepTasks.find((task) => task.id === draggedTaskId);
+ if (!draggedTask) return { kind: "no-op" };
+
+ const overTask =
+ stepTasks.find((task) => task.id === overId) ?? allTasks.find((task) => task.id === overId);
+ const targetStepId = overTask ? overTask.workflowStepId : overId;
+
+ if (targetStepId !== draggedTask.workflowStepId) {
+ return { kind: "cross-step", targetStepId };
+ }
+
+ // Same step. Dropped on the column itself (no specific card under the
+ // pointer) or back on itself: nothing to commit.
+ if (!overTask || overTask.id === draggedTaskId) {
+ return { kind: "no-op" };
+ }
+
+ const { admitted, queued } = partitionWipTasks(stepTasks, draggedTask.workflowStepId);
+ const draggedInAdmitted = admitted.some((task) => task.id === draggedTaskId);
+ const overInAdmitted = admitted.some((task) => task.id === overId);
+ if (draggedInAdmitted !== overInAdmitted) {
+ return { kind: "reject" };
+ }
+
+ const band: ReorderBand = draggedInAdmitted ? "admitted" : "queued";
+ const bandOrder = (draggedInAdmitted ? admitted : queued).map((task) => task.id);
+ const fromIndex = bandOrder.indexOf(draggedTaskId);
+ const toIndex = bandOrder.indexOf(overId);
+ if (fromIndex === -1 || toIndex === -1 || fromIndex === toIndex) {
+ return { kind: "no-op" };
+ }
+
+ return {
+ kind: "reorder",
+ stepId: draggedTask.workflowStepId,
+ band,
+ visibleOrderAfterMove: moveWithinOrder(bandOrder, fromIndex, toIndex),
+ };
+}
diff --git a/apps/web/lib/kanban/keyboard-reorder.test.ts b/apps/web/lib/kanban/keyboard-reorder.test.ts
new file mode 100644
index 0000000000..4a32a81841
--- /dev/null
+++ b/apps/web/lib/kanban/keyboard-reorder.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { moveOneStep } from "./keyboard-reorder";
+
+describe("moveOneStep", () => {
+ const order = ["a", "b", "c"];
+
+ it("moves the task up one place", () => {
+ expect(moveOneStep(order, "b", "up")).toEqual(["b", "a", "c"]);
+ });
+
+ it("moves the task down one place", () => {
+ expect(moveOneStep(order, "b", "down")).toEqual(["a", "c", "b"]);
+ });
+
+ it("ignores an up move at the top of the band", () => {
+ expect(moveOneStep(order, "a", "up")).toBeNull();
+ });
+
+ it("ignores a down move at the bottom of the band", () => {
+ expect(moveOneStep(order, "c", "down")).toBeNull();
+ });
+
+ it("returns null when the task is not in the order", () => {
+ expect(moveOneStep(order, "missing", "up")).toBeNull();
+ });
+});
diff --git a/apps/web/lib/kanban/keyboard-reorder.ts b/apps/web/lib/kanban/keyboard-reorder.ts
new file mode 100644
index 0000000000..67e6a4a1d9
--- /dev/null
+++ b/apps/web/lib/kanban/keyboard-reorder.ts
@@ -0,0 +1,27 @@
+/**
+ * Pure move-validity helper for keyboard reordering
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.12). Kept free of React so the
+ * "ignored at the band edge" rule is unit-testable without simulating a
+ * keydown.
+ */
+
+import { moveWithinOrder } from "./reorder-merge";
+
+export type ArrowDirection = "up" | "down";
+
+/**
+ * Returns `order` with `taskId` moved one place in `direction`, or `null`
+ * when the move would carry it past either end of the band — an arrow press
+ * there is ignored entirely, not clamped to the edge.
+ */
+export function moveOneStep(
+ order: string[],
+ taskId: string,
+ direction: ArrowDirection,
+): string[] | null {
+ const fromIndex = order.indexOf(taskId);
+ if (fromIndex === -1) return null;
+ const toIndex = direction === "up" ? fromIndex - 1 : fromIndex + 1;
+ if (toIndex < 0 || toIndex >= order.length) return null;
+ return moveWithinOrder(order, fromIndex, toIndex);
+}
diff --git a/apps/web/lib/kanban/reorder-merge.test.ts b/apps/web/lib/kanban/reorder-merge.test.ts
new file mode 100644
index 0000000000..c94851750d
--- /dev/null
+++ b/apps/web/lib/kanban/reorder-merge.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import { arraysEqual, mergeVisibleReorderIntoBand, moveWithinOrder } from "./reorder-merge";
+
+describe("moveWithinOrder", () => {
+ it("moves an item forward", () => {
+ expect(moveWithinOrder(["a", "b", "c", "d"], 0, 2)).toEqual(["b", "c", "a", "d"]);
+ });
+
+ it("moves an item backward", () => {
+ expect(moveWithinOrder(["a", "b", "c", "d"], 3, 1)).toEqual(["a", "d", "b", "c"]);
+ });
+
+ it("returns the same order when indexes are equal", () => {
+ const order = ["a", "b", "c"];
+ expect(moveWithinOrder(order, 1, 1)).toEqual(order);
+ });
+
+ it("returns the original array unchanged for an out-of-range index", () => {
+ const order = ["a", "b", "c"];
+ expect(moveWithinOrder(order, -1, 1)).toBe(order);
+ expect(moveWithinOrder(order, 1, 3)).toBe(order);
+ });
+});
+
+describe("mergeVisibleReorderIntoBand", () => {
+ it("inserts the dragged task before its new visible neighbor, preserving hidden tasks", () => {
+ // Full band: A, H1(hidden), B, C, H2(hidden), D. Visible: A, B, C, D.
+ // Dragging C to the front of the visible order.
+ const fullBandOrder = ["A", "H1", "B", "C", "H2", "D"];
+ const visibleOrderAfterMove = ["C", "A", "B", "D"];
+ expect(mergeVisibleReorderIntoBand(fullBandOrder, visibleOrderAfterMove, "C")).toEqual([
+ "C",
+ "A",
+ "H1",
+ "B",
+ "H2",
+ "D",
+ ]);
+ });
+
+ it("inserts the dragged task after its new visible neighbor when moved to the visible end", () => {
+ const fullBandOrder = ["A", "H1", "B", "C", "H2", "D"];
+ const visibleOrderAfterMove = ["B", "C", "D", "A"];
+ expect(mergeVisibleReorderIntoBand(fullBandOrder, visibleOrderAfterMove, "A")).toEqual([
+ "H1",
+ "B",
+ "C",
+ "H2",
+ "D",
+ "A",
+ ]);
+ });
+
+ it("leaves every non-dragged task's relative order unchanged", () => {
+ const fullBandOrder = ["A", "B", "C", "D", "E"];
+ const visibleOrderAfterMove = ["A", "C", "B", "D", "E"];
+ const result = mergeVisibleReorderIntoBand(fullBandOrder, visibleOrderAfterMove, "C");
+ const others = result.filter((id) => id !== "C");
+ expect(others).toEqual(["A", "B", "D", "E"]);
+ });
+
+ it("is a no-op when there is no hidden task and the visible order already matches", () => {
+ const fullBandOrder = ["A", "B", "C"];
+ const visibleOrderAfterMove = ["A", "B", "C"];
+ expect(mergeVisibleReorderIntoBand(fullBandOrder, visibleOrderAfterMove, "B")).toEqual([
+ "A",
+ "B",
+ "C",
+ ]);
+ });
+
+ it("returns the original order when the dragged id is not in the visible order", () => {
+ const fullBandOrder = ["A", "B", "C"];
+ expect(mergeVisibleReorderIntoBand(fullBandOrder, ["A", "B"], "missing")).toEqual(
+ fullBandOrder,
+ );
+ });
+
+ it("moves the dragged task to the true end of the band when a hidden task trails the last visible member (AC.34)", () => {
+ // Full band: v1, v2, h(hidden). Visible: v1, v2. Dragging v1 below v2 —
+ // the last visible member — must land last in the WHOLE band, after h,
+ // not merely after v2.
+ const fullBandOrder = ["v1", "v2", "h"];
+ const visibleOrderAfterMove = ["v2", "v1"];
+ expect(mergeVisibleReorderIntoBand(fullBandOrder, visibleOrderAfterMove, "v1")).toEqual([
+ "v2",
+ "h",
+ "v1",
+ ]);
+ });
+});
+
+describe("arraysEqual", () => {
+ it("is true for identical sequences", () => {
+ expect(arraysEqual(["a", "b"], ["a", "b"])).toBe(true);
+ });
+
+ it("is false for a different order", () => {
+ expect(arraysEqual(["a", "b"], ["b", "a"])).toBe(false);
+ });
+
+ it("is false for a different length", () => {
+ expect(arraysEqual(["a"], ["a", "b"])).toBe(false);
+ });
+});
diff --git a/apps/web/lib/kanban/reorder-merge.ts b/apps/web/lib/kanban/reorder-merge.ts
new file mode 100644
index 0000000000..8c3b1d7276
--- /dev/null
+++ b/apps/web/lib/kanban/reorder-merge.ts
@@ -0,0 +1,64 @@
+/**
+ * Pure order-computation helpers for within-band drag/keyboard reordering
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.5, .12, .34). Kept free of React and
+ * of dnd-kit so the merge algorithm is unit-testable without simulating a
+ * drag gesture.
+ */
+
+/** `arrayMove` semantics without importing `@dnd-kit/sortable` for one helper. */
+export function moveWithinOrder(order: T[], fromIndex: number, toIndex: number): T[] {
+ if (fromIndex < 0 || toIndex < 0 || fromIndex >= order.length || toIndex >= order.length) {
+ return order;
+ }
+ const next = [...order];
+ const [moved] = next.splice(fromIndex, 1);
+ next.splice(toIndex, 0, moved);
+ return next;
+}
+
+/**
+ * Reinserts `draggedId` into `fullBandOrder` (the band's complete membership,
+ * including any task the board is currently hiding behind a filter) so that
+ * it sits adjacent to the same neighbor it now has in `visibleOrderAfterMove`
+ * (the reordered subsequence of members the board is currently showing).
+ *
+ * Every other task's relative order is left exactly as it was — only the
+ * dragged task moves — which is what
+ * REQ-TASKS-KANBAN-TASK-REORDERING-001.34 requires: a reorder made under a
+ * board filter must not rearrange the tasks that filter is hiding.
+ */
+export function mergeVisibleReorderIntoBand(
+ fullBandOrder: string[],
+ visibleOrderAfterMove: string[],
+ draggedId: string,
+): string[] {
+ const withoutDragged = fullBandOrder.filter((id) => id !== draggedId);
+ const draggedIndex = visibleOrderAfterMove.indexOf(draggedId);
+ if (draggedIndex === -1) return fullBandOrder;
+
+ const nextVisibleId = visibleOrderAfterMove[draggedIndex + 1];
+ if (nextVisibleId !== undefined) {
+ const insertAt = withoutDragged.indexOf(nextVisibleId);
+ if (insertAt === -1) return fullBandOrder;
+ const result = [...withoutDragged];
+ result.splice(insertAt, 0, draggedId);
+ return result;
+ }
+
+ // The dragged card is last among the currently visible members: per
+ // REQ-TASKS-KANBAN-TASK-REORDERING-001.34 it lands last in the whole band,
+ // not merely after its visible predecessor — a hidden member trailing that
+ // predecessor must not keep outranking a card the user moved to the bottom
+ // of what they can see.
+ if (visibleOrderAfterMove[draggedIndex - 1] !== undefined) {
+ return [...withoutDragged, draggedId];
+ }
+
+ // Only one visible member — a reorder should never have been offered
+ // (REQ-TASKS-KANBAN-TASK-REORDERING-001.32); nothing to do.
+ return fullBandOrder;
+}
+
+export function arraysEqual(a: string[], b: string[]): boolean {
+ return a.length === b.length && a.every((id, index) => id === b[index]);
+}
diff --git a/apps/web/lib/kanban/task-order.test.ts b/apps/web/lib/kanban/task-order.test.ts
index 06bc95b4d7..b07492a50b 100644
--- a/apps/web/lib/kanban/task-order.test.ts
+++ b/apps/web/lib/kanban/task-order.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
-import { compareTasksByCreatedDesc, sortIdsByCreatedDesc } from "./task-order";
+import {
+ compareStepOrder,
+ compareTasksByCreatedDesc,
+ sortIdsByCreatedDesc,
+ type StepOrderTask,
+} from "./task-order";
describe("compareTasksByCreatedDesc", () => {
it("sorts newer created tasks first", () => {
@@ -77,3 +82,86 @@ describe("sortIdsByCreatedDesc", () => {
expect(sortIdsByCreatedDesc(["a", "missing", "c"], taskById)).toEqual(["c", "a", "missing"]);
});
});
+
+function stepOrderTask(overrides: Partial = {}): StepOrderTask {
+ return {
+ id: "task",
+ position: 0,
+ priority: "medium",
+ queuedAt: "2026-08-12T10:00:00Z",
+ createdAt: "2026-08-12T09:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("compareStepOrder", () => {
+ it("orders by position first", () => {
+ const tasks = [
+ stepOrderTask({ id: "b", position: 2 }),
+ stepOrderTask({ id: "a", position: 1 }),
+ ];
+ expect([...tasks].sort(compareStepOrder).map((t) => t.id)).toEqual(["a", "b"]);
+ });
+
+ it("breaks a position tie by priority rank, highest first", () => {
+ const tasks = [
+ stepOrderTask({ id: "low", position: 1, priority: "low" }),
+ stepOrderTask({ id: "critical", position: 1, priority: "critical" }),
+ ];
+ expect([...tasks].sort(compareStepOrder).map((t) => t.id)).toEqual(["critical", "low"]);
+ });
+
+ const NEVER_QUEUED_ID = "never-queued";
+
+ it("breaks a priority tie by queuedAt ascending, falling back to createdAt when absent", () => {
+ const neverQueued = stepOrderTask({
+ id: NEVER_QUEUED_ID,
+ queuedAt: null,
+ createdAt: "2026-08-12T07:00:00Z",
+ });
+ const queuedLater = stepOrderTask({ id: "queued-later", queuedAt: "2026-08-12T09:00:00Z" });
+ expect([queuedLater, neverQueued].sort(compareStepOrder).map((t) => t.id)).toEqual([
+ NEVER_QUEUED_ID,
+ "queued-later",
+ ]);
+ });
+
+ it("uses a nil queuedAt's own createdAt fallback rather than comparing createdAt directly", () => {
+ // never-queued's fallback (its own createdAt, late) must lose to
+ // "queued-early"'s earlier explicit queuedAt, even though
+ // "queued-early"'s createdAt is later still - a comparator that
+ // silently fell back to comparing createdAt directly (ignoring
+ // queuedAt) would order these the same as the case above and pass it,
+ // but would reverse this one.
+ const neverQueued = stepOrderTask({
+ id: NEVER_QUEUED_ID,
+ queuedAt: null,
+ createdAt: "2026-08-12T09:00:00Z",
+ });
+ const queuedEarly = stepOrderTask({
+ id: "queued-early",
+ queuedAt: "2026-08-12T07:00:00Z",
+ createdAt: "2026-08-12T10:00:00Z",
+ });
+ expect([neverQueued, queuedEarly].sort(compareStepOrder).map((t) => t.id)).toEqual([
+ "queued-early",
+ NEVER_QUEUED_ID,
+ ]);
+ });
+
+ it("breaks a queuedAt tie by createdAt ascending, then id ascending", () => {
+ const tasks = [
+ stepOrderTask({ id: "z", createdAt: "2026-08-12T08:00:00Z" }),
+ stepOrderTask({ id: "a", createdAt: "2026-08-12T08:00:00Z" }),
+ ];
+ expect([...tasks].sort(compareStepOrder).map((t) => t.id)).toEqual(["a", "z"]);
+ });
+
+ it("treats an absent priority as ranking after every named priority", () => {
+ const tasks = [
+ stepOrderTask({ id: "absent", position: 1, priority: undefined }),
+ stepOrderTask({ id: "low", position: 1, priority: "low" }),
+ ];
+ expect([...tasks].sort(compareStepOrder).map((t) => t.id)).toEqual(["low", "absent"]);
+ });
+});
diff --git a/apps/web/lib/kanban/task-order.ts b/apps/web/lib/kanban/task-order.ts
index 470924d930..d142be9cf7 100644
--- a/apps/web/lib/kanban/task-order.ts
+++ b/apps/web/lib/kanban/task-order.ts
@@ -1,3 +1,5 @@
+import type { TaskPriority } from "@/lib/types/http";
+
type CreatedTask = {
createdAt?: string;
};
@@ -30,3 +32,73 @@ export function sortIdsByCreatedDesc(ids: string[], taskById: Map right) return 1;
+ return 0;
+}
+
+export function compareStepOrder(left: StepOrderTask, right: StepOrderTask): number {
+ const position = (left.position ?? 0) - (right.position ?? 0);
+ if (position !== 0) return position;
+
+ const priority = priorityRank(left.priority) - priorityRank(right.priority);
+ if (priority !== 0) return priority;
+
+ const queuedAt = compareOrderNumbers(effectiveQueuedAt(left), effectiveQueuedAt(right));
+ if (queuedAt !== 0) return queuedAt;
+
+ const createdAt = compareOrderNumbers(
+ orderTimestamp(left.createdAt),
+ orderTimestamp(right.createdAt),
+ );
+ if (createdAt !== 0) return createdAt;
+
+ return left.id.localeCompare(right.id);
+}
diff --git a/apps/web/lib/kanban/wip-queue.test.ts b/apps/web/lib/kanban/wip-queue.test.ts
index 4872829c8c..22b24c8c91 100644
--- a/apps/web/lib/kanban/wip-queue.test.ts
+++ b/apps/web/lib/kanban/wip-queue.test.ts
@@ -100,6 +100,27 @@ describe("wip queue helper", () => {
]);
});
+ it("falls back an absent queuedAt to createdAt instead of sorting it last", () => {
+ // AC-TASKS-KANBAN-TASK-REORDERING-001.36: a task with no queuedAt reads as
+ // its own createdAt, not as "unknown, sort last" the way a genuinely
+ // missing/unparseable value does elsewhere in this comparator.
+ const neverQueued = task({
+ id: "never-queued",
+ queuedAt: null,
+ createdAt: "2026-08-12T07:00:00Z",
+ });
+ const queuedLater = task({
+ id: "queued-later",
+ queuedAt: "2026-08-12T09:00:00Z",
+ createdAt: "2026-08-12T10:00:00Z",
+ });
+
+ expect(compareWipQueueTasks(neverQueued, queuedLater)).toBeLessThan(0);
+ expect(
+ getDestinationQueue([queuedLater, neverQueued], "review").map((entry) => entry.task.id),
+ ).toEqual(["never-queued", "queued-later"]);
+ });
+
it("orders missing timestamps deterministically without producing NaN", () => {
const left = task({ id: "left", queuedAt: null, createdAt: null });
const right = task({ id: "right", queuedAt: "not-a-date", createdAt: "not-a-date" });
@@ -108,3 +129,24 @@ describe("wip queue helper", () => {
expect(Number.isNaN(compareWipQueueTasks(left, right))).toBe(false);
});
});
+
+describe("partitionWipTasks — admitted band order (AC.15)", () => {
+ it("keeps partitioned admitted tasks in step order, not raw array order", () => {
+ // The admitted band must sort by compareStepOrder the same way the
+ // queued band already does, so a caller computing drag/keyboard reorder
+ // indices off partitionWipTasks sees the step's true order rather than
+ // whatever order tasks happened to arrive in (e.g. creation order after
+ // a prior reorder changed it).
+ const tasks = [
+ task({ id: "a", wipAdmitted: true, queuedForStepId: undefined, position: 1 }),
+ task({ id: "b", wipAdmitted: true, queuedForStepId: undefined, position: 2 }),
+ task({ id: "c", wipAdmitted: true, queuedForStepId: undefined, position: 0 }),
+ ];
+
+ expect(partitionWipTasks(tasks, "review").admitted.map((item) => item.id)).toEqual([
+ "c",
+ "a",
+ "b",
+ ]);
+ });
+});
diff --git a/apps/web/lib/kanban/wip-queue.ts b/apps/web/lib/kanban/wip-queue.ts
index 4757a36e45..187f1bb19d 100644
--- a/apps/web/lib/kanban/wip-queue.ts
+++ b/apps/web/lib/kanban/wip-queue.ts
@@ -1,14 +1,9 @@
-import type { TaskPriority } from "@/lib/types/http";
+import { compareStepOrder, type StepOrderTask } from "./task-order";
-export type WipQueueTask = {
- id: string;
+export type WipQueueTask = StepOrderTask & {
workflowStepId: string;
queuedForStepId?: string | null;
wipAdmitted?: boolean | null;
- position?: number | null;
- priority?: TaskPriority | null;
- queuedAt?: string | null;
- createdAt?: string | null;
};
export type WipQueueEntry = {
@@ -23,47 +18,11 @@ export type WipQueueStatus = {
destinationTitle: string;
};
-function priorityRank(priority: WipQueueTask["priority"]): number {
- switch (priority) {
- case "critical":
- return 0;
- case "high":
- return 1;
- case "medium":
- return 2;
- case "low":
- return 3;
- default:
- return 4;
- }
-}
-
-function timestamp(value: string | null | undefined): number {
- if (!value) return Number.POSITIVE_INFINITY;
- const parsed = Date.parse(value);
- return Number.isFinite(parsed) ? parsed : Number.POSITIVE_INFINITY;
-}
-
-function compareNumbers(left: number, right: number): number {
- if (left < right) return -1;
- if (left > right) return 1;
- return 0;
-}
-
+// Delegates to task-order.ts's AC.1 total ordering key so the overflow queue
+// and every other board/promotion comparator (REQ-TASKS-KANBAN-TASK-REORDERING-001.36)
+// cannot drift apart.
export function compareWipQueueTasks(left: WipQueueTask, right: WipQueueTask): number {
- const position = (left.position ?? 0) - (right.position ?? 0);
- if (position !== 0) return position;
-
- const priority = priorityRank(left.priority) - priorityRank(right.priority);
- if (priority !== 0) return priority;
-
- const queuedAt = compareNumbers(timestamp(left.queuedAt), timestamp(right.queuedAt));
- if (queuedAt !== 0) return queuedAt;
-
- const createdAt = compareNumbers(timestamp(left.createdAt), timestamp(right.createdAt));
- if (createdAt !== 0) return createdAt;
-
- return left.id.localeCompare(right.id);
+ return compareStepOrder(left, right);
}
function isDestinationQueued(task: WipQueueTask, destinationStepId: string): boolean {
@@ -89,8 +48,10 @@ export function partitionWipTasks(
): { admitted: T[]; queued: T[] } {
const queuedEntries = getDestinationQueue(tasks, destinationStepId);
const queuedIds = new Set(queuedEntries.map(({ task }) => task.id));
+ const admitted = tasks.filter((task) => !queuedIds.has(task.id));
+ admitted.sort(compareWipQueueTasks);
return {
- admitted: tasks.filter((task) => !queuedIds.has(task.id)),
+ admitted,
queued: queuedEntries.map(({ task }) => task),
};
}
diff --git a/apps/web/lib/kanban/workflow-step-order.test.ts b/apps/web/lib/kanban/workflow-step-order.test.ts
index 4e719cd74d..f55e1ce4b6 100644
--- a/apps/web/lib/kanban/workflow-step-order.test.ts
+++ b/apps/web/lib/kanban/workflow-step-order.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { sortWorkflowStepsByPosition } from "./workflow-step-order";
+import { mergeStepOrderRevisions, sortWorkflowStepsByPosition } from "./workflow-step-order";
describe("sortWorkflowStepsByPosition", () => {
it("orders workflow steps deterministically without mutating the snapshot", () => {
@@ -17,3 +17,38 @@ describe("sortWorkflowStepsByPosition", () => {
expect(unordered.map((step) => step.id)).toEqual(["step-b", "step-c", "step-a"]);
});
});
+
+describe("mergeStepOrderRevisions", () => {
+ it("seeds a revision for a step with no prior recorded value", () => {
+ const result = mergeStepOrderRevisions({}, [{ id: "step-1", order_revision: 3 }]);
+ expect(result).toEqual({ "step-1": 3 });
+ });
+
+ it("advances an existing revision when the fetched value is greater", () => {
+ const result = mergeStepOrderRevisions({ "step-1": 2 }, [{ id: "step-1", order_revision: 5 }]);
+ expect(result).toEqual({ "step-1": 5 });
+ });
+
+ it("never rolls back a fresher recorded revision to a stale fetched one", () => {
+ const current = { "step-1": 7 };
+ const result = mergeStepOrderRevisions(current, [{ id: "step-1", order_revision: 4 }]);
+ expect(result).toEqual({ "step-1": 7 });
+ });
+
+ it("returns the same reference when nothing changes, to avoid extra re-renders", () => {
+ const current = { "step-1": 7 };
+ const result = mergeStepOrderRevisions(current, [{ id: "step-1", order_revision: 4 }]);
+ expect(result).toBe(current);
+ });
+
+ it("ignores a step whose order_revision is absent", () => {
+ const result = mergeStepOrderRevisions({}, [{ id: "step-1" }]);
+ expect(result).toEqual({});
+ });
+
+ it("passes through an empty or undefined steps list unchanged", () => {
+ const current = { "step-1": 1 };
+ expect(mergeStepOrderRevisions(current, [])).toBe(current);
+ expect(mergeStepOrderRevisions(current, undefined)).toBe(current);
+ });
+});
diff --git a/apps/web/lib/kanban/workflow-step-order.ts b/apps/web/lib/kanban/workflow-step-order.ts
index 396efb90e8..0f057c3e88 100644
--- a/apps/web/lib/kanban/workflow-step-order.ts
+++ b/apps/web/lib/kanban/workflow-step-order.ts
@@ -5,3 +5,31 @@ export function sortWorkflowStepsByPosition a.position - b.position || a.id.localeCompare(b.id));
}
+
+export type StepOrderRevisionSource = { id: string; order_revision?: number };
+
+/**
+ * Seeds a stepId->revision map from freshly-fetched steps, keeping the
+ * larger revision on conflict. A hydration response can resolve after a
+ * fresher WS-driven `task.reordered` already advanced the recorded
+ * revision (REQ-TASKS-KANBAN-TASK-REORDERING-001.25/.37); taking the max
+ * keeps that later value from being rolled back to a stale one.
+ */
+export function mergeStepOrderRevisions(
+ current: Record,
+ steps: readonly StepOrderRevisionSource[] | undefined,
+): Record {
+ if (!steps || steps.length === 0) return current;
+ let changed = false;
+ const next = { ...current };
+ for (const step of steps) {
+ const revision = step.order_revision;
+ if (revision === undefined) continue;
+ const existing = next[step.id];
+ if (existing === undefined || revision > existing) {
+ next[step.id] = revision;
+ changed = true;
+ }
+ }
+ return changed ? next : current;
+}
diff --git a/apps/web/lib/routing/kanban-route-hydration.test.ts b/apps/web/lib/routing/kanban-route-hydration.test.ts
index 661e8c4ea2..18d3c1b8ed 100644
--- a/apps/web/lib/routing/kanban-route-hydration.test.ts
+++ b/apps/web/lib/routing/kanban-route-hydration.test.ts
@@ -18,6 +18,9 @@ function state(overrides: Partial = {}): HydrationState {
"wf-1": { workflowId: "wf-1", workflowName: "Development", steps: [], tasks: [] },
},
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
},
...overrides,
};
@@ -41,7 +44,13 @@ describe("hasHydratedKanbanRouteState", () => {
hasHydratedKanbanRouteState(
state({
kanban: { workflowId: null, steps: [], tasks: [] },
- kanbanMulti: { snapshots: {}, isLoading: false },
+ kanbanMulti: {
+ snapshots: {},
+ isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
+ },
}),
{},
),
diff --git a/apps/web/lib/ssr/mapper.ts b/apps/web/lib/ssr/mapper.ts
index 23c622afb8..a19eb67a0c 100644
--- a/apps/web/lib/ssr/mapper.ts
+++ b/apps/web/lib/ssr/mapper.ts
@@ -152,6 +152,7 @@ export function snapshotToState(snapshot: WorkflowSnapshot): Partial {
wip_limit: step.wip_limit,
pull_from_step_id: step.pull_from_step_id ?? null,
stage_type: step.stage_type,
+ order_revision: step.order_revision,
})),
tasks,
},
diff --git a/apps/web/lib/state/hydration/hydrator-order-revision.test.ts b/apps/web/lib/state/hydration/hydrator-order-revision.test.ts
new file mode 100644
index 0000000000..2b1a1346e3
--- /dev/null
+++ b/apps/web/lib/state/hydration/hydrator-order-revision.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from "vitest";
+import { produce } from "immer";
+import type { Draft } from "immer";
+import { hydrateState } from "./hydrator";
+import { defaultState } from "@/lib/state/default-state";
+import type { AppState } from "@/lib/state/store";
+
+function makeAppDraft(): AppState {
+ return structuredClone(defaultState) as AppState;
+}
+
+const STEP_COLOR = "bg-neutral-400";
+
+/**
+ * Covers the Build-phase fix for missing order_revision on HTTP hydration:
+ * an unsolicited task.reordered WS event arriving right after a page load
+ * must be compared against the step's real last-known revision, not the
+ * "no revision recorded yet" (-1) fallback that would accept any event as
+ * the first order ever seen.
+ */
+describe("hydrateState — kanbanMulti.orderRevisionByStepId seeding", () => {
+ it("seeds a step's revision from kanban.steps on the initial boot hydration", () => {
+ const result = produce(makeAppDraft(), (draft: Draft) => {
+ hydrateState(draft, {
+ kanban: {
+ workflowId: "wf-1",
+ steps: [
+ {
+ id: "step-1",
+ title: "Step 1",
+ color: STEP_COLOR,
+ position: 0,
+ order_revision: 4,
+ },
+ ],
+ tasks: [],
+ },
+ } as unknown as Partial);
+ });
+
+ expect(result.kanbanMulti.orderRevisionByStepId["step-1"]).toBe(4);
+ });
+
+ it("seeds revisions from every workflow's snapshot, not only the active one", () => {
+ const result = produce(makeAppDraft(), (draft: Draft) => {
+ hydrateState(draft, {
+ kanbanMulti: {
+ snapshots: {
+ "wf-background": {
+ workflowId: "wf-background",
+ workflowName: "Background",
+ steps: [
+ {
+ id: "step-bg",
+ title: "Bg",
+ color: STEP_COLOR,
+ position: 0,
+ order_revision: 2,
+ },
+ ],
+ tasks: [],
+ },
+ },
+ },
+ } as unknown as Partial);
+ });
+
+ expect(result.kanbanMulti.orderRevisionByStepId["step-bg"]).toBe(2);
+ });
+
+ it("never rolls back a fresher recorded revision to a stale hydrated one", () => {
+ const result = produce(makeAppDraft(), (draft: Draft) => {
+ draft.kanbanMulti.orderRevisionByStepId["step-1"] = 9;
+
+ hydrateState(draft, {
+ kanban: {
+ workflowId: "wf-1",
+ steps: [
+ {
+ id: "step-1",
+ title: "Step 1",
+ color: STEP_COLOR,
+ position: 0,
+ order_revision: 3,
+ },
+ ],
+ tasks: [],
+ },
+ } as unknown as Partial);
+ });
+
+ expect(result.kanbanMulti.orderRevisionByStepId["step-1"]).toBe(9);
+ });
+
+ it("leaves the revision map untouched when a step omits order_revision", () => {
+ const result = produce(makeAppDraft(), (draft: Draft) => {
+ hydrateState(draft, {
+ kanban: {
+ workflowId: "wf-1",
+ steps: [{ id: "step-1", title: "Step 1", color: STEP_COLOR, position: 0 }],
+ tasks: [],
+ },
+ } as unknown as Partial);
+ });
+
+ expect(result.kanbanMulti.orderRevisionByStepId["step-1"]).toBeUndefined();
+ });
+});
diff --git a/apps/web/lib/state/hydration/hydrator.ts b/apps/web/lib/state/hydration/hydrator.ts
index bda9b2b019..e46f480c6a 100644
--- a/apps/web/lib/state/hydration/hydrator.ts
+++ b/apps/web/lib/state/hydration/hydrator.ts
@@ -21,6 +21,7 @@ import {
shouldReplaceMcpAttachmentHistory,
} from "@/lib/state/slices/session-runtime/mcp-attachment-reconciliation";
import { preserveOmittedExecutorFields } from "@/lib/kanban/map-task";
+import { mergeStepOrderRevisions } from "@/lib/kanban/workflow-step-order";
import { deepMerge, mergeSessionMap, mergeLoadingState } from "./merge-strategies";
/**
@@ -111,6 +112,24 @@ function backfillServerDerivedFields(
}
}
+/**
+ * Seeds `kanbanMulti.orderRevisionByStepId` from a batch of freshly-hydrated
+ * steps (REQ-TASKS-KANBAN-TASK-REORDERING-001.25/.37) so a `task.reordered`
+ * WS event received right after this hydration is compared against the
+ * step's real last-known revision instead of the "no revision recorded yet"
+ * fallback, which would otherwise accept a stale event as the first order
+ * this client has ever seen.
+ */
+function seedOrderRevisionsFromSteps(
+ draft: Draft,
+ steps: KanbanState["steps"] | undefined,
+): void {
+ draft.kanbanMulti.orderRevisionByStepId = mergeStepOrderRevisions(
+ draft.kanbanMulti.orderRevisionByStepId,
+ steps,
+ );
+}
+
/** Hydrate kanban and workspace slices. */
function hydrateKanbanAndWorkspace(draft: Draft, state: HydrationState): void {
if (state.kanban) {
@@ -118,8 +137,14 @@ function hydrateKanbanAndWorkspace(draft: Draft, state: HydrationState
const { tasks, ...kanbanRest } = state.kanban;
if (Object.keys(kanbanRest).length > 0) deepMerge(draft.kanban, kanbanRest);
mergeKanbanTasks(draft.kanban, tasks);
+ seedOrderRevisionsFromSteps(draft, state.kanban.steps);
+ }
+ if (state.kanbanMulti) {
+ deepMerge(draft.kanbanMulti, state.kanbanMulti);
+ for (const snapshot of Object.values(state.kanbanMulti.snapshots ?? {})) {
+ seedOrderRevisionsFromSteps(draft, snapshot?.steps);
+ }
}
- if (state.kanbanMulti) deepMerge(draft.kanbanMulti, state.kanbanMulti);
if (state.workflows) deepMerge(draft.workflows, state.workflows);
if (state.tasks) deepMerge(draft.tasks, state.tasks);
if (state.workspaces) deepMerge(draft.workspaces, state.workspaces);
diff --git a/apps/web/lib/state/slices/kanban/kanban-slice.test.ts b/apps/web/lib/state/slices/kanban/kanban-slice.test.ts
index 944c843954..dc91dbcb98 100644
--- a/apps/web/lib/state/slices/kanban/kanban-slice.test.ts
+++ b/apps/web/lib/state/slices/kanban/kanban-slice.test.ts
@@ -98,6 +98,9 @@ describe("kanban slice workspace transition", () => {
},
},
isLoading: true,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
},
workflows: {
items: [{ id: WORKFLOW_ID, workspaceId: ARCHIVED_WORKSPACE_ID, name: "Workflow A" }],
@@ -244,3 +247,24 @@ describe("kanban slice resume-skipped marker", () => {
expect(store.getState().tasks.resumeSkippedSessionIds["session-running"]).toBeUndefined();
});
});
+
+describe("kanban slice step order revision and in-flight reorder tracking", () => {
+ it("records and overwrites a step's last-applied order revision", () => {
+ const store = makeStore();
+ store.getState().setStepOrderRevision("step-1", 3);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId["step-1"]).toBe(3);
+
+ store.getState().setStepOrderRevision("step-1", 4);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId["step-1"]).toBe(4);
+ });
+
+ it("marks and clears a band as pending, keyed by step and band", () => {
+ const store = makeStore();
+ store.getState().setBandReorderPending("step-1", "admitted", true);
+ expect(store.getState().kanbanMulti.pendingReorderBandKeys["step-1:admitted"]).toBe(true);
+ expect(store.getState().kanbanMulti.pendingReorderBandKeys["step-1:queued"]).toBeUndefined();
+
+ store.getState().setBandReorderPending("step-1", "admitted", false);
+ expect(store.getState().kanbanMulti.pendingReorderBandKeys["step-1:admitted"]).toBeUndefined();
+ });
+});
diff --git a/apps/web/lib/state/slices/kanban/kanban-slice.ts b/apps/web/lib/state/slices/kanban/kanban-slice.ts
index 73de91a227..2858a6539f 100644
--- a/apps/web/lib/state/slices/kanban/kanban-slice.ts
+++ b/apps/web/lib/state/slices/kanban/kanban-slice.ts
@@ -8,10 +8,17 @@ import {
recordTaskRemovalResult,
releaseTaskRemoval,
} from "@/lib/state/task-removal";
+import { mergeStepOrderRevisions } from "@/lib/kanban/workflow-step-order";
export const defaultKanbanState: KanbanSliceState = {
kanban: { workflowId: null, steps: [], tasks: [] },
- kanbanMulti: { snapshots: {}, isLoading: false },
+ kanbanMulti: {
+ snapshots: {},
+ isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
+ },
sidebarArchivedTasks: {
itemsByWorkspaceId: {},
loadedByWorkspaceId: {},
@@ -231,6 +238,15 @@ export const createKanbanSlice: StateCreator<
setWorkflowSnapshot: (workflowId, data) =>
set((draft) => {
draft.kanbanMulti.snapshots[workflowId] = data;
+ // Seed this workflow's steps into orderRevisionByStepId even when it
+ // is not the currently-active board (hydrate() only walks the active
+ // kanban.steps), so a task.reordered WS event for a background
+ // "All Workflows" column is still gated on a real revision rather
+ // than the no-recorded-revision fallback.
+ draft.kanbanMulti.orderRevisionByStepId = mergeStepOrderRevisions(
+ draft.kanbanMulti.orderRevisionByStepId,
+ data.steps,
+ );
}),
setKanbanMultiLoading: (loading) =>
set((draft) => {
@@ -258,4 +274,26 @@ export const createKanbanSlice: StateCreator<
if (!snapshot) return;
snapshot.tasks = snapshot.tasks.filter((t) => t.id !== taskId);
}),
+ setStepOrderRevision: (stepId, revision) =>
+ set((draft) => {
+ draft.kanbanMulti.orderRevisionByStepId[stepId] = revision;
+ }),
+ setBandReorderPending: (stepId, band, pending) =>
+ set((draft) => {
+ const key = `${stepId}:${band}`;
+ if (pending) {
+ draft.kanbanMulti.pendingReorderBandKeys[key] = true;
+ } else {
+ delete draft.kanbanMulti.pendingReorderBandKeys[key];
+ }
+ }),
+ setWithheldReorder: (stepId, band, payload) =>
+ set((draft) => {
+ const key = `${stepId}:${band}`;
+ if (payload) {
+ draft.kanbanMulti.withheldReorderByBandKey[key] = payload;
+ } else {
+ delete draft.kanbanMulti.withheldReorderByBandKey[key];
+ }
+ }),
});
diff --git a/apps/web/lib/state/slices/kanban/types.ts b/apps/web/lib/state/slices/kanban/types.ts
index 572cd79d2c..e4ae13db2f 100644
--- a/apps/web/lib/state/slices/kanban/types.ts
+++ b/apps/web/lib/state/slices/kanban/types.ts
@@ -1,5 +1,7 @@
import type {
ForegroundActivity,
+ ReorderBand,
+ ReorderedTaskPosition,
TaskPendingAction,
TaskOrigin,
TaskPriority,
@@ -61,6 +63,15 @@ export type KanbanState = {
* decisions). Backend never branches on this field.
*/
stage_type?: "work" | "review" | "approval" | "custom";
+ /**
+ * Last order-revision this step's task order was written at
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.25/.37), as of when this step
+ * record was fetched. Seeded into `kanbanMulti.orderRevisionByStepId` on
+ * hydration so a `task.reordered` WS event received right after page
+ * load is compared against the hydrated value instead of the "no
+ * revision recorded yet" fallback.
+ */
+ order_revision?: number;
}>;
tasks: Array<{
id: string;
@@ -189,6 +200,33 @@ export type WorkflowSnapshotData = {
export type KanbanMultiState = {
snapshots: Record;
isLoading: boolean;
+ /**
+ * Last-applied `order_revision` per workflow step
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.16/.19/.25/.27). An unsolicited
+ * `task.reordered` WS event only applies when its revision is strictly
+ * greater than this; a response to the board's own reorder request applies
+ * unconditionally and then advances it.
+ */
+ orderRevisionByStepId: Record;
+ /**
+ * Bands with a reorder request currently in flight, keyed
+ * `${stepId}:${band}` (REQ-TASKS-KANBAN-TASK-REORDERING-001.27). While a
+ * band's key is present, the board suspends further reorder input on that
+ * band and holds its optimistic order rather than applying an incoming
+ * published order to it.
+ */
+ pendingReorderBandKeys: Record;
+ /**
+ * The most recent published order withheld from a band because it arrived
+ * while that band's own reorder request was in flight, keyed
+ * `${stepId}:${band}`. Reconciled against the request's own resolution by
+ * revision (the higher of the two wins, the response breaking a tie) when
+ * that request settles, then cleared either way.
+ */
+ withheldReorderByBandKey: Record<
+ string,
+ { revision: number; tasks: ReorderedTaskPosition[] } | undefined
+ >;
};
export type SidebarArchivedTasksState = {
@@ -283,6 +321,13 @@ export type KanbanSliceActions = {
clearKanbanMulti: () => void;
updateMultiTask: (workflowId: string, task: KanbanState["tasks"][number]) => void;
removeMultiTask: (workflowId: string, taskId: string) => void;
+ setStepOrderRevision: (stepId: string, revision: number) => void;
+ setBandReorderPending: (stepId: string, band: ReorderBand, pending: boolean) => void;
+ setWithheldReorder: (
+ stepId: string,
+ band: ReorderBand,
+ payload: { revision: number; tasks: ReorderedTaskPosition[] } | null,
+ ) => void;
setSidebarArchivedTasks: (
workspaceId: string,
tasks: KanbanState["tasks"],
diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts
index 4e046840c7..dec42d45e8 100644
--- a/apps/web/lib/types/backend.ts
+++ b/apps/web/lib/types/backend.ts
@@ -22,6 +22,7 @@ import type {
Agent,
AvailableAgent,
ForegroundActivity,
+ ReorderBand,
TaskPendingAction,
TaskPriority,
TaskSessionState,
@@ -81,6 +82,14 @@ export type KanbanUpdatePayload = {
}>;
};
+export type TaskReorderedPayload = {
+ workspace_id?: string;
+ workflow_step_id: string;
+ band: ReorderBand;
+ revision: number;
+ tasks: Array<{ id: string; position: number }>;
+};
+
export type TaskEventPayload = {
task_id: string;
workspace_id?: string;
@@ -430,6 +439,7 @@ export type BackendMessageMap = SessionBackendMessageMap &
import("@/lib/types/http").WalkthroughBackendMessageMap &
import("@/lib/types/review").ReviewBackendMessageMap & {
"kanban.update": BackendMessage<"kanban.update", KanbanUpdatePayload>;
+ "task.reordered": BackendMessage<"task.reordered", TaskReorderedPayload>;
"task.created": BackendMessage<"task.created", TaskEventPayload>;
"task.updated": BackendMessage<"task.updated", TaskEventPayload>;
"task.deleted": BackendMessage<"task.deleted", TaskEventPayload>;
diff --git a/apps/web/lib/types/http.ts b/apps/web/lib/types/http.ts
index 366df12312..8ecf2f0c59 100644
--- a/apps/web/lib/types/http.ts
+++ b/apps/web/lib/types/http.ts
@@ -541,6 +541,15 @@ export type WorkflowStepDTO = {
complete_task_on_enter: boolean;
auto_advance_requires_signal: boolean;
cancel_triggers_turn_complete: boolean;
+ /**
+ * Bumped by the reorder endpoint each time this step's task order changes
+ * (REQ-TASKS-KANBAN-TASK-REORDERING-001.25/.37). Seed
+ * `kanbanMulti.orderRevisionByStepId` from this on hydration so a
+ * `task.reordered` WS event received right after page load is not
+ * mistaken for the first order this client has ever seen. Optional only
+ * because older test fixtures omit it; the backend always sends it.
+ */
+ order_revision?: number;
created_at?: string;
updated_at?: string;
};
@@ -557,6 +566,32 @@ export type MoveTaskResponse = {
};
};
+/** Band discriminator for a within-step reorder request. */
+export type ReorderBand = "admitted" | "queued";
+
+/** One task's new position, as carried by every reorder response/event. */
+export type ReorderedTaskPosition = {
+ id: string;
+ position: number;
+};
+
+/**
+ * Success (200) and step_changed conflict (409) bodies for
+ * `PUT /api/v1/workflow-steps/:id/tasks/reorder` share this shape: the
+ * step's full non-hidden task list in both bands, and the revision it was
+ * written at.
+ */
+export type ReorderStepTasksResponse = {
+ workflow_step_id: string;
+ revision: number;
+ tasks: ReorderedTaskPosition[];
+};
+
+/** Body of a rejected reorder request: `step_changed` (409) or `invalid_reorder` (400). */
+export type ReorderStepTasksErrorBody = Partial & {
+ code: "step_changed" | "invalid_reorder";
+};
+
/** A worktree associated with a task session (one per repo on multi-repo tasks). */
export type TaskSessionWorktree = {
/** Session-worktree association ID. */
diff --git a/apps/web/lib/ws/handlers/agent-session-kanban.test.ts b/apps/web/lib/ws/handlers/agent-session-kanban.test.ts
index 9528ee62fe..25d8e56f5c 100644
--- a/apps/web/lib/ws/handlers/agent-session-kanban.test.ts
+++ b/apps/web/lib/ws/handlers/agent-session-kanban.test.ts
@@ -81,6 +81,9 @@ function makeSnapshotTaskStore(primarySessionId: string) {
const task = makeKanbanTask(primarySessionId);
return {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
"wf-1": {
workflowId: "wf-1",
@@ -197,6 +200,9 @@ describe("session.state_changed -> non-primary kanban card state", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
"wf-1": {
workflowId: "wf-1",
@@ -278,6 +284,9 @@ describe("session.state_changed -> kanban sync guards", () => {
kanban: { workflowId: "wf-1", steps: [], tasks: kanbanTasks },
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
"wf-1": {
workflowId: "wf-1",
diff --git a/apps/web/lib/ws/handlers/kanban-auto-start-failed.test.ts b/apps/web/lib/ws/handlers/kanban-auto-start-failed.test.ts
index c55a627e88..0f599d7e32 100644
--- a/apps/web/lib/ws/handlers/kanban-auto-start-failed.test.ts
+++ b/apps/web/lib/ws/handlers/kanban-auto-start-failed.test.ts
@@ -46,51 +46,54 @@ function makeUpdateMessage(workflowId: string, tasks: unknown[], steps: unknown[
};
}
-describe("kanban.update handler — autoStartFailed preservation", () => {
- it("preserves autoStartFailed from existing tasks", () => {
- const store = makeStore({
- kanban: {
- workflowId: WORKFLOW_ID,
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- autoStartFailed: true,
- },
- ],
- },
- kanbanMulti: {
- isLoading: false,
- snapshots: {
- [WORKFLOW_ID]: {
- workflowId: WORKFLOW_ID,
- workflowName: "WF1",
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- autoStartFailed: true,
- },
- ],
- },
+function makeAutoStartFailedTask(autoStartFailed: boolean) {
+ return {
+ id: TASK_ID,
+ workflowId: WORKFLOW_ID,
+ workflowStepId: STEP_ID,
+ title: TASK_TITLE,
+ position: 0,
+ autoStartFailed,
+ };
+}
+
+function makeAutoStartFailedStore(kanbanFlag: boolean, snapshotFlag: boolean) {
+ return makeStore({
+ kanban: {
+ workflowId: WORKFLOW_ID,
+ steps: [],
+ tasks: [makeAutoStartFailedTask(kanbanFlag)],
+ },
+ kanbanMulti: {
+ isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
+ snapshots: {
+ [WORKFLOW_ID]: {
+ workflowId: WORKFLOW_ID,
+ workflowName: "WF1",
+ steps: [],
+ tasks: [makeAutoStartFailedTask(snapshotFlag)],
},
},
- } as Partial);
+ },
+ } as Partial);
+}
- const handler = registerKanbanHandlers(store)["kanban.update"]!;
- handler(
- makeUpdateMessage(WORKFLOW_ID, [
- { id: TASK_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0 },
- ]),
- );
+function runAutoStartFailedUpdate(store: StoreApi) {
+ const handler = registerKanbanHandlers(store)["kanban.update"]!;
+ handler(
+ makeUpdateMessage(WORKFLOW_ID, [
+ { id: TASK_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0 },
+ ]),
+ );
+}
+
+describe("kanban.update handler — autoStartFailed preservation", () => {
+ it("preserves autoStartFailed from existing tasks", () => {
+ const store = makeAutoStartFailedStore(true, true);
+ runAutoStartFailedUpdate(store);
const task = store.getState().kanban.tasks.find((t) => t.id === TASK_ID);
expect(task?.autoStartFailed).toBe(true);
@@ -107,49 +110,8 @@ describe("kanban.update handler — autoStartFailed preservation", () => {
// the kanbanMulti merge only falls back to the snapshot's value when the
// primary lookup is `undefined` (task absent), not when it resolves to an
// explicit false.
- const store = makeStore({
- kanban: {
- workflowId: WORKFLOW_ID,
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- autoStartFailed: false,
- },
- ],
- },
- kanbanMulti: {
- isLoading: false,
- snapshots: {
- [WORKFLOW_ID]: {
- workflowId: WORKFLOW_ID,
- workflowName: "WF1",
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- autoStartFailed: true,
- },
- ],
- },
- },
- },
- } as Partial);
-
- const handler = registerKanbanHandlers(store)["kanban.update"]!;
- handler(
- makeUpdateMessage(WORKFLOW_ID, [
- { id: TASK_ID, workflowStepId: STEP_ID, title: TASK_TITLE, position: 0 },
- ]),
- );
+ const store = makeAutoStartFailedStore(false, true);
+ runAutoStartFailedUpdate(store);
const snapshotTask = store
.getState()
diff --git a/apps/web/lib/ws/handlers/kanban-priority.test.ts b/apps/web/lib/ws/handlers/kanban-priority.test.ts
index 94b2ee4d6f..1d8350a6d1 100644
--- a/apps/web/lib/ws/handlers/kanban-priority.test.ts
+++ b/apps/web/lib/ws/handlers/kanban-priority.test.ts
@@ -77,6 +77,9 @@ describe("kanban.update handler — priority preservation", () => {
kanban: { workflowId: WORKFLOW_ID, steps: [], tasks: [] },
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
diff --git a/apps/web/lib/ws/handlers/kanban-workspace-orphaned.test.ts b/apps/web/lib/ws/handlers/kanban-workspace-orphaned.test.ts
index 3f0fa26e0b..73a54b83e1 100644
--- a/apps/web/lib/ws/handlers/kanban-workspace-orphaned.test.ts
+++ b/apps/web/lib/ws/handlers/kanban-workspace-orphaned.test.ts
@@ -43,44 +43,53 @@ function makeUpdateMessage(workflowId: string, tasks: unknown[], steps: unknown[
};
}
-describe("kanban.update handler — workspaceOrphaned preservation", () => {
- it("preserves workspaceOrphaned from existing tasks", () => {
- const store = makeStore({
- kanban: {
- workflowId: WORKFLOW_ID,
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- workspaceOrphaned: true,
- },
- ],
- },
- kanbanMulti: {
- isLoading: false,
- snapshots: {
- [WORKFLOW_ID]: {
- workflowId: WORKFLOW_ID,
- workflowName: "WF1",
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- workspaceOrphaned: true,
- },
- ],
- },
+/** Builds a store whose kanban list and kanbanMulti snapshot each carry one
+ * task, with an independently-set workspaceOrphaned flag on each copy. */
+function makeOrphanedState(kanbanOrphaned: boolean, snapshotOrphaned: boolean) {
+ return makeStore({
+ kanban: {
+ workflowId: WORKFLOW_ID,
+ steps: [],
+ tasks: [
+ {
+ id: TASK_ID,
+ workflowId: WORKFLOW_ID,
+ workflowStepId: STEP_ID,
+ title: TASK_TITLE,
+ position: 0,
+ workspaceOrphaned: kanbanOrphaned,
+ },
+ ],
+ },
+ kanbanMulti: {
+ isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
+ snapshots: {
+ [WORKFLOW_ID]: {
+ workflowId: WORKFLOW_ID,
+ workflowName: "WF1",
+ steps: [],
+ tasks: [
+ {
+ id: TASK_ID,
+ workflowId: WORKFLOW_ID,
+ workflowStepId: STEP_ID,
+ title: TASK_TITLE,
+ position: 0,
+ workspaceOrphaned: snapshotOrphaned,
+ },
+ ],
},
},
- } as Partial);
+ },
+ } as Partial);
+}
+
+describe("kanban.update handler — workspaceOrphaned preservation", () => {
+ it("preserves workspaceOrphaned from existing tasks", () => {
+ const store = makeOrphanedState(true, true);
const handler = registerKanbanHandlers(store)["kanban.update"]!;
handler(
@@ -104,42 +113,7 @@ describe("kanban.update handler — workspaceOrphaned preservation", () => {
// kanbanMulti merge only falls back to the snapshot's value when the
// primary lookup is `undefined` (task absent), not when it resolves to an
// explicit false.
- const store = makeStore({
- kanban: {
- workflowId: WORKFLOW_ID,
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- workspaceOrphaned: false,
- },
- ],
- },
- kanbanMulti: {
- isLoading: false,
- snapshots: {
- [WORKFLOW_ID]: {
- workflowId: WORKFLOW_ID,
- workflowName: "WF1",
- steps: [],
- tasks: [
- {
- id: TASK_ID,
- workflowId: WORKFLOW_ID,
- workflowStepId: STEP_ID,
- title: TASK_TITLE,
- position: 0,
- workspaceOrphaned: true,
- },
- ],
- },
- },
- },
- } as Partial);
+ const store = makeOrphanedState(false, true);
const handler = registerKanbanHandlers(store)["kanban.update"]!;
handler(
diff --git a/apps/web/lib/ws/handlers/kanban.test.ts b/apps/web/lib/ws/handlers/kanban.test.ts
index 4233017ad6..3e2dc503c4 100644
--- a/apps/web/lib/ws/handlers/kanban.test.ts
+++ b/apps/web/lib/ws/handlers/kanban.test.ts
@@ -177,6 +177,9 @@ describe("kanban.update handler — foregroundActivity preservation", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
@@ -231,6 +234,9 @@ describe("kanban.update handler — foregroundActivity preservation", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
@@ -289,6 +295,9 @@ describe("kanban.update handler — taskPendingAction preservation", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
@@ -343,6 +352,9 @@ describe("kanban.update handler — taskPendingAction preservation", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
@@ -464,6 +476,9 @@ describe("kanban.update handler — repository switch", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
[WORKFLOW_ID]: {
workflowId: WORKFLOW_ID,
@@ -528,6 +543,9 @@ describe("kanban.update handler — explicit-null primary preservation", () => {
},
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
wf1: {
workflowId: "wf1",
@@ -565,6 +583,9 @@ describe("kanban.update handler — multi-snapshot primary lookup", () => {
kanban: { workflowId: "wf1", steps: [], tasks: [] },
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
wf1: {
workflowId: "wf1",
diff --git a/apps/web/lib/ws/handlers/kanban.ts b/apps/web/lib/ws/handlers/kanban.ts
index b0639b52dc..2b9206b048 100644
--- a/apps/web/lib/ws/handlers/kanban.ts
+++ b/apps/web/lib/ws/handlers/kanban.ts
@@ -2,7 +2,9 @@ import type { StoreApi } from "zustand";
import type { AppState } from "@/lib/state/store";
import type { WsHandlers } from "@/lib/ws/handlers/types";
import type { KanbanState } from "@/lib/state/slices/kanban/types";
+import type { ReorderBand, ReorderedTaskPosition } from "@/lib/types/http";
import { mergeTaskRepositoryFields } from "@/lib/ws/handlers/task-repositories";
+import { partitionWipTasks } from "@/lib/kanban/wip-queue";
type KanbanTask = KanbanState["tasks"][number];
type KanbanStep = KanbanState["steps"][number];
@@ -130,8 +132,184 @@ function preserveMultiSnapshotFields(
};
}
+function applyPositionsToTasks(
+ tasks: T[],
+ positionById: Map,
+): T[] {
+ let changed = false;
+ const next = tasks.map((task) => {
+ const position = positionById.get(task.id);
+ if (position === undefined || task.position === position) return task;
+ changed = true;
+ return { ...task, position };
+ });
+ return changed ? next : tasks;
+}
+
+const REORDER_BANDS: readonly ReorderBand[] = ["admitted", "queued"];
+
+function highestHeldReorderRevision(
+ withheld: AppState["kanbanMulti"]["withheldReorderByBandKey"],
+ stepId: string,
+): number {
+ return Object.entries(withheld).reduce((highest, [key, payload]) => {
+ if (!key.startsWith(`${stepId}:`) || !payload) return highest;
+ return Math.max(highest, payload.revision);
+ }, -1);
+}
+
+function holdPendingReorderTasks(
+ state: AppState,
+ stepId: string,
+ pendingBands: readonly ReorderBand[],
+ held: Record,
+ revision: number,
+): AppState {
+ let nextState = state;
+ for (const band of pendingBands) {
+ if (held[band].length === 0) continue;
+ const key = `${stepId}:${band}`;
+ const existing = nextState.kanbanMulti.withheldReorderByBandKey[key];
+ if (existing && existing.revision >= revision) continue;
+ nextState = {
+ ...nextState,
+ kanbanMulti: {
+ ...nextState.kanbanMulti,
+ withheldReorderByBandKey: {
+ ...nextState.kanbanMulti.withheldReorderByBandKey,
+ [key]: { revision, tasks: held[band] },
+ },
+ },
+ };
+ }
+ return nextState;
+}
+
+/**
+ * Classifies every task id in an event's whole-step payload into the band it
+ * currently belongs to, using this client's own last-known membership flags
+ * (a reorder never changes band membership, so a stale-but-recent local copy
+ * is a safe classifier). A task not found locally (e.g. not yet hydrated on
+ * this client) is left unclassified so its position is applied rather than
+ * held against nothing.
+ */
+function classifyTasksByBand(
+ tasks: ReorderedTaskPosition[],
+ stepId: string,
+ membershipSources: KanbanTask[][],
+): Map {
+ const byId = new Map();
+ for (const source of membershipSources) {
+ const stepTasks = source.filter((task) => task.workflowStepId === stepId);
+ if (stepTasks.length === 0) continue;
+ const { admitted, queued } = partitionWipTasks(stepTasks, stepId);
+ for (const task of admitted) if (!byId.has(task.id)) byId.set(task.id, "admitted");
+ for (const task of queued) if (!byId.has(task.id)) byId.set(task.id, "queued");
+ }
+ const result = new Map();
+ for (const task of tasks) {
+ const band = byId.get(task.id);
+ if (band) result.set(task.id, band);
+ }
+ return result;
+}
+
+function makeTaskReorderedHandler(store: StoreApi): WsHandlers["task.reordered"] {
+ return (message) => {
+ const { workflow_step_id: stepId, revision, tasks } = message.payload;
+
+ store.setState((state) => {
+ // Asymmetric revision gate (Decision 11 / F31): an unsolicited event
+ // only applies on a strictly-greater revision. A step with no recorded
+ // revision (-1) accepts the first order it ever receives.
+ const currentRevision = state.kanbanMulti.orderRevisionByStepId[stepId] ?? -1;
+ if (revision <= currentRevision) {
+ return state;
+ }
+
+ // A pending band can hold a newer whole-step event while the applied
+ // revision remains unchanged. An older event must not update the
+ // sibling band or replace that buffered snapshot on its way through.
+ const highestHeldRevision = highestHeldReorderRevision(
+ state.kanbanMulti.withheldReorderByBandKey,
+ stepId,
+ );
+ if (revision <= highestHeldRevision) {
+ return state;
+ }
+
+ // AC.27: a band with a reorder request in flight keeps its optimistic
+ // order until that request resolves; this whole-step payload's
+ // position for such a task is held rather than applied, while every
+ // other task in the same payload (the sibling band, or another step
+ // entirely) is applied immediately.
+ const pendingBands = REORDER_BANDS.filter(
+ (band) => state.kanbanMulti.pendingReorderBandKeys[`${stepId}:${band}`],
+ );
+ const bandByTaskId = pendingBands.length
+ ? classifyTasksByBand(tasks, stepId, [
+ state.kanban.tasks,
+ ...Object.values(state.kanbanMulti.snapshots).map((s) => s.tasks),
+ ])
+ : new Map();
+
+ const held: Record = { admitted: [], queued: [] };
+ const applyNow: ReorderedTaskPosition[] = [];
+ for (const task of tasks) {
+ const band = bandByTaskId.get(task.id);
+ if (band && pendingBands.includes(band)) {
+ held[band].push(task);
+ } else {
+ applyNow.push(task);
+ }
+ }
+
+ const nextState = holdPendingReorderTasks(state, stepId, pendingBands, held, revision);
+
+ if (applyNow.length === 0) {
+ // Every task in this payload belongs to a band still in flight —
+ // nothing observable changes yet, so the revision scalar is left
+ // alone; the withheld snapshot above carries the revision forward
+ // for reconciliation once the in-flight request resolves.
+ return nextState;
+ }
+
+ const positionById = new Map(applyNow.map((task) => [task.id, task.position]));
+ const nextKanbanTasks = applyPositionsToTasks(nextState.kanban.tasks, positionById);
+ let snapshotsChanged = false;
+ const nextSnapshots: typeof nextState.kanbanMulti.snapshots = {};
+ for (const [workflowId, snapshot] of Object.entries(nextState.kanbanMulti.snapshots)) {
+ const nextTasks = applyPositionsToTasks(snapshot.tasks, positionById);
+ if (nextTasks !== snapshot.tasks) {
+ snapshotsChanged = true;
+ nextSnapshots[workflowId] = { ...snapshot, tasks: nextTasks };
+ } else {
+ nextSnapshots[workflowId] = snapshot;
+ }
+ }
+
+ return {
+ ...nextState,
+ kanban:
+ nextKanbanTasks === nextState.kanban.tasks
+ ? nextState.kanban
+ : { ...nextState.kanban, tasks: nextKanbanTasks },
+ kanbanMulti: {
+ ...nextState.kanbanMulti,
+ snapshots: snapshotsChanged ? nextSnapshots : nextState.kanbanMulti.snapshots,
+ orderRevisionByStepId: {
+ ...nextState.kanbanMulti.orderRevisionByStepId,
+ [stepId]: revision,
+ },
+ },
+ };
+ });
+ };
+}
+
export function registerKanbanHandlers(store: StoreApi): WsHandlers {
return {
+ "task.reordered": makeTaskReorderedHandler(store),
"kanban.update": (message) => {
const workflowId = message.payload.workflowId;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/apps/web/lib/ws/handlers/task-reordered.test.ts b/apps/web/lib/ws/handlers/task-reordered.test.ts
new file mode 100644
index 0000000000..12585ecd22
--- /dev/null
+++ b/apps/web/lib/ws/handlers/task-reordered.test.ts
@@ -0,0 +1,227 @@
+import { describe, it, expect } from "vitest";
+import type { StoreApi } from "zustand";
+import type { AppState } from "@/lib/state/store";
+import { registerKanbanHandlers } from "./kanban";
+
+// kanban.test.ts is already at the file-length limit, so task.reordered gets
+// its own file rather than growing that one further.
+
+const WORKFLOW_ID = "wf1";
+const STEP_ID = "step-1";
+
+type FakeTask = {
+ id: string;
+ workflowStepId: string;
+ position: number;
+ wipAdmitted?: boolean;
+ queuedForStepId?: string;
+};
+
+function makeTask(id: string, position: number): FakeTask {
+ return { id, workflowStepId: STEP_ID, position, wipAdmitted: true };
+}
+
+function makeQueuedTask(id: string, position: number): FakeTask {
+ return { id, workflowStepId: STEP_ID, position, wipAdmitted: false, queuedForStepId: STEP_ID };
+}
+
+function makeStore(overrides: {
+ tasks?: FakeTask[];
+ orderRevisionByStepId?: Record;
+ pendingReorderBandKeys?: Record;
+}) {
+ const tasks = overrides.tasks ?? [makeTask("a", 0), makeTask("b", 1), makeTask("c", 2)];
+ // Independently cloned per side: a handler that mutates only kanban.tasks
+ // (or only the snapshot) must not make a synchronization assertion pass
+ // by accident because both sides happen to share one array/objects.
+ const snapshotTasks = tasks.map((task) => ({ ...task }));
+ let state = {
+ kanban: { workflowId: WORKFLOW_ID, steps: [], tasks: tasks.map((task) => ({ ...task })) },
+ kanbanMulti: {
+ isLoading: false,
+ orderRevisionByStepId: overrides.orderRevisionByStepId ?? {},
+ pendingReorderBandKeys: overrides.pendingReorderBandKeys ?? {},
+ withheldReorderByBandKey: {},
+ snapshots: {
+ [WORKFLOW_ID]: {
+ workflowId: WORKFLOW_ID,
+ workflowName: "WF1",
+ steps: [],
+ tasks: snapshotTasks,
+ },
+ },
+ },
+ } as unknown as AppState;
+
+ return {
+ getState: () => state,
+ setState: (updater: AppState | ((s: AppState) => AppState)) => {
+ state =
+ typeof updater === "function" ? (updater as (s: AppState) => AppState)(state) : updater;
+ },
+ subscribe: () => () => {},
+ destroy: () => {},
+ getInitialState: () => state,
+ } as unknown as StoreApi;
+}
+
+function makeReorderedMessage(
+ revision: number,
+ tasks: Array<{ id: string; position: number }>,
+ band: "admitted" | "queued" = "admitted",
+) {
+ return {
+ id: "msg-1",
+ type: "notification" as const,
+ action: "task.reordered" as const,
+ payload: { workflow_step_id: STEP_ID, band, revision, tasks },
+ };
+}
+
+describe("task.reordered handler", () => {
+ it("applies positions to kanban.tasks and the matching snapshot, and records the revision", () => {
+ const store = makeStore({});
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(
+ makeReorderedMessage(1, [
+ { id: "c", position: 0 },
+ { id: "a", position: 1 },
+ { id: "b", position: 2 },
+ ]),
+ );
+
+ const tasks = store.getState().kanban.tasks;
+ expect(tasks.find((t) => t.id === "c")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(1);
+ expect(tasks.find((t) => t.id === "b")?.position).toBe(2);
+ const snapshotTasks = store.getState().kanbanMulti.snapshots[WORKFLOW_ID]?.tasks;
+ expect(snapshotTasks?.find((t) => t.id === "c")?.position).toBe(0);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(1);
+ });
+
+ it("ignores an event whose revision is not strictly greater than the recorded one", () => {
+ const store = makeStore({ orderRevisionByStepId: { [STEP_ID]: 5 } });
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(makeReorderedMessage(5, [{ id: "a", position: 2 }]));
+
+ expect(store.getState().kanban.tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(5);
+ });
+
+ it("applies the first order it ever receives for a step with no recorded revision", () => {
+ const store = makeStore({});
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(makeReorderedMessage(0, [{ id: "a", position: 9 }]));
+
+ expect(store.getState().kanban.tasks.find((t) => t.id === "a")?.position).toBe(9);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(0);
+ });
+
+ it("does not apply an event for a band with a request currently in flight (AC.27)", () => {
+ const store = makeStore({ pendingReorderBandKeys: { [`${STEP_ID}:admitted`]: true } });
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(makeReorderedMessage(1, [{ id: "a", position: 9 }]));
+
+ expect(store.getState().kanban.tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId[STEP_ID]).toBeUndefined();
+ });
+
+ it("still applies to a different band on the same step while the other band is pending", () => {
+ const store = makeStore({ pendingReorderBandKeys: { [`${STEP_ID}:queued`]: true } });
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(makeReorderedMessage(1, [{ id: "a", position: 9 }], "admitted"));
+
+ expect(store.getState().kanban.tasks.find((t) => t.id === "a")?.position).toBe(9);
+ });
+
+ it("applies the sibling band's positions from the same whole-step payload even when the event's own band matches the in-flight one (AC.27)", () => {
+ const store = makeStore({
+ tasks: [makeTask("a", 0), makeQueuedTask("q", 1)],
+ pendingReorderBandKeys: { [`${STEP_ID}:admitted`]: true },
+ });
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(
+ makeReorderedMessage(
+ 1,
+ [
+ { id: "a", position: 9 },
+ { id: "q", position: 5 },
+ ],
+ "admitted",
+ ),
+ );
+
+ const tasks = store.getState().kanban.tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "q")?.position).toBe(5);
+ expect(store.getState().kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toEqual({
+ revision: 1,
+ tasks: [{ id: "a", position: 9 }],
+ });
+ });
+
+ it("holds the pending band's positions from an event for the other band instead of applying them wholesale", () => {
+ const store = makeStore({
+ tasks: [makeTask("a", 0), makeQueuedTask("q", 1)],
+ pendingReorderBandKeys: { [`${STEP_ID}:admitted`]: true },
+ });
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(
+ makeReorderedMessage(
+ 1,
+ [
+ { id: "a", position: 9 },
+ { id: "q", position: 5 },
+ ],
+ "queued",
+ ),
+ );
+
+ const tasks = store.getState().kanban.tasks;
+ expect(tasks.find((t) => t.id === "a")?.position).toBe(0);
+ expect(tasks.find((t) => t.id === "q")?.position).toBe(5);
+ expect(store.getState().kanbanMulti.orderRevisionByStepId[STEP_ID]).toBe(1);
+ expect(store.getState().kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toEqual({
+ revision: 1,
+ tasks: [{ id: "a", position: 9 }],
+ });
+ });
+});
+
+describe("task.reordered revision buffering", () => {
+ it("keeps the newest held revision when an older event arrives later", () => {
+ const store = makeStore({ pendingReorderBandKeys: { [`${STEP_ID}:admitted`]: true } });
+ const handler = registerKanbanHandlers(store)["task.reordered"]!;
+
+ handler(
+ makeReorderedMessage(3, [
+ { id: "a", position: 30 },
+ { id: "b", position: 31 },
+ { id: "c", position: 32 },
+ ]),
+ );
+ handler(
+ makeReorderedMessage(2, [
+ { id: "a", position: 20 },
+ { id: "b", position: 21 },
+ { id: "c", position: 22 },
+ ]),
+ );
+
+ expect(store.getState().kanbanMulti.withheldReorderByBandKey[`${STEP_ID}:admitted`]).toEqual({
+ revision: 3,
+ tasks: [
+ { id: "a", position: 30 },
+ { id: "b", position: 31 },
+ { id: "c", position: 32 },
+ ],
+ });
+ });
+});
diff --git a/apps/web/lib/ws/handlers/tasks-pending-action.test.ts b/apps/web/lib/ws/handlers/tasks-pending-action.test.ts
index 45f3a9f7f4..2d1cc8c0d6 100644
--- a/apps/web/lib/ws/handlers/tasks-pending-action.test.ts
+++ b/apps/web/lib/ws/handlers/tasks-pending-action.test.ts
@@ -17,6 +17,9 @@ function pendingStore(taskPendingAction?: PendingAction) {
kanban: { workflowId: "wf1", steps: [], tasks: [task] },
kanbanMulti: {
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
snapshots: {
wf1: { workflowId: "wf1", workflowName: "Workflow", steps: [], tasks: [task] },
},
diff --git a/apps/web/lib/ws/handlers/workflows.test.ts b/apps/web/lib/ws/handlers/workflows.test.ts
index b5c3181f3b..91537f7bf2 100644
--- a/apps/web/lib/ws/handlers/workflows.test.ts
+++ b/apps/web/lib/ws/handlers/workflows.test.ts
@@ -263,6 +263,9 @@ describe("workflow step handlers", () => {
},
},
isLoading: false,
+ orderRevisionByStepId: {},
+ pendingReorderBandKeys: {},
+ withheldReorderByBandKey: {},
},
} as AppState);
const handlers = registerWorkflowsHandlers(store);
diff --git a/apps/web/src/locales/en/kanban.json b/apps/web/src/locales/en/kanban.json
index 89919ba52b..07de1b1781 100644
--- a/apps/web/src/locales/en/kanban.json
+++ b/apps/web/src/locales/en/kanban.json
@@ -81,6 +81,7 @@
"queuedCount_other": "{{count}} queued",
"queuedForStep": "Queued for {{step}}",
"queuedSection": "Queued",
+ "reorderPositionAnnouncement": "{{title}}, position {{position}} of {{total}}",
"repository": "Repository",
"searchPlaceholder": "Search...",
"searchSection": "Search",
diff --git a/apps/web/src/locales/en/task.json b/apps/web/src/locales/en/task.json
index 83b07e08d2..a87b1ef649 100644
--- a/apps/web/src/locales/en/task.json
+++ b/apps/web/src/locales/en/task.json
@@ -1892,6 +1892,8 @@
"taskMoveErrorDifferentWorkspace": "The task and target workflow must use the same workspace.",
"taskMoveErrorWorkflowStep": "The target step does not belong to the target workflow.",
"taskMoveErrorWipLimit": "The target workflow step is at its WIP limit.",
+ "failedToReorderTasks": "Failed to reorder tasks",
+ "taskReorderErrorGeneric": "The new order could not be saved. Try again.",
"movedTasksStepDescription_one": "The task is now in the selected step.",
"movedTasksStepDescription_other": "The tasks are now in the selected step.",
"movedTasksToStep_one": "Moved task to step",
diff --git a/apps/web/src/locales/pseudo/kanban.json b/apps/web/src/locales/pseudo/kanban.json
index 35b725f4ad..9b18e65d5c 100644
--- a/apps/web/src/locales/pseudo/kanban.json
+++ b/apps/web/src/locales/pseudo/kanban.json
@@ -81,6 +81,7 @@
"queuedCount_other": "{{count}} qũēũēď",
"queuedForStep": "Qũēũēď ƒōŕ {{step}}",
"queuedSection": "Qũēũēď",
+ "reorderPositionAnnouncement": "{{title}}, ƥōśĩţĩōń {{position}} ōƒ {{total}}",
"repository": "Ŕēƥōśĩţōŕŷ",
"searchPlaceholder": "Śēàŕćĥ...",
"searchSection": "Śēàŕćĥ",
diff --git a/apps/web/src/locales/pseudo/task.json b/apps/web/src/locales/pseudo/task.json
index 79f85e59f6..fa0f3162a3 100644
--- a/apps/web/src/locales/pseudo/task.json
+++ b/apps/web/src/locales/pseudo/task.json
@@ -1892,6 +1892,8 @@
"taskMoveErrorDifferentWorkspace": "Ţĥē ţàśķ àńď ţàŕĝēţ ŵōŕķƒĺōŵ ḿũśţ ũśē ţĥē śàḿē ŵōŕķśƥàćē.",
"taskMoveErrorWorkflowStep": "Ţĥē ţàŕĝēţ śţēƥ ďōēś ńōţ ƀēĺōńĝ ţō ţĥē ţàŕĝēţ ŵōŕķƒĺōŵ.",
"taskMoveErrorWipLimit": "Ţĥē ţàŕĝēţ ŵōŕķƒĺōŵ śţēƥ ĩś àţ ĩţś ŴĨƤ ĺĩḿĩţ.",
+ "failedToReorderTasks": "Ƒàĩĺēď ţō ŕēōŕďēŕ ţàśķś",
+ "taskReorderErrorGeneric": "Ţĥē ńēŵ ōŕďēŕ ćōũĺď ńōţ ƀē śàvēď. Ţŕŷ àĝàĩń.",
"movedTasksStepDescription_one": "Ţĥē ţàśķ ĩś ńōŵ ĩń ţĥē śēĺēćţēď śţēƥ.",
"movedTasksStepDescription_other": "Ţĥē ţàśķś àŕē ńōŵ ĩń ţĥē śēĺēćţēď śţēƥ.",
"movedTasksToStep_one": "Ḿōvēď ţàśķ ţō śţēƥ",
diff --git a/apps/web/src/locales/pt-pt/kanban.json b/apps/web/src/locales/pt-pt/kanban.json
index fc60b00cc2..8725355a73 100644
--- a/apps/web/src/locales/pt-pt/kanban.json
+++ b/apps/web/src/locales/pt-pt/kanban.json
@@ -76,6 +76,7 @@
"queuedCount_other": "{{count}} em fila",
"queuedForStep": "Em fila para {{step}}",
"queuedSection": "Em fila",
+ "reorderPositionAnnouncement": "{{title}}, posição {{position}} de {{total}}",
"repository": "Repositório",
"searchPlaceholder": "Pesquisar...",
"searchSection": "Pesquisar",
diff --git a/apps/web/src/locales/pt-pt/task.json b/apps/web/src/locales/pt-pt/task.json
index 48e9b95330..943a3154f0 100644
--- a/apps/web/src/locales/pt-pt/task.json
+++ b/apps/web/src/locales/pt-pt/task.json
@@ -1835,6 +1835,8 @@
"taskMoveErrorDifferentWorkspace": "A tarefa e o fluxo de trabalho de destino têm de usar a mesma área de trabalho.",
"taskMoveErrorWorkflowStep": "O passo de destino não pertence ao fluxo de trabalho de destino.",
"taskMoveErrorWipLimit": "O passo de destino atingiu o limite WIP.",
+ "failedToReorderTasks": "Falha ao reordenar tarefas",
+ "taskReorderErrorGeneric": "Não foi possível guardar a nova ordem. Tente novamente.",
"movedTasksStepDescription_one": "A tarefa está agora no passo selecionado.",
"movedTasksStepDescription_other": "As tarefas estão agora no passo selecionado.",
"movedTasksToStep_one": "Tarefa movida para o passo",
diff --git a/apps/web/src/locales/zh-cn/kanban.json b/apps/web/src/locales/zh-cn/kanban.json
index c18534a825..5ebd45cea0 100644
--- a/apps/web/src/locales/zh-cn/kanban.json
+++ b/apps/web/src/locales/zh-cn/kanban.json
@@ -76,6 +76,7 @@
"queuedCount_other": "{{count}} 个排队任务",
"queuedForStep": "已排队等待 {{step}}",
"queuedSection": "排队中",
+ "reorderPositionAnnouncement": "{{title}},第 {{position}} 位,共 {{total}} 位",
"repository": "仓库",
"searchPlaceholder": "搜索…",
"searchSection": "搜索",
diff --git a/apps/web/src/locales/zh-cn/task.json b/apps/web/src/locales/zh-cn/task.json
index 29f70c2c79..554db52ce9 100644
--- a/apps/web/src/locales/zh-cn/task.json
+++ b/apps/web/src/locales/zh-cn/task.json
@@ -1835,6 +1835,8 @@
"taskMoveErrorDifferentWorkspace": "任务和目标工作流必须使用同一工作区。",
"taskMoveErrorWorkflowStep": "目标步骤不属于目标工作流。",
"taskMoveErrorWipLimit": "目标工作流步骤已达到 WIP 限制。",
+ "failedToReorderTasks": "重新排序任务失败",
+ "taskReorderErrorGeneric": "无法保存新顺序,请重试。",
"movedTasksStepDescription_one": "任务现已位于所选步骤中。",
"movedTasksStepDescription_other": "任务现已位于所选步骤中。",
"movedTasksToStep_one": "已将任务移动到步骤",
diff --git a/apps/web/src/locales/zh-hk/kanban.json b/apps/web/src/locales/zh-hk/kanban.json
index d746710cb8..62b36ee210 100644
--- a/apps/web/src/locales/zh-hk/kanban.json
+++ b/apps/web/src/locales/zh-hk/kanban.json
@@ -76,6 +76,7 @@
"queuedCount_other": "{{count}} 個排隊任務",
"queuedForStep": "已排隊等待 {{step}}",
"queuedSection": "排隊中",
+ "reorderPositionAnnouncement": "{{title}},第 {{position}} 位,共 {{total}} 位",
"repository": "儲存庫",
"searchPlaceholder": "搜尋…",
"searchSection": "搜尋",
diff --git a/apps/web/src/locales/zh-hk/task.json b/apps/web/src/locales/zh-hk/task.json
index 5b7a32066f..7e6651139e 100644
--- a/apps/web/src/locales/zh-hk/task.json
+++ b/apps/web/src/locales/zh-hk/task.json
@@ -1835,6 +1835,8 @@
"taskMoveErrorDifferentWorkspace": "任務和目標工作流程必須使用同一工作區。",
"taskMoveErrorWorkflowStep": "目標步驟不屬於目標工作流程。",
"taskMoveErrorWipLimit": "目標工作流程步驟已達到 WIP 限制。",
+ "failedToReorderTasks": "重新排序任務失敗",
+ "taskReorderErrorGeneric": "無法儲存新順序,請重試。",
"movedTasksStepDescription_one": "任務現已位於所選步驟中。",
"movedTasksStepDescription_other": "任務現已位於所選步驟中。",
"movedTasksToStep_one": "已將任務移動到步驟",
diff --git a/apps/web/src/locales/zh-tw/kanban.json b/apps/web/src/locales/zh-tw/kanban.json
index 9d4f8d07a3..2d41075ac5 100644
--- a/apps/web/src/locales/zh-tw/kanban.json
+++ b/apps/web/src/locales/zh-tw/kanban.json
@@ -76,6 +76,7 @@
"queuedCount_other": "{{count}} 個排隊任務",
"queuedForStep": "已排隊等待 {{step}}",
"queuedSection": "排隊中",
+ "reorderPositionAnnouncement": "{{title}},第 {{position}} 位,共 {{total}} 位",
"repository": "儲存庫",
"searchPlaceholder": "搜尋…",
"searchSection": "搜尋",
diff --git a/apps/web/src/locales/zh-tw/task.json b/apps/web/src/locales/zh-tw/task.json
index 1a1e0ea6f6..1c48fe4b65 100644
--- a/apps/web/src/locales/zh-tw/task.json
+++ b/apps/web/src/locales/zh-tw/task.json
@@ -1835,6 +1835,8 @@
"taskMoveErrorDifferentWorkspace": "任務和目標工作流程必須使用同一工作區。",
"taskMoveErrorWorkflowStep": "目標步驟不屬於目標工作流程。",
"taskMoveErrorWipLimit": "目標工作流程步驟已達到 WIP 限制。",
+ "failedToReorderTasks": "重新排序任務失敗",
+ "taskReorderErrorGeneric": "無法儲存新順序,請重試。",
"movedTasksStepDescription_one": "任務現已位於所選步驟中。",
"movedTasksStepDescription_other": "任務現已位於所選步驟中。",
"movedTasksToStep_one": "已將任務移動到步驟",
diff --git a/docs/plans/kanban-task-reordering/plan.md b/docs/plans/kanban-task-reordering/plan.md
new file mode 100644
index 0000000000..d0dc6efa08
--- /dev/null
+++ b/docs/plans/kanban-task-reordering/plan.md
@@ -0,0 +1,25 @@
+---
+created: 2026-09-04
+status: complete
+requirements:
+ - REQ-TASKS-KANBAN-TASK-REORDERING-001
+system_design:
+ - ../../specs/tasks/system-design/kanban-task-reordering.md
+---
+
+# Implementation Plan: Kanban Task Reordering
+
+## Outcome
+
+Persist the user-defined order of tasks within each workflow-step band. The
+Kanban and Pipeline views use the same ordering contract, pointer and keyboard
+reordering share one request path, and every connected view converges on the
+server result.
+
+## Delivery
+
+- [x] [Task 01: implement task reordering](task-01-implement-kanban-task-reordering.md)
+
+The implementation uses the existing task service, repository, WebSocket, and
+Kanban state paths. It adds the step revision needed to reject stale client
+orders without changing workflow-step ownership or task-move behavior.
diff --git a/docs/plans/kanban-task-reordering/task-01-implement-kanban-task-reordering.md b/docs/plans/kanban-task-reordering/task-01-implement-kanban-task-reordering.md
new file mode 100644
index 0000000000..3a6b5f0348
--- /dev/null
+++ b/docs/plans/kanban-task-reordering/task-01-implement-kanban-task-reordering.md
@@ -0,0 +1,60 @@
+---
+id: "01-implement-kanban-task-reordering"
+title: "Implement Kanban task reordering"
+status: completed
+wave: 1
+depends_on: []
+plan: "plan.md"
+requirements:
+ - REQ-TASKS-KANBAN-TASK-REORDERING-001
+acceptance_criteria:
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.1
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.5
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.8
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.15
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.16
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.17
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.19
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.23
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.25
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.27
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.34
+ - AC-TASKS-KANBAN-TASK-REORDERING-001.38
+system_design:
+ - ../../specs/tasks/system-design/kanban-task-reordering.md
+---
+
+# Task 01: Implement Kanban task reordering
+
+## Scope
+
+Add the persisted reorder contract across the task repository and service,
+HTTP and WebSocket transport, Kanban state, and desktop and mobile board
+surfaces. Keep band membership derived from task state and keep workflow-step
+changes on their existing path.
+
+## Implementation
+
+- Validate task-write authorization and the complete band membership before
+ writing positions.
+- Lock the workspace, source, and target step rows in a stable order, then
+ allocate dense positions for the two bands.
+- Publish step revisions with the reordered task positions.
+- Apply HTTP and WebSocket updates to both workflow snapshots and the main
+ Kanban task projection, while retaining the newest buffered revision.
+- Support pointer and keyboard reorder interactions in the Kanban surfaces;
+ keep Pipeline display-only.
+
+## Verification
+
+Focused backend service, handler, and repository tests cover authorization,
+HTTP errors, source-step lock drift, and persisted ordering. Focused frontend
+tests cover HTTP/WebSocket revision reconciliation and both Kanban projections.
+Web type checking, scoped lint and formatting, and the affected post-merge
+Kanban tests pass.
+
+## References
+
+The requirement and system design define the complete ordering, validation,
+concurrency, and presentation contract. This work order records the delivery
+slice for that contract and its regression evidence.
diff --git a/docs/public/tasks-and-workflows.md b/docs/public/tasks-and-workflows.md
index 4a015dbf0f..a33083e0fa 100644
--- a/docs/public/tasks-and-workflows.md
+++ b/docs/public/tasks-and-workflows.md
@@ -469,6 +469,8 @@ Choose **Last activity** when you want to review tasks by the least recent user
- Parent tasks and direct subtasks are indented as a tree.
- A subtask's action menu can detach it into a top-level task. Detaching preserves its workflow position and descendants; an inherited workspace remains shared with the former parent.
+On desktop and tablet, drag a card up or down within its column to reorder it relative to the other cards in that step. You can also focus a card and press **Space** or **Enter** to pick it up, **Arrow Up**/**Arrow Down** to move it, **Space**/**Enter** again to drop it, or **Escape** to cancel. The new order is saved immediately and shown to other viewers of the same board.
+
On phones, Kanban focuses one workflow and one step at a time. The board navigator always names both; open it to choose either level, or use the previous/next controls and horizontal swipe to move between steps. Choosing a workflow makes it the active workflow for board actions and task creation. Tap a card to open that task directly. Its **More options** menu opens as a touch-sized bottom surface; **Move to** changes the task's workflow or step. **Edit** can still rename a task after work starts, while its original prompt remains locked.
Regular Kanban does not currently expose label editing or label filters. Do not design a supported Kanban process around labels.
diff --git a/docs/specs/tasks/requirements/kanban-task-reordering.md b/docs/specs/tasks/requirements/kanban-task-reordering.md
new file mode 100644
index 0000000000..e14df428ca
--- /dev/null
+++ b/docs/specs/tasks/requirements/kanban-task-reordering.md
@@ -0,0 +1,343 @@
+---
+status: active
+system: tasks
+created: 2026-09-04
+owners:
+ - kandev
+---
+# Kanban Task Reordering Requirements
+
+## Overview
+
+A workflow step's task order already decides real behavior: the WIP overflow
+queue promotes the lowest-`position` task when a slot frees. Today a
+user cannot set it. `position` is written only as a side effect of a move, and
+the board sorts each column newest first, so what the user sees is unrelated to
+what the system picks up next. This capability makes that order
+a user-controlled, persisted contract: the user drags a card to a new place in
+its column, every view reconciles to it, and the top card is the one the step
+takes next.
+
+Prior art, the wire contract, and the mechanism behind these criteria are in the
+paired [system design](../system-design/kanban-task-reordering.md).
+
+## Terminology
+
+- **Step list:** The ordered tasks the board renders for one workflow step.
+- **Task position:** The `position` column of a task, which this capability
+ makes user-controlled. Every unqualified use of "position" in this document
+ means this column.
+- **Step ordinal:** The `position` column of a workflow *step*, fixing that
+ step's place among its workflow's steps. A different column from the task
+ position, and never written by a reorder.
+- **Queued band:** Tasks physically in the step that are queued for that same
+ step and not WIP-admitted (`wip_admitted` false and `queued_for_step_id`
+ equal to the step).
+- **Admitted band:** Every task of the step that is not in the step's queued
+ band. Defined by exclusion, so the two bands partition the step. A task
+ sitting here while queued for a *different* step is therefore admitted here
+ and reordered like any other member.
+- **Band:** The admitted band or the queued band of one step.
+- **Hidden task:** A task the board never shows in any step list: archived
+ (`archived_at` set), ephemeral (`is_ephemeral` true), or automation-run
+ (`origin` equal to `automation_run`).
+- **Band membership:** The tasks of a band that are not hidden tasks.
+ Membership is independent of any board filter.
+- **Step order:** The order AC-TASKS-KANBAN-TASK-REORDERING-001.1 defines over
+ the tasks of one band. Where a criterion applies it across a whole step, it
+ means those same keys over the step's non-hidden tasks.
+- **Reorder:** A request that rewrites the stored order of exactly one band.
+
+## Requirements
+
+### REQ-TASKS-KANBAN-TASK-REORDERING-001: Persisted task order within a workflow step
+
+**Intent:** Give a step's task order a single, persisted, user-controlled
+definition so the board shows, and the WIP pull uses, the same priority order.
+
+**User story:** As a user with a full backlog, I want to drag a task to the top
+of its step, so that it is visibly and actually the next task that step takes.
+
+#### Acceptance criteria
+
+##### Order contract
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.1:** The system shall order the tasks of
+ a band by `position` ascending, then by priority rank (`critical`, `high`,
+ `medium`, `low`, then any other or absent value), then by `queued_at`
+ ascending treating an absent `queued_at` as that task's `created_at`, then by
+ `created_at` ascending, then by `id` ascending. Every key is a named column
+ and `id` is unique, so the order is total for any two distinct tasks.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.36:** The board, the queue comparator
+ and every promotion comparison shall apply
+ AC-TASKS-KANBAN-TASK-REORDERING-001.1's `queued_at` key identically, using
+ the absent-value rule stated there. No other promotion behavior, including
+ which candidate source is preferred, shall change.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.2:** The board shall render every step
+ list in step order in both shipped views: the Kanban view, on desktop, tablet
+ and mobile, and the Pipeline view. Lower `position` shall render nearer the
+ top. The topmost card of a band is the one it yields next, except under a
+ board filter, where AC-TASKS-KANBAN-TASK-REORDERING-001.34 governs and a
+ hidden member may rank ahead of it. In the Kanban view, which splits a
+ step into bands, the admitted band shall render first and the queued band
+ below it under the existing queued divider. The Pipeline view, which renders
+ one row per task and has no divider, shall order each step's rows by
+ AC-TASKS-KANBAN-TASK-REORDERING-001.1 and shall gain no band split.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.3:** The system shall order the two
+ bands of a step independently: a change to one band shall not change the
+ relative order of the other.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.4:** When a WIP slot frees in a step,
+ the system shall choose the candidate source exactly as it does today,
+ preferring the step's own queued band over its configured feeder step, and
+ within the chosen source shall promote the first candidate in step order. The
+ destination-first contract in
+ [WIP Limits and Visible Overflow Queues](wip-limit-pull-system.md) is
+ unchanged apart from AC-TASKS-KANBAN-TASK-REORDERING-001.36's alignment.
+
+##### Reorder interaction
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.5:** When a user drags a card and drops
+ it at a different index within the same band, the system shall commit that
+ band's new order.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.6:** A drag shall start from the card
+ body under the existing activation constraints (pointer movement of at least
+ 8 CSS pixels, or a touch hold of at least 250 ms), and no grab handle shall be
+ added. A click that does not exceed the activation constraint shall retain its
+ current behavior.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.7:** While a card is dragged over its
+ own band, the system shall show the insertion point the drop would take.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.8:** When a drop commits, the board
+ shall show the new order immediately and then reconcile to the persisted
+ order returned by the system.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.9:** When a drag is cancelled by the
+ Escape key or dropped outside any band, the system shall leave the order
+ unchanged and shall issue no reorder request.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.10:** When a drop would produce the
+ order already displayed, the system shall issue no reorder request and shall
+ leave the board unchanged.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.11:** When a card is dropped on the
+ other band of the same step, the system shall reject the drop, leave both
+ bands unchanged, and issue no request.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.12:** A user shall be able to reorder a
+ card within its band using the keyboard alone, on the same presentations that
+ accept a pointer reorder. With a card focused, Space or Enter shall pick it
+ up, Up Arrow and Down Arrow shall move it one place among the band members the
+ board is currently showing, Space or
+ Enter shall drop it and commit, and Escape shall cancel it under
+ AC-TASKS-KANBAN-TASK-REORDERING-001.9. While a card is picked up the board
+ shall show the insertion point of AC-TASKS-KANBAN-TASK-REORDERING-001.7 and
+ shall announce the card's place in its band to assistive technology on pick-up
+ and each move. An arrow press that would carry the card out of its band, or
+ past the last member the board is showing, shall be ignored. The committed
+ order shall be derived as in AC-TASKS-KANBAN-TASK-REORDERING-001.34 and shall
+ persist identically to a pointer drag.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.13:** Dragging a card onto a different
+ step shall continue to move the task to that step with its existing
+ behavior.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.38:** The Pipeline view shall render
+ step order per AC-TASKS-KANBAN-TASK-REORDERING-001.2 but shall accept no
+ reorder by any input, neither a pointer drag nor the keyboard commands of
+ AC-TASKS-KANBAN-TASK-REORDERING-001.12, and shall issue no reorder request.
+ Its existing per-task step-move control is unchanged.
+
+##### Persistence and propagation
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.14:** The system shall persist a
+ committed order server-side so that it survives a page reload, a workflow or
+ workspace switch, and a Kandev restart.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.15:** When a reorder commits, the system
+ shall renumber the named step densely from `0`: immediately after a reorder
+ the `position` values of the step's non-hidden tasks shall be exactly `0`
+ through `N-1`, where `N` is their count, with no gap and no duplicate. The
+ reordered band shall hold the submitted sequence, the other band shall keep
+ its existing relative order, and each band's values shall be contiguous and
+ disjoint from the other band's, with the admitted band taking the lower
+ range. A hidden task's `position` shall not be rewritten and shall not
+ participate in this guarantee. Band membership shall never be inferred
+ from `position`; it is decided by `wip_admitted` and `queued_for_step_id`.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.16:** When a reorder commits, the system
+ shall publish it so every connected view of that workflow reconciles to the
+ new order without a manual refresh.
+
+##### Reorder request contract
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.17:** A reorder shall name one workflow
+ step, name which of its two bands it targets as an explicit value rather than
+ one inferred from the submitted identifiers, and carry the complete ordered
+ list of task identifiers for that band. A reorder
+ shall not carry a single task's new index.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.18:** When the request names no valid
+ band, or the submitted identifier list is empty, contains a duplicate, names a task that is not in the named step, or
+ names a task that is in the named step but not in the named band, the system
+ shall reject the request with a validation error and shall change no
+ `position`.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.19:** When the submitted identifier set
+ does not exactly equal the current membership of the named band, the system
+ shall reject the whole request atomically with the typed conflict error
+ `step_changed`, shall change no `position`, and the board shall silently
+ reconcile to the authoritative order without showing an error.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.20:** When a reorder is rejected for any
+ reason other than the conflict in
+ AC-TASKS-KANBAN-TASK-REORDERING-001.19, the board shall restore the
+ authoritative order and shall show a localized failure message.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.21:** A reorder shall not change any
+ task's workflow, workflow step, WIP admission, queued destination, queued
+ time, or state; shall not start, stop or interrupt a session; and shall not
+ run step entry or exit behavior, record a step transition, or publish a
+ task-moved event.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.22:** The system shall accept a reorder
+ for a step whose tasks have active sessions, and shall not apply the
+ active-session restriction that guards a step change.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.23:** A caller authorized to move a task
+ in a workflow shall be authorized to reorder the tasks within that workflow's
+ steps. This grants no authority over the step ordinal, which a separate
+ shipped capability owns. The request shall carry no caller-supplied identity,
+ and submitted identifiers shall be validated against persisted membership
+ before any write.
+
+##### Idempotency and concurrency
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.24:** When the same reorder request is
+ submitted more than once and the band's membership has not changed, each
+ submission shall succeed and shall leave the same persisted order, so a retry
+ is safe.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.25:** When two callers submit reorders
+ for the same band with the same membership, the system shall apply them in
+ arrival order, the last committed order shall be authoritative, and every
+ connected view shall reconcile to it.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.26:** When the named band's membership
+ changes between the client reading the order and the drop committing — a task
+ created in, moved into or out of, deleted from, promoted into or queued into
+ it, or becoming a hidden task — the system shall treat the request as the
+ conflict in AC-TASKS-KANBAN-TASK-REORDERING-001.19. Any membership change in
+ that window conflicts, whatever caused it.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.27:** While a reorder request for a band
+ is in flight, the board shall not issue a second reorder request for that
+ band, and shall prevent one being started: its cards shall not accept a
+ reorder drop and shall not accept the keyboard commands of
+ AC-TASKS-KANBAN-TASK-REORDERING-001.12, and the board shall keep showing the
+ optimistic order from AC-TASKS-KANBAN-TASK-REORDERING-001.8 until the request
+ resolves. A gesture already in progress shall be cancelled under
+ AC-TASKS-KANBAN-TASK-REORDERING-001.9 rather than queued. Only reordering is
+ suspended: a card in that band shall stay draggable and a drop on another step
+ shall move it under AC-TASKS-KANBAN-TASK-REORDERING-001.13, while a drop
+ within its own band shall be ignored. The step's other band, and every other
+ step, shall stay reorderable. A published order under
+ AC-TASKS-KANBAN-TASK-REORDERING-001.16 arriving while the request is in flight
+ shall be applied to the other band and to other steps, while this band holds
+ its optimistic order until the request resolves.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.37:** When two reorders name the same
+ step, the system shall apply them one at a time rather than concurrently, each
+ renumbering the step from the state the previous one committed. When they name
+ the step's two different bands, neither shall be rejected because of the
+ other, and each band shall end in the order its own reorder submitted. When
+ they name the same band,
+ AC-TASKS-KANBAN-TASK-REORDERING-001.25 governs instead.
+
+##### Placement of arriving tasks
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.28:** When a task enters a band by
+ creation, manual move, bulk move, drag between steps, WIP promotion, or
+ automatic workflow transition, the system shall give it a `position` one
+ greater than the highest held by any non-hidden task already in that step, or
+ `0` when the step holds none, and shall not disturb the relative order of the
+ tasks there. The arriving task therefore sorts last in its band and never
+ displaces work a user has already ordered. An arrival shall observe that
+ highest value and write its own atomically with respect to any reorder of the
+ same step, so that an arrival concurrent with a reorder still sorts last.
+ Between reorders a step's values may therefore be non-contiguous and the two
+ bands' ranges may overlap:
+ AC-TASKS-KANBAN-TASK-REORDERING-001.15's dense guarantee holds immediately
+ after a reorder, not permanently. A `position` supplied by the caller on any
+ of these paths shall be ignored, including the plugin move API's `position`
+ field, whose documented top-of-step meaning this criterion supersedes. A move
+ naming the task's current step is not an arrival and shall leave its
+ `position` unchanged.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.29:** When several tasks enter the same
+ band in one bulk move, the system shall place them last in that band, ordered
+ by the step ordinal of their source step ascending and, within one source
+ step, by that step's admitted band in step order followed by its queued band
+ in step order. Their `position` values shall be consecutive, shall start from
+ the value AC-TASKS-KANBAN-TASK-REORDERING-001.28 defines, and shall preserve
+ that sequence.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.30:** When a task leaves a band, the
+ system shall preserve the relative order of the remaining tasks. `position`
+ values need not remain contiguous after a departure.
+
+##### Existing data and empty states
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.31:** The system shall require no
+ migration of stored `position` values, and shall rewrite a task's `position`
+ only when that task is in a step being renumbered under
+ AC-TASKS-KANBAN-TASK-REORDERING-001.15 or is entering a band under
+ AC-TASKS-KANBAN-TASK-REORDERING-001.28. No task in another step, and no
+ hidden task, shall have its `position` rewritten.
+ Existing tasks that share a `position` shall order by the remaining keys of
+ AC-TASKS-KANBAN-TASK-REORDERING-001.1.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.32:** An empty step shall render as it
+ does today and shall accept a card dragged from another step. A band that
+ shows fewer than two tasks shall render them, shall offer no reorder within
+ itself, and shall issue no reorder request, whether its membership is that
+ small or a board filter hides the rest.
+
+##### Hidden and filtered tasks
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.33:** A task already hidden when the
+ client read the band (Terminology's hidden tasks) shall never be part of band
+ membership, shall never be named in a reorder, shall never have its `position`
+ rewritten, and shall never cause the conflict in
+ AC-TASKS-KANBAN-TASK-REORDERING-001.19. A task that becomes hidden inside the
+ window is governed by AC-TASKS-KANBAN-TASK-REORDERING-001.26 instead and does
+ conflict. The membership a submitted list is validated against shall exclude
+ exactly the classes the board excludes when it renders the step list, so a
+ client submitting every task it can see never conflicts on a task it was never
+ shown.
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.34:** When the board hides part of a band
+ because a search query, repository filter, or plugin task filter is active,
+ reordering shall remain available, and the request shall carry the band's
+ complete membership rather than only the visible tasks. No task but the
+ dragged one shall change its relative order, so filtered-out tasks are never
+ rearranged by a reorder they were not part of. When the filter leaves the band
+ showing fewer than two
+ tasks, AC-TASKS-KANBAN-TASK-REORDERING-001.32 applies and no reorder is
+ offered.
+
+## Compatibility
+
+- **AC-TASKS-KANBAN-TASK-REORDERING-001.35:** After this capability ships, a
+ step list that has never been reordered shall render in the order of
+ AC-TASKS-KANBAN-TASK-REORDERING-001.1, where it previously rendered newest
+ task first. Tasks created in the step they still occupy hold `position` 0 and
+ therefore sort together, highest priority first and oldest first within a
+ priority; tasks moved, bulk-moved or promoted in hold whatever their move path
+ wrote and may sort after them. No stored `position` changes, and the only
+ promotion change is the tiebreak alignment of
+ AC-TASKS-KANBAN-TASK-REORDERING-001.36.
+
+## Out of scope
+
+- **Dragging a card between different steps or workflows.** Unchanged by
+ AC-TASKS-KANBAN-TASK-REORDERING-001.13.
+- **Dragging a card across the admitted and queued divider.** Rejected by
+ AC-TASKS-KANBAN-TASK-REORDERING-001.11.
+- **Reordering in the Pipeline view, by pointer or keyboard.** Per
+ AC-TASKS-KANBAN-TASK-REORDERING-001.38: it lays out one row per task, so no
+ insertion point or arrow has a defined meaning there.
+- **A band split or queued divider in the Pipeline view.** It has neither today
+ and gains neither, per AC-TASKS-KANBAN-TASK-REORDERING-001.2.
+- **Selecting several cards and dragging them as a group.** Bulk move keeps its
+ existing multi-select path, placed by
+ AC-TASKS-KANBAN-TASK-REORDERING-001.29.
+- **Move-up and move-down buttons or a menu action.** Covered by
+ AC-TASKS-KANBAN-TASK-REORDERING-001.12.
+- **Choosing where a new task lands.** Arrivals go last, per
+ AC-TASKS-KANBAN-TASK-REORDERING-001.28.
+- **Any other sort key, or a sort control.** Step order is exactly
+ AC-TASKS-KANBAN-TASK-REORDERING-001.1.
+- **Changing `priority`, or deriving it from `position`.** They stay separate.
+- **Unifying any promotion behavior beyond the `queued_at` tiebreak.**
+ AC-TASKS-KANBAN-TASK-REORDERING-001.36 aligns that one key and nothing else.
+- **A WebSocket action for a reorder.** HTTP only here; deferred as Kandev task
+ `48fe260c-de9d-434b-8c8f-3aed46280dca`.
+- **Reordering from the task list, sidebar, command panel, or Office
+ surfaces.** Those have their own orderings and are untouched.
diff --git a/docs/specs/tasks/system-design/kanban-task-reordering.md b/docs/specs/tasks/system-design/kanban-task-reordering.md
new file mode 100644
index 0000000000..debc3c61b8
--- /dev/null
+++ b/docs/specs/tasks/system-design/kanban-task-reordering.md
@@ -0,0 +1,506 @@
+---
+status: current
+system: tasks
+requirements:
+ - REQ-TASKS-KANBAN-TASK-REORDERING-001
+created: 2026-09-04
+owners:
+ - kandev
+---
+# Kanban Task Reordering System Design
+
+## Purpose
+
+Paired design for
+[Kanban Task Reordering](../requirements/kanban-task-reordering.md). The
+requirement states what a user observes; this file states the mechanism behind
+it, the prior art the contract was drawn from, and the reasoning that would
+otherwise have to be rediscovered at build time.
+
+## Requirement mapping
+
+| Requirement | Satisfied by |
+| --- | --- |
+| `REQ-TASKS-KANBAN-TASK-REORDERING-001` `.1`, `.36` | Ordering keys and the promotion comparators |
+| `.2`, `.38` | Surfaces |
+| `.12` | Surfaces, Position allocation |
+| `.8`, `.16`, `.17`, `.18`, `.19`, `.20`, `.25` | Reorder contract |
+| `.15`, `.28`, `.29`, `.30`, `.31` | Position allocation |
+| `.26`, `.27`, `.37` | Concurrency |
+| `.32`, `.33`, `.34` | Band model, Position allocation |
+
+## Prior art
+
+**Wiki (`OBSIDIAN_VAULT_PATH=/Users/henry/Documents/henry/wiki`, QMD collection
+`wiki`).** Queried twice: `lex: kanban board ordering drag drop reorder backlog
+priority queue position` / `vec: how tasks should be ordered in a kanban column
+and how drag-and-drop reordering with a persisted position field works`, then
+`lex: backlog prioritization WIP limit queue next in line pull` / `vec: how to
+decide what work gets picked up next, backlog ordering, work-in-progress limits
+and pull-based queues`. Direct page reads were unavailable (the vault path is
+not readable from the task sandbox, so `grep` and `obsidian-wiki graph-query`
+both failed); QMD's own index served the retrieval. **The wiki returned nothing
+useful on board ordering or drag-and-drop reordering.** The nearest hits are
+product-method pages, not interaction or persistence contracts:
+`concepts/shape-up.md` (0.39) records the Basecamp position that backlogs,
+sprints and points should be replaced by a betting table, and
+`concepts/roadmap-from-failure-signal.md` (0.78) records Block's inversion where
+customer signal generates the backlog rather than prioritising within it.
+Neither takes a position this specification departs from: both argue about where
+a backlog comes from, not how an existing queue is ordered. No prior position is
+overridden.
+
+**Cross-vendor (`saas-kb` / `search_fsm_docs`, `category: "ai_sdlc"`).**
+Unavailable: the tool is not exposed in this session and no tool-discovery
+mechanism is offered, so this leg did not run. Recorded rather than faked.
+
+**In-repo prior art, which is the load-bearing one.** Kandev has already solved
+this problem once, for the session message queue:
+[Reorder Queued Messages](../../ui/requirements/message-queue-reorder.md). Its
+request contract is followed deliberately: submit the whole ordered id set
+rather than one task's new index, validate the submitted set against the current
+persisted set and reject atomically when it differs, rewrite positions to a
+dense sequence, update optimistically and reconcile to the server. Two
+departures. The grab handle, per
+AC-TASKS-KANBAN-TASK-REORDERING-001.6: message rows carry a dedicated handle
+because their bodies own text selection and inline editing, whereas a kanban
+card is already dragged by its whole body for cross-step moves, so a handle
+would make the two drags on one card start differently. And the band
+discriminator, per AC-TASKS-KANBAN-TASK-REORDERING-001.17: a message queue has
+one list per session, so `{session_id, ordered_ids}` needs no band field, while
+a step has two bands and the request must say which one it names.
+
+That document also carries `## API Surface`, `## Data Model` and
+`## Failure Modes` sections. Those are migrated legacy detail, not the current
+house style for a requirement, which is why the paired requirement here does not
+imitate them. The equivalents live below: the wire contract in
+`## Reorder contract`, the storage rules in `## Position allocation`, and the
+failure and race behavior in `## Concurrency`.
+
+## Reorder contract
+
+The requirement names an error token (`step_changed`,
+AC-TASKS-KANBAN-TASK-REORDERING-001.19), requires the board to reconcile to
+"the persisted order returned by the system"
+(AC-TASKS-KANBAN-TASK-REORDERING-001.8), and requires publication to every
+connected view (AC-TASKS-KANBAN-TASK-REORDERING-001.16). Those three are only
+observable if one carrier is named, and
+AC-TASKS-KANBAN-TASK-REORDERING-001.20 makes the split behavioral: the board
+reconciles silently on `step_changed` and shows a localized message on anything
+else. Backend and frontend must therefore agree on where the token appears.
+
+**Route.** `PUT /api/v1/workflow-steps/:id/tasks/reorder`. This mirrors the
+existing collection-reorder precedent `PUT
+/api/v1/workspaces/:id/workflows/reorder`
+(`task/handlers/route_registration_test.go`): a `PUT` on a collection nested
+under the parent whose order is being rewritten. The step is the path
+parameter, so the request body never repeats it.
+
+**This route is the only request surface for a reorder.** A WebSocket request
+action was specified in an earlier draft and then deliberately cut; the
+requirement's `## Out of scope` names the task that tracks it. Nothing in the
+board loses anything by that: it already moves a task between steps over HTTP,
+so a reorder now travels the same way as the gesture beside it. The cut is
+scoped to the *request*, and **Publication** below is unaffected —
+`task.reordered` is still delivered over the WebSocket event stream, so
+AC-TASKS-KANBAN-TASK-REORDERING-001.16's live reconciliation across connected
+views works exactly as specified. A reader who finds only one surface here is
+looking at a decision, not an omission.
+
+**Request.** `{"band": "admitted" | "queued", "ordered_task_ids": [...]}`. The
+band is an explicit discriminator rather than something inferred from the
+submitted ids. Inference would make
+AC-TASKS-KANBAN-TASK-REORDERING-001.18's both-bands rejection depend on the
+very value it is validating, and would leave the empty-list case with no band
+at all. Explicit means validation is a single pass: resolve the named band's
+membership, then compare the submitted set against it.
+
+**Success.** `200` with `{"workflow_step_id": ..., "revision": ...,
+"tasks": [{"id": ..., "position": ...}]}` covering the step's non-hidden tasks
+in their new order,
+both bands. The whole step is returned because a reorder renumbers the whole
+step (AC-TASKS-KANBAN-TASK-REORDERING-001.15), so returning only the named band
+would leave the client unable to reconcile the sibling band it just saw change.
+
+**Rejection.** The conflict in AC-TASKS-KANBAN-TASK-REORDERING-001.19 is `409`
+with `{"code": "step_changed", "workflow_step_id": ..., "revision": ...,
+"tasks": [{"id": ..., "position": ...}]}` — the same whole-step list the
+success body carries. The conflict response carries the order deliberately:
+AC-TASKS-KANBAN-TASK-REORDERING-001.19 requires the board to reconcile
+*silently* to the authoritative order, and a bare error code leaves it nothing
+to reconcile to, forcing the builder to invent either an unspecified refetch or
+a wait on an event that may not have arrived yet. Validation failures under
+AC-TASKS-KANBAN-TASK-REORDERING-001.18 are `400` with the code
+`invalid_reorder` and no task list, because a malformed request implies nothing
+about the persisted order; AC-TASKS-KANBAN-TASK-REORDERING-001.20's restore is
+then from what the client already holds. The board branches on `code`, which is
+what makes AC-TASKS-KANBAN-TASK-REORDERING-001.20's
+silent-reconcile-versus-message split implementable.
+
+**Publication.** A new event `task.reordered` in the `task.*` family
+(`internal/events/types.go`), payload `{workflow_step_id, band, revision,
+tasks: [{id, position}]}` with the same whole-step task list and revision as
+the success body. Deliberately not `task.moved`
+(AC-TASKS-KANBAN-TASK-REORDERING-001.21 forbids it) and deliberately not N
+separate `task.updated` events, because a view applying a reorder one task at a
+time would render intermediate orders that were never persisted.
+
+**Which order wins (AC-TASKS-KANBAN-TASK-REORDERING-001.25).** Each step
+carries a monotonic `order_revision`, incremented once per committed reorder of
+that step inside the same serialized section that renumbers it. Every carrier
+of an order — the `200` body, the `409` body and the `task.reordered` payload —
+reports the revision its order was written at. A view applies an *unsolicited*
+published order only when that revision is greater than the one it already holds
+for that step, and applies the body of a response to *its own* request when that
+revision is greater than **or equal to** the one it holds.
+
+The equal case is not a detail, it is the whole reason the two rules differ. The
+counter advances once per committed reorder, so a membership change that is not a
+reorder — an arrival under
+AC-TASKS-KANBAN-TASK-REORDERING-001.28, or any other cause listed in
+AC-TASKS-KANBAN-TASK-REORDERING-001.26 — changes the step's order without
+changing its revision. A `409` reports the state at rejection time, which is
+exactly that case: **an equal revision does not mean an equal order.** Gating the
+`409` on a strictly greater revision would therefore discard the very list
+AC-TASKS-KANBAN-TASK-REORDERING-001.19 requires the board to reconcile to,
+leaving it showing an optimistic order it never persisted and showing no error —
+silently, which is the one outcome that criterion rules out. A response body is
+safe on equality where an event is not, because it is causally after the
+caller's own request and reports the step as the serialized section saw it.
+
+Resolving a request therefore also releases the in-flight hold of
+AC-TASKS-KANBAN-TASK-REORDERING-001.27: the board reconciles that band to the
+highest-revision order it now holds for the step, counting both the response body
+and any `task.reordered` it received and withheld while the request was
+outstanding. Should those two carry the *same* revision and different orders —
+possible, because the response is read after the event's reorder committed and
+may include a membership change that bumped nothing — the response body wins, as
+the later read. A view holding no revision for a step yet, which is every view
+until its first carrier arrives, applies the first order it receives.
+
+The alternative fix — bumping the revision on every membership change — was
+rejected: it puts a step-row write on the path of every task creation and move,
+where this rule costs nothing.
+
+Without this, AC-TASKS-KANBAN-TASK-REORDERING-001.25's "the last committed
+order shall be authoritative, and every connected view shall reconcile to it"
+is not implementable from the client side: a `200` for reorder A can arrive
+after the `task.reordered` for a later reorder B, and a view trusting arrival
+order would render A and stay there. The counter is per step, so unrelated
+steps never invalidate each other, and it lives on the step rather than in the
+task rows, so it adds no per-task write and does not touch stored `position`
+values (AC-TASKS-KANBAN-TASK-REORDERING-001.31). It is a new column on
+`workflow_steps`, which today holds no such field. It starts at `0` for every
+step, existing rows included, so a step that has never been reordered is not a
+special case: the first reorder of any step commits revision `1`.
+
+## Position allocation
+
+`tasks.position` is an existing integer column with no unique constraint and no
+index. This capability changes who writes it, not its shape, and requires no
+migration.
+
+**Renumbering on reorder (AC-TASKS-KANBAN-TASK-REORDERING-001.15).** A reorder
+names one step and one band, but renumbers the whole step. Take the step's
+non-hidden tasks, partition them into the admitted and queued bands, order the
+named band by the submitted id sequence and the other band by its existing step
+order, then assign `0` upward across the concatenation with the admitted band
+first. The admitted band therefore receives the lower contiguous range and the
+queued band the higher one. Two consequences worth stating because a reader will
+otherwise infer the opposite: the two ranges are disjoint rather than
+interleaved, and band membership is never recoverable from `position` alone: it
+is decided by `wip_admitted` and `queued_for_step_id`.
+
+**Arrival (AC-TASKS-KANBAN-TASK-REORDERING-001.28).** An arriving task takes
+`max(position) + 1` over the step's non-hidden tasks, or `0` in an empty step.
+This is deliberately not a renumbering: arrival must not reorder work the user
+has already ordered. It follows that between reorders a step's values drift
+non-contiguous, and that the next reorder of that step restores `0..N-1`. The
+dense invariant is a post-reorder guarantee, not a stored invariant, and nothing
+should assert it at rest.
+
+Because every reorder compacts the step back to `0..N-1`, values are bounded by
+step size across reorders rather than accumulating, so no overflow policy is
+required beyond the column's integer range.
+
+**The caller-supplied `position` argument
+(AC-TASKS-KANBAN-TASK-REORDERING-001.28).** Every move path today takes
+`position` as a literal from its caller and writes it verbatim
+(`MoveTaskWithOptions`, `task/service/service_workflow.go`). AC-TASKS-KANBAN-
+TASK-REORDERING-001.28 makes the server compute it instead, so that argument
+stops deciding anything on an arrival. Spelling out which callers change,
+because the list is not obvious and one of them is a published contract:
+
+- `httpMoveTask`, `wsMoveTask` and the MCP `handleMoveTask` keep accepting the
+ field for wire compatibility and ignore its value.
+- The two frontend drag paths stop computing a target index client-side; the
+ cross-step drag no longer sends `targetTasks.length`.
+- Both bulk-move paths stop assigning indices themselves and take consecutive
+ server-computed values per AC-TASKS-KANBAN-TASK-REORDERING-001.29. Deleting the
+ client-assigned index is necessary but **not sufficient**, and this is the step
+ most easily missed: each selected task is moved by its own call, and the server
+ allocates `max + 1` per call, so the final order is simply the order the calls
+ were issued in. The submission order must therefore be re-derived from
+ AC-TASKS-KANBAN-TASK-REORDERING-001.29 — source step ordinal ascending, then
+ within one source step that step's admitted band in step order followed by its
+ queued band in step order. A selection can span workflows, so two source steps
+ can share an ordinal; break that tie on source step `id` ascending, which keeps
+ the submission order total and reproducible. It must **not** reuse the existing created-descending
+ helper the multi-select path sorts with today
+ (`lib/kanban/task-order.ts`, consumed by `hooks/use-task-multi-select.ts`),
+ whose stated premise is "the board's visible created-desc order" — a premise
+ AC-TASKS-KANBAN-TASK-REORDERING-001.2 retires. Created-descending differs from
+ AC-TASKS-KANBAN-TASK-REORDERING-001.29 whenever a selection spans two source
+ steps, and also within a single one, because step order leads on `position`.
+- The plugin gRPC field `MoveTaskRequest.position`
+ (`proto/kandev/plugin/v1/plugin.proto`) is the one published contract in the
+ list. Its current comment documents the opposite of the new rule — that an
+ omitted position and a position of zero both place the task at the top of the
+ target step — so that comment becomes wrong the moment
+ AC-TASKS-KANBAN-TASK-REORDERING-001.28 lands and must be corrected in the
+ same change. The field itself stays on the wire and keeps its tag: removing
+ it would break every plugin that sets it, whereas ignoring it changes only
+ where the task lands.
+
+The alternative — letting a caller keep injecting a task at the top — was
+rejected rather than overlooked. It would let a plugin or an API client
+silently displace work a user has ordered by hand, which is the single outcome
+AC-TASKS-KANBAN-TASK-REORDERING-001.28 exists to prevent, and it would make the
+top of a step mean different things depending on who wrote the task there.
+
+**A move that names the task's current step is not an arrival.** It changes no
+band membership and no step, so AC-TASKS-KANBAN-TASK-REORDERING-001.28 does not
+apply to it and the task keeps the `position` it already holds. Position
+changes within one step go through the reorder contract instead, which is what
+keeps the band validation in
+AC-TASKS-KANBAN-TASK-REORDERING-001.18 and AC-TASKS-KANBAN-TASK-REORDERING-001.19
+from having a back door.
+
+**Deriving the submitted order under a board filter
+(AC-TASKS-KANBAN-TASK-REORDERING-001.34).** The request carries the band's
+complete membership, but the user only dropped the card relative to the tasks
+they could see. The submitted sequence is the band's persisted order with the
+dragged task moved immediately before the visible task it was dropped above, or
+last in the band when it was dropped below the last visible task. Every other
+task keeps its persisted relative position, which is what makes the
+"only the dragged task moves" guarantee hold for tasks the filter hid.
+
+The keyboard path in AC-TASKS-KANBAN-TASK-REORDERING-001.12 uses the same rule,
+with the visible task the card was moved past standing in for the one it was
+dropped above: each arrow press moves the card one place among the members the
+board is showing, and the submitted sequence places it immediately before the
+visible member now below it, or last in the band when it has passed the last
+visible member. Filtered-out members therefore keep their relative order under a
+keyboard reorder exactly as under a drag, and one arrow press never moves the
+card past two visible cards at once.
+
+**Hidden tasks.** Archived, ephemeral and automation-run tasks keep whatever
+`position` they hold and are skipped by both rules. Their values may collide
+with live ones; the collision is unobservable because every step and workflow
+listing already excludes them (`archived_at IS NULL`, `is_ephemeral = 0`, and
+the automation-origin exclusion applied across the task repository's step and
+workflow queries).
+
+## Concurrency
+
+**The step is the serialization unit, and it covers arrivals as well as
+reorders.** Reorders against one step serialize
+(AC-TASKS-KANBAN-TASK-REORDERING-001.37) because a reorder of either band
+renumbers the whole step and two concurrent renumberings would interleave their
+writes. Arrival position allocation
+(AC-TASKS-KANBAN-TASK-REORDERING-001.28) takes the same step-scoped
+serialization, so an arrival's `max(position) + 1` read and its write cannot
+straddle a reorder's renumbering.
+
+That second half is not a refinement, it is a correctness requirement, and the
+failing case needs no exotic timing. Take a step of five tasks whose highest
+`position` is `0` — the common shape today, because a task created in a step
+takes `0` and only tasks moved or promoted in take a higher value. An arrival
+reads `max = 0` and computes `1`; a concurrent reorder renumbers the five to
+`0..4`. Unserialized, the arriving task lands at `1` and therefore sits
+*second*, displacing work the user has just ordered and contradicting
+AC-TASKS-KANBAN-TASK-REORDERING-001.28's own guarantee that an arrival sorts
+last. Serializing the two makes `max` observed after the renumbering, so the
+arrival takes `5`. Nothing in the argument depends on the whole step being
+tied: any renumbering that raises `max` between an arrival's read and its write
+produces the same displacement.
+
+Serializing at the step, rather than the band, is also what lets two
+different-band reorders both succeed rather than making the second a conflict. A
+reorder changes no band's membership, so the `step_changed` check in
+AC-TASKS-KANBAN-TASK-REORDERING-001.19, which compares only the named band's
+membership, still passes for the second caller. Each reorder imposes order on
+its own band and preserves the other band's current relative order, so applying
+them one after another preserves both intents. A per-band lock would have been
+the wrong unit: it admits concurrent whole-step renumbering and silently loses
+one caller's ordering.
+
+**There is no existing primitive to extend, and the nearest one is a no-op on
+the default store.** `lockWorkflowStepForCapacity`
+(`task/repository/sqlite/task.go`) is not merely scoped to WIP capacity: it
+opens by returning immediately unless the driver is Postgres, so on SQLite —
+the default store — it does nothing at all. Reading it as "a step lock that
+only needs widening" is therefore wrong on the deployment that matters most.
+Serializing reorders and arrival position allocation at the step is build work
+that must supply its own primitive, and the choice is the builder's provided it
+holds across both drivers: on SQLite the write transaction is already
+single-writer, so an immediate-mode transaction spanning the read of `max` and
+the write is sufficient; on Postgres the existing `SELECT ... FOR UPDATE` on
+the step row extends naturally. What the design fixes is the *unit* and the
+*span*, not the mechanism: the unit is the step, and the span must enclose both
+the `max(position)` read and the write that depends on it.
+
+**Two steps at once.** A move both leaves a source step and enters a
+destination step, and AC-TASKS-KANBAN-TASK-REORDERING-001.26 makes it conflict
+with a reorder of either. A move therefore holds both steps, and to avoid a
+deadlock against a second move running the opposite direction, it acquires them
+in a fixed global order — ascending step id — rather than source-then-destination.
+A reorder touches one step and needs no ordering rule.
+
+Failing to acquire is a transient failure, not a conflict: it is retried, and
+if it still fails it surfaces as an ordinary failure under
+AC-TASKS-KANBAN-TASK-REORDERING-001.20, never as `step_changed`. The two are
+not interchangeable, because
+AC-TASKS-KANBAN-TASK-REORDERING-001.19 makes `step_changed` reconcile silently,
+and silently discarding a reorder the user made because a lock was busy would
+look like the drag never happened.
+
+**Publication during an in-flight reorder
+(AC-TASKS-KANBAN-TASK-REORDERING-001.27).** Because a reorder renumbers the
+whole step and a different-band reorder may commit while this band's request is
+still in flight, the originating view can receive a `task.reordered` event
+carrying its own band's *pre-request* order. It applies such an event to the
+other band and to other steps, and holds its optimistic order for the band whose
+request is outstanding until that request resolves, then reconciles to the
+authoritative order. Without that rule the two requirements pull in opposite
+directions: applying the event wholesale flickers the in-flight band back to the
+order the user just changed, and ignoring it wholesale strands the sibling band.
+
+## Ordering keys and the promotion comparators
+
+AC-TASKS-KANBAN-TASK-REORDERING-001.1 names the keys the WIP overflow queue
+already applies. Three implementations of those keys exist and they do not
+agree on one of them: the SQL promotion query orders by
+`COALESCE(queued_at, created_at)`, the two Go comparators
+(`task/service/service_workflow.go` and `orchestrator/workflow_store.go`,
+byte-identical to each other) skip the `queued_at` key entirely when either side
+is null, and the frontend queue comparator (`lib/kanban/wip-queue.ts`) orders a
+null `queued_at` last.
+
+**This divergence is now observable, and
+AC-TASKS-KANBAN-TASK-REORDERING-001.36 requires the three to be aligned on the
+SQL query's rule.** An earlier draft of this design left them alone, on the
+premise that within a single band either every task carries a `queued_at` or
+none does, so the disagreeing case never arises. That premise is false. A task
+created against a full destination step with a configured feeder lands in the
+*feeder* step with `wip_admitted` true, `queued_for_step_id` set to the
+destination, and `queued_at` set
+(`task/repository/sqlite/task.go`, the feeder branch of the create-time WIP
+placement). Under the band model below that task is in the feeder step's
+**admitted** band, sitting beside ordinary admitted tasks whose `queued_at` is
+null. The admitted band therefore mixes the two routinely, and it does so
+exactly in the configuration this capability exists to serve.
+
+The consequence is not theoretical. The feeder pull selects from the feeder step
+with `queued_for_step_id IN ('', NULL, destination)`, which admits both classes
+of task, and orders them by `position` first. On a `position` tie the board
+(null last) and the promotion query (`COALESCE`) order those cards oppositely,
+so the topmost card would not be the one the step yields next, breaking
+AC-TASKS-KANBAN-TASK-REORDERING-001.2 and
+AC-TASKS-KANBAN-TASK-REORDERING-001.4. Ties are not rare at ship time either. Nothing has ever
+assigned a task's `position` for ordering's sake, so every task created in the
+step it still sits in holds `0`, and a step that has only ever been filled by
+creation is entirely tied. Tasks moved, bulk-moved or promoted in hold whatever
+their move path wrote, so real steps mix a block of `0`s with scattered higher
+values (AC-TASKS-KANBAN-TASK-REORDERING-001.35).
+
+Alignment is on `COALESCE(queued_at, created_at)`, for two reasons. It is what
+the SQL promotion query, the path that actually decides promotion today, already
+does. And it is the principled reading: `queued_at` marks when a task became
+eligible, and a task that was never queued became eligible when it was created,
+so falling back to `created_at` measures the same thing rather than inventing a
+sentinel.
+
+This changes no stated contract. The shipped WIP requirement specifies only
+"destination-first deterministic order"
+([WIP Limits and Visible Overflow Queues](../requirements/wip-limit-pull-system.md),
+AC-TASKS-WIP-LIMIT-PULL-SYSTEM-001.2) and says nothing about `queued_at` null
+handling, so no acceptance criterion is being weakened. What is being removed is
+an undocumented three-way disagreement between implementations of one
+under-specified rule, which is the opposite of the determinism that requirement
+asks for. The reordering of the keys themselves, the destination-first
+preference for a same-step queued candidate over a feeder candidate, and every
+other part of the promotion contract are untouched.
+
+## Band model
+
+The board partitions a step by exclusion: the queued band is
+`workflow_step_id == step && queued_for_step_id == step && !wip_admitted`, and
+the admitted band is everything else in the step. The requirement's Terminology
+matches that, deliberately, so the two bands are exhaustive.
+
+The case this makes explicit is a task sitting in step A while queued for step
+B, which holds no WIP slot in A yet renders among A's admitted cards. It is a
+full member of A's admitted band: reorderable, counted in membership, and
+ordered by `position` like any other. That is not merely cosmetic, because B's
+promotion query selects from A ordered by `position`, so reordering these cards
+in A chooses which one B pulls next. This is the WIP-queue case the capability
+exists to serve, and it works without any additional rule. It is also the case
+that makes the ordering-key alignment above mandatory rather than cosmetic.
+
+## Surfaces
+
+**The board ships exactly two views, and they are named in the registry.**
+`lib/kanban/view-registry.ts` enables `kanban` (`SwimlaneKanbanContent`) and
+`graph2`, labelled **Pipeline** (`SwimlaneGraph2Content`). Those two, and no
+others, are what AC-TASKS-KANBAN-TASK-REORDERING-001.2 has to cover. Mobile is
+not a third view: `getEffectiveView` forces the default view on a mobile
+viewport, so the mobile presentation is the Kanban view rendered through
+`components/kanban/swipeable-columns.tsx`.
+
+This is worth stating flatly because there is a decoy.
+`components/kanban/swimlane-graph-content.tsx` looks like a third view, exports
+a component shaped like one, and has its own test file — but it is absent from
+the registry and no production module imports it. It is unreachable, and a
+change made only there ships nothing. Earlier drafts of this design called it
+"the graph presentation"; that was wrong, and Pipeline is the surface those
+criteria mean.
+
+**Kanban view.** `components/kanban-column.tsx` is the only component that
+partitions a step into bands and renders the queued divider, and it backs both
+the desktop/tablet path (`swimlane-kanban-content.tsx`) and the mobile path
+(`swipeable-columns.tsx`). It is the surface that accepts a reorder.
+
+**Pipeline view.** It renders one row per task rather than a column per step:
+`SwimlaneGraph2Content` sorts every task in the workflow by step index and then
+by `position` alone, with no tiebreak, and hands each to `Graph2TaskPipeline`.
+Two consequences for AC-TASKS-KANBAN-TASK-REORDERING-001.2. Its ordering must
+gain the rest of AC-TASKS-KANBAN-TASK-REORDERING-001.1's keys, because bare
+`position` is not a total order and ties are the ship-time norm; and "step
+order" applies to each step's contiguous run of rows rather than to a column.
+It gains no band split and no divider — it has neither today, no acceptance
+criterion asks for one, and rows for one step land admitted-before-queued
+anyway immediately after a reorder, because
+AC-TASKS-KANBAN-TASK-REORDERING-001.15 gives the admitted band the lower
+contiguous range. Pipeline accepts no reorder input at all
+(AC-TASKS-KANBAN-TASK-REORDERING-001.38); its existing per-task step-move
+control is unchanged.
+
+The board's column list is virtualized, with absolutely positioned rows and a
+small overscan window. A sortable context that only covers rendered rows cannot
+express a drop beyond that window, and the keyboard path in
+AC-TASKS-KANBAN-TASK-REORDERING-001.12 has the same constraint: an arrow press
+must be able to move a card past rows that are not mounted. This is the main
+implementation constraint on the interaction ACs and is called out here so it is
+costed rather than discovered. The mechanism is Build's choice: scroll-to-index
+synchronization with the virtualizer and suspending virtualization for the
+duration of a drag both satisfy the stated outcomes.
+
+The in-repo keyboard-sortable convention (a keyboard sensor with sortable
+coordinate resolution) already exists in the quick-chat tab strip and the task
+row settings list, and matches the key bindings the requirement names.
+
+## Related
+
+- [WIP Limits and Visible Overflow Queues](../requirements/wip-limit-pull-system.md)
+- [Reorder Queued Messages](../../ui/requirements/message-queue-reorder.md)